### Linux X11 Example Setup Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Example JavaScript code for setting up and using the SelectionHook on Linux with the X11 display server. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Check environment const envInfo = hook.linuxGetEnvInfo(); if (envInfo && envInfo.displayProtocol === SelectionHook.DisplayProtocol.X11) { console.log("X11 detected"); if (!envInfo.hasInputDeviceAccess) { console.warn("No input device access — mouse/keyboard events won't work"); console.warn("Run: sudo usermod -a -G input $USER"); } } hook.start({ enableClipboard: false, // X11 doesn't need clipboard fallback globalFilterMode: SelectionHook.FilterMode.DEFAULT }); hook.on("text-selection", (data) => { // Position unavailable on X11 console.log(`[${data.programName}] ${data.text}`); }); ``` -------------------------------- ### Example Setup for Wayland Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Sets up the selection hook for Wayland, disabling clipboard and setting global filter mode. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); const envInfo = hook.linuxGetEnvInfo(); if (envInfo && envInfo.displayProtocol === SelectionHook.DisplayProtocol.WAYLAND) { console.log("Wayland mode"); // Wayland has strict security — limited functionality expected hook.start({ enableClipboard: false, globalFilterMode: SelectionHook.FilterMode.DEFAULT }); hook.on("text-selection", (data) => { if (data.method === SelectionHook.SelectionMethod.CLIPBOARD) { console.log("Using clipboard fallback (Wayland limitation)"); } console.log(`[${data.programName}] ${data.text}`); }); } ``` -------------------------------- ### Windows Example Setup Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Example JavaScript code for setting up SelectionHook on Windows, including program filtering and clipboard modes. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Windows-specific: exclude clipboard for modern IDEs hook.setClipboardMode( SelectionHook.FilterMode.EXCLUDE_LIST, ["vscode.exe", "code.exe", "cursor.exe"] ); // Add delay for Office apps hook.setFineTunedList( SelectionHook.FineTunedListType.INCLUDE_CLIPBOARD_DELAY_READ, ["WINWORD.EXE", "EXCEL.EXE", "POWERPNT.EXE"] ); hook.start(); ``` -------------------------------- ### macOS Example Setup Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Example JavaScript code for setting up and using the SelectionHook on macOS, including permission checks and handling fullscreen events. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Check permissions first if (!hook.macIsProcessTrusted()) { console.log("Requesting accessibility permissions..."); hook.macRequestProcessTrust(); // User may need to grant manually } // macOS-specific: handle fullscreen hook.on("text-selection", (data) => { if (data.isFullscreen) { console.log("Selection in fullscreen app (no position data)"); } else { console.log(`Selected at: (${data.endBottom.x}, ${data.endBottom.y})`); } }); hook.start(); ``` -------------------------------- ### Minimal Setup Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Monitors text selections with default configuration. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); hook.on("text-selection", (data) => { console.log(`Selected: "${data.text}"`); console.log(`From: ${data.programName}`); }); hook.start(); ``` -------------------------------- ### Configuration Flow Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Demonstrates setting various configuration options before starting the hook, starting with additional configurations, modifying settings after start, and finally stopping and cleaning up. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Pre-start configuration (can be overridden by start(config)) hook.enableMouseMoveEvent(); hook.setClipboardMode( SelectionHook.FilterMode.EXCLUDE_LIST, ["vscode.exe", "cursor.exe"] ); hook.setGlobalFilterMode( SelectionHook.FilterMode.INCLUDE_LIST, ["google chrome", "firefox", "brave"] ); hook.setFineTunedList( SelectionHook.FineTunedListType.INCLUDE_CLIPBOARD_DELAY_READ, ["acrobat.exe"] ); // Start with additional config (overrides pre-start calls if specified) hook.start({ debug: true, enableMouseMoveEvent: false, // Overrides enableMouseMoveEvent() call above enableClipboard: true }); // Change configuration after start hook.on("text-selection", (data) => { console.log(`[${data.programName}] ${data.text}`); }); // Can still modify some settings after start hook.setSelectionPassiveMode(false); hook.setGlobalFilterMode(SelectionHook.FilterMode.DEFAULT); // Later: stop and restart hook.stop(); // ... do something else ... hook.start(); // Configuration persists // Clean up hook.cleanup(); ``` -------------------------------- ### Debug Configuration Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Example of enabling debug mode via the start() configuration. ```javascript hook.start({ debug: true }); // Console output: // [selection-hook] warnings and errors will be displayed ``` -------------------------------- ### Configuration Option 1: Pass config object to start() Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of configuring selection-hook by passing a configuration object directly to the `start()` method. ```javascript hook.start({ debug: true, enableClipboard: false, globalFilterMode: SelectionHook.FilterMode.EXCLUDE_LIST, globalFilterList: ["terminal.exe", "cmd.exe"], }); ``` -------------------------------- ### Configuration Option 2: Call individual methods Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of configuring selection-hook by calling individual configuration methods before or after `start()`. ```javascript hook.disableClipboard(); hook.setGlobalFilterMode(SelectionHook.FilterMode.EXCLUDE_LIST, ["terminal.exe", "cmd.exe"]); hook.start(); ``` -------------------------------- ### Linux Environment Info Example Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Example of how to get and interpret Linux environment information. ```javascript const info = hook.linuxGetEnvInfo(); // info = { // displayProtocol: 2, // SelectionHook.DisplayProtocol.WAYLAND // compositorType: 1, // SelectionHook.CompositorType.KWIN // hasInputDeviceAccess: true, // user can access input devices // isRoot: false // } ``` -------------------------------- ### Linux Environment Info and Start Configuration Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Example of checking Linux environment information and starting the hook with specific configurations, including a warning for Wayland without input device access. ```javascript const hook = new SelectionHook(); const envInfo = hook.linuxGetEnvInfo(); if (envInfo) { const isWayland = envInfo.displayProtocol === SelectionHook.DisplayProtocol.WAYLAND; if (isWayland && !envInfo.hasInputDeviceAccess) { console.warn("Wayland without input device access — limited functionality"); } hook.start({ enableClipboard: false, // Linux doesn't use clipboard fallback in native code debug: false }); } ``` -------------------------------- ### start() Method Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/api-reference/selectionhook-class.md Starts monitoring text selections and input events. This must be called before any events will be emitted. The hook can be started multiple times and will return immediately if already running. ```javascript const hook = new SelectionHook(); // Simple start hook.start(); // Start with configuration hook.start({ enableClipboard: true, enableMouseMoveEvent: false, debug: true }); ``` -------------------------------- ### Minimal Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/README.md A basic example demonstrating how to initialize the hook, listen for text selection events, and start monitoring. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); hook.on("text-selection", (data) => { console.log(`Selected: "${data.text}"`); console.log(`From: ${data.programName}`); console.log(`At: (${data.endBottom.x}, ${data.endBottom.y})`); }); hook.start(); ``` -------------------------------- ### Configuration via start(config) Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/README.md Example of configuring the hook using the start method with a configuration object. ```javascript hook.start({ debug: true, enableClipboard: true, enableMouseMoveEvent: false, globalFilterMode: SelectionHook.FilterMode.INCLUDE_LIST, globalFilterList: ["google chrome", "firefox"], clipboardMode: SelectionHook.FilterMode.EXCLUDE_LIST, clipboardFilterList: ["vscode.exe"], selectionPassiveMode: false }); ``` -------------------------------- ### Environment Detection Example Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Demonstrates how to detect the operating system and Wayland environment to handle selection monitoring and input device access. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); if (process.platform === "linux") { const info = hook.linuxGetEnvInfo(); if (info.displayProtocol === SelectionHook.DisplayProtocol.WAYLAND) { // Check compositor support if (info.compositorType === SelectionHook.CompositorType.MUTTER) { console.warn("Selection monitoring is not supported on GNOME Wayland."); // Disable the feature or inform the user } // Check input device access if (!info.hasInputDeviceAccess) { console.warn( "Limited functionality: no input device access.\n" + "Run: sudo usermod -aG input $USER\n" + "Then log out and log back in." ); } } } ``` -------------------------------- ### Start with Configuration Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Starts monitoring text selections with a configuration object. Only differing values from defaults are applied. ```javascript hook.start({ debug: true, enableClipboard: false, globalFilterMode: SelectionHook.FilterMode.EXCLUDE_LIST, globalFilterList: ["WindowsTerminal.exe", "cmd.exe"], }); ``` -------------------------------- ### Python Setuptools Installation Source: https://github.com/0xfullex/selection-hook/blob/main/README.md Command to install setuptools if ModuleNotFoundError occurs during build. ```bash pip install setuptools ``` -------------------------------- ### enableClipboard Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples of how to enable or disable clipboard fallback. ```javascript // Via start() config hook.start({ enableClipboard: false }); // Via method call (before start) hook.disableClipboard(); hook.start(); // Via method call (after start) hook.start(); hook.disableClipboard(); // Re-enable clipboard fallback hook.enableClipboard(); ``` -------------------------------- ### Complete Event Monitoring Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/events.md This example demonstrates how to register listeners for all available events provided by the Selection Hook library, including text selection, mouse events, keyboard events, status updates, and error handling. It also shows how to start monitoring and clean up resources on exit. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Register all event listeners hook.on("text-selection", (data) => { console.log(`[SELECTION] "${data.text}" from ${data.programName}`); }); hook.on("mouse-down", (data) => { console.log(`[MOUSE DOWN] Button ${data.button} at (${data.x}, ${data.y})`); }); hook.on("mouse-up", (data) => { console.log(`[MOUSE UP] Button ${data.button} at (${data.x}, ${data.y})`); }); hook.on("mouse-wheel", (data) => { const dir = data.flag > 0 ? "up" : "down"; console.log(`[MOUSE WHEEL] Scroll ${dir} at (${data.x}, ${data.y})`); }); hook.on("key-down", (data) => { console.log(`[KEY DOWN] ${data.uniKey}${data.sys ? " (with modifier)" : ""}`); }); hook.on("key-up", (data) => { console.log(`[KEY UP] ${data.uniKey}`); }); hook.on("status", (status) => { console.log(`[STATUS] ${status}`); }); hook.on("error", (error) => { console.error(`[ERROR] ${error.message}`); }); // Start monitoring hook.start({ debug: true }); // Clean up on exit process.on("SIGINT", () => { hook.cleanup(); process.exit(0); }); ``` -------------------------------- ### Linux Wayland Environment Information and Decision Tree Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of how to use `linuxGetEnvInfo()` to determine the Wayland environment and handle degradation. ```javascript const info = hook.linuxGetEnvInfo(); 1. info.displayProtocol === X11? └─→ Everything works normally. No special handling needed. 2. info.displayProtocol === WAYLAND: 2a. info.compositorType === MUTTER (GNOME)? └─→ ❌ Selection monitoring NOT supported Mutter does not implement the data-control protocol. → Inform user: this feature is unavailable on GNOME Wayland. 2b. info.hasInputDeviceAccess === false? └─→ ⚠️ Degraded mode (data-control debounce): - Text selection still works, but with a slight delay - Mouse/keyboard events are NOT available - posLevel is at most MOUSE_SINGLE → Prompt user: run `sudo usermod -aG input $USER` and re-login. 2c. info.hasInputDeviceAccess === true: └─→ ✅ Full functionality available. Cursor position accuracy depends on compositor: - KWIN, HYPRLAND → accurate logical coordinates - SWAY, WLROOTS, COSMIC → XWayland fallback (may freeze) → Check INVALID_COORDINATE on coordinates. 2d. [Electron only] Running under XWayland? └─→ selection-hook and Electron may use different coordinate spaces. → See Electron Integration section. ``` -------------------------------- ### SelectionConfig Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of how to use the SelectionConfig object when starting the SelectionHook. ```javascript const hook = new SelectionHook(); hook.start({ debug: true, enableClipboard: true, enableMouseMoveEvent: false, globalFilterMode: SelectionHook.FilterMode.INCLUDE_LIST, globalFilterList: ["google chrome", "firefox", "vscode"], clipboardMode: SelectionHook.FilterMode.EXCLUDE_LIST, clipboardFilterList: ["acrobat.exe", "wps.exe"] }); ``` -------------------------------- ### Fine-Tuned List Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples for applying special handling to specific applications using fine-tuned lists. ```javascript // Add delay for clipboard-heavy applications hook.setFineTunedList( SelectionHook.FineTunedListType.INCLUDE_CLIPBOARD_DELAY_READ, ["acrobat.exe", "wps.exe", "cajviewer.exe"] ); // Exclude specific programs from cursor detection hook.setFineTunedList( SelectionHook.FineTunedListType.EXCLUDE_CLIPBOARD_CURSOR_DETECT, ["some-special-app.exe"] ); ``` -------------------------------- ### Multi-Feature Configuration Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Provides a comprehensive setup with multiple features enabled, including debug mode, clipboard, mouse move events, clipboard filtering, global filtering, and selection passive mode. It also registers various event handlers for text selection, mouse down, key down, status, and errors. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Comprehensive configuration hook.start({ debug: true, enableClipboard: true, enableMouseMoveEvent: false, // Set true if you need cursor tracking clipboardMode: SelectionHook.FilterMode.EXCLUDE_LIST, clipboardFilterList: ["vscode.exe", "cursor.exe"], globalFilterMode: SelectionHook.FilterMode.INCLUDE_LIST, globalFilterList: ["google chrome", "firefox", "brave", "code"], selectionPassiveMode: false }); // Register all event handlers hook.on("text-selection", (data) => { console.log(`[SELECTION] ${data.programName}: "${data.text}"`); }); hook.on("mouse-down", (data) => { console.log(`[MOUSE DOWN] Button ${data.button}`); }); hook.on("key-down", (data) => { console.log(`[KEY] ${data.uniKey}`); }); hook.on("status", (status) => { console.log(`[STATUS] ${status}`); }); hook.on("error", (error) => { console.error(`[ERROR] ${error.message}`); }); ``` -------------------------------- ### Error Handling Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of listening for the 'error' event to log general and fatal errors. ```javascript hook.on("error", (error) => { console.error("SelectionHook error:", error.message); }); ``` -------------------------------- ### Basic Usage Source: https://github.com/0xfullex/selection-hook/blob/main/README.md Demonstrates how to install and use the selection-hook library to listen for text selection events, get current selection, and manage the hook's lifecycle. ```bash npm install selection-hook ``` ```javascript const SelectionHook = require("selection-hook"); const selectionHook = new SelectionHook(); // Listen for text selection events selectionHook.on("text-selection", (data) => { console.log("Selected text:", data.text); console.log("Program:", data.programName); console.log("Coordinates:", data.endBottom); }); // Start monitoring selectionHook.start(); // Get the current selection on demand const currentSelection = selectionHook.getCurrentSelection(); if (currentSelection) { console.log("Current selection:", currentSelection.text); } // Stop monitoring (can restart later) selectionHook.stop(); // Clean up when done selectionHook.cleanup(); ``` -------------------------------- ### LinuxEnvInfo Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of retrieving and using Linux environment information. ```javascript const hook = new SelectionHook(); const envInfo = hook.linuxGetEnvInfo(); if (envInfo) { console.log(`Display: ${envInfo.displayProtocol === SelectionHook.DisplayProtocol.X11 ? "X11" : "Wayland"}`); console.log(`Input access: ${envInfo.hasInputDeviceAccess}`); console.log(`Running as root: ${envInfo.isRoot}`); if (!envInfo.hasInputDeviceAccess) { console.warn("No input device access — mouse/keyboard events may not work on Wayland"); } } ``` -------------------------------- ### Configuration via Method Calls Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/README.md Example of configuring the hook using individual method calls before starting. ```javascript hook.enableClipboard(); hook.setGlobalFilterMode( SelectionHook.FilterMode.INCLUDE_LIST, ["chrome", "firefox"] ); hook.start(); ``` -------------------------------- ### Global Filter Mode Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples demonstrating how to configure the global filter mode to control which programs emit text selection events. ```javascript // Only monitor specific programs hook.setGlobalFilterMode( SelectionHook.FilterMode.INCLUDE_LIST, ["Google Chrome", "Firefox", "Code"] ); // Monitor all programs except specific ones hook.setGlobalFilterMode( SelectionHook.FilterMode.EXCLUDE_LIST, ["cursor.exe", "vscode.exe", "slack.exe"] ); // Disable filtering (monitor all) hook.setGlobalFilterMode(SelectionHook.FilterMode.DEFAULT); // Via start() config hook.start({ globalFilterMode: SelectionHook.FilterMode.INCLUDE_LIST, globalFilterList: ["chrome", "firefox", "brave"] }); ``` -------------------------------- ### clipboardMode & clipboardFilterList Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples of how to configure clipboard fallback behavior using modes and program lists. ```javascript // Only use clipboard fallback for specific programs hook.setClipboardMode( SelectionHook.FilterMode.INCLUDE_LIST, ["acrobat.exe", "wps.exe", "cajviewer.exe"] ); // Exclude specific programs from clipboard fallback hook.setClipboardMode( SelectionHook.FilterMode.EXCLUDE_LIST, ["chrome.exe", "firefox.exe"] ); // Reset to default (all programs, subject to enableClipboard setting) hook.setClipboardMode(SelectionHook.FilterMode.DEFAULT); // Via start() config hook.start({ clipboardMode: SelectionHook.FilterMode.EXCLUDE_LIST, clipboardFilterList: ["cursor.exe", "vscode.exe"] }); ``` -------------------------------- ### Installation Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/README.md Install the selection-hook package using npm. ```bash npm install selection-hook ``` -------------------------------- ### Selection Passive Mode Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples showing how to enable passive mode for the hook, requiring manual polling for selections. ```javascript // Enable passive mode hook.setSelectionPassiveMode(true); hook.start(); // Manually check for selections const selection = hook.getCurrentSelection(); if (selection) { console.log("Selected:", selection.text); } // Via start() config hook.start({ selectionPassiveMode: true }); ``` -------------------------------- ### macOS Accessibility Permissions (Node.js) Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of how to request Accessibility permissions in Node.js for selection-hook to function on macOS. ```javascript const hook = new SelectionHook(); if (!hook.macIsProcessTrusted()) { // Returns current status, may show a system dialog hook.macRequestProcessTrust(); console.log("Please grant Accessibility permission in System Settings, then restart."); process.exit(0); } hook.start(); ``` -------------------------------- ### Linux Build Dependencies Source: https://github.com/0xfullex/selection-hook/blob/main/README.md Commands to install build dependencies for Linux. ```bash # Ubuntu/Debian sudo apt install libevdev-dev libxtst-dev libx11-dev libxfixes-dev libwayland-dev # Fedora sudo dnf install libevdev-devel libXtst-devel libX11-devel libXfixes-devel wayland-devel # Arch sudo pacman -S libevdev libxtst libx11 libxfixes wayland ``` -------------------------------- ### Positioning UI elements based on selection data Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md This example demonstrates how to use the `posLevel` field to determine the appropriate coordinates for positioning UI elements relative to a text selection. ```javascript hook.on("text-selection", (data) => { let anchorPoint; switch (data.posLevel) { case SelectionHook.PositionLevel.NONE: // No coordinates available — use fallback (e.g., screen center or cursor query) break; case SelectionHook.PositionLevel.MOUSE_SINGLE: // Single point — show UI near the mouse position anchorPoint = { x: data.mousePosEnd.x, y: data.mousePosEnd.y + 16 }; break; case SelectionHook.PositionLevel.MOUSE_DUAL: // Drag selection — show UI near the end of the drag anchorPoint = { x: data.mousePosEnd.x, y: data.mousePosEnd.y + 16 }; break; case SelectionHook.PositionLevel.SEL_FULL: // Full paragraph coordinates — show UI below the last line anchorPoint = { x: data.endBottom.x, y: data.endBottom.y + 4 }; break; } }); ``` -------------------------------- ### text-selection Event Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/events.md An example demonstrating how to listen for the 'text-selection' event and log details about the selected text, program, and selection method. ```javascript const hook = new SelectionHook(); hook.on("text-selection", (data) => { console.log("=== Text Selection ==="); console.log(`Text: "${data.text}"`); console.log(`Program: ${data.programName}`); console.log(`Position: (${data.endBottom.x}, ${data.endBottom.y})`); const methodNames = { 1: "UI Automation", 3: "Accessibility API", 11: "AXAPI", 22: "PRIMARY Selection", 99: "Clipboard" }; console.log(`Method: ${methodNames[data.method] || "Unknown"}`); if (data.isFullscreen) { console.log("Window is fullscreen"); } }); hook.start(); ``` -------------------------------- ### enableMouseMoveEvent Configuration Examples Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md Examples of how to enable or disable the mouse move event listener. ```javascript // Via start() config hook.start({ enableMouseMoveEvent: true }); // Via method call (before start) hook.enableMouseMoveEvent(); hook.start(); // Via method call (after start) hook.start(); hook.enableMouseMoveEvent(); // Disable to reduce CPU usage hook.disableMouseMoveEvent(); ``` -------------------------------- ### Simple Selection Logger Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Logs every text selection with a timestamp. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); hook.on("text-selection", (data) => { const timestamp = new Date().toISOString(); console.log(`${timestamp} | ${data.programName}: "${data.text}"`); }); hook.start(); ``` -------------------------------- ### Low-Impact Monitoring Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Minimal resource usage configuration: monitor selections only from specific programs. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Low-impact config: monitor selections only from specific programs hook.start({ enableMouseMoveEvent: false, // No mouse tracking enableClipboard: false, // No clipboard fallback globalFilterMode: SelectionHook.FilterMode.INCLUDE_LIST, globalFilterList: ["code"] // Only monitor VS Code }); hook.on("text-selection", (data) => { // Minimal processing if (data.text.length > 0) { console.log("Selection:", data.text); } }); ``` -------------------------------- ### mouse-down Event Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/events.md An example demonstrating how to listen for the 'mouse-down' event and log the button pressed and mouse coordinates. ```javascript hook.on("mouse-down", (data) => { const buttons = { 0: "Left", 1: "Middle", 2: "Right", 3: "Back", 4: "Forward" }; const buttonName = buttons[data.button] || "Unknown"; console.log(`${buttonName} mouse button down at (${data.x}, ${data.y})`); }); hook.start(); ``` -------------------------------- ### Determining Program Names Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Commands to find program names on Linux systems. ```bash # Get window class names (X11) xprop WM_CLASS # Get process names ps aux | grep processname # Get Wayland window info swaymsg -t get_tree # for sway ``` -------------------------------- ### Mouse Wheel Event Listener Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of how to listen for and process mouse wheel scroll events. ```javascript hook.on("mouse-wheel", (data: MouseWheelEventData) => { const wheelType = data.button === 0 ? "Vertical" : "Horizontal"; const direction = data.flag > 0 ? "Up" : "Down"; console.log(`${wheelType} scroll ${direction} at (${data.x}, ${data.y})`); }); hook.start(); ``` -------------------------------- ### Mouse Up Event Listener Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Example of listening for the 'mouse-up' event. ```javascript hook.on("mouse-up", (data) => { // data contains mouse coordinates and button info }); ``` -------------------------------- ### Usage Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Demonstrates how to use the SelectionHookConstructor type. ```typescript import SelectionHook, { SelectionHookConstructor } from "selection-hook"; const HookClass: SelectionHookConstructor = SelectionHook; const instance = new HookClass(); ``` -------------------------------- ### Key Down Event Listener Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Example of listening for the 'key-down' event. ```javascript hook.on("key-down", (data) => { // data contains key code and modifier info }); ``` -------------------------------- ### Default Configuration Object Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md The default configuration object used when `start()` is called without arguments. ```javascript { debug: false, enableMouseMoveEvent: false, enableClipboard: true, selectionPassiveMode: false, clipboardMode: SelectionHook.FilterMode.DEFAULT, globalFilterMode: SelectionHook.FilterMode.DEFAULT, clipboardFilterList: [], globalFilterList: [] } ``` -------------------------------- ### Mouse Wheel Event Listener Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Example of listening for the 'mouse-wheel' event. ```javascript hook.on("mouse-wheel", (data) => { // data contains wheel direction info }); ``` -------------------------------- ### Status Event Listener Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Example of listening for the 'status' event. ```javascript hook.on("status", (status) => { // status is a string, e.g. "started", "stopped" }); ``` -------------------------------- ### Recommended Settings for Windows Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md A JavaScript example demonstrating recommended configuration settings for the selection-hook on Windows. ```javascript const hook = new SelectionHook(); hook.start({ enableClipboard: true, // Use clipboard fallback for legacy apps clipboardMode: SelectionHook.FilterMode.EXCLUDE_LIST, clipboardFilterList: ["cursor.exe", "vscode.exe"], // Avoid clipboard in modern apps globalFilterMode: SelectionHook.FilterMode.DEFAULT, // Monitor all apps debug: false }); ``` -------------------------------- ### Graceful Startup Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Proper initialization with error handling, including platform-specific accessibility checks for macOS. ```javascript const SelectionHook = require("selection-hook"); function initializeHook() { try { const hook = new SelectionHook(); // Check platform-specific requirements if (process.platform === "darwin") { if (!hook.macIsProcessTrusted()) { console.warn("App needs accessibility permissions on macOS"); hook.macRequestProcessTrust(); } } if (!hook.start()) { console.error("Failed to start hook"); return null; } console.log("Hook started successfully"); return hook; } catch (err) { console.error("Failed to initialize hook:", err.message); return null; } } const hook = initializeHook(); if (hook) { hook.on("text-selection", (data) => { console.log("Selection:", data.text); }); } ``` -------------------------------- ### Recommended Settings for macOS Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/configuration.md A JavaScript example showing recommended configuration settings for the selection-hook on macOS, including permission checks. ```javascript const hook = new SelectionHook(); // Check accessibility permissions first if (!hook.macIsProcessTrusted()) { console.log("Requesting accessibility permissions..."); hook.macRequestProcessTrust(); } hook.start({ enableClipboard: true, debug: false }); ``` -------------------------------- ### Shortcut Trigger Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of enabling passive mode and triggering selection retrieval via an external shortcut. ```javascript hook.setSelectionPassiveMode(true); hook.start(); // External shortcut triggers this function function onShortcutPressed() { const selection = hook.getCurrentSelection(); if (selection) { processSelection(selection); } } ``` -------------------------------- ### macOS Accessibility Permissions (Electron) Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of how to check and request Accessibility permissions in Electron for selection-hook on macOS. ```javascript const { systemPreferences } = require("electron"); if (!systemPreferences.isTrustedAccessibilityClient(false)) { // Show prompt to user systemPreferences.isTrustedAccessibilityClient(true); // Guide user to System Settings > Privacy & Security > Accessibility } ``` -------------------------------- ### Modifier Key Trigger Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Example of enabling passive mode and listening for a modifier key hold to trigger selection retrieval. ```javascript // Enable passive mode — no automatic text-selection events hook.setSelectionPassiveMode(true); hook.start(); // Listen for a modifier key hold let keyDownTime = 0; hook.on("key-down", (data) => { // Check for Ctrl key (Windows vkCode: 162/163) if (data.vkCode === 162 || data.vkCode === 163) { if (keyDownTime === 0) keyDownTime = Date.now(); // Trigger after holding for 500ms if (Date.now() - keyDownTime > 500) { const selection = hook.getCurrentSelection(); if (selection) { console.log("Selected text:", selection.text); } keyDownTime = -1; // Prevent re-trigger } } }); hook.on("key-up", (data) => { if (data.vkCode === 162 || data.vkCode === 163) { keyDownTime = 0; } }); ``` -------------------------------- ### Checking coordinate validity Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md This example shows how to check if coordinate data is valid before using it for positioning UI elements, using `INVALID_COORDINATE`. ```javascript if (data.mousePosEnd.x !== SelectionHook.INVALID_COORDINATE) { // Coordinates are valid — use them showToolbar(data.mousePosEnd.x, data.mousePosEnd.y); } ``` -------------------------------- ### Detect Keyboard Shortcuts Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Demonstrates how to detect specific key combinations like Ctrl+C and Ctrl+Shift+S using key-down and key-up events. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); const keysPressed = new Set(); hook.on("key-down", (data) => { keysPressed.add(data.uniKey); // Detect Ctrl+C if (keysPressed.has("Control") && keysPressed.has("c")) { console.log("User pressed Ctrl+C"); } // Detect Ctrl+Shift+S if (keysPressed.has("Control") && keysPressed.has("Shift") && keysPressed.has("s")) { console.log("User pressed Ctrl+Shift+S"); } }); hook.on("key-up", (data) => { keysPressed.delete(data.uniKey); }); hook.start(); ``` -------------------------------- ### Status Event Listener Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/events.md Example of listening for the 'status' event to be notified of changes in the hook's operational status (e.g., started, stopped). ```javascript hook.on("status", (status: string) => {}) ``` -------------------------------- ### Electron App Integration Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Shows how to integrate selection-hook into an Electron application, handling initialization in the main process, sending selection data to the renderer process, and providing IPC handlers for controlling the hook and cleaning up on app exit. ```javascript const { ipcMain } = require("electron"); const SelectionHook = require("selection-hook"); let hook = null; // Main process: initialize hook function initializeHook() { hook = new SelectionHook(); hook.on("text-selection", (data) => { // Send selection to renderer process mainWindow.webContents.send("selection-changed", { text: data.text, program: data.programName, position: { x: data.endBottom.x, y: data.endBottom.y } }); }); hook.start(); } // Renderer process can control the hook pcMain.handle("get-current-selection", async () => { return hook ? hook.getCurrentSelection() : null; }); pcMain.handle("set-global-filter", async (event, mode, programs) => { if (hook) { return hook.setGlobalFilterMode(mode, programs); } return false; }); // Clean up on app exit app.on("before-quit", () => { if (hook) { hook.cleanup(); } }); ``` -------------------------------- ### stop() Method Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/api-reference/selectionhook-class.md Stops monitoring text selections and input events. The hook can be restarted later by calling start() again. Resources are kept in memory until cleanup() is called. ```javascript hook.on("text-selection", (data) => { console.log("Selected:", data.text); }); hook.start(); // ... do work ... hook.stop(); // Pause monitoring // ... later ... hook.start(); // Resume monitoring ``` -------------------------------- ### Check Environment Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/platform-guide.md Checks the current environment to detect the display protocol (Wayland or X11) and input device access. ```javascript const hook = new SelectionHook(); const envInfo = hook.linuxGetEnvInfo(); if (envInfo) { if (envInfo.displayProtocol === SelectionHook.DisplayProtocol.WAYLAND) { console.log("Wayland detected"); console.log(`Compositor: ${compositorName(envInfo.compositorType)}`); console.log(`Input access: ${envInfo.hasInputDeviceAccess}`); if (!envInfo.hasInputDeviceAccess) { console.warn("Input device access required for mouse/keyboard events"); } } } function compositorName(type) { const names = ["Unknown", "KWin", "Mutter", "Hyprland", "Sway", "Wlroots", "COSMIC"]; return names[type] || "Unknown"; } ``` -------------------------------- ### Lifecycle Management in Electron Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Demonstrates how to tie the selection-hook lifecycle to the Electron app lifecycle, ensuring proper cleanup. ```javascript const { app } = require("electron"); app.on("will-quit", () => { hook.stop(); hook.cleanup(); }); ``` -------------------------------- ### SelectionHookInstance Usage Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example demonstrating the usage of the SelectionHookInstance type alias. ```typescript let hook: SelectionHookInstance; hook = new SelectionHook(); ``` -------------------------------- ### Electron Main Process Integration Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Shows how to integrate selection-hook into the Electron main process and forward selection events to the renderer via IPC. ```javascript // Main process const SelectionHook = require("selection-hook"); const { ipcMain, BrowserWindow } = require("electron"); const hook = new SelectionHook(); hook.on("text-selection", (data) => { const win = BrowserWindow.getFocusedWindow(); if (win) { win.webContents.send("selection:text-selected", data); } }); hook.start(); ``` -------------------------------- ### Electron App Configuration in .desktop file Source: https://github.com/0xfullex/selection-hook/blob/main/docs/LINUX.md Configuration for running an Electron application with XWayland via a .desktop file. ```ini # In your .desktop file Exec=your-electron-app --ozone-platform=x11 %U ``` -------------------------------- ### Example Usage of MouseEventData Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of how to use the SelectionHook to listen for mouse down events and access MouseEventData. ```javascript hook.on("mouse-down", (data: MouseEventData) => { const buttonName = ["Left", "Middle", "Right", "Back", "Forward"][data.button] || "Unknown"; console.log(`${buttonName} click at (${data.x}, ${data.y})`); }); hook.start(); ``` -------------------------------- ### Example Usage of TextSelectionData Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of how to use the SelectionHook to listen for text selection events and access TextSelectionData. ```javascript const hook = new SelectionHook(); hook.on("text-selection", (data: TextSelectionData) => { console.log(`Selected: "${data.text}"`); console.log(`From: ${data.programName}`); console.log(`Position: (${data.startBottom.x}, ${data.startBottom.y})`); if (data.method === SelectionHook.SelectionMethod.CLIPBOARD) { console.log("Used clipboard fallback"); } }); hook.start(); ``` -------------------------------- ### Constructor Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/api-reference/selectionhook-class.md Creates a new SelectionHook instance. The constructor initializes the native module binding and prepares the hook for use. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); if (!hook) { console.error("Failed to initialize SelectionHook"); process.exit(1); } ``` -------------------------------- ### Fine-Tuned Application Support Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/usage-examples.md Configures special handling for known applications, including adding delays for PDF readers and office apps, excluding cursor detection for specific apps, and using the clipboard only for designated programs. ```javascript const SelectionHook = require("selection-hook"); const hook = new SelectionHook(); // Add delay for PDF readers and office apps hook.setFineTunedList( SelectionHook.FineTunedListType.INCLUDE_CLIPBOARD_DELAY_READ, ["acrobat.exe", "wps.exe", "cajviewer.exe", "winword.exe", "excel.exe"] ); // Exclude cursor detection for specific apps hook.setFineTunedList( SelectionHook.FineTunedListType.EXCLUDE_CLIPBOARD_CURSOR_DETECT, ["some-special-app.exe"] ); // Use clipboard only for these programs hook.setClipboardMode( SelectionHook.FilterMode.INCLUDE_LIST, ["acrobat.exe", "wps.exe"] ); hook.start(); ``` -------------------------------- ### Constructor Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Creates a new SelectionHook instance and initializes the native module. ```javascript const hook = new SelectionHook(); ``` -------------------------------- ### Linux Clipboard Workaround Source: https://github.com/0xfullex/selection-hook/blob/main/docs/GUIDE.md Explains how to use Electron's clipboard API as a workaround for the limitations of `writeToClipboard()` and `readFromClipboard()` on Linux. ```javascript const { clipboard } = require("electron"); function writeClipboard(text) { if (process.platform === "linux") { clipboard.writeText(text); return true; } return hook.writeToClipboard(text); } ``` -------------------------------- ### Clipboard Fallback Configuration Source: https://github.com/0xfullex/selection-hook/blob/main/docs/API.md Examples demonstrating how to configure clipboard fallback modes for specific applications. ```javascript hook.setClipboardMode(SelectionHook.FilterMode.INCLUDE_LIST, [ "acrobat.exe", "wps.exe" ]); hook.setClipboardMode(SelectionHook.FilterMode.EXCLUDE_LIST, [ "code.exe", "devenv.exe" ]); ``` -------------------------------- ### Keyboard Event Listener Example Source: https://github.com/0xfullex/selection-hook/blob/main/_autodocs/types.md Example of how to listen for and process key down events, including modifier key checks and platform-specific scan code retrieval. ```javascript hook.on("key-down", (data: KeyboardEventData) => { console.log(`Key pressed: ${data.uniKey} (vkCode: ${data.vkCode})`); if (data.sys) { console.log("Modifier key held"); } if (process.platform === "win32" && data.scanCode) { console.log(`Scan code: ${data.scanCode}`); } }); hook.start(); ```