///| The panel's modules: finding them on disk, loading, unloading and replacing them /// while the compositor runs, the capabilities (host data + requests) they use, the /// right-click menu, and the saved panel layout. /// /// A module is a wasm plasmoid component (`chandra:desktop/plasmoid`). Its imports /// are the capabilities it was granted: `theme` and `clock` always, `app-catalog` / /// `app-launch` for the application menu, `windows` for the task list, `layout-control` /// for the layout switcher, `inspector` for the Interface Explorer button and `modules` /// for the module manager. The manager is itself just a module: the wasm picker /// ("Module manager..." in the panel menu) loads it on demand and opens it. ///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right. let default_panel : Array[String] = [ "launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12", "session-settings", "logout", ] ///| The module whose popup is the wasm picker. let manager_module : String = "module-manager" ///| Directories searched for `*.wasm` modules, highest priority first. fn module_dirs() -> Array[String] { let dirs : Array[String] = [] let env = @sys.getenv("CHANDRA_MODULES") if env.length() > 0 { for d in env.split(":") { if d.length() > 0 { dirs.push(d.to_string()) } } } let data_home = { let x = @sys.getenv("XDG_DATA_HOME") if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.local/share" } } dirs.push(data_home + "/chandra/modules") dirs.push("/usr/local/share/chandra/modules") dirs.push("/usr/share/chandra/modules") dirs.push("modules") // the login session runs from /usr/local/share/chandra // In a source checkout (and from a package directory when running its tests). dirs.push("build/components") dirs.push("../build/components") dirs.push("../../build/components") dirs } ///| "/a/b/clock.wasm" -> "clock" fn stem(path : String) -> String { let mut start = 0 for i = 0; i < path.length(); i = i + 1 { if path[i] == '/' { start = i + 1 } } let name = path[start:].to_string() if name.has_suffix(".wasm") { name[:name.length() - 5].to_string() } else { name } } ///| The WIT world ("clock-widget", "taskbar-widget", ...) a module was built for, read from the /// `.meta.json` that build-modules.sh writes next to it; "" when unknown (a module loaded /// from elsewhere). Two modules are interchangeable only when their worlds match. fn module_world(path : String) -> String { let base = if path.has_suffix(".wasm") { path[:path.length() - 5].to_string() } else { path } let text = @utf8.decode_lossy(@sys.read_file_bytes(base + ".meta.json")) match text.find("\"world\":\"") { None => "" Some(i) => { let rest = text[i + 9:].to_string() match rest.find("\"") { Some(j) => rest[:j].to_string() None => "" } } } } ///| Find every module file on the search path (earlier directories win on the same name). fn DesktopShell::scan_catalog(self : DesktopShell) -> Unit { self.catalog.clear() self.catalog_named = false let seen : Map[String, Bool] = {} for dir in module_dirs() { for f in @wasm.list_wasm_files(dir) { let id = stem(f) if !seen.contains(id) { seen.set(id, true) self.catalog.push({ id, path: dir + "/" + f, name: "" }) } } } } ///| Learn each module's display name by loading it once; files that are not plasmoids /// (the shell, window-manager and gfx components live in the same directory) drop out. fn DesktopShell::name_catalog(self : DesktopShell) -> Unit { if self.catalog_named { return } self.catalog_named = true let keep : Array[CatalogEntry] = [] for e in self.catalog { match @wasm.load(e.path, self.tokens) { Ok(pl) => { e.name = pl.name pl.unload() keep.push(e) } Err(_) => () } } self.catalog.clear() for e in keep { self.catalog.push(e) } } ///| Catalog entry for module id `id`. fn DesktopShell::find_module(self : DesktopShell, id : String) -> CatalogEntry? { for e in self.catalog { if e.id == id { return Some(e) } } None } ///| Panel slot descriptions for every loaded module, in panel order. A stretching module /// (the task list) splits the panel: modules after it pack against the right edge. fn DesktopShell::panel_slots(self : DesktopShell) -> Array[@panel.SlotIn] { let mut first_stretch = -1 for i = 0; i < self.widgets.length(); i = i + 1 { if first_stretch < 0 && self.widgets[i].pl.stretch { first_stretch = i } } let out : Array[@panel.SlotIn] = [] for i = 0; i < self.widgets.length(); i = i + 1 { let w = self.widgets[i] out.push({ id: w.slot, pref_w: w.pl.pref_w, pref_h: w.pl.pref_h, min_w: w.pl.min_w, stretch: w.pl.stretch, end_align: first_stretch >= 0 && i > first_stretch, }) } out } ///| Would the panel still fit on screen with the current modules? fn DesktopShell::panel_fits(self : DesktopShell) -> Bool { match @panel.layout(self.screen_w, 100000, 40, 4, 6, self.panel_slots()) { Ok(_) => true Err(_) => false } } ///| Show a short message above the panel for a few seconds. fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit { self.notice = msg self.notice_frames = 1 self.notice_start = wall_secs() } ///| Seconds since local midnight (wall clock). fn wall_secs() -> Int { @sys.wall_time_field(3) * 3600 + @sys.wall_time_field(4) * 60 + @sys.wall_time_field(5) } ///| Panels saved before the wallpaper chooser moved into the settings module list "wallpaper": /// the settings module takes its place (once; a panel that already has it just drops it). fn migrate_panel(entries : Array[String]) -> Array[String] { let has_settings = entries.contains("session-settings") let out : Array[String] = [] for e in entries { if e == "wallpaper" { if !has_settings && !out.contains("session-settings") { out.push("session-settings") } } else { out.push(e) } } out } ///| test "a saved panel's wallpaper button becomes the settings module" { assert_eq(migrate_panel(["launcher", "wallpaper", "logout"]), ["launcher", "session-settings", "logout"]) assert_eq(migrate_panel(["wallpaper", "session-settings"]), ["session-settings"]) assert_eq(migrate_panel(["clock"]), ["clock"]) } ///| Load the panel on first use: the saved layout if there is one, else the default modules. fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit { if self.booted { return } self.booted = true self.scan_catalog() let entries = match self.load_panel_config() { Some(e) => migrate_panel(e) None => default_panel } for e in entries { let path = if e.has_prefix("/") { e } else { match self.find_module(e) { Some(c) => c.path None => { self.say("Module '" + e + "' not found (build it with scripts/build-modules.sh)") "" } } } if path != "" { ignore(self.load_path(path)) } } } ///| Load the module file at `path` into the panel (any number of instances may be loaded). /// None, with a notice, when it is not a plasmoid or the panel has no room for it. pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? { match @wasm.load(path, self.tokens) { Err(e) => { self.say("Can't load module: " + e) None } Ok(pl) => { let id = stem(path) let known = match self.find_module(id) { Some(c) => c.path == path None => false } let w : Widget = { slot: "w" + self.next_slot.to_string(), module_id: if known { id } else { path }, path, pl, caps: pl.imports(), rect: { x: 0, y: 0, w: 0, h: 0 }, popup_rect: { x: 0, y: 0, w: 0, h: 0 }, popup_ops: [], popup_hot: false, } self.next_slot = self.next_slot + 1 self.widgets.push(w) if self.screen_w > 0 && !self.panel_fits() { self.widgets.retain(x => x.slot != w.slot) pl.unload() self.say("No room in the panel for " + pl.name) None } else { Some(w) } } } } ///| Load module `id` (a file stem from the catalog, or a path) and persist the panel. pub fn DesktopShell::load_module(self : DesktopShell, id : String) -> Bool { self.ensure_booted() let path = match self.find_module(id) { Some(c) => c.path None => id } match self.load_path(path) { Some(w) => { self.say("Loaded " + w.pl.name) self.save_panel_config() true } None => false } } ///| Unload the module in `slot`, freeing its panel space. False if there is none. pub fn DesktopShell::unload_slot(self : DesktopShell, slot : String) -> Bool { match self.widget_by_slot(slot) { None => false Some(w) => { self.widgets.retain(x => x.slot != slot) w.pl.unload() if self.drag_slot == slot { self.drag_slot = "" self.drag_active = false } self.save_panel_config() true } } } ///| Replace the module in `slot` with the module file at `path`, keeping its place in the panel. pub fn DesktopShell::replace_slot(self : DesktopShell, slot : String, path : String) -> Bool { let mut idx = -1 for i = 0; i < self.widgets.length(); i = i + 1 { if self.widgets[i].slot == slot { idx = i } } if idx < 0 { return false } let old = self.widgets[idx] self.widgets.remove(idx) |> ignore match self.load_path(path) { None => { self.widgets.insert(idx, old) false } Some(nw) => { // load_path appended it; move it into the old module's place, then drop the old one. self.widgets.retain(x => x.slot != nw.slot) self.widgets.insert(idx, nw) old.pl.unload() self.save_panel_config() true } } } ///| Unload every module (the compositor is closing). pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit { for w in self.widgets { w.pl.unload() } self.widgets.clear() } ///| Slot ids of the loaded modules, in panel order. pub fn DesktopShell::slots(self : DesktopShell) -> Array[String] { self.ensure_booted() self.widgets.map(w => w.slot) } ///| Module id of the module in `slot` ("" if none). pub fn DesktopShell::slot_module(self : DesktopShell, slot : String) -> String { match self.widget_by_slot(slot) { Some(w) => w.module_id None => "" } } ///| Slot of the first loaded instance of module `id` ("" if none). pub fn DesktopShell::slot_of(self : DesktopShell, id : String) -> String { self.ensure_booted() for w in self.widgets { if w.module_id == id { return w.slot } } "" } ///| Panel rectangle of the module in `slot` as last drawn. pub fn DesktopShell::slot_rect(self : DesktopShell, slot : String) -> @scene.Rect { match self.widget_by_slot(slot) { Some(w) => w.rect None => { x: 0, y: 0, w: 0, h: 0 } } } ///| Rectangle of the module's open popup (w == 0 when closed). pub fn DesktopShell::slot_popup_rect(self : DesktopShell, slot : String) -> @scene.Rect { match self.widget_by_slot(slot) { Some(w) => w.popup_rect None => { x: 0, y: 0, w: 0, h: 0 } } } ///| Publish what modules can read through their capabilities (apps, windows, layout, loaded modules). fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit { if self.apps_dirty { self.apps_dirty = false let t = @wasm.Table::new() for a in self.apps { t.str(a.id) t.str(a.name) t.str(a.comment) t.str(a.category) t.str(a.glyph) t.end_row() } @wasm.publish(Apps, t) } let wt = @wasm.Table::new() for win in self.windows { wt.int(win.id.to_int()) wt.str(win.title) wt.int(if win.focused { 1 } else { 0 }) wt.int(if win.minimized { 1 } else { 0 }) wt.end_row() } @wasm.publish(Windows, wt) let lt = @wasm.Table::new() for n in self.layout_names { lt.str(n) lt.end_row() } @wasm.publish(Layouts, lt) @wasm.publish_state(self.layout_sel, self.inspect_on) if self.widgets.iter().any(w => w.has_cap("wallpaper")) { let pt = @wasm.Table::new() for n in @libshell.wallpaper_names { pt.str(n) pt.end_row() } @wasm.publish(Wallpapers, pt) @wasm.publish_wallpaper(self.wallpaper_sel) } if self.widgets.iter().any(w => w.has_cap("session-settings")) { let st = @wasm.Table::new() for n in session_setting_names { st.str(n) st.end_row() } @wasm.publish(SessionSettings, st) @wasm.publish_session_settings(self.session_settings_bits()) } let it = @wasm.Table::new() for w in self.widgets { it.str(w.slot) it.str(w.module_id) it.str(w.pl.name) it.end_row() } @wasm.publish(Instances, it) let mut wants_modules = false for w in self.widgets { if w.has_cap("modules") { wants_modules = true } } if wants_modules { self.name_catalog() let mt = @wasm.Table::new() for e in self.catalog { let mut n = 0 for w in self.widgets { if w.path == e.path { n = n + 1 } } mt.str(e.id) mt.str(e.name) mt.str(e.path) mt.int(n) mt.end_row() } @wasm.publish(Modules, mt) } } ///| Show wallpaper `i` (ignored when out of range) and remember it in state.edn. pub fn DesktopShell::set_wallpaper(self : DesktopShell, i : Int) -> Unit { if i < 0 || i >= @libshell.wallpaper_names.length() || i == self.wallpaper_sel { return } self.wallpaper_sel = i @wasm.publish_wallpaper(i) self.save_state() } ///| The session settings the session settings module lists, in index order. let session_setting_names : Array[String] = [ "Reopen windows at login", "Remember window positions", "Dark mode", ] ///| Which session settings are on: bit i for `session_setting_names[i]`. fn DesktopShell::session_settings_bits(self : DesktopShell) -> Int { (if self.restore_session { 1 } else { 0 }) | (if self.remember_windows { 2 } else { 0 }) | (if self.dark_mode { 4 } else { 0 }) } ///| Turn session setting `i` on or off (ignored when out of range) and remember it in state.edn. pub fn DesktopShell::set_session_setting(self : DesktopShell, i : Int, on : Bool) -> Unit { match i { 0 => self.restore_session = on 1 => self.remember_windows = on 2 => if self.dark_mode != on { self.dark_mode = on self.actions.push(ThemeChanged) } _ => return } @wasm.publish_session_settings(self.session_settings_bits()) self.save_state() } ///| Carry out what modules asked of the host during their last calls. fn DesktopShell::process_requests(self : DesktopShell) -> Unit { while true { match @wasm.next_request() { None => break Some(Launch(id)) => { match self.exec.get(id) { Some(bin) => if @sys.spawn(bin, self.display) { self.note_recent(id) self.apps_dirty = true } else { self.say("Could not start " + bin) } None => self.say("No executable for " + id) } } Some(FocusWindow(n)) => self.actions.push(FocusWindow(n.to_int64().to_uint64())) Some(SetLayout(m)) => self.actions.push(SetLayout(m)) Some(Logout) => self.actions.push(Logout) Some(SetWallpaper(i)) => self.set_wallpaper(i) Some(SetSessionSetting(i, on)) => self.set_session_setting(i, on) Some(SetInspector(on)) => self.set_inspecting(on) Some(LoadModule(path)) => { match self.load_path(path) { Some(w) => { self.say("Loaded " + w.pl.name) self.save_panel_config() } None => () } } Some(UnloadInstance(slot)) => ignore(self.unload_slot(slot)) Some(Browse) => if self.picker is None { self.picker = @wasm.Picker::start() if self.picker is None { self.say("No file chooser available (install zenity)") } } } } // A module that imports `windows.focus` (the 64-bit-id form) asks through its own slot. match @wasm.take_focus_request() { Some(id) => self.actions.push(FocusWindow(id)) None => () } } ///| Re-read the module's popup (size and drawing) and place it above the panel. fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit { if self.widget_by_slot(w.slot) is None { return } match w.pl.popup() { None => { w.popup_rect = { x: 0, y: 0, w: 0, h: 0 } w.popup_ops = [] w.popup_hot = false } Some(ps) => { let (px, py) = @panel.popup_position(self.screen_w, self.screen_h - self.panel_h, w.rect.x, ps.w, ps.h, 6) w.popup_rect = { x: px, y: py, w: ps.w, h: ps.h } w.popup_ops = ps.ops } } } ///| Check the open file dialog; load the chosen .wasm into the panel. fn DesktopShell::poll_picker(self : DesktopShell) -> Unit { match self.picker { None => () Some(pk) => match pk.poll() { None => () Some(None) => self.picker = None Some(Some(path)) => { self.picker = None match self.load_path(path) { Some(w) => { self.say("Loaded " + w.pl.name) self.save_panel_config() } None => () } } } } } ///| The wasm picker: open the module manager app to choose what to load, loading the /// manager itself first if it is not in the panel. pub fn DesktopShell::open_module_manager(self : DesktopShell) -> Bool { self.ensure_booted() let mut mgr : Widget? = None for w in self.widgets { if mgr is None && w.module_id == manager_module { mgr = Some(w) } } if mgr is None { match self.find_module(manager_module) { None => { self.say("Module manager not found (build it with scripts/build-modules.sh)") return false } Some(c) => mgr = self.load_path(c.path) } } match mgr { None => false Some(w) => { self.dismiss_popups(w.slot) if w.popup_rect.w == 0 { ignore(self.deliver(w, false, PointerDown(0, 0))) } self.save_panel_config() true } } } // ---------------------------------------------------------------- right-click menu ///| Title row height and item row height of the menu. let menu_title_h : Int = 26 ///| let menu_item_h : Int = 28 ///| let menu_w : Int = 250 ///| Most "Replace with" rows listed. let max_replace_rows : Int = 8 ///| Right-click: on a module its replace/remove menu, on empty panel space the picker entry. /// True when consumed. pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool { self.ensure_booted() if self.inspect_on { return false } let was_open = self.menu_open self.menu_open = false self.dismiss_popups("") match self.widget_at(x, y) { Some(w) => { self.name_catalog() let rows : Array[MenuRow] = [] // Only modules of the same kind (same WIT world) can stand in for this one. let world = module_world(w.path) for e in self.catalog { if world.length() > 0 && e.id != w.module_id && e.path != w.path && rows.length() < max_replace_rows && module_world(e.path) == world { rows.push({ label: "Replace with " + e.name, kind: 0, arg: e.path }) } } rows.push({ label: "Remove widget", kind: 1, arg: "" }) rows.push({ label: "Module manager...", kind: 2, arg: "" }) self.open_menu(w.pl.name, rows, w.slot, x) true } None => if inside(self.panel_rect, x, y) { self.open_menu("Add widget", [{ label: "Module manager...", kind: 2, arg: "" }], "", x) true } else { was_open } } } ///| fn DesktopShell::open_menu(self : DesktopShell, title : String, rows : Array[MenuRow], slot : String, x : Int) -> Unit { self.menu_open = true self.menu_title = title self.menu_rows = rows self.menu_slot = slot self.menu_hover = -1 self.menu_anchor_x = x } ///| fn DesktopShell::menu_item_at(self : DesktopShell, x : Int, y : Int) -> Int { if !self.menu_open || !inside(self.menu_rect, x, y) { return -1 } let i = (y - self.menu_rect.y - menu_title_h) / menu_item_h if y - self.menu_rect.y >= menu_title_h && i >= 0 && i < self.menu_rows.length() { i } else { -1 } } ///| Left press while the menu is open: choose a row or dismiss. True when consumed. fn DesktopShell::menu_pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool { let i = self.menu_item_at(x, y) let over = inside(self.menu_rect, x, y) self.menu_open = false if i >= 0 { let row = self.menu_rows[i] let slot = self.menu_slot match row.kind { 0 => ignore(self.replace_slot(slot, row.arg)) 1 => ignore(self.unload_slot(slot)) _ => ignore(self.open_module_manager()) } } over } ///| fn DesktopShell::menu_pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool { self.menu_hover = self.menu_item_at(x, y) inside(self.menu_rect, x, y) } ///| fn DesktopShell::render_menu( self : DesktopShell, w : Int, tokens : @theme.Tokens, out : Array[@scene.DrawOp], ) -> Unit { let n = self.menu_rows.length() let mh = menu_title_h + n * menu_item_h + 6 let mx = clamp_menu(self.menu_anchor_x - menu_w / 2, 4, w - menu_w - 4) let my = self.panel_rect.y - mh - 6 self.menu_rect = { x: mx, y: my, w: menu_w, h: mh } let fs = tokens.font_size.reinterpret_as_int() let r = tokens.radius.reinterpret_as_int() let ops : Array[@types.DrawOp] = [ @ui.fill_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.surface_popup, radius=r), @ui.stroke_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.border, radius=r), @ui.text(12, menu_title_h / 2 + 2, self.menu_title, fs - 3, tokens.palette.foreground_muted), ] for i = 0; i < n; i = i + 1 { let top = menu_title_h + i * menu_item_h let hot = i == self.menu_hover if hot { ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r)) } ops.push(@ui.text(14, top + menu_item_h / 2, self.menu_rows[i].label, fs - 2, tokens.palette.foreground)) } translate(ops, mx, my, out) } ///| fn clamp_menu(v : Int, lo : Int, hi : Int) -> Int { if v > hi { hi } else if v < lo { lo } else { v } } // ---------------------------------------------------------------- saved panel ///| Panel config lives in $XDG_CONFIG_HOME/chandra/panel.edn (default ~/.config). fn panel_config_dir() -> String { config_base() + "/chandra" } ///| fn config_base() -> String { let c = @sys.getenv("XDG_CONFIG_HOME") if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.config" } } ///| Read a saved config file. Before the rename to Chandra it lived under /// $XDG_CONFIG_HOME/moon-plasma; fall back to that when there is no new copy yet /// (the next save writes it to the new place). fn read_config_file(name : String) -> Bytes { let b = @sys.read_file_bytes(panel_config_dir() + "/" + name) if b.length() > 0 { b } else { @sys.read_file_bytes(config_base() + "/moon-plasma/" + name) } } ///| Write the loaded modules, in panel order, as EDN: /// {:panel ["launcher" "layout" "tasks" "/home/me/my-widget.wasm"]} /// (catalog modules by name, others by path). A no-op unless `persist` is on. pub fn DesktopShell::save_panel_config(self : DesktopShell) -> Unit { if !self.persist || !self.booted { return } let sb = StringBuilder::new() sb.write_string(";; Chandra panel: the wasm modules loaded into it, in order\n") sb.write_string("{:panel [") let mut first = true for w in self.widgets { if !first { sb.write_string("\n ") } first = false sb.write_string("\"" + w.module_id + "\"") } sb.write_string("]}\n") let dir = panel_config_dir() if @sys.mkdir_p(dir) { ignore(@sys.write_file_bytes(dir + "/panel.edn", @utf8.encode(sb.to_string()))) } } ///| The module list saved in panel.edn; None when persistence is off or there is no saved panel. fn DesktopShell::load_panel_config(self : DesktopShell) -> Array[String]? { if !self.persist { return None } let text = @utf8.decode_lossy(read_config_file("panel.edn")) let lines : Array[String] = [] for l in text.split("\n") { if !l.trim(chars=" \t\r").to_string().has_prefix(";") { lines.push(l.to_string()) } } let body = lines.join("\n") match body.find(":panel") { None => None Some(i) => { let rest = body[i:].to_string() match (rest.find("["), rest.find("]")) { (Some(a), Some(b)) if b > a => { let out : Array[String] = [] for part in rest[a + 1:b].to_string().split("\"") { // quoted strings are the odd-numbered parts out.push(part.to_string()) } let names : Array[String] = [] for k = 1; k < out.length(); k = k + 2 { if out[k].length() > 0 { names.push(out[k]) } } Some(names) } _ => None } } } } ///| Theme tokens in the WIT shape the plasmoids expect. pub fn DesktopShell::tokens_for(_self : DesktopShell, theme : @scene.ThemeTokens) -> @theme.Tokens { conv_theme(theme) }