From 505a8598b16df82c45a4025ba050deee68ca5daf Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 4 Oct 2026 17:01:29 -0300 Subject: [PATCH] Hopefully fix ctrl W for desktop apps --- deno.json | 2 +- desktop/main.ts | 2 + desktop/shortcuts.ts | 49 ++++++++++++++ desktop/shortcuts_windows.ts | 65 +++++++++++++++++++ desktop/shortcuts_x11.ts | 121 +++++++++++++++++++++++++++++++++++ 5 files changed, 238 insertions(+), 1 deletion(-) create mode 100644 desktop/shortcuts.ts create mode 100644 desktop/shortcuts_windows.ts create mode 100644 desktop/shortcuts_x11.ts diff --git a/deno.json b/deno.json index f93fb57..c1d914b 100644 --- a/deno.json +++ b/deno.json @@ -7,7 +7,7 @@ "check-mods": "deno run --allow-read --allow-run tools/check_mods.ts", "pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts", "test": "deno test --allow-read --allow-write --allow-run tests/", - "desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld" + "desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld" }, "compilerOptions": { "lib": ["dom", "dom.asynciterable", "dom.iterable", "deno.ns", "deno.unstable", "deno.webgpu"] diff --git a/desktop/main.ts b/desktop/main.ts index 6639510..0f91100 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -7,6 +7,7 @@ import { fromFileUrl, join } from "@std/path"; import { type Host, serve_static, start_host } from "../server/host.ts"; import { PROTOCOL_VERSION } from "../common/protocol.ts"; import { current_client, update_client } from "./client_updates.ts"; +import { guard_shortcuts } from "./shortcuts.ts"; // where the project was built from: build/ and server_mods/ (the .bmod files) are bundled into the app with --include const ROOT = fromFileUrl(new URL("../", import.meta.url)); @@ -38,6 +39,7 @@ const client_dir: Promise = updates_from === "off" || updates_from === " client_dir.then((dir) => console.log(`Playing the client in ${dir}`)); const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 }); +guard_shortcuts(win); // the singleplayer game server, started the first time singleplayer connects so players who only join other servers // don't get a world made for them. it plays the .bmod files the app was built with diff --git a/desktop/shortcuts.ts b/desktop/shortcuts.ts new file mode 100644 index 0000000..e32fde0 --- /dev/null +++ b/desktop/shortcuts.ts @@ -0,0 +1,49 @@ +// chromium's reserved shortcuts, like ctrl+w closing the window, happen before the page can stop them. sprinting is +// ctrl and walking is w, so the app takes those keys from the os before chromium sees them and hands them to the page. +// how depends on the os, see shortcuts_x11.ts and shortcuts_windows.ts. macs close with cmd+w, which isn't a game key +import { guard_shortcuts_x11 } from "./shortcuts_x11.ts"; +import { guard_shortcuts_windows } from "./shortcuts_windows.ts"; + +// the keys taken with ctrl and with ctrl+shift: their X11 key symbols, windows virtual keys, and how they reach the page +export const KEYS: { keysym: number; vk: number; code: string; key: string; shifted_key: string }[] = [ + // close the window, ctrl+shift+w too + { keysym: 0x77, vk: 0x57, code: "KeyW", key: "w", shifted_key: "W" }, + // new tab, reopen a closed one + { keysym: 0x74, vk: 0x54, code: "KeyT", key: "t", shifted_key: "T" }, + // new window + { keysym: 0x6e, vk: 0x4e, code: "KeyN", key: "n", shifted_key: "N" }, + // ctrl+shift+q quits on linux + { keysym: 0x71, vk: 0x51, code: "KeyQ", key: "q", shifted_key: "Q" }, + // switching tabs + { keysym: 0xff09, vk: 0x09, code: "Tab", key: "Tab", shifted_key: "Tab" }, + { keysym: 0xff55, vk: 0x21, code: "PageUp", key: "PageUp", shifted_key: "PageUp" }, + { keysym: 0xff56, vk: 0x22, code: "PageDown", key: "PageDown", shifted_key: "PageDown" }, + // ctrl+f4 closes the tab on windows + { keysym: 0xffc1, vk: 0x73, code: "F4", key: "F4", shifted_key: "F4" }, +]; + +export type Key = typeof KEYS[number]; + +export function guard_shortcuts(win: Deno.BrowserWindow) { + switch (Deno.build.os) { + case "linux": + guard_shortcuts_x11(win); + break; + case "windows": + guard_shortcuts_windows(win); + break; + } +} + +// to the page as if chromium had sent it, see client/input_manager.ts +export function send_key(win: Deno.BrowserWindow, type: "keydown" | "keyup", key: Key, ctrl: boolean, shift: boolean) { + const init = { + code: key.code, + key: shift ? key.shifted_key : key.key, + ctrlKey: ctrl, + shiftKey: shift, + bubbles: true, + cancelable: true, + }; + win.executeJs(`dispatchEvent(new KeyboardEvent(${JSON.stringify(type)}, ${JSON.stringify(init)}))`).catch(() => {}); +} diff --git a/desktop/shortcuts_windows.ts b/desktop/shortcuts_windows.ts new file mode 100644 index 0000000..32fd1a4 --- /dev/null +++ b/desktop/shortcuts_windows.ts @@ -0,0 +1,65 @@ +// on windows the app takes chromium's reserved shortcuts (see shortcuts.ts) as hotkeys, through user32. a hotkey takes +// the key press before any window gets it, its release still reaches chromium. hotkeys are for the whole system, so +// they're only registered while the app's window has focus. holding the key repeats the hotkey +import { KEYS, send_key } from "./shortcuts.ts"; + +const MOD_CONTROL = 0x2; +const MOD_SHIFT = 0x4; +const WM_HOTKEY = 0x0312; +const PM_REMOVE = 0x1; +// MSG on 64 bit windows: hwnd, then the message, wParam (the hotkey's id) and lParam (its modifiers and virtual key) +const MSG_SIZE = 48; +const MSG_MESSAGE = 8; +const MSG_LPARAM = 24; +// how often it looks for hotkeys, in milliseconds +const POLL_MS = 4; + +const USER32 = { + RegisterHotKey: { parameters: ["pointer", "i32", "u32", "u32"], result: "i32" }, + UnregisterHotKey: { parameters: ["pointer", "i32"], result: "i32" }, + PeekMessageW: { parameters: ["buffer", "pointer", "u32", "u32", "u32"], result: "i32" }, +} as const; + +export function guard_shortcuts_windows(win: Deno.BrowserWindow) { + let lib: Deno.DynamicLibrary; + try { + lib = Deno.dlopen("user32.dll", USER32); + } catch (e) { + console.error(`Not guarding shortcuts, no user32: ${(e as Error).message}`); + return; + } + const user32 = lib.symbols; + + // every key with ctrl and with ctrl+shift, by their ids. without a window, WM_HOTKEY goes to this thread's queue + const hotkeys = KEYS.flatMap((key) => + [MOD_CONTROL, MOD_CONTROL | MOD_SHIFT].map((modifiers) => ({ key, modifiers })) + ); + let registered = false; + const register = () => { + if (registered) return; + // one already taken by another app just isn't guarded + hotkeys.forEach(({ key, modifiers }, id) => user32.RegisterHotKey(null, id + 1, modifiers, key.vk)); + registered = true; + }; + const unregister = () => { + if (!registered) return; + hotkeys.forEach((_, id) => user32.UnregisterHotKey(null, id + 1)); + registered = false; + }; + win.addEventListener("focus", register); + win.addEventListener("blur", unregister); + win.addEventListener("close", unregister); + + const msg = new Uint8Array(MSG_SIZE); + const view = new DataView(msg.buffer); + setInterval(() => { + while (user32.PeekMessageW(msg, null, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) { + if (view.getUint32(MSG_MESSAGE, true) !== WM_HOTKEY) continue; + const lparam = view.getUint32(MSG_LPARAM, true); + const modifiers = lparam & 0xffff; + const vk = lparam >>> 16; + const key = KEYS.find((k) => k.vk === vk); + if (key) send_key(win, "keydown", key, (modifiers & MOD_CONTROL) !== 0, (modifiers & MOD_SHIFT) !== 0); + } + }, POLL_MS); +} diff --git a/desktop/shortcuts_x11.ts b/desktop/shortcuts_x11.ts new file mode 100644 index 0000000..50c44e3 --- /dev/null +++ b/desktop/shortcuts_x11.ts @@ -0,0 +1,121 @@ +// on linux the app takes chromium's reserved shortcuts (see shortcuts.ts) from the x server itself, with a passive grab +// on its window through libX11. deno desktop's chromium always runs on x11, see linux_launcher.ts. a grabbed key goes +// to the grabbing client until it's let go, so the grab is dropped right away and the key's release and everything +// after it reaches chromium as usual. holding it repeats the press, which is grabbed again each time +import { type Key, KEYS, send_key } from "./shortcuts.ts"; + +const SHIFT_MASK = 1 << 0; +const LOCK_MASK = 1 << 1; +const CONTROL_MASK = 1 << 2; +// num lock on most setups. a grab only matches the exact modifiers, so every lock combination gets one +const MOD2_MASK = 1 << 4; +const KEY_PRESS = 2; +const KEY_RELEASE = 3; +const GRAB_MODE_ASYNC = 1; +const CURRENT_TIME = 0n; +// XEvent is a union of 24 longs +const EVENT_SIZE = 24 * 8; +// XKeyEvent's fields on 64 bit systems +const EVENT_STATE = 80; +const EVENT_KEYCODE = 84; +// how often it looks for grabbed keys, in milliseconds +const POLL_MS = 4; + +const X11 = { + XOpenDisplay: { parameters: ["pointer"], result: "pointer" }, + XSetErrorHandler: { parameters: ["function"], result: "pointer" }, + XKeysymToKeycode: { parameters: ["pointer", "u64"], result: "u8" }, + XGetInputFocus: { parameters: ["pointer", "buffer", "buffer"], result: "i32" }, + XQueryTree: { parameters: ["pointer", "u64", "buffer", "buffer", "buffer", "buffer"], result: "i32" }, + XFree: { parameters: ["pointer"], result: "i32" }, + XGrabKey: { parameters: ["pointer", "i32", "u32", "u64", "i32", "i32", "i32"], result: "i32" }, + XUngrabKeyboard: { parameters: ["pointer", "u64"], result: "i32" }, + XPending: { parameters: ["pointer"], result: "i32" }, + XNextEvent: { parameters: ["pointer", "buffer"], result: "i32" }, + XFlush: { parameters: ["pointer"], result: "i32" }, + XSync: { parameters: ["pointer", "i32"], result: "i32" }, +} as const; + +// grabs the shortcuts on the window once it has focus, which is when x11 can tell which window is the app's. nothing +// happens without libX11 +export function guard_shortcuts_x11(win: Deno.BrowserWindow) { + let lib: Deno.DynamicLibrary; + try { + lib = Deno.dlopen("libX11.so.6", X11); + } catch (e) { + console.error(`Not guarding shortcuts, no libX11: ${(e as Error).message}`); + return; + } + const x = lib.symbols; + const display = x.XOpenDisplay(null); + if (!display) { + console.error("Not guarding shortcuts, no X display"); + return; + } + // xlib's own handler exits the process, like when another app already grabbed one of the keys + const on_error = new Deno.UnsafeCallback({ parameters: ["pointer", "pointer"], result: "i32" }, () => 0); + x.XSetErrorHandler(on_error.pointer); + + const by_keycode = new Map(); + for (const key of KEYS) { + const keycode = x.XKeysymToKeycode(display, BigInt(key.keysym)); + if (keycode) by_keycode.set(keycode, key); + } + + let grabbed = false; + win.addEventListener("focus", () => { + if (grabbed) return; + const window = top_level(x, display); + if (!window) return; + for (const keycode of by_keycode.keys()) { + for (const shift of [0, SHIFT_MASK]) { + for (const locks of [0, LOCK_MASK, MOD2_MASK, LOCK_MASK | MOD2_MASK]) { + const modifiers = CONTROL_MASK | shift | locks; + x.XGrabKey(display, keycode, modifiers, window, 0, GRAB_MODE_ASYNC, GRAB_MODE_ASYNC); + } + } + } + x.XSync(display, 0); + grabbed = true; + }); + + const event = new Uint8Array(EVENT_SIZE); + const view = new DataView(event.buffer); + setInterval(() => { + while (x.XPending(display) > 0) { + x.XNextEvent(display, event); + const type = view.getInt32(0, true); + if (type !== KEY_PRESS && type !== KEY_RELEASE) continue; + if (type === KEY_PRESS) { + x.XUngrabKeyboard(display, CURRENT_TIME); + x.XFlush(display); + } + const key = by_keycode.get(view.getUint32(EVENT_KEYCODE, true)); + const state = view.getUint32(EVENT_STATE, true); + if (key) { + const ctrl = (state & CONTROL_MASK) !== 0; + send_key(win, type === KEY_PRESS ? "keydown" : "keyup", key, ctrl, (state & SHIFT_MASK) !== 0); + } + } + }, POLL_MS); +} + +// the window that has focus, up to the one right under the root, which is the app's own window and not one of +// chromium's inside it +function top_level(x: Deno.DynamicLibrary["symbols"], display: Deno.PointerObject): bigint | undefined { + const focus = new BigUint64Array(1); + x.XGetInputFocus(display, focus, new Int32Array(1)); + let window = focus[0]; + // None and PointerRoot + if (window <= 1n) return undefined; + const root = new BigUint64Array(1); + const parent = new BigUint64Array(1); + const children = new BigUint64Array(1); + const count = new Uint32Array(1); + while (true) { + if (!x.XQueryTree(display, window, root, parent, children, count)) return undefined; + if (children[0]) x.XFree(Deno.UnsafePointer.create(children[0])); + if (parent[0] === root[0]) return window; + window = parent[0]; + } +}