From e6be3825d0cd222bac9b986de30ce593531146d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:37:43 +0000 Subject: [PATCH] X11 backend: run Chandra on Xorg (NVIDIA's proprietary driver) --x11 shows the desktop on the X server in $DISPLAY: a resizable window under a window manager (--fullscreen asks it for fullscreen), or the whole screen when no window manager runs, following xrandr resizes. compositor/x11 is a pure X11 wire-protocol client (no libX11/xcb), so it runs in the wasm compositor on both hosts and in the native build. Frames go through MIT-SHM 1.2 (ShmAttachFd of the host frame memfd, paced by ShmCompletion), with a core PutImage fallback. The keymap given to clients is the X server's own (xkbcomp -xkb $DISPLAY -); X auto-repeat is dropped, modifier/lock state comes from X's modifier map; MIT-MAGIC-COOKIE-1 auth. chandra-session --x11 (and the new "Chandra (X11)" xsessions entry) runs it as the login session; --login-session gives an X11 session what --drm implied (power actions, polkit agent, system theme). just run-x11. Docs: docs/x11.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DPL5hhLFs4VtHV26G1iyeo --- README.md | 12 +- compositor/app/app.mbt | 98 ++- compositor/app/moon.pkg | 1 + compositor/bin/main.mbt | 61 +- compositor/bin/moon.pkg | 1 + compositor/x11/moon.pkg | 8 + compositor/x11/x11.mbt | 1431 +++++++++++++++++++++++++++++++++++ compositor/x11/x11_test.mbt | 54 ++ docs/x11.md | 85 +++ justfile | 5 + scripts/test.sh | 2 +- session/chandra-session | 27 +- session/chandra-x11.desktop | 7 + session/install.py | 4 + 14 files changed, 1777 insertions(+), 19 deletions(-) create mode 100644 compositor/x11/moon.pkg create mode 100644 compositor/x11/x11.mbt create mode 100644 compositor/x11/x11_test.mbt create mode 100644 docs/x11.md create mode 100644 session/chandra-x11.desktop diff --git a/README.md b/README.md index 2ed1eba..9f15712 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,10 @@ about 4 seconds (the Rust host takes about 2 minutes). The **Rust host** fallback until it is removed; any host change goes into both. A **native build** of the same compositor code (no wasm, `just run-native`) is used by the test suite. -The compositor runs either **nested**, as a window on your current Wayland session, or as a -**login session** on DRM/KMS with libinput (`--drm`, through libseat/logind). +The compositor runs **nested**, as a window on your current Wayland session, as a **login +session** on DRM/KMS with libinput (`--drm`, through libseat/logind), or **on an X server** +(`--x11`: a window under an X window manager, or the whole screen without one), for NVIDIA's +proprietary driver on Xorg ([docs/x11.md](docs/x11.md)). ## Quickstart @@ -74,7 +76,8 @@ just client # start foot inside it (or: just client konsol |---|---| | `just run` | Nested in a window on your Wayland session, MoonBit host | | `just run-drm` | As a login session on the real screen (from a text console, as yourself) | -| `just install` | Install the "Chandra" display-manager session (asks for root once) | +| `just run-x11` | On the X server in `$DISPLAY` (NVIDIA on Xorg; the whole screen when no window manager runs) | +| `just install` | Install the "Chandra" display-manager session, and "Chandra (X11)" for Xorg (asks for root once) | | `just install-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-rust` | The same with the Rust host | @@ -85,7 +88,8 @@ just client # start foot inside it (or: just client konsol | `just remote-build` | Build on a sprites.dev sprite (`CHANDRA_SPRITE`) and pull the artifacts back | `build/wasmhost build/compositor.wasm --socket PATH` takes `--window` (nested), `--drm` (login -session), `--theme PATH`, `--no-restore`, `--profile`, `--size WxH` and `--gfx-out frame.png` +session), `--x11` (on Xorg; `--fullscreen` under a window manager, `--login-session` to act as the +desktop session), `--theme PATH`, `--no-restore`, `--profile`, `--size WxH` and `--gfx-out frame.png` (render to a PNG, headless; add `--serve` to keep refreshing it). `WASMHOST_PROFILE=1` prints the time spent in each host function every 5 seconds; `WASMHOST_TRACE=1` logs every host call. `CHANDRA_DEBUG_CONFIGURE=1` (any host) logs each window's configures, acks and committed buffer diff --git a/compositor/app/app.mbt b/compositor/app/app.mbt index 66a4895..ff7b4d0 100644 --- a/compositor/app/app.mbt +++ b/compositor/app/app.mbt @@ -2,7 +2,11 @@ /// operating system reached only through `@sys`. The wasm component (components/compositor) /// calls `run`; on the native side it is the same code with `@sys` backed by a C shim. /// -/// Arguments: --socket PATH --theme PATH --window --drm --gfx-out PNG --serve --size WxH +/// Arguments: --socket PATH --theme PATH --window --drm --x11 --fullscreen --gfx-out PNG --serve +/// --size WxH. --x11 shows the desktop on the X server in $DISPLAY (a window, or the whole screen +/// when no window manager runs there); --fullscreen asks a window manager for a fullscreen window; +/// --login-session makes it the user's desktop session as --drm does (power actions, the polkit +/// agent, apps' dark/light preference), for chandra-session --x11. /// --drm runs as a login session: the host takes the display (DRM/KMS) and input (libinput). /// With --gfx-out alone one frame is written and the program exits; add --serve to keep running /// and rewrite the PNG about twice a second (for looking at a live compositor without a display). @@ -49,6 +53,9 @@ pub fn run(args : Array[String]) -> Int { let mut serve = false let mut profile = false let mut drm = false + let mut x11 = false + let mut fullscreen = false + let mut login = false let mut restore = true let mut width = 1280 let mut height = 720 @@ -68,6 +75,15 @@ pub fn run(args : Array[String]) -> Int { } else if a == "--drm" { drm = true i = i + 1 + } else if a == "--x11" { + x11 = true // a window (or, with no window manager, the whole screen) on $DISPLAY + i = i + 1 + } else if a == "--login-session" { + login = true // this is the user's desktop session (as --drm is): power, polkit, system theme + i = i + 1 + } else if a == "--fullscreen" { + fullscreen = true // --x11 under a window manager: ask it for a fullscreen window + i = i + 1 } else if a == "--no-restore" { restore = false // don't reopen the apps of the last session i = i + 1 @@ -125,6 +141,28 @@ pub fn run(args : Array[String]) -> Int { None } + // X11 mode: a window on an X server (NVIDIA's Xorg driver has no usable KMS path for us), or + // the whole screen when no window manager runs there. Opened first so the desktop gets its size. + let xwin = if x11 && !drm { + let display = match @sys.getenv("DISPLAY") { + "" => ":0" + d => d + } + match @x11.X11Window::open(display, "Chandra", "chandra", width, height, fullscreen) { + Some(x) => { + width = x.width + height = x.height + Some(x) + } + None => { + @sys.log("failed to open a window on the X display " + display) + return 1 + } + } + } else { + None + } + let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height) }) match @host.ChandraCompositor::new(socket_path, theme, width, height) { @@ -138,8 +176,9 @@ pub fn run(args : Array[String]) -> Int { } Some(comp) => { comp.shell.persist = true // remember which modules are loaded in the panel - comp.sync_system_theme = drm // the login session sets apps' dark/light preference - comp.login_session = drm // and power actions (suspend, power off) act on the machine + let login = drm || login + comp.sync_system_theme = login // the login session sets apps' dark/light preference + comp.login_session = login // and power actions (suspend, power off) act on the machine comp.restore_state() // and the layout mode and recent apps from the last session comp.shell.screen_w = width // Screenshots and recordings read the host's framebuffer (it draws the desktop). @@ -192,7 +231,7 @@ pub fn run(args : Array[String]) -> Int { @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 drm { + if login { comp.start_auth_agent() // polkit's password prompts (run0, pkexec): Chandra's dialog } if restore { @@ -339,7 +378,53 @@ pub fn run(args : Array[String]) -> Int { busy = busy || input.length() > 0 || need_present wait_fds.push(n.fd) } - None => { + None => + match xwin { + Some(x) => { + if !x.poll() { + break + } + if x.keymap.length() > 0 { + comp.server.set_keymap(x.keymap) + } + // The window or the screen (xrandr) changed size: draw the desktop at the new size. + match x.take_resize() { + Some((nw, nh)) => { + width = nw + height = nh + comp.resize(nw, nh) + need_present = true + busy = true + } + None => () + } + if x.take_redraw() { + need_present = true // exposed: the X server has no copy of what was there + } + let now_ms = @sys.monotonic_ms().to_uint() + let input = x.take_input() + for ev in input { + comp.handle_input(ev, now_ms) + } + x.set_cursor_shape(comp.desired_cursor()) + match comp.compose_scene() { + Some(sg) => { + let r0 = @sys.monotonic_ms() + @raster.submit(sg) + comp.prof_raster_ms = comp.prof_raster_ms + (@sys.monotonic_ms() - r0) + need_present = true + busy = true + } + None => () + } + if need_present && x.frame_ready() { + x.present_frame(width, height) + need_present = false + } + busy = busy || input.length() > 0 || need_present + wait_fds.append(x.wait_fds()) + } + None => { comp.handle_gfx_events(gfx_surface) match comp.compose_scene() { Some(sg) => { @@ -357,7 +442,8 @@ pub fn run(args : Array[String]) -> Int { need_present = false } busy = busy || need_present - } + } + } } if profile { p_n = p_n + 1 diff --git a/compositor/app/moon.pkg b/compositor/app/moon.pkg index b921eb4..db1c9f6 100644 --- a/compositor/app/moon.pkg +++ b/compositor/app/moon.pkg @@ -6,6 +6,7 @@ import { "chandra/desktop/compositor/gfx" @gfx, "chandra/desktop/compositor/host" @host, "chandra/desktop/compositor/nested" @nested, + "chandra/desktop/compositor/x11" @x11, "chandra/desktop/compositor/kms" @kms, "chandra/desktop/compositor/raster" @raster, } diff --git a/compositor/bin/main.mbt b/compositor/bin/main.mbt index c92f474..da23ef8 100644 --- a/compositor/bin/main.mbt +++ b/compositor/bin/main.mbt @@ -9,6 +9,8 @@ fn main { let widgets : Array[String] = [] let mut windowed = false let mut drm = false + let mut x11 = false + let mut fullscreen = false let mut restore = true let mut width = 1280 let mut height = 720 @@ -28,6 +30,12 @@ fn main { } else if a == "--drm" { drm = true i = i + 1 + } else if a == "--x11" { + x11 = true + i = i + 1 + } else if a == "--fullscreen" { + fullscreen = true + i = i + 1 } else if a == "--no-restore" { restore = false // don't reopen the apps of the last session i = i + 1 @@ -71,6 +79,27 @@ fn main { None } + // X11 mode: a window (or the whole screen, without a window manager) on $DISPLAY. + let xwin = if x11 && !drm { + let display = match @env.get_env_var("DISPLAY") { + Some(d) => d + None => ":0" + } + match @x11.X11Window::open(display, "Chandra", "chandra", width, height, fullscreen) { + Some(x) => { + width = x.width + height = x.height + Some(x) + } + None => { + println("failed to open a window on the X display " + display) + return + } + } + } else { + None + } + let gfx_surface = @gfx.Surface::new({ width: Some(width), height: Some(height), @@ -175,10 +204,34 @@ fn main { n.present(comp.present_to_gfx(gfx_ctx)) } } - None => { - comp.handle_gfx_events(gfx_surface) - ignore(comp.present_to_gfx(gfx_ctx)) - } + None => + match xwin { + Some(x) => { + if !x.poll() { + break + } + if x.keymap.length() > 0 { + comp.server.set_keymap(x.keymap) + } + match x.take_resize() { + Some((nw, nh)) => comp.resize(nw, nh) + None => () + } + ignore(x.take_redraw()) // every frame is presented here anyway + let now_ms = @env.now().to_uint() + for ev in x.take_input() { + comp.handle_input(ev, now_ms) + } + x.set_cursor_shape(comp.desired_cursor()) + if x.frame_ready() { + x.present(comp.present_to_gfx(gfx_ctx)) + } + } + None => { + comp.handle_gfx_events(gfx_surface) + ignore(comp.present_to_gfx(gfx_ctx)) + } + } } @sys.sleep_ms(16) } diff --git a/compositor/bin/moon.pkg b/compositor/bin/moon.pkg index b61266f..55c9500 100644 --- a/compositor/bin/moon.pkg +++ b/compositor/bin/moon.pkg @@ -7,6 +7,7 @@ import { "chandra/desktop/compositor/gfx" @gfx, "chandra/desktop/compositor/host" @host, "chandra/desktop/compositor/nested" @nested, + "chandra/desktop/compositor/x11" @x11, "chandra/desktop/compositor/kms" @kms, } diff --git a/compositor/x11/moon.pkg b/compositor/x11/moon.pkg new file mode 100644 index 0000000..b1c6f4d --- /dev/null +++ b/compositor/x11/moon.pkg @@ -0,0 +1,8 @@ +import { + "moonbitlang/core/builtin", + "chandra/desktop/compositor/sys" @sys, + "chandra/desktop/compositor/renderer" @renderer, + "chandra/desktop/compositor/nested" @nested, +} + +supported_targets = "+native+wasm" diff --git a/compositor/x11/x11.mbt b/compositor/x11/x11.mbt new file mode 100644 index 0000000..4ddb328 --- /dev/null +++ b/compositor/x11/x11.mbt @@ -0,0 +1,1431 @@ +///| X11 backend: shows the compositor's frames on an X server (any driver, including the NVIDIA +/// proprietary one) and reads keyboard and pointer input from it. Like the nested backend this +/// is a plain client written against the wire protocol, so it needs no libX11/libxcb and runs +/// the same in the native build and in the wasm compositor (only `@sys` sockets and memfds). +/// +/// Two modes: +/// * **window**: a window of the requested size under a running window manager (resizable, +/// `fullscreen` asks the WM for `_NET_WM_STATE_FULLSCREEN`); +/// * **session**: no window manager on the display (an `xinit`/`startx` session, a display +/// manager's X session, a headless NVIDIA Xorg with a stream grabber on it): the window covers +/// the whole root window and follows it when the screen is resized (xrandr). +/// +/// Frames go through MIT-SHM with fd passing (`ShmAttachFd`, MIT-SHM 1.2): the host's +/// framebuffer memfd is handed to the X server, so no pixels are copied through this program. +/// Without MIT-SHM (an X server on another machine, or `CHANDRA_X11_NO_SHM=1`) it falls back to +/// core `PutImage` in strips. +/// The keymap given to Wayland clients is the X server's own (`xkbcomp -xkb $DISPLAY -`), so +/// keycodes, layout and options match what Xorg was configured with. + +///| +pub(all) struct X11Window { + fd : Int + input : Array[@nested.InputEvent] + /// xkb keymap text (format v1) for Wayland clients; empty when xkbcomp was not found. + mut keymap : Bytes + rx : Array[Byte] + /// Sequence number of the last request sent (16-bit, as the server echoes it). + mut seq : Int + replies : Map[Int, Array[Byte]] + errors : Map[Int, Int] + id_base : Int + id_mask : Int + mut next_xid : Int + /// Longest request the server accepts, in 4-byte units. + max_req : Int + root : Int + mut root_w : Int + mut root_h : Int + depth : Int + visual : Int + mut win : Int + mut gc : Int + /// No window manager: the window is the whole screen and follows the root window's size. + mut session : Bool + mut width : Int + mut height : Int + mut resized : Bool + mut redraw : Bool + mut closed : Bool + mut mapped : Bool + // Atoms. + mut a_wm_protocols : Int + mut a_wm_delete : Int + // MIT-SHM. + mut shm_major : Int + mut shm_event : Int + mut shm_seg : Int + mut use_shm : Bool + mut seg_attached : Bool + mut frame_pending : Bool + /// Core-protocol path: the GetInputFocus sent after a frame; its reply means the frame is done. + mut pending_seq : Int + // Keyboard state. + mod_of_key : Map[Int, Int] + mut lock_mask : Int + pressed : Map[Int, Bool] + mut locked : Int + mut sent_dep : Int + mut sent_lock : Int + mut mapping_changed : Bool + // Cursors. + mut cursor_font : Int + cursors : Map[Int, Int] + mut shape_applied : UInt + mut errors_logged : Int +} + +///| Smallest window size (as for the nested backend). +pub let min_width : Int = 640 + +///| +pub let min_height : Int = 400 + +// ---- byte helpers ------------------------------------------------------------------------- + +///| +fn put8(b : Array[Byte], v : Int) -> Unit { + b.push((v & 0xFF).to_byte()) +} + +///| +fn put16(b : Array[Byte], v : Int) -> Unit { + b.push((v & 0xFF).to_byte()) + b.push(((v >> 8) & 0xFF).to_byte()) +} + +///| +fn put32(b : Array[Byte], v : Int) -> Unit { + b.push((v & 0xFF).to_byte()) + b.push(((v >> 8) & 0xFF).to_byte()) + b.push(((v >> 16) & 0xFF).to_byte()) + b.push(((v >> 24) & 0xFF).to_byte()) +} + +///| +fn put_str(b : Array[Byte], s : Bytes) -> Unit { + for c in s { + b.push(c) + } +} + +///| +fn pad4(b : Array[Byte]) -> Unit { + while b.length() % 4 != 0 { + b.push(b'\x00') + } +} + +///| +fn get8(b : Array[Byte], off : Int) -> Int { + b[off].to_int() +} + +///| +fn get16(b : Array[Byte], off : Int) -> Int { + b[off].to_int() | (b[off + 1].to_int() << 8) +} + +///| Signed 16-bit. +fn gets16(b : Array[Byte], off : Int) -> Int { + let v = get16(b, off) + if v >= 0x8000 { + v - 0x10000 + } else { + v + } +} + +///| +fn get32(b : Array[Byte], off : Int) -> Int { + b[off].to_int() | + (b[off + 1].to_int() << 8) | + (b[off + 2].to_int() << 16) | + (b[off + 3].to_int() << 24) +} + +///| ASCII text as bytes (atom and font names, properties). +fn ascii(s : String) -> Bytes { + @sys.str_to_utf8_bytes(s) +} + +// ---- requests ----------------------------------------------------------------------------- + +///| Send request `opcode` with header byte `data` and `body` (padded here). Returns its sequence. +fn X11Window::request( + self : X11Window, + opcode : Int, + data : Int, + body : Array[Byte], + send_fd? : Int = -1, +) -> Int { + pad4(body) + let out : Array[Byte] = [] + put8(out, opcode) + put8(out, data) + put16(out, (4 + body.length()) / 4) + for c in body { + out.push(c) + } + if send_fd >= 0 { + if !self.closed && @sys.sendmsg_fd(self.fd, Bytes::from_array(out), send_fd) < out.length() { + self.closed = true + } + } else { + self.send_all(Bytes::from_array(out)) + } + self.seq = (self.seq + 1) & 0xFFFF + self.seq +} + +///| Write all of `msg`, waiting for room when the socket is full (a big PutImage). +fn X11Window::send_all(self : X11Window, msg : Bytes) -> Unit { + let mut off = 0 + let mut stalls = 0 + while !self.closed && off < msg.length() { + let chunk = if off == 0 { + msg + } else { + let rest : FixedArray[Byte] = FixedArray::make(msg.length() - off, b'\x00') + rest.blit_from_bytes(0, msg, off, msg.length() - off) + Bytes::from_fixedarray(rest) + } + let n = @sys.sendmsg_fd(self.fd, chunk, -1) + if n > 0 { + off = off + n + stalls = 0 + } else { + // Full (or failed): let the server drain it; give up after about 5 s. + stalls = stalls + 1 + if stalls > 500 { + @sys.log("x11: the X server stopped reading; closing") + self.closed = true + return + } + @sys.sleep_ms(10) + } + } +} + +///| +fn X11Window::alloc_xid(self : X11Window) -> Int { + let id = self.id_base | (self.next_xid & self.id_mask) + self.next_xid = self.next_xid + 1 + id +} + +///| Read whatever the server has sent and dispatch it (non-blocking). +fn X11Window::pump(self : X11Window) -> Unit { + let scratch : FixedArray[Byte] = FixedArray::make(65536, b'\x00') + while !self.closed && @sys.poll_read(self.fd, 0) > 0 { + let (n, rfd) = @sys.recvmsg_fd(self.fd, scratch, 65536) + if rfd >= 0 { + @sys.close_fd(rfd) + } + if n <= 0 { + self.closed = true + break + } + for i = 0; i < n; i = i + 1 { + self.rx.push(scratch[i]) + } + } + let mut off = 0 + while off + 32 <= self.rx.length() { + let code = get8(self.rx, off) & 0x7F + if code == 1 { + let len = 32 + 4 * get32(self.rx, off + 4) + if off + len > self.rx.length() { + break + } + let seq = get16(self.rx, off + 2) + if seq == self.pending_seq && self.pending_seq >= 0 { + self.pending_seq = -1 + self.frame_pending = false + } else { + let rep : Array[Byte] = [] + for i = off; i < off + len; i = i + 1 { + rep.push(self.rx[i]) + } + self.replies.set(seq, rep) + } + off = off + len + } else { + off = off + self.dispatch(off) + } + } + if off > 0 { + let rest : Array[Byte] = [] + for i = off; i < self.rx.length(); i = i + 1 { + rest.push(self.rx[i]) + } + self.rx.clear() + for b in rest { + self.rx.push(b) + } + } +} + +///| Wait (up to about 5 s) for the reply to request `seq`. None on an error or a timeout. +fn X11Window::wait_reply(self : X11Window, seq : Int) -> Array[Byte]? { + let mut tries = 0 + while !self.closed && tries < 500 { + match self.replies.get(seq) { + Some(r) => { + self.replies.remove(seq) + return Some(r) + } + None => () + } + if self.errors.contains(seq) { + self.errors.remove(seq) + return None + } + ignore(@sys.poll_read(self.fd, 10)) + self.pump() + tries = tries + 1 + } + None +} + +///| InternAtom; 0 when it failed. +fn X11Window::intern(self : X11Window, name : String) -> Int { + let n = ascii(name) + let b : Array[Byte] = [] + put16(b, n.length()) + put16(b, 0) + put_str(b, n) + match self.wait_reply(self.request(16, 0, b)) { + Some(r) => get32(r, 8) + None => 0 + } +} + +///| ChangeProperty (replace) with 8- or 32-bit items. +fn X11Window::set_prop( + self : X11Window, + prop : Int, + typ : Int, + format : Int, + data : Array[Byte], +) -> Unit { + let b : Array[Byte] = [] + put32(b, self.win) + put32(b, prop) + put32(b, typ) + put8(b, format) + put8(b, 0) + put16(b, 0) + put32(b, data.length() / (format / 8)) + for c in data { + b.push(c) + } + ignore(self.request(18, 0, b)) +} + +///| Value of `prop` on window `w` as raw bytes (first 64 KiB); None if unset. +fn X11Window::get_prop(self : X11Window, w : Int, prop : Int) -> Array[Byte]? { + let b : Array[Byte] = [] + put32(b, w) + put32(b, prop) + put32(b, 0) // AnyPropertyType + put32(b, 0) + put32(b, 16384) + match self.wait_reply(self.request(20, 0, b)) { + None => None + Some(r) => { + let format = get8(r, 1) + let n = get32(r, 16) + if format == 0 || n == 0 { + return None + } + let len = n * (format / 8) + let out : Array[Byte] = [] + for i = 32; i < 32 + len && i < r.length(); i = i + 1 { + out.push(r[i]) + } + Some(out) + } + } +} + +// ---- connection --------------------------------------------------------------------------- + +///| Display number and screen from a DISPLAY value (":0", ":1.0", "unix:0"). None for TCP +/// displays (host:N), which this backend does not support. +pub fn parse_display(d : String) -> (Int, Int)? { + let mut colon = -1 + for i = 0; i < d.length(); i = i + 1 { + if d[i] == ':' { + colon = i + } + } + if colon < 0 { + return None + } + let host = d[:colon].to_string() + if host != "" && host != "unix" { + return None + } + let mut num = 0 + let mut screen = 0 + let mut seen = false + let mut in_screen = false + for i = colon + 1; i < d.length(); i = i + 1 { + let c = d[i] + if c == '.' { + if in_screen { + return None + } + in_screen = true + } else if c >= '0' && c <= '9' { + if in_screen { + screen = screen * 10 + (c.to_int() - 48) + } else { + num = num * 10 + (c.to_int() - 48) + seen = true + } + } else { + return None + } + } + if !seen { + return None + } + Some((num, screen)) +} + +///| MIT-MAGIC-COOKIE-1 for display `num` from an Xauthority file's contents; empty if none +/// matches. Entries for this host (or FamilyWild) are preferred over any other local entry. +pub fn xauth_cookie(file : Bytes, num : Int, hostname : String) -> Bytes { + let data = file.to_array() + let want_num = num.to_string() + let mut fallback = Bytes::from_array([]) + let mut off = 0 + fn be16(o : Int) -> Int { + (data[o].to_int() << 8) | data[o + 1].to_int() + } + + fn field(o : Int) -> (Array[Byte], Int)? { + if o + 2 > data.length() { + return None + } + let n = be16(o) + if o + 2 + n > data.length() { + return None + } + let out : Array[Byte] = [] + for i = o + 2; i < o + 2 + n; i = i + 1 { + out.push(data[i]) + } + Some((out, o + 2 + n)) + } + + fn text(a : Array[Byte]) -> String { + let sb = StringBuilder::new() + for c in a { + sb.write_char(c.to_int().unsafe_to_char()) + } + sb.to_string() + } + + while off + 2 <= data.length() { + let family = be16(off) + let (addr, o1) = match field(off + 2) { + Some(x) => x + None => break + } + let (number, o2) = match field(o1) { + Some(x) => x + None => break + } + let (name, o3) = match field(o2) { + Some(x) => x + None => break + } + let (cookie, o4) = match field(o3) { + Some(x) => x + None => break + } + off = o4 + let n = text(number) + if text(name) != "MIT-MAGIC-COOKIE-1" || (n != "" && n != want_num) { + continue + } + if family == 0xFFFF || (family == 256 && text(addr) == hostname) { + return Bytes::from_array(cookie) + } + if family == 256 && fallback.length() == 0 { + fallback = Bytes::from_array(cookie) + } + } + fallback +} + +///| Trim trailing whitespace (the hostname file ends in a newline). +fn trim_end(s : String) -> String { + let mut end = s.length() + while end > 0 && (s[end - 1] == '\n' || s[end - 1] == ' ' || s[end - 1] == '\r') { + end = end - 1 + } + s[:end].to_string() +} + +///| +fn bytes_to_string(b : Bytes) -> String { + let sb = StringBuilder::new() + for c in b { + sb.write_char(c.to_int().unsafe_to_char()) + } + sb.to_string() +} + +///| The xkb keymap the X server uses, as text (`xkbcomp -xkb $DISPLAY -`). Empty if xkbcomp is +/// missing or fails. +fn server_keymap(display : String) -> Bytes { + for c in display { + if c == '\'' { + return Bytes::from_array([]) + } + } + let fd = @sys.spawn_socket([ + "/bin/sh", "-c", "exec xkbcomp -w 0 -xkb '" + display + "' - 2>/dev/null", + ]) + if fd < 0 { + return Bytes::from_array([]) + } + let out : Array[Byte] = [] + let scratch : FixedArray[Byte] = FixedArray::make(65536, b'\x00') + let mut tries = 0 + while tries < 300 { + if @sys.poll_read(fd, 10) > 0 { + let (n, rfd) = @sys.recvmsg_fd(fd, scratch, 65536) + if rfd >= 0 { + @sys.close_fd(rfd) + } + if n <= 0 { + break + } + for i = 0; i < n; i = i + 1 { + out.push(scratch[i]) + } + } else { + tries = tries + 1 + } + } + @sys.close_fd(fd) + // Something that is not a keymap (an error message) is no use to clients. + let s = bytes_to_string(Bytes::from_array(out)) + if !s.contains("xkb_keymap") || !s.contains("xkb_symbols") { + return Bytes::from_array([]) + } + out.push(b'\x00') // xkb_keymap_new_from_buffer takes a NUL-terminated buffer, like the KMS one + Bytes::from_array(out) +} + +///| Connect to the X server named by `display` (the DISPLAY value) and open the compositor's +/// window: `width` x `height` under a window manager (`fullscreen` asks it to cover the +/// screen), or the whole screen when there is no window manager. +pub fn X11Window::open( + display : String, + title : String, + app_id : String, + width : Int, + height : Int, + fullscreen : Bool, +) -> X11Window? { + let (num, screen_no) = match parse_display(display) { + Some(x) => x + None => { + @sys.log("x11: unsupported DISPLAY '" + display + "' (only local displays like :0)") + return None + } + } + let fd = @sys.unix_connect("/tmp/.X11-unix/X" + num.to_string()) + if fd < 0 { + @sys.log("x11: cannot connect to /tmp/.X11-unix/X" + num.to_string()) + return None + } + // Authentication: MIT-MAGIC-COOKIE-1 from $XAUTHORITY (or ~/.Xauthority). + let xauth_path = match @sys.getenv("XAUTHORITY") { + "" => @sys.getenv("HOME") + "/.Xauthority" + p => p + } + let hostname = trim_end( + bytes_to_string(@sys.read_proc_bytes("/proc/sys/kernel/hostname")), + ) + let cookie = xauth_cookie(@sys.read_file_bytes(xauth_path), num, hostname) + let auth_name = if cookie.length() > 0 { + ascii("MIT-MAGIC-COOKIE-1") + } else { + Bytes::from_array([]) + } + let setup : Array[Byte] = [] + put8(setup, 0x6C) // 'l': little-endian + put8(setup, 0) + put16(setup, 11) + put16(setup, 0) + put16(setup, auth_name.length()) + put16(setup, cookie.length()) + put16(setup, 0) + put_str(setup, auth_name) + pad4(setup) + put_str(setup, cookie) + pad4(setup) + ignore(@sys.sendmsg_fd(fd, Bytes::from_array(setup), -1)) + // Read the whole setup reply. + let rx : Array[Byte] = [] + let scratch : FixedArray[Byte] = FixedArray::make(65536, b'\x00') + let mut need = 8 + let mut tries = 0 + while rx.length() < need && tries < 500 { + if @sys.poll_read(fd, 10) > 0 { + let (n, rfd) = @sys.recvmsg_fd(fd, scratch, 65536) + if rfd >= 0 { + @sys.close_fd(rfd) + } + if n <= 0 { + break + } + for i = 0; i < n; i = i + 1 { + rx.push(scratch[i]) + } + if rx.length() >= 8 { + need = 8 + 4 * get16(rx, 6) + } + } else { + tries = tries + 1 + } + } + if rx.length() < 8 || rx.length() < need { + @sys.log("x11: no setup reply from the X server") + @sys.close_fd(fd) + return None + } + let status = get8(rx, 0) + if status != 1 { + let rlen = get8(rx, 1) + let sb = StringBuilder::new() + for i = 8; i < 8 + rlen && i < rx.length(); i = i + 1 { + sb.write_char(rx[i].to_int().unsafe_to_char()) + } + @sys.log( + "x11: the X server refused the connection: " + + sb.to_string() + + (if cookie.length() == 0 { + " (no cookie for this display in " + xauth_path + ")" + } else { + "" + }), + ) + @sys.close_fd(fd) + return None + } + let id_base = get32(rx, 12) + let id_mask = get32(rx, 16) + let vendor_len = get16(rx, 24) + let max_req = get16(rx, 26) + let n_screens = get8(rx, 28) + let n_formats = get8(rx, 29) + let image_byte_order = get8(rx, 30) + if image_byte_order != 0 { + @sys.log("x11: the X server wants MSB-first images; colours will be wrong") + } + let mut off = 40 + (vendor_len + 3) / 4 * 4 + let mut bpp24 = 0 + for _ in 0..= n_screens) + if this { + root = get32(rx, off) + root_w = get16(rx, off + 20) + root_h = get16(rx, off + 22) + root_visual = get32(rx, off + 32) + root_depth = get8(rx, off + 38) + } + let n_depths = get8(rx, off + 39) + off = off + 40 + for _ in 0.. true + None => false + } + self.session = !has_wm + if self.session { + self.width = root_w + self.height = root_h + } else { + self.width = if width < min_width { min_width } else { width } + self.height = if height < min_height { min_height } else { height } + if self.width > root_w { + self.width = root_w + } + if self.height > root_h { + self.height = root_h + } + } + // CreateWindow. A non-default visual needs its own colormap and a border pixel. + self.win = self.alloc_xid() + let event_mask = 0x1 | // KeyPress + 0x2 | // KeyRelease + 0x4 | // ButtonPress + 0x8 | // ButtonRelease + 0x10 | // EnterWindow + 0x40 | // PointerMotion + 0x8000 | // Exposure + 0x20000 | // StructureNotify + 0x200000 // FocusChange + let b : Array[Byte] = [] + put32(b, self.win) + put32(b, root) + put16(b, 0) + put16(b, 0) + put16(b, self.width) + put16(b, self.height) + put16(b, 0) // border width + put16(b, 1) // InputOutput + put32(b, visual) + if visual == root_visual { + put32(b, 0x1 | 0x800) // BackPixmap, EventMask + put32(b, 0) // BackPixmap None: no flash of background before the first frame + put32(b, event_mask) + } else { + let cmap = self.alloc_xid() + let cb : Array[Byte] = [] + put32(cb, cmap) + put32(cb, root) + put32(cb, visual) + ignore(self.request(78, 0, cb)) // CreateColormap (AllocNone) + put32(b, 0x1 | 0x8 | 0x800 | 0x2000) // BackPixmap, BorderPixel, EventMask, Colormap + put32(b, 0) + put32(b, 0) + put32(b, event_mask) + put32(b, cmap) + } + ignore(self.request(1, depth, b)) + // Titles, class, close button, minimum size, pid. + let t = ascii(title) + self.set_prop(39, 31, 8, t.to_array()) // WM_NAME STRING + if a_net_wm_name != 0 && a_utf8 != 0 { + self.set_prop(a_net_wm_name, a_utf8, 8, @sys.str_to_utf8_bytes(title).to_array()) + } + let class : Array[Byte] = [] + put_str(class, ascii(app_id)) + put8(class, 0) + put_str(class, ascii(app_id)) + put8(class, 0) + self.set_prop(67, 31, 8, class) // WM_CLASS + if self.a_wm_protocols != 0 && self.a_wm_delete != 0 { + let p : Array[Byte] = [] + put32(p, self.a_wm_delete) + self.set_prop(self.a_wm_protocols, 4, 32, p) // ATOM + } + if a_pid != 0 { + let p : Array[Byte] = [] + put32(p, @sys.getpid()) + self.set_prop(a_pid, 6, 32, p) // CARDINAL + } + let hints : Array[Byte] = [] + put32(hints, 16) // PMinSize + for _ in 0..<4 { + put32(hints, 0) + } + put32(hints, if self.session { 1 } else { min_width }) + put32(hints, if self.session { 1 } else { min_height }) + for _ in 0..<11 { + put32(hints, 0) + } + self.set_prop(40, 41, 32, hints) // WM_NORMAL_HINTS WM_SIZE_HINTS + if fullscreen && !self.session && a_state != 0 && a_fullscreen != 0 { + let p : Array[Byte] = [] + put32(p, a_fullscreen) + self.set_prop(a_state, 4, 32, p) + } + // Follow the screen size (xrandr) when the window is the screen. + if self.session { + let cw : Array[Byte] = [] + put32(cw, root) + put32(cw, 0x800) + put32(cw, 0x20000) // StructureNotify + ignore(self.request(2, 0, cw)) + } + // A GC for PutImage, without GraphicsExpose events. + self.gc = self.alloc_xid() + let g : Array[Byte] = [] + put32(g, self.gc) + put32(g, self.win) + put32(g, 0x10000) + put32(g, 0) + ignore(self.request(55, 0, g)) + self.init_shm() + self.refresh_modmap() + self.keymap = server_keymap(display) + if self.keymap.length() == 0 { + @sys.log( + "x11: could not read the X server's keymap with xkbcomp (install xkbcomp / x11-xkb-utils); apps get no keymap", + ) + } + // The current Caps/Num Lock state. + let qp : Array[Byte] = [] + put32(qp, root) + match self.wait_reply(self.request(38, 0, qp)) { + Some(r) => self.locked = get16(r, 24) & self.lock_mask + None => () + } + let mw : Array[Byte] = [] + put32(mw, self.win) + ignore(self.request(8, 0, mw)) // MapWindow + self.pump() + @sys.log( + "x11: " + + (if self.session { + "no window manager on " + display + ": taking the whole screen" + } else { + "window on " + display + }) + + " (" + + self.width.to_string() + + "x" + + self.height.to_string() + + (if self.use_shm { + ", MIT-SHM" + } else { + ", no MIT-SHM: frames are copied" + }) + + ")", + ) + if self.closed { + return None + } + Some(self) +} + +///| MIT-SHM 1.2 (fd passing) if the server has it. +fn X11Window::init_shm(self : X11Window) -> Unit { + if @sys.getenv("CHANDRA_X11_NO_SHM") != "" { + return // for debugging: always copy frames with core PutImage + } + let n = ascii("MIT-SHM") + let b : Array[Byte] = [] + put16(b, n.length()) + put16(b, 0) + put_str(b, n) + match self.wait_reply(self.request(98, 0, b)) { + Some(r) if get8(r, 8) != 0 => { + self.shm_major = get8(r, 9) + self.shm_event = get8(r, 10) + } + _ => return + } + match self.wait_reply(self.request(self.shm_major, 0, [])) { + Some(r) => { + let major = get16(r, 8) + let minor = get16(r, 10) + if major > 1 || (major == 1 && minor >= 2) { + self.use_shm = true + self.shm_seg = self.alloc_xid() + } + } + None => () + } +} + +///| Which modifier bit each keycode sets (GetModifierMapping), and which are locks. +fn X11Window::refresh_modmap(self : X11Window) -> Unit { + match self.wait_reply(self.request(119, 0, [])) { + None => () + Some(r) => { + self.mod_of_key.clear() + self.lock_mask = 0 + let kpm = get8(r, 1) + for m = 0; m < 8; m = m + 1 { + for k = 0; k < kpm; k = k + 1 { + let kc = get8(r, 32 + m * kpm + k) + if kc != 0 { + self.mod_of_key.set(kc, 1 << m) + // Caps Lock (the Lock modifier) and Num Lock (evdev KEY_NUMLOCK 69) toggle. + if m == 1 || kc == 69 + 8 { + self.lock_mask = self.lock_mask | (1 << m) + } + } + } + } + } + } +} + +// ---- events ------------------------------------------------------------------------------- + +///| Evdev button code for an X button (1 left, 2 middle, 3 right, 8 back, 9 forward). +fn evdev_button(b : Int) -> UInt { + match b { + 1 => 0x110U + 2 => 0x112U + 3 => 0x111U + 8 => 0x113U + 9 => 0x114U + _ => 0x110U + b.reinterpret_as_uint() + } +} + +///| Queue a Modifiers event if the state changed. +fn X11Window::emit_mods(self : X11Window) -> Unit { + let mut dep = 0 + for kc, _ in self.pressed { + match self.mod_of_key.get(kc) { + Some(bit) if (bit & self.lock_mask) == 0 => dep = dep | bit + _ => () + } + } + if dep != self.sent_dep || self.locked != self.sent_lock { + self.sent_dep = dep + self.sent_lock = self.locked + self.input.push( + Modifiers( + dep.reinterpret_as_uint(), + 0U, + self.locked.reinterpret_as_uint(), + 0U, + ), + ) + } +} + +///| Release every key we think is down (focus left the window, so their releases go elsewhere). +fn X11Window::release_all(self : X11Window) -> Unit { + let keys : Array[Int] = [] + for kc, _ in self.pressed { + keys.push(kc) + } + for kc in keys { + if kc >= 8 { + self.input.push(Key((kc - 8).reinterpret_as_uint(), false)) + } + } + self.pressed.clear() + self.emit_mods() +} + +///| Dispatch the 32-byte event or error at `off`; returns how many bytes it used (64 when an +/// auto-repeat release/press pair was dropped). +fn X11Window::dispatch(self : X11Window, off : Int) -> Int { + let rx = self.rx + let code = get8(rx, off) & 0x7F + if code == 0 { + let err = get8(rx, off + 1) + let seq = get16(rx, off + 2) + let major = get8(rx, off + 10) + self.errors.set(seq, err) + if major == self.shm_major && self.shm_major >= 0 { + // MIT-SHM is announced but fd passing does not work (another machine, a namespace): copy. + if self.use_shm { + @sys.log("x11: MIT-SHM failed (error " + err.to_string() + "); copying frames instead") + } + self.use_shm = false + self.seg_attached = false + self.frame_pending = false + self.redraw = true + } else if self.errors_logged < 20 { + self.errors_logged = self.errors_logged + 1 + @sys.log( + "x11: X error " + + err.to_string() + + " for request " + + major.to_string() + + "." + + get16(rx, off + 8).to_string() + + " (value " + + get32(rx, off + 4).to_string() + + ")", + ) + } + if seq == self.pending_seq { + self.pending_seq = -1 + self.frame_pending = false + } + return 32 + } + if self.shm_event >= 0 && code == self.shm_event { + // ShmCompletion: the server has read the frame. + if self.seg_attached { + let b : Array[Byte] = [] + put32(b, self.shm_seg) + ignore(self.request(self.shm_major, 2, b)) // ShmDetach + self.seg_attached = false + } + self.frame_pending = false + return 32 + } + match code { + 2 | 3 => { + let kc = get8(rx, off + 1) + let time = get32(rx, off + 4) + let state = get16(rx, off + 28) + let down = code == 2 + // X reports a held key as release+press pairs with the same timestamp; Wayland clients + // repeat keys themselves, so drop the pair. + if !down && + off + 64 <= rx.length() && + (get8(rx, off + 32) & 0x7F) == 2 && + get8(rx, off + 33) == kc && + get32(rx, off + 36) == time { + return 64 + } + if down && self.pressed.contains(kc) { + return 32 // detectable auto-repeat: a press without a release + } + if kc < 8 { + return 32 + } + let bit = self.mod_of_key.get(kc).unwrap_or(0) + // Lock state before this event, then this key's own toggle. + self.locked = state & self.lock_mask + if down { + self.pressed.set(kc, true) + if (bit & self.lock_mask) != 0 { + self.locked = self.locked ^ bit + } + } else { + self.pressed.remove(kc) + } + self.input.push(Key((kc - 8).reinterpret_as_uint(), down)) + self.emit_mods() + } + 4 | 5 => { + let button = get8(rx, off + 1) + let x = gets16(rx, off + 24).to_double() + let y = gets16(rx, off + 26).to_double() + self.input.push(PointerMove(x, y)) + let down = code == 4 + match button { + 4 | 5 | 6 | 7 => + if down { + let axis = if button >= 6 { 1U } else { 0U } + let step = if button == 4 || button == 6 { -1 } else { 1 } + self.input.push(Scroll(axis, 15.0 * step.to_double(), step)) + } + _ => self.input.push(PointerButton(evdev_button(button), down)) + } + } + 6 | 7 => { + // MotionNotify, EnterNotify + let x = gets16(rx, off + 24).to_double() + let y = gets16(rx, off + 26).to_double() + self.input.push(PointerMove(x, y)) + } + 10 => self.release_all() // FocusOut + 12 => + // Expose: the last one of a series redraws. + if get16(rx, off + 16) == 0 { + self.redraw = true + } + 17 => + // DestroyNotify + if get32(rx, off + 8) == self.win { + self.closed = true + } + 19 => { + // MapNotify: without a window manager nobody gives us the keyboard; take it. + let w = get32(rx, off + 8) + if w == self.win { + self.mapped = true + self.redraw = true + if self.session { + let b : Array[Byte] = [] + put32(b, self.win) + put32(b, 0) + ignore(self.request(42, 1, b)) // SetInputFocus, revert to PointerRoot + } + } + } + 22 => { + // ConfigureNotify + let w = get32(rx, off + 8) + let cw = get16(rx, off + 20) + let ch = get16(rx, off + 22) + if w == self.win { + if cw > 0 && ch > 0 && (cw != self.width || ch != self.height) { + self.width = cw + self.height = ch + self.resized = true + self.redraw = true + } + } else if w == self.root && self.session { + // The screen was resized (xrandr): stay the size of the screen. + self.root_w = cw + self.root_h = ch + let b : Array[Byte] = [] + put32(b, self.win) + put16(b, 0x1 | 0x2 | 0x4 | 0x8) + put16(b, 0) + put32(b, 0) + put32(b, 0) + put32(b, cw) + put32(b, ch) + ignore(self.request(12, 0, b)) // ConfigureWindow + } + } + 33 => { + // ClientMessage: WM_DELETE_WINDOW from the window manager's close button. + if get32(rx, off + 8) == self.a_wm_protocols && + get32(rx, off + 12) == self.a_wm_delete { + self.closed = true + } + } + 34 => { + // MappingNotify: the keymap or the modifier map changed (setxkbmap, xmodmap). + let what = get8(rx, off + 4) + if what == 0 || what == 1 { + self.mapping_changed = true + } + } + _ => () + } + 32 +} + +// ---- the backend API (the same shape as @nested.NestedWindow) ----------------------------- + +///| Pump X events (input is queued; see take_input). False once the window was closed or the +/// X server went away. `display` is used to re-read the keymap after setxkbmap. +pub fn X11Window::poll(self : X11Window) -> Bool { + self.pump() + if self.mapping_changed && !self.closed { + self.mapping_changed = false + self.refresh_modmap() + let km = server_keymap(@sys.getenv("DISPLAY")) + if km.length() > 0 { + self.keymap = km + } + } + !self.closed +} + +///| The new window size if it changed since the last call. +pub fn X11Window::take_resize(self : X11Window) -> (Int, Int)? { + if !self.resized { + return None + } + self.resized = false + Some((self.width, self.height)) +} + +///| True once if the window needs its contents drawn again (exposed, mapped, resized), even +/// though the desktop did not change. +pub fn X11Window::take_redraw(self : X11Window) -> Bool { + let r = self.redraw && self.mapped + if r { + self.redraw = false + } + r +} + +///| Take all input received since the last call. +pub fn X11Window::take_input(self : X11Window) -> Array[@nested.InputEvent] { + let out = self.input.copy() + self.input.clear() + out +} + +///| True when the server is ready for a new frame. +pub fn X11Window::frame_ready(self : X11Window) -> Bool { + !self.frame_pending && !self.closed && self.mapped +} + +///| Show the host's framebuffer (`@sys.frame_memfd`, the wasm compositor). +pub fn X11Window::present_frame(self : X11Window, w : Int, h : Int) -> Unit { + if !self.frame_ready() { + return + } + let memfd = @sys.frame_memfd() + if memfd < 0 { + return + } + self.present_fd(memfd, w, h) +} + +///| Show `pixmap` (RGBA8888; the native build). +pub fn X11Window::present(self : X11Window, pixmap : @renderer.Pixmap) -> Unit { + if !self.frame_ready() { + return + } + let w = pixmap.width + let h = pixmap.height + let len = w * 4 * h + let out : FixedArray[Byte] = FixedArray::make(len, b'\x00') + for i = 0; i < w * h; i = i + 1 { + let o = i * 4 + out[o] = pixmap.data[o + 2] + out[o + 1] = pixmap.data[o + 1] + out[o + 2] = pixmap.data[o] + out[o + 3] = b'\xff' + } + let memfd = @sys.memfd_create("chandra-frame", len) + if memfd < 0 { + return + } + ignore(@sys.pwrite_bytes(memfd, Bytes::from_fixedarray(out), 0)) + self.present_fd(memfd, w, h) +} + +///| Put the little-endian ARGB8888 frame in `memfd` (w x h) in the window. Takes the fd. +fn X11Window::present_fd(self : X11Window, memfd : Int, w : Int, h : Int) -> Unit { + if self.use_shm { + let a : Array[Byte] = [] + put32(a, self.shm_seg) + put8(a, 1) // read-only + put8(a, 0) + put16(a, 0) + ignore(self.request(self.shm_major, 6, a, send_fd=memfd)) // ShmAttachFd + @sys.close_fd(memfd) + self.seg_attached = true + let p : Array[Byte] = [] + put32(p, self.win) + put32(p, self.gc) + put16(p, w) + put16(p, h) + put16(p, 0) + put16(p, 0) + put16(p, w) + put16(p, h) + put16(p, 0) + put16(p, 0) + put8(p, self.depth) + put8(p, 2) // ZPixmap + put8(p, 1) // send ShmCompletion + put8(p, 0) + put32(p, self.shm_seg) + put32(p, 0) + ignore(self.request(self.shm_major, 3, p)) // ShmPutImage + self.frame_pending = true + return + } + // Core PutImage in strips that fit the server's request size. + let t0 = @sys.monotonic_ms() + let data = @sys.mmap_read(memfd, w * 4 * h) + @sys.close_fd(memfd) + let t_read = @sys.monotonic_ms() - t0 + if data.length() < w * 4 * h { + return + } + let max_bytes = self.max_req * 4 - 24 + let rows = if w * 4 > max_bytes { 1 } else { max_bytes / (w * 4) } + let mut y = 0 + while y < h && !self.closed { + let n = if y + rows > h { h - y } else { rows } + let len = n * w * 4 // a multiple of 4: no padding + let req : FixedArray[Byte] = FixedArray::make(24 + len, b'\x00') + let hdr : Array[Byte] = [] + put8(hdr, 72) // PutImage + put8(hdr, 2) // ZPixmap + put16(hdr, (24 + len) / 4) + put32(hdr, self.win) + put32(hdr, self.gc) + put16(hdr, w) + put16(hdr, n) + put16(hdr, 0) + put16(hdr, y) + put8(hdr, 0) + put8(hdr, self.depth) + put16(hdr, 0) + for i = 0; i < 24; i = i + 1 { + req[i] = hdr[i] + } + req.blit_from_bytes(24, data, y * w * 4, len) + self.send_all(Bytes::from_fixedarray(req)) + self.seq = (self.seq + 1) & 0xFFFF + y = y + n + } + if @sys.getenv("CHANDRA_X11_DEBUG") != "" { + @sys.log("x11: PutImage frame " + (@sys.monotonic_ms() - t0).to_string() + " ms (read " + t_read.to_string() + " ms)") + } + // The reply to this tells us the server got through the frame. + self.pending_seq = self.request(43, 0, []) + self.frame_pending = true +} + +///| X cursor-font glyph for a wp_cursor_shape_v1 value. +fn cursor_glyph(shape : UInt) -> Int { + match shape { + 3 => 92 // help: question_arrow + 4 => 60 // pointer: hand2 + 5 | 6 => 150 // progress, wait: watch + 7 => 90 // cell: plus + 8 => 34 // crosshair + 9 | 10 => 152 // text: xterm + 13 | 17 | 32 => 52 // move, grabbing, all-scroll: fleur + 14 | 15 => 0 // no-drop, not-allowed: X_cursor + 16 => 58 // grab: hand1 + 18 => 96 // e-resize: right_side + 19 => 138 // n-resize: top_side + 20 => 136 // ne-resize + 21 => 134 // nw-resize + 22 => 16 // s-resize + 23 => 14 // se-resize + 24 => 12 // sw-resize + 25 => 70 // w-resize: left_side + 26 | 30 => 108 // ew-resize: sb_h_double_arrow + 27 | 31 => 116 // ns-resize: sb_v_double_arrow + 28 => 136 // nesw-resize: top_right_corner + 29 => 14 // nwse-resize: bottom_right_corner + _ => 68 // default: left_ptr + } +} + +///| Show cursor `shape` (wp_cursor_shape_v1) over the window, from the X cursor font. +pub fn X11Window::set_cursor_shape(self : X11Window, shape : UInt) -> Unit { + if shape == self.shape_applied || self.closed { + return + } + self.shape_applied = shape + let glyph = cursor_glyph(shape) + let cursor = match self.cursors.get(glyph) { + Some(c) => c + None => { + if self.cursor_font == 0 { + self.cursor_font = self.alloc_xid() + let name = ascii("cursor") + let f : Array[Byte] = [] + put32(f, self.cursor_font) + put16(f, name.length()) + put16(f, 0) + put_str(f, name) + ignore(self.request(45, 0, f)) // OpenFont + } + let c = self.alloc_xid() + let b : Array[Byte] = [] + put32(b, c) + put32(b, self.cursor_font) + put32(b, self.cursor_font) + put16(b, glyph) + put16(b, glyph + 1) + put16(b, 0) // black, outlined in white + put16(b, 0) + put16(b, 0) + put16(b, 0xFFFF) + put16(b, 0xFFFF) + put16(b, 0xFFFF) + ignore(self.request(94, 0, b)) // CreateGlyphCursor + self.cursors.set(glyph, c) + c + } + } + let b : Array[Byte] = [] + put32(b, self.win) + put32(b, 0x4000) // Cursor + put32(b, cursor) + ignore(self.request(2, 0, b)) // ChangeWindowAttributes +} + +///| The connection's fd, for an idle loop to block on. +pub fn X11Window::wait_fds(self : X11Window) -> Array[Int] { + [self.fd] +} + +///| +pub fn X11Window::close(self : X11Window) -> Unit { + @sys.close_fd(self.fd) + self.closed = true +} diff --git a/compositor/x11/x11_test.mbt b/compositor/x11/x11_test.mbt new file mode 100644 index 0000000..ce99bba --- /dev/null +++ b/compositor/x11/x11_test.mbt @@ -0,0 +1,54 @@ +///| +test "parse_display: local displays only" { + assert_eq(@x11.parse_display(":0"), Some((0, 0))) + assert_eq(@x11.parse_display(":1.2"), Some((1, 2))) + assert_eq(@x11.parse_display("unix:10"), Some((10, 0))) + assert_eq(@x11.parse_display("localhost:10.0"), None) + assert_eq(@x11.parse_display(""), None) + assert_eq(@x11.parse_display(":"), None) +} + +///| One Xauthority entry: family, address, display number, auth name, data (big-endian lengths). +fn xauth_entry(family : Int, addr : String, num : String, data : Array[Byte]) -> Array[Byte] { + let out : Array[Byte] = [] + fn field(b : Array[Byte]) -> Unit { + out.push(((b.length() >> 8) & 0xFF).to_byte()) + out.push((b.length() & 0xFF).to_byte()) + for c in b { + out.push(c) + } + } + + fn text(s : String) -> Array[Byte] { + let b : Array[Byte] = [] + for c in s { + b.push(c.to_int().to_byte()) + } + b + } + + out.push(((family >> 8) & 0xFF).to_byte()) + out.push((family & 0xFF).to_byte()) + field(text(addr)) + field(text(num)) + field(text("MIT-MAGIC-COOKIE-1")) + field(data) + out +} + +///| +test "xauth_cookie: picks this host's entry for the display" { + let file : Array[Byte] = [] + file.append(xauth_entry(256, "otherhost", "0", [b'\x01'])) + file.append(xauth_entry(256, "rig", "1", [b'\x02'])) + file.append(xauth_entry(256, "rig", "0", [b'\x03', b'\x04'])) + let f = Bytes::from_array(file) + assert_eq(@x11.xauth_cookie(f, 0, "rig").to_array(), [b'\x03', b'\x04']) + assert_eq(@x11.xauth_cookie(f, 1, "rig").to_array(), [b'\x02']) + // No entry for this host: any local one for the display. + assert_eq(@x11.xauth_cookie(f, 0, "elsewhere").to_array(), [b'\x01']) + assert_eq(@x11.xauth_cookie(f, 7, "rig").length(), 0) + // FamilyWild (xauth's "ffff" entries, as Docker setups write) matches any host. + let wild = Bytes::from_array(xauth_entry(0xFFFF, "", "0", [b'\x09'])) + assert_eq(@x11.xauth_cookie(wild, 0, "rig").to_array(), [b'\x09']) +} diff --git a/docs/x11.md b/docs/x11.md new file mode 100644 index 0000000..fb9ec95 --- /dev/null +++ b/docs/x11.md @@ -0,0 +1,85 @@ +# Running Chandra on Xorg (NVIDIA) + +`--x11` runs Chandra on an X server instead of on DRM/KMS. It exists for machines where the +display is NVIDIA's proprietary driver on Xorg: the driver draws the screen, Chandra is one X +client on it, and Wayland apps connect to Chandra as usual. + +``` +build/wasmhost build/compositor.wasm --socket "$XDG_RUNTIME_DIR/wayland-moon-0" --x11 +just run-x11 # the same, from the checkout +``` + +## Modes + +| Where | What `--x11` does | +| --- | --- | +| An X desktop with a window manager (GNOME on Xorg, KDE X11, Openbox...) | A normal, resizable window (`--size WxH`, default 1280x720). `--fullscreen` asks the window manager for a fullscreen window. | +| An X server with no window manager (`startx`, `xinit`, the "Chandra (X11)" login entry, a headless NVIDIA Xorg in a container) | Chandra covers the whole screen, takes the keyboard, and follows the screen when it is resized (`xrandr`, as Selkies does when the browser window changes size). | + +Chandra decides by looking for an EWMH window manager on the root window +(`_NET_SUPPORTING_WM_CHECK`). + +## As your login session + +`just install` also installs `/usr/share/xsessions/chandra-x11.desktop`. Pick **Chandra (X11)** on +the login screen (GDM, SDDM, LightDM): the display manager starts Xorg with the NVIDIA driver and +runs `chandra-session --x11`, which starts the compositor with `--x11 --login-session` (power +actions, the polkit password dialog and apps' dark/light preference, as in the DRM session). + +Without a display manager, put this in `~/.xinitrc` and run `startx` from a text console: + +``` +exec /usr/local/bin/chandra-session --x11 +``` + +The log is `~/.local/state/chandra/session.log`, as for the DRM session. + +## How it works + +`compositor/x11/x11.mbt` speaks the X11 wire protocol itself over `/tmp/.X11-unix/X`, like the +nested backend speaks Wayland: no libX11 or libxcb, and the same code runs in the wasm compositor +(either host) and in the native build. + +* **Authentication**: the `MIT-MAGIC-COOKIE-1` for the display from `$XAUTHORITY` (or + `~/.Xauthority`); this host's entry first, then a wildcard or any other local entry. +* **Frames**: MIT-SHM 1.2 with fd passing (`ShmAttachFd` + `ShmPutImage`). The host's framebuffer + memfd goes straight to the X server, so no pixels pass through the compositor, and the next + frame waits for the server's completion event. Needs a 24-bit TrueColor visual (any NVIDIA + setup at the default `DefaultDepth 24`). Without MIT-SHM it falls back to core `PutImage` in + strips, which is slow on the wasm hosts (about 2 frames a second at 1280x800, because the + pixels cross the component boundary); `CHANDRA_X11_NO_SHM=1` forces that path for debugging and + `CHANDRA_X11_DEBUG=1` logs its frame times. +* **Keyboard**: Xorg's keycodes are evdev codes + 8, the same as libinput's. The keymap sent to + Wayland clients is the X server's own (`xkbcomp -xkb $DISPLAY -`), so the layout and options + are whatever Xorg was configured with; after `setxkbmap` new apps get the new one. X's + auto-repeat is dropped (Wayland apps repeat keys themselves). Modifier and lock state come + from X's modifier map. +* **Pointer**: motion, buttons (left, middle, right, back, forward), wheel (buttons 4-7). The + cursor comes from the X cursor font, picked by the shape Chandra wants. +* **Input injection** (XTest, `xdotool`, Selkies, VNC servers) works, since it arrives as ordinary + X events. + +## Limits + +* **Apps don't get the NVIDIA GPU through Chandra.** Chandra composes on the CPU and its Wayland + clients share buffers with `wl_shm`; there is no `zwp_linux_dmabuf_v1` yet, so GPU-drawing apps + (games, Zed, Chrome with GPU raster) fall back to software rendering (llvmpipe/lavapipe) or + fail, exactly as on the DRM backend. Running on Xorg makes Chandra *start* on NVIDIA; it does not + give its apps hardware acceleration. See docs/kiosk-gamerig.md (G4). +* **X11-only apps run on the X server, not in Chandra.** `DISPLAY` stays set, so an app that only + speaks X11 (Steam, xterm) opens on Xorg directly: under a window manager it is a window beside + Chandra's; in whole-screen mode it maps on top of Chandra with no window manager to move it. + Chandra has no Xwayland. +* Only local displays (`:0`, `unix:0`): no TCP displays or `ssh -X`. +* Keyboard layout groups: the group is always reported as 0, so layout switching through XKB + groups (two layouts with a toggle key) shows the first layout's symbols in Wayland apps. +* One screen: Chandra covers the X screen it opened (multi-monitor setups are one big X screen + under NVIDIA's TwinView/xrandr, so Chandra spans all monitors). + +## Isn't there a KMS path on NVIDIA now? + +With the NVIDIA driver 545 or newer and `nvidia-drm.modeset=1` (the default from 560 on), NVIDIA +does offer KMS and dumb buffers, which is all `--drm` uses (no GBM, no EGL). So on a recent +driver the regular Chandra session may work too: try `just run-drm` from a text console. `--x11` +is for older drivers, `modeset=0` setups, and anywhere Xorg must stay the display server (a +streaming rig whose grabber reads the X screen). diff --git a/justfile b/justfile index fe085f8..7096f9c 100644 --- a/justfile +++ b/justfile @@ -45,6 +45,11 @@ run: compositor-wasm wasmhost modules build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --window # The same on the Rust host (host-wasm), kept as a fallback while the MoonBit host settles in. +# On an X server (NVIDIA's proprietary driver, docs/x11.md): a window under a window manager, or the whole screen without one. +run-x11: compositor-wasm wasmhost modules + rm -f {{socket}} + build/wasmhost build/compositor.wasm --socket {{socket}} --theme {{theme}} --x11 + run-rust: compositor-wasm host-wasm modules rm -f {{socket}} host-wasm/target/release/chandra-host build/compositor.wasm --socket {{socket}} --theme {{theme}} --window diff --git a/scripts/test.sh b/scripts/test.sh index 06fefb5..a410c85 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -52,5 +52,5 @@ if [ -d "$WASMER/lib" ]; then fi XDG_CONFIG_HOME="$(mktemp -d)" CHANDRA_TEST_CONFIG=1 \ moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm \ - compositor/network compositor/portal compositor/polkit compositor/host + compositor/network compositor/portal compositor/polkit compositor/x11 compositor/host moon build --target native --warn-list -a compositor/bin diff --git a/session/chandra-session b/session/chandra-session index c4efc13..ff27ea3 100755 --- a/session/chandra-session +++ b/session/chandra-session @@ -1,7 +1,10 @@ #!/bin/sh # Login-session entry point for Chandra (started by the display manager). # Runs the compositor on the seat's display via DRM/KMS + libinput and logs to -# ~/.local/state/chandra/session.log. By default that is the compositor as a +# ~/.local/state/chandra/session.log. With --x11 (the "Chandra (X11)" entry in +# /usr/share/xsessions, or `exec chandra-session --x11` in ~/.xinitrc) it runs on the X server +# in $DISPLAY instead and covers the whole screen: for GPUs whose driver gives Chandra no KMS +# path, such as NVIDIA's proprietary one (docs/x11.md). By default that is the compositor as a # WebAssembly component, run by chandra-host; if only the native binary was installed # (session/install.py --native), it runs that instead. share=/usr/local/share/chandra @@ -28,6 +31,22 @@ if [ -z "$XDG_RUNTIME_DIR" ] && [ -d "/run/user/$(id -u)" ] && [ -O "/run/user/$ fi case "$0" in /*) self="$0" ;; *) self="$PWD/$0" ;; esac # for the dbus-run-session re-exec +# The display backend: drm (default) or x11. Kept in the environment so the dbus-run-session +# re-exec below (which drops the arguments) still knows. +if [ "${1:-}" = "--x11" ]; then + export CHANDRA_BACKEND=x11 +fi +case "${CHANDRA_BACKEND:-drm}" in + x11) + backend="--x11 --login-session" + if [ -z "${DISPLAY:-}" ]; then + echo "chandra-session: --x11 needs DISPLAY (start it from an X session or ~/.xinitrc)" >&2 + exit 1 + fi + ;; + *) backend=--drm ;; +esac + export XDG_SESSION_TYPE=wayland export XDG_CURRENT_DESKTOP=chandra export XDG_SESSION_DESKTOP=chandra @@ -95,7 +114,7 @@ fi if command -v dbus-update-activation-environment >/dev/null 2>&1; then dbus-update-activation-environment --systemd \ WAYLAND_DISPLAY="$(basename "$sock")" XDG_SESSION_TYPE XDG_CURRENT_DESKTOP \ - XDG_SESSION_DESKTOP QT_QPA_PLATFORM QT_QPA_PLATFORMTHEME >>"$log" 2>&1 || + XDG_SESSION_DESKTOP QT_QPA_PLATFORM QT_QPA_PLATFORMTHEME ${DISPLAY:+DISPLAY} >>"$log" 2>&1 || dbus-update-activation-environment \ WAYLAND_DISPLAY="$(basename "$sock")" XDG_SESSION_TYPE XDG_CURRENT_DESKTOP \ XDG_SESSION_DESKTOP QT_QPA_PLATFORM QT_QPA_PLATFORMTHEME >>"$log" 2>&1 || true @@ -122,7 +141,7 @@ fi # A logind session without a seat (made by run0 --user=..., su - or ssh rather than by logging in # on the VT) can't open the screen and input devices through logind; say so in the log, since # the compositor's own error ("could not take control of the session") doesn't explain why. -if [ -n "$XDG_SESSION_ID" ] && command -v loginctl >/dev/null 2>&1; then +if [ "$backend" = --drm ] && [ -n "$XDG_SESSION_ID" ] && command -v loginctl >/dev/null 2>&1; then seat=$(loginctl show-session "$XDG_SESSION_ID" -p Seat --value 2>/dev/null) if [ -z "$seat" ]; then echo "chandra-session: login session $XDG_SESSION_ID has no seat (started by run0, su or" \ @@ -157,5 +176,5 @@ for a in \ done export CHANDRA_POLKIT_FALLBACK="$fallback" -exec "$@" --drm --socket "$sock" \ +exec "$@" $backend --socket "$sock" \ --theme "$share/config/themes/moon-night.json" >>"$log" 2>&1 diff --git a/session/chandra-x11.desktop b/session/chandra-x11.desktop new file mode 100644 index 0000000..378036e --- /dev/null +++ b/session/chandra-x11.desktop @@ -0,0 +1,7 @@ +[Desktop Entry] +Name=Chandra (X11) +Comment=Chandra desktop on the Xorg server, for GPUs without a KMS path Chandra can use (NVIDIA's proprietary driver) +Exec=/usr/local/bin/chandra-session --x11 +TryExec=/usr/local/bin/chandra-session +Type=Application +DesktopNames=chandra diff --git a/session/install.py b/session/install.py index 692b103..61a05b2 100755 --- a/session/install.py +++ b/session/install.py @@ -30,6 +30,7 @@ Installs: /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/share/wayland-sessions/chandra.desktop display-manager entry + /usr/share/xsessions/chandra-x11.desktop display-manager entry on Xorg (NVIDIA; docs/x11.md) /usr/share/xdg-desktop-portal/portals/chandra.portal xdg-desktop-portal backend: the compositor /usr/share/xdg-desktop-portal/chandra-portals.conf serves Settings (apps' dark/light preference) """ @@ -56,6 +57,7 @@ targets = [ "/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraLight.colors", "/usr/share/wayland-sessions/chandra.desktop", + "/usr/share/xsessions/chandra-x11.desktop", "/usr/share/xdg-desktop-portal/portals/chandra.portal", "/usr/share/xdg-desktop-portal/chandra-portals.conf", ] @@ -144,6 +146,8 @@ for f in ("ChandraDark.colors", "ChandraLight.colors"): put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644) # 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) +# The same desktop on an X server (the display manager starts Xorg): for NVIDIA's proprietary driver. +put(os.path.join(root, "session/chandra-x11.desktop"), "/usr/share/xsessions/chandra-x11.desktop", 0o644) # xdg-desktop-portal reads backends only from /usr/share (or $XDG_DESKTOP_PORTAL_DIR), not # /usr/local. With XDG_CURRENT_DESKTOP=chandra and no chandra-portals.conf it offered apps no # Settings portal at all, so Chrome, Firefox, GTK 4 and Qt 6 never saw the Dark mode switch; the