///| Loads the desktop shell (lib/shell background + panel chrome, lib/panel /// layout, lib/launcher button, lib/clock widget) into the native compositor. /// The shell logic is the same code the wasm components wrap; this package only /// adapts its WIT-shaped types to the compositor's scene types. ///| fn conv_color(c : @types.Color) -> @scene.Rgba { { r: c.r, g: c.g, b: c.b, a: c.a } } ///| fn conv_theme(t : @scene.ThemeTokens) -> @theme.Tokens { let p = t.palette let col = fn(c : @scene.Rgba) -> @types.Color { { r: c.r, g: c.g, b: c.b, a: c.a } } { name: t.name, palette: { desktop_top: col(p.desktop_top), desktop_bottom: col(p.desktop_bottom), surface: col(p.surface), surface_hover: col(p.surface_hover), surface_popup: col(p.surface_popup), foreground: col(p.foreground), foreground_muted: col(p.foreground_muted), accent: col(p.accent), accent_foreground: col(p.accent_foreground), border: col(p.border), }, font_size: t.font_size.reinterpret_as_uint(), radius: t.radius.reinterpret_as_uint(), spacing: t.spacing.reinterpret_as_uint(), panel_height: t.panel_height.reinterpret_as_uint(), } } ///| Translate a widget render-list into scene ops, offset to screen coordinates. fn translate( ops : Array[@types.DrawOp], dx : Int, dy : Int, out : Array[@scene.DrawOp], ) -> Unit { let rect = fn(r : @types.Rect) -> @scene.Rect { { x: r.x + dx, y: r.y + dy, w: r.w.reinterpret_as_int(), h: r.h.reinterpret_as_int(), } } for op in ops { match op { FillRect(f) => out.push( @scene.DrawOp::FillRect( rect(f.rect), conv_color(f.color), f.radius.reinterpret_as_int(), ), ) StrokeRect(s) => out.push( @scene.DrawOp::StrokeRect( rect(s.rect), conv_color(s.color), s.width.reinterpret_as_int(), s.radius.reinterpret_as_int(), ), ) Line(l) => out.push( @scene.DrawOp::Line( l.start.x + dx, l.start.y + dy, l.end.x + dx, l.end.y + dy, conv_color(l.color), l.width.reinterpret_as_int(), ), ) Circle(c) => out.push( @scene.DrawOp::Circle( c.center.x + dx, c.center.y + dy, c.radius.reinterpret_as_int(), conv_color(c.color), c.filled, ), ) Text(t) => { let align = match t.style.align { LEFT => @scene.TextAlign::Left CENTER => @scene.TextAlign::Center RIGHT => @scene.TextAlign::Right } out.push( @scene.DrawOp::Text( t.origin.x + dx, t.origin.y + dy, t.text, t.style.size.reinterpret_as_int(), conv_color(t.style.color), align, t.style.bold, ), ) } PushClip(r) => out.push(@scene.DrawOp::PushClip(rect(r))) PopClip => out.push(@scene.DrawOp::PopClip) } } } ///| Current local time in the WIT `datetime` shape. fn now() -> @types.Datetime { { year: @sys.wall_time_field(0).reinterpret_as_uint(), month: @sys.wall_time_field(1).to_byte(), day: @sys.wall_time_field(2).to_byte(), hour: @sys.wall_time_field(3).to_byte(), minute: @sys.wall_time_field(4).to_byte(), second: @sys.wall_time_field(5).to_byte(), weekday: @sys.wall_time_field(6).to_byte(), } } ///| A window as the panel's task list sees it (handed to modules through the `windows` capability). pub(all) struct WinInfo { id : UInt64 title : String focused : Bool minimized : Bool } ///| Something a panel module asked the compositor to do. pub(all) enum ShellAction { SetLayout(Int) FocusWindow(UInt64) } derive(Eq, Debug) ///| One wasm module loaded into the panel. pub(all) struct Widget { /// Panel slot id ("w1", "w2", ...): one per loaded instance. slot : String /// The module's file stem ("clock-digital"), or its path for modules loaded from elsewhere. module_id : String path : String pl : @wasm.Plasmoid /// Host interfaces the module imports (its capabilities). caps : Array[String] mut rect : @scene.Rect /// Where its popup is on screen (w == 0 while closed), and what to draw there. mut popup_rect : @scene.Rect mut popup_ops : Array[@types.DrawOp] mut popup_hot : Bool } ///| A wasm module file found on the module path. pub(all) struct CatalogEntry { id : String path : String /// Filled in (by loading the module once) the first time names are needed; "" until then. mut name : String } ///| One row of the right-click menu: kind 0 replace with module `arg` (a path), 1 remove, 2 open the module manager. pub(all) struct MenuRow { label : String kind : Int arg : String } ///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules /// (application menu, Interface Explorer, layout switcher, task list, moon, clock ...). /// Nothing on the panel is built in: every element is a plasmoid component loaded /// from a `.wasm` file and can be unloaded or replaced while the compositor runs. pub(all) struct DesktopShell { apps : Array[@types.AppEntry] exec : Map[String, String] /// Wayland socket handed to launched apps as WAYLAND_DISPLAY. display : String /// Panel modules in panel order; a module with `stretch` splits the panel into a left and a right group. widgets : Array[Widget] mut next_slot : Int /// Module files on the search path (see `module_dirs`). catalog : Array[CatalogEntry] mut catalog_named : Bool mut booted : Bool /// Read and write panel.edn (the compositor binary turns this on; tests leave it off). mut persist : Bool mut tokens : @theme.Tokens mut screen_w : Int /// Desktop card position (once moved) and drag state. mut desk_set : Bool mut desk_x : Int mut desk_y : Int mut desk_drag : Bool mut desk_off_x : Int mut desk_off_y : Int mut screen_h : Int mut panel_h : Int /// Window list + layout mode, set by the compositor before each frame. mut windows : Array[WinInfo] mut layout_sel : Int mut layout_names : Array[String] /// Things modules asked for (focus a window, switch layout), drained by the compositor. actions : Array[ShellAction] mut apps_dirty : Bool /// The native file chooser opened by the module manager's "Browse" row, and a transient notice. mut picker : @wasm.Picker? /// Machine-state provider behind the `system` interface, and the window list behind `windows`. sampler : SysSampler mut win_list : Array[@wasm.WindowEntry] mut notice : String mut notice_frames : Int mut notice_start : Int /// Right-click menu. mut menu_open : Bool mut menu_rect : @scene.Rect mut menu_title : String mut menu_rows : Array[MenuRow] mut menu_hover : Int mut menu_anchor_x : Int mut menu_slot : String /// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold. mut drag_slot : String /// Panel widget the pointer is over (it gets pointer-move / pointer-leave), "" for none. mut hover_slot : String mut drag_x0 : Int mut drag_y0 : Int mut drag_active : Bool // WIT inspector state (see inspector.mbt) mut inspect_on : Bool mut hover_id : String mut hover_x : Int mut inspect_scroll : Int mut hover_y : Int mut panel_rect : @scene.Rect comps : Array[(String, @scene.Rect)] wit_cache : Map[String, String] /// Most-recently-launched app ids, newest first (persisted). recents : Array[String] } ///| pub fn DesktopShell::new(display : String) -> DesktopShell { let apps : Array[@types.AppEntry] = [] let exec : Map[String, String] = {} for a in scan_desktop_apps() { let glyph = match a.name.to_array().get(0) { Some(c) => c.to_string().to_upper() None => "?" } apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph }) exec.set(a.id, a.command) } let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 } let sh : DesktopShell = { apps, exec, display, widgets: [], next_slot: 1, catalog: [], catalog_named: false, booted: false, persist: false, tokens: conv_theme(@scene.ThemeTokens::moon_night()), screen_w: 0, desk_set: false, desk_x: 0, desk_y: 0, desk_drag: false, desk_off_x: 0, desk_off_y: 0, screen_h: 0, panel_h: 40, windows: [], layout_sel: 0, layout_names: ["Tiling (BSP)", "Monocle", "Floating"], actions: [], apps_dirty: true, sampler: SysSampler::new(), win_list: [], picker: None, notice: "", notice_frames: 0, notice_start: 0, menu_open: false, menu_rect: zero, menu_title: "", menu_rows: [], menu_hover: -1, menu_anchor_x: 0, menu_slot: "", drag_slot: "", hover_slot: "", drag_x0: 0, drag_y0: 0, drag_active: false, inspect_on: false, hover_id: "", hover_x: 0, inspect_scroll: 0, hover_y: 0, panel_rect: zero, comps: [], wit_cache: {}, recents: load_recents(), } sh.order_apps() sh } ///| Tell the shell the theme and output size it will first be drawn with (modules are loaded /// against these); the panel itself is loaded on first use. pub fn DesktopShell::set_output(self : DesktopShell, theme : @scene.ThemeTokens, w : Int, h : Int) -> Unit { self.tokens = conv_theme(theme) self.screen_w = w self.screen_h = h self.panel_h = theme.panel_height } ///| Default launcher entries, in order: each group is matched against app ids (first hit wins). let default_groups : Array[Array[String]] = [ ["foot", "konsole", "terminal", "kitty", "alacritty"], ["dolphin", "nautilus", "thunar", "files"], ["firefox", "chromium", "chrome", "browser"], ["kate", "gedit", "texteditor", "code", "editor"], ["systemsettings", "settings", "control"], ] ///| let max_recents : Int = 8 ///| fn recents_path() -> String { let c = @sys.getenv("XDG_CACHE_HOME") (if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.cache" }) + "/moon-plasma-recent" } ///| fn load_recents() -> Array[String] { let out : Array[String] = [] let text = @utf8.decode_lossy(@sys.read_file_bytes(recents_path())) for l in text.split("\n") { let id = l.trim(chars=" \r").to_string() if id.length() > 0 { out.push(id) } } out } ///| Reorder the launcher: defaults first, then recents (newest first), then the rest A-Z. fn DesktopShell::order_apps(self : DesktopShell) -> Unit { let by_id : Map[String, @types.AppEntry] = {} for a in self.apps { by_id.set(a.id, a) } let out : Array[@types.AppEntry] = [] let seen : Map[String, Bool] = {} fn take(a : @types.AppEntry, out : Array[@types.AppEntry], seen : Map[String, Bool]) -> Unit { if !seen.contains(a.id) { seen.set(a.id, true) out.push(a) } } for g in default_groups { let mut found = false for key in g { if !found { for a in self.apps { if !found && a.id.to_lower().contains(key) { take(a, out, seen) found = true } } } } } for id in self.recents { match by_id.get(id) { Some(a) => take(a, out, seen) None => () } } for a in self.apps { take(a, out, seen) // already A-Z from the scan } self.apps.clear() for a in out { self.apps.push(a) } } ///| Remember `id` as the most recent launch and persist the list. fn DesktopShell::note_recent(self : DesktopShell, id : String) -> Unit { let next : Array[String] = [id] for r in self.recents { if r != id && next.length() < max_recents { next.push(r) } } self.recents.clear() for r in next { self.recents.push(r) } let sb = StringBuilder::new() for r in self.recents { sb.write_string(r + "\n") } ignore(@sys.write_file_bytes(recents_path(), @utf8.encode(sb.to_string()))) self.order_apps() } ///| fn inside(r : @scene.Rect, x : Int, y : Int) -> Bool { r.w > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h } ///| The launcher module (the Super key opens it). let launcher_module : String = "launcher" ///| True while any panel popup or the right-click menu is open (it then owns keyboard input). pub fn DesktopShell::popup_open(self : DesktopShell) -> Bool { self.menu_open || self.open_popup_widget() is Some(_) } ///| The widget whose popup is open, if any. fn DesktopShell::open_popup_widget(self : DesktopShell) -> Widget? { for w in self.widgets { if w.popup_rect.w > 0 { return Some(w) } } None } ///| fn DesktopShell::widget_at(self : DesktopShell, x : Int, y : Int) -> Widget? { for w in self.widgets { if inside(w.rect, x, y) { return Some(w) } } None } ///| fn DesktopShell::widget_by_slot(self : DesktopShell, slot : String) -> Widget? { for w in self.widgets { if w.slot == slot { return Some(w) } } None } ///| True when (x, y) is inside some widget's open popup. fn DesktopShell::popup_covers(self : DesktopShell, x : Int, y : Int) -> Bool { self.popup_at(x, y) is Some(_) } ///| Widget whose popup contains (x, y). fn DesktopShell::popup_at(self : DesktopShell, x : Int, y : Int) -> Widget? { for w in self.widgets { if inside(w.popup_rect, x, y) { return Some(w) } } None } ///| Does the widget import host interface `cap`? fn Widget::has_cap(self : Widget, cap : String) -> Bool { self.caps.contains(cap) } ///| Hand an event to a module, then carry out whatever it asked of the host. fn DesktopShell::deliver(self : DesktopShell, w : Widget, popup : Bool, ev : @wasm.PlasmoidEvent) -> Bool { self.publish_host_data() let changed = w.pl.on_event(popup, ev) self.process_requests() // The module may have unloaded itself (or been replaced) while handling the event. if self.widget_by_slot(w.slot) is Some(_) { self.refresh_popup(w) } changed } ///| Close every popup except `keep`'s (a press elsewhere dismisses them). fn DesktopShell::dismiss_popups(self : DesktopShell, keep : String) -> Unit { for w in self.widgets.copy() { if w.slot != keep && w.popup_rect.w > 0 { ignore(self.deliver(w, false, FocusLost)) } } } ///| Open the launcher module's popup, or close it if already open (the Super-key tap). pub fn DesktopShell::toggle_launcher(self : DesktopShell) -> Unit { self.ensure_booted() self.menu_open = false for w in self.widgets { if w.module_id == launcher_module { if w.popup_rect.w > 0 { ignore(self.deliver(w, false, FocusLost)) } else { self.dismiss_popups(w.slot) ignore(self.deliver(w, false, PointerDown(0, 0))) } return } } } ///| True if (x, y) is over the panel, an open popup or the menu (so windows don't see it). pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool { inside(self.panel_rect, x, y) || (self.menu_open && inside(self.menu_rect, x, y)) || self.popup_at(x, y) is Some(_) } ///| wp_cursor_shape_v1 value for the shell UI under (x, y): hand over panel modules, grabbing /// while one is dragged, 0 when (x, y) is not shell UI. pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt { if self.inspect_on { // help cursor everywhere while inspecting; hand over the Interface Explorer toggle itself return match self.widget_at(x, y) { Some(w) if w.has_cap("inspector") => 4U _ => 3U } } if self.desk_drag { 17U } else if self.drag_active { 17U // grabbing } else if self.menu_open && inside(self.menu_rect, x, y) { if self.menu_hover >= 0 { 4U } else { 1U } } else if self.popup_at(x, y) is Some(_) { 1U } else if self.widget_at(x, y) is Some(_) { 4U } else { 0U } } ///| Pointer press at (x, y). Returns true when the shell consumed it. pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool { self.ensure_booted() if self.menu_open { // A press outside the menu dismisses it and goes through. return self.menu_pointer_down(x, y) } if self.inspect_on { // Inspecting: clicks reach only modules that hold the `inspector` capability (the toggle). match self.widget_at(x, y) { Some(w) if w.has_cap("inspector") => ignore(self.deliver(w, false, PointerDown(x - w.rect.x, y - w.rect.y))) _ => () } return true } match self.popup_at(x, y) { Some(w) => { ignore(self.deliver(w, true, PointerDown(x - w.popup_rect.x, y - w.popup_rect.y))) return true } None => () } match self.widget_at(x, y) { Some(w) => { // A click (delivered on release) or the start of a drag that reorders the panel. // The Interface Explorer toggle leaves open popups alone. if !w.has_cap("inspector") { self.dismiss_popups(w.slot) } self.drag_slot = w.slot self.drag_x0 = x self.drag_y0 = y self.drag_active = false true } None => { // Click elsewhere: dismiss any popup and let the click through. self.dismiss_popups("") inside(self.panel_rect, x, y) } } } ///| Move the dragged widget in panel order to where the pointer is: it lands after every /// other widget whose centre is left of `x`. fn DesktopShell::reorder_dragged(self : DesktopShell, x : Int) -> Unit { match self.widget_by_slot(self.drag_slot) { None => () Some(dragged) => { let others = self.widgets.filter(w => w.slot != self.drag_slot) let mut idx = 0 for w in others { if w.rect.x + w.rect.w / 2 < x { idx = idx + 1 } } others.insert(idx, dragged) self.widgets.clear() for w in others { self.widgets.push(w) } } } } ///| Pointer release: ends a widget drag, or clicks the widget if it never moved. True when a press was pending. pub fn DesktopShell::pointer_up(self : DesktopShell) -> Bool { if self.desk_drag { self.desk_drag = false return true } let slot = self.drag_slot let was_drag = self.drag_active self.drag_slot = "" self.drag_active = false if slot == "" { return false } if was_drag { self.save_panel_config() } else { match self.widget_by_slot(slot) { Some(w) => ignore(self.deliver(w, false, PointerDown(self.drag_x0 - w.rect.x, self.drag_y0 - w.rect.y))) None => () } } true } ///| Pointer motion; returns true when over a popup or the menu (so windows don't see it). pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool { if self.desk_drag { self.desk_set = true self.desk_x = x - self.desk_off_x self.desk_y = y - self.desk_off_y let (cx, cy) = self.desk_pos() self.desk_x = cx self.desk_y = cy return true } if self.drag_slot != "" { if !self.drag_active && (x - self.drag_x0 > 4 || self.drag_x0 - x > 4) { self.drag_active = true } if self.drag_active { self.reorder_dragged(x) } return true } if self.menu_open { return self.menu_pointer_move(x, y) } // Hover: the widget under the pointer sees moves, the one it left sees a leave. let hovered = match self.widget_at(x, y) { Some(w) if !self.popup_covers(x, y) => Some(w) _ => None } let hslot = match hovered { Some(w) => w.slot None => "" } if hslot != self.hover_slot { match self.widget_by_slot(self.hover_slot) { Some(old) => ignore(self.deliver(old, false, PointerLeave)) None => () } self.hover_slot = hslot } match hovered { Some(w) => ignore(self.deliver(w, false, PointerMove(x - w.rect.x, y - w.rect.y))) None => () } let mut over = false for w in self.widgets.copy() { if w.popup_rect.w > 0 { if inside(w.popup_rect, x, y) { w.popup_hot = true over = true ignore(self.deliver(w, true, PointerMove(x - w.popup_rect.x, y - w.popup_rect.y))) } else if w.popup_hot { w.popup_hot = false ignore(self.deliver(w, true, PointerLeave)) } } } over } ///| Key name as used by the plasmoid contract ("Escape", "Backspace", "Enter" or one character). pub fn DesktopShell::key_down(self : DesktopShell, name : String) -> Unit { if self.menu_open { if name == "Escape" { self.menu_open = false } return } match self.open_popup_widget() { Some(w) => ignore(self.deliver(w, true, KeyDown(name))) None => () } } ///| Things panel modules asked the compositor to do since the last call (focus a window, switch layout). pub fn DesktopShell::take_actions(self : DesktopShell) -> Array[ShellAction] { let out = self.actions.copy() self.actions.clear() out } ///| Build the (background, panel) render-lists for the current frame. pub fn DesktopShell::render( self : DesktopShell, w : Int, h : Int, theme : @scene.ThemeTokens, ) -> (Array[@scene.DrawOp], Array[@scene.DrawOp]) { let tokens = conv_theme(theme) self.tokens = tokens self.screen_w = w self.screen_h = h self.panel_h = theme.panel_height self.ensure_booted() self.poll_picker() self.publish_host_data() // Machine state and the rich window list only matter to modules that import them. if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) { self.sampler.refresh() @wasm.set_windows(self.win_list) } let bg : Array[@scene.DrawOp] = [] translate(@libshell.render_background(@ui.size(w, h), tokens), 0, 0, bg) let (dx, dy) = self.desk_pos() render_desktop_widget(dx, dy, tokens, now(), bg) let panel_ops : Array[@scene.DrawOp] = [] self.comps.clear() self.panel_rect = { x: 0, y: 0, w: 0, h: 0 } match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), self.panel_slots()) { Err(_) => () Ok(pl) => { self.panel_rect = { x: pl.x, y: pl.y, w: pl.w, h: pl.h } translate(@libshell.render_panel(@ui.rect(pl.x, pl.y, pl.w, pl.h), tokens), 0, 0, panel_ops) for i = 0; i < pl.placements.length() && i < self.widgets.length(); i = i + 1 { let p = pl.placements[i] let wd = self.widgets[i] translate(wd.pl.render(p.w, p.h, tokens), p.x, p.y, panel_ops) wd.rect = { x: p.x, y: p.y, w: p.w, h: p.h } self.comps.push((wd.slot, wd.rect)) } } } // Popups sit above the panel, left-aligned with their widget. for wd in self.widgets { self.refresh_popup(wd) if wd.popup_rect.w > 0 { translate(wd.popup_ops, wd.popup_rect.x, wd.popup_rect.y, panel_ops) } } if self.menu_open { self.render_menu(w, tokens, panel_ops) } else { self.menu_rect = { x: 0, y: 0, w: 0, h: 0 } } if self.notice_frames > 0 { if (wall_secs() - self.notice_start + 86400) % 86400 >= 4 { self.notice_frames = 0 } } if self.notice_frames > 0 { let nw = self.notice.length() * 7 + 24 translate( [ @ui.fill_rect(@ui.rect(0, 0, nw, 28), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()), @ui.stroke_rect(@ui.rect(0, 0, nw, 28), tokens.palette.border, radius=tokens.radius.reinterpret_as_int()), @ui.text(12, 14, self.notice, tokens.font_size.reinterpret_as_int() - 3, tokens.palette.foreground), ], w - nw - 12, self.panel_rect.y - 40, panel_ops, ) } if self.inspect_on { self.render_inspector(w, h, tokens, panel_ops) } (bg, panel_ops) }