use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
use objc2_foundation::NSPoint;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::ViewId;
pub(crate) static LIVE_MODELS: AtomicUsize = AtomicUsize::new(0);
pub(crate) static LIVE_OBJC: AtomicUsize = AtomicUsize::new(0);
pub fn live_objects() -> (usize, usize) {
(LIVE_MODELS.load(Ordering::Relaxed), LIVE_OBJC.load(Ordering::Relaxed))
}
use crate::host::{mtm, with_host};
pub fn post_key(chars: &str, key_code: u16, command: bool, shift: bool) {
crate::keys::post_key_down(chars, key_code, command, shift);
}
pub fn post_tab(shift: bool) {
post_key("\t", 48, false, shift);
}
pub fn post_click(x: f64, y: f64) {
let Some((window_number, location)) = with_host(|h| {
let window = h.content.window()?;
let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
Some((window.windowNumber(), h.content.convertPoint_toView(p, None)))
})
.flatten() else {
return;
};
for kind in [NSEventType::LeftMouseDown, NSEventType::LeftMouseUp] {
let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
kind, location, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 1, 1.0,
);
if let Some(event) = event {
NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
}
}
}
pub fn post_mouse_move(x: f64, y: f64) {
let Some((window_number, location)) = with_host(|h| {
let window = h.content.window()?;
let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
Some((window.windowNumber(), h.content.convertPoint_toView(p, None)))
})
.flatten() else {
return;
};
let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
NSEventType::MouseMoved, location, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 0, 0.0,
);
if let Some(event) = event {
NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
}
}
pub fn click_reaches(id: ViewId) -> Option<bool> {
with_host(|h| {
let m = h.views.get(&id)?;
let v = m.visible?;
let (x, y) = (v.x + v.width / 2.0, v.y + v.height / 2.0);
let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
let p = unsafe { h.content.superview() }.map_or(p, |s| h.content.convertPoint_toView(p, Some(&s)));
let hit = h.content.hitTest(p)?;
Some(hit.isDescendantOf(&m.view))
})
.flatten()
}
pub fn first_responder() -> String {
with_host(|h| {
let Some(r) = h.content.window().and_then(|w| w.firstResponder()) else { return "none".into() };
if std::ptr::eq(&*r as *const _ as *const objc2_app_kit::NSView, &*h.content) {
return "host".into();
}
r.class().name().to_string_lossy().into_owned()
})
.unwrap_or_else(|| "detached".into())
}
pub fn is_visible(id: ViewId) -> bool {
with_host(|h| h.views.get(&id).is_some_and(|m| m.shown()))
.unwrap_or(false)
}
pub fn set_app_appearance(dark: Option<bool>) {
let app = NSApplication::sharedApplication(mtm());
let appearance = dark.and_then(|dark| {
let name = unsafe { if dark { objc2_app_kit::NSAppearanceNameDarkAqua } else { objc2_app_kit::NSAppearanceNameAqua } };
objc2_app_kit::NSAppearance::appearanceNamed(name)
});
app.setAppearance(appearance.as_deref());
}
pub fn view_is_dark(id: ViewId) -> Option<bool> {
with_host(|h| {
let view = &h.views.get(&id)?.view;
Some(objc2_app_kit::NSAppearanceCustomization::effectiveAppearance(&**view).name().to_string().contains("Dark"))
})
.flatten()
}
pub fn off_grid() -> Vec<ViewId> {
with_host(|h| {
let scale = h.content.window().map_or(1.0, |w| w.backingScaleFactor());
let on = |v: f64| ((v * scale) - (v * scale).round()).abs() < 1e-6;
h.views
.iter()
.filter(|(_, m)| m.shown())
.filter(|(_, m)| {
let f = m.clip_frame();
!(on(f.origin.x) && on(f.origin.y) && on(f.size.width) && on(f.size.height))
})
.map(|(id, _)| *id)
.collect()
})
.unwrap_or_default()
}
pub fn visible_rect(id: ViewId) -> Option<crate::Rect> {
with_host(|h| h.views.get(&id).and_then(|m| m.visible)).flatten()
}
pub fn subview_count() -> usize {
with_host(|h| h.content.subviews().len()).unwrap_or(0)
}
pub fn window_state() -> (bool, bool) {
let key = with_host(|h| h.content.window().is_some_and(|w| w.isKeyWindow())).unwrap_or(false);
(key, NSApplication::sharedApplication(mtm()).isActive())
}
pub fn make_first_responder_raw(id: ViewId) -> bool {
with_host(|h| {
let (Some(m), Some(window)) = (h.views.get(&id), h.content.window()) else { return false };
window.makeFirstResponder(Some(&crate::host::focus_target(&m.view)))
})
.unwrap_or(false)
}
pub fn post_key_with(chars: &str, key_code: u16, flags: NSEventModifierFlags) {
let Some(window_number) = with_host(|h| h.content.window().map(|w| w.windowNumber())).flatten() else { return };
let chars = objc2_foundation::NSString::from_str(chars);
let event = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEventType::KeyDown, NSPoint::ZERO, flags, 0.0, window_number, None, &chars, &chars, false, key_code,
);
if let Some(event) = event {
NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
}
}
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
use objc2::{DefinedClass, MainThreadOnly, Message, define_class, msg_send};
use objc2_app_kit::{
NSDragOperation, NSDraggingInfo, NSPasteboard, NSPasteboardItem, NSPasteboardTypeFileURL, NSPasteboardTypeString,
NSPasteboardWriting, NSTableView, NSTableViewDropOperation, NSView,
};
use objc2_foundation::{NSArray, NSInteger, NSString, NSURL};
struct DragIvars {
pasteboard: Retained<NSPasteboard>,
source: Option<Retained<AnyObject>>,
}
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "FerrokitCoreTestDrag"]
#[ivars = DragIvars]
struct TestDrag;
unsafe impl NSObjectProtocol for TestDrag {}
unsafe impl NSDraggingInfo for TestDrag {
#[unsafe(method_id(draggingPasteboard))]
fn dragging_pasteboard(&self) -> Retained<NSPasteboard> {
self.ivars().pasteboard.clone()
}
#[unsafe(method_id(draggingSource))]
fn dragging_source(&self) -> Option<Retained<AnyObject>> {
self.ivars().source.clone()
}
#[unsafe(method_id(draggingDestinationWindow))]
fn destination_window(&self) -> Option<Retained<objc2_app_kit::NSWindow>> {
None
}
#[unsafe(method(draggingSourceOperationMask))]
fn source_operations(&self) -> NSDragOperation {
NSDragOperation::Copy | NSDragOperation::Move
}
#[unsafe(method(draggingLocation))]
fn location(&self) -> objc2_foundation::NSPoint {
objc2_foundation::NSPoint::ZERO
}
#[unsafe(method(draggedImageLocation))]
fn image_location(&self) -> objc2_foundation::NSPoint {
objc2_foundation::NSPoint::ZERO
}
#[unsafe(method_id(draggedImage))]
fn image(&self) -> Option<Retained<objc2_app_kit::NSImage>> {
None
}
#[unsafe(method(draggingSequenceNumber))]
fn sequence(&self) -> NSInteger {
1
}
#[unsafe(method(slideDraggedImageTo:))]
fn slide(&self, _to: objc2_foundation::NSPoint) {}
#[unsafe(method_id(namesOfPromisedFilesDroppedAtDestination:))]
fn promised(&self, _at: &objc2_foundation::NSURL) -> Option<Retained<objc2_foundation::NSArray<objc2_foundation::NSString>>> {
None
}
#[unsafe(method(draggingFormation))]
fn formation(&self) -> objc2_app_kit::NSDraggingFormation {
objc2_app_kit::NSDraggingFormation::Default
}
#[unsafe(method(setDraggingFormation:))]
fn set_formation(&self, _f: objc2_app_kit::NSDraggingFormation) {}
#[unsafe(method(animatesToDestination))]
fn animates(&self) -> bool {
false
}
#[unsafe(method(setAnimatesToDestination:))]
fn set_animates(&self, _a: bool) {}
#[unsafe(method(numberOfValidItemsForDrop))]
fn valid_items(&self) -> NSInteger {
1
}
#[unsafe(method(setNumberOfValidItemsForDrop:))]
fn set_valid_items(&self, _n: NSInteger) {}
#[unsafe(method(enumerateDraggingItemsWithOptions:forView:classes:searchOptions:usingBlock:))]
fn enumerate(
&self,
_options: objc2_app_kit::NSDraggingItemEnumerationOptions,
_view: Option<&NSView>,
_classes: &objc2_foundation::NSArray<objc2::runtime::AnyClass>,
_search: &objc2_foundation::NSDictionary<objc2_app_kit::NSPasteboardReadingOptionKey, AnyObject>,
_block: &block2::DynBlock<dyn Fn(std::ptr::NonNull<objc2_app_kit::NSDraggingItem>, NSInteger, std::ptr::NonNull<objc2::runtime::Bool>)>,
) {
}
#[unsafe(method(springLoadingHighlight))]
fn spring_highlight(&self) -> objc2_app_kit::NSSpringLoadingHighlight {
objc2_app_kit::NSSpringLoadingHighlight::None
}
#[unsafe(method(resetSpringLoading))]
fn reset_spring(&self) {}
}
);
pub fn private_pasteboard() -> Retained<NSPasteboard> {
NSPasteboard::pasteboardWithUniqueName()
}
pub fn release_pasteboard(pasteboard: &NSPasteboard) {
let () = unsafe { msg_send![pasteboard, releaseGlobally] };
}
pub fn drop_on_table(table: &NSTableView, pasteboard: &NSPasteboard, row: usize, from_table: bool) -> bool {
let source: Option<Retained<AnyObject>> = from_table.then(|| {
let any: &AnyObject = table.as_ref();
any.retain()
});
let drag = TestDrag::alloc(mtm()).set_ivars(DragIvars { pasteboard: pasteboard.retain(), source });
let drag: Retained<TestDrag> = unsafe { msg_send![super(drag), init] };
let info: &ProtocolObject<dyn NSDraggingInfo> = ProtocolObject::from_ref(&*drag);
let Some(ds) = (unsafe { table.dataSource() }) else { return false };
let row = row as NSInteger;
unsafe {
let op: NSDragOperation = msg_send![&*ds, tableView: table, validateDrop: info, proposedRow: row, proposedDropOperation: NSTableViewDropOperation::Above];
if op == NSDragOperation::None {
return false;
}
msg_send![&*ds, tableView: table, acceptDrop: info, row: row, dropOperation: NSTableViewDropOperation::Above]
}
}
pub fn drop_on_view(view: &NSView, pasteboard: &NSPasteboard) -> bool {
let drag = TestDrag::alloc(mtm()).set_ivars(DragIvars { pasteboard: pasteboard.retain(), source: None });
let drag: Retained<TestDrag> = unsafe { msg_send![super(drag), init] };
let info: &ProtocolObject<dyn NSDraggingInfo> = ProtocolObject::from_ref(&*drag);
unsafe {
let op: NSDragOperation = msg_send![view, draggingEntered: info];
if op == NSDragOperation::None {
return false;
}
msg_send![view, performDragOperation: info]
}
}
pub fn drag_rows(table: &NSTableView, rows: &[usize]) -> Option<Retained<NSPasteboard>> {
let ds = unsafe { table.dataSource() }?;
let mut writers: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = Vec::new();
for &r in rows {
let w: Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> =
unsafe { msg_send![&*ds, tableView: table, pasteboardWriterForRow: r as NSInteger] };
writers.push(w?);
}
let pasteboard = private_pasteboard();
pasteboard.clearContents();
pasteboard.writeObjects(&NSArray::from_retained_slice(&writers));
Some(pasteboard)
}
pub fn files_pasteboard(paths: &[&std::path::Path]) -> Retained<NSPasteboard> {
let pasteboard = private_pasteboard();
pasteboard.clearContents();
let items: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = paths
.iter()
.map(|p| {
let item = NSPasteboardItem::new();
let url = NSURL::fileURLWithPath(&NSString::from_str(&p.to_string_lossy()));
if let Some(s) = url.absoluteString() {
item.setString_forType(&s, unsafe { NSPasteboardTypeFileURL });
}
ProtocolObject::from_retained(item)
})
.collect();
pasteboard.writeObjects(&NSArray::from_retained_slice(&items));
pasteboard
}
pub fn pasteboard_text(pasteboard: &NSPasteboard) -> Option<String> {
pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string())
}
pub fn set_pasteboard_text(pasteboard: &NSPasteboard, text: &str) {
pasteboard.clearContents();
pasteboard.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
}