Skip to main content

ferrokit_core/
testing.rs

1//! Helpers for unattended tests: synthetic input posted into the app's own
2//! event queue, and probes of AppKit state. Not for production use.
3
4use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
5use objc2_foundation::NSPoint;
6
7use std::sync::atomic::{AtomicUsize, Ordering};
8
9use crate::ViewId;
10
11/// Table and text models alive (Rust side).
12pub(crate) static LIVE_MODELS: AtomicUsize = AtomicUsize::new(0);
13/// Library-defined Objective-C objects alive (data sources, delegates, text
14/// views): decremented when AppKit actually deallocates them.
15pub(crate) static LIVE_OBJC: AtomicUsize = AtomicUsize::new(0);
16
17/// (models alive, library Objective-C objects alive), for leak checks.
18pub fn live_objects() -> (usize, usize) {
19    (LIVE_MODELS.load(Ordering::Relaxed), LIVE_OBJC.load(Ordering::Relaxed))
20}
21use crate::host::{mtm, with_host};
22
23/// Posts a key-down (optionally with ⌘ / ⇧).
24pub 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
28/// Posts Tab (or Shift-Tab) to the window.
29pub fn post_tab(shift: bool) {
30    post_key("\t", 48, false, shift);
31}
32
33/// Posts a left click at a point in host coordinates (top-left origin, points).
34pub 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
53/// Posts a mouse move to a point in host coordinates (hover).
54pub 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
71/// Would a click at the centre of the view's visible part reach the view?
72/// (AppKit's own hit test, so it reflects what a real click would do.)
73pub 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        // SAFETY: the content view is in a window, so its superview is valid.
80        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
87/// Class name of the window's first responder ("host" for the host's view).
88pub 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
99/// Whether the mounted view's clip container is currently shown.
100pub 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
105/// Forces this app's appearance (`None`: follow the system). The system
106/// setting is untouched; windows' `effectiveAppearance` changes exactly as on
107/// a system switch.
108pub fn set_app_appearance(dark: Option<bool>) {
109    let app = NSApplication::sharedApplication(mtm());
110    let appearance = dark.and_then(|dark| {
111        // SAFETY: framework string constants.
112        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
118/// Whether a mounted view resolves to a dark appearance.
119pub 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
127/// Shown views whose clip frame isn't on the device-pixel grid.
128pub 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
145/// The visible part of a view as last placed (host coordinates).
146pub fn visible_rect(id: ViewId) -> Option<crate::Rect> {
147    with_host(|h| h.views.get(&id).and_then(|m| m.visible)).flatten()
148}
149
150/// Number of subviews of the host's content view (mounted clip containers).
151pub fn subview_count() -> usize {
152    with_host(|h| h.content.subviews().len()).unwrap_or(0)
153}
154
155/// (window is key, app is active), for diagnosing posted clicks.
156pub 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
161/// Makes a mounted view first responder directly through AppKit, bypassing
162/// [`crate::focus`] (as when AppKit moves focus itself, e.g. on a click).
163pub 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
171/// Posts a key-down with explicit modifier flags (e.g. Control for Ctrl-Tab).
172pub 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
183// ---- drag and drop, without a mouse ----
184
185use 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    // The parts of a drag a table's data source reads: its pasteboard and
201    // its source.
202    #[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        // The rest of the protocol's required methods (objc2 checks for
222        // them in debug builds): a drag nowhere in particular.
223        #[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
306/// A fresh private pasteboard (never the general one); release it with
307/// [`release_pasteboard`].
308pub fn private_pasteboard() -> Retained<NSPasteboard> {
309    NSPasteboard::pasteboardWithUniqueName()
310}
311
312/// Releases a pasteboard made by [`private_pasteboard`].
313pub fn release_pasteboard(pasteboard: &NSPasteboard) {
314    // SAFETY: frees a uniquely named pasteboard's resources.
315    let () = unsafe { msg_send![pasteboard, releaseGlobally] };
316}
317
318/// Drops whatever is on `pasteboard` onto `table` above view row `row`, as
319/// AppKit does at the end of a drag: the data source validates the drop,
320/// then accepts it. `from_table` makes the table itself the drag's source.
321/// Returns whether the drop was accepted.
322pub 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    // SAFETY: NSObject's designated initialiser.
329    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    // SAFETY: the table's own data-source methods, with a drag stand-in that
334    // answers what they read.
335    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
344/// Drops whatever is on `pasteboard` onto `view` (a drag destination) as
345/// AppKit does: `draggingEntered:`, then `performDragOperation:` if it
346/// offered an operation. Whether the drop was taken.
347pub fn drop_on_view(view: &NSView, pasteboard: &NSPasteboard) -> bool {
348    let drag = TestDrag::alloc(mtm()).set_ivars(DragIvars { pasteboard: pasteboard.retain(), source: None });
349    // SAFETY: NSObject's designated initialiser.
350    let drag: Retained<TestDrag> = unsafe { msg_send![super(drag), init] };
351    let info: &ProtocolObject<dyn NSDraggingInfo> = ProtocolObject::from_ref(&*drag);
352    // SAFETY: the view's NSDraggingDestination methods, with a drag
353    // stand-in that answers what they read.
354    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
363/// Starts a drag of `table`'s view rows `rows` the way AppKit does (asking
364/// the data source for each row's pasteboard writer) and puts them on a
365/// private pasteboard. `None` if the table doesn't let rows be dragged.
366pub 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        // SAFETY: the data source's tableView:pasteboardWriterForRow:.
371        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
381/// A private pasteboard holding file URLs, as a Finder drag carries them.
382pub 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                // SAFETY: AppKit's pasteboard type constant.
392                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
401/// The plain text on `pasteboard`.
402pub fn pasteboard_text(pasteboard: &NSPasteboard) -> Option<String> {
403    // SAFETY: AppKit's pasteboard type constant.
404    pasteboard.stringForType(unsafe { NSPasteboardTypeString }).map(|s| s.to_string())
405}
406
407/// Puts `text` on `pasteboard`.
408pub fn set_pasteboard_text(pasteboard: &NSPasteboard, text: &str) {
409    pasteboard.clearContents();
410    // SAFETY: AppKit's pasteboard type constant.
411    pasteboard.setString_forType(&NSString::from_str(text), unsafe { NSPasteboardTypeString });
412}