Drop deno desktop

This commit is contained in:
2026-11-22 18:34:18 -03:00
parent 0d770c7bc4
commit 25937f2c31
15 changed files with 147 additions and 801 deletions
+2 -2
View File
@@ -3,7 +3,7 @@
// what the desktop app serves its client from: the client's files (updated from the site, see client_updates.ts),
// and singleplayer, whose worlds are played on a game server of the app's own with the mods each world picked from
// its data folder (see saves.ts). the client is shown by main.ts in chromium, or by native.ts in a window of its own
// its data folder (see saves.ts). main.ts shows the client in the app's window
import { fromFileUrl, join } from "@std/path";
import { serve_static } from "../server/host.ts";
import { PROTOCOL_VERSION } from "../common/protocol.ts";
@@ -11,7 +11,7 @@ import { current_client, update_client } from "./client_updates.ts";
import { data_dir, install_mods } from "./saves.ts";
import { singleplayer_server } from "./singleplayer.ts";
// where the project was built from: build/ and server_mods/ (the .cubi files) are bundled into the app with --include
// where the project was built from, with what deno task build made in build/ and server_mods/ (the .cubi files)
const ROOT = fromFileUrl(new URL("../", import.meta.url));
const BUILD_DIR = join(ROOT, "build");
-117
View File
@@ -1,117 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// when the game lets go of the mouse to open a gui, chromium puts the cursor back where it was grabbed. like minecraft
// it goes to the middle of the window instead, moved there by the os: libX11 on linux, user32 on windows. the page
// asks for it, see desktop/main.ts and client/input_manager.ts. nothing happens without the library or on macs
const X11 = {
XOpenDisplay: { parameters: ["pointer"], result: "pointer" },
XSetErrorHandler: { parameters: ["function"], result: "pointer" },
XGetInputFocus: { parameters: ["pointer", "buffer", "buffer"], result: "i32" },
XGetGeometry: {
parameters: ["pointer", "u64", "buffer", "buffer", "buffer", "buffer", "buffer", "buffer", "buffer"],
result: "i32",
},
XWarpPointer: { parameters: ["pointer", "u64", "u64", "i32", "i32", "u32", "u32", "i32", "i32"], result: "i32" },
XSync: { parameters: ["pointer", "i32"], result: "i32" },
} as const;
const USER32 = {
GetForegroundWindow: { parameters: [], result: "pointer" },
GetWindowThreadProcessId: { parameters: ["pointer", "buffer"], result: "u32" },
GetClientRect: { parameters: ["pointer", "buffer"], result: "i32" },
ClientToScreen: { parameters: ["pointer", "buffer"], result: "i32" },
SetCursorPos: { parameters: ["i32", "i32"], result: "i32" },
} as const;
// moves the cursor to the middle of the app's window, if it's the one in front. set up on the first call
export function center_mouse() {
center ??= setup();
center();
}
let center: (() => void) | undefined;
function setup(): () => void {
switch (Deno.build.os) {
case "linux":
return setup_x11();
case "windows":
return setup_windows();
default:
return () => {};
}
}
function setup_x11(): () => void {
let lib: Deno.DynamicLibrary<typeof X11>;
try {
lib = Deno.dlopen("libX11.so.6", X11);
} catch (e) {
console.error(`Not centering the mouse, no libX11: ${(e as Error).message}`);
return () => {};
}
const x = lib.symbols;
const display = x.XOpenDisplay(null);
if (!display) {
console.error("Not centering the mouse, no X display");
return () => {};
}
// xlib's own handler exits the process, like when the window went away
const on_error = new Deno.UnsafeCallback({ parameters: ["pointer", "pointer"], result: "i32" }, () => 0);
x.XSetErrorHandler(on_error.pointer);
const focus = new BigUint64Array(1);
const revert_to = new Int32Array(1);
const root = new BigUint64Array(1);
const [left, top] = [new Int32Array(1), new Int32Array(1)];
const [width, height, border, depth] = [
new Uint32Array(1),
new Uint32Array(1),
new Uint32Array(1),
new Uint32Array(1),
];
return () => {
// the window with focus, chromium's own inside the app's frame, which has it while the game is asking
x.XGetInputFocus(display, focus, revert_to);
const window = focus[0];
// None and PointerRoot
if (window <= 1n) return;
if (!x.XGetGeometry(display, window, root, left, top, width, height, border, depth)) return;
// from no particular window, to the middle of the app's
x.XWarpPointer(display, 0n, window, 0, 0, 0, 0, width[0] >> 1, height[0] >> 1);
// done before the page hears back, it grabs the mouse again only after that
x.XSync(display, 0);
};
}
function setup_windows(): () => void {
let lib: Deno.DynamicLibrary<typeof USER32>;
try {
lib = Deno.dlopen("user32.dll", USER32);
} catch (e) {
console.error(`Not centering the mouse, no user32: ${(e as Error).message}`);
return () => {};
}
const user32 = lib.symbols;
const owner = new Uint32Array(1);
// RECT: left, top, right, bottom
const rect = new Int32Array(4);
// POINT: x, y
const point = new Int32Array(2);
return () => {
// chromium's windows are this process's own, like in shortcuts_windows.ts
const window = user32.GetForegroundWindow();
if (!window) return;
owner[0] = 0;
user32.GetWindowThreadProcessId(window, owner);
if (owner[0] !== Deno.pid) return;
if (!user32.GetClientRect(window, rect)) return;
point[0] = (rect[0] + rect[2]) >> 1;
point[1] = (rect[1] + rect[3]) >> 1;
if (!user32.ClientToScreen(window, point)) return;
user32.SetCursorPos(point[0], point[1]);
};
}
-68
View File
@@ -1,68 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld
// deno desktop has no setting for chromium's command line, but its linux launcher passes its arguments on to chromium.
// so this moves the launcher to bworld-bin and puts a script in its place that starts it with the switches webgpu
// needs on some linux setups. run it on the app folder after deno desktop builds it; running it again does nothing
const SWITCHES = [
"--enable-features=UseOzonePlatform,Vulkan,VulkanFromANGLE",
// "--enable-unsafe-webgpu",
"--use-angle=vulkan",
"--ozone-platform=wayland",
"--enable-wayland-ime",
"--wayland-text-input-version=3",
];
if (import.meta.main) {
// on its own it's run after building for the os it's on, which only needs wrapping on linux
if (Deno.build.os !== "linux") {
Deno.exit(0);
}
const dir = Deno.args[0];
if (!dir) {
console.error("usage: linux_launcher.ts <app folder>, like dist/cubi");
Deno.exit(1);
}
wrap_linux_launcher(dir);
}
// wraps the launcher of a linux build in dir. it works from any os, see tools/desktop_all.ts, but the script is only
// made executable on unix: zipping it from windows has to set that itself
export function wrap_linux_launcher(dir: string) {
const name = dir.replace(/[\/\\]+$/, "").split(/[\/\\]/).pop()!;
const launcher = `${dir}/${name}`;
const binary = `${launcher}-bin`;
// already wrapped: the launcher is a script now
if (!is_elf(launcher)) {
console.log(`${launcher} is already wrapped`);
return;
}
Deno.renameSync(launcher, binary);
Deno.writeTextFileSync(
launcher,
`#!/bin/sh
# starts ${name} with the chromium switches webgpu needs on some linux setups, see desktop/linux_launcher.ts.
# CUBI_CHROMIUM_FLAGS replaces them, set it to "" to start without any
here="$(dirname "$(readlink -f "$0")")"
# the binary finds its runtime by its own name, which is ${name}.so and not ${name}-bin.so
export LAUFEY_RUNTIME_PATH="$here/${name}.so"
exec "$here/${name}-bin" \${CUBI_CHROMIUM_FLAGS-${SWITCHES.join(" ")}} "$@"
`,
);
if (Deno.build.os !== "windows") {
Deno.chmodSync(launcher, 0o755);
}
console.log(`Wrapped ${launcher}: ${SWITCHES.join(" ")}`);
}
export function is_elf(path: string) {
const head = new Uint8Array(4);
const file = Deno.openSync(path);
file.readSync(head);
file.close();
return head[0] === 0x7f && head[1] === 0x45 && head[2] === 0x4c && head[3] === 0x46;
}
+136 -32
View File
@@ -1,47 +1,151 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference lib="deno.desktop" />
// the desktop app: the web client in a bundled chromium (deno desktop's cef backend), so people whose browser has no
// webgpu (firefox) can still play. its title screen is a main menu like luanti's: singleplayer worlds are played on
// a game server of its own, with the mods each world picked from its data folder, see saves.ts. build it with deno
// task desktop, see the desktop/ docs for how deno desktop works
import { guard_shortcuts } from "./shortcuts.ts";
import { center_mouse } from "./center_mouse.ts";
// the desktop app: an sdl window (sdl.ts) that the client draws into with deno's own webgpu, so it plays without a
// browser. the client runs in a worker (client/native/main.ts) loaded from the client's files like a page, and this
// thread passes it the window's events and does what it asks, like grabbing the mouse or playing sounds (openal.ts).
// the client's files and singleplayer are served on a local address, see app.ts
import { join, toFileUrl } from "@std/path";
import { desktop_app } from "./app.ts";
import { SdlWindow } from "./sdl.ts";
import { OpenAl } from "./openal.ts";
import type { ClientMessage, WindowMessage } from "../client/native/messages.ts";
// how often the window's events are looked at, in milliseconds
const POLL_MS = 2;
// how often sounds are checked for having ended, in polls
const AUDIO_POLLS = 10;
const game_window = new SdlWindow("bworld", 1280, 720);
// the game plays without sound when there's no openal
let audio: OpenAl | undefined;
try {
audio = new OpenAl();
} catch (e) {
console.error(`No sound: ${(e as Error).message}`);
}
const app = desktop_app((message) => {
console.error(message);
alert(`The singleplayer world stopped: ${message}`);
game_window.show_error("bworld", `The singleplayer world stopped: ${message}`);
Deno.exit(1);
});
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
guard_shortcuts(win);
const server = Deno.serve(
{ hostname: "127.0.0.1", port: 0, onListen() {} },
(req) => app.handle(req, new URL(req.url)),
);
const start_page = app.start_page(`http://127.0.0.1:${server.addr.port}`);
// the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the
// last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway
win.addEventListener("close", async (event) => {
event.preventDefault();
await app.singleplayer.stop();
Deno.exit(0);
});
if (Deno.env.get("DEBUG")) {
win.openDevtools();
// what the client remembers, see Platform.storage
const STORAGE_FILE = join(app.data_dir, "client_storage.json");
let storage: Record<string, string> = {};
try {
storage = JSON.parse(Deno.readTextFileSync(STORAGE_FILE));
} catch {
// nothing saved yet
}
// deno desktop binds this to a private local address and opens the window on it, the port given here is ignored
Deno.serve(async (req) => {
const url = new URL(req.url);
if (url.pathname === "/") {
return Response.redirect(app.start_page(url.origin), 302);
let client: Worker | undefined;
let closing = false;
// a fresh client, like loading the page again. the old one is gone with everything it loaded
async function start_client(page: URL) {
client?.terminate();
game_window.set_grabbed(false);
audio?.reset();
const client_dir = await app.client_dir;
const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), {
type: "module",
deno: {
// the servers it plays on, and its own files. ffi is for drawing into the window, it gives it up after
permissions: { net: true, read: [client_dir], ffi: true, write: false, run: false, env: false, sys: false },
},
});
worker.onmessage = (event: MessageEvent<ClientMessage>) => handle(event.data);
worker.onerror = (event) => {
console.error(`The client stopped: ${event.message}`);
};
client = worker;
send({
type: "start",
page: page.href,
surface: game_window.surface_handles(),
...game_window.pixel_size(),
storage,
audio: audio !== undefined,
});
}
function send(message: WindowMessage) {
client?.postMessage(message);
}
function handle(message: ClientMessage) {
// what it asks while the app closes, like sounds, would come after openal and the window are gone
if (closing) return;
switch (message.type) {
case "grab":
game_window.set_grabbed(message.grab);
break;
case "fullscreen":
game_window.toggle_fullscreen();
break;
case "restart": {
const page = new URL(message.page);
// only its own pages
start_client(page.origin === start_page.origin ? page : start_page);
break;
}
// the client can't run at all, like without webgpu
case "fatal":
game_window.set_grabbed(false);
game_window.show_error("bworld", message.message);
close();
break;
case "ask":
game_window.set_grabbed(false);
send({
type: "answer",
id: message.id,
yes: game_window.ask(message.title, message.text, message.yes, message.no),
});
break;
case "read_clipboard":
send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() });
break;
case "write_clipboard":
game_window.write_clipboard(message.text);
break;
case "audio":
audio?.run(message.commands);
break;
case "store":
storage[message.key] = message.value;
Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t"));
break;
}
// the page let go of the mouse, see center_mouse.ts
if (url.pathname === "/desktop/center_mouse" && req.method === "POST") {
center_mouse();
return new Response(null, { status: 204 });
}
// the world gets saved before the app closes. the client isn't terminated first, exiting while a terminated worker is
// still letting go of its webgpu surface can crash deno, exiting stops it as well
async function close() {
if (closing) return;
closing = true;
clearInterval(polling);
await app.singleplayer.stop();
audio?.close();
game_window.close();
Deno.exit(0);
}
let polls = 0;
const polling = setInterval(() => {
game_window.poll(send, close);
if (audio && ++polls % AUDIO_POLLS === 0) {
const ended = audio.ended();
if (ended.length) send({ type: "audio_ended", sources: ended });
}
return await app.handle(req, url);
});
}, POLL_MS);
start_client(start_page);
-151
View File
@@ -1,151 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the desktop app without a browser: an sdl window (sdl.ts) that the client draws into with deno's own webgpu. the
// client runs in a worker (client/native/main.ts) loaded from the client's files like a page, and this thread passes
// it the window's events and does what it asks, like grabbing the mouse. the client's files and singleplayer are
// served on a local address like main.ts's chromium window has them, see app.ts
import { join, toFileUrl } from "@std/path";
import { desktop_app } from "./app.ts";
import { SdlWindow } from "./sdl.ts";
import { OpenAl } from "./openal.ts";
import type { ClientMessage, WindowMessage } from "../client/native/messages.ts";
// how often the window's events are looked at, in milliseconds
const POLL_MS = 2;
// how often sounds are checked for having ended, in polls
const AUDIO_POLLS = 10;
const game_window = new SdlWindow("bworld", 1280, 720);
// the game plays without sound when there's no openal
let audio: OpenAl | undefined;
try {
audio = new OpenAl();
} catch (e) {
console.error(`No sound: ${(e as Error).message}`);
}
const app = desktop_app((message) => {
console.error(message);
game_window.show_error("bworld", `The singleplayer world stopped: ${message}`);
Deno.exit(1);
});
const server = Deno.serve(
{ hostname: "127.0.0.1", port: 0, onListen() {} },
(req) => app.handle(req, new URL(req.url)),
);
const start_page = app.start_page(`http://127.0.0.1:${server.addr.port}`);
// what the client remembers, see Platform.storage
const STORAGE_FILE = join(app.data_dir, "client_storage.json");
let storage: Record<string, string> = {};
try {
storage = JSON.parse(Deno.readTextFileSync(STORAGE_FILE));
} catch {
// nothing saved yet
}
let client: Worker | undefined;
let closing = false;
// a fresh client, like loading the page again. the old one is gone with everything it loaded
async function start_client(page: URL) {
client?.terminate();
game_window.set_grabbed(false);
audio?.reset();
const client_dir = await app.client_dir;
const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), {
type: "module",
deno: {
// the servers it plays on, and its own files. ffi is for drawing into the window, it gives it up after
permissions: { net: true, read: [client_dir], ffi: true, write: false, run: false, env: false, sys: false },
},
});
worker.onmessage = (event: MessageEvent<ClientMessage>) => handle(event.data);
worker.onerror = (event) => {
console.error(`The client stopped: ${event.message}`);
};
client = worker;
send({
type: "start",
page: page.href,
surface: game_window.surface_handles(),
...game_window.pixel_size(),
storage,
audio: audio !== undefined,
});
}
function send(message: WindowMessage) {
client?.postMessage(message);
}
function handle(message: ClientMessage) {
// what it asks while the app closes, like sounds, would come after openal and the window are gone
if (closing) return;
switch (message.type) {
case "grab":
game_window.set_grabbed(message.grab);
break;
case "fullscreen":
game_window.toggle_fullscreen();
break;
case "restart": {
const page = new URL(message.page);
// only its own pages
start_client(page.origin === start_page.origin ? page : start_page);
break;
}
// the client can't run at all, like without webgpu
case "fatal":
game_window.set_grabbed(false);
game_window.show_error("bworld", message.message);
close();
break;
case "ask":
game_window.set_grabbed(false);
send({
type: "answer",
id: message.id,
yes: game_window.ask(message.title, message.text, message.yes, message.no),
});
break;
case "read_clipboard":
send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() });
break;
case "write_clipboard":
game_window.write_clipboard(message.text);
break;
case "audio":
audio?.run(message.commands);
break;
case "store":
storage[message.key] = message.value;
Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t"));
break;
}
}
// the world gets saved before the app closes. the client isn't terminated first, exiting while a terminated worker is
// still letting go of its webgpu surface can crash deno, exiting stops it as well
async function close() {
if (closing) return;
closing = true;
clearInterval(polling);
await app.singleplayer.stop();
audio?.close();
game_window.close();
Deno.exit(0);
}
let polls = 0;
const polling = setInterval(() => {
game_window.poll(send, close);
if (audio && ++polls % AUDIO_POLLS === 0) {
const ended = audio.ended();
if (ended.length) send({ type: "audio_ended", sources: ended });
}
}, POLL_MS);
start_client(start_page);
-52
View File
@@ -1,52 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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(() => {});
}
-81
View File
@@ -1,81 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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 is in front. 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 and which window is in front, 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" },
GetForegroundWindow: { parameters: [], result: "pointer" },
GetWindowThreadProcessId: { parameters: ["pointer", "buffer"], result: "u32" },
} as const;
export function guard_shortcuts_windows(win: Deno.BrowserWindow) {
let lib: Deno.DynamicLibrary<typeof USER32>;
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("close", unregister);
// the cef backend never sends focus or blur on windows, so it checks whether the window in front is the app's.
// chromium's windows are this process's own
const owner = new Uint32Array(1);
const in_front = () => {
const window = user32.GetForegroundWindow();
if (!window) return false;
owner[0] = 0;
user32.GetWindowThreadProcessId(window, owner);
return owner[0] === Deno.pid;
};
const msg = new Uint8Array(MSG_SIZE);
const view = new DataView(msg.buffer);
setInterval(() => {
if (in_front()) register();
else unregister();
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);
}
-124
View File
@@ -1,124 +0,0 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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<typeof X11>;
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<number, Key>();
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<typeof X11>["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];
}
}