///| 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 }