// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the page's keys and mouse for InputManager, and grabbing the mouse with the browser's pointer lock import { InputManager } from "./input_manager.ts"; // the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium // can keep alt+tab and the windows key from the os too const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"]; // chromium's keyboard lock api, typescript's dom types don't have it yet interface KeyboardLock { lock(codes?: string[]): Promise; unlock(): void; } let canvas: HTMLCanvasElement; let pointer_lock_flag = false; let mouse_ungrab_timer = 0; let mouse_ungrab_timeout = -1; let pointer_lock_waiting = false; // chrome sometimes sends a huge movement with the first mouse event after the lock starts let skip_look_event = false; // the browser let go of the mouse while the game wanted it, like escape or switching windows let lost_pointer_lock = false; // the canvas had the pointer lock at the last pointerlockchange let was_locked = false; // the desktop app moving the cursor after the mouse was let go, see center_desktop_mouse. grabbing it again waits // for that, or the move would come while it's locked and turn the camera let centering = Promise.resolve(); let awaiting_centering = false; // the locked mouse doesn't turn the camera until then, the move can still reach chromium after the app answered, // or the mouse was locked again before chromium said it let go let ignore_look_until = 0; // what the game last asked for, it can change while grabbing waits let want_grab = false; export function listen_to_page(page_canvas: HTMLCanvasElement) { canvas = page_canvas; self.addEventListener("keydown", (e) => { e.preventDefault(); e.stopPropagation(); InputManager.key_down(e.code, e.key, is_shortcut(e)); }); self.addEventListener("blur", () => InputManager.release_all()); self.addEventListener("keyup", (e) => { e.preventDefault(); e.stopPropagation(); InputManager.key_up(e.code); }); self.addEventListener("mousedown", (e) => { e.preventDefault(); e.stopPropagation(); if (!document.hasFocus() && document.pointerLockElement !== canvas) { set_mouse_grabbed(true); return; } InputManager.mouse_down(e.button); }); self.addEventListener("mouseup", (e) => { e.preventDefault(); InputManager.mouse_up(e.button); }); // ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that // isn't passive can stop it, and on the window they're passive unless told otherwise self.addEventListener("wheel", (e) => { if (e.ctrlKey) { e.preventDefault(); } InputManager.scroll(e.deltaY); }, { passive: false }); document.addEventListener("mousemove", (e) => { e.preventDefault(); if (document.pointerLockElement === canvas) { if (skip_look_event) { skip_look_event = false; return; } if (performance.now() < ignore_look_until) return; InputManager.look(e.movementX, e.movementY); } else { const rect = canvas.getBoundingClientRect(); InputManager.move_cursor(e.clientX - rect.left, e.clientY - rect.top); } }); document.addEventListener("pointerlockchange", () => { const locked = document.pointerLockElement === canvas; if (was_locked && !locked) { ignore_look_until = Infinity; centering = center_desktop_mouse().then(() => { ignore_look_until = performance.now() + CENTERING_SETTLE_MS; }); } was_locked = locked; skip_look_event = locked; self.setTimeout(() => { const grab = document.pointerLockElement === canvas; if (!grab) { if (pointer_lock_flag) { mouse_ungrab_timer = performance.now(); lost_pointer_lock = true; } } pointer_lock_flag = grab; }, 60); pointer_lock_waiting = false; }); // in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w, // instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before document.addEventListener("fullscreenchange", () => { const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard; if (!keyboard?.lock) return; if (document.fullscreenElement) { keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {}); } else { keyboard.unlock(); } }); document.addEventListener("pointerlockerror", () => { pointer_lock_waiting = false; }); } // ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it // isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl function is_shortcut(e: KeyboardEvent) { return e.metaKey || (e.ctrlKey && !e.altKey); } export async function set_mouse_grabbed(grab: boolean) { pointer_lock_flag = grab; want_grab = grab; // a retry to grab it again mustn't happen once it shouldn't be grabbed if (!grab && mouse_ungrab_timeout !== -1) { self.clearTimeout(mouse_ungrab_timeout); mouse_ungrab_timeout = -1; } // already how it should be, the game calls this every frame const locked = document.pointerLockElement === canvas; if (grab ? locked : !locked && !pointer_lock_waiting) { return; } if (grab) { // called every frame, once is enough if (awaiting_centering) return; awaiting_centering = true; await centering; awaiting_centering = false; // a gui opened again meanwhile if (!want_grab || document.pointerLockElement === canvas) return; } const t = performance.now(); if (grab) { InputManager.mouse_x = -1; InputManager.mouse_y = -1; pointer_lock_waiting = true; try { await canvas.requestPointerLock(); } catch (_) { /* */ } if (mouse_ungrab_timeout !== -1) { self.clearTimeout(mouse_ungrab_timeout); } mouse_ungrab_timeout = -1; if (t - mouse_ungrab_timer < 3000) { mouse_ungrab_timeout = self.setTimeout(async () => { try { await canvas.requestPointerLock(); } catch (_) { /* */ } }, 3100 - (t - mouse_ungrab_timer)); } } else { if (!pointer_lock_waiting) { document.exitPointerLock(); } } } // whether the browser took the mouse away since the last call, it eats the escape that does it export function take_lost_pointer_lock() { const lost = lost_pointer_lock; lost_pointer_lock = false; return lost; } export function is_mouse_grabbed() { return document.hasFocus() && document.pointerLockElement === canvas; } export function toggle_fullscreen() { if (!document.fullscreenElement) { canvas.requestFullscreen(); } else { document.exitFullscreen(); } } const CENTERING_TIMEOUT_MS = 250; const CENTERING_SETTLE_MS = 100; // the desktop app (the page has ?singleplayer there, see desktop/main.ts) moves the cursor to the middle of the // window when the mouse is let go to open a gui, like minecraft. chromium would put it back where it was grabbed. // resolves once the cursor was moved, or after CENTERING_TIMEOUT_MS if the app is slow, so grabbing isn't held up function center_desktop_mouse(): Promise { if (!new URL(location.href).searchParams.has("singleplayer")) return Promise.resolve(); const moved = fetch("/desktop/center_mouse", { method: "POST" }).then(() => {}, () => {}); return Promise.race([moved, new Promise((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]); }