Files
chandra/compositor/shell/widgets.mbt
T
Claude 6253371cb3
CI / test (push) Failing after 30s
Dock and task manager are one module: titled window pills, pins, Super+1..9
The panel had a task list and, beside it, a dock showing the same running
apps again. They are now one module, the dock, in the task list's place:

- Pinned apps, then running ones; an app with windows is a pill with its
  window's title (or name and window count) while there is room, an icon
  when the panel is crowded ("Show window titles" in Dock settings).
- Its right-click menu has the task list's window commands (Minimize /
  Restore, Maximize) for a single window, or the app's windows by title.
- It stretches like the task list did; new panels get it instead of
  tasks. A saved panel's "tasks" becomes the dock (one dock, where the
  task list was); pins are the dock's own setting, so they carry over.
- An empty dock shows a "+ Add apps" tile that opens the Applications
  menu, where right-clicking an app offers Open and Pin to dock (adding a
  dock to the panel if there is none).
- Super+1 .. Super+9 open the dock's first nine apps like a click
  (shortcut "dock-apps", rebindable in Settings > Shortcuts).
- "New window" / "Open" only for apps the catalog can start.

The tasks component, lib/panel's pill geometry and the taskbar-widget
world are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiPCFHRxaJQvwex6ry
2026-11-26 00:08:05 +00:00

1345 lines
44 KiB
MoonBit

///| 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. The dock (pinned and running apps, the task
/// manager) stretches, so what follows it packs right.
let default_panel : Array[String] = [
"launcher", "inspector", "layout", "dock", "moon-disc", "network", "clock-digital", "screenshot",
"session-settings",
]
///| A fresh panel's modules: the defaults, plus the battery before the clock on a machine that
/// has one (a desktop gets no battery module; it can be added from the settings module).
fn fresh_panel(has_battery : Bool) -> Array[String] {
if !has_battery {
return default_panel
}
let out : Array[String] = []
for m in default_panel {
if m == "clock-digital" {
out.push("battery")
}
out.push(m)
}
out
}
///|
test "a fresh panel gets the battery module only on a machine with a battery" {
assert_false(fresh_panel(false).contains("battery"))
let p = fresh_panel(true)
assert_eq(p.search("battery").unwrap() + 1, p.search("clock-digital").unwrap())
}
///| Modules folded into another one: old id -> the module that took over. The old id still
/// works everywhere a module is named (saved panels, load_module), it is just never listed:
/// a stale build/components/clock-digital12.wasm or an old installed copy stays out of the picker.
/// - clock-digital12, the 12-hour clock, is the Digital Clock, which now starts in 12-hour mode.
/// - logout, the Log out button, is the Application Launcher's session row (Reload, Log out,
/// Suspend, Restart, Power off). A saved panel drops it, or gets the launcher in its place when
/// it had none (migrate_panel).
/// - tasks, the Task Manager's window pills, is the dock: pinned and running apps, titled pills
/// when there is room, each window's menu. A saved panel with both keeps one dock, where the
/// task list was (migrate_panel); the dock's pins carry over (they are the dock's own setting).
let retired_modules : Map[String, String] = {
"clock-digital12": "clock-digital",
"logout": "launcher",
"tasks": "dock",
}
///| The id a module goes by now ("clock-digital12" -> "clock-digital").
fn current_module_id(id : String) -> String {
match retired_modules.get(id) {
Some(n) => n
None => id
}
}
///| 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", "dock-widget", ...) a module was built for, read from the
/// `<name>.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) && !retired_modules.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? {
let id = current_module_id(id)
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: self.dock_width(w).unwrap_or(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). The Log out button moved into the launcher the
/// same way: "logout" becomes the launcher when the panel has none, else it is dropped. Other
/// retired modules (clock-digital12) become the module that replaced them; the task list and the
/// dock become one dock, in the task list's place.
fn migrate_panel(entries : Array[String]) -> Array[String] {
let has_settings = entries.contains("session-settings")
let has_launcher = entries.contains("launcher")
// One dock, where the task list was when there was one (it sat in the stretching place).
let dock_at = match entries.search("tasks") {
Some(i) => i
None => entries.search("dock").unwrap_or(-1)
}
let out : Array[String] = []
for i, e in entries {
if (e == "tasks" || e == "dock") && i != dock_at {
continue
}
if e == "wallpaper" || e == "module-manager" {
if !has_settings && !out.contains("session-settings") {
out.push("session-settings")
}
} else if e == "logout" {
if !has_launcher && !out.contains("launcher") {
out.push("launcher")
}
} else {
out.push(current_module_id(e))
}
}
out
}
///|
test "a saved panel's wallpaper button becomes the settings module" {
assert_eq(migrate_panel(["launcher", "wallpaper", "logout"]), ["launcher", "session-settings"])
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"])
}
///|
test "a saved panel's task list and dock become one dock, in the task list's place" {
assert_eq(migrate_panel(["launcher", "tasks", "clock-digital", "dock"]), ["launcher", "dock", "clock-digital"])
assert_eq(migrate_panel(["dock", "launcher", "tasks"]), ["launcher", "dock"])
assert_eq(migrate_panel(["launcher", "dock", "clock-digital"]), ["launcher", "dock", "clock-digital"])
assert_eq(current_module_id("tasks"), "dock")
}
///|
test "a saved panel's 12-hour clock becomes the digital clock" {
assert_eq(migrate_panel(["tasks", "clock-digital12", "logout"]), ["dock", "clock-digital", "launcher"])
assert_eq(current_module_id("clock-digital12"), "clock-digital")
assert_eq(current_module_id("clock-binary"), "clock-binary")
}
///|
test "a saved panel's Log out button folds into the launcher" {
// The launcher's session row has Log out now: the old button is dropped...
assert_eq(migrate_panel(["launcher", "tasks", "session-settings", "logout"]), [
"launcher", "dock", "session-settings",
])
// ...or becomes the launcher on a panel without one, so Log out stays reachable.
assert_eq(migrate_panel(["tasks", "logout"]), ["dock", "launcher"])
assert_eq(migrate_panel(["logout", "launcher"]), ["launcher"])
assert_false(default_panel.contains("logout"))
}
///| 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 saved = self.load_panel_config()
let entries = match saved {
Some(e) => migrate_panel(e)
None => fresh_panel(read_battery().state != 0)
}
match saved {
Some(old) if saved_panel_version() < panel_version => {
// Once, before the modules load so they pick up the moved settings; then the file is
// rewritten with the new names and version (also keeping modules that fail to load).
self.migrate_module_cfg(old)
write_panel_file(entries)
}
// A renamed or folded module (the Log out button, now in the launcher): rewrite the file so
// the old name is gone for good.
Some(old) if old != entries => write_panel_file(entries)
_ => ()
}
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 self.try_load_path(path) {
Ok(w) => Some(w)
Err(e) => {
self.say(e)
None
}
}
}
///| `load_path` without the notice: the widget, or why it could not be loaded.
fn DesktopShell::try_load_path(self : DesktopShell, path : String) -> Result[Widget, String] {
match @wasm.load(path, self.tokens) {
Err(e) => Err("Can't load module: " + e)
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,
slide_t0: 0,
slide_in: false,
ghost_rect: { x: 0, y: 0, w: 0, h: 0 },
ghost_ops: [],
}
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()
Err("No room in the panel for " + pl.name)
} else {
Ok(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
}
}
}
///| Move the module in `slot` `delta` places along the panel (clamped to either end) and save
/// the new order. False when there is no such slot or it is already at that end.
pub fn DesktopShell::move_slot(self : DesktopShell, slot : String, delta : Int) -> 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 mut to = idx + delta
if to < 0 {
to = 0
}
if to > self.widgets.length() - 1 {
to = self.widgets.length() - 1
}
if to == idx {
return false
}
let w = self.widgets.remove(idx)
self.widgets.insert(to, w)
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 {
match self.replace_slot_result(slot, path) {
Ok(_) => true
Err(e) => {
if e != "" {
self.say(e)
}
false
}
}
}
///| `replace_slot` without the notice: the new widget, or why not ("" when there is no `slot`).
/// On failure the old module stays loaded where it was.
fn DesktopShell::replace_slot_result(self : DesktopShell, slot : String, path : String) -> Result[Widget, String] {
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 Err("")
}
let old = self.widgets[idx]
self.widgets.remove(idx) |> ignore
match self.try_load_path(path) {
Err(e) => {
self.widgets.insert(idx, old)
Err(e)
}
Ok(nw) => {
// try_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)
if self.drag_slot == slot {
self.drag_slot = ""
self.drag_active = false
}
old.pl.unload()
self.save_panel_config()
Ok(nw)
}
}
}
///| Reload panel modules from disk (after `just install` or a module rebuild): each
/// loaded module whose module id, file stem, slot or path is `name` (every module when `name` is
/// empty) is loaded again from its path and takes the old instance's place in the panel. Its
/// settings (state.edn `:module-config`) are applied to the new instance as at login. A module
/// that fails to load stays as it was. Returns one line per module ("reloaded w3 clock-digital"
/// or "failed w3 clock-digital: why") and whether all of them reloaded; with no module matching
/// `name`, a single "no module ..." line and false.
pub fn DesktopShell::reload_modules(self : DesktopShell, name : String) -> (Array[String], Bool) {
self.ensure_booted()
self.scan_catalog() // a module installed since login shows up in Settings > Panel
let targets : Array[(String, String, String)] = []
for w in self.widgets {
if name == "" || w.module_id == name || stem(w.path) == name || w.slot == name || w.path == name {
targets.push((w.slot, w.module_id, w.path))
}
}
if targets.length() == 0 {
let msg = if name == "" {
"no modules are loaded"
} else {
"no loaded module named '" + name + "'"
}
return ([msg], false)
}
let lines : Array[String] = []
let mut failed = 0
let mut last_err = ""
for t in targets {
let (slot, id, path) = t
match self.replace_slot_result(slot, path) {
Ok(nw) => lines.push("reloaded " + nw.slot + " " + id)
Err(e) => {
failed = failed + 1
last_err = id + ": " + (if e == "" { "unloaded meanwhile" } else { e })
lines.push("failed " + slot + " " + id + ": " + (if e == "" { "unloaded meanwhile" } else { e }))
}
}
}
if failed == 0 {
self.say(if targets.length() == 1 {
"Reloaded " + targets[0].1
} else {
"Reloaded " + targets.length().to_string() + " modules"
})
} else if failed == 1 {
self.say("Reload failed: " + last_err)
} else {
self.say(
"Reload: " + failed.to_string() + " of " + targets.length().to_string() + " modules failed (chandra-ctl reload shows why)",
)
}
(lines, failed == 0)
}
///| The loaded modules in panel order: (slot, module id, path).
pub fn DesktopShell::loaded_modules(self : DesktopShell) -> Array[(String, String, String)] {
self.ensure_booted()
self.widgets.map(w => (w.slot, w.module_id, w.path))
}
///| 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()
let id = current_module_id(id)
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 }
}
}
///| The text drawn in `slot`'s open popup, with each line's popup-local origin, in drawing
/// order (empty when the popup is closed). Lets tests find a row without knowing the layout.
pub fn DesktopShell::slot_popup_texts(self : DesktopShell, slot : String) -> Array[(String, Int, Int)] {
let out = []
match self.widget_by_slot(slot) {
Some(w) =>
for op in w.popup_ops {
match op {
Text(t) => out.push((t.text, t.origin.x, t.origin.y))
_ => ()
}
}
None => ()
}
out
}
///| 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("shortcuts")) {
self.publish_shortcuts()
}
if self.widgets.iter().any(w => w.has_cap("default-apps")) {
self.publish_default_apps()
}
if self.widgets.iter().any(w => w.has_cap("screenshot")) {
@wasm.publish_screenshot(self.screenshot_state)
}
if self.widgets.iter().any(w => w.has_cap("battery")) {
let b = self.battery.refresh()
@wasm.publish_battery(b.percent, b.state, b.secs_left)
}
self.publish_network()
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()
}
///| Start the catalog app `id` (a desktop file id) and remember it as the latest launch.
fn DesktopShell::launch_catalog_app(self : DesktopShell, id : String) -> Unit {
match self.command_for(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)
}
}
///| 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)) => self.launch_catalog_app(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)
// The launcher's Reload: every panel module again from disk, in place.
Some(ReloadSession) => {
ignore(self.reload_modules(""))
self.actions.push(ModulesReloaded)
}
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(Shortcut(code)) => self.shortcut_request(code)
Some(DefaultApp(code)) => self.default_app_request(code)
Some(PowerAction(a)) => if a >= 0 && a <= 2 { self.actions.push(SystemPower(a)) }
Some(Network(code, ssid, password)) => self.network_request(code, ssid, password)
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(MoveInstance(slot, delta)) => ignore(self.move_slot(slot, delta))
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
}
let was_open = w.popup_rect.w > 0
let old_rect = w.popup_rect
let old_ops = w.popup_ops
match w.pl.popup() {
None => {
if was_open {
self.slide_out(w, old_rect, old_ops)
}
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
if !was_open {
self.slide_in(w)
}
}
}
}
///| 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
/// The keyboard shortcuts: rebind, reset.
Shortcuts
/// Default apps: browser, email, file manager, terminal, editor, viewers and players.
Apps
} 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-6 pick its tabs.
let key = match tab {
Session => "1"
Desktop => "2"
Panel => "3"
Power => "4"
Shortcuts => "5"
Apps => "6"
}
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 an app in the open Applications menu its Open / Pin to dock menu; on an app in
/// the dock its menu (dock.mbt); 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
// An app in the open Applications menu: Open, Pin to dock. The menu stays open behind it.
match self.launcher_app_at(x, y) {
Some(app) => {
self.open_app_menu(app, x)
return true
}
None => ()
}
self.dismiss_popups("")
match self.widget_at(x, y) {
Some(w) if self.dock_item_at(w, x, y) is Some((items, i)) => {
self.open_dock_menu(w, items, i, x)
true
}
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.label.length() == 0 {
// Kept by the module (e.g. the dock's pinned apps) but not a menu choice.
continue
}
if it.choices.length() == 0 {
let on = it.value == "on"
rows.push({ ..menu_row(it.label, 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({ ..menu_row(c, 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)
6 => self.actions.push(Window(row.window_id, row.window_cmd))
7 | 8 | 9 | 10 => self.dock_menu_choice(slot, row)
// 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"] :version 2}
/// (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
}
write_panel_file(self.widgets.map(w => w.module_id))
}
///| panel.edn's format version (`:version`; files without one are 1). 2: written after the
/// 12-hour clock (clock-digital12) became part of the Digital Clock, whose default went from
/// 24-hour to 12-hour; an older file gets its clock settings moved over once (migrate_module_cfg).
let panel_version : Int = 2
///|
fn write_panel_file(names : Array[String]) -> Unit {
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 n in names {
if !first {
sb.write_string("\n ")
}
first = false
sb.write_string("\"" + n + "\"")
}
sb.write_string("]\n :version " + panel_version.to_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 `:version` of the saved panel.edn (1 when it has none).
fn saved_panel_version() -> Int {
let text = @utf8.decode_lossy(read_config_file("panel.edn"))
panel_text_version(text)
}
///|
fn panel_text_version(text : String) -> Int {
match text.find(":version") {
None => 1
Some(i) => {
let mut v = 0
let mut seen = false
for j = i + 8; j < text.length(); j = j + 1 {
let c = text[j]
if c >= '0' && c <= '9' {
v = v * 10 + (c.to_int() - '0'.to_int())
seen = true
} else if seen || (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != ',') {
break
}
}
if seen { v } else { 1 }
}
}
}
///|
test "panel.edn version" {
assert_eq(panel_text_version("{:panel [\"clock-digital12\"]}"), 1)
assert_eq(panel_text_version("{:panel [\"clock-digital\"]\n :version 2}\n"), 2)
assert_eq(panel_text_version("{:version 12 :panel []}"), 12)
}
///| 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)
}