diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index b13ce52..a5d5975 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -358,6 +358,7 @@ pub fn run(args : Array[String]) -> Int { fds.push(pfd) } fds.append(comp.auth_fds()) // polkit asking for a password, and its helper + fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit ignore(@sys.wait_readable(fds, comp.wake_timeout(idle.timeout()))) } else { // Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work. @@ -378,6 +379,7 @@ pub fn run(args : Array[String]) -> Int { let wait_fds = comp.server.wait_fds() wait_fds.append(comp.control_fds()) // chandra-ctl wait_fds.append(comp.auth_fds()) // polkit asking for a password, and its helper + wait_fds.append(comp.shell.launch_fds()) // launched apps' monitors reporting an exit match nested { Some(n) => { if !n.poll() { diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index 812e444..a3e123b 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -599,6 +599,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit { self.auth_tick() self.face_window_tick() self.control_tick() + self.shell.launch_tick() let events = self.server.poll_events() for ev in events { match ev { @@ -910,6 +911,8 @@ pub fn ChandraCompositor::wake_timeout(self : ChandraCompositor, idle_ms : Int) let d = self.shell.desktop_wake_ms(now) let g = self.shell.gamelib_wake_ms(now) let d = if g >= 0 && (d < 0 || g < d) { g } else { d } + let l = self.shell.launch_wake_ms(now) + let d = if l >= 0 && (d < 0 || l < d) { l } else { d } if d >= 0 && d < idle_ms { d } else { diff --git a/compositor/host/control.mbt b/compositor/host/control.mbt index d6ca4d5..c0d1d28 100644 --- a/compositor/host/control.mbt +++ b/compositor/host/control.mbt @@ -210,6 +210,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin "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(", "), @@ -276,6 +277,20 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin } (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) diff --git a/compositor/host/launch_test.mbt b/compositor/host/launch_test.mbt new file mode 100644 index 0000000..eb45e66 --- /dev/null +++ b/compositor/host/launch_test.mbt @@ -0,0 +1,86 @@ +///| Watched launches (compositor/shell/launch.mbt): an app that fails to start shows an error +/// notice with the command, its exit status and the last lines it printed. + +///| Step `comp` until the shell shows an error notice or `ms` pass. +fn wait_notice(comp : @host.ChandraCompositor, ms : Int) -> Array[String] { + let t0 = @sys.monotonic_ms() + while (@sys.monotonic_ms() - t0).to_int() < ms { + comp.step() + if comp.shell.notice_frames > 0 && comp.shell.notice_lines.length() > 0 { + return comp.shell.notice_lines + } + @sys.sleep_ms(20) + } + [] +} + +///| +test "a launch that fails shows the command, the exit status and what it printed" { + let comp = new_comp("launch-fail") + // What V's Flatpak kwi did: bwrap can't set up the sandbox, prints why and exits 1. + let cmd = "echo starting; for i in 1 2 3; do echo \"bwrap: Can't find source path /run/user/1000/doc/by-app/org.kde.kwi: No such file or directory\" >&2; done; exit 1" + assert_true(comp.shell.start_app("org.kde.kwi", cmd)) + assert_eq(comp.shell.launch_fds().length(), 1) + let lines = wait_notice(comp, 5000) + assert_true(lines.length() >= 3) + assert_true(lines[0].has_prefix("Could not start org.kde.kwi: exited with status 1 after")) + assert_eq(lines[1], "Command: " + cmd) + assert_eq(lines[2], "starting") + assert_eq( + lines[3], + "bwrap: Can't find source path /run/user/1000/doc/by-app/org.kde.kwi: No such file or directory (3 times)", + ) + // Drawn above the panel: a red edge at the notice's left side. + let f = comp.compose_frame() + let mut red = 0 + for y = 0; y < 720; y = y + 1 { + for x = 0; x < 1280; x = x + 1 { + let i = (y * f.width + x) * 4 + if f.data[i].to_int() > 200 && f.data[i + 1].to_int() < 100 && f.data[i + 2].to_int() < 100 { + red = red + 1 + } + } + } + assert_true(red > 100) + ignore(@sys.write_file_bytes("/tmp/chandra-launch-notice.png", @renderer.encode_png(f))) + assert_eq(comp.shell.launch_fds().length(), 0) +} + +///| +test "a command that isn't installed says so" { + let comp = new_comp("launch-127") + assert_true(comp.shell.start_app("nothere", "chandra-no-such-program-xyz --flag")) + let lines = wait_notice(comp, 5000) + assert_eq(lines[0], "Could not start nothere: failed: command not found (status 127)") + assert_true(lines[2].contains("chandra-no-such-program-xyz")) +} + +///| +test "an app killed by a signal while starting says which" { + let comp = new_comp("launch-sig") + assert_true(comp.shell.start_app("crashy", "kill -SEGV $$")) + let lines = wait_notice(comp, 5000) + assert_true(lines[0].has_prefix("Could not start crashy: was killed by SIGSEGV after")) + assert_eq(lines[2], "It printed nothing. More in ~/.local/state/chandra/session.log") +} + +///| +test "an app that exits 0 without ever opening a window is reported, after a grace period" { + let comp = new_comp("launch-nowin") + assert_true(comp.shell.start_app("handoff", "echo 'handed the launch to the running instance'")) + let t0 = @sys.monotonic_ms() + let lines = wait_notice(comp, 6000) + assert_true((@sys.monotonic_ms() - t0).to_int() >= 1900) // waited for a window first + assert_true(lines[0].has_prefix("Could not start handoff: exited (status 0) after")) + assert_true(lines[0].has_suffix("without opening a window")) + assert_eq(lines[2], "handed the launch to the running instance") +} + +///| +test "an app that keeps running is not reported, and its output still reaches the log" { + let comp = new_comp("launch-ok") + assert_true(comp.shell.start_app("stays", "echo up; sleep 3")) + let lines = wait_notice(comp, 1500) + assert_eq(lines, []) + assert_eq(comp.shell.launch_fds().length(), 1) +} diff --git a/compositor/shell/launch.mbt b/compositor/shell/launch.mbt new file mode 100644 index 0000000..cbe9328 --- /dev/null +++ b/compositor/shell/launch.mbt @@ -0,0 +1,303 @@ +///| Watched app launches. Every app the launcher, the dock, Super+1..9 or session restore starts +/// runs under a small monitor (`@sys.spawn_watch`) that reports how it exited. An app that fails +/// to start never fails quietly: when it exits with an error (or a signal) within +/// `launch_watch_ms`, or exits cleanly without ever showing a window, the shell shows a notice +/// with the command, the exit status and the last lines it printed, and logs the same. + +///| How long after starting an app its exit counts as a failed launch (later exits are the user +/// quitting it, or a crash the session log keeps). +let launch_watch_ms : UInt64 = 30000UL + +///| After an app exits 0 without a window, how long to wait for one (an app that hands the launch +/// to its running instance opens the window from there, a moment later). +let launch_grace_ms : UInt64 = 2000UL + +///| +struct LaunchWatch { + /// Report socket from the monitor (-1 once closed). + mut fd : Int + id : String + name : String + command : String + started : UInt64 + /// Whether the app already had a window here when it was started. + had_window : Bool + buf : Array[Byte] + /// Parsed report, once the pipe hit EOF. + mut report : LaunchReport? + /// When to check (exited 0 without a window yet) whether a window has appeared since. + mut check_at : UInt64 +} + +///| How a launched command ended, as the monitor reported it. +pub(all) struct LaunchReport { + /// "exit" or "signal" ("" when the report was unreadable). + how : String + /// Exit status or signal number. + code : Int + /// Milliseconds it ran. + ran_ms : Int + /// The end of what it printed (stdout and stderr). + output : String +} derive(Eq, Debug) + +///| Parse the monitor's report: "exit CODE MS\n" or "signal NUM MS\n", then the output tail. +pub fn parse_launch_report(data : Bytes) -> LaunchReport { + let text = @utf8.decode_lossy(data) + let (head, rest) = match text.find("\n") { + Some(i) => (text[:i].to_string(), text[i + 1:].to_string()) + None => (text, "") + } + let parts : Array[String] = head.split(" ").map(x => x.to_string()).collect() + if parts.length() != 3 || (parts[0] != "exit" && parts[0] != "signal") { + return { how: "", code: -1, ran_ms: 0, output: text } + } + let num = fn(s : String) { + let mut n = 0 + for c in s { + if c < '0' || c > '9' { + return -1 + } + n = n * 10 + (c.to_int() - '0'.to_int()) + } + n + } + { how: parts[0], code: num(parts[1]), ran_ms: num(parts[2]), output: rest } +} + +///| The last `max` meaningful lines of `output`: blank lines dropped, a line repeated right after +/// itself shown once with "(N times)". +pub fn output_tail(output : String, max : Int) -> Array[String] { + let lines : Array[(String, Int)] = [] + for raw in output.split("\n") { + let l = raw.trim(chars=" \t\r").to_string() + if l.length() == 0 { + continue + } + match lines.last() { + Some((prev, n)) if prev == l => lines[lines.length() - 1] = (prev, n + 1) + _ => lines.push((l, 1)) + } + } + let start = if lines.length() > max { lines.length() - max } else { 0 } + let out : Array[String] = [] + for i = start; i < lines.length(); i = i + 1 { + let (l, n) = lines[i] + out.push(if n > 1 { l + " (" + n.to_string() + " times)" } else { l }) + } + out +} + +///| Signal names for the ones apps die of. +fn signal_name(n : Int) -> String { + match n { + 1 => "SIGHUP" + 2 => "SIGINT" + 4 => "SIGILL" + 5 => "SIGTRAP" + 6 => "SIGABRT" + 7 => "SIGBUS" + 8 => "SIGFPE" + 9 => "SIGKILL" + 11 => "SIGSEGV" + 13 => "SIGPIPE" + 15 => "SIGTERM" + _ => "signal " + n.to_string() + } +} + +///| The notice for a failed launch of `name` (`command`), or None when `r` is not a failure. +/// `window` says whether the app has a window here now. +pub fn launch_failure(name : String, command : String, r : LaunchReport, window : Bool) -> Array[String]? { + let secs = fn(ms : Int) { + if ms < 1000 { + ms.to_string() + " ms" + } else { + (ms / 1000).to_string() + "." + (ms % 1000 / 100).to_string() + " s" + } + } + let what = match r.how { + "exit" if r.code == 0 => + if window { + return None + } else { + "exited (status 0) after " + secs(r.ran_ms) + " without opening a window" + } + "exit" if r.code == 127 => "failed: command not found (status 127)" + "exit" if r.code == 126 => "failed: command not executable (status 126)" + "exit" => "exited with status " + r.code.to_string() + " after " + secs(r.ran_ms) + "signal" => "was killed by " + signal_name(r.code) + " after " + secs(r.ran_ms) + _ => "ended without a report from its monitor" + } + let lines = ["Could not start " + name + ": " + what, "Command: " + command] + let tail = output_tail(r.output, 4) + if tail.length() == 0 { + lines.push("It printed nothing. More in ~/.local/state/chandra/session.log") + } else { + lines.append(tail) + } + Some(lines) +} + +///| Whether some window here belongs to desktop app `id`. +fn DesktopShell::has_window_for(self : DesktopShell, id : String) -> Bool { + self.win_list.iter().any(e => resolve_app_id(e.app_id, self.exec, self.wm_classes) == Some(id)) +} + +///| The catalog name of app `id` (its id when it has none). +fn DesktopShell::app_name(self : DesktopShell, id : String) -> String { + for a in self.apps { + if a.id == id { + return a.name + } + } + id +} + +///| Start desktop app `id` with `command`, watched. False (with a notice) when nothing started. +pub fn DesktopShell::start_app(self : DesktopShell, id : String, command : String) -> Bool { + let name = self.app_name(id) + let fd = @sys.spawn_watch(command, self.display) + if fd < 0 { + self.say_error(["Could not start " + name + ": the process could not be created", "Command: " + command]) + @sys.log("chandra: launch failed: " + name + " (" + id + "): could not create a process for `" + command + "`") + return false + } + @sys.log("chandra: launching " + name + " (" + id + "): " + command) + self.launches.push({ + fd, + id, + name, + command, + started: @sys.monotonic_ms(), + had_window: self.has_window_for(id), + buf: [], + report: None, + check_at: 0UL, + }) + true +} + +///| Report sockets still open, for the main loop to wake on. +pub fn DesktopShell::launch_fds(self : DesktopShell) -> Array[Int] { + self.launches.filter(l => l.fd >= 0).map(l => l.fd) +} + +///| Milliseconds until a launch needs looking at again (-1: nothing pending). +pub fn DesktopShell::launch_wake_ms(self : DesktopShell, now : UInt64) -> Int { + let mut best = -1 + for l in self.launches { + let at = if l.check_at > 0UL { l.check_at } else if l.fd >= 0 { l.started + launch_watch_ms } else { now } + let d = if at <= now { 0 } else { (at - now).to_int() } + if best < 0 || d < best { + best = d + } + } + best +} + +///| Read the monitors' reports and act on them: a notice for each failed launch. +pub fn DesktopShell::launch_tick(self : DesktopShell) -> Unit { + if self.launches.length() == 0 { + return + } + let now = @sys.monotonic_ms() + let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00') + for l in self.launches { + if l.fd < 0 { + continue + } + let mut eof = false + while @sys.poll_read(l.fd, 0) > 0 { + let (n, extra) = @sys.recvmsg_fd(l.fd, buf, buf.length()) + if extra >= 0 { + @sys.close_fd(extra) + } + if n == -1 { + break + } + if n <= 0 { + eof = true + break + } + for i = 0; i < n; i = i + 1 { + l.buf.push(buf[i]) + } + } + if eof { + @sys.close_fd(l.fd) + l.fd = -1 + let r = parse_launch_report(Bytes::from_array(l.buf)) + l.report = Some(r) + let ran : UInt64 = if r.ran_ms > 0 { r.ran_ms.to_uint64() } else { 0UL } + if ran > launch_watch_ms { + // Ran a while: the user quit it, or it crashed; the monitor logged how. + l.check_at = 0UL + } else if r.how == "exit" && r.code == 0 && !l.had_window { + l.check_at = now + launch_grace_ms + } else { + l.check_at = now + } + } else if now - l.started > launch_watch_ms { + // Running past the watch window: it started. Stop listening (the monitor keeps logging). + @sys.close_fd(l.fd) + l.fd = -1 + l.check_at = 0UL + } + } + let keep : Array[LaunchWatch] = [] + for l in self.launches { + if l.fd >= 0 { + keep.push(l) + continue + } + match l.report { + Some(r) if l.check_at > 0UL => + if l.check_at > now { + keep.push(l) + } else { + let window = l.had_window || self.has_window_for(l.id) + match launch_failure(l.name, l.command, r, window) { + Some(lines) => { + self.say_error(lines) + @sys.log("chandra: launch failed: " + l.id + ": " + lines.join("\n ")) + } + None => () + } + } + _ => () + } + } + self.launches.clear() + self.launches.append(keep) +} + +///| +test "parse_launch_report reads the monitor's report" { + let r = parse_launch_report(b"exit 1 230\nbwrap: no\n") + assert_eq(r, { how: "exit", code: 1, ran_ms: 230, output: "bwrap: no\n" }) + let s = parse_launch_report(b"signal 11 5\n") + assert_eq(s.how, "signal") + assert_eq(s.code, 11) + assert_eq(parse_launch_report(b"").how, "") +} + +///| +test "output_tail keeps the last lines and folds repeats" { + assert_eq(output_tail("a\n\nb\nb\nb\nc\n", 2), ["b (3 times)", "c"]) + assert_eq(output_tail("", 4), []) +} + +///| +test "launch_failure: a clean exit is fine once the app has a window" { + let r = { how: "exit", code: 0, ran_ms: 40, output: "" } + assert_eq(launch_failure("Kwi", "kwi", r, true), None) + match launch_failure("Kwi", "kwi", r, false) { + Some(l) => assert_eq(l[0], "Could not start Kwi: exited (status 0) after 40 ms without opening a window") + None => fail("expected a notice") + } + match launch_failure("Kwi", "kwi", { how: "exit", code: 2, ran_ms: 1500, output: "x" }, true) { + Some(l) => assert_eq(l, ["Could not start Kwi: exited with status 2 after 1.5 s", "Command: kwi", "x"]) + None => fail("expected a notice") + } +} diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index f0aeaf4..9e1afba 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -347,6 +347,11 @@ pub(all) struct DesktopShell { mut notice : String mut notice_frames : Int mut notice_start : Int + /// A multi-line error notice (`say_error`): its lines, shown for `notice_secs`. + mut notice_lines : Array[String] + mut notice_secs : Int + /// Apps started and still watched for a failed launch (launch.mbt). + launches : Array[LaunchWatch] /// Right-click menu. mut menu_open : Bool mut menu_rect : @scene.Rect @@ -504,6 +509,9 @@ pub fn DesktopShell::new(display : String) -> DesktopShell { notice: "", notice_frames: 0, notice_start: 0, + notice_lines: [], + notice_secs: 4, + launches: [], menu_open: false, menu_rect: zero, menu_title: "", @@ -1131,11 +1139,35 @@ pub fn DesktopShell::render( self.menu_rect = { x: 0, y: 0, w: 0, h: 0 } } if self.notice_frames > 0 { - if (wall_secs() - self.notice_start + 86400) % 86400 >= 4 { + if (wall_secs() - self.notice_start + 86400) % 86400 >= self.notice_secs { self.notice_frames = 0 } } - if self.notice_frames > 0 { + if self.notice_frames > 0 && self.notice_lines.length() > 0 { + // An error: its lines in a box above the panel's right end, a red edge on the left. + let rows = notice_rows(self.notice_lines, 110) + let fs = tokens.font_size.reinterpret_as_int() - 3 + let lh = fs + 6 + let mut longest = 0 + for r in rows { + longest = if r.length() > longest { r.length() } else { longest } + } + let nw = longest * 7 + 32 + let nw = if nw > w - 24 { w - 24 } else { nw } + let nh = rows.length() * lh + 16 + let red = @ui.color(229, 72, 77, 255) + let ops = [ + @ui.fill_rect(@ui.rect(0, 0, nw, nh), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()), + @ui.stroke_rect(@ui.rect(0, 0, nw, nh), red, radius=tokens.radius.reinterpret_as_int()), + @ui.fill_rect(@ui.rect(0, 0, 4, nh), red), + ] + for i, r in rows { + ops.push( + @ui.text(16, 8 + i * lh + lh / 2, r, fs, if i == 0 { red } else { tokens.palette.foreground }), + ) + } + translate(ops, w - nw - 12, self.panel_rect.y - nh - 12, panel_ops) + } else if self.notice_frames > 0 { let nw = self.notice.length() * 7 + 24 translate( [ diff --git a/compositor/shell/state.mbt b/compositor/shell/state.mbt index c147c49..6a666a5 100644 --- a/compositor/shell/state.mbt +++ b/compositor/shell/state.mbt @@ -583,7 +583,7 @@ pub fn DesktopShell::launch_app_id(self : DesktopShell, app_id : String) -> Bool match resolve_app_id(app_id, self.exec, self.wm_classes) { Some(id) => match self.command_for(id) { - Some(cmd) => @sys.spawn(cmd, self.display) + Some(cmd) => self.start_app(id, cmd) None => false } None => false diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt index ec8626b..ef1933e 100644 --- a/compositor/shell/widgets.mbt +++ b/compositor/shell/widgets.mbt @@ -215,10 +215,44 @@ fn DesktopShell::panel_fits(self : DesktopShell) -> Bool { ///| Show a short message above the panel for a few seconds. pub fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit { self.notice = msg + self.notice_lines = [] + self.notice_secs = 4 self.notice_frames = 1 self.notice_start = wall_secs() } +///| Show an error notice: the first line is what went wrong, the rest the details. It stays 15 +/// seconds, and the same lines go to the session log. +pub fn DesktopShell::say_error(self : DesktopShell, lines : Array[String]) -> Unit { + self.notice = lines.get(0).unwrap_or("") + self.notice_lines = lines + self.notice_secs = 15 + self.notice_frames = 1 + self.notice_start = wall_secs() +} + +///| The notice's lines as drawn: long ones wrapped at `max` characters, at most 10. +fn notice_rows(lines : Array[String], max : Int) -> Array[String] { + let out : Array[String] = [] + for l in lines { + let chars = l.to_array() + let mut i = 0 + while i < chars.length() || i == 0 { + let end = if i + max < chars.length() { i + max } else { chars.length() } + out.push(String::from_array(chars[i:end].to_array())) + i = end + if end == chars.length() { + break + } + } + } + if out.length() > 10 { + out[out.length() - 10:].to_array() + } else { + out + } +} + ///| Seconds since local midnight (wall clock). fn wall_secs() -> Int { @sys.wall_time_field(3) * 3600 + @sys.wall_time_field(4) * 60 + @sys.wall_time_field(5) @@ -829,14 +863,15 @@ pub fn DesktopShell::set_power_timeouts(self : DesktopShell, screen_off : Int, s ///| Start the catalog app `id` (a desktop file id) and remember it as the latest launch. fn DesktopShell::launch_catalog_app(self : DesktopShell, id : String) -> Unit { match self.command_for(id) { - Some(bin) => - if @sys.spawn(bin, self.display) { + Some(cmd) => + if self.start_app(id, cmd) { self.note_recent(id) self.apps_dirty = true - } else { - self.say("Could not start " + bin) } - None => self.say("No executable for " + id) + None => { + self.say_error(["Could not start " + id + ": no installed .desktop file has that id"]) + @sys.log("chandra: launch failed: no desktop file for " + id) + } } } diff --git a/compositor/sys/sys_native.mbt b/compositor/sys/sys_native.mbt index 698e205..8757b3c 100644 --- a/compositor/sys/sys_native.mbt +++ b/compositor/sys/sys_native.mbt @@ -359,3 +359,14 @@ pub fn surface_thumbnail(_id : UInt, _w : Int, _h : Int, _reuse : UInt) -> UInt pub fn frame_memfd() -> Int { -1 } + +///| +extern "C" fn c_spawn_watch(cmd : Bytes, display : Bytes) -> Int = "mp_spawn_watch" + +///| Launch `cmd` like `spawn`, watched: returns a non-blocking socket (-1 when nothing could +/// start) that reports, once `sh -c cmd` exits, "exit CODE MS\n" or "signal NUM MS\n" (MS = how +/// long it ran) followed by the last 2 KiB of its output, then closes. Its output still goes to +/// our stderr (the session log). See `@shell` launch.mbt. +pub fn spawn_watch(cmd : String, display : String) -> Int { + c_spawn_watch(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) +} diff --git a/compositor/sys/sys_stub.c b/compositor/sys/sys_stub.c index 98dfaa5..c0fa551 100644 --- a/compositor/sys/sys_stub.c +++ b/compositor/sys/sys_stub.c @@ -464,6 +464,27 @@ static void start_private_bus(void) { } } +/* The environment of a launched app (in the forked child): our Wayland socket, and the + * private bus when nested (see start_private_bus). */ +static void app_env(const char *cmd, const char *display) { + /* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */ + signal(SIGCHLD, SIG_DFL); + signal(SIGPIPE, SIG_DFL); + /* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak + * on the real session bus, so they keep it; the sandbox isolates their instances anyway. */ + if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1); + setenv("WAYLAND_DISPLAY", display, 1); + unsetenv("DISPLAY"); + /* Make toolkits pick our Wayland socket, not X11 or the host session. */ + setenv("XDG_SESSION_TYPE", "wayland", 1); + setenv("QT_QPA_PLATFORM", "wayland", 1); + setenv("GDK_BACKEND", "wayland", 1); + setenv("SDL_VIDEODRIVER", "wayland", 1); + setenv("MOZ_ENABLE_WAYLAND", "1", 1); + setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1); + setenv("CLUTTER_BACKEND", "wayland", 1); +} + /* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */ MOONBIT_FFI_EXPORT int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { @@ -477,28 +498,137 @@ int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { if (pid < 0) return -1; if (pid == 0) { setsid(); - /* SIG_IGN survives exec; apps (e.g. terminals that wait() on a helper) need the default. */ - signal(SIGCHLD, SIG_DFL); - signal(SIGPIPE, SIG_DFL); - /* Flatpak apps reach the host (shell lookup, portals) through org.freedesktop.Flatpak - * on the real session bus, so they keep it; the sandbox isolates their instances anyway. */ - if (private_bus[0] && strstr(cmd, "flatpak run") == NULL) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1); - setenv("WAYLAND_DISPLAY", display, 1); - unsetenv("DISPLAY"); - /* Make toolkits pick our Wayland socket, not X11 or the host session. */ - setenv("XDG_SESSION_TYPE", "wayland", 1); - setenv("QT_QPA_PLATFORM", "wayland", 1); - setenv("GDK_BACKEND", "wayland", 1); - setenv("SDL_VIDEODRIVER", "wayland", 1); - setenv("MOZ_ENABLE_WAYLAND", "1", 1); - setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1); - setenv("CLUTTER_BACKEND", "wayland", 1); + app_env(cmd, display); execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); _exit(127); } return 0; } +static uint64_t mono_ms(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; +} + +static void write_all(int fd, const char *p, size_t n) { + while (n > 0) { + ssize_t w = write(fd, p, n); + if (w < 0 && errno == EINTR) continue; + if (w <= 0) return; + p += w; + n -= (size_t)w; + } +} + +/* Keep the last LAUNCH_TAIL bytes an app wrote. */ +#define LAUNCH_TAIL 2048 +struct tail { char buf[LAUNCH_TAIL]; size_t len; }; +static void tail_add(struct tail *t, const char *p, size_t n) { + if (n >= LAUNCH_TAIL) { memcpy(t->buf, p + n - LAUNCH_TAIL, LAUNCH_TAIL); t->len = LAUNCH_TAIL; return; } + if (t->len + n > LAUNCH_TAIL) { + size_t drop = t->len + n - LAUNCH_TAIL; + memmove(t->buf, t->buf + drop, t->len - drop); + t->len -= drop; + } + memcpy(t->buf + t->len, p, n); + t->len += n; +} + +/* Copy what is readable on `from` to our stderr (the session log) and into `t`. 0 at EOF. */ +static int pump(int from, struct tail *t) { + char buf[4096]; + for (;;) { + ssize_t n = read(from, buf, sizeof(buf)); + if (n > 0) { write_all(2, buf, (size_t)n); tail_add(t, buf, (size_t)n); continue; } + if (n < 0 && errno == EINTR) continue; + if (n < 0 && errno == EAGAIN) return 1; + return 0; + } +} + +/* Launch `cmd` like mp_spawn, watched: a small monitor process starts it with its stdout and + * stderr on a pipe, copies that output to our stderr (the session log, as before) and keeps its + * last 2 KiB. When `sh -c cmd` exits the monitor reports on the returned socket (non-blocking): + * "exit CODE MS\n" or "signal NUM MS\n" (MS = how long it ran), then the output tail. + * The socket closes after that. The monitor keeps copying output from anything the command left + * running, until nothing holds the pipe open. Returns our end, or -1 when nothing could start. */ +MOONBIT_FFI_EXPORT +int32_t mp_spawn_watch(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { + char cmd[2048]; + char display[512]; + bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd)); + bytes_to_cstr(display_bytes, display, sizeof(display)); + signal(SIGCHLD, SIG_IGN); /* the monitor is never our zombie */ + start_private_bus(); + int rep[2]; + /* A socket, not a pipe: the compositor reads every fd it watches with recvmsg. */ + if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, rep) != 0) return -1; + int out[2]; + if (pipe2(out, O_CLOEXEC) != 0) { close(rep[0]); close(rep[1]); return -1; } + pid_t mon = fork(); + if (mon < 0) { close(rep[0]); close(rep[1]); close(out[0]); close(out[1]); return -1; } + if (mon == 0) { + setsid(); + signal(SIGCHLD, SIG_DFL); + signal(SIGPIPE, SIG_IGN); /* the compositor may stop listening; keep copying output */ + /* Hold nothing of the compositor's (DRM, seat, client sockets) for the app's lifetime. */ + for (int fd = 3; fd < 1024; fd++) { + if (fd != rep[1] && fd != out[0] && fd != out[1]) close(fd); + } + uint64_t t0 = mono_ms(); + pid_t app = fork(); + if (app < 0) { + char msg[128]; + int n = snprintf(msg, sizeof(msg), "exit 127 0\nfork failed: %s\n", strerror(errno)); + write_all(rep[1], msg, (size_t)n); + _exit(1); + } + if (app == 0) { + /* The command's stdout and stderr go to the monitor; none of our other fds leak into it. */ + dup2(out[1], 1); + dup2(out[1], 2); + for (int fd = 3; fd < 1024; fd++) close(fd); + app_env(cmd, display); + execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); + _exit(127); + } + close(out[1]); + fcntl(out[0], F_SETFL, fcntl(out[0], F_GETFL, 0) | O_NONBLOCK); + struct tail t = { .len = 0 }; + int open_out = 1, reported = 0; + while (open_out || !reported) { + if (open_out) { + struct pollfd p = { .fd = out[0], .events = POLLIN }; + poll(&p, 1, reported ? -1 : 100); + open_out = pump(out[0], &t); + } + if (!reported) { + int st = 0; + pid_t r = waitpid(app, &st, open_out ? WNOHANG : 0); + if (r == app) { + if (open_out) open_out = pump(out[0], &t); /* what it wrote just before exiting */ + char head[64]; + int n = WIFSIGNALED(st) + ? snprintf(head, sizeof(head), "signal %d %llu\n", WTERMSIG(st), (unsigned long long)(mono_ms() - t0)) + : snprintf(head, sizeof(head), "exit %d %llu\n", WEXITSTATUS(st), (unsigned long long)(mono_ms() - t0)); + write_all(rep[1], head, (size_t)n); + fprintf(stderr, "chandra-launch: `%s` %s", cmd, head); /* "... exit 1 230\n" in the session log */ + write_all(rep[1], t.buf, t.len); + close(rep[1]); + reported = 1; + } + } + } + _exit(0); + } + close(rep[1]); + close(out[0]); + close(out[1]); + set_nonblock_cloexec(rep[0]); + return rep[0]; +} + /* Names of "*.desktop" files in `dir`, newline-separated. */ MOONBIT_FFI_EXPORT moonbit_bytes_t mp_list_desktop(moonbit_bytes_t dir_bytes) { diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 45c8a9b..1bca4ce 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -204,6 +204,11 @@ pub fn spawn(cmd : String, display : String) -> Bool { @hostsys.spawn(cmd, display) } +///| Launch `cmd` like `spawn`, watched: a socket that reports how it exited (see sys_native.mbt). +pub fn spawn_watch(cmd : String, display : String) -> Int { + @hostsys.spawn_watch(cmd, display) +} + ///| True once after the host process got SIGUSR1 (reload the panel modules). pub fn take_sigusr1() -> Bool { @hostsys.take_sigusr1() diff --git a/interface/chandra/host/sys/ffi.mbt b/interface/chandra/host/sys/ffi.mbt index 3bc9b2c..58a0141 100644 --- a/interface/chandra/host/sys/ffi.mbt +++ b/interface/chandra/host/sys/ffi.mbt @@ -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 wasmImportSpawnWatch(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn-watch" + ///| fn wasmImportSpawnSocket(p0 : Int, p1 : Int) -> Int = "chandra:host/sys@0.1.0" "spawn-socket" diff --git a/interface/chandra/host/sys/native_stub.mbt b/interface/chandra/host/sys/native_stub.mbt index 9cb5d5e..aa3127f 100644 --- a/interface/chandra/host/sys/native_stub.mbt +++ b/interface/chandra/host/sys/native_stub.mbt @@ -140,6 +140,16 @@ fn wasmImportSpawn(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { abort("wasm-only host import") } +///| +fn wasmImportSpawnWatch(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + +///| +fn wasmImportSpawnSocket(p0 : Int, p1 : Int) -> Int { + abort("wasm-only host import") +} + ///| fn wasmImportTakeSigusr1() -> Int { abort("wasm-only host import") @@ -184,8 +194,3 @@ fn mbt_ffi_bytes2ptr(bytes : FixedArray[Byte]) -> Int { fn mbt_ffi_int_array2ptr(array : FixedArray[Int]) -> Int { abort("wasm-only") } - -///| -fn wasmImportSpawnSocket(p0 : Int, p1 : Int) -> Int { - abort("wasm-only host import") -} diff --git a/interface/chandra/host/sys/pkg.generated.mbti b/interface/chandra/host/sys/pkg.generated.mbti index e2b9119..9283518 100644 --- a/interface/chandra/host/sys/pkg.generated.mbti +++ b/interface/chandra/host/sys/pkg.generated.mbti @@ -44,6 +44,8 @@ pub fn spawn(String, String) -> Bool pub fn spawn_socket(String) -> Int +pub fn spawn_watch(String, String) -> Int + pub fn take_fd(Int32) -> Int32 pub fn take_sigusr1() -> Bool diff --git a/interface/chandra/host/sys/top.mbt b/interface/chandra/host/sys/top.mbt index e83ea12..41676a5 100644 --- a/interface/chandra/host/sys/top.mbt +++ b/interface/chandra/host/sys/top.mbt @@ -325,6 +325,20 @@ pub fn spawn(cmd : String, display : String) -> Bool { mbt_ffi_free(ptr0) return ret +} +///| +/// Launch `cmd` like `spawn`, watched: a socket that reports how it exited (see sys.wit). +pub fn spawn_watch(cmd : String, display : String) -> Int { + + let ptr = mbt_ffi_str2ptr(cmd) + + let ptr0 = mbt_ffi_str2ptr(display) + let result : Int = wasmImportSpawnWatch(ptr, cmd.length(), ptr0, display.length()); + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(ptr0) + return ret + } ///| /// True once after the host process got SIGUSR1 (a request to reload the panel modules from diff --git a/session/chandra-ctl b/session/chandra-ctl index a2962b8..91ec492 100755 --- a/session/chandra-ctl +++ b/session/chandra-ctl @@ -7,6 +7,7 @@ chandra-ctl ping check the compositor answers chandra-ctl shortcut ID do what a keyboard shortcut does (overview, launcher, show-desktop...) chandra-ctl kiosk [lock|unlock|status] kiosk mode (--kiosk, docs/kiosk.md) + chandra-ctl launch ID start desktop app ID (org.kde.kwi) as the dock does chandra-ctl windows how Chandra sees each window, and what is under the pointer chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo"); MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md) @@ -23,7 +24,7 @@ import os import socket import sys -USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | windows | auth-demo [MODE] | auth-status | help}" +USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | auth-demo [MODE] | auth-status | help}" def runtime_dir(): diff --git a/wasmhost/bin/sys.mbt b/wasmhost/bin/sys.mbt index 5e6a0e1..02d16c5 100644 --- a/wasmhost/bin/sys.mbt +++ b/wasmhost/bin/sys.mbt @@ -208,6 +208,10 @@ fn sys_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { "spawn", a => boolean(@sys.spawn(a[0].to_string(), a[1].to_string())), ), + ( + "spawn-watch", + a => s32(@sys.spawn_watch(a[0].to_string(), a[1].to_string())), + ), ( "spawn-socket", a => s32(@sys.spawn_socket(a[0].to_string().split("\n").map(v => v.to_string()).to_array())), diff --git a/wit/host/sys.wit b/wit/host/sys.wit index 11aa2f3..f37cd15 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -66,6 +66,11 @@ interface sys { has-exe: func(name: string) -> bool; /// Launch `cmd` detached with WAYLAND_DISPLAY set to `display`. spawn: func(cmd: string, display: string) -> bool; + /// Launch `cmd` like `spawn`, watched. Returns a non-blocking socket (-1 when nothing could + /// start) that reports once `sh -c cmd` exits: "exit CODE MS\n" or "signal NUM MS\n" (MS = how + /// long it ran), then the last 2 KiB of its stdout and stderr, then EOF. The output still goes + /// to the host's stderr (the session log) as it is written. + spawn-watch: func(cmd: string, display: string) -> s32; /// Run a program with its stdin and stdout on one end of a socket pair; our end, or -1. /// `argv` is the absolute program path then its arguments, separated by newlines. Its stderr /// is the host's. Not waited for. Used for polkit's setuid authentication helper.