X11 dock bridge: show and control host EWMH windows under --x11
CI / test (push) Failing after 2m37s

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.
This commit is contained in:
nandi committed 2026-11-27 14:33:26 -08:00
1 parent 15b7c3f0e3
commit 1871d50a3e
12 files changed
+949 -68

No files matched your search

+34
View File
@@ -257,6 +257,21 @@ pub fn run(args : Array[String]) -> Int {
Some(k) => comp.server.set_keymap(k.keymap)
None => ()
}
match xwin {
Some(x) =>
comp.set_external_window_handler({
focus: fn(xid) { x.focus_external(xid) },
command: fn(xid, cmd) {
match cmd {
Close => x.close_external(xid)
Minimize => x.minimize_external(xid)
Restore => x.focus_external(xid)
ToggleMaximize => x.toggle_maximize_external(xid)
}
},
})
None => ()
}
@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)))
@@ -427,6 +442,25 @@ pub fn run(args : Array[String]) -> Int {
if x.keymap.length() > 0 {
comp.server.set_keymap(x.keymap)
}
match x.take_external_windows() {
Some(ext) => {
comp.set_external_windows(
ext.map(fn(w) -> @host.ExternalWindow {
{
host_id: w.xid,
wm_class: w.wm_class,
wm_instance: w.wm_instance,
title: w.title,
focused: w.focused,
minimized: w.minimized,
maximized: w.maximized,
}
}),
)
busy = true
}
None => ()
}
// The window or the screen (xrandr) changed size: draw the desktop at the new size.
match x.take_resize() {
Some((nw, nh)) => {
+32
View File
@@ -170,6 +170,21 @@ fn main {
Some(k) => comp.server.set_keymap(k.keymap)
None => ()
}
match xwin {
Some(x) =>
comp.set_external_window_handler({
focus: fn(xid) { x.focus_external(xid) },
command: fn(xid, cmd) {
match cmd {
Close => x.close_external(xid)
Minimize => x.minimize_external(xid)
Restore => x.focus_external(xid)
ToggleMaximize => x.toggle_maximize_external(xid)
}
},
})
None => ()
}
println("chandra compositor listening on " + socket_path + " (wasi-gfx surface active)")
// 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)))
@@ -241,6 +256,23 @@ fn main {
if x.keymap.length() > 0 {
comp.server.set_keymap(x.keymap)
}
match x.take_external_windows() {
Some(ext) =>
comp.set_external_windows(
ext.map(fn(w) -> @host.ExternalWindow {
{
host_id: w.xid,
wm_class: w.wm_class,
wm_instance: w.wm_instance,
title: w.title,
focused: w.focused,
minimized: w.minimized,
maximized: w.maximized,
}
}),
)
None => ()
}
match x.take_resize() {
Some((nw, nh)) => comp.resize(nw, nh)
None => ()
+27 -40
View File
@@ -309,6 +309,9 @@ pub(all) struct ChandraCompositor {
/// 1 minimize, 2 maximize, 3 close. A press shows pressed; the release over it acts.
mut deco_hover : (UInt64, Int)?
mut deco_pressed : (UInt64, Int)?
/// External windows from the host X11 WM (`--x11`), bridged into the dock/panel only.
mut ext_windows : Array[ExternalWindow]
mut ext_handler : ExternalWindowHandler?
}
///|
@@ -443,6 +446,8 @@ pub fn ChandraCompositor::new(
rec_press: false,
last_recording: "",
kiosk: None,
ext_windows: [],
ext_handler: None,
}
// Client popups (menus) are placed to stay on screen: the server asks for the output's
// rectangle relative to the parent's content origin when it applies constraint adjustment.
@@ -1118,46 +1123,7 @@ fn ChandraCompositor::build_scene(
@wm.LayoutMode::Monocle => 1
@wm.LayoutMode::Floating => 2
}
// The task list shows every window, minimized ones too (so they can be restored).
let wins : Array[@shell.WinInfo] = []
for wid in order {
match self.windows.get(wid) {
Some(win) =>
wins.push({
id: win.id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: win.focused,
minimized: false,
maximized: win.maximized,
})
None => ()
}
}
for id, r in self.wm.windows {
if r.minimized {
match self.windows.get(id) {
Some(win) =>
wins.push({
id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: false,
minimized: true,
maximized: win.maximized,
})
None => ()
}
}
}
self.shell.windows = wins
// The window list the `windows` interface serves to wasm widgets (task-bar order).
let entries : Array[@wasm.WindowEntry] = []
for w in wins {
match self.windows.get(w.id) {
Some(win) => entries.push({ id: w.id, title: w.title, app_id: win.app_id, focused: w.focused })
None => ()
}
}
self.shell.win_list = entries
self.sync_shell_windows()
self.shell.screenshot_state = (if self.rec is Some(_) { 1 } else { 0 }) |
(if self.rec_pointer { 2 } else { 0 })
// A window over the whole desktop (maximized, fullscreen, monocle) pauses a desktop module's
@@ -1714,6 +1680,16 @@ fn ChandraCompositor::activate_window(self : ChandraCompositor, wid : UInt64) ->
///| Restore a minimized window (or focus a visible one) from its task-bar pill.
fn ChandraCompositor::activate_task(self : ChandraCompositor, wid : UInt64) -> Unit {
match external_host_id(wid) {
Some(xid) => {
match self.ext_handler {
Some(h) => (h.focus)(xid)
None => ()
}
return
}
None => ()
}
let minimized = match self.wm.windows.get(wid) {
Some(r) => r.minimized
None => return
@@ -1735,6 +1711,17 @@ fn ChandraCompositor::window_command(
wid : UInt64,
cmd : @shell.WindowCommand,
) -> Unit {
match external_host_id(wid) {
Some(xid) => {
match self.ext_handler {
Some(h) => (h.command)(xid, cmd)
None => ()
}
self.damage.mark_full()
return
}
None => ()
}
if self.wm.windows.get(wid) is None {
return
}
+125
View File
@@ -0,0 +1,125 @@
///| Bridge external windows (from a host X11 EWMH window manager under `--x11`) into the
/// shell's task/dock window list without mixing them into Chandra's own Wayland window table.
///
/// X11 window IDs (XIDs) are 29-bit unsigned values (`0..0x1FFF_FFFF`). Tagging them with bit 30
/// (`0x4000_0000`) keeps them disjoint from Chandra's sequential Wayland window IDs while staying
/// strictly positive in signed 32-bit ints, as required by the wasm `windows` / `mp_wasm_take_focus`
/// boundary.
///| Bit 30 tag distinguishing host-managed external windows from Wayland client windows.
pub let external_window_tag : UInt64 = 0x4000_0000UL
///| Encode a 29-bit host X11 window ID into a synthetic compositor window ID.
pub fn external_wid(host_id : Int) -> UInt64 {
external_window_tag | (host_id & 0x1FFF_FFFF).reinterpret_as_uint().to_uint64()
}
///| Extract the host X11 window ID from a synthetic external window ID, or None for Wayland windows.
pub fn external_host_id(wid : UInt64) -> Int? {
if (wid & external_window_tag) != 0UL {
Some((wid & 0x1FFF_FFFFUL).to_int())
} else {
None
}
}
///| External top-level window reported by the host display server / WM.
pub(all) struct ExternalWindow {
host_id : Int
wm_class : String
wm_instance : String
title : String
focused : Bool
minimized : Bool
maximized : Bool
} derive(Eq, Debug)
///| Callbacks executed when the dock or panel acts on an external window.
pub(all) struct ExternalWindowHandler {
focus : (Int) -> Unit
command : (Int, @shell.WindowCommand) -> Unit
}
///| Register the handler for focus/close/minimize/maximize requests on external windows.
pub fn ChandraCompositor::set_external_window_handler(
self : ChandraCompositor,
handler : ExternalWindowHandler,
) -> Unit {
self.ext_handler = Some(handler)
}
///| Rebuild `shell.windows` and `shell.win_list` from Chandra's Wayland windows followed by any
/// external windows from the host window manager.
pub fn ChandraCompositor::sync_shell_windows(self : ChandraCompositor) -> Unit {
let order = self.wm.stacking_order()
// The task list shows every window, minimized ones too (so they can be restored).
let wins : Array[@shell.WinInfo] = []
for wid in order {
match self.windows.get(wid) {
Some(win) =>
wins.push({
id: win.id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: win.focused,
minimized: false,
maximized: win.maximized,
})
None => ()
}
}
for id, r in self.wm.windows {
if r.minimized {
match self.windows.get(id) {
Some(win) =>
wins.push({
id,
title: if win.title.length() > 0 { win.title } else { win.app_id },
focused: false,
minimized: true,
maximized: win.maximized,
})
None => ()
}
}
}
// The window list the `windows` interface serves to wasm widgets (task-bar order).
let entries : Array[@wasm.WindowEntry] = []
for w in wins {
match self.windows.get(w.id) {
Some(win) => entries.push({ id: w.id, title: w.title, app_id: win.app_id, focused: w.focused })
None => ()
}
}
for ew in self.ext_windows {
let wid = external_wid(ew.host_id)
let app_id = self.shell.resolve_external_app_id(ew.wm_class, ew.wm_instance, ew.title)
let title = if ew.title.length() > 0 { ew.title } else { app_id }
wins.push({
id: wid,
title,
focused: ew.focused,
minimized: ew.minimized,
maximized: ew.maximized,
})
entries.push({ id: wid, title, app_id, focused: ew.focused })
}
self.shell.windows = wins
self.shell.win_list = entries
}
///| Replace the external window list, immediately refresh shell tables if booted, and mark dirty.
pub fn ChandraCompositor::set_external_windows(
self : ChandraCompositor,
wins : Array[ExternalWindow],
) -> Unit {
if wins == self.ext_windows {
return
}
self.ext_windows = wins
self.sync_shell_windows()
if self.shell.booted {
self.shell.publish_windows()
}
self.damage.mark_full()
self.last_sig = None
}
+152
View File
@@ -0,0 +1,152 @@
///| Host integration tests for external X11 EWMH windows bridged into the dock/panel.
/// Needs the dock module built: scripts/build-modules.sh.
///| Pick row `label` of the open right-click menu (26 px title, then 28 px per row).
fn ext_dock_pick(comp : @host.ChandraCompositor, label : String, t : UInt) -> Unit raise {
let i = comp.shell.menu_rows.map(r => r.label).search(label).unwrap()
let m = comp.shell.menu_rect
click_at(comp, m.x + m.w / 2, m.y + 26 + 28 * i + 14, t)
}
///| Centres of the dock's titled task pills in panel order, from its rendered FillRect pills.
fn ext_pill_centers(comp : @host.ChandraCompositor, slot : String) -> Array[(Int, Int)] {
let r = comp.shell.slot_rect(slot)
let out : Array[(Int, Int)] = []
for op in comp.shell.slot_ops(slot) {
match op {
FillRect(f) if f.rect.y == 3 && f.rect.h.reinterpret_as_int() == r.h - 6 && f.rect.w >= 60U =>
out.push((r.x + f.rect.x + f.rect.w.reinterpret_as_int() / 2, r.y + r.h / 2))
_ => ()
}
}
out
}
///|
test "external X11 windows show in the dock and route clicks, shortcuts, and menu commands" {
let socket_path = "/tmp/wayland-moon-ext-" + @sys.getpid().to_string() + ".sock"
let comp = @host.ChandraCompositor::new(socket_path, @scene.ThemeTokens::moon_night(), 1280, 720).unwrap()
comp.shell.apps.clear()
comp.shell.exec.clear()
comp.shell.wm_classes.clear()
for a in [
("gamerig-astra", "Space Rage: Astra Incognita", "Game", "S", "gamerig-open astra", "astra"),
("com.mitchellh.ghostty", "Ghostty", "System", "G", "gamerig-open terminal", "com.mitchellh.ghostty"),
("steam", "Steam", "Game", "S", "gamerig-open steam", "steam"),
] {
comp.shell.apps.push({ id: a.0, name: a.1, comment: "", category: a.2, glyph: a.3 })
comp.shell.exec.set(a.0, a.4)
comp.shell.wm_classes.set(a.5, a.0)
}
comp.shell.apps_dirty = true
ignore(comp.compose_frame())
let slot = comp.shell.slot_of("dock")
assert_true(slot.length() > 0)
for s in comp.shell.slots() {
let m = comp.shell.slot_module(s)
if m == "inspector" || m == "layout" || m == "screenshot" {
ignore(comp.shell.unload_slot(s))
}
}
comp.shell.set_module_setting(slot, "pinned", "gamerig-astra;com.mitchellh.ghostty;steam")
ignore(comp.compose_frame())
let focuses : Array[Int] = []
let cmds : Array[(Int, @shell.WindowCommand)] = []
comp.set_external_window_handler({
focus: fn(xid) { focuses.push(xid) },
command: fn(xid, cmd) { cmds.push((xid, cmd)) },
})
let ghostty_xid = 0x0120_0007
let astra_xid = 0x0140_0003
let hades_xid = 0x0160_0011
let ext_wins : Array[@host.ExternalWindow] = [
{
host_id: ghostty_xid,
wm_class: "com.mitchellh.ghostty",
wm_instance: "ghostty",
title: "ubuntu@rig: ~",
focused: false,
minimized: false,
maximized: false,
},
{
host_id: astra_xid,
wm_class: "astra",
wm_instance: "astra",
title: "Space Rage: Astra Incognita",
focused: false,
minimized: false,
maximized: true,
},
{
host_id: hades_xid,
wm_class: "steam_app_1145360",
wm_instance: "steam_app_1145360",
title: "Hades",
focused: false,
minimized: false,
maximized: false,
},
]
comp.set_external_windows(ext_wins)
ignore(comp.compose_frame())
// Idle pinned icon (steam) comes first, then the three running task pills:
// gamerig-astra (merged with its pin via StartupWMClass "astra"), com.mitchellh.ghostty, steam_app_1145360.
assert_eq(comp.shell.dock_item_ids(), ["steam", "gamerig-astra", "com.mitchellh.ghostty", "steam_app_1145360"])
// Left-clicking Ghostty's pill routes its tagged XID cleanly through dock.wasm -> activate_task -> focus handler.
let pills = ext_pill_centers(comp, slot)
assert_eq(pills.length(), 3)
let (gx, gy) = pills[1]
click_at(comp, gx, gy, 10U)
assert_eq(focuses, [ghostty_xid])
// Super+2 targets the 2nd dock item (gamerig-astra) and routes to astra_xid.
comp.handle_input(@nested.InputEvent::Key(125U, true), 20U)
comp.handle_input(@nested.InputEvent::Key(3U, true), 21U)
comp.handle_input(@nested.InputEvent::Key(3U, false), 22U)
comp.handle_input(@nested.InputEvent::Key(125U, false), 23U)
ignore(comp.compose_frame())
assert_eq(focuses, [ghostty_xid, astra_xid])
// Right-clicking Ghostty's pill offers Minimize, Maximize, Quit and routes each command.
click_at(comp, gx, gy, 30U, btn=273U)
assert_true(comp.shell.menu_open)
assert_true(comp.shell.menu_rows.map(r => r.label).contains("Minimize"))
assert_true(comp.shell.menu_rows.map(r => r.label).contains("Maximize"))
assert_true(comp.shell.menu_rows.map(r => r.label).contains("Quit"))
ext_dock_pick(comp, "Minimize", 35U)
click_at(comp, gx, gy, 40U, btn=273U)
ext_dock_pick(comp, "Maximize", 45U)
click_at(comp, gx, gy, 50U, btn=273U)
ext_dock_pick(comp, "Quit", 55U)
assert_eq(cmds, [
(ghostty_xid, @shell.WindowCommand::Minimize),
(ghostty_xid, @shell.WindowCommand::ToggleMaximize),
(ghostty_xid, @shell.WindowCommand::Close),
])
// When Ghostty is minimized, its menu changes to Restore and picking it sends Restore.
comp.set_external_windows([
{ ..ext_wins[0], minimized: true },
ext_wins[1],
ext_wins[2],
])
ignore(comp.compose_frame())
click_at(comp, gx, gy, 60U, btn=273U)
assert_true(comp.shell.menu_rows.map(r => r.label).contains("Restore"))
ext_dock_pick(comp, "Restore", 65U)
assert_eq(cmds[cmds.length() - 1], (ghostty_xid, @shell.WindowCommand::Restore))
// External X11 windows are never persisted in Chandra's Wayland session snapshot.
assert_eq(comp.session_snapshot(0UL).length(), 0)
// Closing external windows removes the running pills and unpinned item from the dock.
comp.set_external_windows([])
ignore(comp.compose_frame())
assert_eq(comp.shell.dock_item_ids(), ["gamerig-astra", "com.mitchellh.ghostty", "steam"])
}
+45
View File
@@ -217,3 +217,48 @@ test "resolve_app_id finds the desktop file for a window's app id" {
assert_eq(resolve_app_id("unknown", exec, wm), None)
assert_eq(resolve_app_id("", exec, wm), None)
}
///| Canonical app id for an external X11 window: resolve WM_CLASS class then instance against
/// installed .desktop files (including StartupWMClass, e.g. `astra` -> `gamerig-astra`),
/// falling back to the raw class, instance, or title.
pub fn DesktopShell::resolve_external_app_id(
self : DesktopShell,
wm_class : String,
wm_instance : String,
title : String,
) -> String {
match resolve_app_id(wm_class, self.exec, self.wm_classes) {
Some(id) => return id
None => ()
}
match resolve_app_id(wm_instance, self.exec, self.wm_classes) {
Some(id) => return id
None => ()
}
if wm_class.length() > 0 {
wm_class
} else if wm_instance.length() > 0 {
wm_instance
} else {
title
}
}
///|
test "resolve_external_app_id resolves StartupWMClass and falls back cleanly" {
let sh = DesktopShell::new(":0")
sh.exec.clear()
sh.wm_classes.clear()
sh.exec.set("com.mitchellh.ghostty", "gamerig-open terminal")
sh.exec.set("steam", "gamerig-open steam")
sh.exec.set("gamerig-astra", "gamerig-open astra")
sh.wm_classes.set("com.mitchellh.ghostty", "com.mitchellh.ghostty")
sh.wm_classes.set("steam", "steam")
sh.wm_classes.set("astra", "gamerig-astra")
assert_eq(sh.resolve_external_app_id("com.mitchellh.ghostty", "ghostty", "Terminal"), "com.mitchellh.ghostty")
assert_eq(sh.resolve_external_app_id("steam", "steamwebhelper", "Steam"), "steam")
assert_eq(sh.resolve_external_app_id("astra", "astra", "Space Rage: Astra Incognita"), "gamerig-astra")
assert_eq(sh.resolve_external_app_id("steam_app_1145360", "steam_app_1145360", "Hades"), "steam_app_1145360")
assert_eq(sh.resolve_external_app_id("", "my-inst", "Fallback"), "my-inst")
assert_eq(sh.resolve_external_app_id("", "", "Window Title"), "Window Title")
}
+1 -4
View File
@@ -1090,13 +1090,10 @@ pub fn DesktopShell::render(
self.ensure_booted()
self.poll_picker()
self.publish_host_data()
// Machine state and the rich window list only matter to modules that import them.
// Machine state only matters to modules that import it.
if self.any_cap("system") {
self.sampler.refresh() // reads /proc once a second
}
if self.any_cap("system") || self.any_cap("windows") {
@wasm.set_windows(self.win_list)
}
self.settle_dock_pins()
if self.any_cap("icons") {
self.publish_icons()
+17 -9
View File
@@ -692,6 +692,22 @@ pub fn DesktopShell::slot_popup_texts(self : DesktopShell, slot : String) -> Arr
out
}
///| Publish the current window list (`Windows` table and `windows.all` blob) to modules.
pub fn DesktopShell::publish_windows(self : DesktopShell) -> Unit {
let wt = @wasm.Table::new()
for win in self.windows {
wt.int(win.id.to_int())
wt.str(win.title)
wt.int(if win.focused { 1 } else { 0 })
wt.int(if win.minimized { 1 } else { 0 })
wt.end_row()
}
@wasm.publish(Windows, wt)
if self.any_cap("system") || self.any_cap("windows") {
@wasm.set_windows(self.win_list)
}
}
///| Publish what modules can read through their capabilities (apps, windows, layout, loaded modules).
fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
if self.apps_dirty {
@@ -707,15 +723,7 @@ fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit {
}
@wasm.publish(Apps, t)
}
let wt = @wasm.Table::new()
for win in self.windows {
wt.int(win.id.to_int())
wt.str(win.title)
wt.int(if win.focused { 1 } else { 0 })
wt.int(if win.minimized { 1 } else { 0 })
wt.end_row()
}
@wasm.publish(Windows, wt)
self.publish_windows()
let lt = @wasm.Table::new()
for n in self.layout_names {
lt.str(n)
+1
View File
@@ -1,5 +1,6 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/encoding/utf8" @utf8,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/nested" @nested,
+418 -12
View File
@@ -17,6 +17,17 @@
/// 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
@@ -51,6 +62,25 @@ pub(all) struct X11Window {
// 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
@@ -175,6 +205,8 @@ fn X11Window::request(
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
}
@@ -323,15 +355,20 @@ fn X11Window::set_prop(
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]? {
///| 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)
match self.wait_reply(self.request(20, 0, b)) {
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)
@@ -349,6 +386,117 @@ fn X11Window::get_prop(self : X11Window, w : Int, prop : Int) -> Array[Byte]? {
}
}
///| 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
@@ -720,6 +868,24 @@ pub fn X11Window::open(
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,
@@ -741,12 +907,24 @@ pub fn X11Window::open(
}
self.a_wm_protocols = self.intern("WM_PROTOCOLS")
self.a_wm_delete = self.intern("WM_DELETE_WINDOW")
let a_net_wm_name = self.intern("_NET_WM_NAME")
self.a_net_wm_name = self.intern("_NET_WM_NAME")
let a_utf8 = self.intern("UTF8_STRING")
let a_state = self.intern("_NET_WM_STATE")
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).
@@ -816,8 +994,8 @@ pub fn X11Window::open(
// 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())
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))
@@ -846,18 +1024,25 @@ pub fn X11Window::open(
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 {
if fullscreen && !self.session && self.a_net_wm_state != 0 && a_fullscreen != 0 {
let p : Array[Byte] = []
put32(p, a_fullscreen)
self.set_prop(a_state, 4, 32, p)
self.set_prop(self.a_net_wm_state, 4, 32, p)
}
// Follow the screen size (xrandr) when the window is the screen.
// 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()
@@ -1035,8 +1220,9 @@ fn X11Window::dispatch(self : X11Window, off : Int) -> Int {
self.seg_attached = false
self.frame_pending = false
self.redraw = true
} else if self.errors_logged < 20 && !(major == 20 && err == 3) {
// (BadWindow from GetProperty is the window-manager check finding a stale window.)
} 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 " +
@@ -1176,6 +1362,28 @@ fn X11Window::dispatch(self : X11Window, off : Int) -> Int {
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 &&
@@ -1197,6 +1405,135 @@ fn X11Window::dispatch(self : X11Window, off : Int) -> Int {
// ---- 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 {
@@ -1209,9 +1546,78 @@ pub fn X11Window::poll(self : X11Window) -> Bool {
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 {
+93
View File
@@ -52,3 +52,96 @@ test "xauth_cookie: picks this host's entry for the display" {
let wild = Bytes::from_array(xauth_entry(0xFFFF, "", "0", [b'\x09']))
assert_eq(@x11.xauth_cookie(wild, 0, "rig").to_array(), [b'\x09'])
}
///|
fn utf8_bytes(s : String) -> Array[Byte] {
let out : Array[Byte] = []
for c in s {
out.push(c.to_int().to_byte())
}
out
}
///|
fn le32_bytes(vals : Array[Int]) -> Array[Byte] {
let out : Array[Byte] = []
for v in vals {
out.push((v & 0xFF).to_byte())
out.push(((v >> 8) & 0xFF).to_byte())
out.push(((v >> 16) & 0xFF).to_byte())
out.push(((v >> 24) & 0xFF).to_byte())
}
out
}
///|
fn rd32(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)
}
///|
test "parse_wm_class splits instance and class" {
assert_eq(@x11.parse_wm_class(utf8_bytes("ghostty\u0000com.mitchellh.ghostty\u0000")), ("ghostty", "com.mitchellh.ghostty"))
assert_eq(@x11.parse_wm_class(utf8_bytes("steamwebhelper\u0000steam\u0000")), ("steamwebhelper", "steam"))
assert_eq(@x11.parse_wm_class(utf8_bytes("astra\u0000astra\u0000")), ("astra", "astra"))
assert_eq(@x11.parse_wm_class(utf8_bytes("single")), ("single", ""))
assert_eq(@x11.parse_wm_class([]), ("", ""))
}
///|
test "parse_u32_list decodes little-endian 32-bit properties" {
assert_eq(@x11.parse_u32_list([]), [])
assert_eq(@x11.parse_u32_list(le32_bytes([0x01200007])), [0x01200007])
assert_eq(@x11.parse_u32_list(le32_bytes([0x00400001, 0x01200007, 0x01400003])), [0x00400001, 0x01200007, 0x01400003])
}
///|
test "is_taskbar_window filters self, skip-taskbar, non-task types, and child dialogs" {
let clients : Map[Int, Bool] = { 100: true, 200: true }
let skip = 10
let t_norm = 20
let t_dlg = 21
let t_dock = 22
let t_util = 23
// Chandra's own window and zero are skipped.
assert_false(@x11.is_taskbar_window(0, 50, [], skip, [t_norm], t_norm, t_dlg, 0, clients))
assert_false(@x11.is_taskbar_window(50, 50, [], skip, [t_norm], t_norm, t_dlg, 0, clients))
// _NET_WM_STATE_SKIP_TASKBAR is skipped.
assert_false(@x11.is_taskbar_window(100, 50, [skip], skip, [t_norm], t_norm, t_dlg, 0, clients))
// Dock/utility/unknown window types are skipped when window types are present.
assert_false(@x11.is_taskbar_window(100, 50, [], skip, [t_dock], t_norm, t_dlg, 0, clients))
assert_false(@x11.is_taskbar_window(100, 50, [], skip, [t_util], t_norm, t_dlg, 0, clients))
// Transient child dialog whose parent is in client_set is skipped.
assert_false(@x11.is_taskbar_window(200, 50, [], skip, [t_dlg], t_norm, t_dlg, 100, clients))
// Normal window, standalone dialog (or transient for root 1), and untyped ICCCM window appear.
assert_true(@x11.is_taskbar_window(100, 50, [], skip, [t_norm], t_norm, t_dlg, 0, clients))
assert_true(@x11.is_taskbar_window(200, 50, [], skip, [t_dlg], t_norm, t_dlg, 0, clients))
assert_true(@x11.is_taskbar_window(200, 50, [], skip, [t_dlg], t_norm, t_dlg, 1, clients))
assert_true(@x11.is_taskbar_window(100, 50, [], skip, [], t_norm, t_dlg, 0, clients))
}
///|
test "build_client_msg_body and build_raise_body encode exact X11 wire payloads" {
let msg = @x11.build_client_msg_body(0x200, 0x01200007, 300, 2, 11, 12, 2, 0)
assert_eq(msg.length(), 40)
assert_eq(rd32(msg, 0), 0x200) // root
assert_eq(rd32(msg, 4), 0x180000) // SubstructureRedirectMask | SubstructureNotifyMask
assert_eq(msg[8].to_int(), 33) // ClientMessage
assert_eq(msg[9].to_int(), 32) // format 32
assert_eq(rd32(msg, 12), 0x01200007) // target window
assert_eq(rd32(msg, 16), 300) // message type atom
assert_eq(rd32(msg, 20), 2)
assert_eq(rd32(msg, 24), 11)
assert_eq(rd32(msg, 28), 12)
assert_eq(rd32(msg, 32), 2)
assert_eq(rd32(msg, 36), 0)
let raise_body = @x11.build_raise_body(0x01200007)
assert_eq(raise_body.length(), 12)
assert_eq(rd32(raise_body, 0), 0x01200007)
assert_eq(raise_body[4].to_int() | (raise_body[5].to_int() << 8), 0x40) // CWStackMode
assert_eq(rd32(raise_body, 8), 0) // Above
}
+4 -3
View File
@@ -76,9 +76,10 @@ desktop through a display manager.
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.
speaks X11 (Steam, xterm) opens on Xorg directly: under an EWMH window manager it is a window
beside Chandra's, and Chandra tracks `_NET_CLIENT_LIST` / `_NET_ACTIVE_WINDOW` so the panel's
dock shows and switches to it; 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.