Skip to content

Platform Drivers

pinjinx edited this page Oct 23, 2026 · 2 revisions

The platform driver layer provides a unified interface for injecting keyboard, mouse, scroll, touch, and virtual gamepad input across different operating systems. Built on the low-level cross-platform @imxade/inject library, Rein maps high-level application gestures and commands to native kernel and window-manager APIs through a common PlatformInjector interface, allowing the rest of the application to remain platform-independent.

At startup, Rein detects the host operating system using os.platform() and dynamically loads the appropriate injector implementation from src/server/drivers/ (@imxade/inject/linux, @imxade/inject/mac, or @imxade/inject/windows).


Platform Overview

Platform Driver Module Mouse & Keyboard API Touch API Virtual Gamepad API Virtual Devices / Interfaces
Linux @imxade/inject/linux uinput (EV_REL, EV_KEY) MT Slot B (EV_ABS, ABS_MT_*) uinput Xbox 360 controller emulation 5 /dev/uinput devices (Mouse, Abs Pointer, Keyboard, Touch, Gamepad)
macOS @imxade/inject/mac CoreGraphics (CGEvent) CoreGraphics scroll & touch drag IOKit IOHIDUserDevice (USB HID report descriptor) System Event Tap + Virtual HID Gamepad
Windows @imxade/inject/windows Win32 SendInput Synthetic Pointer API (POINTER_TYPE_INFO) ViGEmBus kernel driver (ViGEmClient.dll) Win32 Input Queue + Virtual Xbox 360 Controller

PlatformInjector Interface (src/server/types.ts)

Every platform backend implements the following TypeScript contract:

export type PlatformInjector = {
  updateConfig(config: Partial<InputConfig>): void
  injectMouseMove(dx: number, dy: number): void
  // Move cursor to absolute position (x, y are desktop pixel coordinates)
  injectMouseAbsolute(x: number, y: number): void
  injectMouseButton(button: "left" | "right" | "middle", isDown: boolean): void
  injectMouseWheel(dx: number, dy: number): void
  injectKey(key: string, pos?: string): void
  injectCombo(keys: string[]): void
  injectText(text: string): void
  injectTouch(contacts: TouchContact[]): void
  injectGamepadButton(button: string, isDown: boolean): void
  injectGamepadAxis(axis: "ls" | "rs", ax: number, ay: number): void
  destroy(): void
}

Linux Driver (src/server/drivers/linux/)

The Linux implementation uses the Linux uinput kernel subsystem via @imxade/inject/linux (UinputDevice), providing native, reliable uinput event injection without external C++ compilation during install.

Virtual Devices

Rein creates five independent virtual devices under /dev/uinput:

/dev/uinput
    ├── Virtual Mouse (Relative motion, buttons, scroll wheels)
    ├── Virtual Absolute Pointer (Pixel positioning [0, 65535] for touchscreen mode)
    ├── Virtual Keyboard (Key events)
    ├── Virtual Multitouch (MT Protocol B slot-based multi-finger touch)
    └── Virtual Gamepad (Xbox 360 controller: dual analog sticks, triggers, D-pad, buttons)

Each virtual device registers with the USB bus (BUS_USB, vendor 0x1234 or 0x045e for gamepad).

Device Event Types & Codes Purpose
mouseDev EV_REL: REL_X, REL_Y, REL_WHEEL, REL_HWHEEL
EV_KEY: BTN_LEFT, BTN_RIGHT, BTN_MIDDLE
Trackpad relative cursor movement, dragging, and scrolling
absMouseDev EV_ABS: ABS_X, ABS_Y (range 0..65535)
EV_KEY: BTN_TOUCH, BTN_LEFT, BTN_RIGHT, BTN_MIDDLE
Direct touchscreen tap-to-click. Warps cursor instantly without relative acceleration artifacts
kbDev EV_KEY: Full keyboard scancodes (KEY_A..KEY_Z, modifiers, function keys) Keyboard typing, shortcuts, and combos
touchDev EV_ABS: ABS_MT_SLOT, ABS_MT_TRACKING_ID, ABS_MT_POSITION_X/Y, ABS_MT_PRESSURE Multi-finger raw touch contact injection (up to 10 contacts)
gamepadDev EV_ABS: ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_Z (LT), ABS_RZ (RT), ABS_HAT0X, ABS_HAT0Y
EV_KEY: BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR, BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR, BTN_MODE
Native Xbox 360 controller emulation for Steam and Linux games

Process Cleanup & Safety

To prevent orphan virtual devices if the server is abruptly stopped, LinuxInputInjector tracks active instances in an internal Set and registers process listeners on SIGINT, SIGTERM, and exit to destroy all open uinput devices cleanly.

Linux Permissions Setup

Creating virtual devices requires write access to /dev/uinput:

sudo groupadd -f uinput
sudo usermod -aG uinput $USER
sudo tee /etc/udev/rules.d/99-rein.rules <<EOF
KERNEL=="uinput", MODE="0660", GROUP="uinput"
EOF
sudo udevadm control --reload-rules
sudo udevadm trigger

macOS Driver (src/server/drivers/mac/)

The macOS implementation uses @imxade/inject/mac, leveraging CoreGraphics for mouse and keyboard injection, and IOKit / IOHIDUserDevice for virtual gamepad creation.

Mouse & Absolute Positioning

  • Relative Movement: Updates internal cursorX and cursorY positions clamped to screen bounds and creates kCGEventMouseMoved (or kCGEventLeftMouseDragged/kCGEventRightMouseDragged when buttons are held) via CGEventCreateMouseEvent().
  • Absolute Positioning (injectMouseAbsolute): Sets cursorX = x and cursorY = y directly and dispatches a mouse move event, ensuring touchscreen taps warp the cursor to the target coordinate immediately.
  • Scroll: Injects smooth pixel scrolling via CGEventCreateScrollWheelEvent2().

Keyboard Input

  • Virtual Key Codes: Named keys (e.g. Return, Escape, Space, Arrow keys) are translated via MAC_KEY_MAP and injected using CGEventCreateKeyboardEvent().
  • Unicode Injection: Arbitrary text strings are injected using CGEventKeyboardSetUnicodeString(), ensuring complete UTF-16 character coverage without relying on layout-dependent key codes.

macOS Virtual Gamepad (MacGamepad)

Creates a virtual HID gamepad device using the userspace IOHIDUserDevice API (available on macOS 10.15+ without requiring a kernel extension or driver kext):

  1. Loads /System/Library/Frameworks/IOKit.framework/IOKit and CoreFoundation via Koffi.
  2. Creates an IOHIDUserDevice configured with a standard USB HID Gamepad Report Descriptor (Usage Page 0x01, Usage 0x05).
  3. Dispatches 16 digital buttons, 2 analog thumbsticks (X, Y, Z, Rz in [-32767, 32767]), and 2 analog triggers ([0, 255]) via IOHIDUserDeviceHandleReport().

macOS Accessibility Permissions

macOS requires Accessibility permissions to generate system input events:

System Settings → Privacy & Security → Accessibility → Add your terminal, IDE, or Rein app


Windows Driver (src/server/drivers/windows/)

The Windows implementation uses @imxade/inject/windows, combining Win32 SendInput, the Synthetic Pointer API, and the ViGEmBus driver.

Mouse & Absolute Positioning

  • Relative Movement: Calls SendInput with MOUSEEVENTF_MOVE.
  • Absolute Positioning (injectMouseAbsolute): Normalizes pixel coordinates (x, y) over the virtual desktop coordinate space [0, 65535]:
    const absX = Math.round((x / config.screenWidth) * 65535)
    const absY = Math.round((y / config.screenHeight) * 65535)
    // Dispatched with dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE
  • Wheel Scrolling: Injects vertical and horizontal scrolling using MOUSEEVENTF_WHEEL and MOUSEEVENTF_HWHEEL.

Keyboard Input

Windows supports two keyboard injection modes:

  • Virtual Key Scan Codes: Physical keyboard keys translated via WIN_KEY_MAP and sent with KEYEVENTF_SCANCODE.
  • Unicode Text: Text characters sent with KEYEVENTF_UNICODE, allowing direct typing of international and special characters.

Windows Virtual Gamepad (WindowsGamepad & ViGEmBus)

Windows games typically require XInput / Xbox controller emulation. Rein integrates with the open-source ViGEmBus (Virtual Gamepad Emulation Bus) kernel driver:

  1. DLL Resolution (src/utils/binPaths.ts): Resolves ViGEmClient.dll from the bundled directory (bin/vigme/ViGEmClient.dll) or system PATH.
  2. Koffi FFI: Loads the DLL and initializes vigem_alloc(), vigem_connect(), and vigem_target_x360_alloc().
  3. Report Updates: Dispatches XUSB_REPORT structures containing digital button bitmasks (wButtons), trigger bytes (bLeftTrigger, bRightTrigger), and 16-bit signed thumbstick axes (sThumbLX, sThumbLY, sThumbRX, sThumbRY) via vigem_target_x360_update().
  4. Graceful Fallback: If ViGEmBus is not installed on the Windows host, the driver logs a warning and gamepad injection operations become graceful no-ops without crashing the server.

Key Mapping Architecture (src/server/drivers/keyMap.ts)

The web client sends platform-neutral key identifiers (e.g. "enter", "escape", "tab", "control", "arrowup", "f5").

Each platform driver maintains a dedicated lookup table:

  • LINUX_KEY_MAP: Maps to Linux evdev scancodes (KEY_ENTER, KEY_ESC, KEY_LEFTCTRL, etc.).
  • MAC_KEY_MAP: Maps to macOS virtual key codes (e.g. 0x24 for Return, 0x35 for Escape).
  • WIN_KEY_MAP: Maps to Win32 virtual key codes (VK_RETURN, VK_ESCAPE, etc.).

Stub Driver

If Rein is launched on an unsupported platform or if native injection initialization fails:

  • A stub injector (createStubInjector()) is instantiated.
  • All injection calls become safe no-ops with logged warnings.
  • An input-injector-init-failed error event is pushed via the session SSE stream (/api/rtc/session-sse), allowing the client UI to display a user-friendly troubleshooting banner.

Clone this wiki locally