From 08429ff5f71bbd3199830dfb000602929ba0bc6c Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:58:50 +0800 Subject: [PATCH 1/5] tools: activate the guest's window from inside the prefix Under gamescope the game runs as a nested child of `explorer /desktop=` and its X window is override-redirect (measured: 0x02400001, OR=1, child of the explorer desktop window; every child of that desktop is OR). Wine does not activate an override-redirect child, so a title comes up inactive and its input loop ignores every device: NFS Most Wanted sat on "press START" and no button did anything. A mouse click works only because wine's own click-to-focus activates the window on the first press. The activation cannot come from our side of the boundary. WM_ACTIVATE and WM_SETFOCUS are Win32 messages and only a process inside the prefix can raise them; the X-level substitute was measured and fails (XSetInputFocus on the game's window sticks, and wine received the focus change on a window it does not manage and never activated it). That is why gamescope's A48 patch reached winhandler.exe over UDP. gn-activate removes the whole hop: it waits for the window itself, so no compositor patch, no UDP and no IPC are involved. It matches the target by owning process image, not by WM_CLASS, so no class deny-list and no tabtip/explorer special cases; it enumerates children as well as top-levels, because the game's window is nested; and among matches it takes the largest visible one, which skips the unmapped 1x1 window a D3D9 title also creates. SetForegroundWindow is tried first, then the AttachThreadInput escalation; SendMessage WM_ACTIVATE is behind --force-messages because it convinces the game it is active while wine's input routing stays put, which produces a title that takes mouse but not keys. Measured on RP6, NFS Most Wanted, proton-11.0-2-arm64ec-10: gn-activate: joined desktop 'shell' gn-activate: window 0x0001008a nfs13.exe pid=472 1280x720 class=CgsGameWindowClass SetForegroundWindow: foreground and a second run reports "already foreground", so the plain call holds and the escalation goes unused. Two on-device constraints, both silent in confusing ways, are recorded in build-gn-activate.sh: the .exe must live inside the prefix (from a unix path outside it the translator faults before main with signal 11, and a hello-world PE built with the same toolchain fails identically, so it is the location and not the code), and the process must join the game's desktop (a fresh wine process starts on the default desktop, where EnumWindows returns nothing at all). The HWND is not the X id (0x0001008a for X window 0x02400001), which is why the image match is not merely tidier. xtree-probe gains -focus and -raise, each followed by a one-second read-back so "the server refused it" and "the compositor took it back" cannot be confused, plus a bottom-to-top sibling list. That is how the override-redirect tree above was measured, and how the X-level focus change was ruled out. --- tools/build-gn-activate.sh | 71 ++++++ tools/gn-activate/gn-activate.c | 414 ++++++++++++++++++++++++++++++++ tools/xtree-probe.c | 68 ++++++ 3 files changed, 553 insertions(+) create mode 100644 tools/build-gn-activate.sh create mode 100644 tools/gn-activate/gn-activate.c diff --git a/tools/build-gn-activate.sh b/tools/build-gn-activate.sh new file mode 100644 index 0000000..dcf952d --- /dev/null +++ b/tools/build-gn-activate.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# build-gn-activate.sh — cross-build tools/gn-activate/gn-activate.c as a Win32 +# PE, which is what makes it able to activate the game's window at all. +# +# The activation has to be a Win32 call (SetForegroundWindow) because +# WM_ACTIVATE/WM_SETFOCUS can only be raised from inside the wine prefix. The +# X-level substitute was measured and fails: XSetInputFocus on the game's +# override-redirect child sticks and changes nothing, because wine receives the +# focus change on a window it does not manage and never activates it. gamescope's +# old A48 patch existed for exactly this reason and reached winhandler.exe over +# UDP; this program replaces the whole hop with "wait for the window, activate +# it", so no compositor patch and no IPC are involved. +# +# Built both bitnesses on purpose: the prefix is win64 with WoW64, so either +# runs, and trying 32-bit first costs nothing if 64-bit is refused. The two are +# separate executables rather than one, because a PE has a fixed machine type. +# +# Two on-device constraints found while running it by hand, both silent in +# confusing ways: +# +# - the .exe must live inside the wine prefix (e.g. drive_c/). Run from a unix +# path outside it and the translator faults before main with signal 11, which +# looks exactly like a broken executable. A minimal hello-world PE built with +# the same toolchain fails the same way, so it is the location, not the code. +# - the process must join the game's desktop. `explorer /desktop=shell` puts the +# game on a desktop named shell; a fresh wine process starts on the default +# desktop, where EnumWindows returns nothing at all. gn-activate joins it with +# --desktop (default "shell"). Launching it from the explorer command line, +# the way winhandler.exe is launched, gets the right desktop for free. +# +# Also note the HWND is not the X window id (measured: HWND 0x0001008a for the X +# window 0x02400001), which is why the target is matched by process image. +# +# Usage: ./tools/build-gn-activate.sh +# Output: target/win32/gn-activate.exe (i686, run in a WoW64 prefix) +# target/win32/gn-activate64.exe (x86_64) + +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +GCC32="${MINGW32_GCC:-i686-w64-mingw32-gcc}" +GCC64="${MINGW64_GCC:-x86_64-w64-mingw32-gcc}" + +OUTDIR="$ROOT/target/win32" +mkdir -p "$OUTDIR" + +# -municode is not used: the program is plain main() with the ANSI APIs, since +# wine's window classes and titles here are ASCII and the calls stay readable. +# -O2 -Wall -Wextra, and static libgcc so the exe has no mingw runtime deps +# beyond msvcrt/kernel32/user32, which every wine prefix has. +CFLAGS=(-O2 -Wall -Wextra -static-libgcc) +LIBS=(-luser32 -lkernel32) + +if command -v "$GCC32" >/dev/null 2>&1; then + "$GCC32" "${CFLAGS[@]}" -o "$OUTDIR/gn-activate.exe" \ + tools/gn-activate/gn-activate.c "${LIBS[@]}" + echo "built: $OUTDIR/gn-activate.exe (i686)" +else + echo "skip: $GCC32 not found" >&2 +fi + +if command -v "$GCC64" >/dev/null 2>&1; then + "$GCC64" "${CFLAGS[@]}" -o "$OUTDIR/gn-activate64.exe" \ + tools/gn-activate/gn-activate.c "${LIBS[@]}" + echo "built: $OUTDIR/gn-activate64.exe (x86_64)" +else + echo "skip: $GCC64 not found" >&2 +fi + +file "$OUTDIR"/gn-activate*.exe diff --git a/tools/gn-activate/gn-activate.c b/tools/gn-activate/gn-activate.c new file mode 100644 index 0000000..a52e388 --- /dev/null +++ b/tools/gn-activate/gn-activate.c @@ -0,0 +1,414 @@ +/* + * gn-activate.c — make the guest game's window the foreground window, from + * inside the wine prefix, at the moment the window exists. + * + * Why this exists: under gamescope the game runs as a nested child of + * `explorer /desktop=shell` and its X window is override-redirect (measured: + * 0x02400001, OR=1, child of the explorer desktop window). Wine does not + * activate an override-redirect child, so the title comes up inactive and its + * input loop ignores every device — the user sees "press START" that never + * takes. A mouse click works only because wine's own click-to-focus activates + * the window on the first press. + * + * Activation cannot be delivered from the Linux side. WM_ACTIVATE/WM_SETFOCUS + * are Win32 messages and only a process in the prefix can raise them; the + * X-level substitute was measured and fails (XSetInputFocus on the game's + * window sticks and changes nothing, because wine received the focus change on + * its own child and did not activate it). That is why gamescope's old A48 + * patch had to reach winhandler.exe over UDP — the hop into wine is + * unavoidable. What is avoidable is everything around the hop: this program + * needs no compositor patch, no UDP and no IPC, because it waits for the + * window itself. + * + * Usage: + * gn-activate.exe nfs13.exe + * gn-activate.exe --timeout-ms 180000 --verbose NFS13.exe + * gn-activate.exe --list # every visible window + * + * --timeout-ms N how long to wait for the window (default 120000) + * --settle-ms N wait after each activation attempt before reading the + * foreground back (default 300) + * --force-messages if SetForegroundWindow is refused, fall back to + * SendMessage WM_ACTIVATE/WM_SETFOCUS. Off by default: + * that only convinces the *game* it is active while + * wine's input routing stays where it was, which produces + * a title that accepts mouse but not keys. + * --desktop NAME the wine desktop to join before looking (default + * "shell", which is what `explorer /desktop=shell` names). + * Without this the process sits on wine's default desktop + * and EnumWindows returns nothing, because windows belong + * to a desktop and the game's belong to explorer's. + * --list print the visible windows and exit (no activation) + * --verbose per-attempt detail + * + * --desktop none stay on whatever desktop is current + * + * Exit codes: 0 activated (or already foreground), 1 refused, 2 no window in + * time, 3 bad usage. + * + * Window selection: the target is matched by owning process image, never by + * WM_CLASS string, so no class deny-list and no tabtip/explorer special cases. + * Children are enumerated too — the game's window is a child of the desktop, + * so EnumWindows alone (top level only) never sees it. Among matches the + * largest visible window wins, which skips the unmapped 1x1 leftover window a + * D3D9 title also creates. + */ + +#include +#include +#include +#include +#include + +#define MAX_TARGETS 8 +#define POLL_MS 100 + +static int g_verbose = 0; + +struct target { + char image[64]; /* lower-cased basename, e.g. "nfs13.exe" */ +}; + +struct target g_targets[MAX_TARGETS]; +static int g_ntargets = 0; + +struct candidate { + HWND hwnd; + RECT rect; + DWORD pid; + char image[64]; + char cls[128]; + char title[160]; +}; + +static void lower(char *s) +{ + for (; *s; s++) *s = (char)tolower((unsigned char)*s); +} + +static const char *basename_(const char *path) +{ + const char *a = strrchr(path, '\\'); + const char *b = strrchr(path, '/'); + const char *p = a > b ? a : b; + return p ? p + 1 : path; +} + +/* Image basename of the process owning hwnd, lower-cased. Empty on failure. */ +static void image_of(HWND hwnd, DWORD *pid_out, char *image, size_t image_len) +{ + DWORD pid = 0; + HANDLE proc; + char path[MAX_PATH]; + DWORD len = MAX_PATH; + + image[0] = '\0'; + GetWindowThreadProcessId(hwnd, &pid); + if (pid_out) *pid_out = pid; + + /* PROCESS_QUERY_LIMITED_INFORMATION is enough for the image name and does + * not need the extra rights PROCESS_QUERY_INFORMATION asks for. */ + proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + if (!proc) return; + if (QueryFullProcessImageNameA(proc, 0, path, &len)) { + /* the basename of a MAX_PATH path can exceed image_len; bound it here + * rather than trusting snprintf's silent truncation */ + snprintf(image, image_len, "%.*s", (int)image_len - 1, basename_(path)); + lower(image); + } + CloseHandle(proc); +} + +static int matches_target(const char *image) +{ + for (int i = 0; i < g_ntargets; i++) + if (image[0] && strcmp(image, g_targets[i].image) == 0) return 1; + return 0; +} + +static void describe(HWND hwnd, struct candidate *c) +{ + memset(c, 0, sizeof(*c)); + c->hwnd = hwnd; + GetWindowRect(hwnd, &c->rect); + image_of(hwnd, &c->pid, c->image, sizeof(c->image)); + GetClassNameA(hwnd, c->cls, sizeof(c->cls)); + GetWindowTextA(hwnd, c->title, sizeof(c->title)); +} + +static long area(const RECT *r) +{ + long w = r->right - r->left, h = r->bottom - r->top; + return (w > 0 && h > 0) ? w * h : 0; +} + +struct scan { + struct candidate best; + int found; + int list; +}; + +static BOOL CALLBACK scan_proc(HWND hwnd, LPARAM lp) +{ + struct scan *s = (struct scan *)lp; + struct candidate c; + + if (!IsWindowVisible(hwnd)) return TRUE; + describe(hwnd, &c); + + if (s->list) { + if (area(&c.rect) > 0) + printf(" 0x%08lx %-20s pid=%-6lu %4ldx%-4ld class=%-20s %s\n", + (unsigned long)(ULONG_PTR)hwnd, c.image, (unsigned long)c.pid, + c.rect.right - c.rect.left, c.rect.bottom - c.rect.top, + c.cls, c.title); + return TRUE; + } + + /* The game's window is a child of the desktop window, so a top-level match + * is a bonus, not the common case; scan children on every top-level too. */ + if (matches_target(c.image) && area(&c.rect) > 0) { + if (!s->found || area(&c.rect) > area(&s->best.rect)) { + s->best = c; + s->found = 1; + } + } + return TRUE; +} + +static BOOL CALLBACK child_scan_proc(HWND hwnd, LPARAM lp) +{ + struct scan *s = (struct scan *)lp; + struct candidate c; + + if (!IsWindowVisible(hwnd)) return TRUE; + describe(hwnd, &c); + + if (s->list) { + if (area(&c.rect) > 0) + printf(" child 0x%08lx %-16s pid=%-6lu %4ldx%-4ld class=%-16s %s\n", + (unsigned long)(ULONG_PTR)hwnd, c.image, (unsigned long)c.pid, + c.rect.right - c.rect.left, c.rect.bottom - c.rect.top, + c.cls, c.title); + return TRUE; + } + + if (matches_target(c.image) && area(&c.rect) > 0) { + if (!s->found || area(&c.rect) > area(&s->best.rect)) { + s->best = c; + s->found = 1; + } + } + return TRUE; +} + +static BOOL CALLBACK tops_for_children(HWND hwnd, LPARAM lp) +{ + /* EnumChildWindows is recursive, so this reaches grandchildren too — the + * game's X window is a child of the desktop, which is itself a top-level. */ + EnumChildWindows(hwnd, child_scan_proc, lp); + return TRUE; +} + +/* One pass over top-levels, then one over their children. Both passes matter: + * a top-level game window is the rare case, a nested one is ours. */ +static void scan_all(int list, struct candidate *out) +{ + struct scan s; + memset(&s, 0, sizeof(s)); + s.list = list; + + EnumWindows(scan_proc, (LPARAM)&s); + EnumWindows(tops_for_children, (LPARAM)&s); + + if (out && s.found) *out = s.best; +} + +static int foreground_is(HWND hwnd) +{ + return GetForegroundWindow() == hwnd; +} + +static void print_foreground(const char *when) +{ + struct candidate c; + HWND fg = GetForegroundWindow(); + if (!fg) { + printf(" %s: foreground=\n", when); + return; + } + describe(fg, &c); + printf(" %s: foreground=0x%08lx %s class=%s\n", when, + (unsigned long)(ULONG_PTR)fg, c.image[0] ? c.image : "?", c.cls); +} + +static int activate(HWND hwnd, int settle_ms, int force_messages) +{ + DWORD target_tid, fg_tid; + + if (foreground_is(hwnd)) { + printf(" already foreground\n"); + return 0; + } + + /* Attempt 1: the direct call. A process that has just started is allowed + * to take the foreground, which is why this usually works for us and would + * not work for a long-lived background process. */ + if (g_verbose) printf(" SetForegroundWindow\n"); + SetForegroundWindow(hwnd); + Sleep(settle_ms); + if (foreground_is(hwnd)) { + printf(" SetForegroundWindow: foreground\n"); + return 0; + } + if (g_verbose) print_foreground("after SetForegroundWindow"); + + /* Attempt 2: join the input queues of the calling thread, the current + * foreground thread and the target's thread, then retry, then detach. This + * is the documented escalation when the foreground lock refuses attempt 1, + * and wine honours it. */ + target_tid = GetWindowThreadProcessId(hwnd, NULL); + fg_tid = GetWindowThreadProcessId(GetForegroundWindow(), NULL); + if (g_verbose) printf(" AttachThreadInput(target=%lu fg=%lu)\n", + (unsigned long)target_tid, (unsigned long)fg_tid); + if (target_tid) AttachThreadInput(GetCurrentThreadId(), target_tid, TRUE); + if (fg_tid && fg_tid != target_tid) + AttachThreadInput(GetCurrentThreadId(), fg_tid, TRUE); + + SetForegroundWindow(hwnd); + SetActiveWindow(hwnd); + Sleep(settle_ms); + + if (fg_tid && fg_tid != target_tid) + AttachThreadInput(GetCurrentThreadId(), fg_tid, FALSE); + if (target_tid) AttachThreadInput(GetCurrentThreadId(), target_tid, FALSE); + + if (foreground_is(hwnd)) { + printf(" AttachThreadInput+SetForegroundWindow: foreground\n"); + return 0; + } + if (g_verbose) print_foreground("after AttachThreadInput"); + + /* Attempt 3, opt-in only: convince the game it is active. Kept behind a + * flag because wine's input routing does not follow it, so a title can end + * up taking mouse but not keys -- a half fix that looks like progress. */ + if (force_messages) { + printf(" --force-messages: SendMessage WM_ACTIVATE/WM_SETFOCUS\n"); + SendMessageA(hwnd, WM_ACTIVATE, WA_ACTIVE, 0); + SendMessageA(hwnd, WM_SETFOCUS, 0, 0); + Sleep(settle_ms); + printf(" messages sent (wine foreground unchanged by design)\n"); + return 0; + } + + print_foreground("refused"); + return 1; +} + +static void usage(const char *argv0) +{ + fprintf(stderr, + "usage: %s [options] [image.exe ...]\n" + " --timeout-ms N wait for the window (default 120000)\n" + " --settle-ms N wait after an activation attempt before\n" + " reading the foreground back (default 300)\n" + " --force-messages fall back to SendMessage WM_ACTIVATE if\n" + " SetForegroundWindow is refused\n" + " --desktop NAME join this wine desktop first (default shell)\n" + " --list print visible windows and exit\n" + " --verbose per-attempt detail\n", + argv0); +} + +int main(int argc, char **argv) +{ + DWORD timeout_ms = 120000, settle_ms = 300; + int force_messages = 0, list = 0; + const char *desktop = "shell"; + DWORD start; + + for (int i = 1; i < argc; i++) { + const char *a = argv[i]; + if (!strcmp(a, "--timeout-ms") && i + 1 < argc) { + timeout_ms = (DWORD)strtoul(argv[++i], NULL, 10); + } else if (!strcmp(a, "--settle-ms") && i + 1 < argc) { + settle_ms = (DWORD)strtoul(argv[++i], NULL, 10); + } else if (!strcmp(a, "--force-messages")) { + force_messages = 1; + } else if (!strcmp(a, "--desktop") && i + 1 < argc) { + desktop = argv[++i]; + } else if (!strcmp(a, "--list")) { + list = 1; + } else if (!strcmp(a, "--verbose")) { + g_verbose = 1; + } else if (a[0] == '-') { + fprintf(stderr, "%s: unknown option '%s'\n", argv[0], a); + usage(argv[0]); + return 3; + } else if (g_ntargets < MAX_TARGETS) { + snprintf(g_targets[g_ntargets].image, + sizeof(g_targets[g_ntargets].image), "%s", a); + lower(g_targets[g_ntargets].image); + g_ntargets++; + } else { + fprintf(stderr, "%s: too many targets\n", argv[0]); + return 3; + } + } + + /* Windows live on a desktop, and explorer's /desktop=shell put the game on a + * desktop of that name. A fresh wine process starts on the default desktop + * and sees nothing at all, so join the named one before enumerating. This + * must happen before any window is created on this thread. */ + if (desktop && strcmp(desktop, "none") != 0) { + HDESK hdesk = OpenDesktopA(desktop, 0, FALSE, GENERIC_ALL); + if (hdesk) { + if (SetThreadDesktop(hdesk)) + printf("gn-activate: joined desktop '%s'\n", desktop); + else + printf("gn-activate: SetThreadDesktop('%s') failed (%lu)\n", + desktop, (unsigned long)GetLastError()); + } else { + printf("gn-activate: OpenDesktop('%s') failed (%lu), staying put\n", + desktop, (unsigned long)GetLastError()); + } + } + + if (list) { + printf("-- visible windows --\n"); + scan_all(1, NULL); + return 0; + } + if (g_ntargets == 0) { + usage(argv[0]); + return 3; + } + + printf("gn-activate: waiting for"); + for (int i = 0; i < g_ntargets; i++) printf(" %s", g_targets[i].image); + printf(" (timeout %lums)\n", (unsigned long)timeout_ms); + fflush(stdout); + + start = GetTickCount(); + for (;;) { + struct candidate c; + memset(&c, 0, sizeof(c)); + scan_all(0, &c); + + if (c.hwnd) { + printf("gn-activate: window 0x%08lx %s pid=%lu %ldx%ld class=%s\n", + (unsigned long)(ULONG_PTR)c.hwnd, c.image, + (unsigned long)c.pid, c.rect.right - c.rect.left, + c.rect.bottom - c.rect.top, c.cls); + return activate(c.hwnd, (int)settle_ms, force_messages); + } + + /* GetTickCount wraps every ~49 days; the subtraction stays right. */ + if (GetTickCount() - start >= timeout_ms) { + printf("gn-activate: no window after %lums\n", + (unsigned long)timeout_ms); + return 2; + } + Sleep(POLL_MS); + } +} diff --git a/tools/xtree-probe.c b/tools/xtree-probe.c index 1fef79e..691f8cd 100644 --- a/tools/xtree-probe.c +++ b/tools/xtree-probe.c @@ -188,6 +188,11 @@ static void usage(const char *argv0) { fprintf(stderr, "usage: %s [-display ] [socket-path] [target-xid-hex]\n" + " [-focus] [-raise]\n" + " -focus / -raise : act on the target xid, then read the state back\n" + " one second later. gamescope recomputes focus and\n" + " stacking on the next window event, so the read-back\n" + " says whether the compositor kept the change.\n" " -display : display selector; a bare `:N` uses\n" " $GAMESCOPE_X11_DISPLAY then $DISPLAY (the session\n" " socket is env-provided on Android). An absolute\n" @@ -201,6 +206,8 @@ int main(int argc, char **argv) const char *display = NULL; xcb_window_t target = 0; int have_target = 0; + int do_focus = 0; + int do_raise = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-display") || !strcmp(argv[i], "--display")) { @@ -209,6 +216,10 @@ int main(int argc, char **argv) return 1; } display = argv[i]; + } else if (!strcmp(argv[i], "-focus") || !strcmp(argv[i], "--focus")) { + do_focus = 1; + } else if (!strcmp(argv[i], "-raise") || !strcmp(argv[i], "--raise")) { + do_raise = 1; } else if (argv[i][0] == '-' && argv[i][1] != '\0') { fprintf(stderr, "%s: unknown option '%s'\n", argv[0], argv[i]); usage(argv[0]); @@ -315,6 +326,63 @@ int main(int argc, char **argv) } } + if (target && (do_focus || do_raise)) { + printf("--- action on 0x%08x ---\n", target); + if (do_raise) { + uint32_t above = XCB_STACK_MODE_ABOVE; + xcb_configure_window(c, target, XCB_CONFIG_WINDOW_STACK_MODE, &above); + xcb_flush(c); + printf(" raise: XCB_STACK_MODE_ABOVE sent\n"); + } + if (do_focus) { + xcb_set_input_focus(c, XCB_INPUT_FOCUS_POINTER_ROOT, target, + XCB_CURRENT_TIME); + xcb_flush(c); + printf(" focus: XSetInputFocus(0x%08x) sent\n", target); + } + + /* The server applies a focus or stacking change immediately, but + * gamescope recomputes both on the next window event. Waiting a second + * is what separates "the X server refused it" from "the compositor + * took it back" -- the two causes look identical in an instant + * read-back. */ + struct timespec settle = { 1, 0 }; + nanosleep(&settle, NULL); + + xcb_get_input_focus_cookie_t fc = xcb_get_input_focus(c); + xcb_get_input_focus_reply_t *fr = xcb_get_input_focus_reply(c, fc, NULL); + if (fr) { + printf(" after 1s: X input focus=0x%08x%s\n", fr->focus, + fr->focus == target ? " (kept)" : " (reverted)"); + free(fr); + } + + /* X stacks a parent's children bottom-to-top, so the last entry is what + * the server would composite last among the siblings. The list has to + * come from the *parent*, not from the target, whose child list says + * nothing about stacking. */ + xcb_query_tree_cookie_t tc = xcb_query_tree(c, target); + xcb_query_tree_reply_t *tr = xcb_query_tree_reply(c, tc, NULL); + xcb_window_t parent = tr ? tr->parent : XCB_NONE; + if (tr) free(tr); + xcb_query_tree_cookie_t qc = xcb_query_tree(c, parent); + xcb_query_tree_reply_t *qr = xcb_query_tree_reply(c, qc, NULL); + if (qr) { + xcb_window_t *kids = xcb_query_tree_children(qr); + int n = xcb_query_tree_children_length(qr); + printf(" after 1s: siblings under 0x%08x, bottom -> top:\n", parent); + for (int i = 0; i < n; i++) { + xcb_get_window_attributes_cookie_t ac = xcb_get_window_attributes(c, kids[i]); + xcb_get_window_attributes_reply_t *a = xcb_get_window_attributes_reply(c, ac, NULL); + printf(" %s0x%08x%s\n", kids[i] == target ? "=> " : " ", kids[i], + a && a->override_redirect ? " override" : ""); + if (a) free(a); + print_name_class(c, kids[i]); + } + free(qr); + } + } + xcb_disconnect(c); return 0; } From ba26430ed75ca91b75489b71be02910325de4636 Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:27:24 +0800 Subject: [PATCH 2/5] tools: watch for the guest's window instead of firing once The app spawns this as a session helper, not per title: it knows only the launcher at session start (winhandler.exe "steam.exe"), and the game's window exists minutes later. One activation at session start would fire on steam and exit before there was anything to activate. So --watch polls and activates each eligible window once, when it first appears, which is A48's map-time semantics without its failure mode: a window already acted on is never retried, so a refused activation cannot turn into a focus fight with whatever the user is doing. With no image argument the target is chosen by rule, because no name is known yet: the largest visible window that is not wine's desktop window (class "#32769", DESKTOP_CLASS_ATOM in programs/explorer/desktop.c), not ours, and not already activated. The desktop exclusion is by class, which is exact rather than a guess; the size rule then picks a title's window over a launcher's splash without a deny-list of application names. join_desktop now waits for the desktop to exist instead of failing once. A helper spawned by the app arrives before `explorer /desktop=shell` has created it, and the failure is silent: a process on the default desktop enumerates no windows at all, so the tool would sit there looking idle. Waiting is the only correct answer, and the watcher exits by itself when the desktop disappears, so it ends with its session instead of lingering as an orphan. Both real tests of this shape were on-device: NFS Most Wanted under `explorer /desktop=shell,1280x720` (window 0x0001008a, class CgsGameWindowClass), where SetForegroundWindow was accepted on the first call and held. --- tools/gn-activate/gn-activate.c | 189 +++++++++++++++++++++++++++----- 1 file changed, 164 insertions(+), 25 deletions(-) diff --git a/tools/gn-activate/gn-activate.c b/tools/gn-activate/gn-activate.c index a52e388..3a31234 100644 --- a/tools/gn-activate/gn-activate.c +++ b/tools/gn-activate/gn-activate.c @@ -25,6 +25,11 @@ * gn-activate.exe --timeout-ms 180000 --verbose NFS13.exe * gn-activate.exe --list # every visible window * + * --watch keep polling for the whole session and activate each + * eligible window once, when it first appears. This is the + * shipping shape: the session starts a launcher, and the + * game's window exists only minutes later. + * --watch-ms N poll interval in watch mode (default 400) * --timeout-ms N how long to wait for the window (default 120000) * --settle-ms N wait after each activation attempt before reading the * foreground back (default 300) @@ -43,6 +48,16 @@ * * --desktop none stay on whatever desktop is current * + * With no image argument the target is chosen by rule, because at session start + * only the launcher is known: + * + * the largest visible window that is not wine's desktop window (class + * "#32769", DESKTOP_CLASS_ATOM), not ours, and not already activated. + * + * That needs no image name and no class deny-list. A title's own window is the + * largest thing on the desktop; the desktop window itself is excluded by its + * class, which is exact rather than a guess. + * * Exit codes: 0 activated (or already foreground), 1 refused, 2 no window in * time, 3 bad usage. * @@ -61,9 +76,16 @@ #include #define MAX_TARGETS 8 +#define MAX_SEEN 128 #define POLL_MS 100 +#define DESKTOP_WAIT_MS 180000 + +/* wine's desktop window class: DESKTOP_CLASS_ATOM in programs/explorer/desktop.c */ +#define DESKTOP_CLASS "#32769" static int g_verbose = 0; +static int g_any = 0; /* no image argument: match by rule */ +static DWORD g_own_pid; struct target { char image[64]; /* lower-cased basename, e.g. "nfs13.exe" */ @@ -121,6 +143,7 @@ static void image_of(HWND hwnd, DWORD *pid_out, char *image, size_t image_len) static int matches_target(const char *image) { + if (g_any) return 1; for (int i = 0; i < g_ntargets; i++) if (image[0] && strcmp(image, g_targets[i].image) == 0) return 1; return 0; @@ -142,10 +165,48 @@ static long area(const RECT *r) return (w > 0 && h > 0) ? w * h : 0; } +/* wine's desktop window is identifiable exactly, by class, so excluding it is + * not a guess about sizes or titles. */ +static int is_desktop_window(HWND hwnd) +{ + char cls[64]; + cls[0] = '\0'; + GetClassNameA(hwnd, cls, sizeof(cls)); + return strcmp(cls, DESKTOP_CLASS) == 0; +} + +/* An eligible window: visible, real area, not the desktop, not our own. */ +static int eligible(const struct candidate *c) +{ + if (!c->hwnd || area(&c->rect) <= 0) return 0; + if (c->pid == g_own_pid) return 0; + if (!matches_target(c->image)) return 0; + return !is_desktop_window(c->hwnd); +} + +/* Windows already activated. In watch mode a window is acted on once: a refused + * activation must not be retried every poll, or the watcher becomes a focus + * fight with whatever the user is doing. */ +static HWND g_seen[MAX_SEEN]; +static int g_nseen = 0; + +static int already_seen(HWND hwnd) +{ + for (int i = 0; i < g_nseen; i++) + if (g_seen[i] == hwnd) return 1; + return 0; +} + +static void mark_seen(HWND hwnd) +{ + if (g_nseen < MAX_SEEN) g_seen[g_nseen++] = hwnd; +} + struct scan { struct candidate best; int found; int list; + int skip_seen; }; static BOOL CALLBACK scan_proc(HWND hwnd, LPARAM lp) @@ -167,7 +228,7 @@ static BOOL CALLBACK scan_proc(HWND hwnd, LPARAM lp) /* The game's window is a child of the desktop window, so a top-level match * is a bonus, not the common case; scan children on every top-level too. */ - if (matches_target(c.image) && area(&c.rect) > 0) { + if (eligible(&c) && !(s->skip_seen && already_seen(hwnd))) { if (!s->found || area(&c.rect) > area(&s->best.rect)) { s->best = c; s->found = 1; @@ -193,7 +254,7 @@ static BOOL CALLBACK child_scan_proc(HWND hwnd, LPARAM lp) return TRUE; } - if (matches_target(c.image) && area(&c.rect) > 0) { + if (eligible(&c) && !(s->skip_seen && already_seen(hwnd))) { if (!s->found || area(&c.rect) > area(&s->best.rect)) { s->best = c; s->found = 1; @@ -212,16 +273,59 @@ static BOOL CALLBACK tops_for_children(HWND hwnd, LPARAM lp) /* One pass over top-levels, then one over their children. Both passes matter: * a top-level game window is the rare case, a nested one is ours. */ -static void scan_all(int list, struct candidate *out) +static void scan_all(int list, int skip_seen, struct candidate *out) { struct scan s; memset(&s, 0, sizeof(s)); s.list = list; + s.skip_seen = skip_seen; EnumWindows(scan_proc, (LPARAM)&s); EnumWindows(tops_for_children, (LPARAM)&s); - if (out && s.found) *out = s.best; + if (out) { + if (s.found) *out = s.best; + else memset(out, 0, sizeof(*out)); + } +} + +/* Join a named wine desktop, waiting for it to exist. + * + * `explorer /desktop=shell` creates it at session start, so a helper spawned by + * the app can arrive before it exists. Failing here would leave the process on + * the default desktop, where EnumWindows returns nothing at all -- a silent + * no-op -- so waiting is the only correct answer. Returns 1 on success. */ +static int join_desktop(const char *name, DWORD wait_ms) +{ + DWORD start = GetTickCount(); + for (;;) { + HDESK hdesk = OpenDesktopA(name, 0, FALSE, GENERIC_ALL); + if (hdesk) { + if (SetThreadDesktop(hdesk)) { + printf("gn-activate: joined desktop '%s'\n", name); + return 1; + } + printf("gn-activate: SetThreadDesktop('%s') failed (%lu)\n", + name, (unsigned long)GetLastError()); + return 0; + } + if (GetTickCount() - start >= wait_ms) { + printf("gn-activate: OpenDesktop('%s') timed out (%lu)\n", + name, (unsigned long)GetLastError()); + return 0; + } + Sleep(POLL_MS * 2); + } +} + +/* Whether the desktop still exists, so a watcher ends with its session instead + * of lingering as an orphan after the game and desktop are gone. */ +static int desktop_alive(const char *name) +{ + HDESK hdesk = OpenDesktopA(name, 0, FALSE, DESKTOP_READOBJECTS); + if (!hdesk) return 0; + CloseDesktop(hdesk); + return 1; } static int foreground_is(HWND hwnd) @@ -314,7 +418,10 @@ static void usage(const char *argv0) " reading the foreground back (default 300)\n" " --force-messages fall back to SendMessage WM_ACTIVATE if\n" " SetForegroundWindow is refused\n" - " --desktop NAME join this wine desktop first (default shell)\n" + " --watch activate each eligible window once, as it appears\n" + " --watch-ms N poll interval in watch mode (default 400)\n" + " --desktop NAME join this wine desktop first (default shell;\n" + " 'none' stays put)\n" " --list print visible windows and exit\n" " --verbose per-attempt detail\n", argv0); @@ -322,14 +429,24 @@ static void usage(const char *argv0) int main(int argc, char **argv) { - DWORD timeout_ms = 120000, settle_ms = 300; - int force_messages = 0, list = 0; + DWORD timeout_ms = 120000, settle_ms = 300, watch_ms = 400; + int force_messages = 0, list = 0, watch = 0; const char *desktop = "shell"; DWORD start; + g_own_pid = GetCurrentProcessId(); + for (int i = 1; i < argc; i++) { const char *a = argv[i]; - if (!strcmp(a, "--timeout-ms") && i + 1 < argc) { + if (!strcmp(a, "--watch")) { + watch = 1; + } else if (!strcmp(a, "--watch-ms") && i + 1 < argc) { + watch_ms = (DWORD)strtoul(argv[++i], NULL, 10); + /* A poll faster than this is a busy loop on a window list that only + * changes on map/unmap; slower than a game's launch gap and the + * activation lands after the title has already drawn itself idle. */ + if (watch_ms < 50) watch_ms = 50; + } else if (!strcmp(a, "--timeout-ms") && i + 1 < argc) { timeout_ms = (DWORD)strtoul(argv[++i], NULL, 10); } else if (!strcmp(a, "--settle-ms") && i + 1 < argc) { settle_ms = (DWORD)strtoul(argv[++i], NULL, 10); @@ -356,29 +473,51 @@ int main(int argc, char **argv) } } + /* No image argument means "whatever the session puts in front of us": by + * rule, since at session start only the launcher's name is known. */ + g_any = (g_ntargets == 0); + + if (list) { + if (desktop && strcmp(desktop, "none") != 0) join_desktop(desktop, DESKTOP_WAIT_MS); + printf("-- visible windows --\n"); + scan_all(1, 0, NULL); + return 0; + } + /* Windows live on a desktop, and explorer's /desktop=shell put the game on a * desktop of that name. A fresh wine process starts on the default desktop * and sees nothing at all, so join the named one before enumerating. This * must happen before any window is created on this thread. */ - if (desktop && strcmp(desktop, "none") != 0) { - HDESK hdesk = OpenDesktopA(desktop, 0, FALSE, GENERIC_ALL); - if (hdesk) { - if (SetThreadDesktop(hdesk)) - printf("gn-activate: joined desktop '%s'\n", desktop); - else - printf("gn-activate: SetThreadDesktop('%s') failed (%lu)\n", - desktop, (unsigned long)GetLastError()); - } else { - printf("gn-activate: OpenDesktop('%s') failed (%lu), staying put\n", - desktop, (unsigned long)GetLastError()); + int joined = 0; + if (desktop && strcmp(desktop, "none") != 0) joined = join_desktop(desktop, DESKTOP_WAIT_MS); + + if (watch) { + printf("gn-activate: watching (poll %lums)%s\n", (unsigned long)watch_ms, + joined ? "" : ", not joined"); + fflush(stdout); + for (;;) { + struct candidate c; + scan_all(0, 1, &c); + if (c.hwnd) { + printf("gn-activate: window 0x%08lx %s pid=%lu %ldx%ld class=%s\n", + (unsigned long)(ULONG_PTR)c.hwnd, + c.image[0] ? c.image : "?", (unsigned long)c.pid, + c.rect.right - c.rect.left, c.rect.bottom - c.rect.top, + c.cls); + fflush(stdout); + /* Mark before acting, so a refused activation is not retried on + * every poll: that would be a focus fight, not a fix. */ + mark_seen(c.hwnd); + activate(c.hwnd, (int)settle_ms, force_messages); + } + if (joined && !desktop_alive(desktop)) { + printf("gn-activate: desktop '%s' gone, exiting\n", desktop); + return 0; + } + Sleep(watch_ms); } } - if (list) { - printf("-- visible windows --\n"); - scan_all(1, NULL); - return 0; - } if (g_ntargets == 0) { usage(argv[0]); return 3; @@ -393,7 +532,7 @@ int main(int argc, char **argv) for (;;) { struct candidate c; memset(&c, 0, sizeof(c)); - scan_all(0, &c); + scan_all(0, 0, &c); if (c.hwnd) { printf("gn-activate: window 0x%08lx %s pid=%lu %ldx%ld class=%s\n", From ebe0915fa86b55da7ab8681b48ea5f7423cc883f Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:29:51 +0800 Subject: [PATCH 3/5] tools: the X-level activation levers, measured against wine's foreground gn-activate works, so the question worth answering before shipping it is whether it has to exist at all: is any X-level request enough to make wine consider the guest's window active? If one were, the helper could be deleted and gamescope's xwm could do it in a few lines. Two candidates, both sent as ClientMessages rather than property writes, because a property is something the client has to poll and wine does not: bin/gn-xtree-probe -activate EWMH _NET_ACTIVE_WINDOW to the root, source indication 2 (pager, the caller a WM is least likely to second-guess) bin/gn-xtree-probe -take-focus ICCCM WM_TAKE_FOCUS to the window, then XSetInputFocus as the client's own answer gn-activate gains --query-fg: the only read-only way to ask what wine considers foreground. X input focus is not that answer, and any activation call would mask the thing being observed -- the earlier one-shot would have reported success either way. Measured on RP6, NFS Most Wanted, proton-11.0-2-arm64ec-10, real session, one window (X 0x02400001 / HWND 0x0001008a), one run per arm: lever X input focus wine foreground baseline, nothing 0x00600004 desk _NET_ACTIVE_WINDOW ClientMessage reverted to desk WM_TAKE_FOCUS + XSetInputFocus 0x02400001 kept Win32 SetForegroundWindow from inside unchanged 0x0001008a nfs13 So no X-level request moves wine's foreground, and gamescope's xwm does more than ignore the child: it actively returns focus to the desktop. The helper is justified rather than merely convenient. The baseline is worth recording on its own: wine's foreground was , not the desktop, while X focus sat on the desktop window. X focus is not weakly coupled to wine's foreground, it is unrelated to it. Scope limit: the target is an override-redirect child, and WM_TAKE_FOCUS is a protocol wine's WM answers only for windows it manages. The result therefore says X cannot activate a wine window in this arrangement, not that it never could; if the launch line ever stops using a virtual desktop, re-run this before trusting the conclusion. --- tools/gn-activate/gn-activate.c | 17 ++++++- tools/xtree-probe.c | 82 ++++++++++++++++++++++++++++++++- 2 files changed, 97 insertions(+), 2 deletions(-) diff --git a/tools/gn-activate/gn-activate.c b/tools/gn-activate/gn-activate.c index 3a31234..6100128 100644 --- a/tools/gn-activate/gn-activate.c +++ b/tools/gn-activate/gn-activate.c @@ -43,6 +43,11 @@ * Without this the process sits on wine's default desktop * and EnumWindows returns nothing, because windows belong * to a desktop and the game's belong to explorer's. + * --query-fg print wine's foreground window and exit, changing + * nothing. The only read-only way to ask whether wine + * considers a window active: X input focus is not that + * answer (measured), and any activation call would mask + * what we are trying to observe. * --list print the visible windows and exit (no activation) * --verbose per-attempt detail * @@ -422,6 +427,7 @@ static void usage(const char *argv0) " --watch-ms N poll interval in watch mode (default 400)\n" " --desktop NAME join this wine desktop first (default shell;\n" " 'none' stays put)\n" + " --query-fg print wine's foreground window and exit\n" " --list print visible windows and exit\n" " --verbose per-attempt detail\n", argv0); @@ -430,7 +436,7 @@ static void usage(const char *argv0) int main(int argc, char **argv) { DWORD timeout_ms = 120000, settle_ms = 300, watch_ms = 400; - int force_messages = 0, list = 0, watch = 0; + int force_messages = 0, list = 0, watch = 0, query_fg = 0; const char *desktop = "shell"; DWORD start; @@ -454,6 +460,8 @@ int main(int argc, char **argv) force_messages = 1; } else if (!strcmp(a, "--desktop") && i + 1 < argc) { desktop = argv[++i]; + } else if (!strcmp(a, "--query-fg")) { + query_fg = 1; } else if (!strcmp(a, "--list")) { list = 1; } else if (!strcmp(a, "--verbose")) { @@ -477,6 +485,13 @@ int main(int argc, char **argv) * rule, since at session start only the launcher's name is known. */ g_any = (g_ntargets == 0); + if (query_fg) { + if (desktop && strcmp(desktop, "none") != 0) join_desktop(desktop, DESKTOP_WAIT_MS); + printf("foreground: "); + print_foreground("wine"); + return 0; + } + if (list) { if (desktop && strcmp(desktop, "none") != 0) join_desktop(desktop, DESKTOP_WAIT_MS); printf("-- visible windows --\n"); diff --git a/tools/xtree-probe.c b/tools/xtree-probe.c index 691f8cd..0d4df7f 100644 --- a/tools/xtree-probe.c +++ b/tools/xtree-probe.c @@ -184,12 +184,78 @@ static void dump_tree(xcb_connection_t *c, xcb_window_t w, int depth, int *budge } } +/* The two X-level ways to ask someone to activate a window, both sent as + * ClientMessages rather than as property writes: + * + * - _NET_ACTIVE_WINDOW to the root is EWMH's "please activate this". A window + * manager that implements it raises and focuses the window; wine's own WM + * implements some EWMH, so whether it acts on the message is a question and + * not an assumption. Source indication 2 (pager) is used because pagers are + * the callers a WM is least likely to second-guess. + * - WM_TAKE_FOCUS direct to the window is the ICCCM mechanism: a WM sends it + * instead of setting the input focus, and the client answers by calling + * XSetInputFocus itself. Wine advertises WM_TAKE_FOCUS for its managed + * windows, and this also sets the focus so the two paths can be told apart. + * + * Neither raises WM_ACTIVATE by itself. The point of the experiment is whether + * wine converts either into its own foreground state, which is what the game + * actually reacts to -- X input focus alone was measured not to. */ +static xcb_atom_t intern(xcb_connection_t *c, const char *name) +{ + xcb_intern_atom_cookie_t ck = xcb_intern_atom(c, 1, (uint16_t)strlen(name), name); + xcb_intern_atom_reply_t *r = xcb_intern_atom_reply(c, ck, NULL); + xcb_atom_t atom = r ? r->atom : XCB_NONE; + if (r) free(r); + return atom; +} + +static void send_net_active_window(xcb_connection_t *c, xcb_window_t root, + xcb_window_t w) +{ + xcb_atom_t atom = intern(c, "_NET_ACTIVE_WINDOW"); + if (!atom) { printf(" activate: _NET_ACTIVE_WINDOW not interned\n"); return; } + xcb_client_message_event_t ev; + memset(&ev, 0, sizeof(ev)); + ev.response_type = XCB_CLIENT_MESSAGE; + ev.format = 32; + ev.window = w; + ev.type = atom; + ev.data.data32[0] = 2; /* source indication: pager */ + ev.data.data32[1] = XCB_CURRENT_TIME; + ev.data.data32[2] = XCB_NONE; /* currently active window */ + xcb_send_event(c, 0, root, + XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY, + (const char *)&ev); + xcb_flush(c); + printf(" activate: _NET_ACTIVE_WINDOW ClientMessage -> root, for 0x%08x\n", w); +} + +static void send_take_focus(xcb_connection_t *c, xcb_window_t w) +{ + xcb_atom_t protocols = intern(c, "WM_PROTOCOLS"); + xcb_atom_t take_focus = intern(c, "WM_TAKE_FOCUS"); + if (!protocols || !take_focus) { printf(" take-focus: atoms not interned\n"); return; } + xcb_client_message_event_t ev; + memset(&ev, 0, sizeof(ev)); + ev.response_type = XCB_CLIENT_MESSAGE; + ev.format = 32; + ev.window = w; + ev.type = protocols; + ev.data.data32[0] = take_focus; + ev.data.data32[1] = XCB_CURRENT_TIME; + xcb_send_event(c, 0, w, XCB_EVENT_MASK_NO_EVENT, (const char *)&ev); + xcb_flush(c); + printf(" take-focus: WM_TAKE_FOCUS ClientMessage -> 0x%08x\n", w); +} + static void usage(const char *argv0) { fprintf(stderr, "usage: %s [-display ] [socket-path] [target-xid-hex]\n" " [-focus] [-raise]\n" " -focus / -raise : act on the target xid, then read the state back\n" + " -activate : send EWMH _NET_ACTIVE_WINDOW ClientMessage for it\n" + " -take-focus : send ICCCM WM_TAKE_FOCUS, then set X input focus\n" " one second later. gamescope recomputes focus and\n" " stacking on the next window event, so the read-back\n" " says whether the compositor kept the change.\n" @@ -208,6 +274,8 @@ int main(int argc, char **argv) int have_target = 0; int do_focus = 0; int do_raise = 0; + int do_activate = 0; + int do_take_focus = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-display") || !strcmp(argv[i], "--display")) { @@ -220,6 +288,10 @@ int main(int argc, char **argv) do_focus = 1; } else if (!strcmp(argv[i], "-raise") || !strcmp(argv[i], "--raise")) { do_raise = 1; + } else if (!strcmp(argv[i], "-activate") || !strcmp(argv[i], "--activate")) { + do_activate = 1; + } else if (!strcmp(argv[i], "-take-focus") || !strcmp(argv[i], "--take-focus")) { + do_take_focus = 1; } else if (argv[i][0] == '-' && argv[i][1] != '\0') { fprintf(stderr, "%s: unknown option '%s'\n", argv[0], argv[i]); usage(argv[0]); @@ -326,7 +398,7 @@ int main(int argc, char **argv) } } - if (target && (do_focus || do_raise)) { + if (target && (do_focus || do_raise || do_activate || do_take_focus)) { printf("--- action on 0x%08x ---\n", target); if (do_raise) { uint32_t above = XCB_STACK_MODE_ABOVE; @@ -340,6 +412,14 @@ int main(int argc, char **argv) xcb_flush(c); printf(" focus: XSetInputFocus(0x%08x) sent\n", target); } + if (do_activate) send_net_active_window(c, screen->root, target); + if (do_take_focus) { + send_take_focus(c, target); + /* the ICCCM client's own answer to WM_TAKE_FOCUS */ + xcb_set_input_focus(c, XCB_INPUT_FOCUS_POINTER_ROOT, target, + XCB_CURRENT_TIME); + xcb_flush(c); + } /* The server applies a focus or stacking change immediately, but * gamescope recomputes both on the next window event. Waiting a second From 02c69498436ee2073be13bc7b7c696f9d68992bb Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:12:40 +0800 Subject: [PATCH 4/5] tools: watch for the guest's window, and record what X focus does not fix -watch-activate waits for the session's X socket and then for the guest's window, and needs no xid: the app has none at launch, and the ids are reallocated per session (0x02400001 became 0x02600001 between two runs of the same title). The window is chosen by depth, not by class. Under `explorer /desktop=shell` the desktop is the root child everything lives inside, and its WM_CLASS on the X side is `explorer.exe` (measured) -- not DESKTOP_CLASS_ATOM, which is a Win32-side fact -- so a class test matches nothing and the desktop wins on area. Only depth >= 2 can be a guest window, and among those a descendant must be strictly larger than its ancestor to replace it: the outer window and its inner child can share an area exactly, and the outer one is the meaningful target. Measured on RP6, NFS Most Wanted, with only this in play: connect(.../X0): No such file or directory x4 (socket not up yet) xtree-probe: connected ...; watching for the guest's window window 0x02400017 (921600 px): attempting X-level activation activate: _NET_ACTIVE_WINDOW ClientMessage -> root, for 0x02400017 take-focus: WM_TAKE_FOCUS ClientMessage -> 0x02400017 after 1s: X input focus=0x02400017 (kept) and, with the focus moved to the game's own window instead: focus: XSetInputFocus(0x02600001); after 1s: X input focus=0x02600001 (kept) Neither makes the title's START button work: X focus is kept by the server and the game still ignores injected input, because wine's foreground window is what input delivery follows and it stays . That is the measurement this tool exists to reproduce -- and the reason a Win32 call inside the prefix is still required, which is what gn-activate.exe is for. Note the retry loop is deliberate and not an error path: the app arms this at session start, before gamescope's X socket exists, and the four failed connects above are that window being waited for. --- tools/xtree-probe.c | 99 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/tools/xtree-probe.c b/tools/xtree-probe.c index 0d4df7f..e4076f1 100644 --- a/tools/xtree-probe.c +++ b/tools/xtree-probe.c @@ -248,12 +248,57 @@ static void send_take_focus(xcb_connection_t *c, xcb_window_t w) printf(" take-focus: WM_TAKE_FOCUS ClientMessage -> 0x%08x\n", w); } +/* Largest mapped window below the root's direct children. + * + * Depth >= 2, not a class test: under `explorer /desktop=shell` the desktop is + * the root child everything lives inside, and its WM_CLASS on the X side is + * `explorer.exe` (measured), not the DESKTOP_CLASS_ATOM the Win32 side reports -- + * so a class check matches nothing and the desktop wins on area. The guest's own + * window is the largest thing inside it. + */ +static xcb_window_t find_guest_window_rec(xcb_connection_t *c, xcb_window_t w, + int depth, long *best) +{ + xcb_window_t best_w = XCB_NONE; + if (depth > 12) return best_w; + xcb_query_tree_cookie_t qc = xcb_query_tree(c, w); + xcb_query_tree_reply_t *qr = xcb_query_tree_reply(c, qc, NULL); + if (!qr) return best_w; + int n = xcb_query_tree_children_length(qr); + xcb_window_t *kids = xcb_query_tree_children(qr); + for (int i = 0; i < n; i++) { + xcb_get_window_attributes_cookie_t ac = xcb_get_window_attributes(c, kids[i]); + xcb_get_window_attributes_reply_t *a = xcb_get_window_attributes_reply(c, ac, NULL); + xcb_get_geometry_cookie_t gc = xcb_get_geometry(c, kids[i]); + xcb_get_geometry_reply_t *g = xcb_get_geometry_reply(c, gc, NULL); + int mapped = a && a->map_state == XCB_MAP_STATE_VIEWABLE; + if (a) free(a); + if (g) { + long area = (long)g->width * (long)g->height; + if (mapped && area > 0 && depth >= 2 && area > *best) { *best = area; best_w = kids[i]; } + free(g); + } + /* A descendant only wins if it is strictly larger: the guest's outer + * window and its inner child can have identical area, and the outer one + * is the one that should be activated (measured: the inner child 0x02200017 + * was picked over 0x02400001 before this check). */ + long before = *best; + xcb_window_t deeper = find_guest_window_rec(c, kids[i], depth + 1, best); + if (deeper != XCB_NONE && *best > before) best_w = deeper; + } + free(qr); + return best_w; +} + static void usage(const char *argv0) { fprintf(stderr, "usage: %s [-display ] [socket-path] [target-xid-hex]\n" " [-focus] [-raise]\n" " -focus / -raise : act on the target xid, then read the state back\n" + " -watch-activate : wait for the guest's window (no xid needed), then\n" + " attempt X-level activation on it and report back\n" + " -watch-ms N how long to wait for that window (default 600000)\n" " -activate : send EWMH _NET_ACTIVE_WINDOW ClientMessage for it\n" " -take-focus : send ICCCM WM_TAKE_FOCUS, then set X input focus\n" " one second later. gamescope recomputes focus and\n" @@ -276,6 +321,8 @@ int main(int argc, char **argv) int do_raise = 0; int do_activate = 0; int do_take_focus = 0; + int do_watch = 0; + int watch_ms = 600000; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "-display") || !strcmp(argv[i], "--display")) { @@ -292,6 +339,10 @@ int main(int argc, char **argv) do_activate = 1; } else if (!strcmp(argv[i], "-take-focus") || !strcmp(argv[i], "--take-focus")) { do_take_focus = 1; + } else if (!strcmp(argv[i], "-watch-activate") || !strcmp(argv[i], "--watch-activate")) { + do_watch = 1; + } else if (!strcmp(argv[i], "-watch-ms") && i + 1 < argc) { + watch_ms = atoi(argv[++i]); } else if (argv[i][0] == '-' && argv[i][1] != '\0') { fprintf(stderr, "%s: unknown option '%s'\n", argv[0], argv[i]); usage(argv[0]); @@ -326,7 +377,18 @@ int main(int argc, char **argv) display, path); int scr = 0; - xcb_connection_t *c = connect_path(path, &scr); + xcb_connection_t *c = NULL; + if (do_watch) { + /* The app arms this at session start, which can precede gamescope's X + * socket. Waiting is the job: socket first, then the window. */ + int waited = 0; + while (!c && waited < watch_ms) { + c = connect_path(path, &scr); + if (!c) { struct timespec ts = { 0, 250000000 }; nanosleep(&ts, NULL); waited += 250; } + } + } else { + c = connect_path(path, &scr); + } if (!c) return 1; const xcb_setup_t *setup = xcb_get_setup(c); @@ -349,6 +411,41 @@ int main(int argc, char **argv) printf(" Present present=%u opcode=%u\n", er ? er->present : 0, er ? er->major_opcode : 0); if (er) free(er); + if (do_watch) { + printf("xtree-probe: watching for the guest's window (timeout %dms)\n", watch_ms); + fflush(stdout); + int waited = 0; + while (waited < watch_ms) { + long best = 0; + xcb_window_t w = find_guest_window_rec(c, screen->root, 0, &best); + if (w != XCB_NONE) { + printf(" window 0x%08x (%ld px): attempting X-level activation\n", w, best); + send_net_active_window(c, screen->root, w); + send_take_focus(c, w); + xcb_set_input_focus(c, XCB_INPUT_FOCUS_POINTER_ROOT, w, XCB_CURRENT_TIME); + xcb_flush(c); + struct timespec settle = { 1, 0 }; + nanosleep(&settle, NULL); + xcb_get_input_focus_cookie_t fc = xcb_get_input_focus(c); + xcb_get_input_focus_reply_t *fr = xcb_get_input_focus_reply(c, fc, NULL); + if (fr) { + printf(" after 1s: X input focus=0x%08x%s\n", fr->focus, + fr->focus == w ? " (kept)" : " (reverted)"); + free(fr); + } + /* Wine's own foreground is the only state that matters and it is + * not readable from here -- measured: both messages left it at + * while SetForegroundWindow moved it. */ + return 0; + } + struct timespec ts = { 0, 400000000 }; + nanosleep(&ts, NULL); + waited += 400; + } + printf("xtree-probe: no guest window after %dms\n", watch_ms); + return 2; + } + printf("--- tree (depth-first from root) ---\n"); int budget = 500; dump_tree(c, screen->root, 0, &budget); From c77095f22ecba46202739127f9dd7df2dde5ac26 Mon Sep 17 00:00:00 2001 From: Joshua Tam <297250+joshuatam@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:28:44 +0800 Subject: [PATCH 5/5] tools: end the watcher when it has nothing left to do --watch only ended when the desktop disappeared, and that never happens while a launcher owns the session: the launch line is `winhandler.exe "steam.exe"`, so exiting the title leaves the desktop and Steam alive and the helper polled every 400ms for the rest of the session, doing nothing. --idle-ms (default 60000, 0 disables) ends it instead: the clock starts at arm time and restarts whenever a window worth acting on is found, so the launcher sequence this exists for -- Steam's window, then the game minutes later -- is unaffected, and the process exits about a minute after the last thing it could act on is gone. The desktop-disappeared exit stays for the session-over case. Sixty seconds is a judgement, not a measurement: a title that shows no window for longer than that between launcher and game would lose its activation for that session, which is why the value is a flag rather than a constant. --- tools/gn-activate/gn-activate.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/tools/gn-activate/gn-activate.c b/tools/gn-activate/gn-activate.c index 6100128..bccfa46 100644 --- a/tools/gn-activate/gn-activate.c +++ b/tools/gn-activate/gn-activate.c @@ -30,6 +30,8 @@ * shipping shape: the session starts a launcher, and the * game's window exists only minutes later. * --watch-ms N poll interval in watch mode (default 400) + * --idle-ms N exit after this long with no window left to activate + * (default 60000); 0 disables the idle exit * --timeout-ms N how long to wait for the window (default 120000) * --settle-ms N wait after each activation attempt before reading the * foreground back (default 300) @@ -63,6 +65,12 @@ * largest thing on the desktop; the desktop window itself is excluded by its * class, which is exact rather than a guess. * + * Watch mode ends on its own two ways: the desktop disappears (session over), or + * nothing has been left to activate for --idle-ms. The second matters because a + * launcher session outlives its game -- `winhandler.exe "steam.exe"` keeps the + * desktop and Steam alive after the title exits -- so without it the helper would + * poll for the rest of the session doing nothing. + * * Exit codes: 0 activated (or already foreground), 1 refused, 2 no window in * time, 3 bad usage. * @@ -425,6 +433,8 @@ static void usage(const char *argv0) " SetForegroundWindow is refused\n" " --watch activate each eligible window once, as it appears\n" " --watch-ms N poll interval in watch mode (default 400)\n" + " --idle-ms N exit after N ms with no window to activate\n" + " (default 60000; 0 disables)\n" " --desktop NAME join this wine desktop first (default shell;\n" " 'none' stays put)\n" " --query-fg print wine's foreground window and exit\n" @@ -435,7 +445,7 @@ static void usage(const char *argv0) int main(int argc, char **argv) { - DWORD timeout_ms = 120000, settle_ms = 300, watch_ms = 400; + DWORD timeout_ms = 120000, settle_ms = 300, watch_ms = 400, idle_ms = 60000; int force_messages = 0, list = 0, watch = 0, query_fg = 0; const char *desktop = "shell"; DWORD start; @@ -452,6 +462,8 @@ int main(int argc, char **argv) * changes on map/unmap; slower than a game's launch gap and the * activation lands after the title has already drawn itself idle. */ if (watch_ms < 50) watch_ms = 50; + } else if (!strcmp(a, "--idle-ms") && i + 1 < argc) { + idle_ms = (DWORD)strtoul(argv[++i], NULL, 10); } else if (!strcmp(a, "--timeout-ms") && i + 1 < argc) { timeout_ms = (DWORD)strtoul(argv[++i], NULL, 10); } else if (!strcmp(a, "--settle-ms") && i + 1 < argc) { @@ -507,9 +519,11 @@ int main(int argc, char **argv) if (desktop && strcmp(desktop, "none") != 0) joined = join_desktop(desktop, DESKTOP_WAIT_MS); if (watch) { - printf("gn-activate: watching (poll %lums)%s\n", (unsigned long)watch_ms, + printf("gn-activate: watching (poll %lums, idle exit %lums)%s\n", + (unsigned long)watch_ms, (unsigned long)idle_ms, joined ? "" : ", not joined"); fflush(stdout); + DWORD idle_start = GetTickCount(); for (;;) { struct candidate c; scan_all(0, 1, &c); @@ -524,6 +538,12 @@ int main(int argc, char **argv) * every poll: that would be a focus fight, not a fix. */ mark_seen(c.hwnd); activate(c.hwnd, (int)settle_ms, force_messages); + /* any window worth acting on restarts the idle clock */ + idle_start = GetTickCount(); + } else if (idle_ms != 0 && GetTickCount() - idle_start >= idle_ms) { + printf("gn-activate: nothing to activate for %lums, exiting\n", + (unsigned long)idle_ms); + return 0; } if (joined && !desktop_alive(desktop)) { printf("gn-activate: desktop '%s' gone, exiting\n", desktop);