///| 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 /// `session-settings`, `wallpaper` and `modules` for the settings module. Managing modules is a /// tab of that module: "System settings..." in the empty-panel right-click menu loads it on demand /// and opens that tab. A module may also export `module-config`: its own settings, listed under /// "Module settings..." in its right-click menu and remembered in state.edn (module_config.mbt). ///| 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", "screenshot", "session-settings", "logout", ] ///| The module whose popup holds the wasm picker (its Modules tab). let manager_module : String = "session-settings" ///| 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. pub 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 and the module manager moved into the settings /// module list "wallpaper" or "module-manager": the settings module takes the first one's place /// (a panel that already has it just drops them). 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" || e == "module-manager" { 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(["module-manager", "clock", "wallpaper"]), ["session-settings", "clock"]) 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.apply_module_cfg(w) 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()) } if self.widgets.iter().any(w => w.has_cap("power")) { @wasm.publish_power(self.screen_off_min, self.suspend_min) } if self.widgets.iter().any(w => w.has_cap("screenshot")) { @wasm.publish_screenshot(self.screenshot_state) } 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() } ///| Default power timeouts, in minutes (0: never): the screen goes off after 10 minutes without /// input; the computer doesn't suspend on its own. let default_screen_off_min : Int = 10 ///| let default_suspend_min : Int = 0 ///| Set the power timeouts (minutes, 0: never; clamped to a day) and remember them. pub fn DesktopShell::set_power_timeouts(self : DesktopShell, screen_off : Int, suspend : Int) -> Unit { let clamp = fn(m : Int) { if m < 0 { 0 } else if m > 1440 { 1440 } else { m } } self.screen_off_min = clamp(screen_off) self.suspend_min = clamp(suspend) @wasm.publish_power(self.screen_off_min, self.suspend_min) 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(Screenshot(code)) => self.actions.push(Screenshot(code)) Some(SetScreenOff(m)) => self.set_power_timeouts(m, self.suspend_min) Some(SetSuspendAfter(m)) => self.set_power_timeouts(self.screen_off_min, m) Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) } 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 => () } } } } } ///| Tabs of the settings module's popup, for `open_settings`. pub(all) enum SettingsTab { /// The session switches. Session /// What is on the desktop: the wallpaper (modules can't be placed on the desktop yet). Desktop /// The panel's modules: remove, add, browse. Panel /// Battery, idle timeouts, suspend / restart / power off. Power } derive(Eq, Debug) ///| Open the settings module ("System settings") on `tab`, loading it into the panel first if it /// isn't there. False when it can't be found or loaded. pub fn DesktopShell::open_settings(self : DesktopShell, tab : SettingsTab) -> 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("Settings module 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))) } // The module's keys 1-4 pick its tabs. let key = match tab { Session => "1" Desktop => "2" Panel => "3" Power => "4" } ignore(self.deliver(w, true, KeyDown(key))) self.save_panel_config() true } } } ///| The wasm picker: open the settings module on its Panel tab to choose what to load. pub fn DesktopShell::open_module_manager(self : DesktopShell) -> Bool { self.open_settings(Panel) } // ---------------------------------------------------------------- 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 menu (Module settings, System settings, replace, remove); on /// empty panel space System settings (whose Panel tab adds modules). 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] = [] if w.pl.config_items().length() > 0 { rows.push(menu_row("Module settings...", 3)) } else { rows.push(menu_row("No module settings", 5)) } rows.push(menu_row("System settings...", 2)) // Only modules of the same kind (same WIT world) can stand in for this one. let world = module_world(w.path) let mut replace = 0 for e in self.catalog { if world.length() > 0 && e.id != w.module_id && e.path != w.path && replace < max_replace_rows && module_world(e.path) == world { rows.push(menu_row("Replace with " + e.name, 0, arg=e.path)) replace = replace + 1 } } rows.push(menu_row("Remove widget", 1)) self.open_menu(w.pl.name, rows, w.slot, x) true } None => if inside(self.panel_rect, x, y) { // Empty panel space: System settings on its Panel tab, where modules are added. self.open_menu("Panel", [menu_row("System settings...", 2, arg="panel")], "", x) true } else { was_open } } } ///| The module's own settings as menu rows: an on/off setting is one row, ticked when on; a /// setting with choices is a heading and one row per choice, the current one ticked. fn config_rows(items : Array[@wasm.ConfigItem]) -> Array[MenuRow] { let rows : Array[MenuRow] = [] for it in items { if it.choices.length() == 0 { let on = it.value == "on" rows.push({ label: it.label, kind: 4, arg: it.key, value: if on { "off" } else { "on" }, ticked: on }) } else { rows.push(menu_row(it.label, 5)) for c in it.choices { rows.push({ label: c, kind: 4, arg: it.key, value: c, ticked: c == it.value }) } } } rows } ///| Show the "Module settings" menu of the module in `slot` (in place of its right-click menu). fn DesktopShell::open_module_settings(self : DesktopShell, slot : String) -> Unit { match self.widget_by_slot(slot) { None => () Some(w) => { let rows = config_rows(w.pl.config_items()) if rows.length() == 0 { rows.push(menu_row("No module settings", 5)) } self.open_menu(w.pl.name + " settings", rows, slot, self.menu_anchor_x) } } } ///| Set a setting of the module in `slot` (and of its other instances) and remember it in state.edn. pub fn DesktopShell::set_module_setting(self : DesktopShell, slot : String, key : String, value : String) -> Unit { match self.widget_by_slot(slot) { None => () Some(w) => { self.remember_module_setting(w.module_id, key, value) for o in self.widgets { if o.module_id == w.module_id { ignore(o.pl.set_config(key, value)) } } } } } ///| The settings the module in `slot` offers, with their current values. pub fn DesktopShell::slot_config(self : DesktopShell, slot : String) -> Array[@wasm.ConfigItem] { match self.widget_by_slot(slot) { Some(w) => w.pl.config_items() None => [] } } ///| What the module in `slot` draws in its panel box now. pub fn DesktopShell::slot_ops(self : DesktopShell, slot : String) -> Array[@types.DrawOp] { match self.widget_by_slot(slot) { Some(w) => w.pl.render(w.rect.w, w.rect.h, self.tokens) None => [] } } ///| A setting chosen in the module's menu: apply it, remember it, and refresh the menu. fn DesktopShell::choose_module_setting(self : DesktopShell, slot : String, key : String, value : String) -> Unit { self.set_module_setting(slot, key, value) let hover = self.menu_hover self.open_module_settings(slot) self.menu_hover = hover } ///| 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)) 2 => ignore(self.open_settings(if row.arg == "panel" { Panel } else { Session })) 3 => self.open_module_settings(slot) 4 => self.choose_module_setting(slot, row.arg, row.value) // A heading: the menu stays open. _ => self.menu_open = true } } 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 row = self.menu_rows[i] let hot = i == self.menu_hover && row.kind != 5 if hot { ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r)) } if row.kind == 5 { ops.push(@ui.text(14, top + menu_item_h / 2, row.label, fs - 3, tokens.palette.foreground_muted)) } else if row.kind == 4 { // A setting: a check box, filled with the accent colour when ticked. let cy = top + menu_item_h / 2 if row.ticked { ops.push(@ui.fill_rect(@ui.rect(16, cy - 6, 12, 12), tokens.palette.accent, radius=3)) ops.push(@ui.line(19, cy, 21, cy + 3, tokens.palette.accent_foreground, width=2)) ops.push(@ui.line(21, cy + 3, 26, cy - 3, tokens.palette.accent_foreground, width=2)) } else { ops.push(@ui.stroke_rect(@ui.rect(16, cy - 6, 12, 12), tokens.palette.foreground_muted, radius=3)) } ops.push(@ui.text(36, cy, row.label, fs - 2, tokens.palette.foreground)) } else { ops.push(@ui.text(14, top + menu_item_h / 2, row.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) }