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..bccfa46 --- /dev/null +++ b/tools/gn-activate/gn-activate.c @@ -0,0 +1,588 @@ +/* + * 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 + * + * --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) + * --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) + * --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. + * --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 + * + * --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. + * + * 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. + * + * 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 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" */ +}; + +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) +{ + 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; +} + +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; +} + +/* 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) +{ + 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 (eligible(&c) && !(s->skip_seen && already_seen(hwnd))) { + 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 (eligible(&c) && !(s->skip_seen && already_seen(hwnd))) { + 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, 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) { + 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) +{ + 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" + " --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" + " --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, watch_ms = 400, idle_ms = 60000; + int force_messages = 0, list = 0, watch = 0, query_fg = 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, "--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, "--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) { + 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, "--query-fg")) { + query_fg = 1; + } 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; + } + } + + /* 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 (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"); + 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. */ + int joined = 0; + if (desktop && strcmp(desktop, "none") != 0) joined = join_desktop(desktop, DESKTOP_WAIT_MS); + + if (watch) { + 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); + 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); + /* 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); + return 0; + } + Sleep(watch_ms); + } + } + + 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, 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..e4076f1 100644 --- a/tools/xtree-probe.c +++ b/tools/xtree-probe.c @@ -184,10 +184,126 @@ 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); +} + +/* 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" + " 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 +317,12 @@ 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; + 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")) { @@ -209,6 +331,18 @@ 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 (!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 (!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]); @@ -243,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); @@ -266,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); @@ -315,6 +495,71 @@ int main(int argc, char **argv) } } + 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; + 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); + } + 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 + * 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; }