import assert from 'node:assert'; import type { Size } from '@midscene/core'; export interface LibNut { getScreenSize(): { width: number; height: number }; getMousePos(): { x: number; y: number }; moveMouse(x: number, y: number): void; mouseClick(button?: MouseButton, double?: boolean): void; mouseToggle(state: 'up' | 'down', button?: MouseButton): void; scrollMouse(x: number, y: number): void; keyTap(key: string, modifiers?: string[]): void; keyToggle(key: string, state: 'up' | 'down', modifiers?: string[]): void; typeString(text: string): void; getActiveWindow?(): number; focusWindow?(handle: number): void; } export type MouseButton = 'left' | 'right' | 'middle'; export type ScrollDirection = 'up' | 'down' | 'left' | 'right'; const MOUSE_COORDINATE_TOLERANCE_PX = 5; interface ComputerInputDriverOptions { getLibnut(): LibNut | null; useAppleScript(): boolean; sendKeyViaAppleScript(key: string, modifiers?: string[]): void; runPhasedScroll( direction: ScrollDirection, pixels: number, steps: number, ): boolean; debug(message: string): void; } export class ComputerInputDriver { private destroyed = false; private pendingInputDelayWaits = new Set<{ timeoutId: ReturnType; reject: (error: Error) => void; }>(); constructor(private readonly options: ComputerInputDriverOptions) {} destroy(): void { if (this.destroyed) { return; } this.destroyed = true; this.rejectPendingInputDelays(); } getScreenSize(): Size { return this.getLibnutOrThrow('getScreenSize').getScreenSize(); } getMousePos(): { x: number; y: number } { return this.getLibnutOrThrow('getMousePos').getMousePos(); } moveMouse(x: number, y: number): void { this.getLibnutOrThrow('moveMouse').moveMouse(x, y); } assertMousePosition( targetX: number, targetY: number, context: string, ): { x: number; y: number } { const current = this.getMousePos(); const drift = { x: current.x - targetX, y: current.y - targetY }; if ( Math.abs(drift.x) > MOUSE_COORDINATE_TOLERANCE_PX || Math.abs(drift.y) > MOUSE_COORDINATE_TOLERANCE_PX ) { throw new Error( `${context}: expected (${targetX}, ${targetY}), got (${current.x}, ${current.y}), drift=(${drift.x}, ${drift.y})`, ); } return drift; } focusActiveWindow(): boolean { const lib = this.getLibnutOrThrow('focusActiveWindow'); if ( typeof lib.getActiveWindow !== 'function' || typeof lib.focusWindow !== 'function' ) { return false; } try { const handle = lib.getActiveWindow(); if (!handle) return false; lib.focusWindow(handle); return true; } catch (error) { this.options.debug(`focusActiveWindow failed: ${error}`); return false; } } mouseClick(button?: MouseButton, double?: boolean): void { const lib = this.getLibnutOrThrow('mouseClick'); // libnut is a native binding that distinguishes "no argument" from // "explicit undefined" — passing undefined for optional args trips // "A boolean was expected" / "A string was expected" type checks. if (double !== undefined) { lib.mouseClick(button, double); } else if (button !== undefined) { lib.mouseClick(button); } else { lib.mouseClick(); } } mouseToggle(state: 'up' | 'down', button: MouseButton = 'left'): void { this.getLibnutOrThrow('mouseToggle').mouseToggle(state, button); } scrollMouse(x: number, y: number): void { this.getLibnutOrThrow('scrollMouse').scrollMouse(x, y); } /** * Emit one `libnut.scrollMouse` call per detent and pace them with * `delayMs`. Per-call magnitude is fixed by the caller so each call is * exactly one detent on the target platform — on Windows the libnut * binding forwards `mouseData` straight to `MOUSEEVENTF_WHEEL`, where * sub-WHEEL_DELTA values (< 120) get accumulated and frequently dropped * by Chromium's WheelEventQueue. */ async emitScrollDetents( dx: number, dy: number, detents: number, delayMs: number, ): Promise { this.assertActive('emitScrollDetents'); for (let i = 0; i < detents; i++) { this.scrollMouse(dx, dy); if (i < detents - 1) { await this.delay(delayMs); } } } keyTap(key: string, modifiers?: string[]): void { const lib = this.getLibnutOrThrow('keyTap'); // See note on mouseClick — avoid passing explicit undefined to libnut. if (modifiers !== undefined) { lib.keyTap(key, modifiers); } else { lib.keyTap(key); } } keyToggle(key: string, state: 'up' | 'down', modifiers?: string[]): void { const lib = this.getLibnutOrThrow('keyToggle'); if (modifiers !== undefined) { lib.keyToggle(key, state, modifiers); } else { lib.keyToggle(key, state); } } /** * Send one modified key through libnut. A positive delay expands the compact * key tap into individually observable modifier transitions. A zero delay * preserves libnut's compact key-tap behavior. */ async keyTapWithModifierDelay( key: string, modifiers: string[], delayMs: number, ): Promise { const uniqueModifiers = [...new Set(modifiers)]; if (uniqueModifiers.length === 0) { this.keyTap(key); return; } if (delayMs === 0) { this.keyTap(key, uniqueModifiers); return; } const pressedModifiers: string[] = []; let failure: unknown; try { for (const modifier of uniqueModifiers) { this.keyToggle(modifier, 'down'); pressedModifiers.push(modifier); await this.delay(delayMs); } this.keyTap(key); await this.delay(delayMs); } catch (error) { failure = error; } for (const modifier of pressedModifiers.reverse()) { const releaseFailure = this.tryReleaseKey(modifier); if (failure === undefined && releaseFailure !== undefined) { failure = releaseFailure; } if (failure === undefined) { try { await this.delay(delayMs); } catch (error) { failure = error; } } } if (failure !== undefined) { throw failure; } } typeString(text: string): void { this.getLibnutOrThrow('typeString').typeString(text); } sendKeyViaAppleScript(key: string, modifiers: string[] = []): void { this.assertActive('sendKeyViaAppleScript'); this.options.sendKeyViaAppleScript(key, modifiers); } sendKey(key: string, modifiers: string[] = []): void { if (this.options.useAppleScript()) { this.sendKeyViaAppleScript(key, modifiers); return; } if (modifiers.length > 0) { this.keyTap(key, modifiers); } else { this.keyTap(key); } } runPhasedScroll( direction: ScrollDirection, pixels: number, steps: number, ): boolean { this.assertActive('runPhasedScroll'); return this.options.runPhasedScroll(direction, pixels, steps); } async delay(ms: number): Promise { this.assertActive('delay'); return new Promise((resolve, reject) => { const waitRef = { timeoutId: setTimeout(() => { this.pendingInputDelayWaits.delete(waitRef); try { this.assertActive('delay'); resolve(); } catch (error) { reject(error); } }, ms), reject, }; this.pendingInputDelayWaits.add(waitRef); }); } async smoothMoveMouse( targetX: number, targetY: number, steps: number, stepDelay: number, ): Promise { const currentPos = this.getMousePos(); for (let i = 1; i <= steps; i++) { const stepX = Math.round( currentPos.x + ((targetX - currentPos.x) * i) / steps, ); const stepY = Math.round( currentPos.y + ((targetY - currentPos.y) * i) / steps, ); this.moveMouse(stepX, stepY); await this.delay(stepDelay); } } async withMouseButton( button: MouseButton, run: () => Promise, ): Promise { this.mouseToggle('down', button); try { return await run(); } finally { this.releaseMouseButton(button); } } private getLibnutOrThrow(methodName: string): LibNut { this.assertActive(methodName); const libnut = this.options.getLibnut(); assert(libnut, 'libnut not initialized'); return libnut; } private assertActive(methodName: string): void { if (this.destroyed) { throw this.createDestroyedError(methodName); } } private createDestroyedError(methodName: string): Error { return new Error( `ComputerDevice has been destroyed (cannot run ${methodName})`, ); } private releaseMouseButton(button: MouseButton): void { try { const libnut = this.options.getLibnut(); assert(libnut, 'libnut not initialized'); libnut.mouseToggle('up', button); } catch (error) { this.options.debug(`Failed to release mouse button ${button}: ${error}`); } } private tryReleaseKey(key: string): Error | undefined { try { const libnut = this.options.getLibnut(); assert(libnut, 'libnut not initialized'); libnut.keyToggle(key, 'up'); return undefined; } catch (error) { const releaseError = new Error( `Failed to release modifier key "${key}"`, { cause: error, }, ); this.options.debug(`${releaseError.message}: ${error}`); return releaseError; } } private rejectPendingInputDelays(): void { const error = this.createDestroyedError('in-flight input'); for (const waitRef of this.pendingInputDelayWaits) { clearTimeout(waitRef.timeoutId); waitRef.reject(error); } this.pendingInputDelayWaits.clear(); } }