Files
chandra/compositor/host/control.mbt
T
Claude 50149e6b99
CI / test (push) Canceled after 17m11s
Launches that fail say why: command, exit status and what it printed
V: "kwi not starting from app menu or dock". Kwi is a Flatpak, and bwrap died
before it opened a window ("Can't find source path /run/user/1000/doc/by-app/
org.kde.kwi"); Chandra forked apps and forgot them, so the failure only reached
the session log and the click did nothing visible.

Every app the Applications menu, the dock, Super+1..9 and session restore start
now runs under a small monitor (sys spawn-watch, compositor/sys/sys_stub.c): it
copies the app's output to the session log as before, keeps its last 2 KiB,
and reports how sh -c CMD exited on a socket the main loop wakes on. The shell
(compositor/shell/launch.mbt) shows a red error notice for 15 s, and logs it,
when the app exits non-zero or by a signal within 30 s, or exits 0 without ever
opening a window here (after a 2 s grace for single-instance hand-offs): the
first line says what happened, then the command and the last lines it printed,
repeats folded ("(3 times)"). Status 127/126 say "command not found" / "not
executable". Launched apps no longer inherit the compositor's fds.

chandra-ctl launch ID starts a desktop app exactly as the dock does.

Tests: compositor/host/launch_test.mbt (bwrap-style failure incl. drawn notice,
127, SIGSEGV, exit 0 without a window, an app that keeps running), unit tests
in launch.mbt. Checked end to end with build/wasmhost + compositor.wasm
headless and a Flatpak-style kwi desktop file: chandra-ctl launch org.kde.kwi
shows the notice.

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

433 lines
15 KiB
MoonBit

///| The control socket: lets scripts outside the session reload panel modules (after
/// `just install` 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",
"shortcut ID do what shortcut ID does (launcher, overview, show-desktop, ...)",
"kiosk [lock|unlock|status] kiosk mode (--kiosk): lock it down or unlock it for admin work",
"launch ID start desktop app ID (e.g. org.kde.kwi) as the dock does; a failed start shows its notice",
"windows each window: frame, layout, box, shadow, size limits; and what is under the pointer",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "),
"auth-status the password dialog's agent: running, registered, or why not",
"ok",
],
true,
)
"auth-demo" => {
if words.length() > 2 {
return (["error usage: auth-demo [" + @polkit.demo_modes.join("|") + "]"], false)
}
match self.start_auth_demo(if words.length() == 2 { words[1] } else { "" }) {
Ok(_) => (["ok the demo dialog opens; the password is \"" + @polkit.demo_password + "\""], true)
Err(why) => (["error " + why], false)
}
}
"auth-status" => {
let out : Array[String] = []
match self.auth_agent {
Some(l) => out.push(if l.ready { "agent: registered with polkit" } else { "agent: started, waiting for polkit" })
None =>
out.push(
if self.fallback_agent_started {
"agent: off in Settings; another polkit agent was started"
} else {
"agent: not running"
},
)
}
match self.auth_notice {
Some(n) => out.push("notice: " + n.text)
None => ()
}
match self.auth {
Some(ui) => out.push("dialog: up (" + @polkit.phase_name(ui.view.phase) + ")")
None => out.push("dialog: not shown")
}
out.push("ok")
(out, 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)
}
"launch" => {
if words.length() != 2 {
return (["error usage: launch DESKTOP-ID"], false)
}
match self.shell.command_for(words[1]) {
Some(cmd) =>
if self.shell.start_app(words[1], cmd) {
(["ok started: " + cmd + " (a failed start shows a notice and goes to the session log)"], true)
} else {
(["error could not create a process for: " + cmd], false)
}
None => (["error no installed .desktop file has the id " + words[1]], false)
}
}
"shortcut" => {
if words.length() != 2 {
return (["error usage: shortcut ID"], false)
}
for d in @shell.shortcut_table {
if d.id == words[1] {
if d.action == SwitchWindows {
return (["error switch-windows needs its keys held"], false)
}
self.run_shortcut(d.action)
self.damage.mark_full()
return (["ok " + d.id], true)
}
}
(["error no shortcut '" + words[1] + "'"], false)
}
"kiosk" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
match (self.kiosk, arg) {
(None, _) => (["error not in kiosk mode (start with --kiosk)"], false)
(Some(k), "status") =>
(["ok " + (if k.locked { "locked" } else { "unlocked" }) + (if k.hybrid { " hybrid" } else { "" }) + " starts=" + k.starts.to_string() + " cmd=" + k.cmd], true)
(Some(_), "lock") => {
ignore(self.set_kiosk_locked(true))
(["ok locked"], true)
}
(Some(_), "unlock") => {
ignore(self.set_kiosk_locked(false))
(["ok unlocked"], true)
}
_ => (["error usage: kiosk [lock|unlock|status]"], false)
}
}
"windows" => {
let out = self.window_report()
out.push("ok " + self.windows.length().to_string() + " windows")
(out, true)
}
other => (["error unknown command '" + other + "' (try: help)"], false)
}
}
///| `chandra-ctl windows`: how Chandra sees each window, for "this window won't resize/move"
/// reports. One line per window, top of the stack first, then what is under the pointer.
fn ChandraCompositor::window_report(self : ChandraCompositor) -> Array[String] {
let out : Array[String] = []
let order = self.wm.stacking_order()
let mut i = order.length() - 1
while i >= 0 {
let id = order[i]
i = i - 1
match self.windows.get(id) {
Some(w) => {
let r = w.client_rect()
let sb = StringBuilder()
sb.write_string(id.to_string() + " " + (if w.app_id == "" { "-" } else { w.app_id }))
sb.write_string(if w.csd { " client-frame" } else { " chandra-frame" })
match self.wm.windows.get(id) {
Some(rec) => {
sb.write_string(
if rec.fullscreen {
" fullscreen"
} else if rec.maximized {
" maximized"
} else if rec.is_floating {
" floating"
} else {
" tiled"
},
)
if rec.minimized {
sb.write_string(" minimized")
}
sb.write_string(" min=" + rec.min_size.w.to_string() + "x" + rec.min_size.h.to_string())
match rec.max_size {
Some(m) => sb.write_string(" max=" + m.w.to_string() + "x" + m.h.to_string())
None => ()
}
}
None => sb.write_string(" unmanaged")
}
sb.write_string(" box=" + r.x.to_string() + "," + r.y.to_string() + "+" + r.w.to_string() + "x" + r.h.to_string())
match w.surface {
Some(s) => {
sb.write_string(" buffer=" + s.width.to_string() + "x" + s.height.to_string())
if w.csd {
// The client's shadow on each side: left, top, right, bottom.
sb.write_string(
" shadow=" + w.geo_x.to_string() + "," + w.geo_y.to_string() + "," +
(s.width - w.geo_x - r.w).to_string() + "," + (s.height - w.geo_y - r.h).to_string(),
)
}
}
None => sb.write_string(" no-buffer")
}
if w.subs.length() > 0 {
sb.write_string(" subsurfaces=" + w.subs.length().to_string())
}
sb.write_string(" \"" + w.title + "\"")
out.push(sb.to_string())
}
None => ()
}
}
let x = self.ptr_x.to_int()
let y = self.ptr_y.to_int()
let under = if self.popup_at(x, y) is Some(_) {
"a popup menu"
} else if self.shell.hit(x, y) {
"the panel"
} else {
match self.resize_at(x, y) {
Some((wid, mode)) => "resize grip " + drag_mode_name(mode) + " of " + wid.to_string()
None =>
match self.window_at(x, y) {
Some((wid, true)) => "window " + wid.to_string()
Some((wid, false)) => "title bar of " + wid.to_string()
None => if self.handle_at(x, y) is Some(_) { "a tiling divider" } else { "the desktop" }
}
}
}
out.push("pointer " + x.to_string() + "," + y.to_string() + " over " + under)
out
}
///|
fn drag_mode_name(m : @wm.DragMode) -> String {
match m {
ResizeN => "top"
ResizeS => "bottom"
ResizeW => "left"
ResizeE => "right"
ResizeNW => "top-left"
ResizeNE => "top-right"
ResizeSW => "bottom-left"
ResizeSE => "bottom-right"
_ => "move"
}
}