Files
chandra/compositor/shell/shell.mbt
T
nandiandClaude Opus 5.5 68baf1a467
CI / test (push) Failing after 49s
Launcher: pick up web apps as they are installed, categories, scrolling
- Read the app catalog again when the Applications menu opens if .desktop files were added or removed (and on Reload); it was only read at login, so a PWA installed during the session was missing from the menu and its search
- List a Chromium browser's web apps in their own category ("Chrome Apps", "Chromium Apps", ...), as Plasma does; don't take one for the default browser
- Category column and a scrollable list (wheel, scrollbar) when the catalog doesn't fit the menu
- Show menu-spec main category names instead of the first Categories= entry; sort apps A-Z (they were sorted shortest name first)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 23:42:10 -08:00

1243 lines
40 KiB
MoonBit

///| 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)
Image(i) => out.push(@scene.DrawOp::Image(rect(i.rect), i.image))
}
}
}
///| 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
/// Maximized (also while minimized: restoring brings it back maximized).
maximized : Bool
}
///| What the window menu of a task-bar pill asks for (`ShellAction::Window`).
pub(all) enum WindowCommand {
/// Ask the app to close the window (xdg_toplevel close; the app may still ask to save).
Close
Minimize
/// Un-minimize and focus.
Restore
/// Maximize, or bring a maximized window back to its size.
ToggleMaximize
} derive(Eq, Debug)
///| Something a panel module asked the compositor to do.
pub(all) enum ShellAction {
SetLayout(Int)
FocusWindow(UInt64)
/// A module (the launcher's Log out) asked to end the session.
Logout
/// The Dark mode setting changed: the compositor swaps the theme (see `dark_mode`).
ThemeChanged
/// The Flat window frames setting changed: the compositor redraws frames in the new style.
WindowStyleChanged
/// The password dialog setting changed: the compositor registers its polkit agent or leaves.
AuthAgentChanged
/// The screenshot module asked for a screenshot or recording (code: see the compositor's
/// screenshot_request).
Screenshot(Int)
/// The settings module's Power tab asked to suspend (0), power off (1) or restart (2) now.
SystemPower(Int)
/// A row of a task-bar pill's right-click menu: do this to that window.
Window(UInt64, WindowCommand)
/// The launcher's Reload reloaded the panel modules: the whole frame needs drawing again.
ModulesReloaded
} 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
/// Popup slide (slide.mbt): when the running slide began (monotonic ms, 0: none), whether it
/// slides in or out, and while sliding out, where the popup was and what it showed.
mut slide_t0 : UInt64
mut slide_in : Bool
mut ghost_rect : @scene.Rect
mut ghost_ops : Array[@types.DrawOp]
}
///| 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
/// A desktop module (it exports `desktop-module`): it fills the desktop, not a panel slot.
/// Known once names are (see `name_catalog`).
mut desktop : Bool
}
///| One row of the right-click menu. `kind`: 0 replace with module `arg` (a path), 1 remove,
/// 2 open System settings, 3 open the module's own settings, 4 set the module's setting `arg` to
/// `value`, 5 a heading or note (not clickable), 6 a window command (`window_cmd`) for the window
/// whose task-bar pill was right-clicked (`window_id`).
pub(all) struct MenuRow {
label : String
kind : Int
arg : String
/// The setting value a kind-4 row sets.
value : String
/// Draw a tick: the value a kind-4 row sets is the current one.
ticked : Bool
/// The window and command of a kind-6 row.
window_id : UInt64
window_cmd : WindowCommand
}
///| A plain menu row (no setting value, no tick).
fn menu_row(label : String, kind : Int, arg? : String = "") -> MenuRow {
{ label, kind, arg, value: "", ticked: false, window_id: 0, window_cmd: Close }
}
///| A window-menu row: `cmd` for window `id`.
fn window_row(label : String, id : UInt64, cmd : WindowCommand) -> MenuRow {
{ label, kind: 6, arg: "", value: "", ticked: false, window_id: id, window_cmd: cmd }
}
///| 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]
/// Lower-cased StartupWMClass -> desktop file id, for apps whose windows' app id differs.
wm_classes : Map[String, String]
/// Desktop file id -> its Icon= value, and the image handle found for each window app id
/// (0: no icon), for the `icons` capability.
icon_names : Map[String, String]
icon_handles : Map[String, UInt]
/// The icons table as last published (app id, handle), so an unchanged table isn't sent again
/// every frame.
mut icons_published : Array[(String, UInt)]
/// Icon base dirs and theme chain (icons.mbt), read on first use.
mut icon_search : IconSearch?
/// 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
/// Kiosk mode (locked): no panel, no panel menus; the desktop module and popups stay.
mut hide_panel : Bool
/// Last floating position and size (x, y, w, h) of each app's window, by app id (persisted).
win_geoms : Map[String, (Int, Int, Int, Int)]
mut tokens : @theme.Tokens
mut screen_w : Int
/// Desktop card position (once moved) and drag state.
/// How many of the background ops are the static wallpaper (the rest is the desktop card).
mut wallpaper_len : Int
/// Which wallpaper is drawn (an index into `@libshell.wallpaper_names`); the wallpaper module sets it.
mut wallpaper_sel : Int
/// The background ops (wallpaper + desktop card) and what they were built from: rebuilt only
/// when that changes (about once a minute), not every frame.
mut bg_cache : Array[@scene.DrawOp]
mut bg_key : BgKey?
/// Session settings (the session settings module flips them; saved in state.edn): reopen the
/// last session's windows at the next start, and remember where floating windows were left.
mut restore_session : Bool
/// What the screenshot module is told (the compositor sets it every frame): bit 0 a
/// recording is running, bit 1 recordings show the pointer.
mut screenshot_state : Int
/// The network service (network.mbt), while a module imports `network`.
mut net : @network.NetService?
mut remember_windows : Bool
/// Chandra's own password dialog answers polkit (run0, pkexec, ...); off: the system's polkit
/// agent does. Saved as state.edn `:auth-agent :system` when off.
mut native_auth_agent : Bool
/// Software or hardware rendering (render_mode.mbt): what was detected at start (or
/// CHANDRA_RENDER, then `render_forced`), why, and the Settings choice when it differs
/// (state.edn `:render`).
mut render_detected : RenderMode
mut render_why : String
mut render_forced : Bool
mut render_choice : RenderMode?
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
mut dark_mode : Bool
/// How window frames look (Flat window frames on: Flatkit's; off: the classic Breeze-like
/// one); saved as `:window-style :breeze` when off. The compositor follows it.
mut window_style : @scene.WindowStyle
/// Power: minutes without input before the login session turns the screen off / suspends
/// (0: never). Saved in state.edn as :power {:screen-off 10 :suspend 0} when not the defaults.
mut screen_off_min : Int
mut suspend_min : Int
mut brightness_pct : Int
/// Keyboard shortcuts (shortcuts.mbt); saved in state.edn as :shortcuts when not the defaults.
shortcuts : Shortcuts
/// The shortcut waiting for its new combo from the Shortcuts tab (-1: none).
mut shortcut_capture : Int
/// Default apps (default_apps.mbt): where mimeapps.list and the .desktop files are, the
/// installed apps (scanned on first use and on the Apps tab's refresh) and each category's
/// choices, and whether they still need publishing.
mut xdg_dirs : XdgDirs
mut handler_apps : Map[String, HandlerApp]?
mut default_apps : Array[CategoryChoices]
mut default_apps_dirty : Bool
/// Face unlock (face.mbt): what `chandra-face` said, for Settings > Session.
face : FaceUnlock
/// The game library (gamelib.mbt): gamerig's library daemon, for the `game-library` capability.
gamelib : GameLib
/// The terminal chosen in the Apps tab (desktop id; "" for none), saved as state.edn :terminal.
mut terminal : String
/// Desktop ids of Terminal=true apps, started inside the terminal.
terminal_apps : Map[String, Bool]
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
/// The battery for modules with the `battery` capability (battery.mbt).
battery : BatteryMeter
mut win_list : Array[@wasm.WindowEntry]
mut notice : String
mut notice_frames : Int
mut notice_start : Int
/// A multi-line error notice (`say_error`): its lines, shown for `notice_secs`.
mut notice_lines : Array[String]
mut notice_secs : Int
/// Apps started and still watched for a failed launch (launch.mbt).
launches : Array[LaunchWatch]
/// 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
/// Each module's own settings (`module-config`), by module id, as saved in state.edn
/// `:module-config`; read on first use.
module_cfg : Map[String, Map[String, String]]
mut module_cfg_read : Bool
/// 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
/// Where the pointer last was (the dock's hover label follows it).
mut ptr_x : Int
mut ptr_y : Int
// 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]
/// The launcher module's state as the shell follows it (dock.mbt `follow_launcher`): what its
/// popup lists, for the right-click "Pin to dock" menu.
launcher_state : @launcher.State
/// What fills the desktop (desktop_module.mbt): "wallpaper", "clock-card" or a desktop
/// module's id (or path); saved in state.edn as `:desktop`.
mut desk_choice : String
mut desk_choice_read : Bool
/// The loaded desktop module (slot "desktop"), its backdrop (0 over the wallpaper, 1 instead of
/// it) and when it was loaded (its clock's zero, monotonic ms).
mut desk_mod : Widget?
mut desk_backdrop : Int
mut desk_t0 : UInt64
/// When its next animation frame is due (monotonic ms, 0: none asked for).
mut desk_next : UInt64
/// Its last drawing (desktop coordinates), a counter bumped each time it is redrawn, whether it
/// must be redrawn, and the size and theme it was drawn for.
mut desk_ops : Array[@scene.DrawOp]
mut desk_gen : Int
mut desk_dirty : Bool
mut desk_drawn : (Int, Int, @scene.ThemeTokens)?
/// Input: the desktop has the keyboard (clicked, no window focused since), the pointer is over
/// it, a press on it is held (moves and the release go to it even over a window).
mut desk_focus : Bool
mut desk_hover : Bool
mut desk_grab : Bool
/// A window covers the whole desktop: animation frames pause (the compositor sets it).
mut desk_covered : Bool
/// The module's hidden settings (empty label) as last saved, to save only changes.
desk_saved : Map[String, String]
/// The menu's top edge when it opens at the pointer (the desktop menu); -1 above the panel.
mut menu_anchor_y : Int
/// Extra bottom inset reserved for panel popups (e.g. an open on-screen keyboard).
mut popup_bottom_inset : Int
/// The .desktop files there were when the catalog was read (`refresh_apps`).
mut app_files : Array[String]
/// Touchpad scrolling over the launcher's popup not yet worth a row, in pixels.
mut popup_scroll : Double
}
///|
pub fn DesktopShell::new(display : String) -> DesktopShell {
let apps : Array[@types.AppEntry] = []
let exec : Map[String, String] = {}
let wm_classes : Map[String, String] = {}
let icon_names : Map[String, String] = {}
let terminal_apps : Map[String, Bool] = {}
let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 }
let sh : DesktopShell = {
apps,
exec,
wm_classes,
icon_names,
icon_handles: {},
icons_published: [],
icon_search: None,
display,
widgets: [],
next_slot: 1,
catalog: [],
catalog_named: false,
booted: false,
persist: false,
hide_panel: false,
win_geoms: {},
tokens: conv_theme(@scene.ThemeTokens::moon_night()),
screen_w: 0,
wallpaper_len: 0,
wallpaper_sel: 0,
bg_cache: [],
bg_key: None,
restore_session: true,
screenshot_state: 2,
net: None,
remember_windows: true,
native_auth_agent: true,
render_detected: Hardware,
render_why: "not detected",
render_forced: false,
render_choice: None,
dark_mode: true,
window_style: @scene.WindowStyle::Flat,
screen_off_min: default_screen_off_min,
suspend_min: default_suspend_min,
brightness_pct: -1,
shortcuts: Shortcuts::defaults(),
shortcut_capture: -1,
xdg_dirs: XdgDirs::from_env(),
handler_apps: None,
default_apps: [],
default_apps_dirty: true,
face: FaceUnlock::new(),
gamelib: GameLib::new(),
terminal: "",
terminal_apps,
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(),
battery: BatteryMeter::new(),
win_list: [],
picker: None,
notice: "",
notice_frames: 0,
notice_start: 0,
notice_lines: [],
notice_secs: 4,
launches: [],
menu_open: false,
menu_rect: zero,
menu_title: "",
menu_rows: [],
menu_hover: -1,
menu_anchor_x: 0,
menu_slot: "",
module_cfg: {},
module_cfg_read: false,
drag_slot: "",
hover_slot: "",
drag_x0: 0,
drag_y0: 0,
drag_active: false,
ptr_x: -1,
ptr_y: -1,
inspect_on: false,
hover_id: "",
hover_x: 0,
inspect_scroll: 0,
hover_y: 0,
panel_rect: zero,
comps: [],
wit_cache: {},
recents: [],
launcher_state: @launcher.State::new(),
desk_choice: default_desktop_id(),
desk_choice_read: false,
desk_mod: None,
desk_backdrop: 0,
desk_t0: 0,
desk_next: 0,
desk_ops: [],
desk_gen: 0,
desk_dirty: false,
desk_drawn: None,
desk_focus: false,
desk_hover: false,
desk_grab: false,
desk_covered: false,
desk_saved: {},
menu_anchor_y: -1,
popup_bottom_inset: 0,
app_files: [],
popup_scroll: 0.0,
}
sh.load_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" }) +
"/chandra-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 {
// A web app's id holds its browser's name (chrome-<app id>-Default): not the browser.
let web = web_app_category(self.exec.get(a.id).unwrap_or("")) is Some(_)
if !found && !web && 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)
}
self.save_state()
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
}
///| The module id of the currently open panel popup, or "" when none (or only the menu is open).
pub fn DesktopShell::open_popup_module_id(self : DesktopShell) -> String {
match self.open_popup_widget() {
Some(w) => w.module_id
None => ""
}
}
///| The screen rectangle of the currently open panel popup, if any.
pub fn DesktopShell::open_popup_rect(self : DesktopShell) -> @scene.Rect? {
match self.open_popup_widget() {
Some(w) if w.popup_rect.w > 0 => Some(w.popup_rect)
_ => None
}
}
///| Reserve extra room at the bottom for popups (e.g. an open on-screen keyboard) and
/// reposition any open popup above it.
pub fn DesktopShell::set_popup_bottom_inset(self : DesktopShell, inset : Int) -> Unit {
let v = if inset > 0 { inset } else { 0 }
if self.popup_bottom_inset == v {
return
}
self.popup_bottom_inset = v
for w in self.widgets.copy() {
if w.popup_rect.w > 0 {
self.refresh_popup(w)
}
}
}
///|
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? {
if slot == desktop_slot {
return self.desk_mod
}
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 {
if w.module_id == launcher_module && !popup && w.popup_rect.w == 0 && ev is PointerDown(_, _) {
self.refresh_apps() // the menu is about to open
}
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)
if w.module_id == launcher_module {
self.follow_launcher(w, popup, ev)
}
}
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
}
}
}
///| Where the launcher's popup is while it is open (the overview lays windows out beside it).
pub fn DesktopShell::launcher_rect(self : DesktopShell) -> @scene.Rect? {
for w in self.widgets {
if w.module_id == launcher_module && w.popup_rect.w > 0 {
return Some(w.popup_rect)
}
}
None
}
///| True while the launcher's popup is open.
pub fn DesktopShell::launcher_open(self : DesktopShell) -> Bool {
self.launcher_rect() is Some(_)
}
///| Wheel or touchpad over an open panel popup: `notches` wheel clicks, or (0 of those) `px`
/// pixels; + is down. The launcher's list scrolls by rows. False when (x, y) is on no popup.
pub fn DesktopShell::scroll_popup(self : DesktopShell, x : Int, y : Int, px : Double, notches : Int) -> Bool {
let w = match self.popup_at(x, y) {
Some(w) => w
None => return false
}
if w.module_id != launcher_module || (self.menu_open && inside(self.menu_rect, x, y)) {
return true
}
let mut rows = notches * 3
if notches == 0 {
self.popup_scroll = self.popup_scroll + px
rows = (self.popup_scroll / 15.0).to_int()
self.popup_scroll = self.popup_scroll - rows.to_double() * 15.0
}
let key = if rows < 0 { "ScrollUp" } else { "ScrollDown" }
let n = if rows < 0 { -rows } else { rows }
for _ in 0..<n {
ignore(self.deliver(w, true, KeyDown(key)))
}
if n > 0 {
// The rows moved under a still pointer.
ignore(self.deliver(w, true, PointerMove(x - w.popup_rect.x, y - w.popup_rect.y)))
}
true
}
///| Close the launcher's popup if it is open.
pub fn DesktopShell::close_launcher(self : DesktopShell) -> Unit {
for w in self.widgets {
if w.module_id == launcher_module && w.popup_rect.w > 0 {
ignore(self.deliver(w, false, FocusLost))
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 && self.menu_rows[self.menu_hover].kind != 5 { 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
self.save_state() // remember where the card was dropped
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) if self.dock_click(w) => ()
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 {
self.ptr_x = x
self.ptr_y = y
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
}
///| What the background (wallpaper + desktop card) is drawn from.
#derive(Eq)
struct BgKey {
w : Int
h : Int
theme : @scene.ThemeTokens
wallpaper : Int
x : Int
y : Int
date : (UInt, Byte, Byte, Byte)
hour : Byte
minute : Byte
/// The desktop module's drawing (`desk_gen`), -1 with the clock card, -2 with the wallpaper
/// alone.
desk : Int
}
///| The wallpaper and the desktop card. Building them costs most of an idle frame (the card's
/// moon disc alone is ~1800 ops), so the last ops are kept, the same array, until something they
/// are drawn from changes: the card shows minutes, so that is about once a minute.
fn DesktopShell::background(
self : DesktopShell,
w : Int,
h : Int,
theme : @scene.ThemeTokens,
tokens : @theme.Tokens,
) -> Array[@scene.DrawOp] {
let card = self.desk_choice == clock_card_desktop && self.desk_mod is None
let key : BgKey = if card {
let at = now()
let (dx, dy) = self.desk_pos()
{
w,
h,
theme,
wallpaper: self.wallpaper_sel,
x: dx,
y: dy,
date: (at.year, at.month, at.day, at.weekday),
hour: at.hour,
minute: at.minute,
desk: -1,
}
} else {
// The wallpaper alone, or under / instead of the desktop module: nothing follows the clock.
self.desktop_render(w, h, theme, tokens)
let replaced = self.desk_mod is Some(_) && self.desk_backdrop == 1
{
w,
h,
theme,
wallpaper: if replaced { -1 } else { self.wallpaper_sel },
x: 0,
y: 0,
date: (0, b'\x00', b'\x00', b'\x00'),
hour: b'\x00',
minute: b'\x00',
desk: if self.desk_mod is Some(_) { self.desk_gen } else { -2 },
}
}
if self.bg_key == Some(key) {
return self.bg_cache
}
let bg : Array[@scene.DrawOp] = []
if key.wallpaper >= 0 {
translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg)
}
self.wallpaper_len = bg.length()
if card {
let (dx, dy) = self.desk_pos()
render_desktop_widget(dx, dy, tokens, now(), bg)
} else if self.desk_mod is Some(_) {
bg.append(self.desk_ops)
}
self.bg_cache = bg
self.bg_key = Some(key)
bg
}
///| 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 only matters to modules that import it.
if self.any_cap("system") {
self.sampler.refresh() // reads /proc once a second
}
self.settle_dock_pins()
if self.any_cap("icons") {
self.publish_icons()
}
let bg = self.background(w, h, theme, tokens)
let panel_ops : Array[@scene.DrawOp] = []
self.comps.clear()
self.panel_rect = { x: 0, y: 0, w: 0, h: 0 }
let layout = if self.hide_panel {
Err("kiosk: no panel")
} else {
@panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), self.panel_slots())
}
match layout {
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; some slide in and out.
for wd in self.widgets {
self.refresh_popup(wd)
self.draw_popup(wd, panel_ops)
}
if !self.menu_open && !self.drag_active {
self.render_dock_label(tokens, 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 >= self.notice_secs {
self.notice_frames = 0
}
}
if self.notice_frames > 0 && self.notice_lines.length() > 0 {
// An error: its lines in a box above the panel's right end, a red edge on the left.
let rows = notice_rows(self.notice_lines, 110)
let fs = tokens.font_size.reinterpret_as_int() - 3
let lh = fs + 6
let mut longest = 0
for r in rows {
longest = if r.length() > longest { r.length() } else { longest }
}
let nw = longest * 7 + 32
let nw = if nw > w - 24 { w - 24 } else { nw }
let nh = rows.length() * lh + 16
let red = @ui.color(229, 72, 77, 255)
let ops = [
@ui.fill_rect(@ui.rect(0, 0, nw, nh), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()),
@ui.stroke_rect(@ui.rect(0, 0, nw, nh), red, radius=tokens.radius.reinterpret_as_int()),
@ui.fill_rect(@ui.rect(0, 0, 4, nh), red),
]
for i, r in rows {
ops.push(
@ui.text(16, 8 + i * lh + lh / 2, r, fs, if i == 0 { red } else { tokens.palette.foreground }),
)
}
translate(ops, w - nw - 12, self.panel_rect.y - nh - 12, panel_ops)
} else 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)
}