Reload panel modules from outside the session: control socket, chandra-ctl, SIGUSR1
CI / test (push) Failing after 16s

Until now a module reload was only reachable by clicking Settings > Panel inside the session.
Now:

- The compositor listens on $XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock (the login
  session's is wayland-moon-0.sock) with a line protocol: ping, list, reload [NAME], help.
  Replies end with an "ok ..." or "error ..." line. It lives in compositor/host/control.mbt,
  runs from ChandraCompositor::step, and its fds join the idle loop's wait set, so an idle
  desktop still sleeps (measured ~0.4% CPU on wasmhost, ~0.1% on host-wasm) and wakes for a
  command. A path another live compositor answers on is left alone.
- DesktopShell::reload_modules(name) reloads every loaded module (or those whose module id,
  stem, slot or path is NAME) in place via replace_slot: same panel position, saved
  :module-config applied, a module that fails to load stays as it was and the error is
  reported to the caller and shown as a notice. The catalog is rescanned.
- SIGUSR1 to the host reloads every module (result in the log and the notice): new WIT
  function sys.take-sigusr1, implemented in compositor/sys (native build and wasmhost) and
  host-wasm; the handler has no SA_RESTART so it interrupts the idle poll.
- session/chandra-ctl (installed to /usr/local/bin), `just reload [NAME]`, docs/reloading.md,
  README.
- Tests: compositor/host/control_test.mbt (protocol, reload all / by name / by slot, order
  and settings kept, failing module kept, busy socket). Checked headless on both hosts with
  chandra-ctl and kill -USR1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjLJtvYcgW48okL6qQ
This commit is contained in:
Claude committed 2026-11-25 20:57:40 +00:00
1 parent 0fc2598d27
commit 68164ff75e
21 files changed
+844 -31

No files matched your search

+3 -2
View File
@@ -32,7 +32,7 @@ interface** with **deny-by-default capabilities**:
Design: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) (Plasma to component mapping, permissions, Design: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) (Plasma to component mapping, permissions,
versioning) and [docs/compositor-design.md](docs/compositor-design.md) (the compositor and its versioning) and [docs/compositor-design.md](docs/compositor-design.md) (the compositor and its
hosts). Toolchain notes: [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). Dark mode and the portal: [docs/dark-mode.md](docs/dark-mode.md). Running as root and run0: hosts). Toolchain notes: [docs/TOOLCHAIN.md](docs/TOOLCHAIN.md). Dark mode and the portal: [docs/dark-mode.md](docs/dark-mode.md). Running as root and run0:
[docs/run0.md](docs/run0.md). Picking up a new build without logging out: [docs/reloading.md](docs/reloading.md). [docs/run0.md](docs/run0.md). Picking up a new build without logging out (`just reload`, `chandra-ctl reload`): [docs/reloading.md](docs/reloading.md).
## How it runs ## How it runs
@@ -76,6 +76,7 @@ just client # start foot inside it (or: just client konsol
| `just run-drm` | As a login session on the real screen (from a text console, as yourself) | | `just run-drm` | As a login session on the real screen (from a text console, as yourself) |
| `just install-session` | Install the "Chandra" display-manager session (asks for root once) | | `just install-session` | Install the "Chandra" display-manager session (asks for root once) |
| `just install-session-dev` | Same, but symlinked into this checkout: later just rebuild | | `just install-session-dev` | Same, but symlinked into this checkout: later just rebuild |
| `just reload` | Reload the running session's panel modules from disk (`chandra-ctl reload [NAME]`) |
| `just run-rust`, `run-drm-rust`, `install-session-rust` | The same with the Rust host | | `just run-rust`, `run-drm-rust`, `install-session-rust` | The same with the Rust host |
| `just run-native`, `run-drm-native`, `install-session-native` | The native (non-wasm) build | | `just run-native`, `run-drm-native`, `install-session-native` | The native (non-wasm) build |
| `just compositor-wasm`, `wasmhost`, `host-wasm`, `modules` | Build one piece | | `just compositor-wasm`, `wasmhost`, `host-wasm`, `modules` | Build one piece |
@@ -188,7 +189,7 @@ lib/ pure, unit-tested logic (panel layout, clock, launcher, ba
wasmhost/ the default host (MoonBit + wasmtime C API) wasmhost/ the default host (MoonBit + wasmtime C API)
host-wasm/ the fallback host (Rust + wasmtime) host-wasm/ the fallback host (Rust + wasmtime)
host/ the original M0 browser/Node host (jco), kept for the component demos host/ the original M0 browser/Node host (jco), kept for the component demos
session/ chandra-session, chandra-root, chandra.desktop, chandra.portal, install.py session/ chandra-session, chandra-root, chandra-ctl, chandra.desktop, chandra.portal, install.py
config/ desktop configs, themes, app list config/ desktop configs, themes, app list
scripts/ setup-toolchain, build-*, gen-bindings, as-root, remote-build, test scripts/ setup-toolchain, build-*, gen-bindings, as-root, remote-build, test
docs/ ARCHITECTURE, compositor-design, TOOLCHAIN, run0, dark-mode, reloading, screenshots docs/ ARCHITECTURE, compositor-design, TOOLCHAIN, run0, dark-mode, reloading, screenshots
+4
View File
@@ -190,6 +190,8 @@ pub fn run(args : Array[String]) -> Int {
None => () None => ()
} }
@sys.log("chandra compositor listening on " + socket_path) @sys.log("chandra compositor listening on " + socket_path)
// chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too.
ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path)))
if restore { if restore {
ignore(comp.restore_session()) // reopen the windows the last session ended with ignore(comp.restore_session()) // reopen the windows the last session ended with
} }
@@ -265,6 +267,7 @@ pub fn run(args : Array[String]) -> Int {
// Idle: sleep until a client, the seat or the clock has something. // Idle: sleep until a client, the seat or the clock has something.
let fds = comp.server.wait_fds() let fds = comp.server.wait_fds()
fds.append(k.wait_fds()) fds.append(k.wait_fds())
fds.append(comp.control_fds()) // chandra-ctl
let pfd = comp.portal_fd() // apps asking the dark/light preference let pfd = comp.portal_fd() // apps asking the dark/light preference
if pfd >= 0 { if pfd >= 0 {
fds.push(pfd) fds.push(pfd)
@@ -287,6 +290,7 @@ pub fn run(args : Array[String]) -> Int {
// Whether this pass had anything to do; an idle pass sleeps on the fds instead of a frame. // Whether this pass had anything to do; an idle pass sleeps on the fds instead of a frame.
let mut busy = false let mut busy = false
let wait_fds = comp.server.wait_fds() let wait_fds = comp.server.wait_fds()
wait_fds.append(comp.control_fds()) // chandra-ctl
match nested { match nested {
Some(n) => { Some(n) => {
if !n.poll() { if !n.poll() {
+2
View File
@@ -121,6 +121,8 @@ fn main {
None => () None => ()
} }
println("chandra compositor listening on " + socket_path + " (wasi-gfx surface active)") println("chandra compositor listening on " + socket_path + " (wasi-gfx surface active)")
// chandra-ctl's socket (reload panel modules from a script); SIGUSR1 reloads too.
ignore(comp.start_control(@host.control_socket_path(@sys.getenv("XDG_RUNTIME_DIR"), socket_path)))
if restore { if restore {
ignore(comp.restore_session()) // reopen the windows the last session ended with ignore(comp.restore_session()) // reopen the windows the last session ended with
} }
+5
View File
@@ -47,6 +47,8 @@ pub(all) struct ChandraCompositor {
/// The xdg-desktop-portal Settings backend apps read the dark/light preference from /// The xdg-desktop-portal Settings backend apps read the dark/light preference from
/// (compositor/portal), started with the first `sync_system_theme_pref`. /// (compositor/portal), started with the first `sync_system_theme_pref`.
mut settings_portal : @portal.SettingsPortal? mut settings_portal : @portal.SettingsPortal?
/// The control socket (control.mbt): chandra-ctl reload / list. None until `start_control`.
mut control : ControlServer?
/// Running as the login session (--drm): power actions act on the machine (power.mbt). /// Running as the login session (--drm): power actions act on the machine (power.mbt).
mut login_session : Bool mut login_session : Bool
/// Power (power.mbt): when input last came (monotonic ms), whether the screen is off for being /// Power (power.mbt): when input last came (monotonic ms), whether the screen is off for being
@@ -173,6 +175,7 @@ pub fn ChandraCompositor::new(
dark_theme: theme, dark_theme: theme,
sync_system_theme: false, sync_system_theme: false,
settings_portal: None, settings_portal: None,
control: None,
login_session: false, login_session: false,
last_input_ms: @sys.monotonic_ms(), last_input_ms: @sys.monotonic_ms(),
screen_off: false, screen_off: false,
@@ -279,6 +282,7 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
for _, win in self.windows { for _, win in self.windows {
release_snapshot(win.surface) release_snapshot(win.surface)
} }
self.stop_control()
self.shell.shutdown() self.shell.shutdown()
match self.settings_portal { match self.settings_portal {
Some(p) => p.close() Some(p) => p.close()
@@ -385,6 +389,7 @@ fn ChandraCompositor::flush_configures(self : ChandraCompositor) -> Unit {
pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
self.flush_configures() self.flush_configures()
self.portal_tick() self.portal_tick()
self.control_tick()
let events = self.server.poll_events() let events = self.server.poll_events()
for ev in events { for ev in events {
match ev { match ev {
+242
View File
@@ -0,0 +1,242 @@
///| The control socket: lets scripts outside the session reload panel modules (after
/// `just install-session` or a module rebuild) without clicking through Settings > Panel.
///
/// A unix stream socket at `$XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock`, for example
/// `/run/user/1000/chandra/wayland-moon-0.sock` (`control_socket_path`). XDG_RUNTIME_DIR is
/// private to the user (0700), so only the user's own processes can reach it. A client writes
/// one command per line; every reply is zero or more lines of output followed by one line that
/// starts with `ok` or `error`:
///
/// ping ok pong
/// list w1 launcher /usr/local/share/chandra/modules/launcher.wasm ... ok 7 modules
/// reload reloaded w8 launcher ... ok 7 reloaded
/// reload clock reloaded w9 clock-digital ok 1 reloaded
/// help the commands, then ok
///
/// `session/chandra-ctl` is the command-line client; docs/reloading.md has the details. SIGUSR1
/// to the host process (`pkill -USR1 -x chandra-host`) reloads every module the same way, with
/// the result shown as a notice above the panel and written to the log.
///
/// The main loop keeps sleeping while idle: the listening socket and the connected clients are
/// in `control_fds`, which the loop adds to the fds it waits on.
///| One connected client: its fd and the bytes of a line not finished yet.
struct ControlClient {
fd : Int
pending : Array[Byte]
}
///| The listening socket, its path (unlinked on close) and the connected clients.
pub(all) struct ControlServer {
path : String
fd : Int
clients : Array[ControlClient]
}
///| Where the control socket of the compositor serving `wayland_socket` lives:
/// `<runtime_dir>/chandra/<file name of wayland_socket>.sock` ("" when `runtime_dir` is empty).
pub fn control_socket_path(runtime_dir : String, wayland_socket : String) -> String {
if runtime_dir == "" {
return ""
}
let mut start = 0
for i = 0; i < wayland_socket.length(); i = i + 1 {
if wayland_socket[i] == '/' {
start = i + 1
}
}
let name = wayland_socket[start:].to_string()
runtime_dir + "/chandra/" + (if name == "" { "chandra" } else { name }) + ".sock"
}
///| Open the control socket at `path` (its directory is created). False, with a log line, when
/// it can't be opened, or when another compositor is already answering on it (its socket is left
/// alone: a nested compositor must not take a running session's socket away).
pub fn ChandraCompositor::start_control(self : ChandraCompositor, path : String) -> Bool {
self.stop_control()
if path == "" {
@sys.log("control socket: XDG_RUNTIME_DIR is not set; chandra-ctl and SIGUSR1 reloads are off")
return false
}
let mut dir = ""
for i = 0; i < path.length(); i = i + 1 {
if path[i] == '/' {
dir = path[:i].to_string()
}
}
if dir != "" {
ignore(@sys.mkdir_p(dir))
}
let probe = @sys.unix_connect(path)
if probe >= 0 {
@sys.close_fd(probe)
@sys.log("control socket: " + path + " is in use by another compositor; this one has none")
return false
}
let fd = @sys.unix_listen(path)
if fd < 0 {
@sys.log("control socket: can't listen on " + path)
return false
}
self.control = Some({ path, fd, clients: [] })
@sys.log("control socket on " + path + " (chandra-ctl reload)")
true
}
///| Close the control socket and its clients and remove the socket file.
pub fn ChandraCompositor::stop_control(self : ChandraCompositor) -> Unit {
match self.control {
None => ()
Some(c) => {
for cl in c.clients {
@sys.close_fd(cl.fd)
}
@sys.close_fd(c.fd)
@sys.unlink(c.path)
self.control = None
}
}
}
///| The fds the idle main loop must wake for: the listening socket and every client.
pub fn ChandraCompositor::control_fds(self : ChandraCompositor) -> Array[Int] {
match self.control {
None => []
Some(c) => {
let fds = [c.fd]
for cl in c.clients {
fds.push(cl.fd)
}
fds
}
}
}
///| Longest command line taken; a client sending more without a newline is dropped.
let control_max_line : Int = 4096
///| Accept new clients and answer every complete line the clients sent (called from `step`).
fn ChandraCompositor::control_tick(self : ChandraCompositor) -> Unit {
if @sys.take_sigusr1() {
@sys.log("SIGUSR1: reloading every panel module")
let (lines, ok) = self.control_command("reload")
for l in lines {
@sys.log(" " + l)
}
ignore(ok)
}
let c = match self.control {
None => return
Some(c) => c
}
while true {
let fd = @sys.unix_accept(c.fd)
if fd < 0 {
break
}
c.clients.push({ fd, pending: [] })
}
let gone : Array[Int] = []
let buf : FixedArray[Byte] = FixedArray::make(1024, b'\x00')
for cl in c.clients {
let mut open = true
while open {
let (n, extra) = @sys.recvmsg_fd(cl.fd, buf, 1024)
if extra >= 0 {
@sys.close_fd(extra)
}
if n == -1 {
break // nothing more for now
}
if n <= 0 {
open = false // EOF or error
break
}
for i = 0; i < n; i = i + 1 {
let b = buf[i]
if b == b'\n' {
let line = @utf8.decode_lossy(Bytes::from_array(cl.pending))
cl.pending.clear()
let (out, _) = self.control_command(line)
let reply = StringBuilder::new()
for l in out {
reply.write_string(l)
reply.write_char('\n')
}
if @sys.sendmsg_fd(cl.fd, @utf8.encode(reply.to_string()), -1) < 0 {
open = false
break
}
} else {
cl.pending.push(b)
}
}
if cl.pending.length() > control_max_line {
ignore(@sys.sendmsg_fd(cl.fd, @utf8.encode("error line too long\n"), -1))
open = false
}
}
if !open {
gone.push(cl.fd)
}
}
if gone.length() > 0 {
for fd in gone {
@sys.close_fd(fd)
}
c.clients.retain(cl => !gone.contains(cl.fd))
}
}
///| Run one control command; the reply lines (the last starts with "ok" or "error") and whether
/// it succeeded.
pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : String) -> (Array[String], Bool) {
let words : Array[String] = []
for w in line.trim(chars=" \t\r").split(" ") {
let s = w.to_string()
if s != "" {
words.push(s)
}
}
if words.length() == 0 {
return (["error empty command (try: help)"], false)
}
match words[0] {
"ping" => (["ok pong"], true)
"help" =>
(
[
"ping check the compositor answers", "list loaded panel modules: slot, module, path",
"reload load every panel module again from disk", "reload NAME only the modules whose name, slot or path is NAME",
"ok",
],
true,
)
"list" => {
let mods = self.shell.loaded_modules()
let out = mods.map(m => m.0 + " " + m.1 + " " + m.2)
out.push("ok " + mods.length().to_string() + " modules")
(out, true)
}
"reload" => {
if words.length() > 2 {
return (["error usage: reload [NAME]"], false)
}
let name = if words.length() == 2 { words[1] } else { "" }
let (out, ok) = self.shell.reload_modules(name)
// The panel changed under the frame signature's feet: draw it again.
self.frame_changed = true
self.damage.mark_full()
let n = out.filter(l => l.has_prefix("reloaded ")).length()
if ok {
out.push("ok " + n.to_string() + " reloaded")
} else if n == 0 && out.length() == 1 && !out[0].has_prefix("failed ") {
out[0] = "error " + out[0]
} else {
out.push("error " + (out.length() - n).to_string() + " of " + out.length().to_string() + " failed to reload")
}
(out, ok)
}
other => (["error unknown command '" + other + "' (try: help)"], false)
}
}
+161
View File
@@ -0,0 +1,161 @@
///| The control socket (control.mbt): chandra-ctl's commands and module reloads.
/// Needs the modules: run scripts/build-modules.sh (just test does).
///| A compositor with its control socket open in a fresh directory.
fn control_comp(tag : String) -> (@host.ChandraCompositor, String) raise {
let comp = new_comp("control-" + tag)
let dir = "/tmp/chandra-control-" + tag + "-" + @sys.getpid().to_string()
let path = @host.control_socket_path(dir, "/run/user/1000/wayland-moon-0")
assert_eq(path, dir + "/chandra/wayland-moon-0.sock")
assert_true(comp.start_control(path))
(comp, path)
}
///| Send `line` over a new connection, let the compositor run a pass, and read its reply lines.
fn ask(comp : @host.ChandraCompositor, path : String, line : String) -> Array[String] raise {
let fd = @sys.unix_connect(path)
assert_true(fd >= 0)
assert_true(@sys.sendmsg_fd(fd, @utf8.encode(line + "\n"), -1) > 0)
let raw : Array[Byte] = []
let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00')
let mut tries = 0
let mut done = false
while !done && tries < 50 {
comp.step()
while @sys.poll_read(fd, 5) > 0 {
let (n, _) = @sys.recvmsg_fd(fd, buf, 4096)
if n <= 0 {
break
}
for i = 0; i < n; i = i + 1 {
raw.push(buf[i])
}
}
let text = @utf8.decode_lossy(Bytes::from_array(raw))
let lines = text.split("\n").map(s => s.to_string()).filter(s => s != "").collect()
if text.has_suffix("\n") && lines.length() > 0 {
let last = lines[lines.length() - 1]
done = last.has_prefix("ok") || last.has_prefix("error")
}
tries = tries + 1
}
@sys.close_fd(fd)
let text = @utf8.decode_lossy(Bytes::from_array(raw))
text.split("\n").map(s => s.to_string()).filter(s => s != "").collect()
}
///| The slot ids of the panel, in order.
fn panel_order(comp : @host.ChandraCompositor) -> Array[String] {
comp.shell.loaded_modules().map(m => m.1)
}
///|
test "control socket path follows the Wayland socket's name" {
assert_eq(@host.control_socket_path("/run/user/1000", "/run/user/1000/wayland-moon-0"), "/run/user/1000/chandra/wayland-moon-0.sock")
assert_eq(@host.control_socket_path("/run/user/1000", "wayland-1"), "/run/user/1000/chandra/wayland-1.sock")
assert_eq(@host.control_socket_path("", "/tmp/wayland-moon-0"), "")
}
///|
test "ping, list and errors over the control socket" {
let (comp, path) = control_comp("basic")
assert_eq(ask(comp, path, "ping"), ["ok pong"])
let list = ask(comp, path, "list")
let n = comp.shell.loaded_modules().length()
assert_true(n > 3)
assert_eq(list.length(), n + 1)
assert_eq(list[n], "ok " + n.to_string() + " modules")
assert_true(list.iter().any(l => l.contains(" clock-digital ") && l.has_suffix("clock-digital.wasm")))
assert_eq(ask(comp, path, "bogus"), ["error unknown command 'bogus' (try: help)"])
assert_eq(ask(comp, path, "reload nope"), ["error no loaded module named 'nope'"])
assert_eq(ask(comp, path, " "), ["error empty command (try: help)"])
assert_eq(ask(comp, path, "help").last(), Some("ok"))
// Several commands on one connection get one reply each, in order.
let both = ask(comp, path, "ping\nping")
assert_eq(both, ["ok pong", "ok pong"])
comp.close()
}
///|
test "reload every module keeps the panel's order" {
let (comp, path) = control_comp("all")
let before = panel_order(comp)
let slots_before = comp.shell.loaded_modules().map(m => m.0)
let reply = ask(comp, path, "reload")
assert_eq(reply.length(), before.length() + 1)
assert_eq(reply.last(), Some("ok " + before.length().to_string() + " reloaded"))
assert_eq(panel_order(comp), before)
// Every instance is new.
for s in comp.shell.loaded_modules().map(m => m.0) {
assert_false(slots_before.contains(s))
}
// And still draws.
ignore(comp.compose_frame())
assert_true(rect_of(comp, "clock-digital").w > 0)
comp.close()
}
///|
test "reload one module by name keeps its place and its settings" {
let (comp, path) = control_comp("one")
let slot = comp.shell.slot_of("clock-digital")
comp.shell.set_module_setting(slot, "week-numbers", "on")
let before = panel_order(comp)
let others = comp.shell.loaded_modules().filter(m => m.1 != "clock-digital").map(m => m.0)
let reply = ask(comp, path, "reload clock-digital")
assert_eq(reply.length(), 2)
assert_true(reply[0].has_prefix("reloaded w"))
assert_eq(reply[1], "ok 1 reloaded")
assert_eq(panel_order(comp), before)
assert_true(comp.shell.slot_of("clock-digital") != slot)
// Only the clock was replaced.
assert_eq(comp.shell.loaded_modules().filter(m => m.1 != "clock-digital").map(m => m.0), others)
// The new instance got the saved setting: its calendar shows week numbers.
ignore(comp.compose_frame())
click_module(comp, "clock-digital", 1U)
finish_slide(comp)
assert_true(cal_texts(comp, "clock-digital").contains("Wk"))
// By slot works too.
let s2 = comp.shell.slot_of("logout")
assert_eq(ask(comp, path, "reload " + s2).last(), Some("ok 1 reloaded"))
comp.close()
}
///|
test "a module that fails to reload stays loaded and the error is reported" {
let (comp, path) = control_comp("fail")
let dir = "/tmp/chandra-control-badmod-" + @sys.getpid().to_string()
ignore(@sys.mkdir_p(dir))
let good = @sys.read_file_bytes("build/components/logout.wasm")
assert_true(good.length() > 0)
let copy = dir + "/logout.wasm"
ignore(@sys.write_file_bytes(copy, good))
assert_true(comp.shell.load_module(copy))
let before = panel_order(comp)
ignore(@sys.write_file_bytes(copy, @utf8.encode("not wasm")))
let reply = ask(comp, path, "reload " + copy)
assert_eq(reply.length(), 2)
assert_true(reply[0].has_prefix("failed w"))
assert_true(reply[0].contains("Can't load module"))
assert_eq(reply[1], "error 1 of 1 failed to reload")
assert_eq(panel_order(comp), before)
// The other modules still reload; the result says one failed.
let all = ask(comp, path, "reload")
assert_eq(all.last(), Some("error 1 of " + before.length().to_string() + " failed to reload"))
assert_eq(panel_order(comp), before)
comp.close()
}
///|
test "a second compositor leaves a live control socket alone" {
let (comp, path) = control_comp("busy")
let other = new_comp("control-busy2")
assert_false(other.start_control(path))
assert_eq(ask(comp, path, "ping"), ["ok pong"])
other.close()
comp.close()
// Closing removes the socket; a new compositor can take the path again.
let third = new_comp("control-busy3")
assert_true(third.start_control(path))
third.close()
}
+97 -12
View File
@@ -288,11 +288,19 @@ fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit {
///| Load the module file at `path` into the panel (any number of instances may be loaded). ///| 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. /// 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? { pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
match @wasm.load(path, self.tokens) { match self.try_load_path(path) {
Ok(w) => Some(w)
Err(e) => { Err(e) => {
self.say("Can't load module: " + e) self.say(e)
None 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) => { Ok(pl) => {
let id = stem(path) let id = stem(path)
let known = match self.find_module(id) { let known = match self.find_module(id) {
@@ -320,10 +328,9 @@ pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? {
if self.screen_w > 0 && !self.panel_fits() { if self.screen_w > 0 && !self.panel_fits() {
self.widgets.retain(x => x.slot != w.slot) self.widgets.retain(x => x.slot != w.slot)
pl.unload() pl.unload()
self.say("No room in the panel for " + pl.name) Err("No room in the panel for " + pl.name)
None
} else { } else {
Some(w) Ok(w)
} }
} }
} }
@@ -393,6 +400,20 @@ pub fn DesktopShell::move_slot(self : DesktopShell, slot : String, delta : Int)
///| Replace the module in `slot` with the module file at `path`, keeping its place in the panel. ///| 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 { 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 let mut idx = -1
for i = 0; i < self.widgets.length(); i = i + 1 { for i = 0; i < self.widgets.length(); i = i + 1 {
if self.widgets[i].slot == slot { if self.widgets[i].slot == slot {
@@ -400,26 +421,90 @@ pub fn DesktopShell::replace_slot(self : DesktopShell, slot : String, path : Str
} }
} }
if idx < 0 { if idx < 0 {
return false return Err("")
} }
let old = self.widgets[idx] let old = self.widgets[idx]
self.widgets.remove(idx) |> ignore self.widgets.remove(idx) |> ignore
match self.load_path(path) { match self.try_load_path(path) {
None => { Err(e) => {
self.widgets.insert(idx, old) self.widgets.insert(idx, old)
false Err(e)
} }
Some(nw) => { Ok(nw) => {
// load_path appended it; move it into the old module's place, then drop the old one. // 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.retain(x => x.slot != nw.slot)
self.widgets.insert(idx, nw) self.widgets.insert(idx, nw)
if self.drag_slot == slot {
self.drag_slot = ""
self.drag_active = false
}
old.pl.unload() old.pl.unload()
self.save_panel_config() self.save_panel_config()
true Ok(nw)
} }
} }
} }
///| Reload panel modules from disk (after `just install-session` 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). ///| Unload every module (the compositor is closing).
pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit { pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit {
for w in self.widgets { for w in self.widgets {
+9
View File
@@ -253,6 +253,15 @@ pub fn spawn(cmd : String, display : String) -> Bool {
c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0 c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0
} }
///|
extern "C" fn c_take_sigusr1() -> Int = "mp_take_sigusr1"
///| True once after the process got SIGUSR1 (reload the panel modules). The first call installs
/// the handler; a signal interrupts `wait_readable`, so an idle loop wakes for it.
pub fn take_sigusr1() -> Bool {
c_take_sigusr1() != 0
}
///| ///|
extern "C" fn c_list_desktop(dir : Bytes) -> Bytes = "mp_list_desktop" extern "C" fn c_list_desktop(dir : Bytes) -> Bytes = "mp_list_desktop"
+29
View File
@@ -347,6 +347,35 @@ void mp_sleep_ms(int32_t ms) {
} }
} }
/* SIGUSR1: reload the panel modules (compositor/host/control.mbt). The handler only sets a
* flag; it is installed without SA_RESTART, so a blocked poll() returns EINTR and the main loop
* runs a pass. */
static volatile sig_atomic_t mp_sigusr1_seen = 0;
static int mp_sigusr1_installed = 0;
static void mp_on_sigusr1(int sig) {
(void)sig;
mp_sigusr1_seen = 1;
}
MOONBIT_FFI_EXPORT
int32_t mp_take_sigusr1(void) {
if (!mp_sigusr1_installed) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = mp_on_sigusr1;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGUSR1, &sa, NULL);
mp_sigusr1_installed = 1;
}
if (mp_sigusr1_seen) {
mp_sigusr1_seen = 0;
return 1;
}
return 0;
}
MOONBIT_FFI_EXPORT MOONBIT_FFI_EXPORT
int32_t mp_getpid(void) { int32_t mp_getpid(void) {
return (int32_t)getpid(); return (int32_t)getpid();
+5
View File
@@ -198,6 +198,11 @@ pub fn spawn(cmd : String, display : String) -> Bool {
@hostsys.spawn(cmd, display) @hostsys.spawn(cmd, display)
} }
///| True once after the host process got SIGUSR1 (reload the panel modules).
pub fn take_sigusr1() -> Bool {
@hostsys.take_sigusr1()
}
///| Names of the `*.desktop` files directly in `dir`. ///| Names of the `*.desktop` files directly in `dir`.
pub fn list_desktop_files(dir : String) -> Array[String] { pub fn list_desktop_files(dir : String) -> Array[String] {
@hostsys.list_desktop_files(dir) @hostsys.list_desktop_files(dir)
+100 -17
View File
@@ -5,33 +5,116 @@ what it loaded at startup. What can be swapped without logging out:
| Part | Reload without logout? | How | | Part | Reload without logout? | How |
|---|---|---| |---|---|---|
| Panel modules (`/usr/local/share/chandra/modules/*.wasm`) | yes | Settings → Panel: remove the module, add it again | | Panel modules (`/usr/local/share/chandra/modules/*.wasm`) | yes | `just reload` / `chandra-ctl reload`, `kill -USR1`, or Settings → Panel (remove, add again) |
| `compositor.wasm` (shell, WM, portal backend) | no | restart the session | | `compositor.wasm` (shell, WM, portal backend) | no | restart the session |
| `chandra-host` (`wasmhost`) | no | restart the session | | `chandra-host` (`wasmhost`) | no | restart the session |
| `config/`, themes, assets | not checked | restart the session to be sure | | `config/`, themes, assets | not checked | restart the session to be sure |
## Panel modules The control socket and the SIGUSR1 handler are part of the compositor and host, so a session
started before they existed has neither. Log out and back in once after installing a build that
has them; from then on module reloads need no logout. Don't send SIGUSR1 to a session older than
that: without the handler the signal's default action ends the session.
Modules are loaded by path. The shell's `load_path` reads the `.wasm` from disk each time, and ## Reloading panel modules
the host's `plasmoids` `load`/`unload` instantiate and drop it (`wasmhost/bin/plasmoids.mbt`).
A module asks for this through the `LoadModule` and `UnloadInstance` requests, handled in
`DesktopShell::process_requests` (`compositor/shell/widgets.mbt`). Settings → Panel (the module
selector, with reordering) and the "Add widget" file chooser are the UI for it. The loaded set and
its order are kept in `~/.config/chandra/panel.edn`.
So after reinstalling, a module that changed is picked up by unloading and loading it again. A ```
module that imports no new host capability needs nothing else. just install-session # or: just modules, with install-session-dev
just reload # reload every panel module from disk
just reload clock-digital # just one
```
`just reload` runs `session/chandra-ctl reload`; `just install-session` also installs it as
`/usr/local/bin/chandra-ctl`:
```
chandra-ctl reload # every loaded module
chandra-ctl reload NAME # modules whose name (clock-digital), slot (w3) or path is NAME
chandra-ctl list # loaded modules in panel order: slot, module, path
chandra-ctl ping # is the compositor answering?
chandra-ctl help
```
It prints one line per module and exits 0 when everything reloaded, 1 when the compositor
reported an error (a module that failed to load, an unknown name), 2 when it could not reach a
compositor:
```
$ chandra-ctl reload
reloaded w10 launcher
...
failed w8 my-widget: Can't load module: not a wasm file
error 1 of 9 failed to reload
```
What a reload does, for each module: load the `.wasm` again from the path it was loaded from
(for an installed session, `/usr/local/share/chandra/modules`), apply its saved settings
(`:module-config` in `~/.config/chandra/state.edn`, the same values a login gives it), put the new
instance in the old one's place in the panel, then drop the old instance. A module that fails to
load is left loaded as it was, and the reply says why. The new instance gets a new slot id
(`w3` becomes `w12`) and starts fresh: an open popup closes. The module catalog is scanned again,
so a module installed since login shows up under Settings → Panel → Add. A notice above the panel
says what happened ("Reloaded 9 modules", or the error).
The reload goes through the same shell code as Settings → Panel (`DesktopShell::reload_modules`
and `replace_slot` in `compositor/shell/widgets.mbt`), so a module that imports no new host
capability needs nothing else. A module that needs a host interface the running host lacks fails
to load and stays as it was: that needs a new session.
### SIGUSR1
Sending SIGUSR1 to the host process reloads every module, like `chandra-ctl reload`:
```
pkill -USR1 -x chandra-host
```
The result goes to the session log (the host's stderr) and the notice above the panel; there is
nobody to answer. The handler is installed by the host at startup (`sys.take-sigusr1`, which the
compositor polls every pass). The signal interrupts the idle loop's wait, so it is handled
promptly.
## The control socket
The compositor listens on `$XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock`. The login
session's Wayland socket is `wayland-moon-0`, so its control socket is
`/run/user/$UID/chandra/wayland-moon-0.sock`. `$XDG_RUNTIME_DIR` is private to the user (mode
0700), so no other user can connect. Without `XDG_RUNTIME_DIR` there is no control socket (the log
says so). When the path is already answered by another running compositor (a nested `just run`
with the same socket name), the newcomer leaves it alone and has no control socket.
`chandra-ctl` finds the socket from `--socket PATH`, then `$CHANDRA_CONTROL`, then
`$WAYLAND_DISPLAY` (inside the session), and otherwise takes the only socket in
`$XDG_RUNTIME_DIR/chandra` (from a text console or ssh as the same user, with
`XDG_RUNTIME_DIR` set). With several compositors running it lists them and asks for `--socket`.
The protocol is lines of text, so anything that can talk to a unix socket can drive it, for
example `echo reload | socat - UNIX-CONNECT:$XDG_RUNTIME_DIR/chandra/wayland-moon-0.sock`. A client
writes one command per line; each reply is zero or more lines of output and then one line
starting with `ok` or `error`. Several commands may be sent on one connection.
| Command | Reply |
|---|---|
| `ping` | `ok pong` |
| `list` | `<slot> <module> <path>` per module, then `ok <n> modules` |
| `reload [NAME]` | `reloaded <new slot> <module>` or `failed <slot> <module>: <why>` per module, then `ok <n> reloaded` or `error ...` |
| `help` | the commands, then `ok` |
The compositor handles the socket in its main loop (`compositor/host/control.mbt`, from
`ChandraCompositor::step`), and the listening socket and its clients are among the fds the idle
loop waits on, so an idle desktop still sleeps (about 0.4% CPU, unchanged) and wakes for a
command. It is the same code on the MoonBit host, the Rust host and the native build.
## Not reloadable ## Not reloadable
`chandra-host` and `compositor.wasm` are read once when `chandra-session` starts them. There is no `chandra-host` and `compositor.wasm` are read once when `chandra-session` starts them. There is no
signal handler, reload request or file watcher for them. `docs/ARCHITECTURE.md` says so reload request or file watcher for them. `docs/ARCHITECTURE.md` says so ("no hot reload on file
("no hot reload on file change"), and the WM hot-swap in `docs/compositor-design.md` (replaying change"), and the WM hot-swap in `docs/compositor-design.md` (replaying `list<window-state>` into a
`list<window-state>` into a new WM component's `sync-windows`) is a design: nothing triggers it new WM component's `sync-windows`) is a design: nothing triggers it yet. Changes to the compositor,
yet. Changes to the compositor, WM, portal backend or host need a new session: log out and back WM, portal backend or host need a new session: log out and back in.
in.
## Status ## Status
Written from reading the code, not from a run: the Panel reload path has not been exercised Tested headless on both hosts (`build/wasmhost` and `host-wasm`) with the modules from
against an installed build. Correct this page if it behaves differently. `build/components`: `ping`, `list`, `reload`, `reload NAME`, a module replaced by a broken file
(reported, old instance kept), SIGUSR1, and idle CPU before and after. Tests:
`compositor/host/control_test.mbt`. Not yet run against an installed login session.
+24
View File
@@ -9,6 +9,7 @@
//! chandra-host build/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window //! chandra-host build/compositor.wasm --socket /run/user/1000/wayland-moon-0 --window
use std::ffi::CString; use std::ffi::CString;
use std::sync::atomic::AtomicBool;
use std::io::Read; use std::io::Read;
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
@@ -36,6 +37,11 @@ wasmtime::component::bindgen!({
use chandra::host::font::Glyph; use chandra::host::font::Glyph;
use chandra::host::sys::{Host, Received}; use chandra::host::sys::{Host, Received};
/// SIGUSR1 (reload the panel modules) arrived and not yet taken by sys.take-sigusr1; whether
/// its handler is installed.
static SIGUSR1_SEEN: AtomicBool = AtomicBool::new(false);
static SIGUSR1_INSTALLED: AtomicBool = AtomicBool::new(false);
#[derive(Default)] #[derive(Default)]
struct State { struct State {
/// Address of the private session bus launched apps use (started on first spawn). /// Address of the private session bus launched apps use (started on first spawn).
@@ -900,6 +906,24 @@ impl Host for State {
std::process::id() as i32 std::process::id() as i32
} }
fn take_sigusr1(&mut self) -> bool {
// The handler only sets a flag. No SA_RESTART: a blocked poll() in wait-readable returns
// EINTR, so an idle compositor runs a pass and sees the request.
extern "C" fn on_sigusr1(_: libc::c_int) {
SIGUSR1_SEEN.store(true, std::sync::atomic::Ordering::SeqCst);
}
if !SIGUSR1_INSTALLED.swap(true, std::sync::atomic::Ordering::SeqCst) {
unsafe {
let mut sa: libc::sigaction = std::mem::zeroed();
sa.sa_sigaction = on_sigusr1 as extern "C" fn(libc::c_int) as usize;
libc::sigemptyset(&mut sa.sa_mask);
sa.sa_flags = 0;
libc::sigaction(libc::SIGUSR1, &sa, std::ptr::null_mut());
}
}
SIGUSR1_SEEN.swap(false, std::sync::atomic::Ordering::SeqCst)
}
fn wall_time_field(&mut self, which: i32) -> i32 { fn wall_time_field(&mut self, which: i32) -> i32 {
unsafe { unsafe {
let t = libc::time(std::ptr::null_mut()); let t = libc::time(std::ptr::null_mut());
+3
View File
@@ -84,6 +84,9 @@ fn wasmImportHasExe(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "has-e
///| ///|
fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn" fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn"
///|
fn wasmImportTakeSigusr1() -> Int = "chandra:host/sys@0.1.0" "take-sigusr1"
///| ///|
extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] = extern "wasm" fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] =
#|(func (param i32) (param i32) (result i32) #|(func (param i32) (param i32) (result i32)
@@ -140,6 +140,11 @@ fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn wasmImportTakeSigusr1() -> Int {
abort("wasm-only host import")
}
///| ///|
fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] { fn mbt_ffi_ptr2bytes(ptr : Int, len : Int) -> FixedArray[Byte] {
abort("wasm-only") abort("wasm-only")
@@ -44,6 +44,8 @@ pub fn spawn(String, String) -> Bool
pub fn take_fd(Int32) -> Int32 pub fn take_fd(Int32) -> Int32
pub fn take_sigusr1() -> Bool
pub fn unix_accept(Int32) -> Int32 pub fn unix_accept(Int32) -> Int32
pub fn unix_connect(String) -> Int32 pub fn unix_connect(String) -> Int32
+10
View File
@@ -326,4 +326,14 @@ pub fn spawn(cmd : String, display : String) -> Bool {
return ret return ret
} }
///|
/// True once after the host process got SIGUSR1 (a request to reload the panel modules from
/// disk; see docs/reloading.md). The first call installs the handler; until then SIGUSR1 keeps
/// its default action. A signal interrupts `wait-readable`, so an idle loop wakes for it.
pub fn take_sigusr1() -> Bool {
let result : Int = wasmImportTakeSigusr1();
let ret = (result != 0)
return ret
}
+4
View File
@@ -110,6 +110,10 @@ install-session-rust: compositor-wasm host-wasm modules
install-session-native: build-release modules install-session-native: build-release modules
scripts/as-root python3 "{{justfile_directory()}}/session/install.py" --native scripts/as-root python3 "{{justfile_directory()}}/session/install.py" --native
# Reload the running session's panel modules from disk (after install-session or `just modules`), keeping their order and settings. `just reload clock-digital` reloads one. See docs/reloading.md.
reload *name:
python3 session/chandra-ctl reload {{name}}
# Remove the login session again. # Remove the login session again.
uninstall-session: uninstall-session:
scripts/as-root python3 "{{justfile_directory()}}/session/install.py" --remove scripts/as-root python3 "{{justfile_directory()}}/session/install.py" --remove
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""chandra-ctl: talk to a running Chandra compositor over its control socket.
chandra-ctl reload load every panel module again from disk
chandra-ctl reload NAME only the module(s) whose name, slot or path is NAME
chandra-ctl list the loaded panel modules: slot, module, path
chandra-ctl ping check the compositor answers
The socket is $XDG_RUNTIME_DIR/chandra/<wayland socket name>.sock (the session's is
wayland-moon-0.sock). It is found in this order: --socket PATH, $CHANDRA_CONTROL, the one for
$WAYLAND_DISPLAY, else the only socket in $XDG_RUNTIME_DIR/chandra. Prints the compositor's reply;
exits 0 when it ends in "ok", 1 on "error", 2 when no compositor could be reached.
See docs/reloading.md.
"""
import glob
import os
import socket
import sys
USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | help}"
def runtime_dir():
d = os.environ.get("XDG_RUNTIME_DIR", "")
if d:
return d
d = "/run/user/%d" % os.getuid()
return d if os.path.isdir(d) else ""
def find_socket(explicit):
if explicit:
return explicit
env = os.environ.get("CHANDRA_CONTROL", "")
if env:
return env
rt = runtime_dir()
if not rt:
sys.exit("chandra-ctl: XDG_RUNTIME_DIR is not set; pass --socket PATH")
base = os.path.join(rt, "chandra")
wd = os.environ.get("WAYLAND_DISPLAY", "")
if wd:
p = os.path.join(base, os.path.basename(wd) + ".sock")
if os.path.exists(p):
return p
socks = sorted(glob.glob(os.path.join(base, "*.sock")))
if len(socks) == 1:
return socks[0]
if not socks:
print("chandra-ctl: no control socket in %s (is a Chandra session running a build "
"with the control socket? it needs one restart after installing it)" % base,
file=sys.stderr)
sys.exit(2)
print("chandra-ctl: several compositors are running; pick one with --socket:", file=sys.stderr)
for s in socks:
print(" " + s, file=sys.stderr)
sys.exit(2)
def main(argv):
explicit = ""
quiet = False
args = []
i = 0
while i < len(argv):
a = argv[i]
if a == "--socket" and i + 1 < len(argv):
explicit = argv[i + 1]
i += 2
continue
if a.startswith("--socket="):
explicit = a.split("=", 1)[1]
elif a in ("-q", "--quiet"):
quiet = True
elif a in ("-h", "--help"):
print(__doc__.strip())
return 0
else:
args.append(a)
i += 1
if not args:
print(USAGE, file=sys.stderr)
return 2
command = " ".join(args)
if "\n" in command:
print("chandra-ctl: one command at a time", file=sys.stderr)
return 2
path = find_socket(explicit)
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(30) # reloading every module takes about a second
try:
s.connect(path)
except OSError as e:
print("chandra-ctl: can't connect to %s: %s" % (path, e.strerror or e), file=sys.stderr)
return 2
s.sendall((command + "\n").encode())
s.shutdown(socket.SHUT_WR)
data = b""
try:
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
# The reply ends with its "ok ..." / "error ..." line.
lines = data.decode("utf-8", "replace").splitlines()
if data.endswith(b"\n") and lines and (lines[-1].startswith("ok") or lines[-1].startswith("error")):
break
except socket.timeout:
print("chandra-ctl: no reply from %s" % path, file=sys.stderr)
return 2
finally:
s.close()
lines = data.decode("utf-8", "replace").splitlines()
if not lines:
print("chandra-ctl: the compositor closed the connection without a reply", file=sys.stderr)
return 2
last = lines[-1]
for l in lines:
if quiet and l is not last:
continue
print(l, file=sys.stderr if l.startswith("error") or l.startswith("failed") else sys.stdout)
return 0 if last.startswith("ok") else 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+7
View File
@@ -21,6 +21,8 @@ Installs:
/usr/local/bin/chandra (--native) release native compositor binary /usr/local/bin/chandra (--native) release native compositor binary
/usr/local/bin/chandra-session session launcher (starts the host if installed) /usr/local/bin/chandra-session session launcher (starts the host if installed)
/usr/local/bin/chandra-root run one graphical app as root in the session (run0) /usr/local/bin/chandra-root run one graphical app as root in the session (run0)
/usr/local/bin/chandra-ctl talk to the running session: `chandra-ctl reload` loads
the panel modules again (docs/reloading.md)
/usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime /usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime
/usr/local/share/chandra/modules/*.wasm the panel's wasm modules (build them first: just modules) /usr/local/share/chandra/modules/*.wasm the panel's wasm modules (build them first: just modules)
/usr/share/wayland-sessions/chandra.desktop display-manager entry /usr/share/wayland-sessions/chandra.desktop display-manager entry
@@ -45,6 +47,7 @@ targets = [
"/usr/local/bin/chandra-host", "/usr/local/bin/chandra-host",
"/usr/local/bin/chandra-session", "/usr/local/bin/chandra-session",
"/usr/local/bin/chandra-root", "/usr/local/bin/chandra-root",
"/usr/local/bin/chandra-ctl",
"/usr/share/wayland-sessions/chandra.desktop", "/usr/share/wayland-sessions/chandra.desktop",
"/usr/share/xdg-desktop-portal/portals/chandra.portal", "/usr/share/xdg-desktop-portal/portals/chandra.portal",
"/usr/share/xdg-desktop-portal/chandra-portals.conf", "/usr/share/xdg-desktop-portal/chandra-portals.conf",
@@ -106,6 +109,7 @@ if not native:
install(component, os.path.join(share, "compositor.wasm")) install(component, os.path.join(share, "compositor.wasm"))
install(os.path.join(root, "session/chandra-session"), "/usr/local/bin/chandra-session") install(os.path.join(root, "session/chandra-session"), "/usr/local/bin/chandra-session")
install(os.path.join(root, "session/chandra-root"), "/usr/local/bin/chandra-root") install(os.path.join(root, "session/chandra-root"), "/usr/local/bin/chandra-root")
install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl")
# The display-manager entry stays a real file: some managers don't follow symlinks there. # The display-manager entry stays a real file: some managers don't follow symlinks there.
put(os.path.join(root, "session/chandra.desktop"), "/usr/share/wayland-sessions/chandra.desktop", 0o644) put(os.path.join(root, "session/chandra.desktop"), "/usr/share/wayland-sessions/chandra.desktop", 0o644)
# xdg-desktop-portal reads backends only from /usr/share (or $XDG_DESKTOP_PORTAL_DIR), not # xdg-desktop-portal reads backends only from /usr/share (or $XDG_DESKTOP_PORTAL_DIR), not
@@ -130,6 +134,7 @@ dst = os.path.join(share, "modules")
if linked: if linked:
link(mods, dst) link(mods, dst)
print("done: pick 'Chandra' in the session menu; rebuild with `just compositor-wasm %s modules`" % host_build.split()[1]) print("done: pick 'Chandra' in the session menu; rebuild with `just compositor-wasm %s modules`" % host_build.split()[1])
print("(in a running session, `just modules reload` picks up rebuilt panel modules)")
sys.exit(0) sys.exit(0)
if os.path.lexists(dst): if os.path.lexists(dst):
shutil.rmtree(dst) if os.path.isdir(dst) and not os.path.islink(dst) else os.remove(dst) shutil.rmtree(dst) if os.path.isdir(dst) and not os.path.islink(dst) else os.remove(dst)
@@ -143,3 +148,5 @@ if n == 0:
sys.exit("no modules in build/components - run `just modules` first") sys.exit("no modules in build/components - run `just modules` first")
print("installed", n, "modules in", dst) print("installed", n, "modules in", dst)
print("done: pick 'Chandra' in the session menu of your login screen") print("done: pick 'Chandra' in the session menu of your login screen")
print("already in a Chandra session? `just reload` (chandra-ctl reload) picks up the new panel modules;")
print("the compositor and host themselves need a new session (docs/reloading.md)")
+1
View File
@@ -200,6 +200,7 @@ fn sys_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
}, },
), ),
("getpid", _ => s32(@sys.getpid())), ("getpid", _ => s32(@sys.getpid())),
("take-sigusr1", _ => boolean(@sys.take_sigusr1())),
("wall-time-field", a => s32(@sys.wall_time_field(a[0].to_int()))), ("wall-time-field", a => s32(@sys.wall_time_field(a[0].to_int()))),
("getenv", a => [Str(@sys.getenv(a[0].to_string()))]), ("getenv", a => [Str(@sys.getenv(a[0].to_string()))]),
("has-exe", a => boolean(@sys.has_exe(a[0].to_string()))), ("has-exe", a => boolean(@sys.has_exe(a[0].to_string()))),
+4
View File
@@ -66,6 +66,10 @@ interface sys {
has-exe: func(name: string) -> bool; has-exe: func(name: string) -> bool;
/// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. /// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`.
spawn: func(cmd: string, display: string) -> bool; spawn: func(cmd: string, display: string) -> bool;
/// True once after the host process got SIGUSR1 (a request to reload the panel modules from
/// disk; see docs/reloading.md). The first call installs the handler; until then SIGUSR1 keeps
/// its default action. A signal interrupts `wait-readable`, so an idle loop wakes for it.
take-sigusr1: func() -> bool;
} }
/// Glyph rasterisation. The component has no C rasteriser, so the host draws glyphs from TTF files /// Glyph rasterisation. The component has no C rasteriser, so the host draws glyphs from TTF files