//! Runs panel modules (plasmoids) for the compositor component. //! //! The native compositor embeds wasmer and marshals the canonical ABI by hand. A component can't //! embed a second runtime, so the compositor asks this host (wit/host/plasmoids.wit) and gets draw //! ops back. Each module is instantiated as a real component with typed bindings against one world, //! `plasmoid-host` (wit/worlds.wit): it imports the subset of host interfaces it uses, and every one //! of them is served here from the data the compositor publishes. use std::cell::RefCell; use std::collections::VecDeque; use std::io::Read; use std::os::unix::process::CommandExt; use std::process::{Child, Command, Stdio}; use std::rc::Rc; use wasmtime::component::{Component, HasSelf, Linker}; use wasmtime::{Engine, Store}; pub mod ph { wasmtime::component::bindgen!({ path: "../wit", world: "plasmoid-host", additional_derives: [PartialEq], }); } use ph::exports::chandra::desktop as ex; use ph::chandra::desktop as d; /// What a module asked of the compositor during a call. pub enum Req { Launch(String), FocusWindow(i32), SetLayout(i32), SetInspector(bool), LoadModule(String), UnloadInstance(String), Browse, Logout, SetWallpaper(i32), SetSessionSetting(i32, bool), } pub const T_APPS: usize = 0; pub const T_WINDOWS: usize = 1; pub const T_LAYOUTS: usize = 2; pub const T_MODULES: usize = 3; pub const T_INSTANCES: usize = 4; pub const T_WALLPAPERS: usize = 5; pub const T_SESSION_SETTINGS: usize = 6; /// Host data every module reads from, shared by all loaded modules. #[derive(Default)] pub struct Shared { pub tables: [Vec; 7], pub layout_mode: i32, pub wallpaper: i32, /// Which session settings are on: bit i for row i of the session settings table. pub session_settings: u32, pub inspector_on: bool, pub system: Option, /// (id, title, app id, focused) pub windows: Vec<(u64, String, String, bool)>, pub requests: VecDeque, pub focus_req: Option, pub tokens: Option, } pub type SharedRef = Rc>; pub struct PState { shared: SharedRef, } enum Field { I(i32), S(String), } /// Parse a table (LE u32 row count, then rows) by its field spec: 'i' = LE i32, 's' = LE u32 length + UTF-8. fn parse_table(bytes: &[u8], spec: &str) -> Vec> { let rd = |p: usize| -> Option { bytes.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) }; let Some(n) = rd(0) else { return Vec::new() }; let mut pos = 4; let mut rows = Vec::new(); 'rows: for _ in 0..n { let mut row = Vec::new(); for c in spec.chars() { let Some(v) = rd(pos) else { break 'rows }; pos += 4; if c == 'i' { row.push(Field::I(v as i32)); } else { let end = pos + v as usize; let Some(s) = bytes.get(pos..end) else { break 'rows }; row.push(Field::S(String::from_utf8_lossy(s).into_owned())); pos = end; } } rows.push(row); } rows } fn s(f: &Field) -> String { match f { Field::S(x) => x.clone(), Field::I(i) => i.to_string(), } } fn i(f: &Field) -> i32 { match f { Field::I(x) => *x, Field::S(_) => 0, } } fn default_tokens() -> d::theme::Tokens { let c = |r, g, b| d::types::Color { r, g, b, a: 255 }; d::theme::Tokens { name: String::new(), palette: d::theme::Palette { desktop_top: c(20, 28, 48), desktop_bottom: c(10, 14, 28), surface: c(30, 36, 50), surface_hover: c(50, 58, 76), surface_popup: c(24, 30, 44), foreground: c(240, 244, 250), foreground_muted: c(150, 160, 180), accent: c(120, 150, 255), accent_foreground: c(255, 255, 255), border: c(70, 80, 100), }, font_size: 14, radius: 6, spacing: 6, panel_height: 40, } } impl PState { fn rows(&self, t: usize, spec: &str) -> Vec> { parse_table(&self.shared.borrow().tables[t], spec) } } impl d::types::Host for PState {} impl d::theme::Host for PState { fn get_tokens(&mut self) -> d::theme::Tokens { self.shared.borrow().tokens.clone().unwrap_or_else(default_tokens) } } impl d::clock::Host for PState { fn now(&mut self) -> d::types::Datetime { unsafe { let t = libc::time(std::ptr::null_mut()); let mut tm: libc::tm = std::mem::zeroed(); libc::localtime_r(&t, &mut tm); d::types::Datetime { year: (tm.tm_year + 1900) as u32, month: (tm.tm_mon + 1) as u8, day: tm.tm_mday as u8, hour: tm.tm_hour as u8, minute: tm.tm_min as u8, second: tm.tm_sec as u8, weekday: tm.tm_wday as u8, } } } } impl d::app_catalog::Host for PState { fn list_apps(&mut self) -> Vec { self.rows(T_APPS, "sssss") .iter() .map(|r| d::types::AppEntry { id: s(&r[0]), name: s(&r[1]), comment: s(&r[2]), category: s(&r[3]), glyph: s(&r[4]), }) .collect() } } impl d::app_launch::Host for PState { /// Known catalog ids succeed; the compositor spawns after the call returns. fn launch(&mut self, id: String) -> Result<(), String> { if self.rows(T_APPS, "sssss").iter().any(|r| s(&r[0]) == id) { self.shared.borrow_mut().requests.push_back(Req::Launch(id)); Ok(()) } else { Err("unknown application".to_string()) } } } impl d::windows::Host for PState { fn list_windows(&mut self) -> Vec { self.rows(T_WINDOWS, "isii") .iter() .map(|r| d::windows::WindowInfo { id: i(&r[0]) as u32, title: s(&r[1]), focused: i(&r[2]) as u32, minimized: i(&r[3]) as u32, }) .collect() } fn focus_window(&mut self, id: u32) { self.shared.borrow_mut().requests.push_back(Req::FocusWindow(id as i32)); } fn all(&mut self) -> Vec { self.shared .borrow() .windows .iter() .take(64) .map(|(id, title, app, focused)| d::windows::WindowDetail { id: *id, title: title.clone(), app_id: app.clone(), focused: *focused, }) .collect() } fn focus(&mut self, id: u64) { self.shared.borrow_mut().focus_req = Some(id); } } impl d::layout_control::Host for PState { fn layout_modes(&mut self) -> Vec { self.rows(T_LAYOUTS, "s").iter().map(|r| s(&r[0])).collect() } fn current_layout(&mut self) -> u32 { self.shared.borrow().layout_mode as u32 } fn set_layout(&mut self, mode: u32) { self.shared.borrow_mut().requests.push_back(Req::SetLayout(mode as i32)); } } impl d::inspector::Host for PState { fn is_on(&mut self) -> bool { self.shared.borrow().inspector_on } fn set_on(&mut self, on: bool) { self.shared.borrow_mut().requests.push_back(Req::SetInspector(on)); } } impl d::modules::Host for PState { fn available(&mut self) -> Vec { self.rows(T_MODULES, "sssi") .iter() .map(|r| d::modules::ModuleInfo { id: s(&r[0]), name: s(&r[1]), path: s(&r[2]), loaded: i(&r[3]) as u32 }) .collect() } fn loaded(&mut self) -> Vec { self.rows(T_INSTANCES, "sss") .iter() .map(|r| d::modules::InstanceInfo { slot: s(&r[0]), module: s(&r[1]), name: s(&r[2]) }) .collect() } fn load_module(&mut self, path: String) { self.shared.borrow_mut().requests.push_back(Req::LoadModule(path)); } fn unload_instance(&mut self, slot: String) { self.shared.borrow_mut().requests.push_back(Req::UnloadInstance(slot)); } fn browse(&mut self) { self.shared.borrow_mut().requests.push_back(Req::Browse); } } impl d::session::Host for PState { fn logout(&mut self) { self.shared.borrow_mut().requests.push_back(Req::Logout); } } impl d::wallpaper::Host for PState { fn wallpapers(&mut self) -> Vec { self.rows(T_WALLPAPERS, "s").iter().map(|r| s(&r[0])).collect() } fn current_wallpaper(&mut self) -> u32 { self.shared.borrow().wallpaper.max(0) as u32 } fn set_wallpaper(&mut self, index: u32) { self.shared.borrow_mut().requests.push_back(Req::SetWallpaper(index as i32)); } } impl d::session_settings::Host for PState { fn settings(&mut self) -> Vec { self.rows(T_SESSION_SETTINGS, "s").iter().map(|r| s(&r[0])).collect() } fn is_on(&mut self, index: u32) -> bool { index < 32 && (self.shared.borrow().session_settings >> index) & 1 == 1 } fn set_setting(&mut self, index: u32, on: bool) { self.shared.borrow_mut().requests.push_back(Req::SetSessionSetting(index as i32, on)); } } impl d::system::Host for PState { fn read(&mut self) -> d::system::Snapshot { self.shared.borrow().system.clone().unwrap_or(d::system::Snapshot { cpu_permille: 0, mem_used_kib: 0, mem_total_kib: 0, battery_percent: -1, charging: false, uptime_secs: 0, net_rx_bytes_per_sec: 0, net_tx_bytes_per_sec: 0, load_centi: 0, }) } } struct Loaded { store: Store, inst: ph::PlasmoidHost, } /// A file-chooser dialog in flight (zenity on the host session). struct Picker { child: Child, } pub struct Runtime { engine: Engine, linker: Linker, pub shared: SharedRef, slots: Vec>, picker: Option, } pub struct LoadedInfo { pub handle: u32, pub info: ex::plasmoid::PlasmoidInfo, pub imports: Vec, } impl Runtime { pub fn new(engine: &Engine) -> wasmtime::Result { let mut linker: Linker = Linker::new(engine); ph::PlasmoidHost::add_to_linker::>(&mut linker, |s| s)?; Ok(Runtime { engine: engine.clone(), linker, shared: Rc::new(RefCell::new(Shared::default())), slots: Vec::new(), picker: None, }) } pub fn load(&mut self, path: &str) -> Result { let bytes = std::fs::read(path).map_err(|_| "cannot read file".to_string())?; if bytes.len() < 8 || &bytes[..4] != b"\0asm" { return Err("not a wasm file".to_string()); } let component = Component::new(&self.engine, &bytes) .map_err(|_| "no plasmoid (chandra:desktop/plasmoid) in this module".to_string())?; // The capability grant: the host interfaces the binary imports, besides the base ones. let mut imports: Vec = Vec::new(); for (name, _) in component.component_type().imports(&self.engine) { if let Some(rest) = name.strip_prefix("chandra:desktop/") { let iface = rest.split('@').next().unwrap_or(rest).to_string(); if iface != "types" && !imports.contains(&iface) { imports.push(iface); } } } let mut store = Store::new(&self.engine, PState { shared: self.shared.clone() }); let inst = ph::PlasmoidHost::instantiate(&mut store, &component, &self.linker) .map_err(|_| "wasm runtime error".to_string())?; let info = inst .chandra_desktop_plasmoid() .call_info(&mut store) .map_err(|_| "widget trapped in info()".to_string())?; let l = Loaded { store, inst }; let handle = match self.slots.iter().position(|s| s.is_none()) { Some(h) => { self.slots[h] = Some(l); h } None => { self.slots.push(Some(l)); self.slots.len() - 1 } }; Ok(LoadedInfo { handle: handle as u32, info, imports }) } pub fn unload(&mut self, handle: u32) { if let Some(slot) = self.slots.get_mut(handle as usize) { *slot = None; } } fn get(&mut self, handle: u32) -> Option<&mut Loaded> { self.slots.get_mut(handle as usize).and_then(|s| s.as_mut()) } /// A trapping module yields no ops. pub fn render(&mut self, handle: u32, size: d::types::Size) -> Vec { let Some(l) = self.get(handle) else { return Vec::new() }; l.inst.chandra_desktop_plasmoid().call_render(&mut l.store, size).unwrap_or_default() } pub fn popup(&mut self, handle: u32) -> Option { let l = self.get(handle)?; l.inst.chandra_desktop_plasmoid().call_popup(&mut l.store).ok().flatten() } pub fn on_event(&mut self, handle: u32, on_popup: bool, ev: d::types::InputEvent) -> bool { let Some(l) = self.get(handle) else { return false }; let target = if on_popup { ex::plasmoid::Surface::Popup } else { ex::plasmoid::Surface::Widget }; l.inst.chandra_desktop_plasmoid().call_on_event(&mut l.store, target, &ev).unwrap_or(false) } pub fn picker_start(&mut self) -> bool { if self.picker.is_some() { return true; } let mut cmd = Command::new("zenity"); cmd.args([ "--file-selection", "--title=Load widget (.wasm)", "--file-filter=WebAssembly widgets | *.wasm", "--file-filter=All files | *", ]) .stdout(Stdio::piped()) .stderr(Stdio::null()) .stdin(Stdio::null()); unsafe { cmd.pre_exec(|| { libc::setsid(); Ok(()) }); } match cmd.spawn() { Ok(child) => { self.picker = Some(Picker { child }); true } Err(_) => false, } } /// None while the dialog is open; Some(None) when cancelled; Some(Some(path)) when chosen. pub fn picker_poll(&mut self) -> Option> { let p = self.picker.as_mut()?; // With SIGCHLD ignored the child is reaped for us, so an error here also means "finished". if let Ok(None) = p.child.try_wait() { return None; } let mut out = String::new(); if let Some(mut so) = p.child.stdout.take() { let _ = so.read_to_string(&mut out); } self.picker = None; let t = out.trim_end_matches(['\n', '\r']).to_string(); Some(if t.is_empty() { None } else { Some(t) }) } } #[cfg(test)] mod tests { use super::*; use d::types::{InputEvent, Point, Size}; fn runtime() -> Runtime { let mut cfg = wasmtime::Config::new(); cfg.wasm_component_model(true); Runtime::new(&Engine::new(&cfg).unwrap()).unwrap() } /// A table: LE u32 row count, then fields as LE u32 length + UTF-8. fn apps_table(apps: &[(&str, &str)]) -> Vec { let mut b = (apps.len() as u32).to_le_bytes().to_vec(); for (id, name) in apps { for f in [id, name, &"comment", &"System", &"T"] { b.extend((f.len() as u32).to_le_bytes()); b.extend(f.as_bytes()); } } b } fn texts(ops: &[d::types::DrawOp]) -> Vec { ops.iter() .filter_map(|o| if let d::types::DrawOp::Text(t) = o { Some(t.text.clone()) } else { None }) .collect() } fn module(name: &str) -> String { for p in [format!("../build/components/{name}.wasm"), format!("build/components/{name}.wasm")] { if std::path::Path::new(&p).exists() { return p; } } panic!("build/components/{name}.wasm is missing: run `just modules`"); } #[test] fn launcher_reads_the_catalog_filters_typed_keys_and_launches() { let mut rt = runtime(); rt.shared.borrow_mut().tables[T_APPS] = apps_table(&[("a.term", "Terminal"), ("b.files", "Files")]); let l = rt.load(&module("launcher")).expect("launcher loads"); // Its capability grant is what the binary imports (the MoonBit side drops the base `theme`). let mut imports = l.imports.clone(); imports.sort(); assert_eq!(imports, ["app-catalog", "app-launch", "theme"]); let h = l.handle; // It draws its button. assert!(!rt.render(h, Size { w: 190, h: 36 }).is_empty()); // Clicking opens the popup; typing narrows it to Files; Enter launches it. assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 1, y: 1 }))); assert!(rt.popup(h).is_some()); for k in ["f", "i", "l", "e", "s"] { rt.on_event(h, true, InputEvent::KeyDown(k.to_string())); } assert!(texts(&rt.popup(h).expect("popup open").ops).contains(&"Files".to_string())); assert!(rt.on_event(h, true, InputEvent::KeyDown("Enter".to_string()))); match rt.shared.borrow_mut().requests.pop_front() { Some(Req::Launch(id)) => assert_eq!(id, "b.files"), _ => panic!("expected a launch request"), } assert!(rt.popup(h).is_none()); rt.unload(h); } #[test] fn modules_are_rejected_cleanly() { let mut rt = runtime(); assert!(rt.load("/nonexistent.wasm").is_err()); let junk = std::env::temp_dir().join("chandra-junk.wasm"); std::fs::write(&junk, b"not wasm at all").unwrap(); assert!(rt.load(junk.to_str().unwrap()).is_err()); } #[test] fn layout_module_follows_the_published_mode_and_sets_it() { let mut rt = runtime(); let l = rt.load(&module("layout")).expect("layout loads"); assert!(l.imports.contains(&"layout-control".to_string())); // layouts table: one string field per row let mut t = 3u32.to_le_bytes().to_vec(); for n in ["Tiling (BSP)", "Monocle", "Floating"] { t.extend((n.len() as u32).to_le_bytes()); t.extend(n.as_bytes()); } rt.shared.borrow_mut().tables[T_LAYOUTS] = t; rt.shared.borrow_mut().layout_mode = 0; let ops = rt.render(l.handle, Size { w: 120, h: 36 }); assert!(!texts(&ops).is_empty()); rt.unload(l.handle); } #[test] fn logout_asks_for_confirmation_then_requests_it() { let mut rt = runtime(); let l = rt.load(&module("logout")).expect("logout loads"); assert!(l.imports.contains(&"session".to_string())); let h = l.handle; assert!(!rt.render(h, Size { w: 84, h: 34 }).is_empty()); // Closed: no popup. A click opens it; nothing is requested yet. assert!(rt.popup(h).is_none()); assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); let p = rt.popup(h).expect("popup open"); assert!(texts(&p.ops).contains(&"Log out".to_string()) && texts(&p.ops).contains(&"Cancel".to_string())); assert!(rt.shared.borrow().requests.is_empty()); // Cancel row (second): closes without logging out. assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 30 + 5 }))); assert!(rt.popup(h).is_none()); assert!(rt.shared.borrow().requests.is_empty()); // Escape also cancels. rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })); assert!(rt.on_event(h, true, InputEvent::KeyDown("Escape".to_string()))); assert!(rt.shared.borrow().requests.is_empty()); // Open again and click the first row: that is the logout request. rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 5 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Logout))); assert!(rt.popup(h).is_none()); // Enter confirms too. rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })); rt.on_event(h, true, InputEvent::KeyDown("Enter".to_string())); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Logout))); rt.unload(h); } #[test] fn settings_module_shows_switches_and_wallpapers_and_requests_changes() { let mut rt = runtime(); let l = rt.load(&module("session-settings")).expect("session-settings loads"); assert!(l.imports.contains(&"session-settings".to_string())); let h = l.handle; assert!(l.imports.contains(&"wallpaper".to_string())); let table = |names: &[&str]| { let mut t = (names.len() as u32).to_le_bytes().to_vec(); for n in names { t.extend((n.len() as u32).to_le_bytes()); t.extend(n.as_bytes()); } t }; let names = ["Reopen windows at login", "Remember window positions", "Dark mode"]; let walls = ["Plasma glow", "Aurora", "Starfield"]; rt.shared.borrow_mut().tables[T_SESSION_SETTINGS] = table(&names); rt.shared.borrow_mut().tables[T_WALLPAPERS] = table(&walls); rt.shared.borrow_mut().session_settings = 0b101; // reopen on, remember off, dark on rt.shared.borrow_mut().wallpaper = 1; assert!(texts(&rt.render(h, Size { w: 92, h: 34 })).contains(&"Settings".to_string())); // A click opens the list of every setting; nothing is requested yet. assert!(rt.popup(h).is_none()); assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 }))); let p = rt.popup(h).expect("popup open"); for n in names.iter().chain(["Session", "Desktop", "Panel"].iter()) { assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed"); } assert!(rt.shared.borrow().requests.is_empty()); // First row is on: a click asks to turn it off. Second row is off: a click asks for on. assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 13 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(0, false)))); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 28 + 13 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(1, true)))); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 2 * 28 + 13 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSessionSetting(2, false)))); // The Desktop tab (second of three 96 px tabs): row 0 is the "Wallpaper" heading // (nothing), rows 1.. the wallpapers: Starfield. assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 6 + 96 + 48, y: 6 + 14 }))); assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Starfield".to_string())); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 13 }))); assert!(rt.shared.borrow().requests.is_empty()); assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 40 + 3 * 28 + 13 }))); assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetWallpaper(2)))); // The list stays open; Escape closes it without another request. assert!(rt.popup(h).is_some()); assert!(rt.on_event(h, true, InputEvent::KeyDown("Escape".to_string()))); assert!(rt.popup(h).is_none()); assert!(rt.shared.borrow().requests.is_empty()); rt.unload(h); } }