1use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
5use objc2_foundation::NSPoint;
6
7use std::sync::atomic::{AtomicUsize, Ordering};
8
9use crate::ViewId;
10
11pub(crate) static LIVE_MODELS: AtomicUsize = AtomicUsize::new(0);
13pub(crate) static LIVE_OBJC: AtomicUsize = AtomicUsize::new(0);
16
17pub fn live_objects() -> (usize, usize) {
19 (LIVE_MODELS.load(Ordering::Relaxed), LIVE_OBJC.load(Ordering::Relaxed))
20}
21use crate::host::{mtm, with_host};
22
23pub fn post_key(chars: &str, key_code: u16, command: bool, shift: bool) {
25 crate::keys::post_key_down(chars, key_code, command, shift);
26}
27
28pub fn post_tab(shift: bool) {
30 post_key("\t", 48, false, shift);
31}
32
33pub fn post_click(x: f64, y: f64) {
35 let Some((window_number, location)) = with_host(|h| {
36 let window = h.content.window()?;
37 let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
38 Some((window.windowNumber(), h.content.convertPoint_toView(p, None)))
39 })
40 .flatten() else {
41 return;
42 };
43 for kind in [NSEventType::LeftMouseDown, NSEventType::LeftMouseUp] {
44 let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
45 kind, location, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 1, 1.0,
46 );
47 if let Some(event) = event {
48 NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
49 }
50 }
51}
52
53pub fn post_mouse_move(x: f64, y: f64) {
55 let Some((window_number, location)) = with_host(|h| {
56 let window = h.content.window()?;
57 let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
58 Some((window.windowNumber(), h.content.convertPoint_toView(p, None)))
59 })
60 .flatten() else {
61 return;
62 };
63 let event = NSEvent::mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure(
64 NSEventType::MouseMoved, location, NSEventModifierFlags::empty(), 0.0, window_number, None, 0, 0, 0.0,
65 );
66 if let Some(event) = event {
67 NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
68 }
69}
70
71pub fn click_reaches(id: ViewId) -> Option<bool> {
74 with_host(|h| {
75 let m = h.views.get(&id)?;
76 let v = m.visible?;
77 let (x, y) = (v.x + v.width / 2.0, v.y + v.height / 2.0);
78 let p = if h.content.isFlipped() { NSPoint::new(x, y) } else { NSPoint::new(x, h.content.bounds().size.height - y) };
79 let p = unsafe { h.content.superview() }.map_or(p, |s| h.content.convertPoint_toView(p, Some(&s)));
81 let hit = h.content.hitTest(p)?;
82 Some(hit.isDescendantOf(&m.view))
83 })
84 .flatten()
85}
86
87pub fn first_responder() -> String {
89 with_host(|h| {
90 let Some(r) = h.content.window().and_then(|w| w.firstResponder()) else { return "none".into() };
91 if std::ptr::eq(&*r as *const _ as *const objc2_app_kit::NSView, &*h.content) {
92 return "host".into();
93 }
94 r.class().name().to_string_lossy().into_owned()
95 })
96 .unwrap_or_else(|| "detached".into())
97}
98
99pub fn is_visible(id: ViewId) -> bool {
101 with_host(|h| h.views.get(&id).is_some_and(|m| m.shown()))
102 .unwrap_or(false)
103}
104
105pub fn set_app_appearance(dark: Option<bool>) {
109 let app = NSApplication::sharedApplication(mtm());
110 let appearance = dark.and_then(|dark| {
111 let name = unsafe { if dark { objc2_app_kit::NSAppearanceNameDarkAqua } else { objc2_app_kit::NSAppearanceNameAqua } };
113 objc2_app_kit::NSAppearance::appearanceNamed(name)
114 });
115 app.setAppearance(appearance.as_deref());
116}
117
118pub fn view_is_dark(id: ViewId) -> Option<bool> {
120 with_host(|h| {
121 let view = &h.views.get(&id)?.view;
122 Some(objc2_app_kit::NSAppearanceCustomization::effectiveAppearance(&**view).name().to_string().contains("Dark"))
123 })
124 .flatten()
125}
126
127pub fn off_grid() -> Vec<ViewId> {
129 with_host(|h| {
130 let scale = h.content.window().map_or(1.0, |w| w.backingScaleFactor());
131 let on = |v: f64| ((v * scale) - (v * scale).round()).abs() < 1e-6;
132 h.views
133 .iter()
134 .filter(|(_, m)| m.shown())
135 .filter(|(_, m)| {
136 let f = m.clip_frame();
137 !(on(f.origin.x) && on(f.origin.y) && on(f.size.width) && on(f.size.height))
138 })
139 .map(|(id, _)| *id)
140 .collect()
141 })
142 .unwrap_or_default()
143}
144
145pub fn visible_rect(id: ViewId) -> Option<crate::Rect> {
147 with_host(|h| h.views.get(&id).and_then(|m| m.visible)).flatten()
148}
149
150pub fn subview_count() -> usize {
152 with_host(|h| h.content.subviews().len()).unwrap_or(0)
153}
154
155pub fn window_state() -> (bool, bool) {
157 let key = with_host(|h| h.content.window().is_some_and(|w| w.isKeyWindow())).unwrap_or(false);
158 (key, NSApplication::sharedApplication(mtm()).isActive())
159}
160
161pub fn make_first_responder_raw(id: ViewId) -> bool {
164 with_host(|h| {
165 let (Some(m), Some(window)) = (h.views.get(&id), h.content.window()) else { return false };
166 window.makeFirstResponder(Some(&crate::host::focus_target(&m.view)))
167 })
168 .unwrap_or(false)
169}
170
171pub fn post_key_with(chars: &str, key_code: u16, flags: NSEventModifierFlags) {
173 let Some(window_number) = with_host(|h| h.content.window().map(|w| w.windowNumber())).flatten() else { return };
174 let chars = objc2_foundation::NSString::from_str(chars);
175 let event = NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
176 NSEventType::KeyDown, NSPoint::ZERO, flags, 0.0, window_number, None, &chars, &chars, false, key_code,
177 );
178 if let Some(event) = event {
179 NSApplication::sharedApplication(mtm()).postEvent_atStart(&event, false);
180 }
181}
182
183use objc2::rc::Retained;
186use objc2::runtime::{AnyObject, NSObject, NSObjectProtocol, ProtocolObject};
187use objc2::{DefinedClass, MainThreadOnly, Message, define_class, msg_send};
188use objc2_app_kit::{
189 NSDragOperation, NSDraggingInfo, NSPasteboard, NSPasteboardItem, NSPasteboardTypeFileURL, NSPasteboardTypeString,
190 NSPasteboardWriting, NSTableView, NSTableViewDropOperation, NSView,
191};
192use objc2_foundation::{NSArray, NSInteger, NSString, NSURL};
193
194struct DragIvars {
195 pasteboard: Retained<NSPasteboard>,
196 source: Option<Retained<AnyObject>>,
197}
198
199define_class!(
200 #[unsafe(super(NSObject))]
203 #[thread_kind = MainThreadOnly]
204 #[name = "FerrokitCoreTestDrag"]
205 #[ivars = DragIvars]
206 struct TestDrag;
207
208 unsafe impl NSObjectProtocol for TestDrag {}
209
210 unsafe impl NSDraggingInfo for TestDrag {
211 #[unsafe(method_id(draggingPasteboard))]
212 fn dragging_pasteboard(&self) -> Retained<NSPasteboard> {
213 self.ivars().pasteboard.clone()
214 }
215
216 #[unsafe(method_id(draggingSource))]
217 fn dragging_source(&self) -> Option<Retained<AnyObject>> {
218 self.ivars().source.clone()
219 }
220
221 #[unsafe(method_id(draggingDestinationWindow))]
224 fn destination_window(&self) -> Option<Retained<objc2_app_kit::NSWindow>> {
225 None
226 }
227
228 #[unsafe(method(draggingSourceOperationMask))]
229 fn source_operations(&self) -> NSDragOperation {
230 NSDragOperation::Copy | NSDragOperation::Move
231 }
232
233 #[unsafe(method(draggingLocation))]
234 fn location(&self) -> objc2_foundation::NSPoint {
235 objc2_foundation::NSPoint::ZERO
236 }
237
238 #[unsafe(method(draggedImageLocation))]
239 fn image_location(&self) -> objc2_foundation::NSPoint {
240 objc2_foundation::NSPoint::ZERO
241 }
242
243 #[unsafe(method_id(draggedImage))]
244 fn image(&self) -> Option<Retained<objc2_app_kit::NSImage>> {
245 None
246 }
247
248 #[unsafe(method(draggingSequenceNumber))]
249 fn sequence(&self) -> NSInteger {
250 1
251 }
252
253 #[unsafe(method(slideDraggedImageTo:))]
254 fn slide(&self, _to: objc2_foundation::NSPoint) {}
255
256 #[unsafe(method_id(namesOfPromisedFilesDroppedAtDestination:))]
257 fn promised(&self, _at: &objc2_foundation::NSURL) -> Option<Retained<objc2_foundation::NSArray<objc2_foundation::NSString>>> {
258 None
259 }
260
261 #[unsafe(method(draggingFormation))]
262 fn formation(&self) -> objc2_app_kit::NSDraggingFormation {
263 objc2_app_kit::NSDraggingFormation::Default
264 }
265
266 #[unsafe(method(setDraggingFormation:))]
267 fn set_formation(&self, _f: objc2_app_kit::NSDraggingFormation) {}
268
269 #[unsafe(method(animatesToDestination))]
270 fn animates(&self) -> bool {
271 false
272 }
273
274 #[unsafe(method(setAnimatesToDestination:))]
275 fn set_animates(&self, _a: bool) {}
276
277 #[unsafe(method(numberOfValidItemsForDrop))]
278 fn valid_items(&self) -> NSInteger {
279 1
280 }
281
282 #[unsafe(method(setNumberOfValidItemsForDrop:))]
283 fn set_valid_items(&self, _n: NSInteger) {}
284
285 #[unsafe(method(enumerateDraggingItemsWithOptions:forView:classes:searchOptions:usingBlock:))]
286 fn enumerate(
287 &self,
288 _options: objc2_app_kit::NSDraggingItemEnumerationOptions,
289 _view: Option<&NSView>,
290 _classes: &objc2_foundation::NSArray<objc2::runtime::AnyClass>,
291 _search: &objc2_foundation::NSDictionary<objc2_app_kit::NSPasteboardReadingOptionKey, AnyObject>,
292 _block: &block2::DynBlock<dyn Fn(std::ptr::NonNull<objc2_app_kit::NSDraggingItem>, NSInteger, std::ptr::NonNull<objc2::runtime::Bool>)>,
293 ) {
294 }
295
296 #[unsafe(method(springLoadingHighlight))]
297 fn spring_highlight(&self) -> objc2_app_kit::NSSpringLoadingHighlight {
298 objc2_app_kit::NSSpringLoadingHighlight::None
299 }
300
301 #[unsafe(method(resetSpringLoading))]
302 fn reset_spring(&self) {}
303 }
304);
305
306pub fn private_pasteboard() -> Retained<NSPasteboard> {
309 NSPasteboard::pasteboardWithUniqueName()
310}
311
312pub fn release_pasteboard(pasteboard: &NSPasteboard) {
314 let () = unsafe { msg_send![pasteboard, releaseGlobally] };
316}
317
318pub fn drop_on_table(table: &NSTableView, pasteboard: &NSPasteboard, row: usize, from_table: bool) -> bool {
323 let source: Option<Retained<AnyObject>> = from_table.then(|| {
324 let any: &AnyObject = table.as_ref();
325 any.retain()
326 });
327 let drag = TestDrag::alloc(mtm()).set_ivars(DragIvars { pasteboard: pasteboard.retain(), source });
328 let drag: Retained<TestDrag> = unsafe { msg_send![super(drag), init] };
330 let info: &ProtocolObject<dyn NSDraggingInfo> = ProtocolObject::from_ref(&*drag);
331 let Some(ds) = (unsafe { table.dataSource() }) else { return false };
332 let row = row as NSInteger;
333 unsafe {
336 let op: NSDragOperation = msg_send![&*ds, tableView: table, validateDrop: info, proposedRow: row, proposedDropOperation: NSTableViewDropOperation::Above];
337 if op == NSDragOperation::None {
338 return false;
339 }
340 msg_send![&*ds, tableView: table, acceptDrop: info, row: row, dropOperation: NSTableViewDropOperation::Above]
341 }
342}
343
344pub fn drop_on_view(view: &NSView, pasteboard: &NSPasteboard) -> bool {
348 let drag = TestDrag::alloc(mtm()).set_ivars(DragIvars { pasteboard: pasteboard.retain(), source: None });
349 let drag: Retained<TestDrag> = unsafe { msg_send![super(drag), init] };
351 let info: &ProtocolObject<dyn NSDraggingInfo> = ProtocolObject::from_ref(&*drag);
352 unsafe {
355 let op: NSDragOperation = msg_send![view, draggingEntered: info];
356 if op == NSDragOperation::None {
357 return false;
358 }
359 msg_send![view, performDragOperation: info]
360 }
361}
362
363pub fn drag_rows(table: &NSTableView, rows: &[usize]) -> Option<Retained<NSPasteboard>> {
367 let ds = unsafe { table.dataSource() }?;
368 let mut writers: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = Vec::new();
369 for &r in rows {
370 let w: Option<Retained<ProtocolObject<dyn NSPasteboardWriting>>> =
372 unsafe { msg_send![&*ds, tableView: table, pasteboardWriterForRow: r as NSInteger] };
373 writers.push(w?);
374 }
375 let pasteboard = private_pasteboard();
376 pasteboard.clearContents();
377 pasteboard.writeObjects(&NSArray::from_retained_slice(&writers));
378 Some(pasteboard)
379}
380
381pub fn files_pasteboard(paths: &[&std::path::Path]) -> Retained<NSPasteboard> {
383 let pasteboard = private_pasteboard();
384 pasteboard.clearContents();
385 let items: Vec<Retained<ProtocolObject<dyn NSPasteboardWriting>>> = paths
386 .iter()
387 .map(|p| {
388 let item = NSPasteboardItem::new();
389 let url = NSURL::fileURLWithPath(&NSString::from_str(&p.to_string_lossy()));
390 if let Some(s) = url.absoluteString() {
391 item.setString_forType(&s, unsafe { NSPasteboardTypeFileURL });
393 }
394 ProtocolObject::from_retained(item)
395 })
396 .collect();
397 pasteboard.writeObjects(&NSArray::from_retained_slice(&items));
398 pasteboard
399}
400
401pub fn pasteboard_text(pasteboard: &NSPasteboard) -> Option<String> {
403 pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string())
405}
406
407pub fn set_pasteboard_text(pasteboard: &NSPasteboard, text: &str) {
409 pasteboard.clearContents();
410 pasteboard.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
412}