Files
chandra/compositor/host/control.mbt
T
nandi 1c954aa657
CI / test (push) Failing after 52s
Add a camera app: photo and video on libcamera or V4L2
- Discover libcamera cameras, falling back to V4L2; label them Back, Front or External and pick the rear sensor first
- Photo mode: JPEG saves to ~/Pictures/Camera, with an optional high-res still capture
- Video mode: H.264 MP4 recording through ffmpeg, saved to ~/Videos/Camera
- Rear torch LED toggle via sysfs, falling back to logind SetBrightness
- GTK3 + Cairo Wayland UI with a viewfinder, timer, grid, camera switch and gallery view
- Add the desktop entry, icon and camera tests
2026-11-28 12:22:36 -08:00

589 lines
20 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",
"screenshot [PATH] save a full-screen PNG directly (without opening the editor)",
"rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display",
"screen [on|off|toggle|status] blank or wake the display",
"brightness [PCT|status] read or set display backlight percent (5..100)",
"settings [TAB] open Settings popup (session, desktop, panel, power, shortcuts, apps)",
"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)
}
"screenshot" => {
if words.length() > 2 {
return (["error usage: screenshot [PATH]"], false)
}
match self.capture_png() {
None => (["error could not capture screen"], false)
Some(png) =>
if words.length() == 2 {
let path = words[1]
if @sys.write_file_bytes(path, png) == 0 {
(["ok " + path], true)
} else {
(["error could not write " + path], false)
}
} else {
let dir = if self.shot_dir.length() > 0 {
self.shot_dir
} else {
pictures_dir() + "/Screenshots"
}
let path = save_png(dir, png)
if path != "" {
(["ok " + path], true)
} else {
(["error could not save screenshot in " + dir], false)
}
}
}
}
"rotate" => {
let arg = if words.length() >= 2 { words[1] } else { "cw" }
if words.length() > 2 {
return (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
match arg {
"status" => (["ok " + (self.rotation * 90).to_string() + " " + self.output_w.to_string() + "x" + self.output_h.to_string()], true)
"cw" | "right" => {
self.rotate_cw()
(["ok rotate cw"], true)
}
"ccw" | "left" => {
self.rotate_ccw()
(["ok rotate ccw"], true)
}
"flip" => {
self.rotate_flip()
(["ok rotate flip"], true)
}
"0" | "normal" => {
self.request_rotation(0)
(["ok rotate 0"], true)
}
"90" | "1" => {
self.request_rotation(1)
(["ok rotate 90"], true)
}
"180" | "2" => {
self.request_rotation(2)
(["ok rotate 180"], true)
}
"270" | "3" => {
self.request_rotation(3)
(["ok rotate 270"], true)
}
_ => (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
}
"screen" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
if words.length() > 2 {
return (["error usage: screen [on|off|toggle|status]"], false)
}
match arg {
"status" => (["ok " + (if self.screen_off || self.manual_screen_off { "off" } else { "on" })], true)
"off" => {
self.set_manual_screen_off(true)
(["ok off"], true)
}
"on" => {
self.set_manual_screen_off(false)
(["ok on"], true)
}
"toggle" => {
let next_off = !(self.screen_off || self.manual_screen_off)
self.set_manual_screen_off(next_off)
(["ok " + (if next_off { "off" } else { "on" })], true)
}
_ => (["error usage: screen [on|off|toggle|status]"], false)
}
}
"brightness" => {
let arg = if words.length() >= 2 { words[1] } else { "status" }
if words.length() > 2 {
return (["error usage: brightness [PCT|status]"], false)
}
if arg == "status" {
let cur = @shell.read_backlight_percent()
if cur < 0 {
(["error no backlight"], false)
} else {
(["ok " + cur.to_string()], true)
}
} else {
let mut val = 0
let mut valid = arg.length() > 0
for ch in arg {
let c = ch.to_int()
if c >= 48 && c <= 57 {
val = val * 10 + (c - 48)
} else {
valid = false
break
}
}
if !valid {
return (["error usage: brightness [PCT|status]"], false)
}
let next = self.shell.set_brightness(val)
if next < 0 {
(["error no backlight"], false)
} else {
(["ok " + next.to_string()], true)
}
}
}
"settings" => {
let arg = if words.length() >= 2 { words[1] } else { "session" }
if words.length() > 2 {
return (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false)
}
let tab : @shell.SettingsTab? = match arg {
"session" => Some(Session)
"desktop" => Some(Desktop)
"panel" => Some(Panel)
"power" => Some(Power)
"shortcuts" => Some(Shortcuts)
"apps" => Some(Apps)
_ => None
}
match tab {
None => (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false)
Some(t) =>
if self.shell.open_settings(t) {
self.frame_changed = true
self.damage.mark_full()
(["ok " + arg], true)
} else {
(["error settings module not loaded"], false)
}
}
}
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"
}
}