Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Xwayland on demand: own X window manager (X11 wire protocol in C), X socket per session, clipboard bridge, primary selection

Federico Pereirab6b516e74249
diff --git a/sdk/wayland.js b/sdk/wayland.js
index 3cece0f..c11a7bd 100644
--- a/sdk/wayland.js
+++ b/sdk/wayland.js
@@ -10,6 +10,7 @@ import { View, Text, Surface, addListener } from '@lordos/runtime';
import { windows, wm, registerBuiltinApp, windowChrome, pointerWorkArea, getApp } from './windows.js';
import { useAppWindow } from './components.jsx';
import { locale, appName } from './i18n.js';
+import { linuxAppFor } from './apps.js';
const idOf = (sid) => `linux#${sid}`;
export const surfaceOf = (wid) => (String(wid).startsWith('linux#') ? Number(String(wid).slice(6)) || 0 : 0);
@@ -52,6 +53,8 @@ globalThis.__lordWayland = (sid, type, d = {}) => {
const win = wm.get(id);
switch (type) {
case 'map': {
+ // X11 (Xwayland): the WM_CLASS class, or its instance when only that names a .desktop
+ if (d.x11 && d.appAlt && !linuxAppFor(d.appId) && linuxAppFor(d.appAlt)) d = { ...d, appId: d.appAlt };
const c = d.csd ? { w: 0, h: 0 } : windowChrome();
const area = pointerWorkArea(); // on the display under the pointer (docs/DISPLAYS.md)
const w = Math.min(area.w, d.width + c.w), hh = Math.min(area.h, d.height + c.h);
@@ -61,7 +64,7 @@ globalThis.__lordWayland = (sid, type, d = {}) => {
wm.open('linux', {
instance: String(sid),
frame: { w, h: hh, x: Math.max(area.x, Math.min(x, area.x + area.w - w)), y: Math.max(area.y, Math.min(y, area.y + area.h - hh)) },
- args: { surface: sid, csd: !!d.csd, appId: d.appId || '', pkg: !!(d.appId && (getApp(d.appId)?.package || getApp(d.appId)?.isolated)) },
+ args: { surface: sid, csd: !!d.csd, appId: d.appId || '', x11: !!d.x11, pkg: !!(d.appId && (getApp(d.appId)?.package || getApp(d.appId)?.isolated)) },
});
// app .lpk aislada: su nombre (del manifest) en vez del id
{ const pkg = d.appId ? getApp(d.appId) : null; wm.setTitle(id, pkg && (pkg.package || pkg.isolated) && (!d.title || d.title === d.appId) ? (pkg.isolated ? appName(pkg) : pkg.name) : (d.title || d.appId || null)); }
@@ -109,8 +112,8 @@ function sync() {
for (const w of list) {
const s = surfaceOf(w.id);
if (!s) continue;
- const st = w.maximized ? 1 : 0;
- if (lastState.get(s) !== st) { lastState.set(s, st); lord.wayland.state(s, !!w.maximized, false); }
+ const st = (w.maximized ? 1 : 0) | (w.minimized ? 2 : 0);
+ if (lastState.get(s) !== st) { lastState.set(s, st); lord.wayland.state(s, !!w.maximized, false, !!w.minimized); }
}
}
windows.subscribe(sync);
diff --git a/server/Makefile b/server/Makefile
index 17ea601..900ac30 100644
--- a/server/Makefile
+++ b/server/Makefile
@@ -28,7 +28,8 @@ WL_MORE := stable/linux-dmabuf/linux-dmabuf-v1 stable/presentation-time/presenta
unstable/relative-pointer/relative-pointer-unstable-v1 unstable/pointer-constraints/pointer-constraints-unstable-v1 \
unstable/pointer-gestures/pointer-gestures-unstable-v1 \
staging/cursor-shape/cursor-shape-v1 unstable/tablet/tablet-unstable-v2 \
- staging/fractional-scale/fractional-scale-v1 unstable/xdg-output/xdg-output-unstable-v1
+ staging/fractional-scale/fractional-scale-v1 unstable/xdg-output/xdg-output-unstable-v1 \
+ unstable/primary-selection/primary-selection-unstable-v1
WL_GEN += $(foreach p,$(WL_MORE),build/gen/$(notdir $(p))-protocol.h)
WL_OBJ += $(foreach p,$(WL_MORE),build/gen/$(notdir $(p))-protocol.o)
@@ -54,7 +55,7 @@ MEDIA_SRC := src/media/media.c src/media/hwdec.c src/media/mview.c src/media/cap
SEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/brokermail.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c src/sec/codesig.c
# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)
APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c src/ui/js_brokermail.c src/app/apphost_bc.c
-SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/remote/ssh_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/keylag.c src/ime.c src/wl/wl.c \
+SRC := src/main.c src/kms.c src/gpu/gpu.c src/input.c src/canvas.c src/admin.c src/install/install.c src/apps.c src/lpk.c src/fsops.c src/remote/mirror.c src/remote/remote_admin.c src/remote/ssh_admin.c src/users/users_admin.c src/users/homedirs.c src/keyboard.c src/keylag.c src/ime.c src/wl/wl.c src/wl/x11wire.c src/wl/xwm.c src/wl/xwayland.c \
src/ui/node.c src/ui/style.c src/ui/layout.c src/ui/transform.c src/ui/text.c src/ui/image.c \
src/ui/paint.c src/ui/js.c src/ui/js_sys.c src/ui/js_term.c src/ui/js_wasm.c src/wasm/wasm.c src/wasm/wasm_run.c src/ui/js_sound.c src/ui/js_net.c src/sound/snd.c src/sound/pulse.c src/ui/otf.c src/ui/fonts.c \
src/ui/unicode.c src/ui/bidi.c src/ui/shape.c src/ui/shape_indic.c src/ui/shape_syl.c src/ui/shape_khmer.c src/ui/shape_myanmar.c src/ui/shape_use.c src/ui/thbrk.c src/ui/textlayout.c \
diff --git a/server/src/apps.c b/server/src/apps.c
index a504b12..bbe7452 100644
--- a/server/src/apps.c
+++ b/server/src/apps.c
@@ -555,6 +555,17 @@ static int grant_ok(const char *path) {
return 1;
}
+/* The session's X socket, from DISPLAY=":<n>" (set by wl/xwayland.c): kept in a restricted app's
+ * private /tmp so an X11 app still opens there. NULL without one. */
+static const char *x11_socket(void) {
+ static char path[40];
+ const char *d = getenv("DISPLAY");
+ if (!d || d[0] != ':' || !d[1] || strlen(d) > 4) return NULL;
+ for (const char *q = d + 1; *q; q++) if (*q < '0' || *q > '9') return NULL;
+ snprintf(path, sizeof path, "/tmp/.X11-unix/X%s", d + 1);
+ return path;
+}
+
static int is_dir(const char *p) { struct stat st; return !lstat(p, &st) && S_ISDIR(st.st_mode); }
/* What a restricted app may touch (see sandbox.h). file: the realpath it was opened with, or NULL. */
@@ -582,6 +593,7 @@ static FilesPlan *files_plan(const DesktopApp *a, const char *file, const char *
p->cfg.sockets[ns++] = "pipewire-0";
p->cfg.sockets[ns++] = "pulse/native";
p->cfg.sockets[ns] = NULL;
+ p->cfg.x11_socket = x11_socket(); /* X11 apps (Xwayland) */
char path[PATH_MAX];
/* its own folders, named exactly after its canonical id, created if missing */
if (own_dir_ok(a->id)) {
@@ -657,6 +669,7 @@ static FilesPlan *view_plan(const char *cwd) {
p->cfg.sockets[ns++] = "pipewire-0"; /* playback; capture goes through the PipeWire guard */
p->cfg.sockets[ns++] = "pulse/native";
p->cfg.sockets[ns] = NULL;
+ p->cfg.x11_socket = x11_socket(); /* X11 apps (Xwayland) */
if (cwd && cwd[0] == '/') { snprintf(p->cwd, sizeof p->cwd, "%s", cwd); p->cfg.cwd = p->cwd; }
return p;
}
diff --git a/server/src/main.c b/server/src/main.c
index 5e9dc98..2a659f9 100644
--- a/server/src/main.c
+++ b/server/src/main.c
@@ -37,6 +37,7 @@
#include "tp/tp.h"
#include "tp/tp_route.h"
#include "wl/wl_input.h"
+#include "wl/xwayland.h"
#include "media/media.h"
#include "app/app.h"
#include "app/apphost_bc.h"
@@ -1628,6 +1629,8 @@ int main(int argc, char **argv) {
if (K0(&s)->fd >= 0 && fstat(K0(&s)->fd, &st) == 0) wl_set_drm_device(st.st_rdev);
}
if (ok && wl_start()) fprintf(stderr, "lord-server: no Wayland (Linux apps will not be able to open)\n");
+ /* X11 apps: an X socket now, Xwayland only when one connects (wl/xwayland.c); not on the login screen */
+ else if (ok && !s.greeter && session_user) xwl_init();
publish_displays(&s); /* one wl_output per display */
if (ok && net_open()) fprintf(stderr, "lord-server: no network notifications (rtnetlink)\n");
/* Backups: a thread running as the user, nice 19 and idle I/O (backup/backup.c) */
diff --git a/server/src/sec/sandbox.c b/server/src/sec/sandbox.c
index 3338d0a..676cf5f 100644
--- a/server/src/sec/sandbox.c
+++ b/server/src/sec/sandbox.c
@@ -388,6 +388,12 @@ int sandbox_files_isolate(const SandboxFilesCfg *cfg) {
keep[nk].fd = t; keep[nk].dir = 0; keep[nk].path = sockpath[nsock]; keep[nk].ro = 0; nk++;
nsock++;
}
+ /* X11 apps: the session's X socket (Xwayland), the only thing kept in the private /tmp */
+ if (cfg->x11_socket && !strncmp(cfg->x11_socket, "/tmp/.X11-unix/X", 16)) {
+ struct stat st;
+ int t = !lstat(cfg->x11_socket, &st) && S_ISSOCK(st.st_mode) ? (int)syscall(SYS_open_tree, AT_FDCWD, cfg->x11_socket, OPEN_TREE_CLONE | O_CLOEXEC) : -1;
+ if (t >= 0) { keep[nk].fd = t; keep[nk].dir = 0; keep[nk].path = cfg->x11_socket; keep[nk].ro = 0; nk++; }
+ }
int bad = 0;
const char *opts = "mode=0700,size=64m";
if (!cfg->keep_home) bad |= mount("tmpfs", cfg->home, "tmpfs", MS_NOSUID | MS_NODEV, opts);
diff --git a/server/src/sec/sandbox.h b/server/src/sec/sandbox.h
index d55aac6..4ece0be 100644
--- a/server/src/sec/sandbox.h
+++ b/server/src/sec/sandbox.h
@@ -89,6 +89,7 @@ typedef struct {
const char *rw[SANDBOX_FILES_MAX + 1]; /* NULL-terminated */
const char *ro[SANDBOX_FILES_MAX + 1];
const char *sockets[8]; /* names inside runtime_dir kept visible (wayland-0...), NULL-terminated */
+ const char *x11_socket; /* the session's X socket (/tmp/.X11-unix/X<n>), kept in the private /tmp; or NULL */
const char *cwd; /* the .desktop's Path= (or NULL: the home folder), entered inside the view */
/* the file or folder the app was opened with ("Open with"; also in rw[] or ro[]): opened
* again without following any symlink and only if it is still the same inode the launcher checked */
diff --git a/server/src/ui/js_sys.c b/server/src/ui/js_sys.c
index 9916fd3..5b7b24c 100644
--- a/server/src/ui/js_sys.c
+++ b/server/src/ui/js_sys.c
@@ -24,6 +24,7 @@
#include "../app/app.h"
#include "../ime.h"
#include "../wl/wl.h"
+#include "../wl/xwayland.h"
#include "../keyboard.h"
#include "../fsops.h"
#include "../remote/mirror.h"
@@ -1344,6 +1345,7 @@ static JSValue f_wl_state(JSContext *c, JSValueConst this_val, int argc, JSValue
int32_t id = 0;
JS_ToInt32(c, &id, argv[0]);
wl_set_state(id, argc > 1 && JS_ToBool(c, argv[1]), argc > 2 && JS_ToBool(c, argv[2]));
+ if (argc > 3) wl_set_minimized(id, JS_ToBool(c, argv[3]));
return JS_UNDEFINED;
}
@@ -1352,6 +1354,8 @@ static JSValue f_wl_info(JSContext *c, JSValueConst this_val, int argc, JSValueC
JSValue o = JS_NewObject(c);
JS_SetPropertyStr(c, o, "socket", JS_NewString(c, wl_socket()));
JS_SetPropertyStr(c, o, "windows", JS_NewInt32(c, wl_count()));
+ JS_SetPropertyStr(c, o, "x11Display", JS_NewString(c, xwl_display())); /* "" without Xwayland */
+ JS_SetPropertyStr(c, o, "x11Running", JS_NewBool(c, xwl_running()));
return o;
}
@@ -1370,7 +1374,7 @@ static const JSCFunctionListEntry wayland_funcs[] = {
JS_CFUNC_DEF("hasKeyboard", 0, f_wl_has_focus),
JS_CFUNC_DEF("focus", 1, f_wl_focus),
JS_CFUNC_DEF("close", 1, f_wl_close),
- JS_CFUNC_DEF("state", 3, f_wl_state),
+ JS_CFUNC_DEF("state", 4, f_wl_state),
JS_CFUNC_DEF("info", 0, f_wl_info),
};
diff --git a/server/src/wl/wl.c b/server/src/wl/wl.c
index d3d827e..dce827f 100644
--- a/server/src/wl/wl.c
+++ b/server/src/wl/wl.c
@@ -12,9 +12,9 @@
* own (GTK) go without a frame and the shadow is clipped with their window geometry. Popup
* menus (xdg_popup) are drawn on top of everything.
*
- * Not there yet: linux-dmabuf (GL apps use shared memory), drag and drop,
- * app cursors, text-input (LordOS input methods inside Wayland apps),
- * Xwayland. */
+ * X11 apps go through Xwayland (xwayland.c starts it on demand, xwm.c is the X window manager):
+ * its X windows are surfaces of one more client, with the toplevel or popup role given here
+ * (wlx_attach). Not there yet: drag and drop, text-input (LordOS input methods inside Wayland apps). */
#include "wl.h"
#include "../keylag.h"
@@ -44,6 +44,9 @@
#include "cursor-shape-v1-protocol.h"
#include "fractional-scale-v1-protocol.h"
#include "xdg-output-unstable-v1-protocol.h"
+#include "primary-selection-unstable-v1-protocol.h"
+#include "xwm.h"
+#include "xwayland.h"
#include "../outputs.h"
#include "../cursor.h"
#include "wl_input.h"
@@ -120,6 +123,10 @@ struct Surf {
unsigned outmask;
int pref_scale;
int logged_ratio; /* buffer px per logical px ×100, last logged (docs/DISPLAYS.md) */
+ /* an X11 window (Xwayland): its window manager record, and for a menu or tooltip its place */
+ XWin *xw;
+ int xpop, xx, xy, xmin;
+ char app_alt[128]; /* X11: the WM_CLASS instance (the class is app_id) */
};
/* Shape of a surface's hole in the UI: if it changes, the UI must be repainted. */
@@ -133,6 +140,7 @@ static Surf *surfs[MAX_SURF];
static int next_id = 1;
static struct wl_display *dpy;
+static struct wl_client *xwl_client; /* Xwayland (X11 apps), or NULL */
static struct wl_event_loop *loop;
static char socket_name[64];
@@ -258,6 +266,11 @@ static int origin(Surf *s, float *x, float *y) {
*y = n->ay - s->gy;
return 1;
}
+ if (s->role == R_POPUP && s->xpop) { /* an X11 menu or tooltip: where X put it */
+ *x = (float)s->xx;
+ *y = (float)s->xy;
+ return 1;
+ }
if (s->role == R_POPUP && s->parent) {
float px, py;
if (!origin(s->parent, &px, &py)) return 0;
@@ -287,7 +300,20 @@ static void popup_box_damage(Surf *s) {
/* ---- configure ---- */
+/* An X11 window: its size (and in fullscreen its place) is set through the window manager. */
+static void x_configure(Surf *s) {
+ if (s == fs_surf && s->fullscreen) {
+ float fx, fy, fw, fh;
+ fs_rect(&fx, &fy, &fw, &fh);
+ xwm_place(s->xw, (int)fx, (int)fy);
+ }
+ if (s->conf_w > 0 && s->conf_h > 0) xwm_resize(s->xw, s->conf_w, s->conf_h);
+ xwm_set_state(s->xw, s->maximized, s->fullscreen, s->xmin);
+ s->sent_configure = 1;
+}
+
static void send_toplevel_configure(Surf *s) {
+ if (s->xw) { x_configure(s); return; }
if (!s->top || !s->xdg) return;
struct wl_array states;
wl_array_init(&states);
@@ -565,6 +591,7 @@ static void unmap_popup(Surf *s) {
static void surface_gone(struct wl_resource *r) {
Surf *s = wl_resource_get_user_data(r);
+ if (s->xw) { xwm_surface_gone(s->xw); s->xw = NULL; }
if (pointer_focus == s) { pointer_focus = NULL; buttons_held = 0; }
if (key_focus == s) key_focus = NULL;
unmap_popup(s);
@@ -626,6 +653,7 @@ static void comp_create_surface(struct wl_client *c, struct wl_resource *r, uint
s->bscale = s->p_bscale = 1;
surfs[slot] = s;
wl_resource_set_implementation(res, &surface_impl, s, surface_gone);
+ if (c == xwl_client) xwm_surface_created(id); /* WL_SURFACE_ID may have come first */
}
static void comp_create_region(struct wl_client *c, struct wl_resource *r, uint32_t id) {
@@ -1113,7 +1141,8 @@ static void store_png(const unsigned char *png, size_t n) {
}
/* reading an app's selection into LordOS */
-typedef struct { int fd, image, sensitive; struct wl_event_source *ev; char *buf; size_t len, cap; char origin[128]; } Reader;
+typedef struct { int fd, image, sensitive, primary; struct wl_event_source *ev; char *buf; size_t len, cap; char origin[128]; } Reader;
+static void prim_store(const char *t, size_t n);
static int reader_ready(int fd, uint32_t mask, void *data) {
Reader *rd = data;
@@ -1132,7 +1161,9 @@ static int reader_ready(int fd, uint32_t mask, void *data) {
if (n < 0 && (errno == EAGAIN || errno == EINTR)) return 0;
break; /* end (or error): done */
}
- if (rd->len && rd->image) {
+ if (rd->primary) {
+ if (rd->len) prim_store(rd->buf, rd->len);
+ } else if (rd->len && rd->image) {
if (rd->len > 8 && !memcmp(rd->buf, "\x89PNG\r\n\x1a\n", 8)) {
store_png((unsigned char *)rd->buf, rd->len);
snprintf(clip_img_origin, sizeof clip_img_origin, "%s", rd->origin);
@@ -1344,6 +1375,118 @@ static void bind_ddm(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
wl_resource_set_implementation(r, &ddm_impl, NULL, NULL);
}
+/* ---- primary selection (zwp_primary_selection_v1: select to copy, middle click to paste) ----
+ * Like the clipboard, but text only and kept here: what the focused app selects is read once
+ * (text/plain) and offered to the app that gets the keyboard next, and to X11 apps through
+ * Xwayland's PRIMARY (xwm.c). Only the app with the keyboard may set it. */
+static struct wl_list prim_devices;
+typedef struct { struct wl_resource *res; char mime[64]; int rank; } PSource;
+static PSource *prim_src;
+static char *prim_text;
+static size_t prim_len;
+static unsigned prim_gen;
+
+static int prim_rank(const char *m) {
+ return !strcmp(m, "text/plain;charset=utf-8") ? 4 : !strcmp(m, "UTF8_STRING") ? 3 : !strcmp(m, "text/plain") ? 2 : text_mime(m) ? 1 : 0;
+}
+static void prim_offer_to(struct wl_resource *dev);
+static void prim_offer_focus(void) {
+ if (!key_focus) return;
+ struct wl_resource *d;
+ FOR_CLIENT(&prim_devices, key_focus->client, d) prim_offer_to(d);
+}
+static void prim_store(const char *t, size_t n) {
+ char *nb = malloc(n + 1);
+ if (!nb) return;
+ memcpy(nb, t, n);
+ nb[n] = 0;
+ if (prim_text) explicit_bzero(prim_text, prim_len);
+ free(prim_text);
+ prim_text = nb;
+ prim_len = strlen(nb);
+ prim_gen++;
+ prim_offer_focus();
+}
+
+static void psrc_offer(struct wl_client *c, struct wl_resource *r, const char *mime) {
+ (void)c;
+ PSource *s = wl_resource_get_user_data(r);
+ int rk = prim_rank(mime);
+ if (s && rk > s->rank) { s->rank = rk; snprintf(s->mime, sizeof s->mime, "%s", mime); }
+}
+static const struct zwp_primary_selection_source_v1_interface psrc_impl = { .offer = psrc_offer, .destroy = res_release };
+static void psrc_gone(struct wl_resource *r) {
+ PSource *s = wl_resource_get_user_data(r);
+ if (prim_src == s) prim_src = NULL; /* its text stays */
+ free(s);
+}
+
+static void poffer_receive(struct wl_client *c, struct wl_resource *r, const char *mime, int32_t fd) {
+ (void)c; (void)r;
+ if (prim_text && prim_rank(mime)) { send_bytes(fd, prim_text, prim_len); return; }
+ close(fd);
+}
+static const struct zwp_primary_selection_offer_v1_interface poffer_impl = { .receive = poffer_receive, .destroy = res_release };
+
+static void prim_offer_to(struct wl_resource *dev) {
+ struct wl_client *c = wl_resource_get_client(dev);
+ if (prim_src && wl_resource_get_client(prim_src->res) == c) return; /* its own */
+ if (!prim_text || !prim_len) { zwp_primary_selection_device_v1_send_selection(dev, NULL); return; }
+ struct wl_resource *o = wl_resource_create(c, &zwp_primary_selection_offer_v1_interface, wl_resource_get_version(dev), 0);
+ if (!o) return;
+ wl_resource_set_implementation(o, &poffer_impl, NULL, NULL);
+ zwp_primary_selection_device_v1_send_data_offer(dev, o);
+ zwp_primary_selection_offer_v1_send_offer(o, "text/plain;charset=utf-8");
+ zwp_primary_selection_offer_v1_send_offer(o, "text/plain");
+ zwp_primary_selection_offer_v1_send_offer(o, "UTF8_STRING");
+ zwp_primary_selection_device_v1_send_selection(dev, o);
+}
+
+static void pdev_set_selection(struct wl_client *c, struct wl_resource *r, struct wl_resource *src, uint32_t serial) {
+ (void)r; (void)serial;
+ if (!key_focus || key_focus->client != c) return; /* only the app with the keyboard */
+ PSource *s = src ? wl_resource_get_user_data(src) : NULL;
+ if (prim_src && prim_src != s) zwp_primary_selection_source_v1_send_cancelled(prim_src->res);
+ prim_src = s;
+ if (!s || !s->rank) return;
+ int p[2];
+ if (pipe2(p, O_CLOEXEC | O_NONBLOCK)) return;
+ zwp_primary_selection_source_v1_send_send(s->res, s->mime, p[1]);
+ close(p[1]);
+ Reader *rd = calloc(1, sizeof *rd);
+ if (!rd) { close(p[0]); return; }
+ rd->fd = p[0];
+ rd->primary = 1;
+ rd->ev = wl_event_loop_add_fd(loop, p[0], WL_EVENT_READABLE, reader_ready, rd);
+ if (!rd->ev) { close(p[0]); free(rd); }
+}
+static const struct zwp_primary_selection_device_v1_interface pdev_impl = { .set_selection = pdev_set_selection, .destroy = res_release };
+
+static void pdm_create_source(struct wl_client *c, struct wl_resource *r, uint32_t id) {
+ PSource *s = calloc(1, sizeof *s);
+ struct wl_resource *res = s ? wl_resource_create(c, &zwp_primary_selection_source_v1_interface, wl_resource_get_version(r), id) : NULL;
+ if (!res) { free(s); wl_client_post_no_memory(c); return; }
+ s->res = res;
+ wl_resource_set_implementation(res, &psrc_impl, s, psrc_gone);
+}
+static void pdm_get_device(struct wl_client *c, struct wl_resource *r, uint32_t id, struct wl_resource *seat) {
+ (void)seat;
+ struct wl_resource *d = wl_resource_create(c, &zwp_primary_selection_device_v1_interface, wl_resource_get_version(r), id);
+ if (!d) { wl_client_post_no_memory(c); return; }
+ wl_resource_set_implementation(d, &pdev_impl, NULL, link_gone);
+ wl_list_insert(&prim_devices, wl_resource_get_link(d));
+ if (key_focus && key_focus->client == c) prim_offer_to(d);
+}
+static const struct zwp_primary_selection_device_manager_v1_interface pdm_impl = {
+ .create_source = pdm_create_source, .get_device = pdm_get_device, .destroy = res_release,
+};
+static void bind_pdm(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
+ (void)data;
+ struct wl_resource *r = wl_resource_create(c, &zwp_primary_selection_device_manager_v1_interface, (int)ver, id);
+ if (!r) { wl_client_post_no_memory(c); return; }
+ wl_resource_set_implementation(r, &pdm_impl, NULL, NULL);
+}
+
/* ---- xdg_positioner ---- */
typedef struct {
@@ -1482,7 +1625,7 @@ static void top_unmaximize(struct wl_client *c, struct wl_resource *r) {
}
/* Fullscreen: presented by the compositor on top of everything (and straight to the card if possible). */
static void enter_fullscreen(Surf *s) {
- if (!s || !s->top || s == fs_surf) return;
+ if (!s || (!s->top && !s->xw) || s == fs_surf) return;
if (fs_surf) { fs_surf->fullscreen = 0; send_toplevel_configure(fs_surf); }
fs_surf = s;
s->fullscreen = 1;
@@ -1755,6 +1898,12 @@ static void surface_commit_role(Surf *s) {
char t[520], a[260];
json_str(t, sizeof t, s->title);
json_str(a, sizeof a, s->app_id);
+ if (s->xw) { /* X11: WM_CLASS class, and its instance for the .desktop match */
+ char alt[260];
+ json_str(alt, sizeof alt, s->app_alt);
+ emit(s, "map", "{\"title\":\"%s\",\"appId\":\"%s\",\"appAlt\":\"%s\",\"x11\":true,\"width\":%d,\"height\":%d,\"csd\":%s}",
+ t, a, alt, w, h, s->csd ? "true" : "false");
+ } else
emit(s, "map", "{\"title\":\"%s\",\"appId\":\"%s\",\"width\":%d,\"height\":%d,\"csd\":%s}", t, a, w, h, s->csd ? "true" : "false");
s->conf_w = w;
s->conf_h = h;
@@ -1901,6 +2050,7 @@ void wl_paint(Canvas *c, int id, int node, float x, float y, float w, float h, f
s->conf_h = ih;
send_toplevel_configure(s);
}
+ if (s->xw && s->mapped && s != fs_surf && !paint_capture_mode) xwm_place(s->xw, (int)lroundf(x), (int)lroundf(y)); /* X routes the pointer by it */
if (s == fs_surf) return; /* presented by the compositor, on top of everything */
Rect clip = rect_and(node_clip(node), (Rect){ (int)floorf(x), (int)floorf(y), (int)ceilf(x + w), (int)ceilf(y + h) });
Rect old = canvas_push_clip(c, PVX(x), PVY(y), w * paint_view.k, h * paint_view.k);
@@ -2795,25 +2945,36 @@ void wl_set_focus(int id) {
s->activated = 1;
send_toplevel_configure(s);
offer_to_focus();
+ prim_offer_focus();
clip_seen = term_clipboard_gen();
}
+ /* X11: the X focus follows (and with it whether X apps may read LordOS's clipboard) */
+ xwm_focus(s && s->xw ? s->xw : NULL);
wl_display_flush_clients(dpy);
}
void wl_close(int id) {
Surf *s = find(id);
if (s && s->top) xdg_toplevel_send_close(s->top);
+ else if (s && s->xw) xwm_close(s->xw);
if (dpy) wl_display_flush_clients(dpy);
}
void wl_set_state(int id, int maximized, int fullscreen) {
Surf *s = find(id);
(void)fullscreen; /* fullscreen is handled by the compositor */
- if (!s || !s->top || s->maximized == maximized) return;
+ if (!s || (!s->top && !s->xw) || s->maximized == maximized) return;
s->maximized = maximized;
send_toplevel_configure(s);
}
+/* Minimized by the theme: an X11 window goes to the bottom of X's stack (it never catches the
+ * pointer there) and is marked iconic. Wayland apps aren't told (xdg-shell has no such event). */
+void wl_set_minimized(int id, int minimized) {
+ Surf *s = find(id);
+ if (s && s->xw) { s->xmin = minimized; xwm_set_state(s->xw, s->maximized, s->fullscreen, minimized); }
+}
+
/* The screen changed size (headless session, docs/SESSIONS.md): new mode for the apps
* and the fullscreen one adapts. */
void wl_output_resized(void) {
@@ -2869,6 +3030,8 @@ int wl_start(void) {
wl_global_create(dpy, &wp_fractional_scale_manager_v1_interface, 1, NULL, bind_frac_mgr);
wl_global_create(dpy, &wl_seat_interface, 9, NULL, bind_seat); /* 8: axis_value120, 9: relative_direction */
wl_global_create(dpy, &wl_data_device_manager_interface, 3, NULL, bind_ddm);
+ wl_list_init(&prim_devices);
+ wl_global_create(dpy, &zwp_primary_selection_device_manager_v1_interface, 1, NULL, bind_pdm); /* middle-click paste */
wl_global_create(dpy, &xdg_wm_base_interface, 6, NULL, bind_wm_base);
wl_global_create(dpy, &zxdg_decoration_manager_v1_interface, 1, NULL, bind_decm);
wl_list_init(&rel_pointers);
@@ -2897,6 +3060,7 @@ int wl_start(void) {
void wl_stop(void) {
if (!dpy) return;
+ xwl_stop();
wl_display_destroy_clients(dpy);
wl_display_destroy(dpy);
dpy = NULL;
@@ -2917,6 +3081,7 @@ void wl_flush(void) {
if (selection) { wl_data_source_send_cancelled(selection->res); selection = NULL; }
offer_to_focus();
}
+ xwm_tick(); /* X11: clipboard changes, pending requests */
wl_display_flush_clients(dpy);
if (keylag_enabled) keylag_flushed();
}
@@ -2947,3 +3112,106 @@ struct wl_resource *wl__surface_at(float x, float y, float *lx, float *ly) {
}
return target ? target->res : NULL;
}
+
+/* ---- X11 windows (xwm.c): the role of Xwayland's surfaces ---- */
+
+struct wl_client *wlx_client(void) { return xwl_client; }
+void wlx_set_client(struct wl_client *c) { xwl_client = c; }
+
+int wlx_attach(uint32_t res_id, XWin *w, const XWinInfo *in) {
+ if (!dpy || !xwl_client) return 0;
+ struct wl_resource *r = wl_client_get_object(xwl_client, res_id);
+ if (!r || !wl_resource_instance_of(r, &wl_surface_interface, &surface_impl)) return 0;
+ Surf *s = wl_resource_get_user_data(r);
+ if (!s || s->role != R_NONE || s->xw) return 0;
+ s->xw = w;
+ s->sent_configure = 1; /* no xdg configure: X sizes it */
+ snprintf(s->title, sizeof s->title, "%s", in->title ? in->title : "");
+ snprintf(s->app_id, sizeof s->app_id, "%s", in->app_id ? in->app_id : "");
+ snprintf(s->app_alt, sizeof s->app_alt, "%s", in->app_alt ? in->app_alt : "");
+ s->csd = in->csd;
+ if (in->popup) { s->role = R_POPUP; s->xpop = 1; s->xx = in->x; s->xy = in->y; }
+ else s->role = R_TOPLEVEL;
+ if (s->content) surface_commit_role(s); /* it already had a buffer */
+ return s->id;
+}
+
+void wlx_detach(int sid) {
+ Surf *s = find(sid);
+ if (!s) return;
+ if (s->role == R_TOPLEVEL && s->mapped) emit(s, "unmap", "{}");
+ if (s->role == R_POPUP) unmap_popup(s);
+ if (key_focus == s) key_focus = NULL;
+ if (pointer_focus == s) { pointer_focus = NULL; buttons_held = 0; }
+ if (fs_surf == s) { fs_surf = NULL; damage_add((Box){ 0, 0, ui.width, ui.height }); }
+ if (s->node) damage_node(s);
+ ui.dirty = 1;
+ s->mapped = 0;
+ s->xw = NULL;
+ s->xpop = 0;
+ s->role = R_NONE;
+}
+
+void wlx_set_title(int sid, const char *t) {
+ Surf *s = find(sid);
+ if (!s) return;
+ snprintf(s->title, sizeof s->title, "%s", t);
+ if (s->mapped && s->role == R_TOPLEVEL) { char e[520]; json_str(e, sizeof e, s->title); emit(s, "title", "{\"title\":\"%s\"}", e); }
+}
+
+void wlx_popup_moved(int sid, int x, int y) {
+ Surf *s = find(sid);
+ if (!s || !s->xpop || (s->xx == x && s->xy == y)) return;
+ popup_box_damage(s);
+ s->xx = x;
+ s->xy = y;
+ popup_box_damage(s);
+}
+
+void wlx_request(int sid, int what, int arg) {
+ Surf *s = find(sid);
+ if (!s || s->role != R_TOPLEVEL) return;
+ switch (what) {
+ case XREQ_MOVE: if (s->mapped) { buttons_held = 0; emit(s, "move", "{\"x\":%.0f,\"y\":%.0f}", press_x, press_y); } break;
+ case XREQ_RESIZE: if (s->mapped) { buttons_held = 0; emit(s, "resize", "{\"edges\":%d,\"x\":%.0f,\"y\":%.0f}", arg, press_x, press_y); } break;
+ case XREQ_MAXIMIZE: if (s->mapped) emit(s, "maximize", "{}"); break;
+ case XREQ_UNMAXIMIZE: if (s->mapped) emit(s, "unmaximize", "{}"); break;
+ case XREQ_MINIMIZE: if (s->mapped) emit(s, "minimize", "{}"); break;
+ case XREQ_FULLSCREEN: enter_fullscreen(s); break;
+ case XREQ_UNFULLSCREEN: leave_fullscreen(s); break;
+ default: break;
+ }
+}
+
+void wlx_fullscreen_rect(int *x, int *y, int *w, int *h) {
+ float fx, fy, fw, fh;
+ fs_rect(&fx, &fy, &fw, &fh);
+ *x = (int)fx; *y = (int)fy; *w = (int)fw; *h = (int)fh;
+}
+
+/* What an X11 app copied: LordOS's clipboard (the next wl_flush offers it to the focused Wayland app
+ * and cancels a Wayland app's selection). */
+void wlx_clip_text(const char *t, size_t n, const char *origin) {
+ term_set_clipboard(t, n);
+ term_clipboard_mark(origin && origin[0] ? origin : "x11", 0);
+}
+
+void wlx_clip_png(const unsigned char *png, size_t n, const char *origin) {
+ if (n < 8 || memcmp(png, "\x89PNG\r\n\x1a\n", 8)) return;
+ if (selection) { wl_data_source_send_cancelled(selection->res); selection = NULL; }
+ store_png(png, n);
+ snprintf(clip_img_origin, sizeof clip_img_origin, "%s", origin && origin[0] ? origin : "x11");
+ clip_img_sensitive = 0;
+ offer_to_focus();
+}
+
+void wlx_primary_text(const char *t, size_t n) {
+ if (prim_src) { zwp_primary_selection_source_v1_send_cancelled(prim_src->res); prim_src = NULL; }
+ prim_store(t, n);
+}
+
+const char *wlx_primary(size_t *n, unsigned *gen) {
+ *n = prim_len;
+ *gen = prim_gen;
+ return prim_text ? prim_text : "";
+}
diff --git a/server/src/wl/wl.h b/server/src/wl/wl.h
index 1888655..b4b1015 100644
--- a/server/src/wl/wl.h
+++ b/server/src/wl/wl.h
@@ -37,6 +37,7 @@ int wl_has_key_focus(void); /* does a Linux app have the keyboard? *
void wl_set_focus(int id); /* 0: no Wayland app has the keyboard */
void wl_close(int id); /* asks the app to close the window */
void wl_set_state(int id, int maximized, int fullscreen);
+void wl_set_minimized(int id, int minimized); /* X11 windows: iconic and at the bottom of X's stack */
int wl_count(void);
void wl_output_resized(void); /* headless: one display of ui.width × ui.height */
/* The displays (docs/DISPLAYS.md): one wl_output (+ xdg-output) each. x, y, w, h: logical rect in the
diff --git a/server/src/wl/x11wire.c b/server/src/wl/x11wire.c
new file mode 100644
index 0000000..e0ae025
--- /dev/null
+++ b/server/src/wl/x11wire.c
@@ -0,0 +1,208 @@
+/* x11wire.c — X11 wire protocol helpers for the window manager (see x11wire.h). */
+#include "x11wire.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+/* ---- output buffer ---- */
+
+static int xo_room(XOut *o, size_t more) {
+ if (o->oom) return 0;
+ if (o->n + more <= o->cap) return 1;
+ size_t cap = o->cap ? o->cap : 4096;
+ while (cap < o->n + more) cap *= 2;
+ if (cap > (64u << 20)) { o->oom = 1; return 0; } /* a stuck peer: never grow without bound */
+ uint8_t *nb = realloc(o->b, cap);
+ if (!nb) { o->oom = 1; return 0; }
+ o->b = nb;
+ o->cap = cap;
+ return 1;
+}
+
+void xo_u8(XOut *o, uint8_t v) { if (xo_room(o, 1)) o->b[o->n++] = v; }
+void xo_u16(XOut *o, uint16_t v) { if (xo_room(o, 2)) { o->b[o->n++] = (uint8_t)v; o->b[o->n++] = (uint8_t)(v >> 8); } }
+void xo_u32(XOut *o, uint32_t v) {
+ if (!xo_room(o, 4)) return;
+ for (int i = 0; i < 4; i++) o->b[o->n++] = (uint8_t)(v >> (8 * i));
+}
+void xo_pad(XOut *o, size_t n) { if (xo_room(o, n)) { memset(o->b + o->n, 0, n); o->n += n; } }
+void xo_bytes(XOut *o, const void *p, size_t n) {
+ if (!xo_room(o, n + 3)) return;
+ if (n) memcpy(o->b + o->n, p, n);
+ o->n += n;
+ xo_pad(o, (4 - n % 4) % 4);
+}
+
+void xo_begin(XOut *o, uint8_t opcode, uint8_t data) {
+ o->start = o->n;
+ xo_u8(o, opcode);
+ xo_u8(o, data);
+ xo_u16(o, 0);
+}
+
+void xo_end(XOut *o) {
+ if (o->oom) return;
+ size_t len = (o->n - o->start + 3) / 4;
+ o->b[o->start + 2] = (uint8_t)len;
+ o->b[o->start + 3] = (uint8_t)(len >> 8);
+}
+
+void xo_drop(XOut *o, size_t n) {
+ if (n >= o->n) { o->n = 0; return; }
+ memmove(o->b, o->b + n, o->n - n);
+ o->n -= n;
+}
+
+void xo_free(XOut *o) { free(o->b); memset(o, 0, sizeof *o); }
+
+/* ---- connection setup ---- */
+
+void x11_setup_request(uint8_t out[12]) {
+ memset(out, 0, 12);
+ out[0] = 'l'; /* little endian */
+ out[2] = 11; /* protocol 11.0 */
+}
+
+int x11_parse_setup(const uint8_t *p, size_t n, XSetup *s, size_t *used) {
+ if (n < 8) return 0;
+ size_t total = 8 + 4 * (size_t)x11_get16(p + 6);
+ if (n < total) return 0;
+ *used = total;
+ if (p[0] != 1 || total < 40) return -1; /* 0 failed, 2 authenticate */
+ const uint8_t *d = p + 8;
+ memset(s, 0, sizeof *s);
+ s->id_base = x11_get32(d + 4);
+ s->id_mask = x11_get32(d + 8);
+ uint16_t vendor_len = x11_get16(d + 16);
+ s->max_req_bytes = (uint32_t)x11_get16(d + 18) * 4;
+ uint8_t nscreens = d[20], nformats = d[21];
+ s->min_keycode = d[26];
+ s->max_keycode = d[27];
+ size_t off = 32 + ((size_t)vendor_len + 3) / 4 * 4 + (size_t)nformats * 8;
+ if (!nscreens || off + 40 > total - 8 || !s->id_mask) return -1;
+ const uint8_t *scr = d + off;
+ s->root = x11_get32(scr);
+ s->width = x11_get16(scr + 20);
+ s->height = x11_get16(scr + 22);
+ s->root_visual = x11_get32(scr + 32);
+ s->root_depth = scr[38];
+ return s->root ? 1 : -1;
+}
+
+size_t x11_packet_len(const uint8_t *p, size_t n) {
+ if (n < 32) return 0;
+ size_t len = 32;
+ if (p[0] == X_Reply || (p[0] & 0x7f) == X_GenericEvent) len += 4 * (size_t)x11_get32(p + 4);
+ return n >= len ? len : 0;
+}
+
+uint32_t x11_seq_widen(uint32_t last_sent, uint16_t s16) {
+ uint32_t full = (last_sent & ~0xffffu) | s16;
+ if (full > last_sent) full -= 0x10000u; /* it can only be one already sent */
+ return full;
+}
+
+/* ---- properties ---- */
+
+static void ascii_copy(const uint8_t *v, size_t n, char *out, size_t size) {
+ size_t o = 0;
+ for (size_t i = 0; i < n && v[i] && o + 1 < size; i++)
+ if (v[i] >= 0x20 && v[i] < 0x7f) out[o++] = (char)v[i];
+ if (size) out[o] = 0;
+}
+
+void x11_wm_class(const uint8_t *v, size_t n, char *inst, size_t ni, char *cls, size_t nc) {
+ if (ni) inst[0] = 0;
+ if (nc) cls[0] = 0;
+ if (!v || !n) return;
+ size_t a = 0;
+ while (a < n && v[a]) a++;
+ ascii_copy(v, a, inst, ni);
+ if (a + 1 < n) {
+ size_t b = a + 1, e = b;
+ while (e < n && v[e]) e++;
+ ascii_copy(v + b, e - b, cls, nc);
+ }
+}
+
+/* Appends one code point as UTF-8 (control characters and surrogates are dropped). */
+static size_t put_utf8(char *out, size_t o, size_t size, uint32_t cp) {
+ if (cp < 0x20 || cp == 0x7f || (cp >= 0x80 && cp < 0xa0) || (cp >= 0xd800 && cp <= 0xdfff) || cp > 0x10ffff) return o;
+ uint8_t b[4];
+ size_t k;
+ if (cp < 0x80) { b[0] = (uint8_t)cp; k = 1; }
+ else if (cp < 0x800) { b[0] = (uint8_t)(0xc0 | cp >> 6); b[1] = (uint8_t)(0x80 | (cp & 0x3f)); k = 2; }
+ else if (cp < 0x10000) { b[0] = (uint8_t)(0xe0 | cp >> 12); b[1] = (uint8_t)(0x80 | ((cp >> 6) & 0x3f)); b[2] = (uint8_t)(0x80 | (cp & 0x3f)); k = 3; }
+ else { b[0] = (uint8_t)(0xf0 | cp >> 18); b[1] = (uint8_t)(0x80 | ((cp >> 12) & 0x3f)); b[2] = (uint8_t)(0x80 | ((cp >> 6) & 0x3f)); b[3] = (uint8_t)(0x80 | (cp & 0x3f)); k = 4; }
+ if (o + k + 1 > size) return o;
+ memcpy(out + o, b, k);
+ return o + k;
+}
+
+void x11_title(const uint8_t *v, size_t n, int latin1, char *out, size_t size) {
+ size_t o = 0;
+ if (!size) return;
+ for (size_t i = 0; v && i < n && o + 1 < size;) {
+ uint32_t cp = v[i];
+ if (!cp) break;
+ if (latin1 || cp < 0x80) { i++; o = put_utf8(out, o, size, cp); continue; }
+ int k = cp >= 0xf0 && cp < 0xf5 ? 4 : cp >= 0xe0 ? 3 : cp >= 0xc2 && cp < 0xe0 ? 2 : 0;
+ if (cp >= 0xf5) k = 0;
+ uint32_t c = k == 2 ? cp & 0x1f : k == 3 ? cp & 0x0f : cp & 0x07;
+ int ok = k > 0 && i + (size_t)k <= n;
+ for (int j = 1; ok && j < k; j++) {
+ if ((v[i + (size_t)j] & 0xc0) != 0x80) ok = 0;
+ else c = c << 6 | (v[i + (size_t)j] & 0x3f);
+ }
+ if (ok && ((k == 3 && c < 0x800) || (k == 4 && (c < 0x10000 || c > 0x10ffff)))) ok = 0; /* overlong */
+ if (!ok) { i++; o = put_utf8(out, o, size, 0xfffd); continue; }
+ i += (size_t)k;
+ o = put_utf8(out, o, size, c);
+ }
+ out[o] = 0;
+}
+
+int x11_motif_decorated(const uint32_t *v, size_t n) {
+ if (!v || n < 3 || !(v[0] & 2)) return -1; /* MWM_HINTS_DECORATIONS */
+ return v[2] != 0;
+}
+
+void x11_size_hints(const uint32_t *v, size_t n, XSizeHints *h) {
+ memset(h, 0, sizeof *h);
+ if (!v || n < 9) return;
+ if (v[0] & 16) { h->min_w = (int)v[5]; h->min_h = (int)v[6]; } /* PMinSize */
+ if (v[0] & 32) { h->max_w = (int)v[7]; h->max_h = (int)v[8]; } /* PMaxSize */
+ if (h->min_w < 0 || h->min_w > 16384) h->min_w = 0;
+ if (h->min_h < 0 || h->min_h > 16384) h->min_h = 0;
+ if (h->max_w < 0 || h->max_w > 32767) h->max_w = 0;
+ if (h->max_h < 0 || h->max_h > 32767) h->max_h = 0;
+}
+
+int x11_wm_hints_input(const uint32_t *v, size_t n) {
+ if (!v || n < 2 || !(v[0] & 1)) return 1; /* InputHint absent: it takes focus */
+ return v[1] != 0;
+}
+
+int x11_moveresize_edges(uint32_t d) {
+ static const int edges[8] = { 1 | 4, 1, 1 | 8, 8, 2 | 8, 2, 2 | 4, 4 };
+ if (d < 8) return edges[d];
+ if (d == 8) return -1; /* _NET_WM_MOVERESIZE_MOVE */
+ return 0; /* keyboard variants, cancel */
+}
+
+int x11_text_rank(const char *m) {
+ if (!m) return 0;
+ if (!strcmp(m, "UTF8_STRING")) return 5;
+ if (!strcmp(m, "text/plain;charset=utf-8")) return 4;
+ if (!strcmp(m, "text/plain")) return 2;
+ if (!strcmp(m, "STRING")) return 3;
+ if (!strcmp(m, "TEXT")) return 1;
+ return 0;
+}
+
+int x11_text_target(const char *m) { return x11_text_rank(m) > 0; }
+
+int x11_pick_display(int (*taken)(int n, void *ctx), void *ctx) {
+ for (int n = 0; n < 64; n++) if (!taken(n, ctx)) return n;
+ return -1;
+}
diff --git a/server/src/wl/x11wire.h b/server/src/wl/x11wire.h
new file mode 100644
index 0000000..36d5df9
--- /dev/null
+++ b/server/src/wl/x11wire.h
@@ -0,0 +1,120 @@
+/* x11wire.h — the small part of the X11 wire protocol that LordOS's X window manager (xwm.c)
+ * speaks with Xwayland. Our own code, no libxcb/libX11 (dependency policy, docs/ARCHITECTURE.md):
+ * request encoding, packet framing, the connection setup reply and the ICCCM/EWMH properties the
+ * window manager reads. Pure functions with no I/O, tested by tests/xwm_test.c. */
+#ifndef LORD_X11WIRE_H
+#define LORD_X11WIRE_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* ---- core request opcodes ---- */
+enum {
+ X_CreateWindow = 1, X_ChangeWindowAttributes = 2, X_GetWindowAttributes = 3, X_DestroyWindow = 4,
+ X_MapWindow = 8, X_UnmapWindow = 10, X_ConfigureWindow = 12, X_GetGeometry = 14, X_InternAtom = 16,
+ X_ChangeProperty = 18, X_DeleteProperty = 19, X_GetProperty = 20, X_SetSelectionOwner = 22,
+ X_ConvertSelection = 24, X_SendEvent = 25, X_SetInputFocus = 42, X_CreatePixmap = 53, X_FreePixmap = 54,
+ X_CreateGC = 55, X_FreeGC = 60, X_PutImage = 72, X_QueryExtension = 98, X_KillClient = 113,
+};
+
+/* ---- events ---- */
+enum {
+ X_Error = 0, X_Reply = 1, X_FocusIn = 9, X_FocusOut = 10, X_CreateNotify = 16, X_DestroyNotify = 17,
+ X_UnmapNotify = 18, X_MapNotify = 19, X_MapRequest = 20, X_ReparentNotify = 21, X_ConfigureNotify = 22,
+ X_ConfigureRequest = 23, X_PropertyNotify = 28, X_SelectionClear = 29, X_SelectionRequest = 30,
+ X_SelectionNotify = 31, X_ClientMessage = 33, X_GenericEvent = 35,
+};
+
+/* event masks and window attribute bits */
+#define XM_KeyPress 0x00000001u
+#define XM_PropertyChange 0x00400000u
+#define XM_StructureNotify 0x00020000u
+#define XM_SubstructureNotify 0x00080000u
+#define XM_SubstructureRedirect 0x00100000u
+#define XM_FocusChange 0x00200000u
+#define XCW_BackPixel 0x00000002u
+#define XCW_OverrideRedirect 0x00000200u
+#define XCW_EventMask 0x00000800u
+#define XCW_Cursor 0x00004000u
+/* ConfigureWindow value mask */
+#define XCF_X 0x01
+#define XCF_Y 0x02
+#define XCF_W 0x04
+#define XCF_H 0x08
+#define XCF_Border 0x10
+#define XCF_Sibling 0x20
+#define XCF_StackMode 0x40
+enum { X_Above = 0, X_Below = 1 };
+
+/* ---- output: requests are appended to one buffer ---- */
+typedef struct {
+ uint8_t *b;
+ size_t n, cap, start;
+ int oom; /* an allocation failed: the connection is dropped */
+} XOut;
+
+void xo_begin(XOut *o, uint8_t opcode, uint8_t data); /* opens a request (4-byte header) */
+void xo_u8(XOut *o, uint8_t v);
+void xo_u16(XOut *o, uint16_t v);
+void xo_u32(XOut *o, uint32_t v);
+void xo_bytes(XOut *o, const void *p, size_t n); /* padded to 4 */
+void xo_pad(XOut *o, size_t n);
+void xo_end(XOut *o); /* writes the length (in 4-byte units) */
+void xo_drop(XOut *o, size_t n); /* n bytes were written to the socket */
+void xo_free(XOut *o);
+
+/* The 12-byte connection setup request (little endian, X11.0, no authorization). */
+void x11_setup_request(uint8_t out[12]);
+
+typedef struct {
+ uint32_t id_base, id_mask, root, root_visual;
+ uint32_t max_req_bytes; /* maximum request length, in bytes */
+ uint16_t width, height;
+ uint8_t root_depth, min_keycode, max_keycode;
+} XSetup;
+/* Parses the setup reply (header included). 1 complete and accepted, 0 needs more bytes,
+ * -1 refused or malformed. */
+int x11_parse_setup(const uint8_t *p, size_t n, XSetup *s, size_t *used);
+
+/* Length of the next packet (event, error or reply) in p, or 0 if not complete yet. */
+size_t x11_packet_len(const uint8_t *p, size_t n);
+
+/* The full sequence number of a reply/event, from its 16 low bits and the last one sent. */
+uint32_t x11_seq_widen(uint32_t last_sent, uint16_t s16);
+
+static inline uint16_t x11_get16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); }
+static inline uint32_t x11_get32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; }
+
+/* ---- properties (ICCCM / EWMH / Motif) ---- */
+
+/* WM_CLASS: "instance\0class\0". Both are copied (empty if missing), printable ASCII only. */
+void x11_wm_class(const uint8_t *v, size_t n, char *inst, size_t ni, char *cls, size_t nc);
+
+/* A title from WM_NAME/_NET_WM_NAME: UTF-8 is copied (invalid bytes become U+FFFD), Latin-1
+ * (STRING) is converted; control characters are dropped. */
+void x11_title(const uint8_t *v, size_t n, int latin1, char *out, size_t size);
+
+/* _MOTIF_WM_HINTS: 1 the window wants a frame, 0 it draws its own (decorations off), -1 no opinion. */
+int x11_motif_decorated(const uint32_t *v, size_t n);
+
+typedef struct { int min_w, min_h, max_w, max_h; } XSizeHints;
+void x11_size_hints(const uint32_t *v, size_t n, XSizeHints *h); /* WM_NORMAL_HINTS (0 = none) */
+
+/* WM_HINTS: 1 if the window takes keyboard focus (input hint true or absent). */
+int x11_wm_hints_input(const uint32_t *v, size_t n);
+
+/* _NET_WM_MOVERESIZE direction → what the theme does: -1 move, 0 nothing (cancel, keyboard),
+ * otherwise the resize edges (1 top, 2 bottom, 4 left, 8 right, like xdg_toplevel.resize). */
+int x11_moveresize_edges(uint32_t direction);
+
+/* Clipboard targets: 1 a text target (UTF8_STRING, text/plain;charset=utf-8, STRING, TEXT,
+ * text/plain), 0 otherwise. */
+int x11_text_target(const char *name);
+/* Preference among the text targets an owner offers (higher is better, 0 = not text). */
+int x11_text_rank(const char *name);
+
+/* First free display number (0..63), given a test for whether :n is in use (a live lock file or
+ * a socket). -1 if they are all taken. */
+int x11_pick_display(int (*taken)(int n, void *ctx), void *ctx);
+
+#endif
diff --git a/server/src/wl/xwayland.c b/server/src/wl/xwayland.c
new file mode 100644
index 0000000..a835468
--- /dev/null
+++ b/server/src/wl/xwayland.c
@@ -0,0 +1,318 @@
+/* xwayland.c — Xwayland on demand: X11 apps start it by connecting (see xwayland.h).
+ *
+ * lord-server reserves an X display for the session (the lock file /tmp/.X<n>-lock and the socket
+ * /tmp/.X11-unix/X<n>, mode 0600: only this user's programs can connect; no abstract socket, no
+ * TCP) and sets DISPLAY=:<n>. Nothing runs until an X11 app connects. Then, and only then, it
+ * starts /usr/bin/Xwayland with a fixed argument list:
+ *
+ * Xwayland :<n> -rootless -listenfd 3 -wm 5 -nolisten tcp -extension XTEST
+ *
+ * fd 3 is the listening socket (Xwayland accepts that first connection and the next ones), fd 4 is
+ * its Wayland connection (WAYLAND_SOCKET, a socketpair: lord-server knows which client is Xwayland)
+ * and fd 5 is the window manager's connection (xwm.c). XTEST (synthetic input) is off: an X11 app
+ * can't type into another one. Xwayland runs in its own scope (lordos-xwayland.scope) and its own
+ * network namespace (no network at all), with no_new_privs, a minimal environment and its log in
+ * ~/.cache/lordos/xwayland.log. 10 s after the last X11 app closes, the window manager stops it
+ * (xwl_idle); the socket stays in lord-server, so the next X11 app starts it again. */
+#include "xwayland.h"
+#include "xwm.h"
+#include "x11wire.h"
+#include "wl.h"
+#include "../sec/cgroup.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <sys/un.h>
+#include <sys/wait.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-server-core.h>
+
+#define XWAYLAND_BIN "/usr/bin/Xwayland"
+
+struct wl_display *wl__display(void);
+
+static struct {
+ int disp, lfd;
+ char display[16], sock[64], lock[64];
+ struct wl_event_loop *loop;
+ struct wl_event_source *lev; /* the X socket, watched while Xwayland isn't running */
+ pid_t pid;
+ int pidfd;
+ struct wl_event_source *pev;
+ struct wl_client *client;
+ struct wl_listener gone;
+ time_t started, disabled_until;
+ int quick_fails;
+} XW = { .disp = -1, .lfd = -1, .pidfd = -1 };
+
+static int on_connect(int fd, uint32_t mask, void *data);
+
+/* Is display n in use? A lock file with a live process, or a socket nobody's lock explains. A
+ * stale lock and socket of ours (a previous session that crashed) are removed. */
+static int display_taken(int n, void *ctx) {
+ (void)ctx;
+ char lock[64], sock[64];
+ snprintf(lock, sizeof lock, "/tmp/.X%d-lock", n);
+ snprintf(sock, sizeof sock, "/tmp/.X11-unix/X%d", n);
+ struct stat st;
+ if (!lstat(lock, &st)) {
+ char buf[16] = "";
+ int fd = open(lock, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
+ if (fd >= 0) { if (read(fd, buf, sizeof buf - 1) < 0) buf[0] = 0; close(fd); }
+ long pid = strtol(buf, NULL, 10);
+ if (pid > 0 && (kill((pid_t)pid, 0) == 0 || errno == EPERM)) return 1;
+ if (st.st_uid != getuid() || !S_ISREG(st.st_mode)) return 1; /* someone else's: not ours to clean */
+ unlink(lock);
+ if (!lstat(sock, &st) && st.st_uid == getuid() && S_ISSOCK(st.st_mode)) unlink(sock);
+ }
+ return !lstat(sock, &st);
+}
+
+static void drain(int fd) {
+ for (int i = 0; i < 64; i++) {
+ int c = accept4(fd, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
+ if (c < 0) break;
+ close(c);
+ }
+}
+
+static void watch_socket(int on) {
+ if (on && !XW.lev && XW.lfd >= 0) XW.lev = wl_event_loop_add_fd(XW.loop, XW.lfd, WL_EVENT_READABLE, on_connect, NULL);
+ else if (!on && XW.lev) { wl_event_source_remove(XW.lev); XW.lev = NULL; }
+}
+
+int xwl_init(void) {
+ struct wl_display *dpy = wl__display();
+ if (!dpy || XW.lfd >= 0) return -1;
+ struct stat st;
+ if (stat(XWAYLAND_BIN, &st) || !S_ISREG(st.st_mode)) {
+ fprintf(stderr, "xwayland: not installed (the xwayland package): X11 apps can't open\n");
+ return -1;
+ }
+ XW.loop = wl_display_get_event_loop(dpy);
+ if (lstat("/tmp/.X11-unix", &st)) {
+ if (mkdir("/tmp/.X11-unix", 01777) == 0) chmod("/tmp/.X11-unix", 01777);
+ } else if (!S_ISDIR(st.st_mode) || (st.st_uid != 0 && st.st_uid != getuid())) {
+ fprintf(stderr, "xwayland: /tmp/.X11-unix isn't a directory of root's: no X11 apps\n");
+ return -1;
+ }
+ for (int tries = 0; tries < 8; tries++) {
+ int n = x11_pick_display(display_taken, NULL);
+ if (n < 0) break;
+ snprintf(XW.lock, sizeof XW.lock, "/tmp/.X%d-lock", n);
+ snprintf(XW.sock, sizeof XW.sock, "/tmp/.X11-unix/X%d", n);
+ int lf = open(XW.lock, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0444);
+ if (lf < 0) continue; /* someone took it meanwhile */
+ char pid[16];
+ int len = snprintf(pid, sizeof pid, "%10d\n", (int)getpid());
+ if (write(lf, pid, (size_t)len) != len) { close(lf); unlink(XW.lock); continue; }
+ close(lf);
+ int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
+ struct sockaddr_un a = { .sun_family = AF_UNIX };
+ snprintf(a.sun_path, sizeof a.sun_path, "%s", XW.sock);
+ mode_t old = umask(0177); /* 0600: only this user can connect */
+ int ok = fd >= 0 && !bind(fd, (struct sockaddr *)&a, sizeof a);
+ umask(old);
+ if (ok) ok = !chmod(XW.sock, 0600) && !listen(fd, 64);
+ if (!ok) { if (fd >= 0) close(fd); unlink(XW.lock); continue; }
+ XW.lfd = fd;
+ XW.disp = n;
+ snprintf(XW.display, sizeof XW.display, ":%d", n);
+ break;
+ }
+ if (XW.lfd < 0) { fprintf(stderr, "xwayland: no free X display\n"); return -1; }
+ setenv("DISPLAY", XW.display, 1); /* inherited by the apps LordOS starts */
+ watch_socket(1);
+ fprintf(stderr, "xwayland: DISPLAY=%s (%s), started on the first X11 connection\n", XW.display, XW.sock);
+ return 0;
+}
+
+static void child_exited(void) {
+ int st = 0;
+ if (XW.pid > 0 && waitpid(XW.pid, &st, WNOHANG) <= 0) return; /* not yet */
+ if (XW.pev) { wl_event_source_remove(XW.pev); XW.pev = NULL; }
+ if (XW.pidfd >= 0) { close(XW.pidfd); XW.pidfd = -1; }
+ int quick = time(NULL) - XW.started < 4 && !(WIFEXITED(st) && WEXITSTATUS(st) == 0);
+ fprintf(stderr, "xwayland: exited (%s %d)\n", WIFSIGNALED(st) ? "signal" : "status", WIFSIGNALED(st) ? WTERMSIG(st) : WEXITSTATUS(st));
+ XW.pid = 0;
+ xwm_stop();
+ if (XW.client) { struct wl_client *c = XW.client; XW.client = NULL; wlx_set_client(NULL); wl_list_remove(&XW.gone.link); wl_client_destroy(c); }
+ XW.quick_fails = quick ? XW.quick_fails + 1 : 0;
+ if (XW.quick_fails >= 3) {
+ XW.disabled_until = time(NULL) + 60;
+ XW.quick_fails = 0;
+ fprintf(stderr, "xwayland: it failed to start three times; X11 apps are refused for a minute\n");
+ }
+ watch_socket(1);
+}
+
+static int on_pidfd(int fd, uint32_t mask, void *data) {
+ (void)fd; (void)mask; (void)data;
+ child_exited();
+ return 0;
+}
+
+static void client_gone(struct wl_listener *l, void *data) {
+ (void)l; (void)data;
+ XW.client = NULL;
+ wlx_set_client(NULL);
+ wl_list_init(&XW.gone.link);
+ xwm_stop();
+ if (XW.pid > 0) kill(XW.pid, SIGTERM); /* its Wayland connection is gone: so is it */
+}
+
+void xwl_wm_lost(void) { if (XW.pid > 0) kill(XW.pid, SIGTERM); }
+
+void xwl_idle(void) {
+ if (XW.pid <= 0) return;
+ fprintf(stderr, "xwayland: no X11 app for 10 s: stopping it (the next one starts it again)\n");
+ XW.started = 0; /* a normal stop, not a failed start */
+ kill(XW.pid, SIGTERM);
+}
+
+/* The binary: a regular file owned by root and writable by nobody else. */
+static int binary_ok(void) {
+ struct stat st;
+ return !stat(XWAYLAND_BIN, &st) && S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) && (st.st_mode & 0111);
+}
+
+static int open_log(void) {
+ const char *home = getenv("HOME");
+ if (!home) return -1;
+ char p[512];
+ snprintf(p, sizeof p, "%s/.cache/lordos/xwayland.log", home);
+ struct stat st;
+ int trunc = !stat(p, &st) && st.st_size > (1 << 20);
+ return open(p, O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW | O_CLOEXEC | (trunc ? O_TRUNC : 0), 0600);
+}
+
+static void spawn(void) {
+ if (!binary_ok()) {
+ fprintf(stderr, "xwayland: %s is missing or not root's: not started\n", XWAYLAND_BIN);
+ XW.disabled_until = time(NULL) + 60;
+ drain(XW.lfd);
+ return;
+ }
+ int wlp[2] = { -1, -1 }, wmp[2] = { -1, -1 };
+ if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, wlp) || socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, wmp)) {
+ for (int i = 0; i < 2; i++) { if (wlp[i] >= 0) close(wlp[i]); if (wmp[i] >= 0) close(wmp[i]); }
+ drain(XW.lfd);
+ return;
+ }
+ int logfd = open_log();
+ char disp[16];
+ snprintf(disp, sizeof disp, ":%d", XW.disp);
+ /* everything the child needs, prepared before fork (it only calls async-signal-safe functions
+ * and the scope request) */
+ char env_home[600], env_rt[600];
+ snprintf(env_home, sizeof env_home, "HOME=%s", getenv("HOME") ? getenv("HOME") : "/");
+ snprintf(env_rt, sizeof env_rt, "XDG_RUNTIME_DIR=%s", getenv("XDG_RUNTIME_DIR") ? getenv("XDG_RUNTIME_DIR") : "/tmp");
+ char *envp[] = { env_home, env_rt, "PATH=/usr/bin:/bin", "WAYLAND_SOCKET=4", "LANG=C.UTF-8", NULL };
+ char *argv[] = { "Xwayland", disp, "-rootless", "-listenfd", "3", "-wm", "5",
+ "-nolisten", "tcp", "-extension", "XTEST", NULL };
+ int managed = getenv("LORDOS_SESSIOND") != NULL;
+ pid_t pid = fork();
+ if (pid == 0) {
+ setsid();
+ sigset_t none;
+ sigemptyset(&none);
+ sigprocmask(SIG_SETMASK, &none, NULL);
+ for (int s = 1; s < 32; s++) signal(s, SIG_DFL);
+ /* fds 3, 4, 5 (moved high first so none overwrites another) */
+ int a = fcntl(XW.lfd, F_DUPFD_CLOEXEC, 100), b = fcntl(wlp[1], F_DUPFD_CLOEXEC, 100), c = fcntl(wmp[1], F_DUPFD_CLOEXEC, 100);
+ int null = open("/dev/null", O_RDWR | O_CLOEXEC);
+ if (a < 0 || b < 0 || c < 0 || null < 0) _exit(126);
+ dup2(null, 0);
+ dup2(logfd >= 0 ? logfd : null, 1);
+ dup2(logfd >= 0 ? logfd : null, 2);
+ if (dup2(a, 3) != 3 || dup2(b, 4) != 4 || dup2(c, 5) != 5) _exit(126);
+ syscall(SYS_close_range, 6, ~0u, 0);
+ /* its own scope: never lord-server's (the firewall and the Monitor know it apart) */
+ CgroupLimits lim = { 0, 0, 0 };
+ if (cgroup_enter("lordos-xwayland.scope", &lim) && managed) {
+ static const char m[] = "xwayland: could not enter lordos-xwayland.scope: not started\n";
+ if (write(2, m, sizeof m - 1) < 0) {}
+ _exit(126);
+ }
+ /* no network at all: its own (empty) network namespace, inside a user namespace mapping
+ * only this user (Xwayland never needs root or the network) */
+ uid_t uid = getuid();
+ gid_t gid = getgid();
+ /* lord-server dropped root, so it isn't dumpable and /proc/self is root's: the maps below
+ * couldn't be written (Xwayland would run as the overflow uid and fail to start xkbcomp) */
+ prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
+ if (!unshare(CLONE_NEWUSER | CLONE_NEWNET)) {
+ char map[64];
+ int f = open("/proc/self/setgroups", O_WRONLY | O_CLOEXEC);
+ if (f >= 0) { if (write(f, "deny", 4) < 0) {} close(f); }
+ int len = snprintf(map, sizeof map, "%u %u 1", (unsigned)uid, (unsigned)uid);
+ f = open("/proc/self/uid_map", O_WRONLY | O_CLOEXEC);
+ if (f >= 0) { if (write(f, map, (size_t)len) < 0) {} close(f); }
+ len = snprintf(map, sizeof map, "%u %u 1", (unsigned)gid, (unsigned)gid);
+ f = open("/proc/self/gid_map", O_WRONLY | O_CLOEXEC);
+ if (f >= 0) { if (write(f, map, (size_t)len) < 0) {} close(f); }
+ }
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ execve(XWAYLAND_BIN, argv, envp);
+ _exit(127);
+ }
+ close(wlp[1]);
+ close(wmp[1]);
+ if (logfd >= 0) close(logfd);
+ if (pid < 0) { close(wlp[0]); close(wmp[0]); drain(XW.lfd); return; }
+ XW.pid = pid;
+ XW.started = time(NULL);
+ watch_socket(0); /* Xwayland accepts from now on */
+ XW.client = wl_client_create(wl__display(), wlp[0]);
+ if (!XW.client) { close(wlp[0]); close(wmp[0]); kill(pid, SIGTERM); }
+ else {
+ XW.gone.notify = client_gone;
+ wl_client_add_destroy_listener(XW.client, &XW.gone);
+ wlx_set_client(XW.client);
+ if (xwm_start(wmp[0], XW.loop)) kill(pid, SIGTERM);
+ }
+ XW.pidfd = (int)syscall(SYS_pidfd_open, pid, 0);
+ if (XW.pidfd >= 0) XW.pev = wl_event_loop_add_fd(XW.loop, XW.pidfd, WL_EVENT_READABLE, on_pidfd, NULL);
+ fprintf(stderr, "xwayland: started (pid %d) for an X11 app on %s\n", (int)pid, XW.display);
+}
+
+static int on_connect(int fd, uint32_t mask, void *data) {
+ (void)mask; (void)data;
+ if (XW.pid > 0) { watch_socket(0); return 0; }
+ if (time(NULL) < XW.disabled_until) { drain(fd); return 0; }
+ spawn();
+ return 0;
+}
+
+void xwl_stop(void) {
+ watch_socket(0);
+ if (XW.pid > 0) {
+ kill(XW.pid, SIGTERM);
+ for (int i = 0; i < 20 && waitpid(XW.pid, NULL, WNOHANG) == 0; i++) usleep(10000);
+ XW.pid = 0;
+ }
+ if (XW.pev) { wl_event_source_remove(XW.pev); XW.pev = NULL; }
+ if (XW.pidfd >= 0) { close(XW.pidfd); XW.pidfd = -1; }
+ xwm_stop();
+ if (XW.lfd >= 0) {
+ close(XW.lfd);
+ XW.lfd = -1;
+ unlink(XW.sock);
+ unlink(XW.lock);
+ }
+ XW.display[0] = 0;
+}
+
+const char *xwl_display(void) { return XW.display; }
+const char *xwl_socket_path(void) { return XW.lfd >= 0 ? XW.sock : ""; }
+int xwl_running(void) { return XW.pid > 0; }
diff --git a/server/src/wl/xwayland.h b/server/src/wl/xwayland.h
new file mode 100644
index 0000000..387025f
--- /dev/null
+++ b/server/src/wl/xwayland.h
@@ -0,0 +1,19 @@
+/* xwayland.h — X11 apps through Xwayland, started only when one connects (xwayland.c).
+ *
+ * The fourth exception to "lord-server doesn't run programs" (AGENTS.md): it only ever starts
+ * /usr/bin/Xwayland (root-owned, not writable by others), with an argument list fixed in C, when
+ * the first X11 client connects to this session's X socket; never from JS and with no argument
+ * from anyone. See docs/WAYLAND.md, "X11 apps (Xwayland)". */
+#ifndef LORD_XWAYLAND_H
+#define LORD_XWAYLAND_H
+
+/* After wl_start(), in a user session (not the login screen, not app mode): if Xwayland is
+ * installed, reserves a display (/tmp/.X11-unix/X<n>, 0600, and its lock file), sets DISPLAY for
+ * the apps LordOS starts, and waits for a connection. 0 if there is an X socket. */
+int xwl_init(void);
+void xwl_stop(void); /* stops Xwayland and removes the socket and the lock */
+const char *xwl_display(void); /* ":1", or "" */
+const char *xwl_socket_path(void); /* "/tmp/.X11-unix/X1", or "" (apps.c: restricted apps' view) */
+int xwl_running(void); /* is Xwayland running now? */
+
+#endif
diff --git a/server/src/wl/xwm.c b/server/src/wl/xwm.c
new file mode 100644
index 0000000..2a5bf5e
--- /dev/null
+++ b/server/src/wl/xwm.c
@@ -0,0 +1,1176 @@
+/* xwm.c — LordOS's X window manager for Xwayland (see xwm.h).
+ *
+ * It speaks the X11 protocol itself (x11wire.c), on the connection Xwayland opened for it with
+ * `-wm`, fully asynchronously: it never waits for a reply, so lord-server can't stall on
+ * Xwayland while Xwayland waits on the compositor. Replies are matched by sequence number to a
+ * FIFO of callbacks.
+ *
+ * What it does:
+ * - takes SubstructureRedirect on the root and maps the windows that ask (MapRequest); reads their
+ * title, class (WM_CLASS → the app's .desktop), protocols, hints, Motif decorations, window type
+ * and transient parent; WL_SURFACE_ID tells which wl_surface shows each one;
+ * - keeps every X window where LordOS shows it (the X position is the content's position on
+ * screen, so Xwayland routes the pointer right), and stacks the focused one on top;
+ * - focus (SetInputFocus / WM_TAKE_FOCUS), close (WM_DELETE_WINDOW or KillClient), fullscreen,
+ * maximize and minimize requests (_NET_WM_STATE, WM_CHANGE_STATE), moves and resizes asked by
+ * apps that draw their own frame (_NET_WM_MOVERESIZE);
+ * - an X app may not move the keyboard focus to another X app's window (FocusIn from another
+ * client is reverted);
+ * - the clipboard: CLIPBOARD and PRIMARY both ways (XFixes tells when an X app copies; the copy is
+ * read once and becomes LordOS's; LordOS's is offered to X only while an X window has the
+ * keyboard, so a background X app can't read what was copied elsewhere);
+ * - the root window's cursor is LordOS's arrow (Render cursor).
+ * See docs/WAYLAND.md, "X11 apps (Xwayland)". */
+#include "xwm.h"
+#include "x11wire.h"
+#include "wl.h"
+#include "../cursor.h"
+#include "../term/term.h"
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+#include <wayland-server-core.h>
+
+void xwl_wm_lost(void); /* xwayland.c: the window manager connection is gone */
+void xwl_idle(void); /* xwayland.c: no X11 app left: Xwayland may stop */
+#define IDLE_MS 10000 /* grace period after the last X11 app closes */
+
+/* predefined atoms */
+enum { XA_PRIMARY = 1, XA_ATOM = 4, XA_CARDINAL = 6, XA_STRING = 31, XA_WINDOW = 33, XA_WM_HINTS = 35, XA_WM_NAME = 39,
+ XA_WM_NORMAL_HINTS = 40, XA_WM_CLASS = 67, XA_WM_TRANSIENT_FOR = 68 };
+
+#define ATOM_LIST(X) \
+ X(WM_PROTOCOLS, "WM_PROTOCOLS") X(WM_DELETE_WINDOW, "WM_DELETE_WINDOW") X(WM_TAKE_FOCUS, "WM_TAKE_FOCUS") \
+ X(WM_STATE, "WM_STATE") X(WM_CHANGE_STATE, "WM_CHANGE_STATE") X(WM_S0, "WM_S0") X(UTF8_STRING, "UTF8_STRING") \
+ X(NET_WM_NAME, "_NET_WM_NAME") X(NET_SUPPORTED, "_NET_SUPPORTED") X(NET_SUPPORTING_WM_CHECK, "_NET_SUPPORTING_WM_CHECK") \
+ X(NET_ACTIVE_WINDOW, "_NET_ACTIVE_WINDOW") X(NET_WM_STATE, "_NET_WM_STATE") \
+ X(NET_WM_STATE_FULLSCREEN, "_NET_WM_STATE_FULLSCREEN") X(NET_WM_STATE_MAXIMIZED_VERT, "_NET_WM_STATE_MAXIMIZED_VERT") \
+ X(NET_WM_STATE_MAXIMIZED_HORZ, "_NET_WM_STATE_MAXIMIZED_HORZ") X(NET_WM_STATE_HIDDEN, "_NET_WM_STATE_HIDDEN") \
+ X(NET_WM_STATE_FOCUSED, "_NET_WM_STATE_FOCUSED") X(NET_WM_WINDOW_TYPE, "_NET_WM_WINDOW_TYPE") \
+ X(NET_WM_WINDOW_TYPE_NORMAL, "_NET_WM_WINDOW_TYPE_NORMAL") X(NET_WM_WINDOW_TYPE_DIALOG, "_NET_WM_WINDOW_TYPE_DIALOG") \
+ X(NET_WM_WINDOW_TYPE_SPLASH, "_NET_WM_WINDOW_TYPE_SPLASH") X(NET_WM_WINDOW_TYPE_MENU, "_NET_WM_WINDOW_TYPE_MENU") \
+ X(NET_WM_WINDOW_TYPE_DROPDOWN_MENU, "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU") \
+ X(NET_WM_WINDOW_TYPE_POPUP_MENU, "_NET_WM_WINDOW_TYPE_POPUP_MENU") X(NET_WM_WINDOW_TYPE_TOOLTIP, "_NET_WM_WINDOW_TYPE_TOOLTIP") \
+ X(NET_WM_WINDOW_TYPE_NOTIFICATION, "_NET_WM_WINDOW_TYPE_NOTIFICATION") X(NET_WM_WINDOW_TYPE_COMBO, "_NET_WM_WINDOW_TYPE_COMBO") \
+ X(NET_WM_WINDOW_TYPE_DND, "_NET_WM_WINDOW_TYPE_DND") X(NET_WM_MOVERESIZE, "_NET_WM_MOVERESIZE") X(NET_WM_PID, "_NET_WM_PID") \
+ X(NET_CLIENT_LIST, "_NET_CLIENT_LIST") X(NET_FRAME_EXTENTS, "_NET_FRAME_EXTENTS") X(MOTIF_WM_HINTS, "_MOTIF_WM_HINTS") \
+ X(WL_SURFACE_ID, "WL_SURFACE_ID") X(CLIPBOARD, "CLIPBOARD") X(TARGETS, "TARGETS") X(TIMESTAMP, "TIMESTAMP") X(INCR, "INCR") \
+ X(TEXT, "TEXT") X(MIME_UTF8, "text/plain;charset=utf-8") X(MIME_TEXT, "text/plain") X(MIME_PNG, "image/png") \
+ X(PW_HINT, "x-kde-passwordManagerHint") X(LORD_SEL_CLIPBOARD, "_LORD_SEL_CLIPBOARD") X(LORD_SEL_PRIMARY, "_LORD_SEL_PRIMARY")
+
+#define AE(id, name) A_##id,
+enum { ATOM_LIST(AE) A_COUNT };
+#define AN(id, name) name,
+static const char *const atom_names[A_COUNT] = { ATOM_LIST(AN) };
+static uint32_t atom[A_COUNT];
+#define AT(id) atom[A_##id]
+
+struct XWin {
+ uint32_t id;
+ XWin *next;
+ int x, y, w, h; /* X geometry (root coordinates) */
+ int override, managed, viewable;
+ uint32_t surface_res; /* WL_SURFACE_ID */
+ int sid; /* wl.c surface (0: not attached) */
+ char title[256], cls[128], inst[128];
+ int net_name; /* _NET_WM_NAME seen: WM_NAME no longer counts */
+ int decorated, input, take_focus, del_window;
+ uint32_t transient, wtype;
+ XSizeHints hints;
+ int want_fs; /* asked for fullscreen before it had a surface */
+ int fullscreen, maximized, minimized, focused;
+ int px, py, pw, ph, placed; /* last position/size we configured */
+ unsigned state_sig;
+};
+
+typedef void (*ReplyFn)(const uint8_t *r, size_t n, uint32_t a, uint32_t b);
+typedef struct { uint32_t seq; ReplyFn fn; uint32_t a, b; } Pend;
+#define NPEND 4096
+
+/* a selection being sent to an X app in chunks (INCR) */
+typedef struct Xfer {
+ uint32_t win, prop, type;
+ uint8_t *buf;
+ size_t len, off;
+ time_t t0;
+ struct Xfer *next;
+} Xfer;
+
+enum { SEL_CLIP, SEL_PRIM, NSEL };
+typedef struct {
+ int owned; /* the window manager owns it in X (LordOS's selection) */
+ unsigned owned_gen;
+ unsigned x_gen; /* LordOS generation that belongs to an X app's copy */
+ int stage; /* import: 0 idle, 1 TARGETS, 2 data, 3 INCR chunks */
+ uint32_t owner, target;
+ int image, latin1;
+ uint8_t *buf;
+ size_t len, cap;
+} Sel;
+
+static struct {
+ int fd;
+ struct wl_event_loop *loop;
+ struct wl_event_source *ev;
+ XOut out;
+ uint8_t *in;
+ size_t in_n, in_cap;
+ int setup_done, init_left, ready, debug;
+ XSetup su;
+ uint32_t seq, id_next, wmwin, cursor;
+ uint8_t xfixes_op, xfixes_ev, render_op, composite_op, xres_op;
+ struct wl_event_source *idle; /* fires IDLE_MS after the last X window is gone */
+ Pend pend[NPEND];
+ unsigned ph, pn;
+ XWin *wins;
+ XWin *focus;
+ Sel sel[NSEL];
+ Xfer *xfers;
+} X = { .fd = -1 };
+
+#define CLIP_MAX (16u << 20)
+
+static void lost(const char *why);
+static void idle_arm(void);
+
+/* ---- requests ---- */
+
+static void req(uint8_t op, uint8_t data) { X.seq++; xo_begin(&X.out, op, data); }
+static void expect(ReplyFn fn, uint32_t a, uint32_t b) {
+ if (X.pn == NPEND) { X.out.oom = 1; return; }
+ X.pend[(X.ph + X.pn) % NPEND] = (Pend){ X.seq, fn, a, b };
+ X.pn++;
+}
+static uint32_t new_id(void) {
+ uint32_t inc = X.su.id_mask & (~X.su.id_mask + 1);
+ X.id_next += inc;
+ return X.su.id_base | (X.id_next & X.su.id_mask);
+}
+
+static void change_attrs(uint32_t win, uint32_t mask, uint32_t value) {
+ req(X_ChangeWindowAttributes, 0);
+ xo_u32(&X.out, win); xo_u32(&X.out, mask); xo_u32(&X.out, value);
+ xo_end(&X.out);
+}
+
+static void change_prop(uint32_t win, uint32_t prop, uint32_t type, int format, const void *data, uint32_t units) {
+ req(X_ChangeProperty, 0); /* Replace */
+ xo_u32(&X.out, win); xo_u32(&X.out, prop); xo_u32(&X.out, type);
+ xo_u8(&X.out, (uint8_t)format); xo_pad(&X.out, 3);
+ xo_u32(&X.out, units);
+ xo_bytes(&X.out, data, (size_t)units * (size_t)(format / 8));
+ xo_end(&X.out);
+}
+
+static void get_prop(uint32_t win, uint32_t prop, int del, uint32_t longs, ReplyFn fn, uint32_t a, uint32_t b) {
+ req(X_GetProperty, (uint8_t)del);
+ xo_u32(&X.out, win); xo_u32(&X.out, prop); xo_u32(&X.out, 0); xo_u32(&X.out, 0); xo_u32(&X.out, longs);
+ xo_end(&X.out);
+ expect(fn, a, b);
+}
+
+static void configure(uint32_t win, uint16_t mask, const int32_t *vals, int nvals) {
+ req(X_ConfigureWindow, 0);
+ xo_u32(&X.out, win); xo_u16(&X.out, mask); xo_u16(&X.out, 0);
+ for (int i = 0; i < nvals; i++) xo_u32(&X.out, (uint32_t)vals[i]);
+ xo_end(&X.out);
+}
+
+static void set_focus(uint32_t win) {
+ req(X_SetInputFocus, win ? 1 : 0); /* revert to PointerRoot / None */
+ xo_u32(&X.out, win); xo_u32(&X.out, 0);
+ xo_end(&X.out);
+}
+
+static void set_owner(uint32_t owner, uint32_t selection) {
+ req(X_SetSelectionOwner, 0);
+ xo_u32(&X.out, owner); xo_u32(&X.out, selection); xo_u32(&X.out, 0);
+ xo_end(&X.out);
+}
+
+static void convert(uint32_t selection, uint32_t target, uint32_t prop, uint32_t time) {
+ req(X_ConvertSelection, 0);
+ xo_u32(&X.out, X.wmwin); xo_u32(&X.out, selection); xo_u32(&X.out, target); xo_u32(&X.out, prop); xo_u32(&X.out, time);
+ xo_end(&X.out);
+}
+
+/* SendEvent with a 32-byte event to the window's owner (no propagation, empty mask). */
+static void send_event(uint32_t dest, const uint8_t ev[32]) {
+ req(X_SendEvent, 0);
+ xo_u32(&X.out, dest); xo_u32(&X.out, 0);
+ xo_bytes(&X.out, ev, 32);
+ xo_end(&X.out);
+}
+
+static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
+
+static void client_message(uint32_t win, uint32_t type, const uint32_t d[5]) {
+ uint8_t ev[32] = { X_ClientMessage, 32 };
+ put32(ev + 4, win);
+ put32(ev + 8, type);
+ for (int i = 0; i < 5; i++) put32(ev + 12 + 4 * i, d[i]);
+ send_event(win, ev);
+}
+
+static void flush(void) {
+ if (X.fd < 0) return;
+ if (X.out.oom) { lost("out of memory"); return; }
+ while (X.out.n) {
+ ssize_t w = send(X.fd, X.out.b, X.out.n, MSG_NOSIGNAL | MSG_DONTWAIT);
+ if (w > 0) { xo_drop(&X.out, (size_t)w); continue; }
+ if (w < 0 && errno == EINTR) continue;
+ if (w < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) break;
+ lost("write failed");
+ return;
+ }
+ wl_event_source_fd_update(X.ev, WL_EVENT_READABLE | (X.out.n ? WL_EVENT_WRITABLE : 0));
+}
+
+/* ---- windows ---- */
+
+static XWin *find(uint32_t id) {
+ for (XWin *w = X.wins; w; w = w->next) if (w->id == id) return w;
+ return NULL;
+}
+
+static XWin *add_win(uint32_t id) {
+ XWin *w = find(id);
+ if (w) return w;
+ w = calloc(1, sizeof *w);
+ if (!w) return NULL;
+ w->id = id;
+ w->decorated = -1;
+ w->input = 1;
+ w->next = X.wins;
+ X.wins = w;
+ return w;
+}
+
+static int same_client(uint32_t a, uint32_t b) { return (a & ~X.su.id_mask) == (b & ~X.su.id_mask); }
+
+static int is_popup_type(uint32_t t) {
+ return t && (t == AT(NET_WM_WINDOW_TYPE_MENU) || t == AT(NET_WM_WINDOW_TYPE_DROPDOWN_MENU) ||
+ t == AT(NET_WM_WINDOW_TYPE_POPUP_MENU) || t == AT(NET_WM_WINDOW_TYPE_TOOLTIP) ||
+ t == AT(NET_WM_WINDOW_TYPE_NOTIFICATION) || t == AT(NET_WM_WINDOW_TYPE_COMBO) ||
+ t == AT(NET_WM_WINDOW_TYPE_DND));
+}
+
+static void update_client_list(void) {
+ uint32_t ids[256];
+ uint32_t n = 0;
+ for (XWin *w = X.wins; w && n < 256; w = w->next) if (w->managed) ids[n++] = w->id;
+ change_prop(X.su.root, AT(NET_CLIENT_LIST), XA_WINDOW, 32, ids, n);
+}
+
+static void set_wm_state(XWin *w, uint32_t state) {
+ uint32_t v[2] = { state, 0 };
+ change_prop(w->id, AT(WM_STATE), AT(WM_STATE), 32, v, 2);
+}
+
+static void write_net_state(XWin *w) {
+ uint32_t v[6];
+ uint32_t n = 0;
+ if (w->fullscreen) v[n++] = AT(NET_WM_STATE_FULLSCREEN);
+ if (w->maximized) { v[n++] = AT(NET_WM_STATE_MAXIMIZED_VERT); v[n++] = AT(NET_WM_STATE_MAXIMIZED_HORZ); }
+ if (w->minimized) v[n++] = AT(NET_WM_STATE_HIDDEN);
+ if (w->focused) v[n++] = AT(NET_WM_STATE_FOCUSED);
+ unsigned sig = (unsigned)(w->fullscreen | w->maximized << 1 | w->minimized << 2 | w->focused << 3) + 1;
+ if (sig == w->state_sig) return;
+ w->state_sig = sig;
+ change_prop(w->id, AT(NET_WM_STATE), XA_ATOM, 32, v, n);
+}
+
+/* Origin for the clipboard history: the class of the X app that copied. */
+static const char *origin_of(uint32_t owner) {
+ XWin *w = find(owner);
+ if (!w || !w->cls[0])
+ for (XWin *o = X.wins; o; o = o->next) if (o->managed && o->cls[0] && same_client(o->id, owner)) { w = o; break; }
+ return w && w->cls[0] ? w->cls : "x11";
+}
+
+static void try_attach(XWin *w) {
+ if (!w->surface_res || w->sid) return;
+ XWinInfo info = {
+ .title = w->title, .app_id = w->cls, .app_alt = w->inst,
+ .csd = w->decorated == 0 || w->wtype == AT(NET_WM_WINDOW_TYPE_SPLASH),
+ .popup = w->override || is_popup_type(w->wtype),
+ .x = w->x, .y = w->y, .width = w->w, .height = w->h,
+ };
+ int sid = wlx_attach(w->surface_res, w, &info);
+ if (!sid) return;
+ w->sid = sid;
+ if (X.debug) fprintf(stderr, "xwm: 0x%x is surface %d (%s, class %s, %dx%d%s)\n", w->id, sid,
+ info.popup ? "popup" : "window", w->cls, w->w, w->h, info.csd ? ", own frame" : "");
+ if (w->want_fs && !info.popup) { w->want_fs = 0; wlx_request(sid, XREQ_FULLSCREEN, 0); }
+}
+
+static void detach(XWin *w) {
+ if (w->sid) { int sid = w->sid; w->sid = 0; wlx_detach(sid); }
+ w->surface_res = 0;
+}
+
+static void free_win(XWin *w) {
+ detach(w);
+ if (X.focus == w) X.focus = NULL;
+ for (XWin **p = &X.wins; *p; p = &(*p)->next) if (*p == w) { *p = w->next; break; }
+ free(w);
+}
+
+/* ---- properties ---- */
+
+static void prop_reply(const uint8_t *r, size_t n, uint32_t id, uint32_t prop) {
+ XWin *w = find(id);
+ if (!w || !r || n < 32) return;
+ int format = r[1];
+ uint32_t type = x11_get32(r + 8), units = x11_get32(r + 16);
+ size_t bytes = (size_t)units * (size_t)(format / 8);
+ if (bytes > n - 32) bytes = n - 32;
+ const uint8_t *v = r + 32;
+ uint32_t longs[64];
+ size_t nl = format == 32 ? bytes / 4 : 0;
+ if (nl > 64) nl = 64;
+ for (size_t i = 0; i < nl; i++) longs[i] = x11_get32(v + 4 * i);
+ if (prop == XA_WM_CLASS) {
+ x11_wm_class(v, bytes, w->inst, sizeof w->inst, w->cls, sizeof w->cls);
+ } else if (prop == XA_WM_NAME || prop == AT(NET_WM_NAME)) {
+ if (prop == XA_WM_NAME && w->net_name) return;
+ if (prop == AT(NET_WM_NAME)) w->net_name = type != 0;
+ if (!type && prop == AT(NET_WM_NAME)) return;
+ x11_title(v, bytes, type == XA_STRING, w->title, sizeof w->title);
+ if (w->sid) wlx_set_title(w->sid, w->title);
+ } else if (prop == AT(WM_PROTOCOLS)) {
+ w->take_focus = w->del_window = 0;
+ for (size_t i = 0; i < nl; i++) {
+ if (longs[i] == AT(WM_TAKE_FOCUS)) w->take_focus = 1;
+ if (longs[i] == AT(WM_DELETE_WINDOW)) w->del_window = 1;
+ }
+ } else if (prop == XA_WM_HINTS) {
+ w->input = x11_wm_hints_input(nl ? longs : NULL, nl);
+ } else if (prop == XA_WM_NORMAL_HINTS) {
+ x11_size_hints(nl ? longs : NULL, nl, &w->hints);
+ } else if (prop == AT(NET_WM_WINDOW_TYPE)) {
+ w->wtype = nl ? longs[0] : 0;
+ } else if (prop == XA_WM_TRANSIENT_FOR) {
+ w->transient = nl ? longs[0] : 0;
+ } else if (prop == AT(MOTIF_WM_HINTS)) {
+ w->decorated = x11_motif_decorated(nl ? longs : NULL, nl);
+ } else if (prop == AT(NET_WM_STATE)) {
+ for (size_t i = 0; i < nl; i++) if (longs[i] == AT(NET_WM_STATE_FULLSCREEN) && !w->sid) w->want_fs = 1;
+ }
+}
+
+static const int watched[] = { XA_WM_CLASS, XA_WM_NAME, -1 /* _NET_WM_NAME */, -2 /* WM_PROTOCOLS */, XA_WM_HINTS,
+ XA_WM_NORMAL_HINTS, -3 /* window type */, XA_WM_TRANSIENT_FOR, -4 /* Motif */, -5 /* state */ };
+static uint32_t watched_atom(int i) {
+ switch (watched[i]) {
+ case -1: return AT(NET_WM_NAME);
+ case -2: return AT(WM_PROTOCOLS);
+ case -3: return AT(NET_WM_WINDOW_TYPE);
+ case -4: return AT(MOTIF_WM_HINTS);
+ case -5: return AT(NET_WM_STATE);
+ default: return (uint32_t)watched[i];
+ }
+}
+#define NWATCHED (int)(sizeof watched / sizeof watched[0])
+
+static void read_props(XWin *w) {
+ for (int i = 0; i < NWATCHED; i++) get_prop(w->id, watched_atom(i), 0, 1024, prop_reply, w->id, watched_atom(i));
+}
+
+/* ---- the clipboard bridge ---- */
+
+static uint32_t sel_atom(int k) { return k == SEL_CLIP ? AT(CLIPBOARD) : XA_PRIMARY; }
+static uint32_t sel_prop(int k) { return k == SEL_CLIP ? AT(LORD_SEL_CLIPBOARD) : AT(LORD_SEL_PRIMARY); }
+static int sel_index(uint32_t a) { return a == AT(CLIPBOARD) ? SEL_CLIP : a == XA_PRIMARY ? SEL_PRIM : -1; }
+
+/* LordOS's current selection, as a generation (any change → another value). */
+static unsigned lord_gen(int k) {
+ if (k == SEL_PRIM) { size_t n; unsigned g; wlx_primary(&n, &g); return g; }
+ return term_clipboard_gen() * 2654435761u + wl_clip_image_gen() * 40503u + 1;
+}
+static int lord_has(int k) {
+ if (k == SEL_PRIM) { size_t n; unsigned g; return wlx_primary(&n, &g) && n > 0; }
+ return wl_clip_is_image() || term_clipboard()[0];
+}
+
+/* LordOS's selection is offered to X only while an X window has the keyboard, and only if it is
+ * newer than what an X app copied. */
+static void clip_sync(void) {
+ for (int k = 0; k < NSEL; k++) {
+ Sel *s = &X.sel[k];
+ unsigned g = lord_gen(k);
+ if (X.focus && lord_has(k) && g != s->x_gen) {
+ if (!s->owned || s->owned_gen != g) {
+ set_owner(X.wmwin, sel_atom(k));
+ s->owned = 1;
+ s->owned_gen = g;
+ }
+ } else if (!X.focus && s->owned) {
+ set_owner(0, sel_atom(k));
+ s->owned = 0;
+ }
+ }
+}
+
+static void sel_reset(Sel *s) { free(s->buf); s->buf = NULL; s->len = s->cap = 0; s->stage = 0; }
+
+static int sel_append(Sel *s, const uint8_t *p, size_t n) {
+ if (s->len + n > CLIP_MAX) return -1;
+ if (s->len + n + 1 > s->cap) {
+ size_t cap = s->cap ? s->cap : 4096;
+ while (cap < s->len + n + 1) cap *= 2;
+ uint8_t *nb = realloc(s->buf, cap);
+ if (!nb) return -1;
+ s->buf = nb;
+ s->cap = cap;
+ }
+ memcpy(s->buf + s->len, p, n);
+ s->len += n;
+ return 0;
+}
+
+static void sel_finish(int k) {
+ Sel *s = &X.sel[k];
+ if (s->len) {
+ const char *origin = origin_of(s->owner);
+ if (s->latin1) { /* STRING is Latin-1 */
+ uint8_t *u = malloc(s->len * 2 + 1);
+ size_t o = 0;
+ for (size_t i = 0; u && i < s->len; i++) {
+ if (s->buf[i] < 0x80) u[o++] = s->buf[i];
+ else { u[o++] = (uint8_t)(0xc0 | s->buf[i] >> 6); u[o++] = (uint8_t)(0x80 | (s->buf[i] & 0x3f)); }
+ }
+ if (u) { free(s->buf); s->buf = u; s->len = o; s->cap = s->len * 2 + 1; }
+ }
+ if (k == SEL_PRIM) wlx_primary_text((const char *)s->buf, s->len);
+ else if (s->image) wlx_clip_png(s->buf, s->len, origin);
+ else wlx_clip_text((const char *)s->buf, s->len, origin);
+ s->x_gen = lord_gen(k); /* this one is the X app's: not offered back */
+ if (X.debug) fprintf(stderr, "xwm: %s copied %zu bytes (%s) from %s\n", k ? "PRIMARY" : "CLIPBOARD", s->len,
+ s->image ? "image/png" : "text", origin);
+ }
+ sel_reset(s);
+}
+
+static void sel_reply(const uint8_t *r, size_t n, uint32_t k, uint32_t stage) {
+ Sel *s = &X.sel[k];
+ if (s->stage != (int)stage) return; /* a newer copy replaced it */
+ if (!r || n < 32) { sel_reset(s); return; }
+ int format = r[1];
+ uint32_t type = x11_get32(r + 8);
+ size_t bytes = (size_t)x11_get32(r + 16) * (size_t)(format / 8);
+ if (bytes > n - 32) bytes = n - 32;
+ const uint8_t *v = r + 32;
+ if (stage == 1) { /* TARGETS: the best text, or a PNG */
+ uint32_t best = 0;
+ int rank = 0, png = 0;
+ for (size_t i = 0; format == 32 && i + 4 <= bytes; i += 4) {
+ uint32_t a = x11_get32(v + i);
+ int rk = a == AT(UTF8_STRING) ? 5 : a == AT(MIME_UTF8) ? 4 : a == XA_STRING ? 3 : a == AT(MIME_TEXT) ? 2 : a == AT(TEXT) ? 1 : 0;
+ if (rk > rank) { rank = rk; best = a; }
+ if (a == AT(MIME_PNG)) png = 1;
+ }
+ if (!best && png && k == SEL_CLIP) { best = AT(MIME_PNG); s->image = 1; }
+ if (!best) { sel_reset(s); return; }
+ s->target = best;
+ s->latin1 = best == XA_STRING;
+ s->stage = 2;
+ convert(sel_atom((int)k), best, sel_prop((int)k), 0);
+ return;
+ }
+ if (stage == 2 && type == AT(INCR)) { s->stage = 3; return; } /* chunks follow (PropertyNotify) */
+ if (bytes && sel_append(s, v, bytes)) { sel_reset(s); return; }
+ if (stage == 2 || !bytes) sel_finish((int)k);
+}
+
+static void sel_start(int k, uint32_t owner) {
+ Sel *s = &X.sel[k];
+ sel_reset(s);
+ s->owner = owner;
+ s->image = s->latin1 = 0;
+ s->stage = 1;
+ convert(sel_atom(k), AT(TARGETS), sel_prop(k), 0);
+}
+
+static void sel_owner_changed(const uint8_t *p) {
+ uint32_t owner = x11_get32(p + 8), selection = x11_get32(p + 12);
+ int k = sel_index(selection);
+ if (k < 0 || owner == X.wmwin) return;
+ Sel *s = &X.sel[k];
+ s->owned = 0;
+ if (!owner) { s->x_gen = 0; return; } /* the X app that had it is gone */
+ s->x_gen = lord_gen(k);
+ sel_start(k, owner);
+}
+
+static void sel_notify_event(const uint8_t *p) {
+ uint32_t requestor = x11_get32(p + 8), selection = x11_get32(p + 12), target = x11_get32(p + 16), prop = x11_get32(p + 20);
+ int k = sel_index(selection);
+ if (k < 0 || requestor != X.wmwin) return;
+ Sel *s = &X.sel[k];
+ if (!s->stage) return;
+ if (!prop) { /* refused */
+ if (s->stage == 1) { s->stage = 2; s->target = AT(UTF8_STRING); convert(selection, AT(UTF8_STRING), sel_prop(k), 0); }
+ else sel_reset(s);
+ return;
+ }
+ (void)target;
+ get_prop(X.wmwin, sel_prop(k), 1, CLIP_MAX / 4, sel_reply, (uint32_t)k, (uint32_t)s->stage);
+}
+
+static void notify_requestor(uint32_t time, uint32_t requestor, uint32_t selection, uint32_t target, uint32_t prop) {
+ uint8_t ev[32] = { X_SelectionNotify };
+ put32(ev + 4, time);
+ put32(ev + 8, requestor);
+ put32(ev + 12, selection);
+ put32(ev + 16, target);
+ put32(ev + 20, prop);
+ send_event(requestor, ev);
+}
+
+static void write_data(uint32_t win, uint32_t prop, uint32_t type, const uint8_t *data, size_t len) {
+ if (len + 64 <= X.su.max_req_bytes) { change_prop(win, prop, type, 8, data, (uint32_t)len); return; }
+ Xfer *t = calloc(1, sizeof *t);
+ if (!t || !(t->buf = malloc(len))) { free(t); return; }
+ memcpy(t->buf, data, len);
+ t->len = len;
+ t->win = win;
+ t->prop = prop;
+ t->type = type;
+ t->t0 = time(NULL);
+ t->next = X.xfers;
+ X.xfers = t;
+ XWin *known = find(win);
+ change_attrs(win, XCW_EventMask, XM_PropertyChange | (known ? XM_FocusChange : 0));
+ uint32_t total = (uint32_t)len;
+ change_prop(win, prop, AT(INCR), 32, &total, 1);
+}
+
+static void xfer_free(Xfer *t) {
+ for (Xfer **p = &X.xfers; *p; p = &(*p)->next) if (*p == t) { *p = t->next; break; }
+ explicit_bzero(t->buf, t->len); /* may be a password copied in Passwords */
+ free(t->buf);
+ free(t);
+}
+
+static int xfer_step(uint32_t win, uint32_t prop) {
+ for (Xfer *t = X.xfers; t; t = t->next) {
+ if (t->win != win || t->prop != prop) continue;
+ size_t chunk = X.su.max_req_bytes > 1024 ? X.su.max_req_bytes - 64 : 960;
+ if (chunk > 65536) chunk = 65536;
+ size_t n = t->len - t->off < chunk ? t->len - t->off : chunk;
+ change_prop(win, prop, t->type, 8, t->buf + t->off, (uint32_t)n);
+ t->off += n;
+ if (!n) xfer_free(t); /* the empty chunk ends it */
+ return 1;
+ }
+ return 0;
+}
+
+static void sel_request(const uint8_t *p) {
+ uint32_t time_ = x11_get32(p + 4), owner = x11_get32(p + 8), requestor = x11_get32(p + 12), selection = x11_get32(p + 16),
+ target = x11_get32(p + 20), prop = x11_get32(p + 24);
+ int k = sel_index(selection);
+ if (!prop) prop = target; /* obsolete clients */
+ if (k < 0 || owner != X.wmwin || !X.sel[k].owned || !X.focus) { notify_requestor(time_, requestor, selection, target, 0); return; }
+ int image = k == SEL_CLIP && wl_clip_is_image();
+ const char *text = "";
+ size_t tlen = 0;
+ unsigned g;
+ if (k == SEL_PRIM) text = wlx_primary(&tlen, &g);
+ else if (!image) { text = term_clipboard(); tlen = strlen(text); }
+ int sensitive = k == SEL_CLIP && !image && term_clipboard_sensitive();
+ if (target == AT(TARGETS)) {
+ uint32_t list[10];
+ uint32_t nl = 0;
+ list[nl++] = AT(TARGETS);
+ list[nl++] = AT(TIMESTAMP);
+ if (image) list[nl++] = AT(MIME_PNG);
+ else { list[nl++] = AT(UTF8_STRING); list[nl++] = AT(MIME_UTF8); list[nl++] = AT(MIME_TEXT); list[nl++] = XA_STRING; list[nl++] = AT(TEXT); }
+ if (sensitive) list[nl++] = AT(PW_HINT);
+ change_prop(requestor, prop, XA_ATOM, 32, list, nl);
+ } else if (target == AT(TIMESTAMP)) {
+ uint32_t t = 0;
+ change_prop(requestor, prop, XA_CARDINAL, 32, &t, 1);
+ } else if (image && target == AT(MIME_PNG)) {
+ size_t n = 0;
+ const unsigned char *png = wl_clip_png(&n);
+ if (!png) { notify_requestor(time_, requestor, selection, target, 0); return; }
+ write_data(requestor, prop, target, png, n);
+ } else if (!image && target == XA_STRING) { /* Latin-1 (what can't be said becomes '?') */
+ uint8_t *l = malloc(tlen + 1);
+ size_t o = 0;
+ for (size_t i = 0; l && i < tlen;) {
+ unsigned char c = (unsigned char)text[i];
+ uint32_t cp;
+ int k2 = c < 0x80 ? 1 : (c & 0xe0) == 0xc0 ? 2 : (c & 0xf0) == 0xe0 ? 3 : (c & 0xf8) == 0xf0 ? 4 : 1;
+ if (k2 == 2 && i + 1 < tlen) cp = (uint32_t)(c & 0x1f) << 6 | ((unsigned char)text[i + 1] & 0x3f);
+ else cp = c < 0x80 ? c : 0x3f;
+ l[o++] = cp <= 0xff ? (uint8_t)cp : '?';
+ i += (size_t)k2;
+ }
+ if (l) write_data(requestor, prop, XA_STRING, l, o);
+ free(l);
+ } else if (!image && (target == AT(UTF8_STRING) || target == AT(MIME_UTF8) || target == AT(MIME_TEXT) || target == AT(TEXT))) {
+ write_data(requestor, prop, target == AT(TEXT) ? AT(UTF8_STRING) : target, (const uint8_t *)text, tlen);
+ } else if (sensitive && target == AT(PW_HINT)) { /* clipboard managers skip it */
+ change_prop(requestor, prop, AT(PW_HINT), 8, "secret", 6);
+ } else {
+ notify_requestor(time_, requestor, selection, target, 0);
+ return;
+ }
+ notify_requestor(time_, requestor, selection, target, prop);
+}
+
+/* ---- events ---- */
+
+static void on_create(const uint8_t *p) {
+ uint32_t parent = x11_get32(p + 4), id = x11_get32(p + 8);
+ if (parent != X.su.root || id == X.wmwin) return;
+ XWin *w = add_win(id);
+ if (!w) return;
+ idle_arm();
+ w->x = (int16_t)x11_get16(p + 12);
+ w->y = (int16_t)x11_get16(p + 14);
+ w->w = x11_get16(p + 16);
+ w->h = x11_get16(p + 18);
+ w->override = p[22] != 0;
+ change_attrs(id, XCW_EventMask, XM_PropertyChange | XM_FocusChange);
+ read_props(w);
+}
+
+static void on_map_request(const uint8_t *p) {
+ uint32_t id = x11_get32(p + 8);
+ XWin *w = add_win(id);
+ if (!w) return;
+ if (!w->managed) {
+ w->managed = 1;
+ w->placed = 0;
+ uint32_t ext[4] = { 0, 0, 0, 0 };
+ change_prop(id, AT(NET_FRAME_EXTENTS), XA_CARDINAL, 32, ext, 4);
+ set_wm_state(w, 1); /* NormalState */
+ update_client_list();
+ }
+ req(X_MapWindow, 0);
+ xo_u32(&X.out, id);
+ xo_end(&X.out);
+}
+
+static void on_unmap(const uint8_t *p) {
+ XWin *w = find(x11_get32(p + 8));
+ if (!w) return;
+ w->viewable = 0;
+ detach(w);
+ if (w->managed) { w->managed = 0; set_wm_state(w, 0); update_client_list(); } /* WithdrawnState */
+ if (X.focus == w) X.focus = NULL;
+}
+
+static void on_configure_request(const uint8_t *p) {
+ uint32_t id = x11_get32(p + 8);
+ uint16_t mask = x11_get16(p + 26);
+ int x = (int16_t)x11_get16(p + 16), y = (int16_t)x11_get16(p + 18), w_ = x11_get16(p + 20), h = x11_get16(p + 22),
+ border = x11_get16(p + 24);
+ XWin *w = find(id);
+ if (!w || !w->managed || w->override || is_popup_type(w->wtype)) {
+ /* not one of LordOS's windows (yet): as asked */
+ int32_t v[5];
+ int n = 0;
+ uint16_t m = mask & (XCF_X | XCF_Y | XCF_W | XCF_H | XCF_Border);
+ if (m & XCF_X) v[n++] = x;
+ if (m & XCF_Y) v[n++] = y;
+ if (m & XCF_W) v[n++] = w_;
+ if (m & XCF_H) v[n++] = h;
+ if (m & XCF_Border) v[n++] = border;
+ if (m) configure(id, m, v, n);
+ return;
+ }
+ /* a LordOS window: it may change its size (not while maximized or fullscreen), never its place */
+ int nw = (mask & XCF_W) && !w->maximized && !w->fullscreen ? w_ : w->w;
+ int nh = (mask & XCF_H) && !w->maximized && !w->fullscreen ? h : w->h;
+ if (nw != w->w || nh != w->h) {
+ int32_t v[2] = { nw, nh };
+ configure(id, XCF_W | XCF_H, v, 2);
+ w->pw = nw;
+ w->ph = nh;
+ } else { /* ICCCM: a synthetic ConfigureNotify */
+ uint8_t ev[32] = { X_ConfigureNotify };
+ put32(ev + 4, id);
+ put32(ev + 8, id);
+ ev[16] = (uint8_t)w->x; ev[17] = (uint8_t)(w->x >> 8);
+ ev[18] = (uint8_t)w->y; ev[19] = (uint8_t)(w->y >> 8);
+ ev[20] = (uint8_t)w->w; ev[21] = (uint8_t)(w->w >> 8);
+ ev[22] = (uint8_t)w->h; ev[23] = (uint8_t)(w->h >> 8);
+ req(X_SendEvent, 0);
+ xo_u32(&X.out, id); xo_u32(&X.out, XM_StructureNotify);
+ xo_bytes(&X.out, ev, 32);
+ xo_end(&X.out);
+ }
+}
+
+static void on_configure_notify(const uint8_t *p) {
+ uint32_t ev = x11_get32(p + 4), id = x11_get32(p + 8);
+ XWin *w = find(id);
+ if (!w || ev != X.su.root) return;
+ w->x = (int16_t)x11_get16(p + 16);
+ w->y = (int16_t)x11_get16(p + 18);
+ w->w = x11_get16(p + 20);
+ w->h = x11_get16(p + 22);
+ w->override = p[26] != 0;
+ if (w->sid && (w->override || is_popup_type(w->wtype))) wlx_popup_moved(w->sid, w->x, w->y);
+}
+
+static void on_property(const uint8_t *p) {
+ uint32_t id = x11_get32(p + 4), a = x11_get32(p + 8);
+ int deleted = p[16] == 1;
+ if (id == X.wmwin) { /* the next INCR chunk of a copy */
+ for (int k = 0; k < NSEL; k++)
+ if (a == sel_prop(k) && !deleted && X.sel[k].stage == 3)
+ get_prop(X.wmwin, a, 1, CLIP_MAX / 4, sel_reply, (uint32_t)k, 3);
+ return;
+ }
+ if (deleted && xfer_step(id, a)) return; /* a paste in chunks asks for more */
+ XWin *w = find(id);
+ if (!w) return;
+ for (int i = 0; i < NWATCHED; i++)
+ if (watched_atom(i) == a) { get_prop(id, a, 0, 1024, prop_reply, id, a); break; }
+}
+
+static void on_client_message(const uint8_t *p) {
+ uint32_t id = x11_get32(p + 4), type = x11_get32(p + 8);
+ uint32_t d[5];
+ for (int i = 0; i < 5; i++) d[i] = x11_get32(p + 12 + 4 * i);
+ XWin *w = find(id);
+ if (!w) return;
+ if (type == AT(WL_SURFACE_ID)) {
+ w->surface_res = d[0];
+ try_attach(w);
+ } else if (type == AT(NET_WM_STATE)) {
+ int action = (int)d[0]; /* 0 remove, 1 add, 2 toggle */
+ for (int i = 1; i <= 2; i++) {
+ if (d[i] == AT(NET_WM_STATE_FULLSCREEN)) {
+ int on = action == 1 || (action == 2 && !w->fullscreen);
+ if (w->sid) wlx_request(w->sid, on ? XREQ_FULLSCREEN : XREQ_UNFULLSCREEN, 0);
+ else w->want_fs = on;
+ } else if (d[i] == AT(NET_WM_STATE_MAXIMIZED_VERT) || (d[i] == AT(NET_WM_STATE_MAXIMIZED_HORZ) && d[1] != AT(NET_WM_STATE_MAXIMIZED_VERT))) {
+ int on = action == 1 || (action == 2 && !w->maximized);
+ if (w->sid) wlx_request(w->sid, on ? XREQ_MAXIMIZE : XREQ_UNMAXIMIZE, 0);
+ } else if (d[i] == AT(NET_WM_STATE_HIDDEN) && action == 1 && w->sid) {
+ wlx_request(w->sid, XREQ_MINIMIZE, 0);
+ }
+ }
+ } else if (type == AT(NET_WM_MOVERESIZE)) {
+ int e = x11_moveresize_edges(d[2]);
+ if (w->sid && e) wlx_request(w->sid, e < 0 ? XREQ_MOVE : XREQ_RESIZE, e < 0 ? 0 : e);
+ } else if (type == AT(WM_CHANGE_STATE)) {
+ if (d[0] == 3 && w->sid) wlx_request(w->sid, XREQ_MINIMIZE, 0); /* IconicState */
+ }
+ /* _NET_ACTIVE_WINDOW from an app is ignored: only the user moves the focus (no focus stealing) */
+}
+
+static void on_focus_in(const uint8_t *p) {
+ uint32_t id = x11_get32(p + 4);
+ int mode = p[8];
+ if (mode == 1 || mode == 2) return; /* grabs */
+ XWin *w = find(id);
+ if (!w || !w->managed || w == X.focus) return;
+ /* an X app moved the keyboard to a window of another X app: back to the one the user chose */
+ if (!X.focus || !same_client(w->id, X.focus->id)) set_focus(X.focus && X.focus->input ? X.focus->id : 0);
+}
+
+static void handle(const uint8_t *p, size_t n) {
+ int type = p[0] & 0x7f;
+ if (type == X_Error || type == X_Reply) {
+ uint32_t seq = x11_seq_widen(X.seq, x11_get16(p + 2));
+ if (type == X_Error && X.debug) fprintf(stderr, "xwm: X error %u (request %u.%u, value 0x%x)\n", p[1], p[10], x11_get16(p + 8), x11_get32(p + 4));
+ while (X.pn && (int32_t)(X.pend[X.ph].seq - seq) < 0) { /* no reply came: its request failed */
+ Pend e = X.pend[X.ph];
+ X.ph = (X.ph + 1) % NPEND; X.pn--;
+ e.fn(NULL, 0, e.a, e.b);
+ }
+ if (X.pn && X.pend[X.ph].seq == seq) {
+ Pend e = X.pend[X.ph];
+ X.ph = (X.ph + 1) % NPEND; X.pn--;
+ e.fn(type == X_Reply ? p : NULL, type == X_Reply ? n : 0, e.a, e.b);
+ }
+ return;
+ }
+ if (X.xfixes_ev && type == X.xfixes_ev) { sel_owner_changed(p); return; }
+ switch (type) {
+ case X_CreateNotify: on_create(p); break;
+ case X_DestroyNotify: { XWin *w = find(x11_get32(p + 8)); if (w) { int m = w->managed; free_win(w); if (m) update_client_list(); idle_arm(); } break; }
+ case X_UnmapNotify: on_unmap(p); break;
+ case X_MapNotify: { XWin *w = find(x11_get32(p + 8)); if (w) { w->viewable = 1; w->override = p[12] != 0; } break; }
+ case X_MapRequest: on_map_request(p); break;
+ case X_ConfigureRequest: on_configure_request(p); break;
+ case X_ConfigureNotify: on_configure_notify(p); break;
+ case X_PropertyNotify: on_property(p); break;
+ case X_ClientMessage: on_client_message(p); break;
+ case X_FocusIn: on_focus_in(p); break;
+ case X_SelectionNotify: sel_notify_event(p); break;
+ case X_SelectionRequest: sel_request(p); break;
+ case X_SelectionClear: { int k = sel_index(x11_get32(p + 12)); if (k >= 0) X.sel[k].owned = 0; break; }
+ default: break;
+ }
+}
+
+/* ---- stopping when unused ----
+ * The window manager is an X client too, so Xwayland's own -terminate never fires. When no X
+ * window is left for IDLE_MS, the X-Resource extension tells whether any other client is still
+ * connected (one without windows, like a clipboard tool); if none, Xwayland is stopped. */
+static void idle_arm(void) { if (X.idle) wl_event_source_timer_update(X.idle, X.wins ? 0 : IDLE_MS); }
+
+static void clients_reply(const uint8_t *r, size_t n, uint32_t a, uint32_t b) {
+ (void)a; (void)b;
+ if (!r || n < 32 || X.wins) return;
+ uint32_t count = x11_get32(r + 8), others = 0;
+ for (uint32_t i = 0; i < count && 32 + (size_t)(i + 1) * 8 <= n; i++) {
+ uint32_t base = x11_get32(r + 32 + (size_t)i * 8);
+ if (base && base != X.su.id_base) others++; /* not the server, not us */
+ }
+ if (others) { idle_arm(); return; }
+ if (X.debug) fprintf(stderr, "xwm: no X11 app left\n");
+ xwl_idle();
+}
+
+static int idle_fired(void *data) {
+ (void)data;
+ if (X.wins || !X.ready) return 0;
+ if (!X.xres_op) { xwl_idle(); return 0; }
+ req(X.xres_op, 1); /* XResQueryClients */
+ xo_end(&X.out);
+ expect(clients_reply, 0, 0);
+ flush();
+ return 0;
+}
+
+/* ---- startup ---- */
+
+static void ignore_reply(const uint8_t *r, size_t n, uint32_t a, uint32_t b) { (void)r; (void)n; (void)a; (void)b; }
+
+/* The root window's cursor: LordOS's arrow, through the Render extension (ARGB). */
+static void pictfmt_reply(const uint8_t *r, size_t n, uint32_t a, uint32_t b) {
+ (void)a; (void)b;
+ if (!r || n < 32) return;
+ uint32_t nf = x11_get32(r + 8), fmt = 0;
+ for (uint32_t i = 0; i < nf && 32 + (size_t)(i + 1) * 28 <= n; i++) {
+ const uint8_t *f = r + 32 + (size_t)i * 28;
+ if (f[4] == 1 && f[5] == 32 && x11_get16(f + 8) == 16 && x11_get16(f + 12) == 8 && x11_get16(f + 16) == 0 &&
+ x11_get16(f + 20) == 24 && x11_get16(f + 22) == 0xff) { fmt = x11_get32(f); break; }
+ }
+ const CursorImage *ci = cursor_image(CUR_DEFAULT, 1);
+ if (!fmt || !ci || ci->w <= 0 || ci->h <= 0 || ci->w > 128 || ci->h > 128) return;
+ uint32_t pix = new_id(), gc = new_id(), pic = new_id(), cur = new_id();
+ req(X_CreatePixmap, 32);
+ xo_u32(&X.out, pix); xo_u32(&X.out, X.su.root); xo_u16(&X.out, (uint16_t)ci->w); xo_u16(&X.out, (uint16_t)ci->h);
+ xo_end(&X.out);
+ req(X_CreateGC, 0);
+ xo_u32(&X.out, gc); xo_u32(&X.out, pix); xo_u32(&X.out, 0);
+ xo_end(&X.out);
+ req(X_PutImage, 2); /* ZPixmap */
+ xo_u32(&X.out, pix); xo_u32(&X.out, gc); xo_u16(&X.out, (uint16_t)ci->w); xo_u16(&X.out, (uint16_t)ci->h);
+ xo_u16(&X.out, 0); xo_u16(&X.out, 0); xo_u8(&X.out, 0); xo_u8(&X.out, 32); xo_pad(&X.out, 2);
+ for (int i = 0; i < ci->w * ci->h; i++) xo_u32(&X.out, ci->px[i]);
+ xo_end(&X.out);
+ req(X.render_op, 4); /* RenderCreatePicture */
+ xo_u32(&X.out, pic); xo_u32(&X.out, pix); xo_u32(&X.out, fmt); xo_u32(&X.out, 0);
+ xo_end(&X.out);
+ req(X.render_op, 27); /* RenderCreateCursor */
+ xo_u32(&X.out, cur); xo_u32(&X.out, pic); xo_u16(&X.out, (uint16_t)ci->hx); xo_u16(&X.out, (uint16_t)ci->hy);
+ xo_end(&X.out);
+ change_attrs(X.su.root, XCW_Cursor, cur);
+ req(X.render_op, 7); xo_u32(&X.out, pic); xo_end(&X.out); /* RenderFreePicture */
+ req(X_FreeGC, 0); xo_u32(&X.out, gc); xo_end(&X.out);
+ req(X_FreePixmap, 0); xo_u32(&X.out, pix); xo_end(&X.out);
+ X.cursor = cur;
+ flush();
+}
+
+static void init_done(void) {
+ uint32_t root = X.su.root;
+ /* the window manager: every top-level window's map and configure requests come to us */
+ change_attrs(root, XCW_EventMask, XM_SubstructureRedirect | XM_SubstructureNotify | XM_PropertyChange | XM_FocusChange);
+ X.wmwin = new_id();
+ req(X_CreateWindow, 0); /* depth CopyFromParent */
+ xo_u32(&X.out, X.wmwin); xo_u32(&X.out, root);
+ xo_u16(&X.out, (uint16_t)-100); xo_u16(&X.out, (uint16_t)-100); xo_u16(&X.out, 1); xo_u16(&X.out, 1);
+ xo_u16(&X.out, 0); xo_u16(&X.out, 2); /* InputOnly */
+ xo_u32(&X.out, 0); /* visual CopyFromParent */
+ xo_u32(&X.out, XCW_OverrideRedirect | XCW_EventMask);
+ xo_u32(&X.out, 1); xo_u32(&X.out, XM_PropertyChange);
+ xo_end(&X.out);
+ change_prop(X.wmwin, AT(NET_SUPPORTING_WM_CHECK), XA_WINDOW, 32, &X.wmwin, 1);
+ change_prop(root, AT(NET_SUPPORTING_WM_CHECK), XA_WINDOW, 32, &X.wmwin, 1);
+ change_prop(X.wmwin, AT(NET_WM_NAME), AT(UTF8_STRING), 8, "LordOS", 6);
+ uint32_t sup[] = { AT(NET_WM_STATE), AT(NET_WM_STATE_FULLSCREEN), AT(NET_WM_STATE_MAXIMIZED_VERT), AT(NET_WM_STATE_MAXIMIZED_HORZ),
+ AT(NET_WM_STATE_HIDDEN), AT(NET_WM_STATE_FOCUSED), AT(NET_ACTIVE_WINDOW), AT(NET_WM_MOVERESIZE),
+ AT(NET_CLIENT_LIST), AT(NET_SUPPORTING_WM_CHECK), AT(NET_WM_NAME), AT(NET_FRAME_EXTENTS),
+ AT(NET_WM_WINDOW_TYPE), AT(NET_WM_WINDOW_TYPE_NORMAL), AT(NET_WM_WINDOW_TYPE_DIALOG),
+ AT(NET_WM_WINDOW_TYPE_SPLASH), AT(NET_WM_WINDOW_TYPE_MENU), AT(NET_WM_WINDOW_TYPE_POPUP_MENU),
+ AT(NET_WM_WINDOW_TYPE_DROPDOWN_MENU), AT(NET_WM_WINDOW_TYPE_TOOLTIP), AT(NET_WM_WINDOW_TYPE_COMBO) };
+ change_prop(root, AT(NET_SUPPORTED), XA_ATOM, 32, sup, (uint32_t)(sizeof sup / sizeof sup[0]));
+ uint32_t none = 0;
+ change_prop(root, AT(NET_ACTIVE_WINDOW), XA_WINDOW, 32, &none, 1);
+ update_client_list();
+ if (X.xfixes_op) {
+ req(X.xfixes_op, 0); xo_u32(&X.out, 5); xo_u32(&X.out, 0); xo_end(&X.out); /* XFixesQueryVersion */
+ expect(ignore_reply, 0, 0);
+ for (int k = 0; k < NSEL; k++) {
+ req(X.xfixes_op, 2); /* XFixesSelectSelectionInput: owner, window, client */
+ xo_u32(&X.out, X.wmwin); xo_u32(&X.out, sel_atom(k)); xo_u32(&X.out, 7);
+ xo_end(&X.out);
+ }
+ } else fprintf(stderr, "xwm: no XFIXES: the clipboard is not shared with X11 apps\n");
+ if (X.render_op) {
+ req(X.render_op, 0); xo_u32(&X.out, 0); xo_u32(&X.out, 11); xo_end(&X.out); /* RenderQueryVersion */
+ expect(ignore_reply, 0, 0);
+ req(X.render_op, 1); xo_end(&X.out); /* RenderQueryPictFormats */
+ expect(pictfmt_reply, 0, 0);
+ }
+ /* rootless Xwayland gives a wl_surface only to windows the window manager redirected */
+ if (X.composite_op) {
+ req(X.composite_op, 0); xo_u32(&X.out, 0); xo_u32(&X.out, 4); xo_end(&X.out); /* CompositeQueryVersion */
+ expect(ignore_reply, 0, 0);
+ req(X.composite_op, 2); /* CompositeRedirectSubwindows, manual */
+ xo_u32(&X.out, root); xo_u8(&X.out, 1); xo_pad(&X.out, 3);
+ xo_end(&X.out);
+ } else fprintf(stderr, "xwm: no Composite extension: X11 windows can't be shown\n");
+ /* owning WM_S0 tells Xwayland the window manager is ready: only then it accepts X apps */
+ set_owner(X.wmwin, AT(WM_S0));
+ X.ready = 1;
+ X.idle = wl_event_loop_add_timer(X.loop, idle_fired, NULL);
+ idle_arm();
+ fprintf(stderr, "xwm: ready (root 0x%x, %ux%u)\n", root, X.su.width, X.su.height);
+}
+
+static void atom_reply(const uint8_t *r, size_t n, uint32_t i, uint32_t b) {
+ (void)b;
+ if (r && n >= 12 && i < A_COUNT) atom[i] = x11_get32(r + 8);
+ if (--X.init_left == 0) init_done();
+}
+
+static void ext_reply(const uint8_t *r, size_t n, uint32_t which, uint32_t b) {
+ (void)b;
+ if (r && n >= 12 && r[8]) {
+ if (which == 0) { X.xfixes_op = r[9]; X.xfixes_ev = r[10]; }
+ else if (which == 1) X.render_op = r[9];
+ else if (which == 2) X.composite_op = r[9];
+ else X.xres_op = r[9];
+ }
+ if (--X.init_left == 0) init_done();
+}
+
+static void query_ext(const char *name, uint32_t which) {
+ size_t n = strlen(name);
+ req(X_QueryExtension, 0);
+ xo_u16(&X.out, (uint16_t)n); xo_u16(&X.out, 0);
+ xo_bytes(&X.out, name, n);
+ xo_end(&X.out);
+ expect(ext_reply, which, 0);
+ X.init_left++;
+}
+
+static void start_init(void) {
+ for (int i = 0; i < A_COUNT; i++) {
+ size_t n = strlen(atom_names[i]);
+ req(X_InternAtom, 0);
+ xo_u16(&X.out, (uint16_t)n); xo_u16(&X.out, 0);
+ xo_bytes(&X.out, atom_names[i], n);
+ xo_end(&X.out);
+ expect(atom_reply, (uint32_t)i, 0);
+ X.init_left++;
+ }
+ query_ext("XFIXES", 0);
+ query_ext("RENDER", 1);
+ query_ext("Composite", 2);
+ query_ext("X-Resource", 3);
+}
+
+/* ---- the connection ---- */
+
+static int on_fd(int fd, uint32_t mask, void *data) {
+ (void)data;
+ if (mask & WL_EVENT_WRITABLE) flush();
+ if (X.fd < 0) return 0;
+ if (mask & WL_EVENT_READABLE) {
+ for (;;) {
+ if (X.in_cap - X.in_n < 65536) {
+ size_t cap = X.in_cap ? X.in_cap * 2 : 131072;
+ if (cap > (40u << 20)) { lost("reply too large"); return 0; }
+ uint8_t *nb = realloc(X.in, cap);
+ if (!nb) { lost("out of memory"); return 0; }
+ X.in = nb;
+ X.in_cap = cap;
+ }
+ ssize_t r = recv(fd, X.in + X.in_n, X.in_cap - X.in_n, MSG_DONTWAIT);
+ if (r > 0) { X.in_n += (size_t)r; continue; }
+ if (r == 0) { lost("Xwayland closed the connection"); return 0; }
+ if (errno == EINTR) continue;
+ if (errno == EAGAIN || errno == EWOULDBLOCK) break;
+ lost("read failed");
+ return 0;
+ }
+ size_t off = 0;
+ if (!X.setup_done) {
+ size_t used = 0;
+ int ok = x11_parse_setup(X.in, X.in_n, &X.su, &used);
+ if (ok < 0) { lost("connection refused"); return 0; }
+ if (ok > 0) {
+ off = used;
+ X.setup_done = 1;
+ if (X.su.max_req_bytes < 4096) X.su.max_req_bytes = 4096;
+ start_init();
+ }
+ }
+ while (X.setup_done && X.fd >= 0) {
+ size_t len = x11_packet_len(X.in + off, X.in_n - off);
+ if (!len) break;
+ handle(X.in + off, len);
+ off += len;
+ }
+ if (X.fd < 0) return 0;
+ memmove(X.in, X.in + off, X.in_n - off);
+ X.in_n -= off;
+ } else if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) {
+ lost("Xwayland hung up");
+ return 0;
+ }
+ flush();
+ return 0;
+}
+
+int xwm_start(int fd, struct wl_event_loop *loop) {
+ xwm_stop();
+ X.debug = 1; /* XWMDEBUG-TEMP */
+ X.fd = fd;
+ X.loop = loop;
+ X.ev = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, on_fd, NULL);
+ if (!X.ev) { close(fd); X.fd = -1; return -1; }
+ uint8_t setup[12];
+ x11_setup_request(setup);
+ for (int i = 0; i < 12; i++) xo_u8(&X.out, setup[i]);
+ flush();
+ return 0;
+}
+
+void xwm_stop(void) {
+ while (X.wins) free_win(X.wins);
+ while (X.xfers) xfer_free(X.xfers);
+ for (int k = 0; k < NSEL; k++) sel_reset(&X.sel[k]);
+ if (X.ev) wl_event_source_remove(X.ev);
+ if (X.idle) wl_event_source_remove(X.idle);
+ if (X.fd >= 0) close(X.fd);
+ xo_free(&X.out);
+ free(X.in);
+ int debug = X.debug;
+ memset(&X, 0, sizeof X);
+ X.fd = -1;
+ X.debug = debug;
+ memset(atom, 0, sizeof atom);
+}
+
+static void lost(const char *why) {
+ if (X.fd < 0) return;
+ fprintf(stderr, "xwm: %s\n", why);
+ xwm_stop();
+ xwl_wm_lost();
+}
+
+int xwm_running(void) { return X.fd >= 0 && X.ready; }
+
+/* ---- from the compositor ---- */
+
+void xwm_surface_created(uint32_t res_id) {
+ for (XWin *w = X.wins; w; w = w->next) if (w->surface_res == res_id && !w->sid) { try_attach(w); break; }
+}
+
+void xwm_surface_gone(XWin *w) {
+ if (!w) return;
+ for (XWin *o = X.wins; o; o = o->next) if (o == w) { w->sid = 0; w->surface_res = 0; return; }
+}
+
+void xwm_place(XWin *w, int x, int y) {
+ if (!X.ready || !w->managed || w->minimized) return;
+ if (w->placed && x == w->px && y == w->py) return;
+ int32_t v[2] = { x, y };
+ configure(w->id, XCF_X | XCF_Y, v, 2);
+ w->px = x;
+ w->py = y;
+ w->placed = 1;
+ flush();
+}
+
+void xwm_resize(XWin *w, int width, int height) {
+ if (!X.ready || !w->managed || width < 1 || height < 1 || width > 32767 || height > 32767) return;
+ if (width == w->pw && height == w->ph && width == w->w && height == w->h) return;
+ int32_t v[2] = { width, height };
+ configure(w->id, XCF_W | XCF_H, v, 2);
+ w->pw = width;
+ w->ph = height;
+ flush();
+}
+
+void xwm_set_state(XWin *w, int maximized, int fullscreen, int minimized) {
+ if (!X.ready || !w->managed) return;
+ int was_min = w->minimized;
+ w->maximized = maximized;
+ w->fullscreen = fullscreen;
+ w->minimized = minimized;
+ if (minimized != was_min) {
+ set_wm_state(w, minimized ? 3 : 1); /* IconicState / NormalState */
+ if (minimized) { /* at the bottom: it never catches the pointer */
+ int32_t v[1] = { X_Below };
+ configure(w->id, XCF_StackMode, v, 1);
+ } else w->placed = 0;
+ }
+ write_net_state(w);
+ flush();
+}
+
+void xwm_focus(XWin *w) {
+ if (!X.ready || w == X.focus) { if (X.ready) flush(); return; }
+ XWin *old = X.focus;
+ X.focus = w;
+ if (old) { old->focused = 0; write_net_state(old); }
+ uint32_t id = w ? w->id : 0;
+ if (w) {
+ if (w->input) set_focus(w->id); /* ICCCM: passive / locally active */
+ else if (!w->take_focus) set_focus(0); /* no input */
+ if (w->take_focus) {
+ uint32_t d[5] = { AT(WM_TAKE_FOCUS), 0, 0, 0, 0 };
+ client_message(w->id, AT(WM_PROTOCOLS), d);
+ }
+ int32_t v[1] = { X_Above };
+ configure(w->id, XCF_StackMode, v, 1);
+ w->focused = 1;
+ write_net_state(w);
+ } else set_focus(0);
+ change_prop(X.su.root, AT(NET_ACTIVE_WINDOW), XA_WINDOW, 32, &id, 1);
+ clip_sync();
+ flush();
+}
+
+void xwm_close(XWin *w) {
+ if (!X.ready) return;
+ if (w->del_window) {
+ uint32_t d[5] = { AT(WM_DELETE_WINDOW), 0, 0, 0, 0 };
+ client_message(w->id, AT(WM_PROTOCOLS), d);
+ } else {
+ req(X_KillClient, 0);
+ xo_u32(&X.out, w->id);
+ xo_end(&X.out);
+ }
+ flush();
+}
+
+void xwm_tick(void) {
+ if (!X.ready) return;
+ clip_sync();
+ time_t now = time(NULL);
+ for (Xfer *t = X.xfers, *nx; t; t = nx) { nx = t->next; if (now - t->t0 > 30) xfer_free(t); } /* a paste nobody reads */
+ flush();
+}
diff --git a/server/src/wl/xwm.h b/server/src/wl/xwm.h
new file mode 100644
index 0000000..20fd6db
--- /dev/null
+++ b/server/src/wl/xwm.h
@@ -0,0 +1,59 @@
+/* xwm.h — LordOS's X window manager for Xwayland (xwm.c) and its glue with the compositor (wl.c).
+ *
+ * X11 apps are clients of Xwayland; Xwayland is one Wayland client of lord-server and gives every
+ * mapped top-level X window a wl_surface. The window manager is a second X client (on the fd
+ * Xwayland gets with -wm) that decides what those windows are: a LordOS window with the theme's
+ * frame, a menu or tooltip drawn above everything (override-redirect), their title and app
+ * (WM_CLASS), focus, stacking, close, fullscreen, and the clipboard bridge. See docs/WAYLAND.md,
+ * "X11 apps (Xwayland)", and docs/PRIVACY.md, "X11 apps". */
+#ifndef LORD_XWM_H
+#define LORD_XWM_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+struct wl_client;
+struct wl_event_loop;
+typedef struct XWin XWin;
+
+/* ---- xwm.c, called by xwayland.c ---- */
+int xwm_start(int fd, struct wl_event_loop *loop); /* the -wm connection; 0 ok (takes the fd) */
+void xwm_stop(void);
+int xwm_running(void);
+
+/* ---- xwm.c, called by wl.c ---- */
+void xwm_surface_created(uint32_t res_id); /* Xwayland created a wl_surface (WL_SURFACE_ID may wait for it) */
+void xwm_surface_gone(XWin *w); /* its wl_surface was destroyed */
+void xwm_place(XWin *w, int x, int y); /* where its content is on screen (logical, from wl_paint) */
+void xwm_resize(XWin *w, int width, int height); /* the theme's frame gave it this size */
+void xwm_set_state(XWin *w, int maximized, int fullscreen, int minimized);
+void xwm_focus(XWin *w); /* NULL: a LordOS or Wayland window has the keyboard */
+void xwm_close(XWin *w);
+void xwm_tick(void); /* once per loop (wl_flush): clipboard changes, output */
+
+/* ---- wl.c, called by xwm.c ---- */
+typedef struct {
+ const char *title, *app_id, *app_alt; /* WM_CLASS class and instance */
+ int csd; /* draws its own frame (Motif hints): no theme frame */
+ int popup; /* menu, tooltip, override-redirect: drawn above everything */
+ int x, y, width, height;
+} XWinInfo;
+struct wl_client *wlx_client(void); /* Xwayland's connection (NULL if not running) */
+void wlx_set_client(struct wl_client *c);
+/* Gives the X window's wl_surface its role. Returns the surface id, 0 if that surface doesn't exist
+ * (yet) or isn't Xwayland's. */
+int wlx_attach(uint32_t res_id, XWin *w, const XWinInfo *info);
+void wlx_detach(int sid); /* the X window was unmapped or destroyed */
+void wlx_set_title(int sid, const char *title);
+void wlx_popup_moved(int sid, int x, int y);
+enum { XREQ_MOVE = 1, XREQ_RESIZE, XREQ_MAXIMIZE, XREQ_UNMAXIMIZE, XREQ_MINIMIZE, XREQ_FULLSCREEN, XREQ_UNFULLSCREEN };
+void wlx_request(int sid, int what, int arg);
+void wlx_fullscreen_rect(int *x, int *y, int *w, int *h); /* the display a fullscreen X window covers */
+/* Clipboard: what an X app copied becomes LordOS's (and every Wayland app's) selection. */
+void wlx_clip_text(const char *text, size_t n, const char *origin);
+void wlx_clip_png(const unsigned char *png, size_t n, const char *origin);
+void wlx_primary_text(const char *text, size_t n);
+/* The PRIMARY selection of Wayland apps (middle-click paste), for X: text and a generation. */
+const char *wlx_primary(size_t *n, unsigned *gen);
+
+#endif