Files
chandra/compositor/x11/x11.mbt
T
nandi 1871d50a3e
CI / test (push) Failing after 2m37s
X11 dock bridge: show and control host EWMH windows under --x11
Under --x11 with a host EWMH window manager (e.g. Openbox in Gamerig),
Chandra is one top-level X11 client while other apps run directly on Xorg,
so the dock only saw Chandra's Wayland windows.

- compositor/x11: intern EWMH/ICCCM atoms and track _NET_CLIENT_LIST,
  _NET_ACTIVE_WINDOW, titles, and window states via PropertyChangeMask,
  filtering non-taskbar/child windows and adding focus, close, minimize,
  and toggle-maximize EWMH/ICCCM actions.
- compositor/shell: add resolve_external_app_id (matching WM_CLASS and
  StartupWMClass against installed .desktop files) and publish_windows.
- compositor/host: bridge ExternalWindow entries with bit-30 tagged IDs
  into shell.windows/win_list while keeping Wayland wm.windows and session
  snapshots untouched, and route activate_task / window_command actions.
- compositor/app, compositor/bin, docs/x11.md: wire external window sync
  before X11 input handling and register ExternalWindowHandler.

Verified: moon test --target native compositor/x11 compositor/shell (38/38),
external_windows_test.mbt + dock_test.mbt (3/3), build-compositor-wasm.sh,
and moon build --target native compositor/bin.
2026-11-27 14:33:26 -08:00

1847 lines
51 KiB
MoonBit

///| 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.
///| One top-level X11 client window reported by the host EWMH window manager (`_NET_CLIENT_LIST`).
pub(all) struct ExternalWindow {
xid : Int
wm_class : String
wm_instance : String
title : String
focused : Bool
minimized : Bool
maximized : Bool
} derive(Eq, Debug)
///|
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
mut a_net_wm_name : Int
mut a_net_client_list : Int
mut a_net_active_window : Int
mut a_net_close_window : Int
mut a_net_wm_state : Int
mut a_net_wm_state_hidden : Int
mut a_net_wm_state_skip_taskbar : Int
mut a_net_wm_state_max_vert : Int
mut a_net_wm_state_max_horz : Int
mut a_net_wm_window_type : Int
mut a_net_wm_window_type_normal : Int
mut a_net_wm_window_type_dialog : Int
mut a_wm_change_state : Int
mut a_wm_state : Int
// External EWMH windows (when running under an X11 window manager).
mut ext_windows : Array[ExternalWindow]
mut ext_dirty : Bool
mut ext_changed : Bool
mut ext_watched : Map[Int, Bool]
// 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.replies.remove(self.seq)
self.errors.remove(self.seq)
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))
}
///| Send a GetProperty request for `prop` on window `w` and return its sequence number.
fn X11Window::request_prop(self : X11Window, w : Int, prop : Int) -> Int {
let b : Array[Byte] = []
put32(b, w)
put32(b, prop)
put32(b, 0) // AnyPropertyType
put32(b, 0)
put32(b, 16384)
self.request(20, 0, b)
}
///| Read a GetProperty reply for sequence `seq` as raw bytes; None if unset or errored.
fn X11Window::read_prop(self : X11Window, seq : Int) -> Array[Byte]? {
match self.wait_reply(seq) {
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)
}
}
}
///| 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]? {
self.read_prop(self.request_prop(w, prop))
}
///| Parse ICCCM `WM_CLASS` bytes (`instance\0class\0`) into `(instance, class)`.
pub fn parse_wm_class(raw : Array[Byte]) -> (String, String) {
let parts : Array[Array[Byte]] = []
let mut cur : Array[Byte] = []
for b in raw {
if b == b'\x00' {
parts.push(cur)
cur = []
} else {
cur.push(b)
}
}
if cur.length() > 0 {
parts.push(cur)
}
let inst = if parts.length() >= 1 {
@utf8.decode_lossy(Bytes::from_array(parts[0]))
} else {
""
}
let cls = if parts.length() >= 2 {
@utf8.decode_lossy(Bytes::from_array(parts[1]))
} else {
""
}
(inst, cls)
}
///| Parse a 32-bit property (CARDINAL/ATOM/WINDOW list) from little-endian bytes.
pub fn parse_u32_list(raw : Array[Byte]) -> Array[Int] {
let out : Array[Int] = []
let n = raw.length() / 4
for i = 0; i < n; i = i + 1 {
out.push(get32(raw, i * 4))
}
out
}
///| Whether an X11 window from `_NET_CLIENT_LIST` should appear in the dock/taskbar.
pub fn is_taskbar_window(
w : Int,
self_win : Int,
states : Array[Int],
skip_taskbar : Int,
types : Array[Int],
normal_type : Int,
dialog_type : Int,
transient_for : Int,
client_set : Map[Int, Bool],
) -> Bool {
if w == 0 || w == self_win {
return false
}
if skip_taskbar != 0 && states.contains(skip_taskbar) {
return false
}
if types.length() > 0 {
let ok = (normal_type != 0 && types.contains(normal_type)) ||
(dialog_type != 0 && types.contains(dialog_type))
if !ok {
return false
}
}
if transient_for != 0 && client_set.contains(transient_for) {
return false
}
true
}
///| Build the 40-byte `SendEvent` (opcode 25) body for a 32-bit EWMH/ICCCM ClientMessage on `root`.
pub fn build_client_msg_body(
root : Int,
target : Int,
msg_type : Int,
d0 : Int,
d1 : Int,
d2 : Int,
d3 : Int,
d4 : Int,
) -> Array[Byte] {
let b : Array[Byte] = []
put32(b, root)
put32(b, 0x180000) // SubstructureRedirectMask | SubstructureNotifyMask
put8(b, 33) // ClientMessage
put8(b, 32) // format 32
put16(b, 0) // sequence
put32(b, target)
put32(b, msg_type)
put32(b, d0)
put32(b, d1)
put32(b, d2)
put32(b, d3)
put32(b, d4)
b
}
///| Build the 12-byte `ConfigureWindow` (opcode 12) body to raise `target` to the top (`StackMode=Above`).
pub fn build_raise_body(target : Int) -> Array[Byte] {
let b : Array[Byte] = []
put32(b, target)
put16(b, 0x40) // CWStackMode
put16(b, 0)
put32(b, 0) // Above
b
}
// ---- 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_formats {
if get8(rx, off) == 24 {
bpp24 = get8(rx, off + 1)
}
off = off + 8
}
let mut root = 0
let mut root_w = 0
let mut root_h = 0
let mut root_visual = 0
let mut root_depth = 0
let mut visual = 0
let mut depth = 0
for s = 0; s < n_screens; s = s + 1 {
let this = s == screen_no || (s == 0 && screen_no >= 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..<n_depths {
let d = get8(rx, off)
let n_vis = get16(rx, off + 2)
off = off + 8
for _ in 0..<n_vis {
let vid = get32(rx, off)
let class = get8(rx, off + 4)
let red = get32(rx, off + 8)
let green = get32(rx, off + 12)
let blue = get32(rx, off + 16)
// A 24-bit TrueColor visual whose pixels are 0x00RRGGBB, so our little-endian ARGB8888
// frames go in unchanged. Prefer the root visual.
if this &&
d == 24 &&
class == 4 &&
red == 0xFF0000 &&
green == 0xFF00 &&
blue == 0xFF &&
(visual == 0 || vid == root_visual) {
visual = vid
depth = d
}
off = off + 24
}
}
}
if visual == 0 || bpp24 != 32 {
@sys.log(
"x11: no 24-bit TrueColor visual with 32 bits per pixel on this screen (root depth " +
root_depth.to_string() +
")",
)
@sys.close_fd(fd)
return None
}
let self : X11Window = {
fd,
input: [],
keymap: Bytes::from_array([]),
rx: [],
seq: 0,
replies: {},
errors: {},
id_base,
id_mask,
next_xid: 1,
max_req,
root,
root_w,
root_h,
depth,
visual,
win: 0,
gc: 0,
session: false,
width,
height,
resized: false,
redraw: true,
closed: false,
mapped: false,
a_wm_protocols: 0,
a_wm_delete: 0,
a_net_wm_name: 0,
a_net_client_list: 0,
a_net_active_window: 0,
a_net_close_window: 0,
a_net_wm_state: 0,
a_net_wm_state_hidden: 0,
a_net_wm_state_skip_taskbar: 0,
a_net_wm_state_max_vert: 0,
a_net_wm_state_max_horz: 0,
a_net_wm_window_type: 0,
a_net_wm_window_type_normal: 0,
a_net_wm_window_type_dialog: 0,
a_wm_change_state: 0,
a_wm_state: 0,
ext_windows: [],
ext_dirty: false,
ext_changed: false,
ext_watched: {},
shm_major: -1,
shm_event: -1,
shm_seg: 0,
use_shm: false,
seg_attached: false,
frame_pending: false,
pending_seq: -1,
mod_of_key: {},
lock_mask: 0,
pressed: {},
locked: 0,
sent_dep: 0,
sent_lock: -1,
mapping_changed: false,
cursor_font: 0,
cursors: {},
shape_applied: 0U,
errors_logged: 0,
}
self.a_wm_protocols = self.intern("WM_PROTOCOLS")
self.a_wm_delete = self.intern("WM_DELETE_WINDOW")
self.a_net_wm_name = self.intern("_NET_WM_NAME")
let a_utf8 = self.intern("UTF8_STRING")
self.a_net_wm_state = self.intern("_NET_WM_STATE")
let a_fullscreen = self.intern("_NET_WM_STATE_FULLSCREEN")
let a_wm_check = self.intern("_NET_SUPPORTING_WM_CHECK")
let a_pid = self.intern("_NET_WM_PID")
self.a_net_client_list = self.intern("_NET_CLIENT_LIST")
self.a_net_active_window = self.intern("_NET_ACTIVE_WINDOW")
self.a_net_close_window = self.intern("_NET_CLOSE_WINDOW")
self.a_net_wm_state_hidden = self.intern("_NET_WM_STATE_HIDDEN")
self.a_net_wm_state_skip_taskbar = self.intern("_NET_WM_STATE_SKIP_TASKBAR")
self.a_net_wm_state_max_vert = self.intern("_NET_WM_STATE_MAXIMIZED_VERT")
self.a_net_wm_state_max_horz = self.intern("_NET_WM_STATE_MAXIMIZED_HORZ")
self.a_net_wm_window_type = self.intern("_NET_WM_WINDOW_TYPE")
self.a_net_wm_window_type_normal = self.intern("_NET_WM_WINDOW_TYPE_NORMAL")
self.a_net_wm_window_type_dialog = self.intern("_NET_WM_WINDOW_TYPE_DIALOG")
self.a_wm_change_state = self.intern("WM_CHANGE_STATE")
self.a_wm_state = self.intern("WM_STATE")
// A window manager announces itself on the root window (EWMH); without one, take the screen.
// The property outlives a window manager that was killed, so also check that the window it
// names still exists and points at itself (EWMH).
let has_wm = match self.get_prop(root, a_wm_check) {
Some(v) if v.length() >= 4 => {
let child = get32(v, 0)
match self.get_prop(child, a_wm_check) {
Some(c) if c.length() >= 4 && get32(c, 0) == child => true
_ => false
}
}
_ => 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 self.a_net_wm_name != 0 && a_utf8 != 0 {
self.set_prop(self.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 && self.a_net_wm_state != 0 && a_fullscreen != 0 {
let p : Array[Byte] = []
put32(p, a_fullscreen)
self.set_prop(self.a_net_wm_state, 4, 32, p)
}
// Follow the screen size (xrandr) when the window is the screen; under a WM, watch EWMH root props.
if self.session {
let cw : Array[Byte] = []
put32(cw, root)
put32(cw, 0x800)
put32(cw, 0x20000) // StructureNotify
ignore(self.request(2, 0, cw))
} else {
let cw : Array[Byte] = []
put32(cw, root)
put32(cw, 0x800)
put32(cw, 0x400000) // PropertyChangeMask
ignore(self.request(2, 0, cw))
self.ext_dirty = true
}
// 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 &&
!(err == 3 && (major == 2 || major == 12 || major == 20 || major == 25)) {
// (BadWindow on ChangeWindowAttributes / ConfigureWindow / GetProperty / SendEvent is a client that closed.)
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
}
}
28 => {
// PropertyNotify: EWMH window list, active window, or watched client properties changed.
if !self.session {
let w = get32(rx, off + 4)
let atom = get32(rx, off + 8)
if w == self.root {
if atom == self.a_net_client_list || atom == self.a_net_active_window {
self.ext_dirty = true
}
} else if self.ext_watched.contains(w) {
if atom == self.a_net_wm_name ||
atom == 39 ||
atom == 67 ||
atom == self.a_net_wm_state ||
atom == self.a_wm_state ||
atom == self.a_net_wm_window_type ||
atom == 68 {
self.ext_dirty = true
}
}
}
}
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) -----------------------------
///| Re-read `_NET_CLIENT_LIST`, `_NET_ACTIVE_WINDOW`, and each taskbar window's metadata.
fn X11Window::refresh_external_windows(self : X11Window) -> Unit {
if self.session || self.closed || self.a_net_client_list == 0 {
return
}
let client_ids = match self.get_prop(self.root, self.a_net_client_list) {
Some(b) => parse_u32_list(b)
None => []
}
let active_win = if self.a_net_active_window != 0 {
match self.get_prop(self.root, self.a_net_active_window) {
Some(b) => {
let ids = parse_u32_list(b)
if ids.length() > 0 { ids[0] } else { 0 }
}
None => 0
}
} else {
0
}
let client_set : Map[Int, Bool] = {}
for w in client_ids {
if w != 0 && w != self.win {
client_set.set(w, true)
if !self.ext_watched.contains(w) {
let cw : Array[Byte] = []
put32(cw, w)
put32(cw, 0x800) // CWEventMask
put32(cw, 0x400000) // PropertyChangeMask
ignore(self.request(2, 0, cw))
}
}
}
self.ext_watched = client_set
let next : Array[ExternalWindow] = []
for w in client_ids {
if w == 0 || w == self.win {
continue
}
let s_state = if self.a_net_wm_state != 0 { Some(self.request_prop(w, self.a_net_wm_state)) } else { None }
let s_type = if self.a_net_wm_window_type != 0 {
Some(self.request_prop(w, self.a_net_wm_window_type))
} else {
None
}
let s_trans = self.request_prop(w, 68) // WM_TRANSIENT_FOR
let s_class = self.request_prop(w, 67) // WM_CLASS
let s_net_name = if self.a_net_wm_name != 0 { Some(self.request_prop(w, self.a_net_wm_name)) } else { None }
let s_name = self.request_prop(w, 39) // WM_NAME
let s_wm_state = if self.a_wm_state != 0 { Some(self.request_prop(w, self.a_wm_state)) } else { None }
let read_opt = fn(seq : Int?) -> Array[Byte]? {
match seq {
Some(s) => self.read_prop(s)
None => None
}
}
let states = match read_opt(s_state) {
Some(b) => parse_u32_list(b)
None => []
}
let types = match read_opt(s_type) {
Some(b) => parse_u32_list(b)
None => []
}
let transient_for = match self.read_prop(s_trans) {
Some(b) => {
let ids = parse_u32_list(b)
if ids.length() > 0 { ids[0] } else { 0 }
}
None => 0
}
let (wm_instance, wm_class) = match self.read_prop(s_class) {
Some(b) => parse_wm_class(b)
None => ("", "")
}
let net_name = read_opt(s_net_name)
let legacy_name = self.read_prop(s_name)
let title = match net_name {
Some(b) if b.length() > 0 => @utf8.decode_lossy(Bytes::from_array(b))
_ =>
match legacy_name {
Some(b) => @utf8.decode_lossy(Bytes::from_array(b))
None => ""
}
}
let wm_state_iconic = match read_opt(s_wm_state) {
Some(b) => {
let vals = parse_u32_list(b)
vals.length() > 0 && vals[0] == 3
}
None => false
}
if !is_taskbar_window(
w,
self.win,
states,
self.a_net_wm_state_skip_taskbar,
types,
self.a_net_wm_window_type_normal,
self.a_net_wm_window_type_dialog,
transient_for,
client_set,
) {
continue
}
if wm_class == "" && wm_instance == "" && title == "" {
continue
}
let minimized = (self.a_net_wm_state_hidden != 0 && states.contains(self.a_net_wm_state_hidden)) ||
wm_state_iconic
let maximized = (self.a_net_wm_state_max_vert != 0 && states.contains(self.a_net_wm_state_max_vert)) ||
(self.a_net_wm_state_max_horz != 0 && states.contains(self.a_net_wm_state_max_horz))
next.push({
xid: w,
wm_class,
wm_instance,
title,
focused: w == active_win,
minimized,
maximized,
})
}
if next != self.ext_windows {
self.ext_windows = next
self.ext_changed = true
}
}
///| 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
}
}
if self.ext_dirty && !self.session && !self.closed {
self.ext_dirty = false
self.refresh_external_windows()
}
!self.closed
}
///| Updated external X11 window list if `_NET_CLIENT_LIST`, focus, titles, or states changed.
pub fn X11Window::take_external_windows(self : X11Window) -> Array[ExternalWindow]? {
if !self.ext_changed {
return None
}
self.ext_changed = false
Some(self.ext_windows.copy())
}
///| Send a 32-bit EWMH/ICCCM ClientMessage on the root window targeting `target`.
fn X11Window::send_client_msg(
self : X11Window,
target : Int,
msg_type : Int,
d0 : Int,
d1 : Int,
d2 : Int,
d3 : Int,
d4 : Int,
) -> Unit {
if self.closed || target == 0 || msg_type == 0 {
return
}
ignore(self.request(25, 0, build_client_msg_body(self.root, target, msg_type, d0, d1, d2, d3, d4)))
}
///| Ask the host EWMH window manager to restore, focus, and raise external window `xid`.
pub fn X11Window::focus_external(self : X11Window, xid : Int) -> Unit {
if self.closed || xid == 0 {
return
}
self.send_client_msg(xid, self.a_net_active_window, 2, 0, 0, 0, 0)
ignore(self.request(12, 0, build_raise_body(xid)))
}
///| Ask the host EWMH window manager to close external window `xid`.
pub fn X11Window::close_external(self : X11Window, xid : Int) -> Unit {
self.send_client_msg(xid, self.a_net_close_window, 0, 2, 0, 0, 0)
}
///| Ask the host EWMH window manager to minimize (iconify) external window `xid`.
pub fn X11Window::minimize_external(self : X11Window, xid : Int) -> Unit {
self.send_client_msg(xid, self.a_wm_change_state, 3, 0, 0, 0, 0)
}
///| Ask the host EWMH window manager to focus and toggle maximized state on external window `xid`.
pub fn X11Window::toggle_maximize_external(self : X11Window, xid : Int) -> Unit {
if self.closed || xid == 0 {
return
}
self.focus_external(xid)
if self.a_net_wm_state != 0 &&
(self.a_net_wm_state_max_vert != 0 || self.a_net_wm_state_max_horz != 0) {
self.send_client_msg(
xid,
self.a_net_wm_state,
2,
self.a_net_wm_state_max_vert,
self.a_net_wm_state_max_horz,
2,
0,
)
}
}
///| 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
}