use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType, NSView, NSWindow};
use objc2_foundation::{NSPoint, NSProcessInfo, NSString};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Key {
Char(char),
Return,
Tab,
Escape,
Delete,
Left,
Right,
Up,
Down,
}
fn code_of(c: char) -> u16 {
const KEYS: &str = "asdfhgzxcv\0bqweryt123465=97-80]ou[ip\0lj'k;\\,/nm.";
if c == ' ' {
return 49;
}
KEYS.chars().position(|k| k == c.to_ascii_lowercase()).map_or(0, |i| i as u16)
}
impl Key {
fn parts(self) -> (u16, String, bool) {
let f = |c: u32| char::from_u32(c).unwrap().to_string();
match self {
Key::Char(c) => (code_of(c), c.to_string(), false),
Key::Return => (36, "\r".into(), false),
Key::Tab => (48, "\t".into(), false),
Key::Escape => (53, "\u{1b}".into(), false),
Key::Delete => (51, "\u{7f}".into(), false),
Key::Left => (123, f(0xF702), true),
Key::Right => (124, f(0xF703), true),
Key::Down => (125, f(0xF701), true),
Key::Up => (126, f(0xF700), true),
}
}
}
pub(crate) fn flags(mods: &[crate::Modifier]) -> NSEventModifierFlags {
let mut f = NSEventModifierFlags::empty();
for m in mods {
f |= match m {
crate::Modifier::Command => NSEventModifierFlags::Command,
crate::Modifier::Shift => NSEventModifierFlags::Shift,
crate::Modifier::Option => NSEventModifierFlags::Option,
crate::Modifier::Control => NSEventModifierFlags::Control,
};
}
f
}
fn now() -> f64 {
NSProcessInfo::processInfo().systemUptime()
}
fn post(event: Option<Retained<NSEvent>>) {
if let Some(e) = event {
NSApplication::sharedApplication(crate::mtm()).postEvent_atStart(&e, false);
}
}
pub fn ready(window: &crate::WindowRef) -> bool {
let window = window.ns();
let app = NSApplication::sharedApplication(crate::mtm());
if !app.isActive() {
#[allow(deprecated)]
app.activateIgnoringOtherApps(true);
}
if !window.isKeyWindow() {
window.makeKeyAndOrderFront(None);
}
app.isActive() && window.isKeyWindow()
}
fn in_window(view: &NSView, x: f64, y: f64) -> NSPoint {
let b = view.bounds();
let y = if view.isFlipped() { y } else { b.size.height - y };
view.convertPoint_toView(NSPoint::new(b.origin.x + x, b.origin.y + y), None)
}
fn mouse(window: &NSWindow, kind: NSEventType, at: NSPoint, clicks: isize, mods: &[crate::Modifier]) {
post(NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
kind,
at,
flags(mods),
now(),
window.windowNumber(),
None,
0,
clicks,
1.0,
));
}
pub fn click_at_with(view: &NSView, x: f64, y: f64, mods: &[crate::Modifier]) -> bool {
let Some(window) = view.window() else { return false };
let at = in_window(view, x, y);
mouse(&window, NSEventType::LeftMouseDown, at, 1, mods);
mouse(&window, NSEventType::LeftMouseUp, at, 1, mods);
true
}
pub fn click_at(view: &NSView, x: f64, y: f64) -> bool {
click_at_with(view, x, y, &[])
}
pub fn click(view: &NSView) -> bool {
let b = view.bounds();
click_at(view, b.size.width / 2.0, b.size.height / 2.0)
}
pub fn double_click(view: &NSView) -> bool {
let Some(window) = view.window() else { return false };
let b = view.bounds();
let at = in_window(view, b.size.width / 2.0, b.size.height / 2.0);
for clicks in [1, 2] {
mouse(&window, NSEventType::LeftMouseDown, at, clicks, &[]);
mouse(&window, NSEventType::LeftMouseUp, at, clicks, &[]);
}
true
}
pub fn key(window: &crate::WindowRef, key: Key, mods: &[crate::Modifier]) {
let window = window.ns();
let (code, chars, function) = key.parts();
let mut f = flags(mods);
if function {
f |= NSEventModifierFlags::Function | NSEventModifierFlags::NumericPad;
}
let s = NSString::from_str(&chars);
for kind in [NSEventType::KeyDown, NSEventType::KeyUp] {
post(NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
kind,
NSPoint::ZERO,
f,
now(),
window.windowNumber(),
None,
&s,
&s,
false,
code,
));
}
}
pub fn type_text(window: &crate::WindowRef, text: &str) {
for c in text.chars() {
match c {
'\n' => key(window, Key::Return, &[]),
'\t' => key(window, Key::Tab, &[]),
c if c.is_uppercase() => key(window, Key::Char(c), &[crate::Modifier::Shift]),
c => key(window, Key::Char(c), &[]),
}
}
}
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn AXIsProcessTrusted() -> u8;
}
pub fn server_available() -> bool {
unsafe { AXIsProcessTrusted() != 0 }
}
fn pid() -> i32 {
std::process::id() as i32
}
pub fn server_click(view: &NSView) -> bool {
use objc2_core_graphics::{CGEvent, CGEventType, CGMouseButton};
let Some(window) = view.window().filter(|_| server_available()) else { return false };
let b = view.bounds();
let p = window.convertPointToScreen(in_window(view, b.size.width / 2.0, b.size.height / 2.0));
let top = objc2_app_kit::NSScreen::screens(crate::mtm()).firstObject().map_or(0.0, |s| s.frame().size.height);
let at = objc2_core_foundation::CGPoint::new(p.x, top - p.y);
for kind in [CGEventType::LeftMouseDown, CGEventType::LeftMouseUp] {
if let Some(e) = CGEvent::new_mouse_event(None, kind, at, CGMouseButton::Left) {
CGEvent::post_to_pid(pid(), Some(&e));
}
}
true
}
pub fn server_type(text: &str) -> bool {
use objc2_core_graphics::CGEvent;
if !server_available() {
return false;
}
for c in text.chars() {
let units: Vec<u16> = c.to_string().encode_utf16().collect();
for down in [true, false] {
if let Some(e) = CGEvent::new_keyboard_event(None, code_of(c), down) {
unsafe { CGEvent::keyboard_set_unicode_string(Some(&e), units.len() as _, units.as_ptr()) };
CGEvent::post_to_pid(pid(), Some(&e));
}
}
}
true
}