Wasm panel modules, widget host, merged plasmoid host design, and shell/UI work

Panel and wasm host
- The panel is built from wasm plasmoid modules (compositor/wasm: wasmer-backed host).
  Modules get capabilities by importing host interfaces; the host publishes data tables
  and serves a request queue (launch, focus window, set layout, inspector, load/unload
  modules). New WIT: windows, layout-control, inspector, modules, system.
- Merged two competing host designs: generic tables + requests are the base; the
  `system` snapshot and the id-stable `windows.all/focus` (Desktop Pulse) run on top of it.
- Panel widgets: load a .wasm from a path or file chooser, reorder by dragging,
  right-click replace/remove/add, saved to panel.edn.
- Desktop widget, system sampler (sysinfo), app catalog/humanised names, Interface
  Explorer (inspector), real font rendering (compositor/font, assets/fonts).

Compositor
- Drag the divider between tiled windows; lower tiled rows leave room for the title bar.
- Title-bar buttons, 12-hour clock, truncated titles, task-list/layout menus.
- DRM/KMS session, tcc debug builds (vendored tinycc incl. conftest.c), justfile
  recipes (modules, run, test), pixi.toml.

Known gaps
- The sources for the pulse, tasks, layout, inspector, module-manager, moon-* and
  clock-digital12 modules are not in the tree yet, so `just modules` stops at pulse and
  the host tests that load those modules fail until they land.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-24 23:38:05 -08:00
1 parent 080377fd79
commit 0145981c6a
57 files changed
+11461 -221

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
///| Installed desktop applications, discovered from freedesktop `.desktop` files
/// (XDG data dirs + flatpak exports). Feeds the launcher's search.
///|
priv struct DesktopApp {
id : String
name : String
comment : String
category : String
command : String
}
///| Directories scanned, lowest priority first (later ones override by file name).
fn app_dirs() -> Array[String] {
let home = @sys.getenv("HOME")
let data_home = {
let x = @sys.getenv("XDG_DATA_HOME")
if x.length() > 0 { x } else { home + "/.local/share" }
}
let dirs : Array[String] = []
let xdg = @sys.getenv("XDG_DATA_DIRS")
let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" }
let parts : Array[String] = list.split(":").map(x => x.to_string()).collect()
// XDG_DATA_DIRS is highest priority first; we want lowest first.
for i = parts.length() - 1; i >= 0; i = i - 1 {
if parts[i].length() > 0 {
dirs.push(parts[i] + "/applications")
}
}
dirs.push("/var/lib/flatpak/exports/share/applications")
dirs.push(home + "/.local/share/flatpak/exports/share/applications")
dirs.push(data_home + "/applications")
dirs
}
///| Drop Exec field codes (%f %U ...), keep a literal %%.
fn clean_exec(exec : String) -> String {
let sb = StringBuilder::new()
let chars = exec.to_array()
let mut i = 0
while i < chars.length() {
if chars[i] == '%' && i + 1 < chars.length() {
if chars[i + 1] == '%' {
sb.write_char('%')
}
i = i + 2
} else {
sb.write_char(chars[i])
i = i + 1
}
}
sb.to_string().trim(chars=" ").to_string()
}
///| Parse one .desktop file; None when it should not be listed.
fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp? {
let mut in_entry = false
let mut name = ""
let mut generic = ""
let mut comment = ""
let mut exec = ""
let mut cats = ""
let mut hidden = false
let mut terminal = false
let mut kind = "Application"
for raw in text.split("\n") {
let line = raw.trim(chars=" \r\t").to_string()
if line.length() == 0 || line.has_prefix("#") {
continue
}
if line.has_prefix("[") {
in_entry = line == "[Desktop Entry]"
continue
}
if !in_entry {
continue
}
match line.find("=") {
None => ()
Some(eq) => {
let key = line[:eq].trim(chars=" ").to_string()
let val = line[eq + 1:].trim(chars=" ").to_string()
match key {
"Name" => name = val
"GenericName" => generic = val
"Comment" => comment = val
"Exec" => exec = val
"Categories" => cats = val
"Type" => kind = val
"NoDisplay" | "Hidden" => if val == "true" { hidden = true }
"Terminal" => terminal = val == "true"
_ => ()
}
}
}
}
if hidden || kind != "Application" || name.length() == 0 || exec.length() == 0 {
return None
}
if terminal && !have_terminal {
return None
}
let mut command = clean_exec(exec)
if terminal {
command = "foot -e " + command
}
let category = match cats.split(";").next() {
Some(c) if c.length() > 0 => c.to_string()
_ => "Other"
}
let comment = if comment.length() > 0 { comment } else { generic }
Some({ id, name, comment, category, command })
}
///| Scan every applications dir; later dirs override earlier ones, result sorted by name.
fn scan_desktop_apps() -> Array[DesktopApp] {
let have_terminal = @sys.has_exe("foot")
let by_id : Map[String, DesktopApp] = {}
let removed : Map[String, Bool] = {}
for dir in app_dirs() {
for file in @sys.list_desktop_files(dir) {
let bytes = @sys.read_file_bytes(dir + "/" + file)
let id = file[:file.length() - 8].to_string()
match parse_desktop(id, @utf8.decode_lossy(bytes), have_terminal) {
Some(app) => {
by_id.set(id, app)
removed.remove(id)
}
None => {
by_id.remove(id)
}
}
}
}
let apps : Array[DesktopApp] = []
for _, a in by_id {
apps.push(a)
}
apps.sort_by(fn(a, b) {
let x = a.name.to_lower()
let y = b.name.to_lower()
if x < y { -1 } else if x > y { 1 } else { 0 }
})
apps
}
///|
test "parse_desktop reads a normal entry and strips field codes" {
let t = "[Desktop Entry]\nType=Application\nName=Firefox\nName[de]=Feuerfuchs\nComment=Browse\nExec=firefox %u\nCategories=Network;WebBrowser;\n[Desktop Action x]\nName=Nope\n"
match parse_desktop("firefox", t, true) {
Some(a) => {
assert_eq(a.name, "Firefox")
assert_eq(a.command, "firefox")
assert_eq(a.category, "Network")
assert_eq(a.comment, "Browse")
}
None => fail("expected entry")
}
}
///|
test "parse_desktop hides NoDisplay entries" {
let t = "[Desktop Entry]\nType=Application\nName=X\nExec=x\nNoDisplay=true\n"
assert_true(parse_desktop("x", t, true) is None)
}
+44
View File
@@ -0,0 +1,44 @@
///| Desktop widget: a card on the wallpaper (below all windows, top-right) showing
/// the time, the date and the current moon phase. Built from the same pure lib/*
/// renderers as the panel widgets.
///|
let desktop_widget_w : Int = 260
///|
let desktop_widget_h : Int = 120
///|
fn render_desktop_widget(
screen_w : Int,
tokens : @theme.Tokens,
at : @types.Datetime,
out : Array[@scene.DrawOp],
) -> Unit {
let r = tokens.radius.reinterpret_as_int()
let hour = at.hour.to_int()
let minute = at.minute.to_int()
let time = @timefmt.hhmm12(hour, minute)
let date = @timefmt.weekday_short(at.weekday.to_int()) +
", " +
at.day.to_int().to_string() +
" " +
@timefmt.month_short(at.month.to_int())
let p = @moon.phase(at.year.reinterpret_as_int(), at.month.to_int(), at.day.to_int())
let ops : Array[@types.DrawOp] = [
@ui.fill_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.surface, radius=r),
@ui.stroke_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.border, width=1, radius=r),
@ui.text(18, 38, time, 32, tokens.palette.foreground, bold=true),
@ui.text(18, 74, date, tokens.font_size.reinterpret_as_int(), tokens.palette.foreground),
@ui.text(
18,
98,
@moon.phase_name(p) + " " + @moon.illumination(p).to_string() + "%",
tokens.font_size.reinterpret_as_int() - 2,
tokens.palette.foreground,
),
]
let x0 = screen_w - desktop_widget_w - 24
translate(ops, x0, 24, out)
translate(@moon.render_disc(@ui.size(56, 56), tokens, p), x0 + desktop_widget_w - 56 - 18, 24 + 18, out)
}
+429
View File
@@ -0,0 +1,429 @@
///| Turns WIT source into narrative prose for the Interface Explorer.
///
/// Output is one paragraph per line (the renderer word-wraps), with `""` between
/// paragraphs. A `# ` prefix marks a heading. Terms are wrapped in `**bold**`.
///|
fn trim(s : String) -> String {
s.trim(chars=" \t\r").to_string()
}
///| "window-state" -> "window state"
fn dashes(s : String) -> String {
let sb = StringBuilder::new()
for ch in s {
sb.write_char(if ch == '-' { ' ' } else { ch })
}
sb.to_string()
}
///|
fn pad(n : Int) -> String {
let sb = StringBuilder::new()
for _i = 0; _i < n; _i = _i + 1 {
sb.write_char(' ')
}
sb.to_string()
}
///| Split on `sep` outside <...>, (...) and {...}.
fn split_top(s : String, sep : Char) -> Array[String] {
let out : Array[String] = []
let mut depth = 0
let mut start = 0
for i = 0; i < s.length(); i = i + 1 {
let ch = s[i]
if ch == '<' || ch == '(' || ch == '{' {
depth = depth + 1
} else if ch == '>' || ch == ')' || ch == '}' {
depth = depth - 1
} else if ch == sep.to_int().to_uint16() && depth == 0 {
out.push(trim(s[start:i].to_string()))
start = i + 1
}
}
let last = trim(s[start:].to_string())
if last.length() > 0 {
out.push(last)
}
out
}
///| Index of `ch` in `s`, or -1.
fn index_of(s : String, ch : Char) -> Int {
for i = 0; i < s.length(); i = i + 1 {
if s[i] == ch.to_int().to_uint16() {
return i
}
}
-1
}
///| Index of the last `ch` in `s`, or -1.
fn last_index_of(s : String, ch : Char) -> Int {
for i = s.length() - 1; i >= 0; i = i - 1 {
if s[i] == ch.to_int().to_uint16() {
return i
}
}
-1
}
///| A WIT type in words.
fn ty(t0 : String) -> String {
let t = trim(t0)
match t {
"string" => "text"
"bool" => "yes/no"
"u8" | "u16" | "u32" | "u64" | "s8" | "s16" | "s32" | "s64" | "f32" | "f64" =>
"number"
"char" => "a character"
"_" => "nothing"
_ => {
let lt = index_of(t, '<')
if lt > 0 && t.has_suffix(">") {
let head = t[:lt].to_string()
let args = split_top(t[lt + 1:t.length() - 1].to_string(), ',')
let a0 = if args.length() > 0 { ty(args[0]) } else { "" }
match head {
"list" => "list of " + a0
"option" => "optional " + a0
"borrow" | "own" => a0
"tuple" => "(" + args.map(ty).join(", ") + ")"
"result" => {
let err = if args.length() > 1 { ty(args[1]) } else { "" }
let ok = if a0 == "nothing" { "success" } else { a0 }
if err == "" || err == "nothing" {
ok + ", or failure"
} else {
ok + ", or an error (" + err + ")"
}
}
_ => dashes(t)
}
} else {
dashes(t)
}
}
}
}
///| Strip "///" and one space.
fn doc_text(l : String) -> String {
trim(trim(l)[3:].to_string())
}
///|
fn bold(s : String) -> String {
"**" + s + "**"
}
///| Join with commas and a final "and".
fn and_list(items : Array[String]) -> String {
if items.length() == 0 {
"nothing"
} else if items.length() == 1 {
items[0]
} else {
items[:items.length() - 1].to_array().join(", ") +
" and " +
items[items.length() - 1]
}
}
///| Docs as running text, with a trailing space if non-empty.
fn doc_prose(docs : Array[String]) -> String {
if docs.length() == 0 {
""
} else {
let t = docs.join(" ")
(if t.has_suffix(".") { t } else { t + "." }) + " "
}
}
///| "name: func(a: t, b: t) -> r" as one sentence.
fn func_sentence(entry : String) -> String {
let c = index_of(entry, ':')
let name = dashes(trim(entry[:c].to_string()))
let rest = entry[c + 1:].to_string()
let open = index_of(rest, '(')
let mut depth = 0
let mut close = -1
for i = open; i >= 0 && i < rest.length(); i = i + 1 {
if rest[i] == '(' {
depth = depth + 1
} else if rest[i] == ')' {
depth = depth - 1
if depth == 0 {
close = i
break
}
}
}
let params = if open >= 0 && close > open {
split_top(rest[open + 1:close].to_string(), ',')
} else {
[]
}
let after = if close >= 0 { rest[close + 1:].to_string() } else { "" }
let arrow = after.find("->")
let ret = match arrow {
Some(i) => trim(after[i + 2:].to_string())
None => ""
}
let gives = if ret == "" { "returns nothing" } else { "returns " + ty(ret) }
if params.length() == 0 {
bold(name) + " " + gives + "."
} else {
let ps = params.map(fn(p) {
let pc = index_of(p, ':')
if pc < 0 {
bold(dashes(p))
} else {
bold(dashes(trim(p[:pc].to_string()))) +
" (" +
ty(p[pc + 1:].to_string()) +
")"
}
})
bold(name) + " takes " + and_list(ps) + " and " + gives + "."
}
}
///| One field / case / call as a clause, plus its docs.
fn entry_sentence(kind : String, entry : String, docs : Array[String]) -> String {
let e = trim(entry)
let body = if e.contains(": func(") {
func_sentence(e)
} else if kind == "record" {
let c = index_of(e, ':')
if c >= 0 {
bold(dashes(trim(e[:c].to_string()))) + " is " + ty(e[c + 1:].to_string()) + "."
} else {
bold(dashes(e)) + "."
}
} else if kind == "variant" {
let p = index_of(e, '(')
if p > 0 && e.has_suffix(")") {
bold(dashes(e[:p].to_string())) +
" carries " +
ty(e[p + 1:e.length() - 1].to_string()) +
"."
} else {
bold(dashes(e)) + " carries nothing."
}
} else {
bold(dashes(e)) + "."
}
body + (if docs.length() > 0 { " " + doc_prose(docs).trim(chars=" ").to_string() } else { "" })
}
///| Plain-English rendering of a `interface <name> { ... }` block (as returned by extract_block).
fn humanise_interface(name : String, block : Array[String]) -> Array[String] {
let out : Array[String] = []
let mut i = 0
let head_docs : Array[String] = []
while i < block.length() && trim(block[i]).has_prefix("///") {
head_docs.push(doc_text(block[i]))
i = i + 1
}
out.push("# " + dashes(name) + " (interface)")
if head_docs.length() > 0 {
out.push(doc_prose(head_docs).trim(chars=" ").to_string())
}
i = i + 1 // header line
let mut pending : Array[String] = []
let mut calls_shown = false
let kinds = ["record", "enum", "variant", "flags", "resource"]
while i < block.length() {
let l = trim(block[i])
i = i + 1
if l.has_prefix("///") {
pending.push(doc_text(l))
continue
}
if l == "" || l == "}" {
continue
}
if l.has_prefix("use ") {
pending = []
continue
}
let kw = first_word(l)
if kinds.contains(kw) {
let nm = dashes(first_word(trim(l[kw.length():].to_string())))
let entries : Array[(Array[String], String)] = []
let lb = index_of(l, '{')
let rb = last_index_of(l, '}')
if lb >= 0 && rb > lb {
for e in split_top(l[lb + 1:rb].to_string(), ',') {
entries.push(([], e))
}
} else {
let mut ed : Array[String] = []
while i < block.length() {
let el = trim(block[i])
i = i + 1
if el.has_prefix("}") {
break
}
if el.has_prefix("///") {
ed.push(doc_text(el))
} else if el != "" {
let clean = if el.has_suffix(",") || el.has_suffix(";") {
el[:el.length() - 1].to_string()
} else {
el
}
entries.push((ed, clean))
ed = []
}
}
}
out.push("")
let intro = match kw {
"record" => "A " + bold(nm) + " is a group of fields. "
"enum" => "A " + bold(nm) + " is exactly one of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". "
"variant" => "A " + bold(nm) + " is one of several cases, some carrying data. "
"flags" => "A " + bold(nm) + " is any combination of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". "
_ => "A " + bold(nm) + " is a handle owned by the host. "
}
let sb = StringBuilder::new()
sb.write_string(intro + doc_prose(pending))
if kw == "record" || kw == "variant" {
let parts = entries.map(fn(e) { entry_sentence(kw, e.1, e.0) })
sb.write_string(parts.join(" "))
}
out.push(sb.to_string().trim(chars=" ").to_string())
} else if kw == "type" && l.contains("=") {
let eq = index_of(l, '=')
let nm = dashes(first_word(trim(l[kw.length():].to_string())))
let tgt = trim(l[eq + 1:].to_string())
let tgt = if tgt.has_suffix(";") { tgt[:tgt.length() - 1].to_string() } else { tgt }
out.push("")
out.push(bold(nm) + " is just another name for " + ty(tgt) + ". " + doc_prose(pending).trim(chars=" ").to_string())
} else if l.contains(": func(") {
if !calls_shown {
out.push("")
out.push("What it can do:")
calls_shown = true
out.push("")
}
let clean = if l.has_suffix(";") { l[:l.length() - 1].to_string() } else { l }
out.push(entry_sentence("func", clean, pending))
}
pending = []
}
out
}
///| "moonplasma:desktop/theme@0.1.0;" -> "theme" (raw WIT identifier, dashes kept)
fn ref_name(s : String) -> String {
let mut r = trim(s)
if r.has_suffix(";") {
r = r[:r.length() - 1].to_string()
}
let sl = last_index_of(r, '/')
if sl >= 0 {
r = r[sl + 1:].to_string()
}
let at = index_of(r, '@')
if at >= 0 {
r = r[:at].to_string()
}
r
}
///| "moonplasma:desktop/app-catalog@0.1.0" -> "app catalog"
fn short_ref(s : String) -> String {
dashes(ref_name(s))
}
///| Interfaces a world uses, resolved through `include`: exports first, then imports.
fn world_interfaces(text : String, name : String) -> Array[String] {
let imports : Array[String] = []
let exports : Array[String] = []
collect_world_raw(text, name, imports, exports, 0)
let out : Array[String] = []
for e in exports {
if !out.contains(e) {
out.push(e)
}
}
for i in imports {
if !out.contains(i) {
out.push(i)
}
}
out
}
///|
fn collect_world_raw(
text : String,
name : String,
imports : Array[String],
exports : Array[String],
depth : Int,
) -> Unit {
if depth > 3 {
return
}
for l in extract_block(text, "world", name) {
let t = trim(l)
if t.has_prefix("import ") {
imports.push(ref_name(t[7:].to_string()))
} else if t.has_prefix("export ") {
exports.push(ref_name(t[7:].to_string()))
} else if t.has_prefix("include ") {
collect_world_raw(text, ref_name(t[8:].to_string()), imports, exports, depth + 1)
}
}
}
///|
fn collect_world(
text : String,
name : String,
imports : Array[String],
exports : Array[String],
depth : Int,
) -> Unit {
if depth > 3 {
return
}
for l in extract_block(text, "world", name) {
let t = trim(l)
if t.has_prefix("import ") {
imports.push(short_ref(t[7:].to_string()))
} else if t.has_prefix("export ") {
exports.push(short_ref(t[7:].to_string()))
} else if t.has_prefix("include ") {
collect_world(text, trim(short_ref(t[8:].to_string())).replace_all(old=" ", new="-"), imports, exports, depth + 1)
}
}
}
///| Plain-English rendering of a world: what it provides and what it needs.
fn humanise_world(text : String, name : String) -> Array[String] {
let out : Array[String] = []
let block = extract_block(text, "world", name)
let docs : Array[String] = []
for l in block {
if trim(l).has_prefix("///") {
docs.push(doc_text(l))
} else {
break
}
}
out.push("# " + dashes(name) + " (component)")
if docs.length() > 0 {
out.push(doc_prose(docs).trim(chars=" ").to_string())
}
let imports : Array[String] = []
let exports : Array[String] = []
collect_world(text, name, imports, exports, 0)
out.push("")
out.push("It provides " + and_list(exports.map(bold)) + ", and needs " + and_list(imports.map(bold)) + " from the host.")
out
}
+396
View File
@@ -0,0 +1,396 @@
///| Interface Explorer: a shell tool. Toggle it from the panel's "Interface Explorer" button, then
/// hover any system component (launcher, clock, panel, window title bar, ...)
/// to see the WIT interface that component implements in a dialog.
/// WIT text is read from the repo's `wit/` directory at runtime, so the dialog
/// always shows what is on disk.
///| A system component the inspector knows about.
priv struct Component {
id : String
title : String
note : String
/// (file, world name)
world : (String, String)?
/// (file, interface name) pairs, in display order.
ifaces : Array[(String, String)]
}
///|
let components : Array[Component] = [
{
id: "panel",
title: "Panel",
note: "containment: places widgets and draws the panel frame",
world: Some(("wit/worlds.wit", "panel")),
ifaces: [],
},
{
id: "desktop",
title: "Desktop surface",
note: "wallpaper / desktop containment",
world: Some(("wit/worlds.wit", "shell")),
ifaces: [],
},
{
id: "window-decoration",
title: "Window decoration",
note: "server-side title bar and buttons",
world: Some(("wit/wm/worlds.wit", "decoration-provider")),
ifaces: [],
},
{
id: "window-surface",
title: "Client surface",
note: "a client's committed buffer, composited by the host",
world: None,
ifaces: [("wit/compositor/surface.wit", "surface")],
},
]
///| The component behind `id`: a loaded panel module (described from its real binary:
/// the plasmoid contract it exports and the capability interfaces it imports) or one
/// of the fixed shell parts (panel, desktop, window decoration, client surface).
fn DesktopShell::find_component(self : DesktopShell, id : String) -> Component? {
match self.widget_by_slot(id) {
Some(w) => {
let ifaces : Array[(String, String)] = [("", "plasmoid")]
for c in w.caps {
ifaces.push(("", c))
}
Some({
id,
title: w.pl.name,
note: "wasm module " + w.module_id + ", imports: " + (if w.caps.length() == 0 { "nothing" } else { w.caps.join(", ") }),
world: None,
ifaces,
})
}
None => {
for c in components {
if c.id == id {
return Some(c)
}
}
None
}
}
}
///| Read a file under the repo's wit/ directory (cached); "" when missing.
fn DesktopShell::wit_file(self : DesktopShell, path : String) -> String {
match self.wit_cache.get(path) {
Some(t) => t
None => {
let bytes = @sys.read_file_bytes(path)
let text = if bytes.length() == 0 {
""
} else {
@utf8.decode_lossy(bytes)
}
self.wit_cache.set(path, text)
text
}
}
}
///| The `kind name { ... }` block (with its leading /// docs), one line per entry.
fn extract_block(text : String, kind : String, name : String) -> Array[String] {
let lines : Array[String] = []
for l in text.split("\n") {
lines.push(l.to_string())
}
let head = kind + " " + name + " {"
let out : Array[String] = []
let mut start = -1
for i = 0; i < lines.length(); i = i + 1 {
if lines[i].has_prefix(head) {
start = i
break
}
}
if start < 0 {
return out
}
// leading doc comments
let mut s = start
while s > 0 && lines[s - 1].has_prefix("///") {
s = s - 1
}
for i = s; i < lines.length(); i = i + 1 {
out.push(lines[i])
if i >= start && (lines[i] == "}" || (i == start && lines[i].has_suffix("}"))) {
break
}
}
out
}
///| WIT files searched for interface/world definitions.
let wit_sources : Array[String] = [
"wit/worlds.wit", "wit/plasmoid.wit", "wit/capabilities.wit", "wit/shell.wit",
"wit/theme.wit", "wit/types.wit", "wit/wm/worlds.wit", "wit/wm/policy.wit",
"wit/wm/decoration.wit", "wit/compositor/surface.wit",
]
///| Interface block `name` from whichever WIT file defines it.
fn DesktopShell::find_interface(self : DesktopShell, name : String) -> Array[String] {
for f in wit_sources {
let b = extract_block(self.wit_file(f), "interface", name)
if b.length() > 0 {
return b
}
}
[]
}
///| All dialog lines for a component (blank line between blocks).
fn DesktopShell::inspector_lines(self : DesktopShell, c : Component) -> Array[String] {
let out : Array[String] = []
match c.world {
Some((file, name)) => {
for l in humanise_world(self.wit_file(file), name) {
out.push(l)
}
out.push("")
}
None => ()
}
// Interfaces come from the world (exports + imports) unless listed explicitly.
let names : Array[String] = []
match c.world {
Some((file, wname)) if c.ifaces.length() == 0 =>
for n in world_interfaces(self.wit_file(file), wname) {
names.push(n)
}
_ => for fi in c.ifaces { names.push(fi.1) }
}
for name in names {
let b = self.find_interface(name)
if b.length() == 0 {
out.push("(interface " + name + " not found - run from the repo root)")
} else {
for l in humanise_interface(name, b) {
out.push(l)
}
}
out.push("")
}
if names.length() == 0 && c.world is None {
out.push("(no WIT: not a component)")
}
// drop trailing blank
while out.length() > 0 && out[out.length() - 1] == "" {
ignore(out.pop())
}
out
}
///| Word length at the start of `s` (letters, digits, '-').
fn first_word(s : String) -> String {
let mut n = 0
while n < s.length() {
let ch = s[n]
let ok = (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-'
if !ok {
break
}
n = n + 1
}
s[:n].to_string()
}
///| Draw the dialog for the hovered component into `ops`.
fn DesktopShell::render_inspector(
self : DesktopShell,
w : Int,
h : Int,
tokens : @theme.Tokens,
ops : Array[@scene.DrawOp],
) -> Unit {
match self.find_component(self.hover_id) {
None => ()
Some(c) => {
let p = tokens.palette
let line_h = 18
let body_sz = 12
let header_h = 22 + 16 + 10
let text_w = 400
let dw = text_w + 28
// Word-wrap each paragraph to `text_w` using real glyph widths. A row is
// a list of (word, bold) runs; `**term**` in the prose marks bold terms.
let rows_all : Array[(Int, Array[(String, Bool, Bool)])] = [] // (kind: 0 body, 1 heading, 2 blank)
for para in self.inspector_lines(c) {
if para == "" {
rows_all.push((2, []))
} else if para.has_prefix("# ") {
rows_all.push((1, [(para[2:].to_string(), true, false)]))
} else {
// (word, bold, glued to the previous word: no space between)
let words : Array[(String, Bool, Bool)] = []
let mut is_bold = false
let mut prev_space = true
for seg in para.split("**") {
let sg = seg.to_string()
let mut first_word = true
for wd in sg.split(" ") {
let wd = wd.to_string()
if wd.length() > 0 {
words.push((wd, is_bold, first_word && !sg.has_prefix(" ") && !prev_space))
}
first_word = false
}
if sg.length() > 0 {
prev_space = sg.has_suffix(" ")
}
is_bold = !is_bold
}
let space = @renderer.text_width(" ", body_sz, false, false)
let mut cur : Array[(String, Bool, Bool)] = []
let mut cw = 0
for wv in words {
let ww = @renderer.text_width(wv.0, body_sz, wv.1, false)
if cur.length() > 0 && !wv.2 && cw + space + ww > text_w {
rows_all.push((0, cur))
cur = []
cw = 0
}
cw = cw + (if cur.length() > 0 && !wv.2 { space } else { 0 }) + ww
cur.push(wv)
}
if cur.length() > 0 {
rows_all.push((0, cur))
}
}
}
// Compact dialog: at most ~14 visible rows (or what fits the screen),
// the rest scrolls with the mouse wheel.
let fit = (h - 16 - header_h - 12) / line_h
let max_rows = if fit < 14 { fit } else { 14 }
let max_rows = if max_rows < 1 { 1 } else { max_rows }
let rows = if rows_all.length() < max_rows { rows_all.length() } else { max_rows }
let max_scroll = rows_all.length() - rows
if self.inspect_scroll > max_scroll {
self.inspect_scroll = max_scroll
}
if self.inspect_scroll < 0 {
self.inspect_scroll = 0
}
let first = self.inspect_scroll
let dh = header_h + rows * line_h + 12
let mut dx = self.hover_x + 18
let mut dy = self.hover_y + 18
if dx + dw > w {
dx = w - dw - 4
}
if dx < 4 {
dx = 4
}
if dy + dh > h {
dy = self.hover_y - dh - 12
}
if dy < 4 {
dy = 4
}
let local : Array[@types.DrawOp] = []
let r = tokens.radius.reinterpret_as_int()
local.push(@ui.fill_rect(@ui.rect(0, 0, dw, dh), p.surface_popup, radius=r + 4))
local.push(@ui.stroke_rect(@ui.rect(0, 0, dw, dh), p.accent, radius=r + 4))
local.push(@ui.text(14, 16, c.title, 14, p.foreground, bold=true))
local.push(@ui.text(14, 34, c.note, 11, p.foreground_muted))
local.push(@ui.fill_rect(@ui.rect(10, 46, dw - 20, 1), p.border))
let mut y = 58 + line_h / 2
let space = @renderer.text_width(" ", body_sz, false, false)
for i = first; i < rows_all.length() && i < first + rows; i = i + 1 {
let (kind, runs) = rows_all[i]
if kind == 1 {
local.push(@ui.text(14, y, runs[0].0, 13, p.accent, bold=true))
} else if kind == 0 {
let mut x = 14
for run in runs {
let (wd, b, glued) = run
if glued {
x = x - space
}
local.push(@ui.text(x, y, wd, body_sz, if b { p.accent } else { p.foreground }, bold=b))
x = x + @renderer.text_width(wd, body_sz, b, false) + space
}
}
y = y + line_h
}
if max_scroll > 0 {
// Scrollbar track + thumb on the right edge, plus a hint.
let th = rows * line_h
let thumb = if th * rows / rows_all.length() < 12 { 12 } else { th * rows / rows_all.length() }
let ty = 52 + (th - thumb) * first / max_scroll
local.push(@ui.fill_rect(@ui.rect(dw - 8, 52, 3, th), p.border))
local.push(@ui.fill_rect(@ui.rect(dw - 8, ty, 3, thumb), p.accent))
local.push(@ui.text(dw - 24 - 90, 34, "scroll for more", 11, p.foreground_muted))
}
let scene_ops : Array[@scene.DrawOp] = []
translate(local, dx, dy, scene_ops)
for op in scene_ops {
ops.push(op)
}
}
}
}
///| True while inspect mode is on.
pub fn DesktopShell::inspecting(self : DesktopShell) -> Bool {
self.inspect_on
}
///| Turn inspect mode on/off. The launcher popup is left as it is.
pub fn DesktopShell::set_inspecting(self : DesktopShell, on : Bool) -> Unit {
self.inspect_on = on
self.hover_id = ""
}
///| Shell component under (x, y): a panel widget id, "panel" for bare panel,
/// "" for anything else (windows or the desktop - the compositor resolves those).
pub fn DesktopShell::component_at(self : DesktopShell, x : Int, y : Int) -> String {
for entry in self.comps {
let (id, r) = entry
if inside(r, x, y) {
return id
}
}
if inside(self.panel_rect, x, y) {
"panel"
} else {
""
}
}
///| Record what the pointer is over while inspecting.
pub fn DesktopShell::set_hover(self : DesktopShell, id : String, x : Int, y : Int) -> Unit {
if id != self.hover_id {
self.inspect_scroll = 0
}
self.hover_id = id
self.hover_x = x
self.hover_y = y
}
///| Dialog lines for component `id` (for tests and tooling).
pub fn DesktopShell::inspector_lines_for(self : DesktopShell, id : String) -> Array[String] {
match self.find_component(id) {
Some(c) => self.inspector_lines(c)
None => []
}
}
///| Mouse-wheel scroll of the explorer dialog (lines, + = down). True if consumed.
pub fn DesktopShell::scroll_inspector(self : DesktopShell, lines : Int) -> Bool {
if !self.inspect_on || self.hover_id == "" {
return false
}
self.inspect_scroll = self.inspect_scroll + lines
if self.inspect_scroll < 0 {
self.inspect_scroll = 0
}
true
}
+13
View File
@@ -1,14 +1,27 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"moonplasma/desktop/interface/moonplasma/desktop/types" @types,
"moonplasma/desktop/interface/moonplasma/desktop/theme" @theme,
"moonplasma/desktop/lib/ui" @ui,
"moonplasma/desktop/lib/shell" @libshell,
"moonplasma/desktop/lib/panel" @panel,
"moonplasma/desktop/lib/clock" @clock,
"moonplasma/desktop/lib/moon" @moon,
"moonplasma/desktop/lib/timefmt" @timefmt,
"moonplasma/desktop/lib/launcher" @launcher,
"moonplasma/desktop/compositor/scene" @scene,
"moonplasma/desktop/compositor/sys" @sys,
"moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/compositor/wasm" @wasm,
}
supported_targets = "-all+native"
options(
link: {
"native": {
"cc-link-flags": "-lwasmer",
},
},
)
+537 -145
View File
@@ -125,59 +125,279 @@ fn now() -> @types.Datetime {
}
}
///| The desktop shell: wallpaper + bottom panel with launcher, task list and clock.
///| A window as the panel's task list sees it (handed to modules through the `windows` capability).
pub(all) struct WinInfo {
id : UInt64
title : String
focused : Bool
minimized : Bool
}
///| Something a panel module asked the compositor to do.
pub(all) enum ShellAction {
SetLayout(Int)
FocusWindow(UInt64)
} derive(Eq, Debug)
///| One wasm module loaded into the panel.
pub(all) struct Widget {
/// Panel slot id ("w1", "w2", ...): one per loaded instance.
slot : String
/// The module's file stem ("clock-digital"), or its path for modules loaded from elsewhere.
module_id : String
path : String
pl : @wasm.Plasmoid
/// Host interfaces the module imports (its capabilities).
caps : Array[String]
mut rect : @scene.Rect
/// Where its popup is on screen (w == 0 while closed), and what to draw there.
mut popup_rect : @scene.Rect
mut popup_ops : Array[@types.DrawOp]
mut popup_hot : Bool
}
///| A wasm module file found on the module path.
pub(all) struct CatalogEntry {
id : String
path : String
/// Filled in (by loading the module once) the first time names are needed; "" until then.
mut name : String
}
///| One row of the right-click menu: kind 0 replace with module `arg` (a path), 1 remove, 2 open the module manager.
pub(all) struct MenuRow {
label : String
kind : Int
arg : String
}
///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules
/// (application menu, Interface Explorer, layout switcher, task list, moon, clock ...).
/// Nothing on the panel is built in: every element is a plasmoid component loaded
/// from a `.wasm` file and can be unloaded or replaced while the compositor runs.
pub(all) struct DesktopShell {
launcher_state : @launcher.State
apps : Array[@types.AppEntry]
exec : Map[String, String]
/// Wayland socket handed to launched apps as WAYLAND_DISPLAY.
display : String
/// Panel modules in panel order; a module with `stretch` splits the panel into a left and a right group.
widgets : Array[Widget]
mut next_slot : Int
/// Module files on the search path (see `module_dirs`).
catalog : Array[CatalogEntry]
mut catalog_named : Bool
mut booted : Bool
/// Read and write panel.edn (the compositor binary turns this on; tests leave it off).
mut persist : Bool
mut tokens : @theme.Tokens
mut screen_w : Int
mut launcher_rect : @scene.Rect
mut popup_rect : @scene.Rect
mut screen_h : Int
mut panel_h : Int
/// Window list + layout mode, set by the compositor before each frame.
mut windows : Array[WinInfo]
mut layout_sel : Int
mut layout_names : Array[String]
/// Things modules asked for (focus a window, switch layout), drained by the compositor.
actions : Array[ShellAction]
mut apps_dirty : Bool
/// The native file chooser opened by the module manager's "Browse" row, and a transient notice.
mut picker : @wasm.Picker?
/// Machine-state provider behind the `system` interface, and the window list behind `windows`.
sampler : SysSampler
mut win_list : Array[@wasm.WindowEntry]
mut notice : String
mut notice_frames : Int
mut notice_start : Int
/// Right-click menu.
mut menu_open : Bool
mut menu_rect : @scene.Rect
mut menu_title : String
mut menu_rows : Array[MenuRow]
mut menu_hover : Int
mut menu_anchor_x : Int
mut menu_slot : String
/// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold.
mut drag_slot : String
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]
}
///| Apps the launcher offers, kept only if their executable exists.
/// (id, name, comment, category, glyph, executable)
let candidates : Array[(String, String, String, String, String, String)] = [
("org.moonplasma.terminal", "Terminal", "Command-line shell", "System", ">_", "foot"),
("org.moonplasma.konsole", "Konsole", "KDE terminal", "System", ">_", "konsole"),
("org.moonplasma.files", "Files", "Browse folders and files", "Utilities", "F", "dolphin"),
("org.moonplasma.browser", "Web Browser", "Browse the web", "Internet", "W", "firefox"),
("org.moonplasma.editor", "Text Editor", "Edit plain text files", "Utilities", "T", "kate"),
("org.moonplasma.settings", "System Settings", "Configure the desktop", "System", "S", "systemsettings"),
]
///|
pub fn DesktopShell::new(display : String) -> DesktopShell {
let apps : Array[@types.AppEntry] = []
let exec : Map[String, String] = {}
for c in candidates {
let (id, name, comment, category, glyph, bin) = c
if @sys.has_exe(bin) {
apps.push({ id, name, comment, category, glyph })
exec.set(id, bin)
for a in scan_desktop_apps() {
let glyph = match a.name.to_array().get(0) {
Some(c) => c.to_string().to_upper()
None => "?"
}
apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph })
exec.set(a.id, a.command)
}
{
launcher_state: @launcher.State::new(),
let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 }
let sh : DesktopShell = {
apps,
exec,
display,
widgets: [],
next_slot: 1,
catalog: [],
catalog_named: false,
booted: false,
persist: false,
tokens: conv_theme(@scene.ThemeTokens::moon_night()),
screen_w: 0,
launcher_rect: { x: 0, y: 0, w: 0, h: 0 },
popup_rect: { x: 0, y: 0, w: 0, h: 0 },
screen_h: 0,
panel_h: 40,
windows: [],
layout_sel: 0,
layout_names: ["Tiling (BSP)", "Monocle", "Floating"],
actions: [],
apps_dirty: true,
sampler: SysSampler::new(),
win_list: [],
picker: None,
notice: "",
notice_frames: 0,
notice_start: 0,
menu_open: false,
menu_rect: zero,
menu_title: "",
menu_rows: [],
menu_hover: -1,
menu_anchor_x: 0,
menu_slot: "",
drag_slot: "",
drag_x0: 0,
drag_y0: 0,
drag_active: false,
inspect_on: false,
hover_id: "",
hover_x: 0,
inspect_scroll: 0,
hover_y: 0,
panel_rect: zero,
comps: [],
wit_cache: {},
recents: load_recents(),
}
sh.order_apps()
sh
}
///| Tell the shell the theme and output size it will first be drawn with (modules are loaded
/// against these); the panel itself is loaded on first use.
pub fn DesktopShell::set_output(self : DesktopShell, theme : @scene.ThemeTokens, w : Int, h : Int) -> Unit {
self.tokens = conv_theme(theme)
self.screen_w = w
self.screen_h = h
self.panel_h = theme.panel_height
}
///| Default launcher entries, in order: each group is matched against app ids (first hit wins).
let default_groups : Array[Array[String]] = [
["foot", "konsole", "terminal", "kitty", "alacritty"],
["dolphin", "nautilus", "thunar", "files"],
["firefox", "chromium", "chrome", "browser"],
["kate", "gedit", "texteditor", "code", "editor"],
["systemsettings", "settings", "control"],
]
///|
let max_recents : Int = 8
///|
fn recents_path() -> String {
let c = @sys.getenv("XDG_CACHE_HOME")
(if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.cache" }) +
"/moon-plasma-recent"
}
///|
fn load_recents() -> Array[String] {
let out : Array[String] = []
let text = @utf8.decode_lossy(@sys.read_file_bytes(recents_path()))
for l in text.split("\n") {
let id = l.trim(chars=" \r").to_string()
if id.length() > 0 {
out.push(id)
}
}
out
}
///| Reorder the launcher: defaults first, then recents (newest first), then the rest A-Z.
fn DesktopShell::order_apps(self : DesktopShell) -> Unit {
let by_id : Map[String, @types.AppEntry] = {}
for a in self.apps {
by_id.set(a.id, a)
}
let out : Array[@types.AppEntry] = []
let seen : Map[String, Bool] = {}
fn take(a : @types.AppEntry, out : Array[@types.AppEntry], seen : Map[String, Bool]) -> Unit {
if !seen.contains(a.id) {
seen.set(a.id, true)
out.push(a)
}
}
for g in default_groups {
let mut found = false
for key in g {
if !found {
for a in self.apps {
if !found && a.id.to_lower().contains(key) {
take(a, out, seen)
found = true
}
}
}
}
}
for id in self.recents {
match by_id.get(id) {
Some(a) => take(a, out, seen)
None => ()
}
}
for a in self.apps {
take(a, out, seen) // already A-Z from the scan
}
self.apps.clear()
for a in out {
self.apps.push(a)
}
}
///| Truncate `s` with ".." so it fits `width` px (the renderer's small text is 6 px per char).
fn fit_title(s : String, width : Int) -> String {
let max_chars = width / 6
if s.length() <= max_chars {
s
} else {
s[:max_chars - 2].to_string() + ".."
///| Remember `id` as the most recent launch and persist the list.
fn DesktopShell::note_recent(self : DesktopShell, id : String) -> Unit {
let next : Array[String] = [id]
for r in self.recents {
if r != id && next.length() < max_recents {
next.push(r)
}
}
self.recents.clear()
for r in next {
self.recents.push(r)
}
let sb = StringBuilder::new()
for r in self.recents {
sb.write_string(r + "\n")
}
ignore(@sys.write_file_bytes(recents_path(), @utf8.encode(sb.to_string())))
self.order_apps()
}
///|
@@ -185,43 +405,122 @@ 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
}
///| True while the launcher popup is open (it then owns keyboard input).
///| 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.launcher_state.open
self.menu_open || self.open_popup_widget() is Some(_)
}
///| True if (x, y) is over the launcher button or its open popup.
pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool {
inside(self.launcher_rect, x, y) ||
(self.launcher_state.open && inside(self.popup_rect, x, y))
///| 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::launch(self : DesktopShell, id : String) -> Result[Unit, String] {
match self.exec.get(id) {
None => Err("no executable for " + id)
Some(bin) =>
if @sys.spawn(bin, self.display) {
Ok(())
} else {
Err("could not start " + bin)
}
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
}
///| 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))
}
}
}
///| wp_cursor_shape_v1 value for the shell UI under (x, y): 4 pointer (hand) over the
/// launcher button and popup entries, 9 text over the search field, else 0 (not shell-specific).
pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt {
if inside(self.launcher_rect, x, y) {
4U
} else if self.launcher_state.open && inside(self.popup_rect, x, y) {
if self.launcher_state.hover >= 0 {
4U
} else if y - self.popup_rect.y < 52 {
9U
} else {
1U
///| 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.drag_active {
17U // grabbing
} else if self.menu_open && inside(self.menu_rect, x, y) {
if self.menu_hover >= 0 { 4U } else { 1U }
} else if self.popup_at(x, y) is Some(_) {
1U
} else if self.widget_at(x, y) is Some(_) {
4U
} else {
0U
}
@@ -229,47 +528,139 @@ pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt {
///| Pointer press at (x, y). Returns true when the shell consumed it.
pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool {
let launch = fn(id : String) { self.launch(id) }
if inside(self.launcher_rect, x, y) {
ignore(
@launcher.handle_event(self.apps, self.launcher_state, Widget, PointerDown({ x: x - self.launcher_rect.x, y: y - self.launcher_rect.y }), launch),
)
true
} else if self.launcher_state.open {
if inside(self.popup_rect, x, y) {
ignore(
@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerDown({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch),
)
true
} else {
// Click outside: dismiss, and let the click through.
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, FocusLost, launch))
false
}
} else {
false
self.ensure_booted()
if self.menu_open {
// A press outside the menu dismisses it and goes through.
return self.menu_pointer_down(x, y)
}
}
///| Pointer motion; returns true when over the popup (so windows don't see it).
pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool {
if self.launcher_state.open {
let launch = fn(id : String) { self.launch(id) }
if inside(self.popup_rect, x, y) {
ignore(
@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerMove({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch),
)
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
}
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerLeave, launch))
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)
}
}
false
}
///| Key name as used by lib/launcher ("Escape", "Backspace", "Enter" or one character).
///| 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 {
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.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)
}
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 {
let launch = fn(id : String) { self.launch(id) }
ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, KeyDown(name), launch))
if self.menu_open {
if name == "Escape" {
self.menu_open = false
}
return
}
match self.open_popup_widget() {
Some(w) => ignore(self.deliver(w, true, KeyDown(name)))
None => ()
}
}
///| Things panel modules asked the compositor to do since the last call (focus a window, switch layout).
pub fn DesktopShell::take_actions(self : DesktopShell) -> Array[ShellAction] {
let out = self.actions.copy()
self.actions.clear()
out
}
///| Build the (background, panel) render-lists for the current frame.
@@ -278,72 +669,73 @@ pub fn DesktopShell::render(
w : Int,
h : Int,
theme : @scene.ThemeTokens,
layout_label : String,
window_titles : Array[String],
) -> (Array[@scene.DrawOp], Array[@scene.DrawOp]) {
let tokens = conv_theme(theme)
self.tokens = tokens
self.screen_w = w
self.screen_h = h
self.panel_h = theme.panel_height
self.ensure_booted()
self.poll_picker()
self.publish_host_data()
// Machine state and the rich window list only matter to modules that import them.
if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) {
self.sampler.refresh()
@wasm.set_windows(self.win_list)
}
let bg : Array[@scene.DrawOp] = []
translate(@libshell.render_background(@ui.size(w, h), tokens), 0, 0, bg)
render_desktop_widget(w, tokens, now(), bg)
let (_, _, clock_w, clock_h, clock_min) = @clock.digital_info()
let slots : Array[@panel.SlotIn] = [
{ id: "launcher", pref_w: 190, pref_h: 36, min_w: 170, stretch: false, end_align: false },
{ id: "layout", pref_w: 96, pref_h: 36, min_w: 80, stretch: false, end_align: false },
{ id: "tasks", pref_w: 100, pref_h: 36, min_w: 0, stretch: true, end_align: false },
{ id: "clock", pref_w: clock_w, pref_h: clock_h, min_w: clock_min, stretch: false, end_align: true },
]
let panel_ops : Array[@scene.DrawOp] = []
match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), slots) {
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) => {
let pr = @ui.rect(pl.x, pl.y, pl.w, pl.h)
translate(@libshell.render_panel(pr, tokens), 0, 0, panel_ops)
for p in pl.placements {
let size = @ui.size(p.w, p.h)
let local : Array[@types.DrawOp] = match p.id {
"launcher" => @launcher.render_button(size, tokens, self.launcher_state)
"clock" => @clock.render_digital(size, tokens, now(), hour12=true)
"layout" => [
@ui.fill_rect(@ui.rect(0, 0, p.w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()),
@ui.text(p.w / 2, p.h / 2, layout_label, tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground, align=CENTER),
]
_ => []
}
translate(local, p.x, p.y, panel_ops)
if p.id == "launcher" {
self.launcher_rect = { x: p.x, y: p.y, w: p.w, h: p.h }
}
if p.id == "tasks" {
let mut tx = 0
for title in window_titles {
let pill_w = 140
if tx + pill_w <= p.w {
translate(
[
@ui.fill_rect(@ui.rect(tx, 0, pill_w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()),
@ui.text(tx + 10, p.h / 2, fit_title(title, pill_w - 20), tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground),
],
p.x,
p.y,
panel_ops,
)
tx = tx + pill_w + 6
}
}
}
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))
}
}
}
if self.launcher_state.open {
let size = @launcher.popup_size(self.apps, self.launcher_state)
let pw = size.w.reinterpret_as_int()
let ph = size.h.reinterpret_as_int()
let (px, py) = @panel.popup_position(w, h - theme.panel_height, self.launcher_rect.x, pw, ph, 6)
self.popup_rect = { x: px, y: py, w: pw, h: ph }
translate(@launcher.render_popup(self.apps, tokens, self.launcher_state), px, py, panel_ops)
// Popups sit above the panel, left-aligned with their widget.
for wd in self.widgets {
self.refresh_popup(wd)
if wd.popup_rect.w > 0 {
translate(wd.popup_ops, wd.popup_rect.x, wd.popup_rect.y, panel_ops)
}
}
if self.menu_open {
self.render_menu(w, tokens, panel_ops)
} else {
self.popup_rect = { x: 0, y: 0, w: 0, h: 0 }
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)
}
+199
View File
@@ -0,0 +1,199 @@
///| Linux provider for the `system` interface: samples /proc and /sys about once a second
/// and hands widgets a `SystemSnapshot`. Widgets never see these paths; swapping this file
/// for another provider (a VM, a remote host, a mock) changes nothing for them.
///|
pub(all) struct SysSampler {
mut last_secs : Int
mut prev_busy : Int64
mut prev_total : Int64
mut prev_rx : Int64
mut prev_tx : Int64
mut primed : Bool
mut cur : @wasm.SystemSnapshot
}
///|
fn SysSampler::new() -> SysSampler {
{
last_secs: -1,
prev_busy: 0L,
prev_total: 0L,
prev_rx: 0L,
prev_tx: 0L,
primed: false,
cur: {
cpu_permille: 0,
mem_used_kib: 0L,
mem_total_kib: 0L,
battery_percent: -1,
charging: false,
uptime_secs: 0L,
rx_bps: 0L,
tx_bps: 0L,
load_centi: 0,
},
}
}
///|
fn proc_text(path : String) -> String {
@utf8.decode_lossy(@sys.read_proc_bytes(path))
}
///| Leading unsigned integer of `s` (0 if none).
fn parse_i64(s : String) -> Int64 {
let mut v = 0L
for ch in s {
let c = ch.to_int()
if c >= 48 && c <= 57 {
v = v * 10L + (c - 48).to_int64()
} else {
break
}
}
v
}
///| Whitespace-separated fields.
fn fields(s : String) -> Array[String] {
let out : Array[String] = []
let mut cur = ""
for ch in s {
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
if cur.length() > 0 {
out.push(cur)
cur = ""
}
} else {
cur = cur + ch.to_string()
}
}
if cur.length() > 0 {
out.push(cur)
}
out
}
///| "0.52" -> 52 (hundredths).
fn parse_centi(s : String) -> Int {
let parts = s.split(".").collect()
let whole = parse_i64(parts[0].to_string()).to_int()
let frac = if parts.length() > 1 {
let f = parts[1].to_string()
let two = if f.length() >= 2 { f[:2].to_string() } else { f + "0" }
parse_i64(two).to_int()
} else {
0
}
whole * 100 + frac
}
///| (busy, total) jiffies from the aggregate "cpu" line of /proc/stat.
fn cpu_times() -> (Int64, Int64) {
let text = proc_text("/proc/stat")
for line in text.split("\n") {
let f = fields(line.to_string())
if f.length() > 5 && f[0] == "cpu" {
let mut total = 0L
for i = 1; i < f.length() && i <= 8; i = i + 1 {
total = total + parse_i64(f[i])
}
let idle = parse_i64(f[4]) + parse_i64(f[5])
return (total - idle, total)
}
}
(0L, 0L)
}
///| (rx, tx) bytes summed over every interface but loopback.
fn net_bytes() -> (Int64, Int64) {
let mut rx = 0L
let mut tx = 0L
for line in proc_text("/proc/net/dev").split("\n") {
let l = line.to_string()
match l.find(":") {
None => ()
Some(i) => {
let name = l[:i].to_string().trim(chars=" ").to_string()
if name != "lo" {
let f = fields(l[i + 1:].to_string())
if f.length() > 8 {
rx = rx + parse_i64(f[0])
tx = tx + parse_i64(f[8])
}
}
}
}
}
(rx, tx)
}
///| (total, available) KiB from /proc/meminfo.
fn mem_kib() -> (Int64, Int64) {
let mut total = 0L
let mut avail = 0L
for line in proc_text("/proc/meminfo").split("\n") {
let f = fields(line.to_string())
if f.length() >= 2 {
if f[0] == "MemTotal:" {
total = parse_i64(f[1])
} else if f[0] == "MemAvailable:" {
avail = parse_i64(f[1])
}
}
}
(total, avail)
}
///| (percent, plugged-in) for the first battery, or (-1, true) without one.
fn battery() -> (Int, Bool) {
for name in ["BAT0", "BAT1", "BATT"] {
let base = "/sys/class/power_supply/" + name
let cap = proc_text(base + "/capacity")
if cap.length() > 0 {
let status = proc_text(base + "/status").trim(chars=" \n").to_string()
return (parse_i64(cap).to_int(), status != "Discharging")
}
}
(-1, true)
}
///| Re-sample if a wall-clock second passed since the last call; cheap otherwise.
fn SysSampler::refresh(self : SysSampler) -> Unit {
let now = wall_secs()
if now == self.last_secs {
return
}
let dt = if self.last_secs < 0 {
1
} else {
let d = now - self.last_secs
if d <= 0 { d + 86400 } else { d }
}
self.last_secs = now
let (busy, total) = cpu_times()
let (rx, tx) = net_bytes()
let (mt, ma) = mem_kib()
let (pct, plugged) = battery()
let dtotal = total - self.prev_total
let cpu = if self.primed && dtotal > 0L { ((busy - self.prev_busy) * 1000L / dtotal).to_int() } else { 0 }
let load = parse_centi(fields(proc_text("/proc/loadavg")).get(0).unwrap_or("0"))
self.cur = {
cpu_permille: if cpu < 0 { 0 } else if cpu > 1000 { 1000 } else { cpu },
mem_used_kib: mt - ma,
mem_total_kib: mt,
battery_percent: pct,
charging: plugged,
uptime_secs: parse_i64(fields(proc_text("/proc/uptime")).get(0).unwrap_or("0")),
rx_bps: if self.primed && rx >= self.prev_rx { (rx - self.prev_rx) / dt.to_int64() } else { 0L },
tx_bps: if self.primed && tx >= self.prev_tx { (tx - self.prev_tx) / dt.to_int64() } else { 0L },
load_centi: load,
}
self.prev_busy = busy
self.prev_total = total
self.prev_rx = rx
self.prev_tx = tx
self.primed = true
@wasm.set_system(self.cur)
}
+724
View File
@@ -0,0 +1,724 @@
///| 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 (`moonplasma: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 `modules`
/// for the module manager. The manager is itself just a module: the wasm picker
/// ("Module manager..." in the panel menu) loads it on demand and opens it.
///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right.
let default_panel : Array[String] = [
"launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12",
]
///| The module whose popup is the wasm picker.
let manager_module : String = "module-manager"
///| Directories searched for `*.wasm` modules, highest priority first.
fn module_dirs() -> Array[String] {
let dirs : Array[String] = []
let env = @sys.getenv("MOON_PLASMA_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 + "/moon-plasma/modules")
dirs.push("/usr/local/share/moon-plasma/modules")
dirs.push("/usr/share/moon-plasma/modules")
dirs.push("modules") // the login session runs from /usr/local/share/moon-plasma
// 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
}
}
///| Find every module file on the search path (earlier directories win on the same name).
fn DesktopShell::scan_catalog(self : DesktopShell) -> Unit {
self.catalog.clear()
self.catalog_named = false
let seen : Map[String, Bool] = {}
for dir in module_dirs() {
for f in @wasm.list_wasm_files(dir) {
let id = stem(f)
if !seen.contains(id) {
seen.set(id, true)
self.catalog.push({ id, path: dir + "/" + f, name: "" })
}
}
}
}
///| Learn each module's display name by loading it once; files that are not plasmoids
/// (the shell, window-manager and gfx components live in the same directory) drop out.
fn DesktopShell::name_catalog(self : DesktopShell) -> Unit {
if self.catalog_named {
return
}
self.catalog_named = true
let keep : Array[CatalogEntry] = []
for e in self.catalog {
match @wasm.load(e.path, self.tokens) {
Ok(pl) => {
e.name = pl.name
pl.unload()
keep.push(e)
}
Err(_) => ()
}
}
self.catalog.clear()
for e in keep {
self.catalog.push(e)
}
}
///| Catalog entry for module id `id`.
fn DesktopShell::find_module(self : DesktopShell, id : String) -> CatalogEntry? {
for e in self.catalog {
if e.id == id {
return Some(e)
}
}
None
}
///| Panel slot descriptions for every loaded module, in panel order. A stretching module
/// (the task list) splits the panel: modules after it pack against the right edge.
fn DesktopShell::panel_slots(self : DesktopShell) -> Array[@panel.SlotIn] {
let mut first_stretch = -1
for i = 0; i < self.widgets.length(); i = i + 1 {
if first_stretch < 0 && self.widgets[i].pl.stretch {
first_stretch = i
}
}
let out : Array[@panel.SlotIn] = []
for i = 0; i < self.widgets.length(); i = i + 1 {
let w = self.widgets[i]
out.push({
id: w.slot,
pref_w: w.pl.pref_w,
pref_h: w.pl.pref_h,
min_w: w.pl.min_w,
stretch: w.pl.stretch,
end_align: first_stretch >= 0 && i > first_stretch,
})
}
out
}
///| Would the panel still fit on screen with the current modules?
fn DesktopShell::panel_fits(self : DesktopShell) -> Bool {
match @panel.layout(self.screen_w, 100000, 40, 4, 6, self.panel_slots()) {
Ok(_) => true
Err(_) => false
}
}
///| Show a short message above the panel for a few seconds.
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)
}
///| Load the panel on first use: the saved layout if there is one, else the default modules.
fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
if self.booted {
return
}
self.booted = true
self.scan_catalog()
let entries = match self.load_panel_config() {
Some(e) => e
None => default_panel
}
for e in entries {
let path = if e.has_prefix("/") {
e
} else {
match self.find_module(e) {
Some(c) => c.path
None => {
self.say("Module '" + e + "' not found (build it with scripts/build-modules.sh)")
""
}
}
}
if path != "" {
ignore(self.load_path(path))
}
}
}
///| Load the module file at `path` into the panel (any number of instances may be loaded).
/// None, with a notice, when it is not a plasmoid or the panel has no room for it.
pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
match @wasm.load(path, self.tokens) {
Err(e) => {
self.say("Can't load module: " + e)
None
}
Ok(pl) => {
let id = stem(path)
let known = match self.find_module(id) {
Some(c) => c.path == path
None => false
}
let w : Widget = {
slot: "w" + self.next_slot.to_string(),
module_id: if known { id } else { path },
path,
pl,
caps: pl.imports(),
rect: { x: 0, y: 0, w: 0, h: 0 },
popup_rect: { x: 0, y: 0, w: 0, h: 0 },
popup_ops: [],
popup_hot: false,
}
self.next_slot = self.next_slot + 1
self.widgets.push(w)
if self.screen_w > 0 && !self.panel_fits() {
self.widgets.retain(x => x.slot != w.slot)
pl.unload()
self.say("No room in the panel for " + pl.name)
None
} else {
Some(w)
}
}
}
}
///| Load module `id` (a file stem from the catalog, or a path) and persist the panel.
pub fn DesktopShell::load_module(self : DesktopShell, id : String) -> Bool {
self.ensure_booted()
let path = match self.find_module(id) {
Some(c) => c.path
None => id
}
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
true
}
None => false
}
}
///| Unload the module in `slot`, freeing its panel space. False if there is none.
pub fn DesktopShell::unload_slot(self : DesktopShell, slot : String) -> Bool {
match self.widget_by_slot(slot) {
None => false
Some(w) => {
self.widgets.retain(x => x.slot != slot)
w.pl.unload()
if self.drag_slot == slot {
self.drag_slot = ""
self.drag_active = false
}
self.save_panel_config()
true
}
}
}
///| Replace the module in `slot` with the module file at `path`, keeping its place in the panel.
pub fn DesktopShell::replace_slot(self : DesktopShell, slot : String, path : String) -> Bool {
let mut idx = -1
for i = 0; i < self.widgets.length(); i = i + 1 {
if self.widgets[i].slot == slot {
idx = i
}
}
if idx < 0 {
return false
}
let old = self.widgets[idx]
self.widgets.remove(idx) |> ignore
match self.load_path(path) {
None => {
self.widgets.insert(idx, old)
false
}
Some(nw) => {
// load_path appended it; move it into the old module's place, then drop the old one.
self.widgets.retain(x => x.slot != nw.slot)
self.widgets.insert(idx, nw)
old.pl.unload()
self.save_panel_config()
true
}
}
}
///| Unload every module (the compositor is closing).
pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit {
for w in self.widgets {
w.pl.unload()
}
self.widgets.clear()
}
///| Slot ids of the loaded modules, in panel order.
pub fn DesktopShell::slots(self : DesktopShell) -> Array[String] {
self.ensure_booted()
self.widgets.map(w => w.slot)
}
///| Module id of the module in `slot` ("" if none).
pub fn DesktopShell::slot_module(self : DesktopShell, slot : String) -> String {
match self.widget_by_slot(slot) {
Some(w) => w.module_id
None => ""
}
}
///| Slot of the first loaded instance of module `id` ("" if none).
pub fn DesktopShell::slot_of(self : DesktopShell, id : String) -> String {
self.ensure_booted()
for w in self.widgets {
if w.module_id == id {
return w.slot
}
}
""
}
///| Panel rectangle of the module in `slot` as last drawn.
pub fn DesktopShell::slot_rect(self : DesktopShell, slot : String) -> @scene.Rect {
match self.widget_by_slot(slot) {
Some(w) => w.rect
None => { x: 0, y: 0, w: 0, h: 0 }
}
}
///| Rectangle of the module's open popup (w == 0 when closed).
pub fn DesktopShell::slot_popup_rect(self : DesktopShell, slot : String) -> @scene.Rect {
match self.widget_by_slot(slot) {
Some(w) => w.popup_rect
None => { x: 0, y: 0, w: 0, h: 0 }
}
}
///| Publish what modules can read through their capabilities (apps, windows, layout, loaded modules).
fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.apps_dirty {
self.apps_dirty = false
let t = @wasm.Table::new()
for a in self.apps {
t.str(a.id)
t.str(a.name)
t.str(a.comment)
t.str(a.category)
t.str(a.glyph)
t.end_row()
}
@wasm.publish(Apps, t)
}
let wt = @wasm.Table::new()
for win in self.windows {
wt.int(win.id.to_int())
wt.str(win.title)
wt.int(if win.focused { 1 } else { 0 })
wt.int(if win.minimized { 1 } else { 0 })
wt.end_row()
}
@wasm.publish(Windows, wt)
let lt = @wasm.Table::new()
for n in self.layout_names {
lt.str(n)
lt.end_row()
}
@wasm.publish(Layouts, lt)
@wasm.publish_state(self.layout_sel, self.inspect_on)
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)
}
}
///| Carry out what modules asked of the host during their last calls.
fn DesktopShell::process_requests(self : DesktopShell) -> Unit {
while true {
match @wasm.next_request() {
None => break
Some(Launch(id)) => {
match self.exec.get(id) {
Some(bin) =>
if @sys.spawn(bin, self.display) {
self.note_recent(id)
self.apps_dirty = true
} else {
self.say("Could not start " + bin)
}
None => self.say("No executable for " + id)
}
}
Some(FocusWindow(n)) => self.actions.push(FocusWindow(n.to_int64().to_uint64()))
Some(SetLayout(m)) => self.actions.push(SetLayout(m))
Some(SetInspector(on)) => self.set_inspecting(on)
Some(LoadModule(path)) => {
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
}
None => ()
}
}
Some(UnloadInstance(slot)) => ignore(self.unload_slot(slot))
Some(Browse) =>
if self.picker is None {
self.picker = @wasm.Picker::start()
if self.picker is None {
self.say("No file chooser available (install zenity)")
}
}
}
}
// A module that imports `windows.focus` (the 64-bit-id form) asks through its own slot.
match @wasm.take_focus_request() {
Some(id) => self.actions.push(FocusWindow(id))
None => ()
}
}
///| Re-read the module's popup (size and drawing) and place it above the panel.
fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit {
if self.widget_by_slot(w.slot) is None {
return
}
match w.pl.popup() {
None => {
w.popup_rect = { x: 0, y: 0, w: 0, h: 0 }
w.popup_ops = []
w.popup_hot = false
}
Some(ps) => {
let (px, py) = @panel.popup_position(self.screen_w, self.screen_h - self.panel_h, w.rect.x, ps.w, ps.h, 6)
w.popup_rect = { x: px, y: py, w: ps.w, h: ps.h }
w.popup_ops = ps.ops
}
}
}
///| Check the open file dialog; load the chosen .wasm into the panel.
fn DesktopShell::poll_picker(self : DesktopShell) -> Unit {
match self.picker {
None => ()
Some(pk) =>
match pk.poll() {
None => ()
Some(None) => self.picker = None
Some(Some(path)) => {
self.picker = None
match self.load_path(path) {
Some(w) => {
self.say("Loaded " + w.pl.name)
self.save_panel_config()
}
None => ()
}
}
}
}
}
///| The wasm picker: open the module manager app to choose what to load, loading the
/// manager itself first if it is not in the panel.
pub fn DesktopShell::open_module_manager(self : DesktopShell) -> 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("Module manager 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)))
}
self.save_panel_config()
true
}
}
}
// ---------------------------------------------------------------- right-click menu
///| Title row height and item row height of the menu.
let menu_title_h : Int = 26
///|
let menu_item_h : Int = 28
///|
let menu_w : Int = 250
///| Most "Replace with" rows listed.
let max_replace_rows : Int = 8
///| Right-click: on a module its replace/remove menu, on empty panel space the picker entry.
/// True when consumed.
pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool {
self.ensure_booted()
if self.inspect_on {
return false
}
let was_open = self.menu_open
self.menu_open = false
self.dismiss_popups("")
match self.widget_at(x, y) {
Some(w) => {
self.name_catalog()
let rows : Array[MenuRow] = []
for e in self.catalog {
if e.id != w.module_id && e.path != w.path && rows.length() < max_replace_rows {
rows.push({ label: "Replace with " + e.name, kind: 0, arg: e.path })
}
}
rows.push({ label: "Remove widget", kind: 1, arg: "" })
rows.push({ label: "Module manager...", kind: 2, arg: "" })
self.open_menu(w.pl.name, rows, w.slot, x)
true
}
None =>
if inside(self.panel_rect, x, y) {
self.open_menu("Add widget", [{ label: "Module manager...", kind: 2, arg: "" }], "", x)
true
} else {
was_open
}
}
}
///|
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))
_ => ignore(self.open_module_manager())
}
}
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 hot = i == self.menu_hover
if hot {
ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r))
}
ops.push(@ui.text(14, top + menu_item_h / 2, self.menu_rows[i].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/moon-plasma/panel.edn (default ~/.config).
fn panel_config_dir() -> String {
let c = @sys.getenv("XDG_CONFIG_HOME")
(if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.config" }) +
"/moon-plasma"
}
///| Write the loaded modules, in panel order, as EDN:
/// {:panel ["launcher" "layout" "tasks" "/home/me/my-widget.wasm"]}
/// (catalog modules by name, others by path). A no-op unless `persist` is on.
pub fn DesktopShell::save_panel_config(self : DesktopShell) -> Unit {
if !self.persist || !self.booted {
return
}
let sb = StringBuilder::new()
sb.write_string(";; Moon Plasma panel: the wasm modules loaded into it, in order\n")
sb.write_string("{:panel [")
let mut first = true
for w in self.widgets {
if !first {
sb.write_string("\n ")
}
first = false
sb.write_string("\"" + w.module_id + "\"")
}
sb.write_string("]}\n")
let dir = panel_config_dir()
if @sys.mkdir_p(dir) {
ignore(@sys.write_file_bytes(dir + "/panel.edn", @utf8.encode(sb.to_string())))
}
}
///| The module list saved in panel.edn; None when persistence is off or there is no saved panel.
fn DesktopShell::load_panel_config(self : DesktopShell) -> Array[String]? {
if !self.persist {
return None
}
let text = @utf8.decode_lossy(@sys.read_file_bytes(panel_config_dir() + "/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)
}