enigo

repository·main·Indexed 23 days ago

https://github.com/enigo-rs/enigo

A cross-platform Rust library for simulating keyboard and mouse events on Windows, macOS, and Linux (X11, Wayland, and libei). It provides traits for keyboard and mouse control, allowing developers to programmatically move the cursor, click buttons, type text, and send raw keycodes. The library includes a Token enum and Agent trait for orchestrating input sequences and supports serialization via the serde feature.

Tokens
3.5K
Snippets
7
Records
25
Agent score
82%

What's inside enigo

  1. Quickstart: Simulate mouse and text input with Enigo

    main

    To use Enigo, initialize an Enigo instance with Settings::default(). You can then perform mouse movements using absolute or relative coordinates, trigger mouse buttons, and type text strings. Note that most methods return a Result, so you should handle potential errors with .unwrap() or proper error handling.

    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();
  2. Install runtime dependencies for Linux

    main

    If you are using the xdo feature on Linux, you must install the corresponding development libraries for your distribution:

    • Debian-based: apt install libxdo-dev
    • Arch: pacman -S xdotool
    • Fedora: dnf install libX11-devel libxdo-devel
    • Gentoo: emerge -a xdotool
  3. Enable logging for Enigo

    main

    Enigo uses the log crate for internal messaging. To see debug output, you must use a logging implementation (like env_logger used in the project's examples) in your application. You can control the verbosity using the RUST_LOG environment variable.

    To see all debug messages, set RUST_LOG=debug. To limit output to a specific module, use the format RUST_LOG=module_path=level (e.g., RUST_LOG=enigo::platform::x11=debug).

  4. Debug X11 messages using xtrace

    main

    To inspect X11 messages, you must use a proxy server. The recommended method is using the xtrace-example from the x11rb crate.

    1. Clone the x11rb repository.
    2. Navigate to x11rb/xtrace-example.
    3. Run the example, which will provide instructions on how to wrap your command.

    Example usage pattern:

    /path/to/xtrace-example cargo run --example keyboard --features x11rb
    git clone https://github.com/psychon/x11rb.git
    cd x11rb/xtrace-example
    cargo run
    # Follow the output instructions to run your specific command through the proxy
  5. Run Enigo tests safely

    main

    Warning: Enigo tests actively control your mouse, keyboard, and applications. To prevent tests from interfering with each other or your system, run them sequentially using a single thread. It is recommended to close all other applications before running tests.

    cargo test --all-features -- --test-threads=1
  6. Debug Linux compositor communication

    main

    On Linux, you can inspect the messages exchanged between Enigo and the compositor by setting specific environment variables depending on the protocol in use:

    • Libei: Set REIS_DEBUG=1.
    • Wayland: Set WAYLAND_DEBUG=1.
  7. Configure macOS Accessibility permissions

    main

    On macOS, applications require explicit user permission to access accessibility features. enigo automatically checks for these permissions and will prompt the user to grant them if they are missing.

    Users can manually grant these permissions via System Settings. You can also customize how enigo handles permission checks by adjusting the settings when initializing the Enigo struct.

  8. Configure Enigo features

    main

    Enigo's default configuration supports Windows, macOS, and Linux (X11). You can enable additional capabilities via Cargo features:

    • serde: Enables serialization and deserialization of commands.
    • Linux-specific protocols: Wayland and libei support are currently experimental and are hidden behind feature flags.
  9. Use the Key enum for keyboard simulation

    main

    The Key enum represents various keyboard keys used for input simulation.

    Handling Missing Keys

    If a specific key is not present in the Key enum, you can simulate it using:

    • Key::Unicode(char): To enter arbitrary Unicode characters.
    • Key::Other(u32): To provide a raw value. The resulting value depends on your platform:
      • Linux: Results in a keysym.
      • Windows: Results in a Virtual_Key.
      • macOS: Results in a KeyCode.
    • crate::Keyboard::raw: An alternative method for raw input.

    Platform Specificity

    Many keys are only available on specific platforms (e.g., certain Windows-only keys or macOS-only brightness keys). Use conditional compilation (#[cfg(target_os = "...")]) when referencing platform-specific variants to ensure your code compiles across different operating systems.

  10. How to use Enigo to simulate input

    main

    Enigo allows you to simulate mouse and keyboard events as if they were made by actual hardware. To use it, you primarily interact with the Enigo struct, which implements the Keyboard and Mouse traits.

    To get started, create a new instance of Enigo using Enigo::new(&Settings::default()). You can then use its methods to press keys, type text, move the mouse, or click buttons.

    use enigo::{
        Button, Coordinate,
        Direction::{Click, Press, Release},
        Enigo, Key, Keyboard, Mouse, Settings,
    };
    
    let mut enigo = Enigo::new(&Settings::default()).unwrap();
    
    // Paste
    enigo.key(Key::Control, Press);
    enigo.key(Key::Unicode('v'), Click);
    enigo.key(Key::Control, Release);
    
    // Do things with the mouse
    enigo.move_mouse(500, 200, Coordinate::Abs);
    enigo.button(Button::Left, Press);
    enigo.move_mouse(100, 100, Coordinate::Rel);
    enigo.button(Button::Left, Release);
    
    // Enter text
    enigo.text("hello world");
  11. Handle Windows UIPI restrictions

    main
    On Windows, User Interface Privilege Isolation (UIPI) prevents processes with a lower integrity level (IL) from sending messages to processes with a higher IL. If your application needs to control processes with higher privileges (such as the Task Manager), you must run your program as an administrator. Otherwise, enigo will fail to interact with those specific processes.