CI / test (push) Failing after 18s
- New `network` panel module (in the default panel, before the battery and the clock): signal bars and the
Wi-Fi network's name, a plug when wired, crossed-out bars offline or in airplane mode. Its
popup shows the status and the last action's outcome ("Couldn't connect to X: wrong
password?"), switches for Wi-Fi and airplane mode, and the networks in range (strongest
access point per name, the one in use first). Click a saved or open network to connect, a new
secured one to type its password in a field under it (Enter or Connect), the one in use to
disconnect, or "Forget" on a saved one. Opening the popup asks for a scan.
- compositor/network: NetworkManager over D-Bus through a small D-Bus client of our own
(wire format, EXTERNAL auth, async calls) on the existing @sys socket calls, so neither host
needed new imports. One ObjectManager.GetManagedObjects + GetAll every 2 s; GetSettings once
per saved connection; RequestScan, Device.Disconnect, WirelessEnabled / WwanEnabled,
ActivateConnection (saved), AddAndActivateConnection (new: open, WPA/WPA2 PSK, WPA3 SAE) and
Settings.Connection.Delete. Without NetworkManager it falls back to read-only status from
/proc/net/dev, /proc/net/wireless and /sys/class/net (no network names there), and looks for
NetworkManager again every 30 s.
- New `network` capability (wit/capabilities.wit): status, wifi-networks, scan, connect,
disconnect, forget, set-wifi-enabled, set-airplane-mode. Served from host tables 8/9 and a
`network(network-request)` request by the wasmer/wasmtime stub (compositor/wasm), host-wasm
and the MoonBit wasmhost. The stub's build_list learned bool fields; request strings are
wiped after use (Wi-Fi passwords).
- Running out of module instances now says "too many modules loaded".
- Deferred: VPN, hotspot, hidden networks, WEP and 802.1X (enterprise) networks, IP settings,
mobile broadband beyond the airplane switch, D-Bus signals (state is polled).
- Tests: D-Bus wire format (incl. the well-known Hello bytes), NetworkManager objects -> status
and list, security settings, /proc parsing; the module through the shell against a fake
backend (list, connect/forget/disconnect, password entry, switches, read-only); a host-wasm
test; and scripts/test-network-dbus.sh, which runs the backend against python-dbusmock's
NetworkManager on a private bus.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hizqNXcNDuef3gxa7D
1046 lines
41 KiB
Rust
1046 lines
41 KiB
Rust
//! 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],
|
|
});
|
|
}
|
|
/// The optional `module-config` export (wit/worlds.wit `configurable`): a module's own settings
|
|
/// for its right-click menu. Bound separately so modules without it still instantiate.
|
|
pub mod cfg {
|
|
wasmtime::component::bindgen!({
|
|
path: "../wit",
|
|
world: "configurable",
|
|
});
|
|
}
|
|
pub use cfg::exports::chandra::desktop::module_config::ConfigItem;
|
|
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),
|
|
/// The screenshot capability: 0-3 take, 10-12 record, 20 stop, 30/31 pointer off/on.
|
|
Screenshot(i32),
|
|
SetScreenOff(i32),
|
|
SetSuspendAfter(i32),
|
|
/// 0 suspend, 1 power off, 2 restart.
|
|
PowerAction(i32),
|
|
/// A network action (0 scan, 1 disconnect, 2/3 Wi-Fi off/on, 4/5 airplane mode off/on,
|
|
/// 6 connect, 7 forget), the network's name and the password.
|
|
Network(i32, String, String),
|
|
}
|
|
|
|
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;
|
|
/// App id -> raster image handle (`raster.load-image`), behind `icons.app-icon`.
|
|
pub const T_ICONS: usize = 7;
|
|
/// One row (iissiiii): state signal name message wifi-enabled airplane can-manage has-wifi.
|
|
pub const T_NET_STATUS: usize = 8;
|
|
/// Wi-Fi networks in range (siiii): ssid signal secured active saved.
|
|
pub const T_NET_NETWORKS: usize = 9;
|
|
|
|
/// Host data every module reads from, shared by all loaded modules.
|
|
#[derive(Default)]
|
|
pub struct Shared {
|
|
pub tables: [Vec<u8>; 10],
|
|
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,
|
|
/// Screenshot state: bit 0 a recording is running, bit 1 recordings show the pointer.
|
|
pub screenshot: u32,
|
|
/// Power timeouts in minutes (0: never).
|
|
pub screen_off_min: u32,
|
|
pub suspend_min: u32,
|
|
pub inspector_on: bool,
|
|
pub system: Option<d::system::Snapshot>,
|
|
/// The battery (`battery.read`): percent (-1: none), charge-state index, seconds left.
|
|
pub battery: (i32, u32, u32),
|
|
/// (id, title, app id, focused)
|
|
pub windows: Vec<(u64, String, String, bool)>,
|
|
pub requests: VecDeque<Req>,
|
|
pub focus_req: Option<u64>,
|
|
pub tokens: Option<d::theme::Tokens>,
|
|
}
|
|
pub type SharedRef = Rc<RefCell<Shared>>;
|
|
|
|
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<Vec<Field>> {
|
|
let rd = |p: usize| -> Option<u32> { 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<Vec<Field>> {
|
|
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<d::types::AppEntry> {
|
|
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<d::windows::WindowInfo> {
|
|
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<d::windows::WindowDetail> {
|
|
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<String> {
|
|
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<d::modules::ModuleInfo> {
|
|
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<d::modules::InstanceInfo> {
|
|
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<String> {
|
|
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::power::Host for PState {
|
|
fn screen_off_minutes(&mut self) -> u32 {
|
|
self.shared.borrow().screen_off_min
|
|
}
|
|
fn set_screen_off_minutes(&mut self, minutes: u32) {
|
|
self.shared.borrow_mut().requests.push_back(Req::SetScreenOff(minutes as i32));
|
|
}
|
|
fn suspend_minutes(&mut self) -> u32 {
|
|
self.shared.borrow().suspend_min
|
|
}
|
|
fn set_suspend_minutes(&mut self, minutes: u32) {
|
|
self.shared.borrow_mut().requests.push_back(Req::SetSuspendAfter(minutes as i32));
|
|
}
|
|
fn suspend(&mut self) {
|
|
self.shared.borrow_mut().requests.push_back(Req::PowerAction(0));
|
|
}
|
|
fn power_off(&mut self) {
|
|
self.shared.borrow_mut().requests.push_back(Req::PowerAction(1));
|
|
}
|
|
fn reboot(&mut self) {
|
|
self.shared.borrow_mut().requests.push_back(Req::PowerAction(2));
|
|
}
|
|
}
|
|
|
|
impl d::screenshot::Host for PState {
|
|
fn take(&mut self, mode: u32) {
|
|
if mode <= 3 {
|
|
self.shared.borrow_mut().requests.push_back(Req::Screenshot(mode as i32));
|
|
}
|
|
}
|
|
fn start_recording(&mut self, mode: u32) {
|
|
if mode <= 2 {
|
|
self.shared.borrow_mut().requests.push_back(Req::Screenshot(10 + mode as i32));
|
|
}
|
|
}
|
|
fn stop_recording(&mut self) {
|
|
self.shared.borrow_mut().requests.push_back(Req::Screenshot(20));
|
|
}
|
|
fn is_recording(&mut self) -> bool {
|
|
self.shared.borrow().screenshot & 1 == 1
|
|
}
|
|
fn records_pointer(&mut self) -> bool {
|
|
self.shared.borrow().screenshot & 2 == 2
|
|
}
|
|
fn set_records_pointer(&mut self, on: bool) {
|
|
self.shared.borrow_mut().requests.push_back(Req::Screenshot(if on { 31 } else { 30 }));
|
|
}
|
|
}
|
|
|
|
impl d::network::Host for PState {
|
|
fn status(&mut self) -> d::network::NetStatus {
|
|
let rows = self.rows(T_NET_STATUS, "iissiiii");
|
|
match rows.first() {
|
|
Some(r) if r.len() == 8 => d::network::NetStatus {
|
|
state: i(&r[0]) as u32,
|
|
signal: i(&r[1]) as u32,
|
|
name: s(&r[2]),
|
|
message: s(&r[3]),
|
|
wifi_enabled: i(&r[4]) != 0,
|
|
airplane: i(&r[5]) != 0,
|
|
can_manage: i(&r[6]) != 0,
|
|
has_wifi: i(&r[7]) != 0,
|
|
},
|
|
_ => d::network::NetStatus {
|
|
state: 0,
|
|
signal: 0,
|
|
name: String::new(),
|
|
message: String::new(),
|
|
wifi_enabled: false,
|
|
airplane: false,
|
|
can_manage: false,
|
|
has_wifi: false,
|
|
},
|
|
}
|
|
}
|
|
fn wifi_networks(&mut self) -> Vec<d::network::WifiNetwork> {
|
|
self.rows(T_NET_NETWORKS, "siiii")
|
|
.iter()
|
|
.filter(|r| r.len() == 5)
|
|
.map(|r| d::network::WifiNetwork {
|
|
ssid: s(&r[0]),
|
|
signal: i(&r[1]) as u32,
|
|
secured: i(&r[2]) != 0,
|
|
active: i(&r[3]) != 0,
|
|
saved: i(&r[4]) != 0,
|
|
})
|
|
.collect()
|
|
}
|
|
fn scan(&mut self) {
|
|
self.net(0, String::new(), String::new());
|
|
}
|
|
fn connect(&mut self, ssid: String, password: String) {
|
|
self.net(6, ssid, password);
|
|
}
|
|
fn disconnect(&mut self) {
|
|
self.net(1, String::new(), String::new());
|
|
}
|
|
fn forget(&mut self, ssid: String) {
|
|
self.net(7, ssid, String::new());
|
|
}
|
|
fn set_wifi_enabled(&mut self, on: bool) {
|
|
self.net(if on { 3 } else { 2 }, String::new(), String::new());
|
|
}
|
|
fn set_airplane_mode(&mut self, on: bool) {
|
|
self.net(if on { 5 } else { 4 }, String::new(), String::new());
|
|
}
|
|
}
|
|
|
|
impl PState {
|
|
fn net(&mut self, action: i32, ssid: String, password: String) {
|
|
self.shared.borrow_mut().requests.push_back(Req::Network(action, ssid, password));
|
|
}
|
|
}
|
|
|
|
impl d::session_settings::Host for PState {
|
|
fn settings(&mut self) -> Vec<String> {
|
|
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::icons::Host for PState {
|
|
/// The handle the compositor published for this app id: it found the app's .desktop file and
|
|
/// its themed icon, and had the rasteriser load it. Modules never see the path.
|
|
fn app_icon(&mut self, app_id: String) -> u32 {
|
|
self.rows(T_ICONS, "si")
|
|
.iter()
|
|
.find(|r| s(&r[0]) == app_id)
|
|
.map(|r| i(&r[1]) as u32)
|
|
.unwrap_or(0)
|
|
}
|
|
}
|
|
|
|
impl d::battery::Host for PState {
|
|
fn read(&mut self) -> d::battery::Status {
|
|
use d::battery::ChargeState as C;
|
|
let (percent, state, secs_left) = self.shared.borrow().battery;
|
|
let state = match state {
|
|
1 => C::Discharging,
|
|
2 => C::Charging,
|
|
3 => C::Full,
|
|
4 => C::NotCharging,
|
|
_ => C::None,
|
|
};
|
|
d::battery::Status { percent: if state == C::None { -1 } else { percent }, state, secs_left }
|
|
}
|
|
}
|
|
|
|
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<PState>,
|
|
inst: ph::PlasmoidHost,
|
|
/// Present when the module exports `module-config`.
|
|
cfg: Option<cfg::Configurable>,
|
|
}
|
|
|
|
/// A file-chooser dialog in flight (zenity on the host session).
|
|
struct Picker {
|
|
child: Child,
|
|
}
|
|
|
|
pub struct Runtime {
|
|
engine: Engine,
|
|
linker: Linker<PState>,
|
|
pub shared: SharedRef,
|
|
slots: Vec<Option<Loaded>>,
|
|
picker: Option<Picker>,
|
|
}
|
|
|
|
pub struct LoadedInfo {
|
|
pub handle: u32,
|
|
pub info: ex::plasmoid::PlasmoidInfo,
|
|
pub imports: Vec<String>,
|
|
}
|
|
|
|
impl Runtime {
|
|
pub fn new(engine: &Engine) -> wasmtime::Result<Self> {
|
|
let mut linker: Linker<PState> = Linker::new(engine);
|
|
ph::PlasmoidHost::add_to_linker::<PState, HasSelf<PState>>(&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<LoadedInfo, String> {
|
|
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<String> = 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 instance =
|
|
self.linker.instantiate(&mut store, &component).map_err(|_| "wasm runtime error".to_string())?;
|
|
let inst = ph::PlasmoidHost::new(&mut store, &instance)
|
|
.map_err(|_| "no plasmoid (chandra:desktop/plasmoid) in this module".to_string())?;
|
|
let cfg = cfg::Configurable::new(&mut store, &instance).ok();
|
|
let info = inst
|
|
.chandra_desktop_plasmoid()
|
|
.call_info(&mut store)
|
|
.map_err(|_| "widget trapped in info()".to_string())?;
|
|
let l = Loaded { store, inst, cfg };
|
|
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<d::types::DrawOp> {
|
|
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<ex::plasmoid::PopupSurface> {
|
|
let l = self.get(handle)?;
|
|
l.inst.chandra_desktop_plasmoid().call_popup(&mut l.store).ok().flatten()
|
|
}
|
|
|
|
/// The module's settings; empty without `module-config` (or when it traps).
|
|
pub fn config_items(&mut self, handle: u32) -> Vec<ConfigItem> {
|
|
let Some(l) = self.get(handle) else { return Vec::new() };
|
|
let Some(c) = &l.cfg else { return Vec::new() };
|
|
c.chandra_desktop_module_config().call_config_items(&mut l.store).unwrap_or_default()
|
|
}
|
|
|
|
/// Set one of the module's settings; true when it wants a redraw.
|
|
pub fn set_config(&mut self, handle: u32, key: &str, value: &str) -> bool {
|
|
let Some(l) = self.get(handle) else { return false };
|
|
let Some(c) = &l.cfg else { return false };
|
|
c.chandra_desktop_module_config().call_set_config(&mut l.store, key, value).unwrap_or(false)
|
|
}
|
|
|
|
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<Option<String>> {
|
|
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<u8> {
|
|
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<String> {
|
|
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 module_settings_are_listed_and_set_when_the_module_exports_them() {
|
|
let mut rt = runtime();
|
|
let c = rt.load(&module("clock-digital")).expect("clock loads");
|
|
let items = rt.config_items(c.handle);
|
|
assert_eq!(items.len(), 2);
|
|
assert_eq!(items[0].key, "format");
|
|
assert_eq!(items[0].choices, vec!["24-hour".to_string(), "12-hour".to_string()]);
|
|
assert_eq!(items[0].value, "24-hour");
|
|
assert!(rt.set_config(c.handle, "format", "12-hour"));
|
|
assert!(!rt.set_config(c.handle, "bogus", "x"));
|
|
assert_eq!(rt.config_items(c.handle)[0].value, "12-hour");
|
|
let ops = rt.render(c.handle, d::types::Size { w: 120, h: 36 });
|
|
assert!(texts(&ops).iter().any(|t| t.ends_with("AM") || t.ends_with("PM")));
|
|
// A module without the export: no settings, and setting one does nothing.
|
|
let l = rt.load(&module("layout")).expect("layout loads");
|
|
assert!(rt.config_items(l.handle).is_empty());
|
|
assert!(!rt.set_config(l.handle, "format", "12-hour"));
|
|
}
|
|
|
|
#[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 four 72 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 + 72 + 36, 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);
|
|
}
|
|
|
|
#[test]
|
|
fn task_list_draws_the_published_icon_handle_else_the_letter_tile() {
|
|
let mut rt = runtime();
|
|
let l = rt.load(&module("tasks")).expect("tasks loads");
|
|
assert!(l.imports.contains(&"icons".to_string()));
|
|
// windows table (isii: id title focused minimized) and the richer windows.all view
|
|
let mut t = 2u32.to_le_bytes().to_vec();
|
|
for (id, title) in [(3i32, "Firefox"), (4, "foot")] {
|
|
t.extend(id.to_le_bytes());
|
|
t.extend((title.len() as u32).to_le_bytes());
|
|
t.extend(title.as_bytes());
|
|
t.extend(0i32.to_le_bytes());
|
|
t.extend(0i32.to_le_bytes());
|
|
}
|
|
// icons table (si: app id, image handle): only Firefox has one
|
|
let mut ic = 1u32.to_le_bytes().to_vec();
|
|
ic.extend(7u32.to_le_bytes());
|
|
ic.extend(b"firefox");
|
|
ic.extend(42i32.to_le_bytes());
|
|
{
|
|
let mut sh = rt.shared.borrow_mut();
|
|
sh.tables[T_WINDOWS] = t;
|
|
sh.tables[T_ICONS] = ic;
|
|
sh.windows = vec![(3, "Firefox".into(), "firefox".into(), false), (4, "foot".into(), "foot".into(), false)];
|
|
}
|
|
let ops = rt.render(l.handle, Size { w: 400, h: 36 });
|
|
let images: Vec<u32> =
|
|
ops.iter().filter_map(|o| if let d::types::DrawOp::Image(i) = o { Some(i.image) } else { None }).collect();
|
|
assert_eq!(images, [42]);
|
|
assert_eq!(texts(&ops), ["Firefox", "F", "foot"]);
|
|
rt.unload(l.handle);
|
|
}
|
|
#[test]
|
|
fn screenshot_module_offers_the_modes_and_asks_for_them() {
|
|
let mut rt = runtime();
|
|
let l = rt.load(&module("screenshot")).expect("screenshot loads");
|
|
assert!(l.imports.contains(&"screenshot".to_string()));
|
|
let h = l.handle;
|
|
rt.shared.borrow_mut().screenshot = 0b10; // not recording, pointer shown
|
|
assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Screenshot".to_string()));
|
|
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
|
let p = rt.popup(h).expect("popup open");
|
|
for n in ["Rectangular Region", "Full Screen", "Record a Region", "Show pointer in recordings"] {
|
|
assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed");
|
|
}
|
|
// Row 2 (Full Screen): the popup closes and a full-screen shot is asked for.
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 20, y: 6 + 2 * 30 + 5 })));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(1))));
|
|
assert!(rt.popup(h).is_none());
|
|
// Reopen; Record the Screen (row 7).
|
|
assert!(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 + 7 * 30 + 5 })));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(11))));
|
|
// While recording the button reads Stop, and a click stops it.
|
|
rt.shared.borrow_mut().screenshot = 0b11;
|
|
assert!(texts(&rt.render(h, Size { w: 110, h: 34 })).contains(&"Stop".to_string()));
|
|
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Screenshot(20))));
|
|
assert!(rt.popup(h).is_none());
|
|
rt.unload(h);
|
|
}
|
|
|
|
#[test]
|
|
fn settings_power_tab_steps_timeouts_and_confirms_power_off() {
|
|
let mut rt = runtime();
|
|
let l = rt.load(&module("session-settings")).expect("session-settings loads");
|
|
assert!(l.imports.contains(&"power".to_string()));
|
|
let h = l.handle;
|
|
rt.shared.borrow_mut().screen_off_min = 10;
|
|
rt.shared.borrow_mut().suspend_min = 0;
|
|
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
|
assert!(rt.on_event(h, true, InputEvent::KeyDown("4".to_string()))); // the Power tab
|
|
let ts = texts(&rt.popup(h).expect("popup open").ops);
|
|
for want in ["Turn screen off after", "10 min", "Suspend after", "Never", "Power off"] {
|
|
assert!(ts.contains(&want.to_string()), "{want} shown");
|
|
}
|
|
// No battery: rows of 28 below the tab bar (40) are When idle, screen off, suspend, Now,
|
|
// Suspend, Restart, Power off.
|
|
let row = |i: i32| Point { x: 20, y: 40 + i * 28 + 13 };
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1))));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetScreenOff(15))));
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(2))));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::SetSuspendAfter(5))));
|
|
// Power off takes two clicks.
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6))));
|
|
assert!(rt.shared.borrow().requests.is_empty());
|
|
assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Click again to power off".to_string()));
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(6))));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::PowerAction(1))));
|
|
rt.unload(h);
|
|
}
|
|
|
|
#[test]
|
|
fn battery_module_shows_charge_time_left_and_warns() {
|
|
let mut rt = runtime();
|
|
let l = rt.load(&module("battery")).expect("battery loads");
|
|
assert!(l.imports.contains(&"battery".to_string()));
|
|
let h = l.handle;
|
|
let size = Size { w: 104, h: 34 };
|
|
// No battery: a plug and no text.
|
|
assert!(!rt.render(h, size).is_empty());
|
|
assert!(texts(&rt.render(h, size)).is_empty());
|
|
rt.shared.borrow_mut().battery = (64, 1, 2 * 3600 + 5 * 60);
|
|
assert_eq!(texts(&rt.render(h, size)), vec!["64% 2:05".to_string()]);
|
|
assert!(rt.set_config(h, "time", "off"));
|
|
assert_eq!(texts(&rt.render(h, size)), vec!["64%".to_string()]);
|
|
// Critical: the warning opens by itself; a click on it closes it.
|
|
rt.shared.borrow_mut().battery = (7, 1, 600);
|
|
rt.render(h, size);
|
|
let ts = texts(&rt.popup(h).expect("warning open").ops);
|
|
assert!(ts.contains(&"Battery low: 7%".to_string()));
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
|
assert!(rt.popup(h).is_none());
|
|
rt.unload(h);
|
|
}
|
|
/// Table bytes from rows of fields ('i' a number, 's' a string).
|
|
enum F<'a> {
|
|
I(i32),
|
|
S(&'a str),
|
|
}
|
|
fn rows_table(rows: &[Vec<F>]) -> Vec<u8> {
|
|
let mut t = (rows.len() as u32).to_le_bytes().to_vec();
|
|
for r in rows {
|
|
for f in r {
|
|
match f {
|
|
F::I(v) => t.extend(v.to_le_bytes()),
|
|
F::S(s) => {
|
|
t.extend((s.len() as u32).to_le_bytes());
|
|
t.extend(s.as_bytes());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
t
|
|
}
|
|
|
|
#[test]
|
|
fn network_module_shows_the_connection_and_connects_with_a_password() {
|
|
let mut rt = runtime();
|
|
let l = rt.load(&module("network")).expect("network loads");
|
|
assert!(l.imports.contains(&"network".to_string()));
|
|
let h = l.handle;
|
|
{
|
|
let mut sh = rt.shared.borrow_mut();
|
|
// Wi-Fi "Home" at 72%, NetworkManager there, Wi-Fi on.
|
|
sh.tables[T_NET_STATUS] = rows_table(&[vec![
|
|
F::I(2),
|
|
F::I(72),
|
|
F::S("Home"),
|
|
F::S(""),
|
|
F::I(1),
|
|
F::I(0),
|
|
F::I(1),
|
|
F::I(1),
|
|
]]);
|
|
sh.tables[T_NET_NETWORKS] = rows_table(&[
|
|
vec![F::S("Home"), F::I(72), F::I(1), F::I(1), F::I(1)],
|
|
vec![F::S("Office"), F::I(55), F::I(1), F::I(0), F::I(0)],
|
|
]);
|
|
}
|
|
assert!(texts(&rt.render(h, Size { w: 130, h: 34 })).contains(&"Home".to_string()));
|
|
// Opening the popup asks for a scan.
|
|
assert!(rt.on_event(h, false, InputEvent::PointerDown(Point { x: 5, y: 5 })));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(0, _, _))));
|
|
let p = rt.popup(h).expect("popup open");
|
|
for n in ["Connected to Home (72%)", "Wi-Fi", "Airplane mode", "Office", "Secured"] {
|
|
assert!(texts(&p.ops).contains(&n.to_string()), "{n} listed");
|
|
}
|
|
// Row 5 (Office) opens the password field; typing and Enter connects.
|
|
let row = |i: i32| Point { x: 60, y: 6 + i * 30 + 14 };
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(5))));
|
|
assert!(texts(&rt.popup(h).unwrap().ops).contains(&"Password|".to_string()));
|
|
for k in ["p", "w", "Enter"] {
|
|
rt.on_event(h, true, InputEvent::KeyDown(k.to_string()));
|
|
}
|
|
match rt.shared.borrow_mut().requests.pop_front() {
|
|
Some(Req::Network(6, ssid, pw)) => assert_eq!((ssid.as_str(), pw.as_str()), ("Office", "pw")),
|
|
_ => panic!("connect asked for"),
|
|
}
|
|
// The Wi-Fi switch (row 1).
|
|
assert!(rt.on_event(h, true, InputEvent::PointerDown(row(1))));
|
|
assert!(matches!(rt.shared.borrow_mut().requests.pop_front(), Some(Req::Network(2, _, _))));
|
|
rt.unload(h);
|
|
}
|
|
}
|