8447
Co
conveyor / files
conveyor / crates / conveyor-app / src / reload.rs
2.7 KB
1//! Loads the widget library's latest build into this process: libconveyor_widgets (.so or .dylib), next to 2//! the binary. Old builds stay mapped, since their threads may still be winding down. A build 3//! made against another build of this app waits for the app's own restart. 4use crate::api::{Abouts, Kinds}; 5use std::{ffi::{CStr, CString, c_char, c_void}, path::PathBuf, time::SystemTime}; 6 7unsafe extern "C" { 8 fn dlopen(file: *const c_char, mode: i32) -> *mut c_void; 9 fn dlsym(handle: *mut c_void, name: *const c_char) -> *mut c_void; 10 fn dlerror() -> *const c_char; 11} 12 13pub struct Loader { 14 file: PathBuf, 15 loaded: Option<SystemTime>, 16 count: u32, 17} 18 19impl Loader { 20 pub fn new() -> Self { 21 let dir = std::env::current_exe().ok().and_then(|e| Some(e.parent()?.to_owned())).unwrap_or_default(); 22 Loader { file: dir.join(format!("libconveyor_widgets.{}", std::env::consts::DLL_EXTENSION)), loaded: None, count: 0 } 23 } 24 25 /// The widgets of a build not loaded yet, when there is one this app can run. 26 pub fn poll(&mut self) -> Option<(Kinds, Abouts)> { 27 let t = std::fs::metadata(&self.file).and_then(|m| m.modified()).ok()?; 28 if Some(t) == self.loaded { return None; } 29 self.count += 1; 30 // dlopen keys on the path: each build gets its own. 31 let dir = std::env::var("XDG_RUNTIME_DIR").map_or(std::env::temp_dir(), PathBuf::from); 32 let copy = dir.join(format!("conveyor-widgets-{}-{}.{}", std::process::id(), self.count, std::env::consts::DLL_EXTENSION)); 33 std::fs::copy(&self.file, ©).ok()?; 34 let loaded = unsafe { open(©) }; 35 let _ = std::fs::remove_file(©); 36 self.loaded = Some(t); 37 match loaded { 38 Ok((build, kinds, about)) if build == crate::BUILD => Some((kinds, about)), 39 Ok(_) => { eprintln!("widgets built against a newer app: waiting for its restart"); None } 40 Err(e) => { eprintln!("widgets didn't load: {e}"); None } 41 } 42 } 43} 44 45/// Safe while the library was built by the same compiler against this app: the build id says so. 46unsafe fn open(path: &std::path::Path) -> Result<(&'static str, Kinds, Abouts), String> { 47 let err = || unsafe { CStr::from_ptr(dlerror()).to_string_lossy().into_owned() }; 48 let path = CString::new(path.as_os_str().as_encoded_bytes()).map_err(|e| e.to_string())?; 49 let handle = unsafe { dlopen(path.as_ptr(), 2) }; // RTLD_NOW 50 if handle.is_null() { return Err(err()); } 51 let entry = unsafe { dlsym(handle, c"conveyor_widgets".as_ptr()) }; 52 if entry.is_null() { return Err(err()); } 53 let entry: fn() -> (&'static str, Kinds, Abouts) = unsafe { std::mem::transmute(entry) }; 54 Ok(entry()) 55}