Files
chandra/compositor/host/control.mbt
T
Claude 4437a3a576
CI / test (push) Failing after 16s
Rename just install-session to just install
install-session(-dev/-rust/-native) become install(-dev/-rust/-native) and
uninstall-session becomes uninstall, so installing is just `just install`.
The old names stay as hidden recipes that print a one-line note and run the
new one. Docs, scripts and comments now point at the new names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hj5zRiffcgWaggHdjv
2026-11-25 22:17:05 +00:00

243 lines
7.8 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",
"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)
}
}