Files
chandra/compositor/shell/shell.mbt
T
Claude bb7c9b947f
CI / test (push) Failing after 45s
Settings > Apps: choose the default browser, email, files, terminal, editor, viewers and players
- A sixth Settings tab, Apps (key 6, SettingsTab::Apps; the popup is 390 px wide for it): Web
  browser, Email, File manager, Terminal, Text editor, Image viewer, Video player, Music player,
  PDF and documents, Archive manager. Each row shows the current default with its real icon (the
  icon-theme lookup the task manager uses; a letter tile when there is none). Click a row to list
  the installed apps that can take it, click one to make it the default. A chosen app that has
  been uninstalled since is named in red under its row ("gthumb is not installed any more").
- Installed apps come from the .desktop files in the XDG data dirs (and flatpak's exports), with
  MimeType= and Categories= (desktop_entry_keys, now shared with the launcher's parse_desktop).
  A kind lists the shown apps that handle one of its MIME types; the terminal lists
  TerminalEmulator apps; browsers are only offered as browsers.
- Reading follows the mimeapps.list spec: $XDG_CONFIG_HOME/[chandra-]mimeapps.list, then
  $XDG_CONFIG_DIRS (/etc/xdg), then $XDG_DATA_HOME and $XDG_DATA_DIRS applications/; the first
  installed [Default Applications] entry wins, else [Added Associations], else mimeinfo.cache
  (minus [Removed Associations]), else the first installed app that handles the type. A hidden
  (NoDisplay) default still counts and its name is shown.
- Setting writes [Default Applications] in ~/.config/mimeapps.list for each of the kind's MIME
  types the app handles (always the main one: http/https/text/html for browsers, mailto,
  inode/directory, text/plain, image/png..., video/mp4..., audio/mpeg..., application/pdf...,
  application/zip...), as xdg-mime default / xdg-settings do, without running them. Every other
  section, entry, comment and blank line is kept; the app leaves those types' [Removed
  Associations]; a chandra-mimeapps.list that already names one of those types is updated too.
- The terminal has no MIME type: state.edn :terminal "kitty" (desktop id), also written first in
  ~/.config/xdg-terminals.list (xdg-terminal-exec). Terminal=true apps from the launcher (and
  session restore) now start in it (foot -e, kgx/gnome-terminal/ptyxis --, kitty <cmd>, wezterm
  start --) instead of always foot; with no choice: xdg-terminals.list, then foot, then any
  installed terminal. Terminal apps are listed when any terminal emulator is installed, not only
  foot.
- New `default-apps` capability (categories, apps, set-default, refresh): host tables 11 (sss:
  name current missing) and 12 (issii: category id name icon current), request 19 (category *
  1000 + app, -1 rescans) in the wasmer/wasmtime stub, host-wasm and the MoonBit wasmhost
  (chandra:host/plasmoids default-app(s32)). Nothing is scanned until the tab opens (refresh).
- Tests with a temporary XDG tree: categories and current defaults (user file, system file,
  Added Associations, mimeinfo.cache, missing apps, hidden defaults), writing that keeps other
  entries, desktop-specific files, the terminal list and commands, the Apps tab end to end, and
  the :terminal round trip through state.edn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hgywj7RPmFdFhpzGZj
2026-11-25 21:27:30 +00:00

1008 lines
31 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 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
}
///| 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]
/// 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
/// 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
/// Dark mode (the configured theme) or light (Moon Day); saved as `:theme :light` when off.
mut dark_mode : Bool
/// 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
/// 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
/// 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
/// 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
// 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] = {}
let wm_classes : Map[String, String] = {}
let icon_names : Map[String, String] = {}
let terminal_apps : Map[String, Bool] = {}
for a in scan_desktop_apps() {
if a.terminal {
terminal_apps.set(a.id, true)
}
if a.icon.length() > 0 {
icon_names.set(a.id, a.icon)
}
if a.wm_class.length() > 0 {
wm_classes.set(a.wm_class.to_lower(), a.id)
}
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,
wm_classes,
icon_names,
icon_handles: {},
display,
widgets: [],
next_slot: 1,
catalog: [],
catalog_named: false,
booted: false,
persist: 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,
dark_mode: true,
screen_off_min: default_screen_off_min,
suspend_min: default_suspend_min,
shortcuts: Shortcuts::defaults(),
shortcut_capture: -1,
xdg_dirs: XdgDirs::from_env(),
handler_apps: None,
default_apps: [],
default_apps_dirty: true,
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,
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,
inspect_on: false,
hover_id: "",
hover_x: 0,
inspect_scroll: 0,
hover_y: 0,
panel_rect: zero,
comps: [],
wit_cache: {},
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" }) +
"/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 {
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)
}
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
}
///|
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 && 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) => 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 => ()
}
// 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 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 at = now()
let (dx, dy) = self.desk_pos()
let key : BgKey = {
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,
}
if self.bg_key == Some(key) {
return self.bg_cache
}
let bg : Array[@scene.DrawOp] = []
translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg)
self.wallpaper_len = bg.length()
render_desktop_widget(dx, dy, tokens, at, bg)
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 and the rich window list only matter to modules that import them.
if self.widgets.iter().any(w => w.has_cap("system")) {
self.sampler.refresh() // reads /proc once a second
}
if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) {
@wasm.set_windows(self.win_list)
}
if self.widgets.iter().any(w => w.has_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 }
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; 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.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)
}