Skip to content

armgit / mimik

Public Imported from GitHub
0

🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots πŸ“–

feat(capture-native): hook input and read the accessibility tree on macOS

Luis Ortiz2f8e02c57eb2
diff --git a/packages/capture-native/index.d.ts b/packages/capture-native/index.d.ts
index 6fa7c1e..803fa9b 100644
--- a/packages/capture-native/index.d.ts
+++ b/packages/capture-native/index.d.ts
@@ -39,12 +39,27 @@ export interface ElementRect {
export declare function focusedElement(): Promise<UiElement | null>
+export interface HookEvent {
+ kind: string
+ button: number
+ x: number
+ y: number
+ clicks: number
+ keycode: number
+ shift: boolean
+ ctrl: boolean
+ alt: boolean
+ meta: boolean
+}
+
export declare function isSupported(): boolean
export declare function keyLabel(keycode: number): string | null
export declare function resolveKey(keycode: number, shift: boolean, ctrl: boolean, alt: boolean): string | null
+export declare function startInputHook(callback: (event: HookEvent) => void): void
+
export interface UiElement {
role?: string
name?: string
diff --git a/packages/capture-native/index.js b/packages/capture-native/index.js
index 9f8697f..6c19c43 100644
--- a/packages/capture-native/index.js
+++ b/packages/capture-native/index.js
@@ -785,4 +785,5 @@ module.exports.focusedElement = nativeBinding.focusedElement
module.exports.isSupported = nativeBinding.isSupported
module.exports.keyLabel = nativeBinding.keyLabel
module.exports.resolveKey = nativeBinding.resolveKey
+module.exports.startInputHook = nativeBinding.startInputHook
module.exports.windowAt = nativeBinding.windowAt
diff --git a/packages/capture-native/package.json b/packages/capture-native/package.json
index 7bd5e3e..6bbbf09 100644
--- a/packages/capture-native/package.json
+++ b/packages/capture-native/package.json
@@ -9,7 +9,7 @@
"files": ["index.js", "index.d.ts", "*.node"],
"napi": {
"binaryName": "capture-native",
- "targets": ["x86_64-pc-windows-msvc"]
+ "targets": ["x86_64-pc-windows-msvc", "x86_64-apple-darwin", "aarch64-apple-darwin"]
},
"scripts": {
"build": "napi build --platform --release",
diff --git a/packages/capture-native/src/lib.rs b/packages/capture-native/src/lib.rs
index 2075856..abba167 100644
--- a/packages/capture-native/src/lib.rs
+++ b/packages/capture-native/src/lib.rs
@@ -6,10 +6,20 @@ use napi_derive::napi;
#[cfg(any(windows, test))]
mod hit;
+#[cfg(target_os = "macos")]
+mod mac;
+#[cfg(target_os = "macos")]
+mod machook;
+#[cfg(any(target_os = "macos", test))]
+mod macmap;
#[cfg(windows)]
mod win;
#[cfg(any(windows, test))]
mod window;
+#[cfg(target_os = "macos")]
+use mac as platform;
+#[cfg(windows)]
+use win as platform;
#[napi(object)]
pub struct ElementRect {
@@ -49,6 +59,34 @@ pub struct ActiveWindow {
pub height: f64,
}
+#[napi(object)]
+pub struct HookEvent {
+ pub kind: String,
+ pub button: u32,
+ pub x: f64,
+ pub y: f64,
+ pub clicks: u32,
+ pub keycode: u32,
+ pub shift: bool,
+ pub ctrl: bool,
+ pub alt: bool,
+ pub meta: bool,
+}
+
+pub type HookCallback =
+ napi::threadsafe_function::ThreadsafeFunction<HookEvent, (), HookEvent, napi::Status, false, true>;
+
+#[napi(ts_args_type = "callback: (event: HookEvent) => void")]
+pub fn start_input_hook(callback: HookCallback) -> Result<()> {
+ #[cfg(target_os = "macos")]
+ return machook::start(callback);
+ #[cfg(not(target_os = "macos"))]
+ {
+ drop(callback);
+ Err(napi::Error::from_reason("the native input hook is macOS only"))
+ }
+}
+
pub struct ElementLookup {
at: Option<(i32, i32)>,
}
@@ -57,15 +95,15 @@ impl Task for ElementLookup {
type Output = Option<UiElement>;
type JsValue = Option<UiElement>;
- #[cfg(windows)]
+ #[cfg(any(windows, target_os = "macos"))]
fn compute(&mut self) -> Result<Self::Output> {
match self.at {
- Some((x, y)) => win::element_at_point(x, y),
- None => win::focused_element(),
+ Some((x, y)) => platform::element_at_point(x, y),
+ None => platform::focused_element(),
}
}
- #[cfg(not(windows))]
+ #[cfg(not(any(windows, target_os = "macos")))]
fn compute(&mut self) -> Result<Self::Output> {
Ok(None)
}
@@ -87,9 +125,9 @@ pub fn focused_element() -> AsyncTask<ElementLookup> {
#[napi]
pub fn key_label(keycode: u32) -> Option<String> {
- #[cfg(windows)]
- return win::key_label(keycode);
- #[cfg(not(windows))]
+ #[cfg(any(windows, target_os = "macos"))]
+ return platform::key_label(keycode);
+ #[cfg(not(any(windows, target_os = "macos")))]
{
let _ = keycode;
None
@@ -98,9 +136,9 @@ pub fn key_label(keycode: u32) -> Option<String> {
#[napi]
pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<String> {
- #[cfg(windows)]
- return win::resolve_key(keycode, shift, ctrl, alt);
- #[cfg(not(windows))]
+ #[cfg(any(windows, target_os = "macos"))]
+ return platform::resolve_key(keycode, shift, ctrl, alt);
+ #[cfg(not(any(windows, target_os = "macos")))]
{
let _ = (keycode, shift, ctrl, alt);
None
@@ -109,17 +147,17 @@ pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<S
#[napi]
pub fn active_window() -> Option<ActiveWindow> {
- #[cfg(windows)]
- return win::active_window();
- #[cfg(not(windows))]
+ #[cfg(any(windows, target_os = "macos"))]
+ return platform::active_window();
+ #[cfg(not(any(windows, target_os = "macos")))]
None
}
#[napi]
pub fn window_at(x: i32, y: i32) -> Option<ActiveWindow> {
- #[cfg(windows)]
- return win::window_at(x, y);
- #[cfg(not(windows))]
+ #[cfg(any(windows, target_os = "macos"))]
+ return platform::window_at(x, y);
+ #[cfg(not(any(windows, target_os = "macos")))]
{
let _ = (x, y);
None
@@ -128,11 +166,11 @@ pub fn window_at(x: i32, y: i32) -> Option<ActiveWindow> {
#[napi]
pub fn clear_dead_key() {
- #[cfg(windows)]
- win::clear_dead_key();
+ #[cfg(any(windows, target_os = "macos"))]
+ platform::clear_dead_key();
}
#[napi]
pub fn is_supported() -> bool {
- cfg!(windows)
+ cfg!(any(windows, target_os = "macos"))
}
diff --git a/packages/capture-native/src/mac.rs b/packages/capture-native/src/mac.rs
new file mode 100644
index 0000000..ab0e411
--- /dev/null
+++ b/packages/capture-native/src/mac.rs
@@ -0,0 +1,566 @@
+use std::collections::HashSet;
+use std::ffi::{c_char, c_void, CStr};
+use std::path::Path;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::Mutex;
+
+use napi::Result;
+
+use crate::macmap::{is_control, is_label, mac_keycode, named_key, printable, role, PROMOTE_DEPTH};
+use crate::{ActiveWindow, ElementNode, ElementRect, UiElement};
+
+type CFTypeRef = *const c_void;
+type CFStringRef = *const c_void;
+type CFArrayRef = *const c_void;
+type CFDictionaryRef = *const c_void;
+type AXUIElementRef = *const c_void;
+type AXError = i32;
+type Boolean = u8;
+
+const UTF8: u32 = 0x0800_0100;
+const AX_POINT: u32 = 1;
+const AX_SIZE: u32 = 2;
+const NUMBER_INT32: isize = 3;
+const NUMBER_FLOAT64: isize = 6;
+const ON_SCREEN_ONLY: u32 = 1;
+const EXCLUDE_DESKTOP: u32 = 16;
+const MESSAGING_TIMEOUT_SECONDS: f32 = 1.0;
+const MAX_ANCESTORS: usize = 4;
+const MAX_CHILDREN: usize = 12;
+
+#[repr(C)]
+#[derive(Default, Clone, Copy)]
+struct CGPoint {
+ x: f64,
+ y: f64,
+}
+
+#[repr(C)]
+#[derive(Default, Clone, Copy)]
+struct CGSize {
+ width: f64,
+ height: f64,
+}
+
+#[repr(C)]
+#[derive(Default, Clone, Copy)]
+struct CGRect {
+ origin: CGPoint,
+ size: CGSize,
+}
+
+#[link(name = "CoreFoundation", kind = "framework")]
+extern "C" {
+ fn CFRelease(value: CFTypeRef);
+ fn CFGetTypeID(value: CFTypeRef) -> usize;
+ fn CFStringGetTypeID() -> usize;
+ fn CFArrayGetTypeID() -> usize;
+ fn CFStringCreateWithBytes(
+ allocator: *const c_void,
+ bytes: *const u8,
+ length: isize,
+ encoding: u32,
+ external: Boolean,
+ ) -> CFStringRef;
+ fn CFStringGetLength(string: CFStringRef) -> isize;
+ fn CFStringGetMaximumSizeForEncoding(length: isize, encoding: u32) -> isize;
+ fn CFStringGetCString(string: CFStringRef, buffer: *mut c_char, size: isize, encoding: u32) -> Boolean;
+ fn CFArrayGetCount(array: CFArrayRef) -> isize;
+ fn CFArrayGetValueAtIndex(array: CFArrayRef, index: isize) -> *const c_void;
+ fn CFDictionaryGetValue(dictionary: CFDictionaryRef, key: *const c_void) -> *const c_void;
+ fn CFNumberGetValue(number: CFTypeRef, kind: isize, value: *mut c_void) -> Boolean;
+ fn CFDataGetBytePtr(data: CFTypeRef) -> *const u8;
+ static kCFBooleanTrue: CFTypeRef;
+}
+
+#[link(name = "ApplicationServices", kind = "framework")]
+extern "C" {
+ fn AXUIElementCreateSystemWide() -> AXUIElementRef;
+ fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef;
+ fn AXUIElementCopyElementAtPosition(
+ application: AXUIElementRef,
+ x: f32,
+ y: f32,
+ element: *mut AXUIElementRef,
+ ) -> AXError;
+ fn AXUIElementCopyAttributeValue(
+ element: AXUIElementRef,
+ attribute: CFStringRef,
+ value: *mut CFTypeRef,
+ ) -> AXError;
+ fn AXUIElementSetAttributeValue(
+ element: AXUIElementRef,
+ attribute: CFStringRef,
+ value: CFTypeRef,
+ ) -> AXError;
+ fn AXUIElementSetMessagingTimeout(element: AXUIElementRef, seconds: f32) -> AXError;
+ fn AXUIElementGetPid(element: AXUIElementRef, pid: *mut i32) -> AXError;
+ fn AXValueGetValue(value: CFTypeRef, kind: u32, out: *mut c_void) -> Boolean;
+}
+
+#[link(name = "CoreGraphics", kind = "framework")]
+extern "C" {
+ fn CGWindowListCopyWindowInfo(option: u32, relative_to: u32) -> CFArrayRef;
+ fn CGRectMakeWithDictionaryRepresentation(dictionary: CFDictionaryRef, rect: *mut CGRect) -> bool;
+ fn CGEventSourceFlagsState(state: i32) -> u64;
+ static kCGWindowLayer: CFStringRef;
+ static kCGWindowBounds: CFStringRef;
+ static kCGWindowOwnerPID: CFStringRef;
+ static kCGWindowOwnerName: CFStringRef;
+ static kCGWindowName: CFStringRef;
+ static kCGWindowAlpha: CFStringRef;
+}
+
+#[link(name = "Carbon", kind = "framework")]
+extern "C" {
+ fn TISCopyCurrentKeyboardLayoutInputSource() -> CFTypeRef;
+ fn TISCopyCurrentASCIICapableKeyboardLayoutInputSource() -> CFTypeRef;
+ fn TISGetInputSourceProperty(source: CFTypeRef, key: CFStringRef) -> CFTypeRef;
+ fn LMGetKbdType() -> u8;
+ fn UCKeyTranslate(
+ layout: *const u8,
+ keycode: u16,
+ action: u16,
+ modifiers: u32,
+ keyboard: u32,
+ options: u32,
+ dead_key: *mut u32,
+ max: usize,
+ length: *mut usize,
+ text: *mut u16,
+ ) -> i32;
+ static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
+}
+
+extern "C" {
+ fn proc_pidpath(pid: i32, buffer: *mut c_void, size: u32) -> i32;
+}
+
+struct Owned(CFTypeRef);
+
+impl Owned {
+ fn new(value: CFTypeRef) -> Option<Self> {
+ (!value.is_null()).then_some(Self(value))
+ }
+}
+
+impl Drop for Owned {
+ fn drop(&mut self) {
+ unsafe { CFRelease(self.0) };
+ }
+}
+
+fn cf_string(text: &str) -> Owned {
+ Owned(unsafe { CFStringCreateWithBytes(std::ptr::null(), text.as_ptr(), text.len() as isize, UTF8, 0) })
+}
+
+fn clean(value: String) -> Option<String> {
+ let trimmed = value.trim();
+ (!trimmed.is_empty()).then(|| trimmed.to_string())
+}
+
+fn string_of(value: CFTypeRef) -> Option<String> {
+ if value.is_null() || unsafe { CFGetTypeID(value) != CFStringGetTypeID() } {
+ return None;
+ }
+ let length = unsafe { CFStringGetLength(value) };
+ let size = unsafe { CFStringGetMaximumSizeForEncoding(length, UTF8) } + 1;
+ let mut buffer = vec![0 as c_char; size as usize];
+ if unsafe { CFStringGetCString(value, buffer.as_mut_ptr(), size, UTF8) } == 0 {
+ return None;
+ }
+ let text = unsafe { CStr::from_ptr(buffer.as_ptr()) };
+ clean(text.to_string_lossy().into_owned())
+}
+
+fn attribute(element: AXUIElementRef, name: &str) -> Option<Owned> {
+ let key = cf_string(name);
+ let mut value: CFTypeRef = std::ptr::null();
+ let read = unsafe { AXUIElementCopyAttributeValue(element, key.0, &mut value) };
+ if read == 0 {
+ Owned::new(value)
+ } else {
+ None
+ }
+}
+
+fn text(element: AXUIElementRef, name: &str) -> Option<String> {
+ attribute(element, name).and_then(|value| string_of(value.0))
+}
+
+fn ax_value<T: Default>(element: AXUIElementRef, name: &str, kind: u32) -> Option<T> {
+ let value = attribute(element, name)?;
+ let mut out = T::default();
+ (unsafe { AXValueGetValue(value.0, kind, (&mut out as *mut T).cast()) } != 0).then_some(out)
+}
+
+fn rect_of(element: AXUIElementRef) -> Option<ElementRect> {
+ let origin: CGPoint = ax_value(element, "AXPosition", AX_POINT)?;
+ let size: CGSize = ax_value(element, "AXSize", AX_SIZE)?;
+ (size.width > 0.0 && size.height > 0.0).then_some(ElementRect {
+ x: origin.x,
+ y: origin.y,
+ width: size.width,
+ height: size.height,
+ })
+}
+
+fn role_of(element: AXUIElementRef) -> Option<String> {
+ role(
+ text(element, "AXRole").as_deref(),
+ text(element, "AXSubrole").as_deref(),
+ )
+}
+
+fn secure(element: AXUIElementRef) -> bool {
+ text(element, "AXSubrole").as_deref() == Some("AXSecureTextField")
+}
+
+fn label_of(element: AXUIElementRef) -> Option<String> {
+ text(element, "AXTitle")
+ .or_else(|| text(element, "AXDescription"))
+ .or_else(|| {
+ let title = attribute(element, "AXTitleUIElement")?;
+ text(title.0, "AXValue").or_else(|| text(title.0, "AXTitle"))
+ })
+}
+
+fn describe(element: AXUIElementRef) -> UiElement {
+ let is_password = secure(element);
+ UiElement {
+ role: role_of(element),
+ name: label_of(element),
+ automation_id: text(element, "AXIdentifier"),
+ value: if is_password {
+ None
+ } else {
+ text(element, "AXValue")
+ },
+ help_text: text(element, "AXHelp").or_else(|| text(element, "AXPlaceholderValue")),
+ is_password,
+ rect: rect_of(element),
+ ancestors: Vec::new(),
+ children: Vec::new(),
+ }
+}
+
+fn node(element: AXUIElementRef) -> ElementNode {
+ ElementNode {
+ role: role_of(element),
+ name: label_of(element),
+ }
+}
+
+fn parent(element: AXUIElementRef) -> Option<Owned> {
+ attribute(element, "AXParent")
+}
+
+fn ancestors(element: AXUIElementRef) -> Vec<ElementNode> {
+ let mut out = Vec::new();
+ let mut current = parent(element);
+ while let Some(found) = current {
+ if out.len() == MAX_ANCESTORS {
+ break;
+ }
+ out.push(node(found.0));
+ current = parent(found.0);
+ }
+ out
+}
+
+fn children(element: AXUIElementRef) -> Vec<ElementNode> {
+ let Some(list) = attribute(element, "AXChildren") else {
+ return Vec::new();
+ };
+ if unsafe { CFGetTypeID(list.0) != CFArrayGetTypeID() } {
+ return Vec::new();
+ }
+ let count = unsafe { CFArrayGetCount(list.0) }.min(MAX_CHILDREN as isize);
+ (0..count)
+ .map(|index| node(unsafe { CFArrayGetValueAtIndex(list.0, index) }))
+ .collect()
+}
+
+fn promoted(hit: Owned) -> Owned {
+ if !is_label(role_of(hit.0).as_deref()) {
+ return hit;
+ }
+ let mut current = parent(hit.0);
+ for _ in 0..PROMOTE_DEPTH {
+ let Some(found) = current else { break };
+ if is_control(role_of(found.0).as_deref()) {
+ return found;
+ }
+ current = parent(found.0);
+ }
+ hit
+}
+
+static OPENED: Mutex<Option<HashSet<i32>>> = Mutex::new(None);
+
+fn pid_of(element: AXUIElementRef) -> Option<i32> {
+ let mut pid = 0;
+ (unsafe { AXUIElementGetPid(element, &mut pid) } == 0).then_some(pid)
+}
+
+fn ours(element: AXUIElementRef) -> bool {
+ pid_of(element) == Some(std::process::id() as i32)
+}
+
+fn open_web_content(element: AXUIElementRef) -> bool {
+ let Some(pid) = pid_of(element).filter(|_| !ours(element)) else {
+ return false;
+ };
+ let mut opened = OPENED.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
+ if !opened.get_or_insert_with(HashSet::new).insert(pid) {
+ return false;
+ }
+ let Some(app) = Owned::new(unsafe { AXUIElementCreateApplication(pid) }) else {
+ return false;
+ };
+ let key = cf_string("AXManualAccessibility");
+ unsafe { AXUIElementSetAttributeValue(app.0, key.0, kCFBooleanTrue) == 0 }
+}
+
+fn system() -> Option<Owned> {
+ let wide = Owned::new(unsafe { AXUIElementCreateSystemWide() })?;
+ unsafe { AXUIElementSetMessagingTimeout(wide.0, MESSAGING_TIMEOUT_SECONDS) };
+ Some(wide)
+}
+
+fn hit_test(wide: &Owned, x: i32, y: i32) -> Option<Owned> {
+ let mut found: AXUIElementRef = std::ptr::null();
+ let read = unsafe { AXUIElementCopyElementAtPosition(wide.0, x as f32, y as f32, &mut found) };
+ if read == 0 {
+ Owned::new(found)
+ } else {
+ None
+ }
+}
+
+pub fn element_at_point(x: i32, y: i32) -> Result<Option<UiElement>> {
+ let Some(wide) = system() else { return Ok(None) };
+ let Some(mut hit) = hit_test(&wide, x, y).filter(|found| !ours(found.0)) else {
+ return Ok(None);
+ };
+ if open_web_content(hit.0) {
+ if let Some(again) = hit_test(&wide, x, y) {
+ hit = again;
+ }
+ }
+ let found = promoted(hit);
+ let mut element = describe(found.0);
+ if element.name.is_none() {
+ element.ancestors = ancestors(found.0);
+ element.children = children(found.0);
+ }
+ Ok(Some(element))
+}
+
+pub fn focused_element() -> Result<Option<UiElement>> {
+ let Some(wide) = system() else { return Ok(None) };
+ Ok(attribute(wide.0, "AXFocusedUIElement").map(|found| describe(found.0)))
+}
+
+static DEAD_KEY: AtomicU32 = AtomicU32::new(0);
+
+const SHIFT: u32 = 1 << 9;
+const CAPS: u32 = 1 << 10;
+const OPTION: u32 = 1 << 11;
+const CONTROL: u32 = 1 << 12;
+const NO_DEAD_KEYS: u32 = 1;
+const CAPS_FLAG: u64 = 0x0001_0000;
+const COMBINED_SESSION: i32 = 0;
+
+fn translate(keycode: u16, modifiers: u32, options: u32, dead_key: &mut u32) -> Option<String> {
+ let source = Owned::new(unsafe { TISCopyCurrentKeyboardLayoutInputSource() })?;
+ let mut data = unsafe { TISGetInputSourceProperty(source.0, kTISPropertyUnicodeKeyLayoutData) };
+ let _fallback;
+ if data.is_null() {
+ let ascii = Owned::new(unsafe { TISCopyCurrentASCIICapableKeyboardLayoutInputSource() })?;
+ data = unsafe { TISGetInputSourceProperty(ascii.0, kTISPropertyUnicodeKeyLayoutData) };
+ _fallback = ascii;
+ }
+ if data.is_null() {
+ return None;
+ }
+ let layout = unsafe { CFDataGetBytePtr(data) };
+ let mut buffer = [0u16; 8];
+ let mut length = 0usize;
+ let status = unsafe {
+ UCKeyTranslate(
+ layout,
+ keycode,
+ 0,
+ (modifiers >> 8) & 0xff,
+ u32::from(LMGetKbdType()),
+ options,
+ dead_key,
+ buffer.len(),
+ &mut length,
+ buffer.as_mut_ptr(),
+ )
+ };
+ if status != 0 || length == 0 {
+ return None;
+ }
+ String::from_utf16(&buffer[..length]).ok()
+}
+
+pub fn key_label(keycode: u32) -> Option<String> {
+ if let Some(name) = named_key(keycode) {
+ return Some(name);
+ }
+ let mac = mac_keycode(keycode)?;
+ [0, SHIFT].iter().find_map(|&modifiers| {
+ let mut ignored = 0;
+ translate(mac, modifiers, NO_DEAD_KEYS, &mut ignored)
+ .filter(|found| found.chars().count() == 1 && found.chars().all(|found| found.is_ascii_alphanumeric()))
+ .map(|found| found.to_ascii_uppercase())
+ })
+}
+
+pub fn resolve_key(keycode: u32, shift: bool, ctrl: bool, alt: bool) -> Option<String> {
+ let mac = mac_keycode(keycode)?;
+ let mut modifiers = 0;
+ if shift {
+ modifiers |= SHIFT;
+ }
+ if alt {
+ modifiers |= OPTION;
+ }
+ if ctrl {
+ modifiers |= CONTROL;
+ }
+ if unsafe { CGEventSourceFlagsState(COMBINED_SESSION) } & CAPS_FLAG != 0 {
+ modifiers |= CAPS;
+ }
+ let mut dead_key = DEAD_KEY.load(Ordering::Relaxed);
+ let found = translate(mac, modifiers, 0, &mut dead_key);
+ DEAD_KEY.store(dead_key, Ordering::Relaxed);
+ found.and_then(|found| printable(&found))
+}
+
+pub fn clear_dead_key() {
+ DEAD_KEY.store(0, Ordering::Relaxed);
+}
+
+struct WindowInfo {
+ pid: i32,
+ owner: Option<String>,
+ title: Option<String>,
+ bounds: CGRect,
+}
+
+fn number(dictionary: CFDictionaryRef, key: CFStringRef, kind: isize) -> Option<f64> {
+ let value = unsafe { CFDictionaryGetValue(dictionary, key) };
+ if value.is_null() {
+ return None;
+ }
+ if kind == NUMBER_INT32 {
+ let mut out = 0i32;
+ (unsafe { CFNumberGetValue(value, kind, (&mut out as *mut i32).cast()) } != 0).then_some(f64::from(out))
+ } else {
+ let mut out = 0f64;
+ (unsafe { CFNumberGetValue(value, kind, (&mut out as *mut f64).cast()) } != 0).then_some(out)
+ }
+}
+
+fn windows() -> Vec<WindowInfo> {
+ let Some(list) = Owned::new(unsafe { CGWindowListCopyWindowInfo(ON_SCREEN_ONLY | EXCLUDE_DESKTOP, 0) })
+ else {
+ return Vec::new();
+ };
+ let own = std::process::id() as i32;
+ (0..unsafe { CFArrayGetCount(list.0) })
+ .filter_map(|index| {
+ let entry = unsafe { CFArrayGetValueAtIndex(list.0, index) };
+ let layer = number(entry, unsafe { kCGWindowLayer }, NUMBER_INT32)?;
+ let alpha = number(entry, unsafe { kCGWindowAlpha }, NUMBER_FLOAT64).unwrap_or(1.0);
+ let pid = number(entry, unsafe { kCGWindowOwnerPID }, NUMBER_INT32)? as i32;
+ if layer != 0.0 || alpha <= 0.0 || pid == own {
+ return None;
+ }
+ let mut bounds = CGRect::default();
+ let dictionary = unsafe { CFDictionaryGetValue(entry, kCGWindowBounds) };
+ if dictionary.is_null() || !unsafe { CGRectMakeWithDictionaryRepresentation(dictionary, &mut bounds) } {
+ return None;
+ }
+ (bounds.size.width > 1.0 && bounds.size.height > 1.0).then(|| WindowInfo {
+ pid,
+ owner: string_of(unsafe { CFDictionaryGetValue(entry, kCGWindowOwnerName) }),
+ title: string_of(unsafe { CFDictionaryGetValue(entry, kCGWindowName) }),
+ bounds,
+ })
+ })
+ .collect()
+}
+
+fn process_path(pid: i32) -> Option<String> {
+ let mut buffer = [0u8; 4096];
+ let length = unsafe { proc_pidpath(pid, buffer.as_mut_ptr().cast(), buffer.len() as u32) };
+ if length <= 0 {
+ return None;
+ }
+ clean(String::from_utf8_lossy(&buffer[..length as usize]).into_owned())
+}
+
+fn app_bundle(path: &str) -> String {
+ Path::new(path)
+ .ancestors()
+ .find(|found| found.extension().is_some_and(|extension| extension == "app"))
+ .map_or_else(|| path.to_string(), |found| found.to_string_lossy().into_owned())
+}
+
+fn framed(found: &WindowInfo) -> ActiveWindow {
+ let path = process_path(found.pid).map(|path| app_bundle(&path));
+ let app_name = found
+ .owner
+ .clone()
+ .or_else(|| {
+ path
+ .as_deref()
+ .and_then(|found| Path::new(found).file_stem())
+ .map(|stem| stem.to_string_lossy().into_owned())
+ })
+ .unwrap_or_default();
+ ActiveWindow {
+ title: found.title.clone(),
+ app_name,
+ app_path: path,
+ x: found.bounds.origin.x,
+ y: found.bounds.origin.y,
+ width: found.bounds.size.width,
+ height: found.bounds.size.height,
+ }
+}
+
+fn frontmost_pid() -> Option<i32> {
+ let wide = system()?;
+ let app = attribute(wide.0, "AXFocusedApplication")?;
+ pid_of(app.0)
+}
+
+pub fn active_window() -> Option<ActiveWindow> {
+ let all = windows();
+ let front = frontmost_pid();
+ all
+ .iter()
+ .find(|found| Some(found.pid) == front)
+ .or_else(|| all.first())
+ .map(framed)
+}
+
+pub fn window_at(x: i32, y: i32) -> Option<ActiveWindow> {
+ let (x, y) = (f64::from(x), f64::from(y));
+ windows()
+ .iter()
+ .find(|found| {
+ let bounds = found.bounds;
+ x >= bounds.origin.x
+ && y >= bounds.origin.y
+ && x < bounds.origin.x + bounds.size.width
+ && y < bounds.origin.y + bounds.size.height
+ })
+ .map(framed)
+}
diff --git a/packages/capture-native/src/machook.rs b/packages/capture-native/src/machook.rs
new file mode 100644
index 0000000..974caa7
--- /dev/null
+++ b/packages/capture-native/src/machook.rs
@@ -0,0 +1,163 @@
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicPtr, Ordering};
+use std::sync::{mpsc, OnceLock};
+use std::time::Duration;
+
+use napi::threadsafe_function::ThreadsafeFunctionCallMode;
+use napi::Result;
+
+use crate::macmap::hook_keycode;
+use crate::{HookCallback, HookEvent};
+
+type CFTypeRef = *const c_void;
+type CGEventRef = *const c_void;
+
+#[repr(C)]
+#[derive(Default, Clone, Copy)]
+struct CGPoint {
+ x: f64,
+ y: f64,
+}
+
+type TapCallback = extern "C" fn(*const c_void, u32, CGEventRef, *mut c_void) -> CGEventRef;
+
+#[link(name = "CoreGraphics", kind = "framework")]
+extern "C" {
+ fn CGEventTapCreate(
+ tap: u32,
+ place: u32,
+ options: u32,
+ events: u64,
+ callback: TapCallback,
+ info: *mut c_void,
+ ) -> CFTypeRef;
+ fn CGEventTapEnable(tap: CFTypeRef, enable: bool);
+ fn CGEventGetLocation(event: CGEventRef) -> CGPoint;
+ fn CGEventGetIntegerValueField(event: CGEventRef, field: u32) -> i64;
+ fn CGEventGetFlags(event: CGEventRef) -> u64;
+}
+
+#[link(name = "CoreFoundation", kind = "framework")]
+extern "C" {
+ fn CFMachPortCreateRunLoopSource(allocator: *const c_void, port: CFTypeRef, order: isize) -> CFTypeRef;
+ fn CFRunLoopGetCurrent() -> CFTypeRef;
+ fn CFRunLoopAddSource(run_loop: CFTypeRef, source: CFTypeRef, mode: CFTypeRef);
+ fn CFRunLoopRun();
+ static kCFRunLoopCommonModes: CFTypeRef;
+}
+
+const SESSION_TAP: u32 = 1;
+const HEAD_INSERT: u32 = 0;
+const ACTIVE_TAP: u32 = 0;
+const LEFT_DOWN: u32 = 1;
+const RIGHT_DOWN: u32 = 3;
+const OTHER_DOWN: u32 = 25;
+const KEY_DOWN: u32 = 10;
+const DISABLED_BY_TIMEOUT: u32 = 0xFFFF_FFFE;
+const DISABLED_BY_USER: u32 = 0xFFFF_FFFF;
+const CLICK_STATE: u32 = 1;
+const KEYCODE: u32 = 9;
+const SHIFT: u64 = 1 << 17;
+const CONTROL: u64 = 1 << 18;
+const OPTION: u64 = 1 << 19;
+const COMMAND: u64 = 1 << 20;
+const START_TIMEOUT: Duration = Duration::from_secs(3);
+
+static CALLBACK: OnceLock<HookCallback> = OnceLock::new();
+static TAP: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
+
+fn event(kind: &str, button: u32, at: CGPoint, clicks: i64, keycode: u32, flags: u64) -> HookEvent {
+ HookEvent {
+ kind: kind.to_string(),
+ button,
+ x: at.x,
+ y: at.y,
+ clicks: clicks.max(1) as u32,
+ keycode,
+ shift: flags & SHIFT != 0,
+ ctrl: flags & CONTROL != 0,
+ alt: flags & OPTION != 0,
+ meta: flags & COMMAND != 0,
+ }
+}
+
+extern "C" fn on_event(_proxy: *const c_void, kind: u32, raw: CGEventRef, _info: *mut c_void) -> CGEventRef {
+ if kind == DISABLED_BY_TIMEOUT || kind == DISABLED_BY_USER {
+ let tap = TAP.load(Ordering::Acquire);
+ if !tap.is_null() {
+ unsafe { CGEventTapEnable(tap, true) };
+ }
+ return raw;
+ }
+ let Some(callback) = CALLBACK.get() else {
+ return raw;
+ };
+ let flags = unsafe { CGEventGetFlags(raw) };
+ let found = match kind {
+ LEFT_DOWN | RIGHT_DOWN | OTHER_DOWN => {
+ let button = match kind {
+ LEFT_DOWN => 1,
+ RIGHT_DOWN => 2,
+ _ => 3,
+ };
+ let at = unsafe { CGEventGetLocation(raw) };
+ let clicks = unsafe { CGEventGetIntegerValueField(raw, CLICK_STATE) };
+ Some(event("click", button, at, clicks, 0, flags))
+ }
+ KEY_DOWN => {
+ let mac = unsafe { CGEventGetIntegerValueField(raw, KEYCODE) } as u16;
+ Some(event(
+ "keydown",
+ 0,
+ CGPoint::default(),
+ 1,
+ hook_keycode(mac),
+ flags,
+ ))
+ }
+ _ => None,
+ };
+ if let Some(found) = found {
+ callback.call(found, ThreadsafeFunctionCallMode::NonBlocking);
+ }
+ raw
+}
+
+pub fn start(callback: HookCallback) -> Result<()> {
+ if CALLBACK.set(callback).is_err() {
+ return Ok(());
+ }
+ let (ready, started) = mpsc::channel::<bool>();
+ std::thread::spawn(move || {
+ let mask = (1u64 << LEFT_DOWN) | (1u64 << RIGHT_DOWN) | (1u64 << OTHER_DOWN) | (1u64 << KEY_DOWN);
+ let tap = unsafe {
+ CGEventTapCreate(
+ SESSION_TAP,
+ HEAD_INSERT,
+ ACTIVE_TAP,
+ mask,
+ on_event,
+ std::ptr::null_mut(),
+ )
+ };
+ if tap.is_null() {
+ let _ = ready.send(false);
+ return;
+ }
+ TAP.store(tap as *mut c_void, Ordering::Release);
+ unsafe {
+ let source = CFMachPortCreateRunLoopSource(std::ptr::null(), tap, 0);
+ CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
+ CGEventTapEnable(tap, true);
+ }
+ let _ = ready.send(true);
+ unsafe { CFRunLoopRun() };
+ });
+ match started.recv_timeout(START_TIMEOUT) {
+ Ok(true) => Ok(()),
+ Ok(false) => Err(napi::Error::from_reason(
+ "macOS refused the event tap: Mimik needs Accessibility permission",
+ )),
+ Err(_) => Err(napi::Error::from_reason("the event tap did not start")),
+ }
+}
diff --git a/packages/capture-native/src/macmap.rs b/packages/capture-native/src/macmap.rs
new file mode 100644
index 0000000..124287d
--- /dev/null
+++ b/packages/capture-native/src/macmap.rs
@@ -0,0 +1,305 @@
+const ROLES: &[(&str, &str)] = &[
+ ("AXButton", "button"),
+ ("AXMenuButton", "button"),
+ ("AXDisclosureTriangle", "button"),
+ ("AXColorWell", "button"),
+ ("AXCheckBox", "checkbox"),
+ ("AXRadioButton", "radio"),
+ ("AXTextField", "textbox"),
+ ("AXTextArea", "textbox"),
+ ("AXDateField", "textbox"),
+ ("AXComboBox", "combobox"),
+ ("AXPopUpButton", "combobox"),
+ ("AXLink", "link"),
+ ("AXImage", "img"),
+ ("AXStaticText", "text"),
+ ("AXHeading", "heading"),
+ ("AXMenuItem", "menuitem"),
+ ("AXMenuBarItem", "menuitem"),
+ ("AXMenu", "menu"),
+ ("AXMenuBar", "menubar"),
+ ("AXList", "list"),
+ ("AXTable", "table"),
+ ("AXOutline", "tree"),
+ ("AXRow", "row"),
+ ("AXCell", "cell"),
+ ("AXColumn", "columnheader"),
+ ("AXTabGroup", "tablist"),
+ ("AXSlider", "slider"),
+ ("AXIncrementor", "spinbutton"),
+ ("AXProgressIndicator", "progressbar"),
+ ("AXLevelIndicator", "progressbar"),
+ ("AXScrollBar", "scrollbar"),
+ ("AXValueIndicator", "thumb"),
+ ("AXToolbar", "toolbar"),
+ ("AXGroup", "group"),
+ ("AXSplitGroup", "group"),
+ ("AXRadioGroup", "group"),
+ ("AXScrollArea", "pane"),
+ ("AXWebArea", "document"),
+ ("AXWindow", "window"),
+ ("AXSheet", "window"),
+ ("AXHelpTag", "tooltip"),
+ ("AXSplitter", "separator"),
+];
+
+const SUBROLES: &[(&str, &str)] = &[
+ ("AXSwitch", "switch"),
+ ("AXTabButton", "tab"),
+ ("AXOutlineRow", "treeitem"),
+ ("AXSearchField", "textbox"),
+ ("AXSecureTextField", "textbox"),
+];
+
+const CONTROLS: &[&str] = &[
+ "button", "checkbox", "switch", "radio", "link", "menuitem", "tab", "treeitem", "row", "cell", "combobox",
+];
+
+pub const PROMOTE_DEPTH: usize = 3;
+
+pub fn role(role: Option<&str>, subrole: Option<&str>) -> Option<String> {
+ let find = |table: &[(&str, &str)], key: Option<&str>| {
+ key.and_then(|key| {
+ table
+ .iter()
+ .find(|(ax, _)| *ax == key)
+ .map(|(_, name)| (*name).to_string())
+ })
+ };
+ find(SUBROLES, subrole).or_else(|| find(ROLES, role))
+}
+
+pub fn is_label(role: Option<&str>) -> bool {
+ matches!(role, Some("text" | "img"))
+}
+
+pub fn is_control(role: Option<&str>) -> bool {
+ role.is_some_and(|role| CONTROLS.contains(&role))
+}
+
+const KEYCODES: &[(u32, u16)] = &[
+ (0x02, 0x12),
+ (0x03, 0x13),
+ (0x04, 0x14),
+ (0x05, 0x15),
+ (0x06, 0x17),
+ (0x07, 0x16),
+ (0x08, 0x1a),
+ (0x09, 0x1c),
+ (0x0a, 0x19),
+ (0x0b, 0x1d),
+ (0x0c, 0x1b),
+ (0x0d, 0x18),
+ (0x10, 0x0c),
+ (0x11, 0x0d),
+ (0x12, 0x0e),
+ (0x13, 0x0f),
+ (0x14, 0x11),
+ (0x15, 0x10),
+ (0x16, 0x20),
+ (0x17, 0x22),
+ (0x18, 0x1f),
+ (0x19, 0x23),
+ (0x1a, 0x21),
+ (0x1b, 0x1e),
+ (0x1e, 0x00),
+ (0x1f, 0x01),
+ (0x20, 0x02),
+ (0x21, 0x03),
+ (0x22, 0x05),
+ (0x23, 0x04),
+ (0x24, 0x26),
+ (0x25, 0x28),
+ (0x26, 0x25),
+ (0x27, 0x29),
+ (0x28, 0x27),
+ (0x29, 0x32),
+ (0x2b, 0x2a),
+ (0x2c, 0x06),
+ (0x2d, 0x07),
+ (0x2e, 0x08),
+ (0x2f, 0x09),
+ (0x30, 0x0b),
+ (0x31, 0x2d),
+ (0x32, 0x2e),
+ (0x33, 0x2b),
+ (0x34, 0x2f),
+ (0x35, 0x2c),
+ (0x39, 0x31),
+ (0x56, 0x0a),
+];
+
+const NAMED_KEYS: &[(u32, &str)] = &[
+ (0x1c, "Enter"),
+ (0x0f, "Tab"),
+ (0x01, "Escape"),
+ (0x0e, "Backspace"),
+ (0x39, "Space"),
+ (0x0e53, "Delete"),
+ (0x0e52, "Insert"),
+ (0x0e47, "Home"),
+ (0x0e4f, "End"),
+ (0x0e49, "PageUp"),
+ (0x0e51, "PageDown"),
+ (0xe048, "ArrowUp"),
+ (0xe050, "ArrowDown"),
+ (0xe04b, "ArrowLeft"),
+ (0xe04d, "ArrowRight"),
+];
+
+const FUNCTION_KEYS: &[(u32, u8)] = &[
+ (0x3b, 1),
+ (0x3c, 2),
+ (0x3d, 3),
+ (0x3e, 4),
+ (0x3f, 5),
+ (0x40, 6),
+ (0x41, 7),
+ (0x42, 8),
+ (0x43, 9),
+ (0x44, 10),
+ (0x57, 11),
+ (0x58, 12),
+];
+
+const MAC_ONLY_KEYS: &[(u16, u32)] = &[
+ (0x24, 0x1c),
+ (0x4c, 0x0e1c),
+ (0x30, 0x0f),
+ (0x35, 0x01),
+ (0x33, 0x0e),
+ (0x75, 0x0e53),
+ (0x72, 0x0e52),
+ (0x73, 0x0e47),
+ (0x77, 0x0e4f),
+ (0x74, 0x0e49),
+ (0x79, 0x0e51),
+ (0x7e, 0xe048),
+ (0x7d, 0xe050),
+ (0x7b, 0xe04b),
+ (0x7c, 0xe04d),
+ (0x7a, 0x3b),
+ (0x78, 0x3c),
+ (0x63, 0x3d),
+ (0x76, 0x3e),
+ (0x60, 0x3f),
+ (0x61, 0x40),
+ (0x62, 0x41),
+ (0x64, 0x42),
+ (0x65, 0x43),
+ (0x6d, 0x44),
+ (0x67, 0x57),
+ (0x6f, 0x58),
+];
+
+pub fn hook_keycode(mac: u16) -> u32 {
+ KEYCODES
+ .iter()
+ .find(|(_, found)| *found == mac)
+ .map(|(vc, _)| *vc)
+ .or_else(|| {
+ MAC_ONLY_KEYS
+ .iter()
+ .find(|(found, _)| *found == mac)
+ .map(|(_, vc)| *vc)
+ })
+ .unwrap_or(0)
+}
+
+pub fn mac_keycode(keycode: u32) -> Option<u16> {
+ KEYCODES
+ .iter()
+ .find(|(vc, _)| *vc == keycode)
+ .map(|(_, mac)| *mac)
+}
+
+pub fn named_key(keycode: u32) -> Option<String> {
+ if let Some((_, name)) = NAMED_KEYS.iter().find(|(vc, _)| *vc == keycode) {
+ return Some((*name).to_string());
+ }
+ FUNCTION_KEYS
+ .iter()
+ .find(|(vc, _)| *vc == keycode)
+ .map(|(_, number)| format!("F{number}"))
+}
+
+pub fn printable(text: &str) -> Option<String> {
+ (!text.is_empty() && text.chars().all(|found| !found.is_control())).then(|| text.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{hook_keycode, is_control, is_label, mac_keycode, named_key, printable, role};
+
+ #[test]
+ fn mac_keys_come_back_as_hook_codes() {
+ assert_eq!(hook_keycode(0x00), 0x1e);
+ assert_eq!(hook_keycode(0x24), 0x1c);
+ assert_eq!(hook_keycode(0x33), 0x0e);
+ assert_eq!(hook_keycode(0x7b), 0xe04b);
+ assert_eq!(hook_keycode(0x6f), 0x58);
+ assert_eq!(hook_keycode(0xff), 0);
+ for vc in [0x1e, 0x10, 0x02, 0x0b, 0x35] {
+ assert_eq!(hook_keycode(mac_keycode(vc).unwrap()), vc);
+ }
+ }
+
+ #[test]
+ fn subroles_win_over_roles() {
+ assert_eq!(
+ role(Some("AXCheckBox"), Some("AXSwitch")).as_deref(),
+ Some("switch")
+ );
+ assert_eq!(
+ role(Some("AXRadioButton"), Some("AXTabButton")).as_deref(),
+ Some("tab")
+ );
+ assert_eq!(
+ role(Some("AXRow"), Some("AXOutlineRow")).as_deref(),
+ Some("treeitem")
+ );
+ assert_eq!(
+ role(Some("AXCheckBox"), Some("AXUnknown")).as_deref(),
+ Some("checkbox")
+ );
+ }
+
+ #[test]
+ fn unknown_roles_are_null() {
+ assert_eq!(role(Some("AXLayoutArea"), None), None);
+ assert_eq!(role(None, None), None);
+ }
+
+ #[test]
+ fn text_inside_a_control_is_a_label() {
+ assert!(is_label(Some("text")));
+ assert!(is_label(Some("img")));
+ assert!(!is_label(Some("button")));
+ assert!(is_control(Some("button")));
+ assert!(!is_control(Some("group")));
+ assert!(!is_control(None));
+ }
+
+ #[test]
+ fn hook_codes_map_to_mac_virtual_keys() {
+ assert_eq!(mac_keycode(0x1e), Some(0x00));
+ assert_eq!(mac_keycode(0x10), Some(0x0c));
+ assert_eq!(mac_keycode(0x0b), Some(0x1d));
+ assert_eq!(mac_keycode(0xe048), None);
+ }
+
+ #[test]
+ fn named_and_function_keys_skip_the_layout() {
+ assert_eq!(named_key(0x1c).as_deref(), Some("Enter"));
+ assert_eq!(named_key(0xe04b).as_deref(), Some("ArrowLeft"));
+ assert_eq!(named_key(0x58).as_deref(), Some("F12"));
+ assert_eq!(named_key(0x1e), None);
+ }
+
+ #[test]
+ fn control_characters_are_not_typing() {
+ assert_eq!(printable("Γ©").as_deref(), Some("Γ©"));
+ assert_eq!(printable("\u{13}"), None);
+ assert_eq!(printable(""), None);
+ }
+}