### Setup and Run X11 Debugging Example Source: https://github.com/enigo-rs/enigo/blob/main/DEBUGGING.md Clone the x11rb repository, navigate to the xtrace-example directory, build it, and then use it to run the Enigo keyboard example with X11 features enabled. ```bash git clone https://github.com/psychon/x11rb.git cd x11rb/xtrace-example cargo run # The output of the command will tell you how to use it. # Example: # /home/pentamassiv/x11rb/target/debug/xtrace-example cargo run --example keyboard --features x11rb ``` -------------------------------- ### Create Enigo with Default Settings Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Instantiate Enigo using its default configuration. This is the simplest way to get started. ```rust let enigo = Enigo::new(&Settings::default()).unwrap(); ``` -------------------------------- ### Run Keyboard Example with Debug Logging Source: https://github.com/enigo-rs/enigo/blob/main/DEBUGGING.md Execute the keyboard example with general debug logging enabled for RUST_LOG, WAYLAND_DEBUG, and REIS_DEBUG. ```bash RUST_LOG=debug WAYLAND_DEBUG=1 REIS_DEBUG=1 cargo run --example keyboard ``` -------------------------------- ### Minimal Enigo Configuration Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/configuration.md Initializes Enigo with default settings. This is the simplest way to get started with the library. ```rust use enigo::{Enigo, Settings}; let enigo = Enigo::new(&Settings::default()).unwrap(); ``` -------------------------------- ### Install development libraries on Fedora Source: https://github.com/enigo-rs/enigo/blob/main/README.md Installs libX11-devel and libxdo-devel, which are required for input simulation on Fedora systems. ```Bash dnf install libX11-devel libxdo-devel ``` -------------------------------- ### Debug X11 Specific Logging in Keyboard Example Source: https://github.com/enigo-rs/enigo/blob/main/DEBUGGING.md Run the keyboard example with debug logging specifically for the enigo::platform::x11 module, using the x11rb feature and disabling default features. ```bash RUST_LOG=enigo::platform::x11=debug cargo run --example keyboard --features x11rb --no-default-features ``` -------------------------------- ### Install xdotool on Gentoo Source: https://github.com/enigo-rs/enigo/blob/main/README.md Installs the xdotool package using emerge for Gentoo Linux. ```Bash emerge -a xdotool ``` -------------------------------- ### Keyboard Input Simulation Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Demonstrates how to use the Enigo library to simulate keyboard input for named keys and Unicode characters, including emoji. ```rust use enigo::{Enigo, Keyboard, Key, Direction::Click, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Named key enigo.key(Key::Return, Click).unwrap(); // Unicode character enigo.key(Key::Unicode('é'), Click).unwrap(); // Emoji enigo.key(Key::Unicode('🔥'), Click).unwrap(); ``` -------------------------------- ### Install libxdo-dev on Debian-based systems Source: https://github.com/enigo-rs/enigo/blob/main/README.md Installs the necessary development library for X11 input simulation on Debian-based Linux distributions. ```Bash apt install libxdo-dev ``` -------------------------------- ### Basic Enigo Usage Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Demonstrates basic input simulation using Enigo, including typing text, moving the mouse, performing clicks, and executing keyboard shortcuts. ```rust use enigo::{ Button, Coordinate, Direction::{Click, Press, Release}, Enigo, Key, Keyboard, Mouse, Settings, }; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Type text enigo.text("Hello World").unwrap(); // Move mouse enigo.move_mouse(500, 200, Coordinate::Abs).unwrap(); // Click enigo.button(Button::Left, Click).unwrap(); // Keyboard shortcut enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('a'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); ``` -------------------------------- ### Install xdotool on Arch Linux Source: https://github.com/enigo-rs/enigo/blob/main/README.md Installs the xdotool package, which may be required for certain input simulation functionalities on Arch Linux. ```Bash pacman -S xdotool ``` -------------------------------- ### Log Everything Including X11 and Wayland Source: https://github.com/enigo-rs/enigo/blob/main/DEBUGGING.md Execute the keyboard example with comprehensive debug logging enabled for RUST_LOG, WAYLAND_DEBUG, REIS_DEBUG, and using the x11rb xtrace-example for X11 messages, along with Wayland features. ```bash RUST_LOG=debug WAYLAND_DEBUG=1 REIS_DEBUG=1 /home/pentamassiv/x11rb/target/debug/xtrace-example cargo run --example keyboard --features x11rb,wayland --no-default-features ``` -------------------------------- ### Rust Keyboard Input Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/modules-and-traits.md Demonstrates how to use the Keyboard trait methods to input text, send named keys, and perform key combinations. Ensure Enigo and necessary types are imported. ```rust use enigo::{Enigo, Keyboard, Key, Direction::{Press, Release, Click}, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Text input enigo.text("Hello World!").unwrap(); // Named key enigo.key(Key::Return, Click).unwrap(); // Modifier + key combination enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('a'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); // Raw scancode enigo.raw(0x1E, Click).unwrap(); // 'A' on QWERTY ``` -------------------------------- ### Mouse Movement Example with Coordinate Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Demonstrates how to use the Coordinate enum to move the mouse to an absolute position and then relative to the current position. Requires Enigo and Settings imports. ```rust use enigo::{Enigo, Mouse, Coordinate::{Abs, Rel}, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Move to absolute (500, 200) enigo.move_mouse(500, 200, Abs).unwrap(); // Move 100 pixels right relative to current position enigo.move_mouse(100, 0, Rel).unwrap(); ``` -------------------------------- ### Windows Specific Enigo Code Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Execute Enigo code only on Windows using `#[cfg(target_os = "windows")]`. This example sets DPI awareness. ```rust #[cfg(target_os = "windows")] { enigo::set_dpi_awareness().unwrap(); } ``` -------------------------------- ### Simulate Mouse Drag Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md This example demonstrates how to simulate a mouse drag operation. It involves pressing the mouse button, moving the cursor, and then releasing the button. ```rust // Drag 200 pixels right enigo.button(Button::Left, Press).unwrap(); enigo.move_mouse(200, 0, Rel).unwrap(); enigo.button(Button::Left, Release).unwrap(); ``` -------------------------------- ### Rust Mouse Input and Query Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/modules-and-traits.md Shows how to use the Mouse trait to query display dimensions and cursor location, move the mouse, perform clicks, drag operations, and scroll. Ensure necessary imports are included. ```rust use enigo::{Enigo, Mouse, Button, Direction::{Press, Release, Click}, Coordinate::{Abs, Rel}, Axis::Vertical, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Query display let (width, height) = enigo.main_display().unwrap(); println!("Display: {}x{}", width, height); // Query cursor position let (x, y) = enigo.location().unwrap(); println!("Cursor at ({}, {})", x, y); // Move cursor enigo.move_mouse(500, 200, Abs).unwrap(); // Click enigo.button(Button::Left, Click).unwrap(); // Drag enigo.button(Button::Left, Press).unwrap(); enigo.move_mouse(200, 100, Rel).unwrap(); enigo.button(Button::Left, Release).unwrap(); // Scroll enigo.scroll(5, Vertical).unwrap(); ``` -------------------------------- ### Keyboard Shortcuts Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Simulate keyboard shortcuts by pressing and releasing modifier keys and other keys. Examples include Ctrl+C, Ctrl+A, and Alt+Tab. ```APIDOC ## Keyboard Shortcuts ### Description Simulate keyboard shortcuts by pressing and releasing modifier keys and other keys. Examples include Ctrl+C, Ctrl+A, and Alt+Tab. ### Method ```rust // Ctrl+C (copy) enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('c'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); // Ctrl+A (select all) enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('a'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); // Alt+Tab enigo.key(Key::Alt, Press).unwrap(); enigo.key(Key::Tab, Click).unwrap(); enigo.key(Key::Alt, Release).unwrap(); ``` ``` -------------------------------- ### Scrolling Example with Axis Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Shows how to perform horizontal and vertical scrolling using the Axis enum. Requires Enigo, Mouse, Axis, and Settings imports. ```rust use enigo::{Enigo, Mouse, Axis::{Vertical, Horizontal}, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Scroll down 5 notches enigo.scroll(5, Vertical).unwrap(); // Scroll left 2 notches enigo.scroll(-2, Horizontal).unwrap(); ``` -------------------------------- ### NewConError Display Output Examples Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Illustrates the string representations for different NewConError variants. These messages can be helpful for user feedback. ```text "no connection could be established: (X11 connection denied)" ``` ```text "the application does not have the permission to simulate input" ``` ```text "there were no empty keycodes that could be used" ``` -------------------------------- ### Handling Input Simulation Errors Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Shows an example of how to handle potential InputErrors when simulating text input, specifically catching InvalidInput and Simulate errors. ```rust use enigo::{Enigo, Keyboard, InputError, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); match enigo.text("hello\0world") { Ok(()) => println!("Text entered successfully"), Err(InputError::InvalidInput(msg)) => eprintln!("Invalid input: {}", msg), Err(InputError::Simulate(msg)) => eprintln!("Simulation error: {}", msg), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Control Mouse Movement Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Use these examples to move the mouse cursor to absolute screen coordinates or relative to its current position. Ensure the Enigo instance is initialized. ```rust // Move to absolute position enigo.move_mouse(500, 200, Abs).unwrap(); // Move relative to current enigo.move_mouse(100, 50, Rel).unwrap(); // Get current position let (x, y) = enigo.location().unwrap(); ``` -------------------------------- ### Rust Agent Token Execution Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/modules-and-traits.md Demonstrates executing a sequence of actions defined as Token variants using the Agent trait's execute method. This allows for batch processing of input commands. ```rust use enigo::{Enigo, Agent, Settings, agent::Token, Button, Direction::Click}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let actions = vec![ Token::Text("Hello".to_string()), Token::Button(Button::Left, Click), Token::Scroll(5, Axis::Vertical), ]; for token in actions { enigo.execute(&token).unwrap(); } ``` -------------------------------- ### Control Keyboard Input with Direction Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Shows how to press, release, or click keyboard keys using the Direction enum. This example demonstrates modifier key usage. ```rust use enigo::{Enigo, Direction::{Press, Release, Click}, Key, Keyboard, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('c'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); ``` -------------------------------- ### macOS Smooth Scrolling Example Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Shows how to perform pixel-based smooth scrolling on macOS using the `smooth_scroll` method. This feature provides a smoother scrolling experience compared to traditional wheel-based scrolling. ```rust #[cfg(all(feature = "platform_specific", target_os = "macos"))] enigo.smooth_scroll(100, Axis::Vertical).unwrap(); ``` -------------------------------- ### Basic Input Simulation with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/README.md Demonstrates initializing Enigo and performing mouse movements, clicks, and text input. Ensure Enigo is properly initialized before use. ```Rust let mut enigo = Enigo::new(&Settings::default()).unwrap(); enigo.move_mouse(500, 200, Abs).unwrap(); enigo.button(Button::Left, Click).unwrap(); enigo.text("Hello World! here is a lot of text ❤️").unwrap(); ``` -------------------------------- ### Enigo::new Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Creates a new Enigo instance with the specified settings. This is the entry point for all input simulation operations. ```APIDOC ## Enigo::new ### Description Initializes a new `Enigo` instance. This method allows for custom settings to be applied to the input simulation. ### Method Associated function (constructor) ### Parameters - **settings** (`&Settings`) - Required - The settings to configure the Enigo instance. ### Response #### Success Response (Ok) - `Enigo` - An initialized Enigo instance. #### Error Response (Err) - `InputError` - If initialization fails. ### Request Example ```rust use enigo::Settings; let enigo = Enigo::new(&Settings::default()).unwrap(); ``` ``` -------------------------------- ### Windows Raw Key Input (Virtual vs. Extended) Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Demonstrates sending raw key input using Enigo, differentiating between regular and extended keys on Windows. Extended keys require a prefix to indicate their special nature. ```rust // Regular key enigo.raw(0x1D, Click).unwrap(); // Left Ctrl // Extended key (right side) // Windows: set high byte to indicate extended enigo.raw(0xE01D, Click).unwrap(); // Right Ctrl (0xE0 = extended bit) ``` -------------------------------- ### Enigo::new Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Initializes a new Enigo instance with custom settings. This is the primary way to create an Enigo object for interacting with the system's input devices. ```APIDOC ## Enigo::new ### Description Initializes a new `Enigo` instance with the provided `Settings`. This method allows for custom configuration of the input simulation environment. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **settings** (`&Settings`) - Required - The configuration settings for the Enigo instance. ### Request Example ```rust let settings = Settings { x11_display: None, wayland_display: None, windows_dw_extra_info: None, event_source_user_data: None, release_keys_when_dropped: true, open_prompt_to_get_permissions: true, independent_of_keyboard_state: true, windows_subject_to_mouse_speed_and_acceleration_level: false, restore_token: None, }; let enigo = Enigo::new(&settings); ``` ### Response #### Success Response - **Enigo** - An initialized `Enigo` instance. #### Error Response - **NewConError** - An error if the Enigo instance cannot be created. #### Response Example ```rust Result ``` ``` -------------------------------- ### Handling NewConError::EstablishCon on Windows Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Demonstrates how to handle the `EstablishCon` error when initializing Enigo on Windows. It suggests running with administrator privileges if permission-related issues are suspected. ```rust use enigo::{Enigo, NewConError, Settings}; match Enigo::new(&Settings::default()) { Ok(enigo) => println!("Connected"), Err(NewConError::EstablishCon(msg)) => { eprintln!("Cannot establish connection: {}", msg); eprintln!("Try running with Administrator privileges"); } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Input Text and Mouse Click with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/README.md Demonstrates how to input text and perform a left mouse click using the Enigo library. Ensure necessary imports are included. ```rust use enigo::{Enigo, Keyboard, Mouse, Button, Direction::Click, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); enigo.text("Hello World").unwrap(); enigo.button(Button::Left, Click).unwrap(); ``` -------------------------------- ### Set DPI Awareness on Windows Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md On Windows, call `set_dpi_awareness()` to resolve mouse coordinate mismatches on high-DPI displays or multi-monitor setups with different DPIs. ```rust #[cfg(target_os = "windows")] enigo::set_dpi_awareness().unwrap(); ``` -------------------------------- ### Enigo::new() Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Creates a new Enigo instance for simulating input. This function establishes a connection to the appropriate display server based on the operating system and initializes the necessary state for input simulation. It accepts a `Settings` struct to configure the connection behavior. ```APIDOC ## Enigo::new() ### Description Creates a new `Enigo` instance to establish a connection for input simulation. ### Method `new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **settings** (`&Settings`) - Required - Configuration for the connection. Use `Settings::default()` for standard behavior. ### Return Type `Result` ### Throws - `NewConError::NoPermission` (macOS): If the application lacks input simulation permissions. - `NewConError::EstablishCon(description)`: If connection to the display server fails. - `NewConError::NoEmptyKeycodes` (Linux): If the keymap is full. - `NewConError::Reply`: If there is a protocol error. ### Example ```rust use enigo::{Enigo, Settings}; // Default settings let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Custom settings let mut settings = Settings::default(); settings.release_keys_when_dropped = false; let mut enigo = Enigo::new(&settings).unwrap(); ``` ``` -------------------------------- ### macOS Specific Enigo Code Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Execute Enigo code only on macOS using `#[cfg(target_os = "macos")]`. This example demonstrates smooth scrolling. ```rust #[cfg(target_os = "macos")] { // macOS-specific code enigo.smooth_scroll(100, Axis::Vertical).unwrap(); } ``` -------------------------------- ### Screen Recording Helper with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md This snippet demonstrates how to create a screen recording helper using Enigo. It captures screen dimensions and simulates user interactions, storing them as tokens. Serialization to JSON is supported if the 'serde' feature is enabled. ```rust use enigo::{Enigo, Mouse, Keyboard, Button, Key, Direction::*, Coordinate::*, agent::Token, Agent, Settings}; use std::thread; use std::time::Duration; fn main() -> Result<(), Box> { let mut enigo = Enigo::new(&Settings::default())?; // Get screen dimensions let (width, height) = enigo.main_display()?; println!("Screen: {}x{}", width, height); // Record actions let mut actions = Vec::new(); // Simulate interaction enigo.move_mouse(width / 2, height / 2, Coordinate::Abs)?; actions.push(Token::MoveMouse(width / 2, height / 2, Coordinate::Abs)); thread::sleep(Duration::from_millis(500)); enigo.button(Button::Left, Direction::Click)?; actions.push(Token::Button(Button::Left, Direction::Click)); // Serialize actions #[cfg(feature = "serde")] { let json = serde_json::to_string(&actions)?; println!("Recorded: {}", json); } Ok(()) } ``` -------------------------------- ### Handling NoEmptyKeycodes Error Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Example of how to catch and handle the InputError::NoEmptyKeycodes error. It shows dropping the current instance and creating a new one as a recovery step. ```rust use enigo::{Enigo, Keyboard, InputError, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); match enigo.text("some text") { Ok(()) => {}, // Operation successful Err(InputError::NoEmptyKeycodes) => { eprintln!("Keymap exhausted. Drop the instance and create a new one."); drop(enigo); // Release keycodes let enigo = Enigo::new(&Settings::default()).unwrap(); // Create a new instance } Err(e) => eprintln!("Error: {}", e), // Handle other errors } ``` -------------------------------- ### Manage Session Tokens with libei Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Demonstrates how to use session tokens with the libei backend for restoring previous input simulation sessions. This involves loading a token, creating an Enigo instance, and saving a new token. ```rust let mut settings = Settings::default(); // Try to restore previous session if let Some(token) = load_previous_token() { settings.restore_token = Some(token); } let enigo = Enigo::new(&settings)?; // Save new token for next session if let Some(new_token) = enigo.restore_token() { save_token(new_token); } ``` -------------------------------- ### Get Current Mouse Location with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Obtains the current cursor's X and Y coordinates in pixels. This is useful for tracking the mouse position or for relative input simulations. ```rust use enigo::{Enigo, Mouse, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let (x, y) = enigo.location().unwrap(); println!("Mouse is at ({}, {})", x, y); ``` -------------------------------- ### Execute Input Actions with Agent Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Demonstrates how to create a vector of Token variants and execute them sequentially using the Enigo Agent. This is useful for scripting a series of input actions. ```rust use enigo::{Enigo, Agent, Settings, agent::Token, Button, Direction::Click, Coordinate::Abs, Axis::Vertical}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let tokens = vec![ Token::Text("Hello".to_string()), Token::MoveMouse(500, 200, Abs), Token::Button(Button::Left, Click), Token::Scroll(5, Vertical), ]; for token in tokens { enigo.execute(&token).unwrap(); } ``` -------------------------------- ### Get Main Display Dimensions with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Retrieves the width and height of the primary display in pixels. This function is useful for understanding the screen's resolution for input simulation. ```rust use enigo::{Enigo, Mouse, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let (width, height) = enigo.main_display().unwrap(); println!("Display: {}x{}", width, height); ``` -------------------------------- ### Create Enigo with Custom Settings Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Configure Enigo with specific settings before instantiation. This allows for fine-tuning behavior on different operating systems. ```rust let mut settings = Settings::default(); settings.release_keys_when_dropped = true; // Default: true settings.open_prompt_to_get_permissions = true; // macOS only, default: true settings.independent_of_keyboard_state = true; // macOS only, default: true settings.x11_display = Some(":0".to_string()); // Linux X11 settings.wayland_display = Some("wayland-0".to_string()); // Linux Wayland settings.windows_dw_extra_info = Some(100); // Windows event marker settings.event_source_user_data = Some(100); // macOS event marker settings.windows_subject_to_mouse_speed_and_acceleration_level = false; // Windows let enigo = Enigo::new(&settings).unwrap(); ``` -------------------------------- ### Get Cursor Position with x11rb Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Obtain the current X and Y coordinates of the mouse cursor using the x11rb backend. This is useful for tracking user interaction or for relative positioning. ```rust // Get cursor position let (x, y) = enigo.location()?; ``` -------------------------------- ### Get Main Display Size with x11rb Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Retrieve the dimensions of the primary display using the x11rb backend. This function is essential for positioning elements or determining screen boundaries. ```rust // Get current display size let (width, height) = enigo.main_display()?; ``` -------------------------------- ### Windows Specific Key Input Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Shows how to use Windows-specific virtual key codes for keyboard input. For cross-platform compatibility, `Key::Unicode()` is recommended. ```rust #[cfg(target_os = "windows")] { enigo.key(Key::A, Click).unwrap(); // VK_A (only on Windows) } enigo.key(Key::Unicode('a'), Click).unwrap(); // Works everywhere ``` -------------------------------- ### Basic Usage Template Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md This is the basic template for using the Enigo library. It includes necessary imports and the initialization of an Enigo instance. ```rust use enigo::{Enigo, Settings, Keyboard, Mouse, Button, Key, Direction::*, Coordinate::*, Axis::*}; fn main() { let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Use enigo here } ``` -------------------------------- ### Check Display Connection on Linux Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Verify display server connection details on Linux using `echo` and `xdpyinfo` for X11, or by checking environment variables for Wayland. ```bash # X11 echo $DISPLAY xdpyinfo # Wayland echo $WAYLAND_DISPLAY echo $XDG_SESSION_TYPE ``` -------------------------------- ### Handling Invalid Input Errors Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Demonstrates how to handle InputError::InvalidInput, which occurs when the application provides malformed data. Includes examples of checking for NULL bytes and validating input before simulation. ```rust use enigo::{Enigo, Keyboard, InputError, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Bad: text with NULL bytes match enigo.text("hello\0world") { Ok(()) => {}, Err(InputError::InvalidInput(msg)) => { eprintln!("Invalid input: {}", msg); } Err(e) => eprintln!("Other error: {}", e), } // Good: validate before sending let user_text = "hello world"; if user_text.contains('\0') { eprintln!("Text contains NULL bytes"); } else { enigo.text(user_text).unwrap(); } ``` -------------------------------- ### Handle InputError::Unmapping with Retries Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Example demonstrating how to handle the InputError::Unmapping error on Linux by retrying the operation. This error can occur due to transient X11 server issues or connection problems. ```rust use enigo::{Enigo, Keyboard, Key, Direction::Click, InputError, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Try multiple times for transient failures let mut attempts = 0; loop { match enigo.key(Key::Unicode('a'), Click) { Ok(()) => break, Err(InputError::Unmapping(_)) if attempts < 3 => { attempts += 1; std::thread::sleep(std::time::Duration::from_millis(100)); continue; } Err(e) => { eprintln!("Unmapping failed: {}", e); break; } } } ``` -------------------------------- ### Handling Enigo Connection Errors Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/types.md Demonstrates how to handle potential errors when initializing Enigo. It specifically checks for permission issues and connection establishment failures. ```rust use enigo::{Enigo, NewConError, Settings}; match Enigo::new(&Settings::default()) { Ok(enigo) => println!("Connected successfully"), Err(NewConError::NoPermission) => eprintln!("Please grant accessibility permissions"), Err(NewConError::EstablishCon(msg)) => eprintln!("Connection failed: {}", msg), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Automate Form Filling with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Use this snippet to automate filling out forms by simulating mouse clicks and keyboard input. It requires importing necessary modules and setting up an Enigo instance. Delays are included to ensure actions are registered. ```rust use enigo::{Enigo, Keyboard, Mouse, Button, Key, Direction::*, Coordinate::*, Axis::*, Settings}; use std::thread; use std::time::Duration; fn main() -> Result<(), Box> { let mut enigo = Enigo::new(&Settings::default())?; let delay = Duration::from_millis(100); // Click on first field enigo.move_mouse(100, 50, Abs)?; enigo.button(Button::Left, Click)?; thread::sleep(delay); // Type name enigo.text("John Doe")?; thread::sleep(delay); // Tab to next field enigo.key(Key::Tab, Click)?; thread::sleep(delay); // Type email enigo.text("john@example.com")?; thread::sleep(delay); // Tab to password field enigo.key(Key::Tab, Click)?; thread::sleep(delay); // Type password enigo.text("SecurePassword123!")?; thread::sleep(delay); // Submit form (Ctrl+Return or click button) enigo.key(Key::Return, Click)?; Ok(()) } ``` -------------------------------- ### Handle InputError::Mapping on Linux Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Example of handling the InputError::Mapping error, which occurs when keycode-to-keysym mapping fails on Linux. This typically happens due to keyboard layout issues or X11 server misconfiguration. ```rust use enigo::{Enigo, Keyboard, Key, Direction::Click, InputError, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); match enigo.key(Key::Unicode('🔥'), Click) { Ok(()) => println!("Key sent successfully"), Err(InputError::Mapping(msg)) => { eprintln!("Mapping failed: {}", msg); // Try a different key or encoding } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Simulate Keyboard Shortcut (Ctrl+A) with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/README.md Shows how to simulate pressing a keyboard shortcut like Ctrl+A. This involves pressing the control key, typing 'a', and releasing the control key. ```rust use enigo::{Enigo, Keyboard, Key, Direction::{Press, Release, Click}, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); enigo.key(Key::Control, Press).unwrap(); enigo.key(Key::Unicode('a'), Click).unwrap(); enigo.key(Key::Control, Release).unwrap(); ``` -------------------------------- ### Linux Keymap Management Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/README.md Demonstrates releasing keymap resources on Linux by ensuring the Enigo instance is dropped after use. This is important due to limited keymap space on Linux systems. ```rust { let mut enigo = Enigo::new(&Settings::default()).unwrap(); enigo.text("hello").unwrap(); } // Enigo dropped, keycodes released ``` -------------------------------- ### Implement a Retry Loop for Input Actions Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md When input actions might fail temporarily (e.g., due to timing issues), implement a retry loop with a delay. This example retries text input up to a maximum number of attempts. ```rust use enigo::{Enigo, Keyboard, InputError, Settings}; use std::thread; use std::time::Duration; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let max_retries = 3; for attempt in 1..=max_retries { match enigo.text("hello") { Ok(()) => break, Err(InputError::Simulate(_)) if attempt < max_retries => { thread::sleep(Duration::from_millis(100)); } Err(e) => panic!("Failed: {}", e), } } ``` -------------------------------- ### Serializable Input Sequence with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Shows how to execute a sequence of input actions defined as tokens using Enigo's `execute` method. This is useful for replaying or serializing input operations. ```rust use enigo::{Enigo, Agent, Settings, agent::Token}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let tokens = vec![ Token::Text("Hello".to_string()), Token::MoveMouse(100, 100, Coordinate::Rel), Token::Scroll(5, Axis::Vertical), ]; for token in tokens { enigo.execute(&token).unwrap(); } ``` -------------------------------- ### Enigo Keymap Structure (X11) Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Illustrates the internal structure of the `Enigo` struct on X11, specifically the `keymap` field which maps `KeySym` to `KeyCode`. This map has limited space, so efficient management is crucial. ```Rust struct Enigo { // Maps keysym to currently-mapped keycode // Limited number of available slots (8-12 depending on modifiers) keymap: HashMap, } ``` -------------------------------- ### Execute Agent Token Instruction Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Demonstrates executing a single input action represented by a Token. Useful for running serialized or deserialized input sequences. ```rust use enigo::{Enigo, Agent, Button, Direction::Click, Settings, agent::Token}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let token = Token::Text("Hello".to_string()); enigo.execute(&token).unwrap(); let token = Token::Button(Button::Left, Click); enigo.execute(&token).unwrap(); ``` -------------------------------- ### macOS Permission Check and Initialization Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md Checks for necessary accessibility permissions before initializing the enigo instance. If permissions are missing and a prompt is configured, it will attempt to open the system's permission dialog. ```rust pub fn new(settings: &Settings) -> Result { if !has_permission(settings.open_prompt_to_get_permissions) { return Err(NewConError::NoPermission); } // ... rest of initialization } ``` -------------------------------- ### Basic Error Handling for Enigo Operations Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/errors.md Demonstrates how to handle potential connection and simulation errors using `match` statements when initializing Enigo and performing text input. ```Rust use enigo::{Enigo, InputError, NewConError, Settings}; // Connection errors match Enigo::new(&Settings::default()) { Ok(mut enigo) => { // Simulation errors match enigo.text("hello") { Ok(()) => println!("Success"), Err(InputError::InvalidInput(msg)) => eprintln!("Invalid input: {}", msg), Err(InputError::Simulate(msg)) => eprintln!("Simulation failed: {}", msg), Err(e) => eprintln!("Error: {}", e), } } Err(NewConError::NoPermission) => eprintln!("Please grant permissions"), Err(NewConError::EstablishCon(msg)) => eprintln!("Cannot connect: {}", msg), Err(e) => eprintln!("Connection error: {}", e), } ``` -------------------------------- ### Configure Windows Event Extra Info Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/configuration.md Set an arbitrary value to distinguish enigo-created events from hardware events on Windows. Defaults to 0 if not provided. ```rust use enigo::{Enigo, Settings, EVENT_MARKER}; let mut settings = Settings::default(); settings.windows_dw_extra_info = Some(EVENT_MARKER as usize); let enigo = Enigo::new(&settings).unwrap(); ``` -------------------------------- ### Create New Enigo Instance with Custom Settings Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Instantiates Enigo with custom settings, such as disabling automatic key release on drop. Useful for scenarios requiring manual control over key states. ```rust use enigo::{Enigo, Settings}; let mut settings = Settings::default(); settings.release_keys_when_dropped = false; let mut enigo = Enigo::new(&settings).unwrap(); ``` -------------------------------- ### Reusing Enigo Instances Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/README.md Shows the recommended practice of creating an Enigo instance once and reusing it for multiple operations to improve efficiency. Avoid creating new instances within loops. ```rust let mut enigo = Enigo::new(&Settings::default()).unwrap(); for i in 0..1000 { enigo.text(&i.to_string()).unwrap(); } ``` -------------------------------- ### Check and Set DISPLAY Variable on Linux Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/platform-specifics.md If encountering X11 connection denied errors on Linux, verify the `DISPLAY` environment variable is set correctly. If not, export it. ```bash # Check X11 is running echo $DISPLAY # Should output ":0" or similar # If not set export DISPLAY=:0 ``` -------------------------------- ### Execute Agent Tokens with Enigo Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/modules-and-traits.md Demonstrates how to use the `Agent` trait to execute a sequence of `Token` instructions. This is useful for serializing input sequences and replaying recorded sessions. ```rust use enigo::{Enigo, agent::{Agent, Token}, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); let tokens = vec![Token::Text("hello".to_string())]; for token in tokens { enigo.execute(&token).unwrap(); } ``` -------------------------------- ### Perform Mouse Clicks Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md This snippet shows how to perform single clicks, right-clicks, and double-clicks using the Enigo library. Ensure the Enigo instance is initialized. ```rust // Single click enigo.button(Button::Left, Click).unwrap(); // Right-click (context menu) enigo.button(Button::Right, Click).unwrap(); // Double-click enigo.button(Button::Left, Click).unwrap(); enigo.button(Button::Left, Click).unwrap(); ``` -------------------------------- ### Using Enigo Keyboard Keys Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/modules-and-traits.md Demonstrates how to use the Key enum with Enigo for various keyboard actions, including named keys, modifiers, and Unicode characters. Platform-specific keys are conditionally compiled. ```Rust use enigo::{Enigo, Keyboard, Key, Direction::Click, Settings}; let mut enigo = Enigo::new(&Settings::default()).unwrap(); // Named keys (cross-platform) enigo.key(Key::Return, Click).unwrap(); enigo.key(Key::Backspace, Click).unwrap(); // Modifiers enigo.key(Key::Control, Direction::Press).unwrap(); // Unicode (cross-platform) enigo.key(Key::Unicode('a'), Click).unwrap(); enigo.key(Key::Unicode('é'), Click).unwrap(); enigo.key(Key::Unicode('🔥'), Click).unwrap(); // Windows-specific letter keys #[cfg(target_os = "windows")] enigo.key(Key::A, Click).unwrap(); ``` -------------------------------- ### Settings Struct Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/enigo-api-reference.md Configuration struct for creating and controlling Enigo behavior, including display settings and event handling. ```APIDOC ## Settings Struct ### Description Configuration for creating and controlling `Enigo` behavior. ### Fields - **x11_display**: `Option` - **wayland_display**: `Option` - **windows_dw_extra_info**: `Option` - **event_source_user_data**: `Option` - **release_keys_when_dropped**: `bool` (Default: `true`) - **open_prompt_to_get_permissions**: `bool` (Default: `true`) - **independent_of_keyboard_state**: `bool` (Default: `true`) - **windows_subject_to_mouse_speed_and_acceleration_level**: `bool` (Default: `false`) - **restore_token**: `Option` ### Default Values ```rust Settings { x11_display: None, wayland_display: None, windows_dw_extra_info: None, event_source_user_data: None, release_keys_when_dropped: true, open_prompt_to_get_permissions: true, independent_of_keyboard_state: true, windows_subject_to_mouse_speed_and_acceleration_level: false, restore_token: None, } ``` ### See `configuration.md` for detailed field descriptions. ``` -------------------------------- ### Input Text Source: https://github.com/enigo-rs/enigo/blob/main/_autodocs/quick-reference.md Use this snippet to input simple text, Unicode characters, and emoji. Ensure the Enigo instance is initialized. ```rust // Simple text enigo.text("Hello World").unwrap(); // Unicode and emoji enigo.text("Hello ❤️ 世界").unwrap(); // Individual Unicode character enigo.key(Key::Unicode('é'), Click).unwrap(); ```