use ferrokit_core::kept::{UiCell, UiLocal};
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSTextField};
use objc2_foundation::NSString;
use crate::mtm;
#[path = "input.rs"]
pub mod input;
#[path = "soak.rs"]
pub mod soak;
thread_local! {
static FAILED_CHECKS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}
pub fn check(name: &str, pass: bool, note: impl std::fmt::Display) {
eprintln!("[check] {name} {} {note}", if pass { "PASS" } else { "FAIL" });
if !pass {
FAILED_CHECKS.set(FAILED_CHECKS.get() + 1);
}
}
pub fn skip(name: &str, why: impl std::fmt::Display) {
eprintln!("[check] {name} SKIP {why}");
}
pub fn finish() -> ! {
let failed = FAILED_CHECKS.get();
eprintln!("[check] done, {failed} failed");
std::process::exit(if failed == 0 { 0 } else { 1 });
}
pub fn steps(pause_ms: u64, steps: Vec<Box<dyn FnOnce()>>) {
fn next(pause_ms: u64, mut rest: std::collections::VecDeque<Box<dyn FnOnce()>>) {
crate::spawn(
move || std::thread::sleep(std::time::Duration::from_millis(pause_ms)),
move |()| {
if still_waiting() {
return next(WAIT_POLL_MS, rest);
}
match rest.pop_front() {
Some(step) => {
step();
next(pause_ms, rest);
}
None => finish(),
}
},
);
}
next(pause_ms, steps.into());
}
const WAIT_POLL_MS: u64 = 20;
type Wait = (Box<dyn Fn() -> bool>, std::time::Instant, u64);
thread_local! {
static WAIT: UiCell<Option<Wait>> = UiCell::new(None);
}
fn still_waiting() -> bool {
let Some((condition, deadline, ms)) = WAIT.with(|w| w.borrow_mut().take()) else { return false };
if condition() {
return false;
}
if std::time::Instant::now() >= deadline {
eprintln!("[check] (waited {ms} ms for a condition that stayed false; going on)");
return false;
}
WAIT.with(|w| *w.borrow_mut() = Some((condition, deadline, ms)));
true
}
pub fn wait_for(timeout_ms: u64, condition: impl Fn() -> bool + 'static) {
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
WAIT.with(|w| *w.borrow_mut() = Some((Box::new(condition), deadline, timeout_ms)));
}
pub fn wait_until(timeout_ms: u64, condition: impl Fn() -> bool + 'static, then: impl FnOnce(bool) + 'static) {
fn poll(deadline: std::time::Instant, condition: Box<dyn Fn() -> bool>, then: Box<dyn FnOnce(bool)>) {
if condition() {
return then(true);
}
if std::time::Instant::now() >= deadline {
return then(false);
}
crate::spawn(move || std::thread::sleep(std::time::Duration::from_millis(WAIT_POLL_MS)), move |()| poll(deadline, condition, then));
}
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
poll(deadline, Box::new(condition), Box::new(then));
}
pub fn press_sheet_button(window: &crate::WindowRef, title: &str) -> bool {
let window = window.ns();
fn find(view: &objc2_app_kit::NSView, title: &str) -> Option<Retained<objc2_app_kit::NSButton>> {
if let Some(b) = view.downcast_ref::<objc2_app_kit::NSButton>()
&& b.title().to_string() == title
&& b.isEnabled()
{
return Some(objc2::Message::retain(b));
}
view.subviews().iter().find_map(|v| find(&v, title))
}
let Some(sheet) = window.attachedSheet() else { return false };
let Some(button) = sheet.contentView().and_then(|v| find(&v, title)) else { return false };
unsafe { button.performClick(None) };
true
}
pub fn view_labeled(window: &crate::WindowRef, label: &str) -> Option<Retained<objc2_app_kit::NSView>> {
let window = window.ns();
fn find(view: &objc2_app_kit::NSView, label: &str) -> Option<Retained<objc2_app_kit::NSView>> {
let own: Option<Retained<NSString>> = unsafe { objc2::msg_send![view, accessibilityLabel] };
if own.is_some_and(|l| l.to_string() == label) {
return Some(objc2::Message::retain(view));
}
view.subviews().iter().find_map(|v| find(&v, label))
}
find(&*window.contentView()?, label)
}
pub fn footprint_mb() -> f64 {
rusage().map_or(0.0, |r| r.ri_phys_footprint as f64 / (1 << 20) as f64)
}
pub fn peak_footprint_mb() -> f64 {
rusage().map_or(0.0, |r| r.ri_lifetime_max_phys_footprint as f64 / (1 << 20) as f64)
}
fn rusage() -> Option<libc::rusage_info_v4> {
let mut info = std::mem::MaybeUninit::<libc::rusage_info_v4>::zeroed();
let ok = unsafe { libc::proc_pid_rusage(std::process::id() as i32, libc::RUSAGE_INFO_V4, info.as_mut_ptr().cast()) } == 0;
ok.then(|| unsafe { info.assume_init() })
}
pub fn ax_tree(window: &crate::WindowRef) -> Vec<(String, String, String)> {
let window = window.ns();
fn responds(obj: &objc2::runtime::AnyObject, sel: objc2::runtime::Sel) -> bool {
obj.class().responds_to(sel)
}
fn s(obj: &objc2::runtime::AnyObject, sel: &str) -> String {
let selector = match sel {
"role" => objc2::sel!(accessibilityRole),
"subrole" => objc2::sel!(accessibilitySubrole),
"label" => objc2::sel!(accessibilityLabel),
_ => objc2::sel!(accessibilityTitle),
};
if !responds(obj, selector) {
return String::new();
}
let value: Option<Retained<objc2::runtime::AnyObject>> = unsafe {
match sel {
"role" => objc2::msg_send![obj, accessibilityRole],
"subrole" => objc2::msg_send![obj, accessibilitySubrole],
"label" => objc2::msg_send![obj, accessibilityLabel],
_ => objc2::msg_send![obj, accessibilityTitle],
}
};
value.and_then(|v| v.downcast::<NSString>().ok()).map(|s| s.to_string()).unwrap_or_default()
}
fn walk(obj: &objc2::runtime::AnyObject, out: &mut Vec<(String, String, String)>, depth: usize) {
let label = { let l = s(obj, "label"); if l.is_empty() { s(obj, "title") } else { l } };
out.push((s(obj, "role"), s(obj, "subrole"), label));
if depth > 12 {
return;
}
if !responds(obj, objc2::sel!(accessibilityChildren)) {
return;
}
let kids: Option<Retained<objc2_foundation::NSArray<objc2::runtime::AnyObject>>> =
unsafe { objc2::msg_send![obj, accessibilityChildren] };
if let Some(kids) = kids {
for k in kids.iter() {
walk(&k, out, depth + 1);
}
}
}
let mut out = Vec::new();
walk(&window.contentView().unwrap(), &mut out, 0);
out
}
pub fn has_ax(tree: &[(String, String, String)], role: &str, subrole: &str, label: &str) -> bool {
tree.iter().any(|(r, s, l)| r == role && (subrole.is_empty() || s == subrole) && (label.is_empty() || l == label))
}
pub fn post_edit(field: &NSTextField, text: &str) {
field.setStringValue(&NSString::from_str(text));
unsafe {
objc2_foundation::NSNotificationCenter::defaultCenter()
.postNotificationName_object(objc2_app_kit::NSControlTextDidChangeNotification, Some(field))
};
}
pub fn send_action(control: &objc2_app_kit::NSControl) -> bool {
unsafe { control.sendAction_to(control.action(), control.target().as_deref()) }
}
pub fn set_right_to_left(on: Option<bool>) {
crate::force_right_to_left(on);
}
pub fn failures() -> Vec<crate::Failure> {
crate::failure::caught()
}
pub fn thumbnails_made() -> usize {
crate::quicklook::THUMBNAILS.with(std::cell::Cell::get)
}
pub fn quick_look_state() -> (Vec<std::path::PathBuf>, Option<usize>) {
crate::quicklook::quick_look_state()
}
pub fn snapshot_windows(dir: &str) {
for w in crate::windows_ns() {
let content = w.contentView().unwrap();
let view = unsafe { content.superview() }.unwrap_or(content);
let bounds = view.bounds();
let Some(rep) = view.bitmapImageRepForCachingDisplayInRect(bounds) else { continue };
view.cacheDisplayInRect_toBitmapImageRep(bounds, &rep);
let png = unsafe {
rep.representationUsingType_properties(objc2_app_kit::NSBitmapImageFileType::PNG, &objc2_foundation::NSDictionary::new())
};
if let Some(png) = png {
let path = format!("{dir}/{}.png", w.title());
png.writeToFile_atomically(&NSString::from_str(&path), true);
}
}
}
pub fn about_shown() -> u32 {
crate::ABOUT_SHOWN.with(|a| a.get())
}
pub fn menu_key(chars: &str, modifiers: &[crate::Modifier]) -> bool {
let modifiers = input::flags(modifiers);
use objc2_app_kit::{NSEvent, NSEventType};
let event = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEventType::KeyDown,
objc2_foundation::NSPoint::new(0.0, 0.0),
modifiers,
0.0,
0,
None,
&NSString::from_str(chars),
&NSString::from_str(chars),
false,
0,
)
.unwrap();
NSApplication::sharedApplication(mtm()).mainMenu().unwrap().performKeyEquivalent(&event)
}
pub fn shortcut(window: &crate::WindowRef, chars: &str, shift: bool) -> bool {
let window = window.ns();
use objc2_app_kit::{NSEventModifierFlags, NSMenu};
fn find(menu: &NSMenu, key: &str, shift: bool) -> Option<(Retained<NSMenu>, isize)> {
for i in 0..menu.numberOfItems() {
let item = menu.itemAtIndex(i)?;
if let Some(sub) = item.submenu() {
if let Some(found) = find(&sub, key, shift) {
return Some(found);
}
continue;
}
let k = item.keyEquivalent().to_string();
let mask = item.keyEquivalentModifierMask();
let wants_shift = mask.contains(NSEventModifierFlags::Shift) || (k.chars().all(char::is_uppercase) && !k.is_empty());
let others = mask.intersects(NSEventModifierFlags::Option | NSEventModifierFlags::Control);
if k.to_lowercase() == key && mask.contains(NSEventModifierFlags::Command) && wants_shift == shift && !others {
return Some((objc2::Message::retain(menu), i));
}
}
None
}
let app = NSApplication::sharedApplication(mtm());
let Some((menu, i)) = app.mainMenu().and_then(|m| find(&m, &chars.to_lowercase(), shift)) else { return false };
let Some(item) = menu.itemAtIndex(i) else { return false };
if item.target().is_some() {
menu.update();
if !item.isEnabled() {
return false;
}
menu.performActionForItemAtIndex(i);
return true;
}
let Some(action) = item.action() else { return false };
window.firstResponder().is_some_and(|r| unsafe { r.tryToPerform_with(action, Some(&item)) })
}
pub fn capture_reveals(on: bool) {
crate::services::capture_reveals(on);
}
pub fn revealed() -> Vec<Vec<std::path::PathBuf>> {
crate::services::take_reveals()
}
pub fn set_last_opened(path: &std::path::Path, secs: Option<i64>) -> std::io::Result<()> {
crate::services::set_last_opened(path, secs)
}
pub fn catching(f: impl FnOnce()) {
crate::failure::entry("a check", (), f);
}
pub fn pending_crash_reports(dir: &std::path::Path) -> Vec<crate::CrashReport> {
crate::crash::pending(dir)
}
pub fn is_misspelled(word: &str) -> bool {
let checker = objc2_app_kit::NSSpellChecker::sharedSpellChecker();
let mut count: isize = 0;
let range: objc2_foundation::NSRange = unsafe {
objc2::msg_send![&*checker, checkSpellingOfString: &*NSString::from_str(word), startingAt: 0isize,
language: &*NSString::from_str("en"), wrap: false, inSpellDocumentWithTag: 0isize, wordCount: &mut count]
};
range.length > 0
}
pub fn context_menu_for_word(view: &objc2_app_kit::NSTextView, word: &str) -> Vec<String> {
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType};
use objc2_foundation::{NSPoint, NSRange, NSRect};
let Some(window) = view.window() else { return Vec::new() };
let text = view.string().to_string();
let Some(byte_index) = text.find(word) else { return Vec::new() };
let location = text[..byte_index].encode_utf16().count();
let screen: NSRect = unsafe {
objc2::msg_send![view, firstRectForCharacterRange: NSRange::new(location + word.len() / 2, 1), actualRange: std::ptr::null_mut::<NSRange>()]
};
let w = window.convertRectFromScreen(screen);
let point = NSPoint::new(w.origin.x + w.size.width / 2.0, w.origin.y + w.size.height / 2.0);
let Some(event) = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
NSEventType::RightMouseDown, point, NSEventModifierFlags::empty(), 0.0, window.windowNumber(), None, 0, 1, 1.0,
) else {
return Vec::new();
};
let Some(menu) = view.menuForEvent(&event) else { return Vec::new() };
(0..menu.numberOfItems()).filter_map(|i| menu.itemAtIndex(i)).map(|item| item.title().to_string()).collect()
}
pub fn capture_window(window: &crate::WindowRef) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
let window = window.ns();
let path = std::env::temp_dir().join(format!("ferrokit-capture-{}-{}.png", std::process::id(), window.windowNumber()));
let ok = std::process::Command::new("screencapture")
.args(["-x", "-o", "-l", &window.windowNumber().to_string()])
.arg(&path)
.status()
.is_ok_and(|s| s.success());
let bytes = if ok { std::fs::read(&path).ok() } else { None };
let rep = bytes.and_then(|b| objc2_app_kit::NSBitmapImageRep::imageRepWithData(&objc2_foundation::NSData::with_bytes(&b)));
let _ = std::fs::remove_file(&path);
rep.filter(|r| (r.pixelsWide() as f64 - window.frame().size.width * window.backingScaleFactor()).abs() < 2.0)
.filter(|r| has_content(r))
}
fn has_content(rep: &objc2_app_kit::NSBitmapImageRep) -> bool {
let srgb = objc2_app_kit::NSColorSpace::sRGBColorSpace();
let (w, h) = (rep.pixelsWide(), rep.pixelsHigh());
let mut seen: Vec<(f64, f64, f64)> = Vec::new();
for y in (0..h).step_by((h / 40).max(1) as usize) {
for x in (0..w).step_by((w / 40).max(1) as usize) {
if let Some(c) = rep.colorAtX_y(x, y).and_then(|c| c.colorUsingColorSpace(&srgb)) {
let p = (c.redComponent(), c.greenComponent(), c.blueComponent());
if !seen.iter().any(|q| (q.0 - p.0).abs() + (q.1 - p.1).abs() + (q.2 - p.2).abs() < 0.05) {
seen.push(p);
}
}
}
}
seen.len() >= 3
}
pub fn captured_pixels(rep: &objc2_app_kit::NSBitmapImageRep, view: &objc2_app_kit::NSView, step: usize) -> Vec<Vec<(f64, f64, f64)>> {
let Some(window) = view.window() else { return Vec::new() };
let scale = window.backingScaleFactor();
let r = view.convertRect_toView(view.bounds(), None);
let height = window.frame().size.height;
let (x0, x1) = ((r.origin.x * scale) as isize, ((r.origin.x + r.size.width) * scale) as isize);
let (y0, y1) = (((height - r.origin.y - r.size.height) * scale) as isize, ((height - r.origin.y) * scale) as isize);
let srgb = objc2_app_kit::NSColorSpace::sRGBColorSpace();
let mut out = Vec::new();
for y in (y0.max(0)..y1.min(rep.pixelsHigh())).step_by(step.max(1)) {
let row = (x0.max(0)..x1.min(rep.pixelsWide()))
.step_by(step.max(1))
.map(|x| rep.colorAtX_y(x, y).and_then(|c| c.colorUsingColorSpace(&srgb)).map_or((0.0, 0.0, 0.0), |c| (c.redComponent(), c.greenComponent(), c.blueComponent())))
.collect();
out.push(row);
}
out
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct AxElement {
pub depth: usize,
pub role: String,
pub subrole: String,
pub name: String,
pub label: String,
pub value: String,
}
pub fn ax_elements(window: &crate::WindowRef) -> Vec<AxElement> {
let window = window.ns();
use objc2::runtime::AnyObject;
fn responds(obj: &AnyObject, sel: objc2::runtime::Sel) -> bool {
unsafe { objc2::msg_send![obj, respondsToSelector: sel] }
}
fn attribute(obj: &AnyObject, sel: objc2::runtime::Sel, name: &str) -> Option<Retained<AnyObject>> {
if responds(obj, sel) {
unsafe { objc2::msg_send![obj, performSelector: sel] }
} else if responds(obj, objc2::sel!(accessibilityAttributeValue:)) {
unsafe { objc2::msg_send![obj, accessibilityAttributeValue: &*NSString::from_str(name)] }
} else {
None
}
}
fn string(obj: &AnyObject, sel: objc2::runtime::Sel, name: &str) -> String {
attribute(obj, sel, name).and_then(|v| v.downcast::<NSString>().ok()).map(|s| s.to_string()).unwrap_or_default()
}
fn value(obj: &AnyObject) -> String {
let Some(v) = attribute(obj, objc2::sel!(accessibilityValue), "AXValue") else { return String::new() };
match v.downcast::<NSString>() {
Ok(s) => s.to_string(),
Err(v) => v.downcast::<objc2_foundation::NSNumber>().map(|n| n.stringValue().to_string()).unwrap_or_default(),
}
}
fn walk(obj: &AnyObject, depth: usize, parent: &str, parent_name: &str, out: &mut Vec<AxElement>) {
let label = string(obj, objc2::sel!(accessibilityLabel), "AXDescription");
let title = string(obj, objc2::sel!(accessibilityTitle), "AXTitle");
let linked = if responds(obj, objc2::sel!(accessibilityTitleUIElement)) {
let e: Option<Retained<AnyObject>> = unsafe { objc2::msg_send![obj, accessibilityTitleUIElement] };
e.map(|e| string(&e, objc2::sel!(accessibilityValue), "AXValue")).unwrap_or_default()
} else {
String::new()
};
let placeholder = string(obj, objc2::sel!(accessibilityPlaceholderValue), "AXPlaceholderValue");
let role = string(obj, objc2::sel!(accessibilityRole), "AXRole");
let read_by_value = role == "AXStaticText" || (role == "AXTextField" && ["AXList", "AXRow", "AXCell"].contains(&parent));
let text = if read_by_value { string(obj, objc2::sel!(accessibilityValue), "AXValue") } else { String::new() };
let text = if read_by_value && text.trim().is_empty() && parent == "AXCell" { parent_name.to_string() } else { text };
let name = [&label, &title, &linked, &placeholder, &text].into_iter().find(|s| !s.trim().is_empty()).cloned().unwrap_or_default();
out.push(AxElement {
depth,
role,
subrole: string(obj, objc2::sel!(accessibilitySubrole), "AXSubrole"),
name,
label,
value: value(obj),
});
if depth > 14 {
return;
}
let kids = match out.last().map(|e| e.role.as_str()) {
Some("AXTable" | "AXOutline") => attribute(obj, objc2::sel!(accessibilityVisibleRows), "AXVisibleRows"),
Some("AXList") => attribute(obj, objc2::sel!(accessibilityVisibleChildren), "AXVisibleChildren"),
_ => attribute(obj, objc2::sel!(accessibilityChildren), "AXChildren"),
}
.and_then(|k| k.downcast::<objc2_foundation::NSArray>().ok());
let (role, name) = out.last().map(|e| (e.role.clone(), e.name.clone())).unwrap_or_default();
for k in kids.iter().flat_map(|k| k.iter()) {
walk(&k, depth + 1, &role, &name, out);
}
}
let mut out = Vec::new();
if let Some(content) = window.contentView() {
wake_swiftui(&content);
walk(&content, 0, "", "", &mut out);
}
out
}
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn AXUIElementCreateApplication(pid: i32) -> *const std::ffi::c_void;
fn AXUIElementCopyAttributeValue(element: *const std::ffi::c_void, attribute: *const std::ffi::c_void, value: *mut *const std::ffi::c_void) -> i32;
fn CFRelease(object: *const std::ffi::c_void);
}
fn wake_swiftui(view: &objc2_app_kit::NSView) {
fn has_hosting(v: &objc2_app_kit::NSView) -> bool {
v.class().name().to_string_lossy().contains("HostingView") || v.subviews().iter().any(|s| has_hosting(&s))
}
if !has_hosting(view) {
return;
}
let windows = NSString::from_str("AXWindows");
unsafe {
let app = AXUIElementCreateApplication(std::process::id() as i32);
if app.is_null() {
return;
}
let mut value = std::ptr::null();
if AXUIElementCopyAttributeValue(app, (&*windows as *const NSString).cast(), &mut value) == 0 && !value.is_null() {
CFRelease(value);
}
CFRelease(app);
}
}
pub fn ax_audit(window: &crate::WindowRef) -> Vec<String> {
const NEEDS_NAME: &[&str] =
&["AXTextField", "AXTextArea", "AXSlider", "AXPopUpButton", "AXCheckBox", "AXRadioButton", "AXButton", "AXIncrementor", "AXComboBox", "AXMenuButton", "AXDateTimeArea", "AXColorWell"];
let symbol_like = |s: &str| s.contains('.') && !s.contains(' ') && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.');
let elements = ax_elements(window);
let in_named_date = |i: usize| {
let mut depth = elements[i].depth;
elements[..i].iter().rev().any(|a| {
if a.depth < depth {
depth = a.depth;
return a.role == "AXDateTimeArea" && !a.name.trim().is_empty();
}
false
})
};
elements
.iter()
.enumerate()
.filter_map(|(i, e)| {
let part = ["AXIncrementArrow", "AXDecrementArrow", "AXIncrementPage", "AXDecrementPage"].contains(&e.subrole.as_str()) || in_named_date(i);
let unnamed = NEEDS_NAME.contains(&e.role.as_str()) && !part && e.name.trim().is_empty();
let is_symbol = |n: &str| e.role == "AXImage" || objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(n), None).is_some();
let symbol = (e.role == "AXImage" && e.name.is_empty()) || (symbol_like(&e.name) && is_symbol(&e.name));
(unnamed || symbol).then(|| {
let what = if e.subrole.is_empty() { e.role.clone() } else { format!("{} {}", e.role, e.subrole) };
if symbol { format!("#{i} {what} named {:?}", e.name) } else { format!("#{i} {what} without a name") }
})
})
.collect()
}
#[repr(C)]
#[derive(Default)]
struct MallocStatistics {
blocks_in_use: u32,
size_in_use: usize,
max_size_in_use: usize,
size_allocated: usize,
}
unsafe extern "C" {
fn malloc_zone_statistics(zone: *mut std::ffi::c_void, stats: *mut MallocStatistics);
}
pub fn heap_in_use_mb() -> f64 {
let mut stats = MallocStatistics::default();
unsafe { malloc_zone_statistics(std::ptr::null_mut(), &mut stats) };
stats.size_in_use as f64 / (1024.0 * 1024.0)
}
unsafe extern "C" {
fn sysctlbyname(name: *const std::ffi::c_char, old: *mut std::ffi::c_void, len: *mut usize, new: *mut std::ffi::c_void, new_len: usize) -> i32;
}
pub fn virtual_machine() -> bool {
let mut on: i32 = 0;
let mut len = std::mem::size_of::<i32>();
let ok = unsafe { sysctlbyname(c"kern.hv_vmm_present".as_ptr(), (&raw mut on).cast(), &mut len, std::ptr::null_mut(), 0) };
ok == 0 && on == 1
}
pub fn canvas_drawing(view: &objc2_app_kit::NSView) -> Option<Vec<String>> {
crate::canvas::describe(view)
}
pub fn canvas_png(view: &objc2_app_kit::NSView) -> Option<Vec<u8>> {
crate::canvas::png(view)
}
pub fn canvas_click(view: &objc2_app_kit::NSView, x: f64, y: f64) -> bool {
crate::canvas::click_at(view, x, y)
}
pub fn canvas_scroll(view: &objc2_app_kit::NSView, dx: f64, dy: f64, x: f64, y: f64) -> bool {
crate::canvas::scroll_at(view, dx, dy, x, y)
}
pub fn canvas_magnify(view: &objc2_app_kit::NSView, amount: f64, x: f64, y: f64) -> bool {
crate::canvas::magnify_at(view, amount, x, y)
}
pub fn canvas_drag(view: &objc2_app_kit::NSView) -> Option<crate::DragItem> {
crate::canvas::drag_item(view)
}
pub fn canvas_move(view: &objc2_app_kit::NSView, from: (f64, f64), to: (f64, f64)) -> bool {
crate::canvas::move_on(view, from, to)
}
pub fn fulfil(item: &crate::DragItem, dir: &std::path::Path) -> std::io::Result<std::path::PathBuf> {
crate::transfer::fulfil(item, dir)
}
pub fn drop_on_view(view: &objc2_app_kit::NSView, pasteboard: &objc2_app_kit::NSPasteboard) -> bool {
ferrokit_core::testing::drop_on_view(view, pasteboard)
}
pub fn set_reduce_motion(on: Option<bool>) {
crate::motion::set_reduce_motion(on);
}
pub fn hover(view: &objc2_app_kit::NSView, inside: bool) -> bool {
crate::interact::hover(view, inside)
}
pub fn press(view: &objc2_app_kit::NSView, down: bool) -> bool {
crate::interact::press(view, down)
}
pub fn hold_notifications() {
crate::services::HOLD.with(|h| h.set(true));
}
pub fn sent_notifications() -> Vec<crate::SentNotification> {
crate::services::SENT.with_borrow(|s| s.clone())
}
pub fn click_notification(id: &str) -> bool {
crate::services::click(id)
}
pub fn shared_items(button: &objc2_app_kit::NSButton) -> Option<Vec<crate::ShareItem>> {
crate::services::shared_by(button)
}
pub fn menu_bar_extras() -> Vec<(Retained<objc2_app_kit::NSStatusItem>, Option<Retained<objc2_app_kit::NSPopover>>)> {
crate::status::EXTRAS.with_borrow(|e| e.iter().map(|i| (i.item.clone(), i.popover.clone())).collect())
}
pub fn live_signals() -> usize {
crate::signal::live_signals()
}
pub fn live_nodes() -> usize {
crate::view::live_nodes()
}
pub mod probes {
#[allow(unused_imports)]
use super::*;
pub fn symbol_effects() -> (isize, usize) {
crate::controls::SYMBOL_EFFECTS.with(std::cell::Cell::get)
}
pub fn set_preview_mode(on: bool) {
crate::set_preview_mode(on);
}
pub fn key_equiv(w: &crate::WindowRef, chars: &str, shift: bool) -> bool {
let w = w.ns();
use objc2_app_kit::{NSEvent, NSEventModifierFlags, NSEventType};
let mut flags = NSEventModifierFlags::Command;
let typed = if shift { chars.to_uppercase() } else { chars.to_string() };
if shift {
flags |= NSEventModifierFlags::Shift;
}
let event = {
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEventType::KeyDown,
objc2_foundation::NSPoint::new(0.0, 0.0),
flags,
0.0,
w.windowNumber(),
None,
&NSString::from_str(&typed),
&NSString::from_str(&typed),
false,
0,
)
}
.unwrap();
NSApplication::sharedApplication(mtm()).mainMenu().unwrap().performKeyEquivalent(&event)
}
pub fn app_menu_titles() -> Vec<String> {
let bar = NSApplication::sharedApplication(mtm()).mainMenu();
let menu = bar.and_then(|b| b.itemAtIndex(0)).and_then(|i| i.submenu());
menu.map(|m| m.itemArray().iter().map(|i| if i.isSeparatorItem() { "-".into() } else { i.title().to_string() }).collect()).unwrap_or_default()
}
pub fn layout_stats() -> (u64, u64, u64) {
crate::layout::layout_stats()
}
pub fn effect_runs() -> u64 {
crate::signal::effect_runs()
}
pub fn layout_times_us() -> Vec<f64> {
crate::layout_times_us()
}
pub fn layout_passes() -> u64 {
crate::layout_passes()
}
pub fn motion_running() -> usize {
crate::motion::running()
}
pub fn leaving_views() -> usize {
crate::motion::leaving()
}
pub fn is_pressed(view: &objc2_app_kit::NSView) -> Option<bool> {
crate::interact::is_pressed(view)
}
pub fn step_motion(seconds: f64) {
crate::motion::step(seconds);
}
pub fn remember_open_documents() {
crate::documents::remember_open();
}
pub fn collection_cells_made() -> u64 {
crate::collection::collection_cells_made()
}
}