{"modulePath":"github.com/LocalKinAI/input-go","version":"v0.3.1","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package input\n\nPackage input is a pure-Go macOS mouse and keyboard synthesis library.\n\ninput uses CGEvent (Quartz Event Services) to post mouse and keyboard events system-wide. It's the foundation for automation, UI testing, screen-demo tooling, and remote-control agents — anything that needs to drive the cursor or type text.\n\n### Quick start {#hdr-Quick_start}\n\n\tctx := context.Background()\n\tif err := input.Load(); err != nil { log.Fatal(err) }\n\n\t// Move cursor and click\n\tinput.ClickAt(ctx, 400, 300)\n\n\t// Type text\n\tinput.Type(ctx, \"hello, world\")\n\n\t// Cmd+C hotkey\n\tinput.Hotkey(ctx, input.ModCommand, input.KeyC)\n\n### Permissions {#hdr-Permissions}\n\nmacOS requires the invoking binary to be listed in System Settings → Privacy \u0026 Security → Accessibility for synthesized events to take effect. Without permission, calls return nil (no error) but the events have no visible effect — this matches macOS's silent-failure model. Use [Trusted](#Trusted) to check, and [PromptTrust](#PromptTrust) to trigger the system dialog.\n\n### Dylib placement {#hdr-Dylib_placement}\n\ninput-go ships a universal (arm64+x86\\_64) companion dylib via //go:embed. On the first call into the package, the embedded bytes are extracted to ~/Library/Caches/input-go/\\\u003chash\u003e/libinput\\_sync.dylib and Dlopened. Set [DylibPath](#DylibPath) to a non-empty value before the first call if you ship a custom-built or patched dylib.\n\n## Constants\n\n```go\nconst Version = \"0.3.0\"\n```\nVersion is the semantic-version tag of this package. Kept in sync with git tags; updated per release.\n\n## Variables\n\n```go\nvar DylibPath = \"\"\n```\nDylibPath is an optional override for the location of libinput\\_sync.dylib. Default (empty): extract the embedded copy to the user cache directory. Set to a non-empty path BEFORE the first call into this package if shipping a custom-built dylib.\n\n```go\nvar ErrInvalidArg = errors.New(\"input: invalid argument\")\n```\nErrInvalidArg is returned for malformed inputs (e.g. an empty key, a negative click count).\n\n```go\nvar ErrNotTrusted = errors.New(\"input: accessibility permission not granted\")\n```\nErrNotTrusted is returned when the current process lacks Accessibility permission AND the caller explicitly requested a trust check (see [RequireTrust](#RequireTrust)). Regular input calls DO NOT return this error — they silently no-op, matching macOS behavior.\n\n## Functions\n\n```go\nfunc Click(ctx context.Context, button MouseButton, clicks int, opts ...PostOption) error\n```\nClick presses and releases \\`button\\` at the current cursor position. \\`clicks\\` is the click count (1 = single, 2 = double, 3 = triple). A zero or negative \\`clicks\\` is treated as 1.\n\n```go\nfunc ClickAt(ctx context.Context, x, y float64, opts ...PostOption) error\n```\nClickAt moves the cursor to (x, y) and single-left-clicks. This is the most common convenience — 90% of automation needs it.\n\n```go\nfunc ClickAtButton(ctx context.Context, x, y float64, button MouseButton, clicks int, opts ...PostOption) error\n```\nClickAtButton is like [ClickAt](#ClickAt) but with a configurable button and click count.\n\n```go\nfunc CursorPosition() (x, y float64, err error)\n```\nCursorPosition returns the current cursor location in global screen coordinates (origin at top-left).\n\n```go\nfunc DoubleClick(ctx context.Context, x, y float64, opts ...PostOption) error\n```\nDoubleClick is shorthand for ClickAtButton(..., ButtonLeft, 2).\n\n```go\nfunc Drag(ctx context.Context, fromX, fromY, toX, toY float64, duration time.Duration, opts ...PostOption) error\n```\nDrag performs a \"mouse-down → move → mouse-up\" sequence: press the left button at \\`from\\`, interpolate the cursor toward \\`to\\` over \\`duration\\`, release. Used for drag-select, drag-to-reorder, slider control, etc.\n\n```go\nfunc Hold(ctx context.Context, mods Modifier, keys []Key, opts ...PostOption) func()\n```\nHold presses the given modifiers and keys, then returns a release closure that lifts them. Designed for \\`defer\\` to guarantee teardown even on panic or early return:\n\n\tdefer input.Hold(ctx, input.ModShift, nil)()\n\tinput.Press(ctx, input.KeyTab)   // Shift+Tab\n\tinput.Press(ctx, input.KeyTab)   // still Shift+Tab\n\n\\`keys\\` is a slice (rather than variadic) because the function already has a variadic \\`opts\\` tail; pass nil when only modifiers are needed:\n\n\tdefer input.Hold(ctx, input.ModCommand, nil, input.WithPID(p))()\n\nWithout this helper, any error path between [KeyDown](#KeyDown) and [KeyUp](#KeyUp) leaks a \"stuck\" modifier — every subsequent input gets corrupted at the OS level (sticky shift / cmd / etc.) until the user notices and taps the modifier manually. Hold + defer eliminates the whole class of bug.\n\nMultiple keys are pressed in order, released in reverse order — so \\`Hold(ctx, ModCommand|ModShift)\\` releases Shift before Command, the natural teardown order.\n\nThe release closure is idempotent — calling it twice is safe but only the first call has effect. Release errors are silently dropped (macOS's silent-failure model means there's no useful action anyway).\n\nReturns a no-op release if [Load](#Load) failed or ctx is already canceled.\n\n```go\nfunc Hotkey(ctx context.Context, mods Modifier, key Key, opts ...PostOption) error\n```\nHotkey presses \\`key\\` with \\`mods\\` held: down-modifiers → down-key → up-key → up-modifiers. This is how you send Cmd+C, Cmd+Shift+T, etc.\n\n\tinput.Hotkey(ctx, input.ModCommand, input.KeyC)                 // copy\n\tinput.Hotkey(ctx, input.ModCommand|input.ModShift, input.KeyT)  // reopen tab\n\n```go\nfunc KeyDown(ctx context.Context, key Key, mods Modifier, opts ...PostOption) error\n```\nKeyDown posts a key-down event for \\`key\\`. Optionally carries modifier flags — pass 0 for no modifiers.\n\n```go\nfunc KeyUp(ctx context.Context, key Key, mods Modifier, opts ...PostOption) error\n```\nKeyUp posts a key-up event for \\`key\\`.\n\n```go\nfunc Load() error\n```\nLoad explicitly loads the companion dylib. It's idempotent: subsequent calls return the same cached error (or nil).\n\nResolution order:\n\n 1. If DylibPath is non-empty, use it (user override).\n 2. Otherwise, extract the embedded universal dylib to the cache directory and Dlopen from there.\n\nLoad is called automatically by every public function; the exported form exists so applications can fail fast at startup.\n\n```go\nfunc Move(ctx context.Context, x, y float64, opts ...PostOption) error\n```\nMove jumps the cursor instantly to (x, y) in global screen coordinates. (0, 0) is the top-left of the main display. Pass [WithPID](#WithPID) to route the event to a specific app without focus steal.\n\n```go\nfunc MoveBy(ctx context.Context, dx, dy float64, opts ...PostOption) error\n```\nMoveBy offsets the cursor by (dx, dy) from its current position.\n\n```go\nfunc MoveSmooth(ctx context.Context, x, y float64, duration time.Duration, opts ...PostOption) error\n```\nMoveSmooth moves the cursor from its current position to (x, y) by linearly interpolating through intermediate points. \\`duration\\` controls total animation length; shorter values feel snappier. A \\`duration\\` of 0 degenerates to [Move](#Move).\n\nThis is the animation primitive used for \"screen demo\" recordings where a teleporting cursor looks jarring.\n\n```go\nfunc PasteText(ctx context.Context, text string, opts ...PostOption) error\n```\nPasteText injects a string by writing to the macOS clipboard, firing ⌘V via the standard [Hotkey](#Hotkey) path, and restoring the user's previous clipboard text ~150ms later.\n\nWhy a separate function rather than just [Type](#Type): [Type](#Type) synthesizes a key event per character at full keyboard rate (~100 char/s). IME front-ends (Pinyin / Wubi / Kotoeri) frequently can't keep up with that rate — characters get dropped or the IME's composition state desyncs. PasteText sidesteps the IME entirely by routing through the system pasteboard.\n\nRestore semantics: PasteText always saves the previous clipboard before writing + restores it after the keystroke. Non-text pasteboard content (image / file / RTF) does NOT survive the round-trip — by macOS pasteboard design — but plain text (the 95% case) does. If you don't want the restore, set the clipboard yourself with [WriteClipboard](#WriteClipboard) after PasteText returns.\n\nRouting: \\[PostOption]s (e.g. [WithPID](#WithPID)) apply to the ⌘V keystroke, so paste can target a background app without stealing focus from the user's foreground window. The pbcopy/pbpaste shell-outs are system-wide either way — there's only one macOS pasteboard.\n\n\tif err := input.PasteText(ctx, \"你好世界\"); err != nil { ... }\n\tinput.PasteText(ctx, longChineseText, input.WithPID(pid))\n\nErrors:\n\n  - pbcopy / pbpaste failures propagate as \"pbcopy: …\" / \"pbpaste: …\". Rare unless running in a sandbox without /usr/bin.\n  - The ⌘V keystroke uses the same error chain as [Hotkey](#Hotkey).\n\n```go\nfunc Press(ctx context.Context, key Key, opts ...PostOption) error\n```\nPress taps a key: down then up. This is the common case for any key that doesn't need to be held.\n\n```go\nfunc PromptTrust() bool\n```\nPromptTrust triggers the system \"\\\u003capp\u003e wants access to control your computer\" dialog if permission has not yet been granted. Returns current trust state (true if granted, false if the user hasn't responded yet or denied).\n\nThis is a one-shot prompt — subsequent calls return the current state without showing the dialog again (until the user resets TCC).\n\n```go\nfunc ReadClipboard(ctx context.Context) (string, error)\n```\nReadClipboard returns the macOS clipboard's current text content via pbpaste. Useful as a building block for code that needs to inspect / round-trip the pasteboard without going through the whole PasteText flow.\n\n```go\nfunc RequireTrust() error\n```\nRequireTrust returns nil if Accessibility permission is granted, or [ErrNotTrusted](#ErrNotTrusted) otherwise. Convenience for callers that want a hard fail rather than silent no-ops.\n\n```go\nfunc ResolvedDylibPath() string\n```\nResolvedDylibPath returns the filesystem path that Load used (or would use) to Dlopen the dylib. Intended for diagnostics.\n\n```go\nfunc RightClick(ctx context.Context, x, y float64, opts ...PostOption) error\n```\nRightClick is shorthand for ClickAtButton(..., ButtonRight, 1).\n\n```go\nfunc ScreenSize() (w, h float64, err error)\n```\nScreenSize returns the main display's pixel dimensions.\n\n```go\nfunc Scroll(ctx context.Context, dx, dy int, opts ...PostOption) error\n```\nScroll posts a scroll-wheel event. \\`dy\\` is vertical (positive scrolls content up — same as flicking your finger upward on a trackpad); \\`dx\\` is horizontal (positive scrolls right). Units are pixels.\n\n```go\nfunc ScrollSmooth(ctx context.Context, dx, dy int, duration time.Duration, opts ...PostOption) error\n```\nScrollSmooth posts a series of smaller scroll events to approximate a single larger scroll. Looks more natural than a single big jump and avoids \"overshoot\" on momentum-scrolling apps.\n\n```go\nfunc Trusted() bool\n```\nTrusted returns true if the current process has Accessibility permission granted. Does not prompt — use [PromptTrust](#PromptTrust) for that.\n\n```go\nfunc Type(ctx context.Context, text string, opts ...PostOption) error\n```\nType synthesizes keyboard events that produce \\`text\\` in the currently focused text field. Works for arbitrary UTF-8 including emoji and CJK, because it uses CGEventKeyboardSetUnicodeString rather than translating through the current keyboard layout.\n\nNote: because this bypasses the keyboard layout, typing \"A\" is a literal A glyph, not \"shift+a\". Apps that listen for raw keycodes (games, key remappers) won't see a modifier press.\n\n```go\nfunc TypeSlow(ctx context.Context, text string, perCharDelay time.Duration, opts ...PostOption) error\n```\nTypeSlow is like [Type](#Type) but inserts \\`perCharDelay\\` between characters. Useful for demos where \"instant paste\" looks artificial, or for apps that throttle rapid-fire input.\n\n```go\nfunc WriteClipboard(ctx context.Context, text string) error\n```\nWriteClipboard writes text to the macOS clipboard via pbcopy. Companion to [ReadClipboard](#ReadClipboard). Use this if you want to populate the clipboard without immediately firing ⌘V.\n\n## Types\n\n```go\ntype Key int32\n```\nKey is a macOS virtual keycode. Values match \\\u003cCarbon/HIToolbox/Events.h\u003e.\n\nUse the named constants (KeyA, KeySpace, ...) rather than numeric values — Apple's keycodes are ANSI-layout specific and not obvious.\n\n```go\nconst (\n\tKeyA Key = 0x00\n\tKeyB Key = 0x0B\n\tKeyC Key = 0x08\n\tKeyD Key = 0x02\n\tKeyE Key = 0x0E\n\tKeyF Key = 0x03\n\tKeyG Key = 0x05\n\tKeyH Key = 0x04\n\tKeyI Key = 0x22\n\tKeyJ Key = 0x26\n\tKeyK Key = 0x28\n\tKeyL Key = 0x25\n\tKeyM Key = 0x2E\n\tKeyN Key = 0x2D\n\tKeyO Key = 0x1F\n\tKeyP Key = 0x23\n\tKeyQ Key = 0x0C\n\tKeyR Key = 0x0F\n\tKeyS Key = 0x01\n\tKeyT Key = 0x11\n\tKeyU Key = 0x20\n\tKeyV Key = 0x09\n\tKeyW Key = 0x0D\n\tKeyX Key = 0x07\n\tKeyY Key = 0x10\n\tKeyZ Key = 0x06\n\n\tKey0 Key = 0x1D\n\tKey1 Key = 0x12\n\tKey2 Key = 0x13\n\tKey3 Key = 0x14\n\tKey4 Key = 0x15\n\tKey5 Key = 0x17\n\tKey6 Key = 0x16\n\tKey7 Key = 0x1A\n\tKey8 Key = 0x1C\n\tKey9 Key = 0x19\n\n\tKeyReturn        Key = 0x24\n\tKeyTab           Key = 0x30\n\tKeySpace         Key = 0x31\n\tKeyDelete        Key = 0x33 // Backspace on PC keyboards\n\tKeyEscape        Key = 0x35\n\tKeyForwardDelete Key = 0x75 // fn+delete / dedicated Del key\n\n\tKeyLeftCommand  Key = 0x37\n\tKeyLeftShift    Key = 0x38\n\tKeyCapsLock     Key = 0x39\n\tKeyLeftOption   Key = 0x3A\n\tKeyLeftControl  Key = 0x3B\n\tKeyRightShift   Key = 0x3C\n\tKeyRightOption  Key = 0x3D\n\tKeyRightControl Key = 0x3E\n\tKeyFn           Key = 0x3F\n\n\tKeyArrowLeft  Key = 0x7B\n\tKeyArrowRight Key = 0x7C\n\tKeyArrowDown  Key = 0x7D\n\tKeyArrowUp    Key = 0x7E\n\n\tKeyF1  Key = 0x7A\n\tKeyF2  Key = 0x78\n\tKeyF3  Key = 0x63\n\tKeyF4  Key = 0x76\n\tKeyF5  Key = 0x60\n\tKeyF6  Key = 0x61\n\tKeyF7  Key = 0x62\n\tKeyF8  Key = 0x64\n\tKeyF9  Key = 0x65\n\tKeyF10 Key = 0x6D\n\tKeyF11 Key = 0x67\n\tKeyF12 Key = 0x6F\n\n\tKeyHome     Key = 0x73\n\tKeyEnd      Key = 0x77\n\tKeyPageUp   Key = 0x74\n\tKeyPageDown Key = 0x79\n\n\tKeyMinus        Key = 0x1B\n\tKeyEqual        Key = 0x18\n\tKeyLeftBracket  Key = 0x21\n\tKeyRightBracket Key = 0x1E\n\tKeyBackslash    Key = 0x2A\n\tKeySemicolon    Key = 0x29\n\tKeyQuote        Key = 0x27\n\tKeyComma        Key = 0x2B\n\tKeyPeriod       Key = 0x2F\n\tKeySlash        Key = 0x2C\n\tKeyGrave        Key = 0x32\n)\n```\nUS-ANSI virtual keycodes — stable across macOS versions. Source: \\\u003cHIToolbox/Events.h\u003e kVK\\_\\* constants.\n\n```go\nfunc KeyByName(name string) (Key, bool)\n```\nKeyByName looks up a Key by its common name (case-insensitive). Used by the CLI so \\`input key --press enter\\` works. Returns (0, false) if the name is unknown.\n\n```go\ntype Modifier uint64\n```\nModifier is a bitmask of keyboard modifier flags. Combine with bitwise OR: \\`input.ModCommand | input.ModShift\\`. Values match CGEventFlags.\n\n```go\nconst (\n\t// ModCommand is the Command (⌘) modifier.\n\tModCommand Modifier = 1 \u003c\u003c 20 // kCGEventFlagMaskCommand\n\t// ModShift is the Shift (⇧) modifier.\n\tModShift Modifier = 1 \u003c\u003c 17 // kCGEventFlagMaskShift\n\t// ModOption is the Option/Alt (⌥) modifier.\n\tModOption Modifier = 1 \u003c\u003c 19 // kCGEventFlagMaskAlternate\n\t// ModControl is the Control (⌃) modifier.\n\tModControl Modifier = 1 \u003c\u003c 18 // kCGEventFlagMaskControl\n\t// ModFunction is the Function (fn) modifier.\n\tModFunction Modifier = 1 \u003c\u003c 23 // kCGEventFlagMaskSecondaryFn\n)\n```\n\n```go\nfunc ParseModifiers(s string) (Modifier, bool)\n```\nParseModifiers parses a comma- or '+'-delimited modifier string like \"cmd+shift\" or \"cmd,option\" into a [Modifier](#Modifier) bitmask. Unknown tokens return (0, false). Empty string returns (0, true).\n\n```go\ntype MouseButton int32\n```\nMouseButton enumerates the three mouse buttons that CGEvent understands.\n\n```go\nconst (\n\tButtonLeft  MouseButton = 0\n\tButtonRight MouseButton = 1\n\tButtonOther MouseButton = 2\n)\n```\n\n```go\ntype PostOption func(*postConfig)\n```\nPostOption tunes how an event is posted to the OS. Pass via the variadic \\`opts\\` tail of any event-posting function.\n\n```go\nfunc WithPID(pid int32) PostOption\n```\nWithPID routes events directly to the given process via CGEventPostToPid, avoiding focus steal — your foreground app stays foreground while input-go drives a background app. pid=0 (the default when the option is omitted) keeps the legacy system-wide HID event tap behavior, which moves focus to the targeted control's owning app.\n\nVerified working on Lark / VSCode / Chrome and other Electron + Web View hosts. Some Apple sandboxed apps (newer Mail / Messages) may ignore PID-targeted events — fall back to the default if you see no effect.\n\n\tinput.Click(ctx, 400, 300, input.WithPID(int32(targetPID)))\n\tinput.Type(ctx, \"hello\", input.WithPID(int32(targetPID)))\n\tinput.Hotkey(ctx, input.ModCommand, input.KeyS, input.WithPID(int32(targetPID)))\n\n","path":"github.com/LocalKinAI/input-go","name":"input","synopsis":"Package input is a pure-Go macOS mouse and keyboard synthesis library.","isRedistributable":true}
