### Example: Start Listening for Key Down Events Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Shows how to create an `InputHook` instance, attach a `onKeyDown` listener, and then start the hook to begin capturing events. ```javascript const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key)) hook.start() ``` -------------------------------- ### Example: Request and Setup Input Listener Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/permissions-and-access.md This example shows how to request Input Monitoring access if it's not already granted, then sets up an event listener. It handles user denial by logging an error. ```javascript import { preflightListenEventAccess, requestListenEventAccess, startListen } from 'monio-napi' function setupInputListener() { if (!preflightListenEventAccess()) { console.log('Requesting Input Monitoring access...') const granted = requestListenEventAccess() if (!granted) { console.error('User denied Input Monitoring access') console.error('Grant access in System Settings > Privacy & Security > Accessibility') return } } // Start listening for events const hook = startListen((event) => { console.log('Event:', event.eventType) }) hook.stop() } setupInputListener() ``` -------------------------------- ### Example: Preflight Input Monitoring Access Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/permissions-and-access.md This example demonstrates how to check for Input Monitoring access before starting to listen for events. It logs an error and provides instructions if access is not granted on macOS. ```javascript import { preflightListenEventAccess, startListen } from 'monio-napi' if (!preflightListenEventAccess()) { console.error('Input Monitoring access is not granted on macOS') console.log('Please grant access in System Settings > Privacy & Security > Accessibility') } else { const hook = startListen((event) => { console.log('Event received:', event.eventType) }) } ``` -------------------------------- ### Complete InputHook Example Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md A full example demonstrating how to import, instantiate, and use InputHook. It covers registering various event handlers (key down/up, mouse move, click, wheel), starting the hook, dynamically changing handlers, and stopping the hook. ```javascript import { InputHook, KeyJs, ButtonJs } from 'monio-napi' const hook = new InputHook() // Register event handlers hook.onKeyDown((data) => { console.log('Key down:', data.key, 'at', new Date(data.time * 1000)) }) hook.onKeyUp((data) => { console.log('Key up:', data.key) }) hook.onMouseMove((data) => { console.log(`Mouse moved to (${data.x.toFixed(0)}, ${data.y.toFixed(0)})`) }) hook.onClick((data) => { console.log(`Clicked button ${data.button} at (${data.x}, ${data.y})`) }) hook.onWheel((data) => { console.log(`Scrolled ${data.direction} by ${data.delta}`) }) // Start listening hook.start() // Later, dynamically change handlers setTimeout(() => { hook.offMouseMove() // Stop listening to mouse movement }, 5000) // Stop completely setTimeout(() => { hook.stop() }, 10000) ``` -------------------------------- ### Create and Start InputHook Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Instantiates an InputHook, registers callbacks for key down and mouse move events, starts the hook, and provides an example of stopping it later. Ensure the hook is started before events are captured. ```javascript import { InputHook } from 'monio-napi' const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key, data.rawCode)) hook.onMouseMove((data) => console.log('mouse:', data.x, data.y)) hook.start() // ... later: hook.stop() ``` -------------------------------- ### Install Monio NAPI Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Install the monio-napi package using npm. ```bash npm install monio-napi ``` -------------------------------- ### start() Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Starts listening for input events. This method initializes the native hook and begins capturing events. It will throw an error if the hook is already running. ```APIDOC ## start() ### Description Start listening for input events. This method initializes the native hook and begins capturing events. Throws if the hook is already running. ### Method `start(): void` ### Throws `GenericFailure` — If the hook is already running or fails to start. ### Example ```javascript const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key)) hook.start() ``` ``` -------------------------------- ### Permission Guard for Production Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/permissions-and-access.md This example shows a class-based approach to manage input listener access, ensuring permissions are granted before starting to listen. It's suitable for production environments where access is critical. ```javascript import { preflightListenEventAccess, requestListenEventAccess } from 'monio-napi' class InputListenerManager { constructor() { this.hook = null this.hasAccess = false } async ensureAccess() { if (this.hasAccess) { return true } // Check current status if (preflightListenEventAccess()) { this.hasAccess = true return true } // Request if not granted console.warn('Input Monitoring access required') const granted = requestListenEventAccess() if (granted) { this.hasAccess = true return true } else { console.error('Input Monitoring access denied') return false } } async startListening(callback) { if (!await this.ensureAccess()) { throw new Error('Cannot start listening without Input Monitoring access') } const { startListen } = await import('monio-napi') this.hook = startListen(callback) return this.hook } stop() { if (this.hook) { this.hook.stop() this.hook = null } } } // Usage const manager = new InputListenerManager() manager.startListening((event) => { console.log('Event:', event.eventType) }).catch(console.error) // Later... manager.stop() ``` -------------------------------- ### Install monio-napi Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Install the monio-napi package using npm or pnpm. ```bash npm install monio-napi # or pnpm add monio-napi ``` -------------------------------- ### Start Listening with Event Mask Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Starts a listener that only forwards specific input events based on the provided eventMask. This example filters to include only keyboard events. ```typescript import { startListen, EVENT_MASK_KEYBOARD } from 'monio-napi'; const hook = startListen((event) => { console.log('Received keyboard event:', event); }, EVENT_MASK_KEYBOARD); // To stop the listener later: // hook.stop(); ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Installs necessary libraries for Linux systems to enable input event monitoring. ```bash # Ubuntu/Debian sudo apt-get install libx11-6 libxtst6 # Fedora sudo dnf install libX11 libXtst # Arch sudo pacman -S libx11 libxtst ``` -------------------------------- ### Get Mouse Position Example Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/display-functions.md Demonstrates how to import and use the getMousePosition function to log the current mouse coordinates to the console. ```javascript import { getMousePosition } from 'monio-napi' const position = getMousePosition() console.log(`Mouse is at (${position.x}, ${position.y})`) ``` -------------------------------- ### Complete Display and Mouse Analysis Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/display-functions.md Analyzes the entire display setup, including listing all displays, identifying the primary display, calculating the virtual screen bounds, and determining the current mouse position and the display it resides on. This example requires importing multiple functions from 'monio-napi'. ```javascript import { getDisplays, getPrimaryDisplay, getDisplayAtPoint, getMousePosition } from 'monio-napi' function analyzeDisplaySetup() { const displays = getDisplays() const primary = getPrimaryDisplay() const mousePos = getMousePosition() console.log(` === Display Setup ===`) console.log(`Total displays: ${displays.length}`) console.log(`Primary display ID: ${primary.id}`) // Find total virtual screen bounds let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity for (const display of displays) { minX = Math.min(minX, display.bounds.x) minY = Math.min(minY, display.bounds.y) maxX = Math.max(maxX, display.bounds.x + display.bounds.width) maxY = Math.max(maxY, display.bounds.y + display.bounds.height) } console.log(` Virtual screen: (${minX}, ${minY}) to (${maxX}, ${maxY})`) console.log(`Total virtual resolution: ${maxX - minX}x${maxY - minY}`) // Detailed display information console.log(` === Individual Displays ===`) for (const display of displays) { console.log(` Display ${display.id}${display.isPrimary ? ' (PRIMARY)' : ''}: `) console.log(` Position: (${display.bounds.x}, ${display.bounds.y})`) console.log(` Resolution: ${display.bounds.width}x${display.bounds.height}`) console.log(` Scale factor: ${display.scaleFactor}`) if (display.refreshRate) { console.log(` Refresh rate: ${display.refreshRate}Hz`) } } // Current mouse location console.log(` === Mouse Location ===`) console.log(`Current position: (${mousePos.x}, ${mousePos.y})`) const displayAtMouse = getDisplayAtPoint(mousePos.x, mousePos.y) if (displayAtMouse) { console.log(`On display: ${displayAtMouse.id}`) const relX = mousePos.x - displayAtMouse.bounds.x const relY = mousePos.y - displayAtMouse.bounds.y console.log(`Relative position on display: (${relX}, ${relY})`) } } analyzeDisplaySetup() ``` -------------------------------- ### Example: Stop Listening for Input Events Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Illustrates the process of starting the input hook, attaching a listener, and then stopping the hook later to cease event capture. ```javascript const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key)) hook.start() // Later... hook.stop() ``` -------------------------------- ### Complete Example: Comprehensive Key Information Display Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/key-functions.md A comprehensive example showcasing multiple monio-napi functions including getKeyDisplayName, getKeyCategory, isModifierKey, and getAllKeyDisplayInfo. It defines a displayKeyInfo function and a printKeyboardLayout function to demonstrate usage with specific keys and by category. ```javascript import { getKeyDisplayName, getKeyCategory, isModifierKey, getAllKeyDisplayInfo, KeyJs } from 'monio-napi' function displayKeyInfo(key) { const displayName = getKeyDisplayName(key) const category = getKeyCategory(key) const isModifier = isModifierKey(key) console.log(`Key: ${displayName}`) console.log(` Category: ${category}`) console.log(` Is modifier: ${isModifier}`) } displayKeyInfo(KeyJs.ShiftLeft) // Output: // Key: Shift // Category: modifier // Is modifier: true displayKeyInfo(KeyJs.KeyA) // Output: // Key: A // Category: letter // Is modifier: false function printKeyboardLayout() { const allKeys = getAllKeyDisplayInfo() const byCategory = {} // Group keys by category for (const keyInfo of allKeys) { if (!byCategory[keyInfo.category]) { byCategory[keyInfo.category] = [] } byCategory[keyInfo.category].push(keyInfo) } // Print by category for (const [category, keys] of Object.entries(byCategory).sort()) { console.log(`\n${category.toUpperCase()} KEYS (${keys.length}):`) const displayNames = keys.map(k => k.displayName).join(', ') console.log(displayNames) } } printKeyboardLayout() ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Install necessary X11 libraries on Linux to resolve 'X11 server not available' errors. Ensure your application runs under an X11 session. ```bash sudo apt-get install libx11-6 libxtst6 ``` -------------------------------- ### start-listen.md Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for the main event listening function, including parameters, return types, event mask constants, and usage examples. ```APIDOC ## startListen ### Description This is the main function for initiating event listening. It allows users to capture various system events. ### Method N/A (Node.js N-API function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript // Example usage of startListen const { startListen } = require('monio-napi'); async function listenForEvents() { const listener = await startListen({ // event mask configuration }); // ... handle events ... listener.stop(); } listenForEvents(); ``` ### Response #### Success Response - **listener** (object) - A handle to the event listener, providing methods for management. #### Response Example ```json { "listener": { /* ... listener object ... */ } } ``` ### Event Mask Constants Reference Documentation includes reference to event mask constants for configuring the listener. ### Usage Examples Includes 4 detailed usage examples. ``` -------------------------------- ### Monio NAPI Complete Configuration Example Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/configuration.md Demonstrates various configuration patterns including optimized event masks, automatic mask handling with InputHook, and dynamic mask switching. ```javascript import { startListen, EVENT_MASK_KEYBOARD, EVENT_MASK_MOUSE_BUTTONS, EVENT_MASK_MOUSE_MOVEMENT, InputHook } from 'monio-napi' // Example 1: startListen with optimized mask class KeyBindingMonitor { constructor() { this.hook = startListen( (event) => this.handleEvent(event), EVENT_MASK_KEYBOARD | EVENT_MASK_MOUSE_BUTTONS ) } handleEvent(event) { console.log('Event:', event.eventType) } stop() { this.hook.stop() } } // Example 2: InputHook with automatic mask class MouseTracker { constructor() { this.hook = new InputHook() this.hook.onMouseMove((data) => { console.log(`Mouse: (${data.x}, ${data.y})`) }) } start() { this.hook.start() console.log(`Event mask: 0x${this.hook.eventMask.toString(16)}`) } stop() { this.hook.stop() } } // Example 3: Dynamic mask switching class AdaptiveMonitor { constructor() { this.hook = startListen( (event) => this.handleEvent(event), EVENT_MASK_KEYBOARD ) this.mode = 'keyboard' } switchMode(newMode) { let mask if (newMode === 'keyboard') { mask = EVENT_MASK_KEYBOARD } else if (newMode === 'mouse') { mask = EVENT_MASK_MOUSE_MOVEMENT } else if (newMode === 'all') { mask = EVENT_MASK_KEYBOARD | EVENT_MASK_MOUSE_BUTTONS | EVENT_MASK_MOUSE_MOVEMENT } this.hook.setEventMask(mask) this.mode = newMode } handleEvent(event) { console.log(`[${this.mode}] Event:`, event.eventType) } stop() { this.hook.stop() } } ``` -------------------------------- ### Build monio-napi Project Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Build the monio-napi project for release or debugging using pnpm. Includes commands for installation and testing. ```bash pnpm install pnpm build # release build pnpm build:debug # debug build pnpm test ``` -------------------------------- ### Example: Filtering and Displaying Key Information Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/key-functions.md Demonstrates how to use getAllKeyDisplayInfo to fetch all key data and then filter it by category (function, modifier, letter) for display. Requires importing the function from 'monio-napi'. ```javascript import { getAllKeyDisplayInfo } from 'monio-napi' const allKeys = getAllKeyDisplayInfo() // Display all function keys const functionKeys = allKeys.filter(k => k.category === 'function') console.log('Function keys:') for (const key of functionKeys) { console.log(` Key ${key.key}: ${key.displayName}`) } // Display all modifier keys const modifierKeys = allKeys.filter(k => k.category === 'modifier') console.log('\nModifier keys:') for (const key of modifierKeys) { console.log(` Key ${key.key}: ${key.displayName}`) } // Display all letters const letterKeys = allKeys.filter(k => k.category === 'letter') console.log(`\nTotal letter keys: ${letterKeys.length}`) ``` -------------------------------- ### Start Listening for All Events Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Starts a listener that forwards all input events to the provided callback function. No eventMask is specified, so all events are processed. ```typescript import { startListen, EVENT_MASK_ALL } from 'monio-napi'; const hook = startListen((event) => { console.log('Received event:', event); }); // To stop the listener later: // hook.stop(); ``` -------------------------------- ### event-simulation.md Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for keyboard and mouse simulation functions, including multi-scenario examples. ```APIDOC ## Event Simulation Functions ### Description Provides functions to simulate keyboard and mouse events. ### Keyboard Simulation Functions (3) Details functions for simulating key presses, releases, and combinations. ### Mouse Simulation Functions (4) Details functions for simulating mouse movements, clicks, and drags. ### Multi-Scenario Examples Includes comprehensive examples covering various simulation scenarios. ### Platform-Specific Notes Provides notes on platform-specific behavior for event simulation. ``` -------------------------------- ### Add monio-napi AI Agent Skill Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Install the monio-napi skill for agent guidance using npx. ```bash npx skills add https://github.com/HuakunShen/monio-napi/skills --skill monio-napi ``` -------------------------------- ### InputHook Constructor Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Creates a new InputHook instance. The hook must be started with `start()` before events are captured. ```APIDOC ## InputHook Constructor ### Description Creates a new `InputHook` instance. The hook must be started with `start()` before events are captured. ### Method ```typescript constructor() ``` ### Example ```javascript import { InputHook } from 'monio-napi' const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key, data.rawCode)) hook.onMouseMove((data) => console.log('mouse:', data.x, data.y)) hook.start() // ... later: hook.stop() ``` ``` -------------------------------- ### startListen Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Starts listening for input events (keyboard and mouse) in a non-blocking background listener. It returns a HookJs instance for managing the listener. ```APIDOC ## startListen ### Description Starts listening for input events (keyboard and mouse) in a non-blocking background listener. Returns a `HookJs` instance that can be used to stop the listener or manage event filtering at runtime. The `eventMask` parameter is an optional bitmask that filters events on the native side before crossing the NAPI boundary, providing a performance optimization. High-frequency events like `MouseMoved` never reach JavaScript if the corresponding bit is not set in the mask. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```typescript startListen(callback: (event: EventJs) => void, eventMask?: number | undefined | null): HookJs ``` ### Parameters - **callback** (`(event: EventJs) => void`) - Required - Callback function invoked for each input event. Receives an `EventJs` object containing event type and data. - **eventMask** (`number | undefined | null`) - Optional - Bitmask controlling which event types are forwarded. Use `EVENT_MASK_*` constants or combine bits. If not provided or `null`, all events are forwarded. Defaults to `EVENT_MASK_ALL`. ### Return Type **`HookJs`** — Hook instance with lifecycle and filtering capabilities: - `stop(): void` — Stops listening for events - `isRunning: boolean` — (getter) Whether the hook is currently active - `setEventMask(mask: number): void` — Update the event filter at runtime - `eventMask: number` — (getter) Get the current event filter bitmask ``` -------------------------------- ### Selective Input Hooks with InputHook Class Source: https://github.com/huakunshen/monio-napi/blob/main/skills/monio-napi/SKILL.md Utilize the `InputHook` class for type-specific event listeners. Call `start()` to begin listening and `stop()` to end. This example listens for mouse movements and key presses. ```javascript import { InputHook, EventTypeJs } from 'monio-napi' const hook = new InputHook() hook.onMouseMove((data) => { console.log('Move', data.x, data.y) }) hook.onKeyDown((data) => { console.log('KeyDown', data.key, data.rawCode) }) hook.start() setTimeout(() => hook.stop(), 5000) ``` -------------------------------- ### Handle Linux X11 Server Errors Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md This function starts listening for events on Linux. It includes error handling for cases where the X11 server is not available, providing instructions to install necessary libraries (libx11 and libxtst) for different Linux distributions. ```javascript import { startListen } from 'monio-napi' function startListeningOnLinux() { try { const hook = startListen((event) => { console.log('Event:', event.eventType) }) return hook } catch (error) { if (error.message.includes('display') || error.message.includes('X11')) { console.error('X11 server not available') console.error('Ensure libx11 and libxtst are installed:') console.error(' Ubuntu/Debian: sudo apt-get install libx11-6 libxtst6') console.error(' Fedora: sudo dnf install libX11 libXtst') } throw error } } ``` -------------------------------- ### display-functions.md Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/GENERATION_SUMMARY.txt Documentation for display enumeration functions and system settings queries, with multi-display examples. ```APIDOC ## Display Functions ### Description Provides functions to query display information and system settings. ### Display Enumeration Functions (3) Details functions for enumerating connected displays. ### System Settings Queries (2) Details functions for querying system display settings. ### Multi-Display Examples Includes examples demonstrating handling of multi-monitor setups. ### Type Documentation Inline Type definitions are documented inline with the functions. ``` -------------------------------- ### Event Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Starts listening for input events and returns a HookJs handle to manage the listener. ```APIDOC ## startListen(callback, eventMask?) ### Description Starts listening for input events and provides a callback function to process them. An optional event mask can be provided to filter events. ### Parameters #### Arguments - **callback** (function) - Required - Function to be called when an event occurs. - **eventMask** (number) - Optional - A bitmask to filter the types of events to listen for. ### Returns - **HookJs** - A handle object with methods to control the listener. ``` -------------------------------- ### Graceful Degradation with Input Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md Demonstrates how to gracefully handle errors when starting input listening. If an error occurs, it logs a warning and continues operation without listening. ```javascript import { startListen, getDisplays } from 'monio-napi' class InputManager { constructor() { this.hook = null } tryStartListening() { try { this.hook = startListen((event) => { this.handleEvent(event) }) console.log('Input listening started') } catch (error) { console.warn('Could not start input listener:', error.message) this.hook = null // Gracefully continue without listening } } handleEvent(event) { // Process event } stop() { if (this.hook) { try { this.hook.stop() } catch (error) { console.warn('Error stopping listener:', error.message) } this.hook = null } } } ``` -------------------------------- ### Example: Remove All Listeners Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Demonstrates how to register multiple event listeners and then remove them all using `removeAllListeners()`. ```javascript const hook = new InputHook() hook.onKeyDown((data) => console.log('key down')) hook.onMouseMove((data) => console.log('mouse move')) hook.start() // Later, remove all listeners hook.removeAllListeners() ``` -------------------------------- ### Unit Test for InputHook Start Error Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md This unit test verifies that calling `start()` on an already running InputHook instance throws the expected error. It uses the Ava testing framework. ```javascript import test from 'ava' import { InputHook } from 'monio-napi' test('InputHook rejects start when already running', (t) => { const hook = new InputHook() hook.onKeyDown(() => {}) hook.start() // First start succeeds const error = t.throws(() => { hook.start() // Second start throws }) t.is(error.message, 'Hook is already running') hook.stop() }) ``` -------------------------------- ### Start Listening for All Events Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Initiates listening for all system events. The hook object returned can be used to check the listening status and to stop the listener. ```javascript import { startListen } from 'monio-napi' const hook = startListen((event) => { console.log('Event:', event.eventType) console.log('Time:', event.time) }) // Check status console.log('Listening:', hook.isRunning) // Stop when done hook.stop() ``` -------------------------------- ### Example: Type Uppercase Text Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/event-simulation.md Demonstrates how to type uppercase text by holding the Shift key and tapping each character. This function requires importing multiple key simulation utilities. ```javascript import { simulateKeyTap, simulateKeyPress, simulateKeyRelease, KeyJs } from 'monio-napi' function typeUppercaseText(text) { simulateKeyPress(KeyJs.ShiftLeft) for (const char of text) { const keyCode = `Key${char}` // e.g., KeyH, KeyE, KeyL, KeyL, KeyO simulateKeyTap(KeyJs[keyCode]) } simulateKeyRelease(KeyJs.ShiftLeft) } typeUppercaseText('HELLO') ``` -------------------------------- ### Event Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/INDEX.md Starts listening for system events. A callback function is invoked when specified events occur. ```APIDOC ## startListen(callback, eventMask?) ### Description Starts listening for system events. The provided callback function will be invoked when events matching the `eventMask` occur. If `eventMask` is not provided, it defaults to listening for all events. ### Parameters - **callback** (function) - Required - The function to be called when an event occurs. - **eventMask** (number) - Optional - A bitmask specifying which events to listen for. Defaults to all events. ``` -------------------------------- ### Simulate Keyboard Shortcut Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/event-simulation.md This example demonstrates how to simulate a keyboard shortcut, such as Ctrl+C, by pressing and releasing modifier keys and tapping other keys. Ensure to import the necessary simulation functions and the KeyJs enum. ```javascript import { simulateKeyPress, simulateKeyTap, simulateKeyRelease, KeyJs } from 'monio-napi' function performKeyboardShortcut() { // Simulate Ctrl+C (copy) simulateKeyPress(KeyJs.ControlLeft) simulateKeyTap(KeyJs.KeyC) simulateKeyRelease(KeyJs.ControlLeft) } performKeyboardShortcut() ``` -------------------------------- ### Listen for Input Events Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Start listening for keyboard and mouse events. The listener will automatically stop after 10 seconds. ```javascript import { startListen, EventTypeJs } from 'monio-napi' const hook = startListen((event) => { switch (event.eventType) { case EventTypeJs.KeyPressed: console.log('Key:', event.keyboard?.key) break case EventTypeJs.MouseMoved: console.log(`Mouse: (${event.mouse?.x}, ${event.mouse?.y})`) break } }) // Stop after 10 seconds setTimeout(() => hook.stop(), 10000) ``` -------------------------------- ### Start Listening for Keyboard Events Only Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Starts listening specifically for keyboard-related events using the `EVENT_MASK_KEYBOARD` constant. The callback function processes events that contain keyboard data. ```javascript import { startListen, EVENT_MASK_KEYBOARD } from 'monio-napi' const hook = startListen((event) => { if (event.keyboard) { console.log('Key pressed:', event.keyboard.key) } }, EVENT_MASK_KEYBOARD) hook.stop() ``` -------------------------------- ### Detailed Event Handling with Switch Statement Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Provides a comprehensive example of handling various event types using a switch statement based on `eventType`. It logs detailed information for different keyboard, mouse, and wheel events. ```javascript import { startListen, EventTypeJs, ButtonJs, ScrollDirectionJs } from 'monio-napi' const hook = startListen((event) => { switch (event.eventType) { case EventTypeJs.KeyPressed: console.log('Key pressed:', event.keyboard?.key, 'raw code:', event.keyboard?.rawCode) break case EventTypeJs.KeyReleased: console.log('Key released:', event.keyboard?.key) break case EventTypeJs.MouseMoved: console.log(`Mouse moved to (${event.mouse?.x}, ${event.mouse?.y})`) break case EventTypeJs.MouseDragged: console.log(`Mouse dragged to (${event.mouse?.x}, ${event.mouse?.y})`) console.log(`Button: ${event.mouse?.button}`) break case EventTypeJs.MousePressed: console.log(`Mouse button pressed: ${event.mouse?.button}`) break case EventTypeJs.MouseReleased: console.log(`Mouse button released: ${event.mouse?.button}`) break case EventTypeJs.MouseClicked: console.log(`Mouse clicked: ${event.mouse?.button}`) break case EventTypeJs.MouseWheel: console.log(`Scroll direction: ${event.wheel?.direction}, delta: ${event.wheel?.delta}`) break } }) hook.stop() ``` -------------------------------- ### Get All Key Display Information Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/key-functions.md Retrieves an array of objects, each containing display information for a known keyboard key. Use this to get a comprehensive list of keys and their properties. ```typescript getAllKeyDisplayInfo(): KeyDisplayInfo[] ``` ```typescript interface KeyDisplayInfo { key: number // Key code (0-137) displayName: string // Display name (e.g., "A", "Ctrl", "F1") category: string // Key category (e.g., "letter", "modifier", "function") } ``` -------------------------------- ### Start Input Event Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Initializes the native input hook and begins capturing events. This method must be called before any event listeners can receive data. Throws an error if the hook is already running. ```typescript start(): void ``` -------------------------------- ### Get System Input Settings Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/display-functions.md Fetches current system-wide input configurations, including keyboard repeat behavior and mouse sensitivity. Note that not all settings are available on all platforms. ```javascript import { getSystemSettings } from 'monio-napi' const settings = getSystemSettings() console.log('System Input Settings:') if (settings.keyboardRepeatRate !== undefined) { console.log(` Keyboard repeat rate: ${settings.keyboardRepeatRate}`) } if (settings.keyboardRepeatDelay !== undefined) { console.log(` Keyboard repeat delay: ${settings.keyboardRepeatDelay}ms`) } if (settings.doubleClickTime !== undefined) { console.log(` Double-click time: ${settings.doubleClickTime}ms`) } if (settings.keyboardLayout !== undefined) { console.log(` Keyboard layout: ${settings.keyboardLayout}`) } ``` -------------------------------- ### Check Permissions Before Input Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md Ensures necessary permissions for input monitoring are granted before attempting to start listening. It checks preflight access, requests it if needed, and throws an error if access is denied. ```javascript import { preflightListenEventAccess, requestListenEventAccess, startListen } from 'monio-napi' async function safeStartListening() { if (!preflightListenEventAccess()) { console.log('Requesting Input Monitoring access...') const granted = requestListenEventAccess() if (!granted) { throw new Error('User denied Input Monitoring access') } } try { const hook = startListen((event) => { console.log('Event:', event.eventType) }) return hook } catch (error) { throw new Error(`Failed to start listening: ${error.message}`) } } ``` -------------------------------- ### Event Listening Functions Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/INDEX.md Functions for starting and managing event listeners, including handling listener lifecycle and updating event masks. ```APIDOC ## Event Listening ### `start-listen.md` **Description**: Main function to initiate event listening. ### `hook-js.md` **Description**: Manages the listener handle and its lifecycle, providing methods to stop listening and update event masks. - **Methods**: `stop()`, `setEventMask(mask)` - **Properties**: `isRunning` (getter), `eventMask` (getter) ``` -------------------------------- ### Key Information Functions Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/README.md Utility functions to get details and display names for keyboard keys and mouse buttons. ```APIDOC ## Key Information Functions ### Description Utility functions to obtain human-readable names and categorize keyboard keys and mouse buttons. ### Functions - **getKeyDisplayName(key)**: Returns the display name of a given key. - **getKeyCategory(key)**: Returns the category of a given key (e.g., 'letter', 'modifier'). - **isModifierKey(key)**: Returns `true` if the key is a modifier key, `false` otherwise. - **getButtonDisplayName(button)**: Returns the display name of a given mouse button. - **getAllKeyDisplayInfo()**: Returns an array of metadata objects for all known keys. ``` -------------------------------- ### Register Key Up Event Callback Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Sets up a listener for key release events. The callback receives keyboard event data, primarily the key that was released. The hook must be started to receive events. ```javascript const hook = new InputHook() hook.onKeyUp((data) => { console.log('Key released:', data.key) }) hook.start() ``` -------------------------------- ### Retry with Exponential Backoff for Input Listening Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md Implements a strategy to retry starting input listening with exponential backoff. If all retries fail, it throws a final error indicating the persistent failure. ```javascript import { startListen } from 'monio-napi' async function startListeningWithRetry(maxRetries = 3) { let hook = null let error = null for (let attempt = 1; attempt <= maxRetries; attempt++) { try { hook = startListen((event) => { console.log('Event:', event.eventType) }) console.log(`Successfully started listening on attempt ${attempt}`) return hook } catch (err) { error = err console.warn(`Attempt ${attempt} failed:`, err.message) if (attempt < maxRetries) { const delay = Math.pow(2, attempt) * 100 // Exponential backoff await new Promise(resolve => setTimeout(resolve, delay)) } } } throw new Error(`Failed to start listening after ${maxRetries} attempts: ${error.message}`) } startListeningWithRetry().catch(console.error) ``` -------------------------------- ### Start Listening for Mouse Movement Events Only Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md Initiates listening for mouse movement events using the `EVENT_MASK_MOUSE_MOVEMENT` constant. The callback function logs the mouse coordinates when movement occurs. ```javascript import { startListen, EVENT_MASK_MOUSE_MOVEMENT } from 'monio-napi' const hook = startListen((event) => { if (event.mouse) { console.log(`Mouse at (${event.mouse.x}, ${event.mouse.y})`) } }, EVENT_MASK_MOUSE_MOVEMENT) hook.stop() ``` -------------------------------- ### Listen for Input Events Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Start listening for various input events like key presses, mouse movements, and wheel scrolls. The hook object returned can be used to check its running status and to stop the listener. ```javascript import { startListen, EventTypeJs } from 'monio-napi' const hook = startListen((event) => { switch (event.eventType) { case EventTypeJs.KeyPressed: console.log('Key pressed:', event.keyboard?.key, 'raw:', event.keyboard?.rawCode) break case EventTypeJs.MouseMoved: console.log(`Mouse at (${event.mouse?.x}, ${event.mouse?.y})`) break case EventTypeJs.MouseDragged: console.log(`Dragging at (${event.mouse?.x}, ${event.mouse?.y})`) break case EventTypeJs.MouseWheel: console.log('Scroll:', event.wheel?.direction, event.wheel?.delta) break } }) // Check if running console.log('Listening:', hook.isRunning) // Stop when done hook.stop() ``` -------------------------------- ### Get Display and System Information Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Retrieve information about connected displays, including their bounds, scale factor, and refresh rate. Also fetches system-wide settings like double-click time and keyboard layout. ```javascript import { getDisplays, getPrimaryDisplay, getDisplayAtPoint, getSystemSettings } from 'monio-napi' // All displays const displays = getDisplays() for (const display of displays) { console.log(`Display ${display.id}: ${display.bounds.width}x${display.bounds.height}`) console.log(` Scale: ${display.scaleFactor}, Refresh: ${display.refreshRate}Hz`) } // Primary display const primary = getPrimaryDisplay() // Display at a point const display = getDisplayAtPoint(500, 300) // System settings const settings = getSystemSettings() console.log('Double-click time:', settings.doubleClickTime, 'ms') console.log('Keyboard layout:', settings.keyboardLayout) ``` -------------------------------- ### Listening for Events Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Starts a non-blocking background listener for various input events. The listener accepts a callback function that is invoked with event details. The returned hook object provides methods to check its running status and to stop the listener. ```APIDOC ## startListen ### Description Starts a non-blocking background listener for input events. The listener invokes a provided callback function with event details. ### Signature `startListen(callback: (event: Event) => void): Hook` ### Parameters #### callback - `event` (Event) - An object containing details about the detected input event. ### Returns - `Hook` - An object with methods to manage the listener. - `isRunning` (boolean) - Indicates if the listener is currently active. - `stop()` - Stops the event listener. ### Event Types Refer to the 'Event Types' section for a list of possible `event.eventType` values and their descriptions. ``` -------------------------------- ### Register Key Down Event Callback Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Sets up a listener for key press events. The callback receives detailed keyboard event data including the key, raw code, and timestamp. The hook must be started to receive events. ```javascript const hook = new InputHook() hook.onKeyDown((data) => { console.log('Key pressed:', data.key, 'raw code:', data.rawCode) }) hook.start() ``` -------------------------------- ### Project Content Statistics Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/VERIFICATION_REPORT.md Provides a summary of the monio-napi project's content, including file counts, total lines, size, and the number of documented functions, code examples, code blocks, tables, and cross-references. ```text Total Files: 14 (13 markdown + 1 summary) Total Lines: ~4,200 Total Size: ~110 KB Functions Documented: 40 (100% coverage) Code Examples: 40+ Code Blocks: 120+ Tables: 50+ Cross-References: 100+ ``` -------------------------------- ### Register Mouse Move Event Callback Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md Sets up a listener for mouse movement events, including dragging. The callback receives the mouse coordinates (x, y) and timestamp. The hook must be started to receive events. ```javascript const hook = new InputHook() hook.onMouseMove((data) => { console.log(`Mouse at (${data.x}, ${data.y})`) }) hook.start() ``` -------------------------------- ### Get InputHook Event Mask Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/input-hook.md The `eventMask` getter returns a bitmask representing the currently registered event callbacks. This mask is computed automatically before the hook starts. ```typescript get eventMask(): number ``` ```javascript const hook = new InputHook() hook.onKeyDown((data) => console.log('key down')) hook.onMouseMove((data) => console.log('mouse move')) // Mask is automatically computed before start() console.log(hook.eventMask) // Contains bits for KeyPressed and MouseMoved/MouseDragged hook.start() ``` -------------------------------- ### Basic Global Input Listener with startListen Source: https://github.com/huakunshen/monio-napi/blob/main/skills/monio-napi/SKILL.md Use `startListen` for callback-based global input listening. The listener stops automatically after 3 seconds. Inspect `event.eventType` to branch logic. ```javascript import { startListen, EventTypeJs } from 'monio-napi' const hook = startListen((event) => { if (event.eventType === EventTypeJs.MouseDragged) { console.log('Dragging at', event.mouse?.x, event.mouse?.y) } }) setTimeout(() => hook.stop(), 3000) ``` -------------------------------- ### Catching InputHookAlreadyRunningError Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md Handle errors when attempting to start an InputHook that is already active. Ensure that start() is not called multiple times on the same hook instance. ```javascript import { InputHook } from 'monio-napi' const hook = new InputHook() hook.onKeyDown((data) => console.log('key:', data.key)) try { hook.start() hook.start() // Error: already running } catch (error) { console.error('Hook already running:', error.message) // Message: "Hook is already running" } ``` -------------------------------- ### Get display name for a mouse button Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/key-functions.md Use `getButtonDisplayName` to get a human-readable string for a mouse button. Requires importing `getButtonDisplayName` and `ButtonJs` from 'monio-napi'. ```typescript getButtonDisplayName(button: ButtonJs): string ``` ```javascript import { getButtonDisplayName, ButtonJs } from 'monio-napi' console.log(getButtonDisplayName(ButtonJs.Left)) // "MouseL" console.log(getButtonDisplayName(ButtonJs.Right)) // "MouseR" console.log(getButtonDisplayName(ButtonJs.Middle)) // "MouseM" console.log(getButtonDisplayName(ButtonJs.Button4)) // "Mouse4" console.log(getButtonDisplayName(ButtonJs.Button5)) // "Mouse5" ``` -------------------------------- ### Get Primary Display Information Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/display-functions.md Retrieves details about the main display connected to the system. Use this to get dimensions and scale factor of the primary screen. ```javascript import { getPrimaryDisplay } from 'monio-napi' const primary = getPrimaryDisplay() console.log(`Primary display is ${primary.bounds.width}x${primary.bounds.height}`) console.log(`Scale factor: ${primary.scaleFactor}`) ``` -------------------------------- ### Fail Fast with Fallback for Display Configuration Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/errors.md Illustrates failing fast when enumerating displays but providing a safe default configuration if an error occurs. This ensures the application can continue with a known state. ```javascript import { getDisplays } from 'monio-napi' async function getDisplayConfiguration() { try { const displays = getDisplays() return displays } catch (error) { console.error('Failed to enumerate displays:', error.message) // Fall back to a safe default return [{ id: 0, bounds: { x: 0, y: 0, width: 1920, height: 1080 }, scaleFactor: 1.0, isPrimary: true }] } } ``` -------------------------------- ### startListen Function Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/api-reference/start-listen.md The startListen function initiates a listener for system events. It accepts a callback function that will be invoked for each event and an optional event mask to filter events. It returns a hook object with methods to control the listener. ```APIDOC ## startListen ### Description Initiates a listener for system events. Accepts a callback function and an optional event mask. ### Parameters - **callback** (function) - Required - A function to be called when an event occurs. It receives an event object as an argument. - **eventMask** (number) - Optional - A bitmask to filter which events to listen for. Defaults to `EVENT_MASK_ALL`. ### Returns - **hook** (object) - An object with methods to control the listener: - **isRunning** (boolean) - Indicates if the listener is currently active. - **stop** () - Stops the event listener. - **setEventMask** (eventMask: number) - Dynamically updates the event mask. ### Throws - **`GenericFailure`** - If the listener fails to start (e.g., platform-specific reasons, missing permissions on macOS). ``` -------------------------------- ### Event Listening Architecture Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/ARCHITECTURE.md Illustrates the flow of input events from the native system to JavaScript callbacks. ```text Native Input System (OS-level) ↓ monio (Rust library) ↓ HookJs / InputHook (Rust) ↓ Event Mask Filter (Rust-side) ↓ ThreadsafeFunction (NAPI) ↓ JavaScript Callback ``` -------------------------------- ### Key Information Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/INDEX.md Utility functions to get display names, categories, and properties of keys and mouse buttons. ```APIDOC ## Key Information Functions ### getKeyDisplayName(key) #### Description Returns the display name of a given key. ### getKeyCategory(key) #### Description Returns the category of a given key. ### isModifierKey(key) #### Description Returns a boolean indicating whether the specified key is a modifier key (e.g., Shift, Ctrl, Alt). ### getButtonDisplayName(button) #### Description Returns the display name of a given mouse button. ### getAllKeyDisplayInfo() #### Description Returns an array of `KeyDisplayInfo` objects containing display information for all keys. ``` -------------------------------- ### Publish monio-napi to npm Source: https://github.com/huakunshen/monio-napi/blob/main/README.md Publish the monio-napi package to npm after versioning and pushing tags to the repository. Assumes NPM_TOKEN is set in GitHub secrets for automated builds. ```bash npm version patch git push --follow-tags ``` -------------------------------- ### Keyboard and Mouse Metadata Functions Source: https://github.com/huakunshen/monio-napi/blob/main/_autodocs/INDEX.md Functions to get human-readable names, categories, and metadata for keyboard keys and mouse buttons. ```APIDOC ## Keyboard and Mouse Metadata ### `key-functions.md` **Description**: Provides functions to get display names and categorize keys and buttons. - `getKeyDisplayName(key)`: Gets the human-readable name of a key. - `getKeyCategory(key)`: Categorizes a key (e.g., letter, modifier). - `isModifierKey(key)`: Checks if a key is a modifier key. - `getButtonDisplayName(button)`: Gets the display name for a mouse button. - `getAllKeyDisplayInfo()`: Retrieves metadata for all keys. ```