/** * Cross-platform input event dispatcher and coordinator. * * Routes validated input messages to the appropriate platform-specific * injector, manages runtime configuration, applies input processing, * throttles high-frequency events, and provides a unified interface for * mouse, keyboard, touch, clipboard, and gesture interactions. */ import os from "node:os" import { applyMotion } from "./drivers/utils.ts" import { DEFAULT_SCREEN_HEIGHT, DEFAULT_SCREEN_WIDTH, MAX_TEXT_LENGTH, MAX_COMBO_KEYS, MAX_COORD, MAX_KEY_LENGTH, MAX_ZOOM_STEP, ZOOM_IDLE_RESET_MS, ZOOM_SCALE, } from "./constants.ts" import type { InputConfig, InputMessage, PlatformInjector } from "./types.ts" const VALID_BUTTONS = ["left", "right", "middle"] as const type MouseButton = (typeof VALID_BUTTONS)[number] export class InputHandler { private injector: PlatformInjector private platform: "win32" | "linux" | "darwin" | "other" private lastMoveTime = 0 private lastScrollTime = 0 private pendingMove: InputMessage | null = null private pendingScroll: InputMessage | null = null private moveTimer: ReturnType | null = null private scrollTimer: ReturnType | null = null private lastLsTime = 0 private lastRsTime = 0 private pendingLs: InputMessage | null = null private pendingRs: InputMessage | null = null private lsTimer: ReturnType | null = null private rsTimer: ReturnType | null = null private throttleMs: number private zoomRemainder = 0 private lastZoomTime = 0 private onError?: (errorType: string, message: string) => void private config: InputConfig = { sensitivity: 1.0, invertScroll: false, acceleration: true, screenWidth: DEFAULT_SCREEN_WIDTH, screenHeight: DEFAULT_SCREEN_HEIGHT, } constructor( config: Partial = {}, throttleMs = 8, onError?: (errorType: string, message: string) => void, ) { this.throttleMs = throttleMs this.config = { ...this.config, ...config } this.onError = onError const plat = os.platform() try { if (plat === "win32") { this.platform = "win32" const { WindowsInputInjector } = require("./drivers/windows") this.injector = new WindowsInputInjector( this.config, ) as PlatformInjector } else if (plat === "linux") { this.platform = "linux" const { LinuxInputInjector } = require("./drivers/linux") this.injector = new LinuxInputInjector(this.config) as PlatformInjector } else if (plat === "darwin") { this.platform = "darwin" const { MacInputInjector } = require("./drivers/mac") this.injector = new MacInputInjector(this.config) as PlatformInjector } else { this.platform = "other" const msg = `Unsupported platform: ${plat}` console.warn(`[InputHandler] ${msg}`) this.injector = createStubInjector() if (this.onError) { this.onError("unsupported-platform", msg) } } } catch (e) { this.injector = createStubInjector() this.platform = "other" const errMsg = `Input injector initialization failed: ${e instanceof Error ? e.message : String(e)}` console.warn(e) if (this.onError) { this.onError("Input Device Error", errMsg) } } } updateConfig(config: Partial): void { console.log("[InputHandler] Updating config:", config) this.config = { ...this.config, ...config } this.injector.updateConfig(config) clearInputInjectorProbeCache() } setThrottleMs(ms: number): void { this.throttleMs = ms } async handleMessage(msg: InputMessage): Promise { this.sanitizeMessage(msg) if (msg.type === "move" || msg.type === "scroll") { if (this.throttle(msg)) return } if (msg.type === "gamepad-axis") { if (this.throttleAxis(msg)) return } try { this.dispatch(msg) } catch (err: unknown) { const errMsg = err instanceof Error ? err.message : String(err) console.error(`[InputHandler] Error handling ${msg.type} event:`, errMsg) // Safety: release mouse button if a click-down throws if (msg.type === "click" && msg.press && isValidButton(msg.button)) { try { this.injector.injectMouseButton(msg.button, false) } catch (cleanupErr) { console.error( "[InputHandler] Cleanup after click failure:", cleanupErr, ) } } } } destroy(): void { this.injector.destroy() clearTimeout(this.moveTimer ?? undefined) clearTimeout(this.scrollTimer ?? undefined) clearTimeout(this.lsTimer ?? undefined) clearTimeout(this.rsTimer ?? undefined) this.moveTimer = null this.scrollTimer = null this.lsTimer = null this.rsTimer = null console.log("[InputHandler] Destroyed") } private sanitizeMessage(msg: InputMessage): void { if (typeof msg.text === "string" && msg.text.length > MAX_TEXT_LENGTH) { msg.text = msg.text.substring(0, MAX_TEXT_LENGTH) } msg.dx = clampFinite(msg.dx, -MAX_COORD, MAX_COORD) msg.dy = clampFinite(msg.dy, -MAX_COORD, MAX_COORD) msg.delta = clampFinite(msg.delta, -MAX_COORD, MAX_COORD) if (typeof msg.ax === "number" && Number.isFinite(msg.ax)) msg.ax = clampFinite(msg.ax, -1, 1) if (typeof msg.ay === "number" && Number.isFinite(msg.ay)) msg.ay = clampFinite(msg.ay, -1, 1) // Clamp normalised absolute coordinates to [0, 1] if (msg.type === "absoluteClick") { msg.x = clampFinite(msg.x, 0, 1) msg.y = clampFinite(msg.y, 0, 1) } } private throttle(msg: InputMessage): boolean { const now = Date.now() const isMove = msg.type === "move" const lastKey = isMove ? "lastMoveTime" : "lastScrollTime" const pendingKey = isMove ? "pendingMove" : "pendingScroll" const timerKey = isMove ? "moveTimer" : "scrollTimer" if (now - this[lastKey] < this.throttleMs) { // dx/dy are relative, so merge them; overwriting would lose motion (#452) const queued = this[pendingKey] this[pendingKey] = queued ? { ...msg, dx: (queued.dx ?? 0) + (msg.dx ?? 0), dy: (queued.dy ?? 0) + (msg.dy ?? 0), } : msg if (!this[timerKey]) { this[timerKey] = setTimeout(() => { this[timerKey] = null const pending = this[pendingKey] if (pending) { this[pendingKey] = null this.handleMessage(pending).catch((err) => console.error( `[InputHandler] Error flushing pending ${msg.type}:`, err, ), ) } }, this.throttleMs) } return true } this[lastKey] = now return false } private throttleAxis(msg: InputMessage): boolean { if ( msg.type !== "gamepad-axis" || (msg.axis !== "ls" && msg.axis !== "rs") ) { return false } const now = Date.now() const isLs = msg.axis === "ls" const lastKey = isLs ? "lastLsTime" : "lastRsTime" const pendingKey = isLs ? "pendingLs" : "pendingRs" const timerKey = isLs ? "lsTimer" : "rsTimer" // Neutral (0, 0) dispatches immediately and cancels pending timer if (msg.ax === 0 && msg.ay === 0) { if (this[timerKey]) { clearTimeout(this[timerKey]) this[timerKey] = null } this[pendingKey] = null this[lastKey] = now return false } if (now - this[lastKey] < this.throttleMs) { this[pendingKey] = msg if (!this[timerKey]) { this[timerKey] = setTimeout(() => { this[timerKey] = null const pending = this[pendingKey] if (pending) { this[pendingKey] = null this.handleMessage(pending).catch((err) => console.error( `[InputHandler] Error flushing pending gamepad-axis (${isLs ? "ls" : "rs"}):`, err, ), ) } }, this.throttleMs) } return true } this[lastKey] = now return false } /** * Convert a pinch delta (change in finger distance, in px) into whole * Ctrl+wheel steps, carrying the fractional remainder over to the next event. * * Without the carry, every event below the rounding threshold was dropped, so * a slow pinch never zoomed. The remainder is reset when the pinch changes * direction or after a pause, so a new gesture never starts from leftovers. * * @returns The wheel amount to inject (negative zooms in), or 0. */ private accumulateZoom(delta: number): number { const now = Date.now() const step = Math.sign(delta) * Math.min(Math.abs(delta) * ZOOM_SCALE, MAX_ZOOM_STEP) if ( now - this.lastZoomTime > ZOOM_IDLE_RESET_MS || Math.sign(step) !== Math.sign(this.zoomRemainder) ) { this.zoomRemainder = 0 } this.lastZoomTime = now this.zoomRemainder += step const whole = Math.trunc(this.zoomRemainder) this.zoomRemainder -= whole // Positive delta (fingers apart) zooms in, which is a negative wheel amount. return whole === 0 ? 0 : -whole } private dispatch(msg: InputMessage): void { switch (msg.type) { case "move": { if (msg.dx === 0 && msg.dy === 0) break const { ax, ay } = applyMotion(msg.dx ?? 0, msg.dy ?? 0, this.config) this.injector.injectMouseMove(ax, ay) break } case "click": { if (!isValidButton(msg.button)) break if (typeof msg.press !== "boolean") break this.injector.injectMouseButton(msg.button, msg.press) break } case "absoluteClick": { if (!isValidButton(msg.button)) break if (typeof msg.press !== "boolean") break const absX = msg.x * this.config.screenWidth const absY = msg.y * this.config.screenHeight this.injector.injectMouseAbsolute(absX, absY) console.log({ "Injected at": { absX, absY } }) this.injector.injectMouseButton(msg.button, msg.press) break } case "scroll": { this.injector.injectMouseWheel(msg.dx ?? 0, msg.dy ?? 0) break } case "zoom": { if (!Number.isFinite(msg.delta) || msg.delta === 0) break const amount = this.accumulateZoom(msg.delta ?? 0) if (amount !== 0) { // The drivers apply invertScroll inside injectMouseWheel. That is a // scroll preference and must not flip the pinch direction, so cancel it. const wheel = this.config.invertScroll ? -amount : amount this.injector.injectKey("control", "HOLD") this.injector.injectMouseWheel(0, wheel) this.injector.injectKey("control", "RELEASE") } break } case "copy": { this.injector.injectCombo( this.platform === "darwin" ? ["meta", "c"] : ["control", "c"], ) break } case "paste": { this.injector.injectCombo( this.platform === "darwin" ? ["meta", "v"] : ["control", "v"], ) break } case "key": { if ( !msg.key || typeof msg.key !== "string" || msg.key.length > MAX_KEY_LENGTH || msg.key.toLowerCase() === "unidentified" || msg.key.toLowerCase() === "process" ) break const key = msg.key === " " || msg.key.toLowerCase() === "space" ? "space" : msg.key this.injector.injectKey(key, msg.pos ?? "") break } case "combo": { if ( !Array.isArray(msg.keys) || msg.keys.length === 0 || msg.keys.length > MAX_COMBO_KEYS ) break const validKeys = msg.keys.filter( (k): k is string => typeof k === "string" && k.length > 0 && k.length <= MAX_KEY_LENGTH, ) if (validKeys.length === 0) { console.error("[InputHandler] No valid keys in combo") break } this.injector.injectCombo(validKeys) console.log(`[InputHandler] Combo executed: ${validKeys.join("+")}`) break } case "text": { if ( !msg.text || typeof msg.text !== "string" || msg.text.length > MAX_TEXT_LENGTH ) break this.injector.injectText(msg.text) break } case "touch": { if (!msg.contacts?.length) break const valid = msg.contacts.filter( (c) => typeof c.id === "number" && typeof c.x === "number" && typeof c.y === "number" && ["down", "move", "up"].includes(c.state), ) if (valid.length > 0) this.injector.injectTouch(valid) break } case "gamepad": { if (!msg.button || typeof msg.button !== "string") break if (typeof msg.press !== "boolean") break this.injector.injectGamepadButton(msg.button, msg.press) break } case "gamepad-axis": { if (msg.axis !== "ls" && msg.axis !== "rs") break if ( typeof msg.ax !== "number" || !Number.isFinite(msg.ax) || typeof msg.ay !== "number" || !Number.isFinite(msg.ay) ) break this.injector.injectGamepadAxis(msg.axis, msg.ax, msg.ay) break } default: console.warn( `[InputHandler] Unknown message type: ${(msg as { type?: unknown }).type}`, ) } } } function clampFinite(value: unknown, min: number, max: number): number { if (typeof value !== "number" || !Number.isFinite(value)) return 0 return Math.max(min, Math.min(max, value)) } function isValidButton(button: unknown): button is MouseButton { return ( typeof button === "string" && (VALID_BUTTONS as readonly string[]).includes(button) ) } function createStubInjector(): PlatformInjector { const warn = (method: string) => console.warn(`[InputHandler] ${method} called on unsupported platform`) return { updateConfig: () => {}, injectMouseMove: () => warn("injectMouseMove"), injectMouseAbsolute: () => warn("injectMouseAbsolute"), injectMouseButton: () => warn("injectMouseButton"), injectMouseWheel: () => warn("injectMouseWheel"), injectKey: () => warn("injectKey"), injectCombo: () => warn("injectCombo"), injectText: () => warn("injectText"), injectTouch: () => warn("injectTouch"), injectGamepadButton: () => warn("injectGamepadButton"), injectGamepadAxis: () => warn("injectGamepadAxis"), destroy: () => {}, } } let lastProbeResult: { ok: boolean; error?: string } | null = null let lastProbeTime = 0 const PROBE_CACHE_TTL_MS = 10_000 export function clearInputInjectorProbeCache(): void { lastProbeResult = null lastProbeTime = 0 } /** * Probes whether the host environment can successfully create virtual input devices. * Results are cached for 10 seconds to avoid device churn on Linux (/dev/uinput). */ export function probeInputInjector(forceRefresh = false): { ok: boolean error?: string } { const now = Date.now() if ( !forceRefresh && lastProbeResult && now - lastProbeTime < PROBE_CACHE_TTL_MS ) { return lastProbeResult } const plat = os.platform() try { let result: { ok: boolean; error?: string } if (plat === "win32") { const { WindowsInputInjector } = require("./drivers/windows") const injector = new WindowsInputInjector() injector.destroy?.() result = { ok: true } } else if (plat === "linux") { const { LinuxInputInjector } = require("./drivers/linux") const injector = new LinuxInputInjector() injector.destroy?.() result = { ok: true } } else if (plat === "darwin") { const { MacInputInjector } = require("./drivers/mac") const injector = new MacInputInjector() injector.destroy?.() result = { ok: true } } else { result = { ok: false, error: `Unsupported platform: ${plat}` } } lastProbeResult = result lastProbeTime = now return result } catch (e) { const result = { ok: false, error: e instanceof Error ? e.message : String(e), } lastProbeResult = result lastProbeTime = now return result } }