mitsuami-appkit 1.3.3

AppKit (macOS) backend for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! The real AppKit services, end to end: clipboard (on a private
//! pasteboard), the menu bar, alert sheets, file panels and the trash. App tests use
//! scripted services instead, so this is where the native ones are checked.
//!
//! A plain `main` (harness = false): AppKit has to run on the main thread.

#[cfg(target_os = "macos")]
mod checks {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    use mitsuami_appkit::{AppKitBackend, AppKitHandle, BackendOptions, NativeView};
    use mitsuami_core::services::{Alert, Menu, MenuBar, MenuItem, MenuRole, OpenFile, ServiceError, Shortcut};
    use mitsuami_core::{Key, Size, Ui, View};
    use objc2::rc::Retained;
    use objc2::runtime::AnyObject;
    use objc2_app_kit::{
        NSApplication, NSButton, NSControlStateValueOff, NSControlStateValueOn, NSEventModifierFlags, NSMenu,
        NSMenuItem, NSSavePanel, NSView, NSWindow, NSWindowDidBecomeMainNotification,
        NSWindowDidResignMainNotification,
    };
    use objc2_foundation::{NSDate, NSNotificationCenter, NSRunLoop};

    pub struct Fixture {
        pub ui: Ui,
        pub handle: AppKitHandle,
    }

    pub fn fixture() -> Fixture {
        let mtm = mitsuami_appkit::init_for_tests();
        let options = BackendOptions { show_windows: false, private_clipboard: true, ..BackendOptions::default() };
        let backend = AppKitBackend::new(mtm, options);
        let handle = backend.handle();
        Fixture { ui: Ui::new(backend), handle }
    }

    /// Lets AppKit deliver completion handlers, then ticks the UI.
    fn pump(ui: &Ui) {
        for _ in 0..10 {
            let until = NSDate::dateWithTimeIntervalSinceNow(0.02);
            NSRunLoop::currentRunLoop().runUntilDate(&until);
            ui.tick();
        }
    }

    /// Pumps until `done`, for work on another thread (the trash), for up
    /// to five seconds.
    fn pump_until(ui: &Ui, done: impl Fn() -> bool) {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !done() && std::time::Instant::now() < deadline {
            pump(ui);
        }
    }

    fn find_button(view: &NSView, title: &str) -> Option<Retained<NSButton>> {
        for sub in view.subviews().iter() {
            if let Some(button) = sub.downcast_ref::<NSButton>()
                && button.title().to_string() == title
            {
                return Some(button.retain());
            }
            if let Some(found) = find_button(&sub, title) {
                return Some(found);
            }
        }
        None
    }

    fn sheet_of(window: &NSWindow) -> Retained<NSWindow> {
        window.attachedSheet().expect("a sheet is attached to the window")
    }

    use objc2::Message;

    pub fn clipboard_round_trips(f: &Fixture) {
        let written = Rc::new(RefCell::new(None));
        let read = Rc::new(RefCell::new(None));
        let (w, r) = (written.clone(), read.clone());
        let write = f.ui.set_clipboard_text("mitsuami ✓");
        let ui = f.ui.clone();
        f.ui.spawn_local(async move {
            *w.borrow_mut() = Some(write.await);
            *r.borrow_mut() = ui.clipboard_text().await;
        });
        f.ui.tick();
        assert_eq!(*written.borrow(), Some(Ok(())));
        assert_eq!(read.borrow().as_deref(), Some("mitsuami ✓"));
    }

    pub fn menus_are_installed_and_activate(f: &Fixture) {
        let chosen = Rc::new(Cell::new(0));
        let c = chosen.clone();
        f.ui.set_menu(
            MenuBar::new()
                .menu(
                    Menu::new("File")
                        .item(
                            MenuItem::new("New").on_select(move || c.set(c.get() + 1)).shortcut(Shortcut::primary('n')),
                        )
                        .item(MenuItem::new("Unavailable").enabled(false))
                        .item(MenuItem::new("Move to Trash").shortcut(Shortcut::primary(Key::Backspace)))
                        .item(MenuItem::new("Enclosing Folder").shortcut(Shortcut::primary(Key::Up))),
                )
                .menu(Menu::new("View").item(MenuItem::new("Zoom"))),
        );
        let mtm = objc2::MainThreadMarker::new().unwrap();
        let bar = NSApplication::sharedApplication(mtm).mainMenu().expect("a main menu");
        let titles: Vec<String> = bar.itemArray().iter().map(|i| i.title().to_string()).collect();
        assert_eq!(&titles[1..], ["File", "Edit", "View"], "app menu, File, Edit, then the rest");

        let file = bar.itemAtIndex(1).and_then(|i| i.submenu()).expect("File submenu");
        let new = file.itemAtIndex(0).unwrap();
        assert_eq!(new.keyEquivalent().to_string(), "n");
        assert!(new.keyEquivalentModifierMask().contains(NSEventModifierFlags::Command));
        assert!(new.isEnabled());
        assert!(!file.itemAtIndex(1).unwrap().isEnabled());
        // Keys that type nothing, as Finder names them.
        let trash = file.itemAtIndex(2).unwrap();
        assert_eq!(trash.keyEquivalent().to_string(), "\u{8}");
        assert_eq!(trash.keyEquivalentModifierMask(), NSEventModifierFlags::Command);
        assert_eq!(file.itemAtIndex(3).unwrap().keyEquivalent().to_string(), "\u{f700}");

        file.performActionForItemAtIndex(0);
        f.ui.tick();
        assert_eq!(chosen.get(), 1, "the handler ran");
    }

    fn main_menu() -> Retained<NSMenu> {
        let mtm = objc2::MainThreadMarker::new().unwrap();
        NSApplication::sharedApplication(mtm).mainMenu().expect("a main menu")
    }

    /// As people see them: without the marks the app's language isolates
    /// the app's name with (U+2068, U+2069).
    fn titles(menu: &NSMenu) -> Vec<String> {
        let visible = |title: String| title.chars().filter(|c| !('\u{2066}'..='\u{2069}').contains(c)).collect();
        menu.itemArray()
            .iter()
            .map(|i| if i.isSeparatorItem() { "-".into() } else { visible(i.title().to_string()) })
            .collect()
    }

    fn submenu(menu: &NSMenu, title: &str) -> Retained<NSMenu> {
        menu.itemWithTitle(&objc2_foundation::NSString::from_str(title)).and_then(|i| i.submenu()).expect(title)
    }

    fn item(menu: &NSMenu, title: &str) -> Retained<NSMenuItem> {
        menu.itemWithTitle(&objc2_foundation::NSString::from_str(title)).expect(title)
    }

    pub fn submenus_check_marks_and_roles(f: &Fixture) {
        let settings = Rc::new(Cell::new(0));
        let s = settings.clone();
        let sidebar = mitsuami_reactive::signal(true);
        let zoom = mitsuami_reactive::signal(1);
        f.ui.set_menu(
            MenuBar::new()
                .menu(
                    Menu::new("File")
                        .submenu(Menu::new("Open Recent").item(MenuItem::new("notes.txt")))
                        .separator()
                        .item(
                            MenuItem::new("Preferences").role(MenuRole::Settings).on_select(move || s.set(s.get() + 1)),
                        ),
                )
                .menu(
                    Menu::new("View")
                        .item(MenuItem::new("Show Sidebar").bind(sidebar))
                        .separator()
                        .item(MenuItem::new("Small").radio((zoom, 0)))
                        .item(MenuItem::new("Large").radio((zoom, 1))),
                )
                .menu(Menu::new("Help").item(MenuItem::new("About the app").role(MenuRole::About))),
        );
        let bar = main_menu();
        let name = objc2_foundation::NSProcessInfo::processInfo().processName().to_string();
        let app_menu = bar.itemAtIndex(0).and_then(|i| i.submenu()).unwrap();
        assert_eq!(
            titles(&app_menu),
            [
                format!("About {name}"),
                "-".into(),
                "Settings…".into(),
                "-".into(),
                format!("Hide {name}"),
                "-".into(),
                format!("Quit {name}")
            ],
            "roles go to the app menu, with AppKit's titles"
        );
        assert_eq!(item(&app_menu, "Settings…").keyEquivalent().to_string(), ",");
        assert_eq!(titles(&bar)[1..], ["File", "Edit", "View"], "Help went with its only item");

        let file = submenu(&bar, "File");
        assert_eq!(titles(&file), ["Open Recent"], "and File lost the separator before Settings");
        assert_eq!(titles(&submenu(&file, "Open Recent")), ["notes.txt"]);

        let view = submenu(&bar, "View");
        let state = |title: &str| {
            submenu(&main_menu(), "View").itemWithTitle(&objc2_foundation::NSString::from_str(title)).unwrap().state()
        };
        assert_eq!(state("Show Sidebar"), NSControlStateValueOn);
        assert_eq!((state("Small"), state("Large")), (NSControlStateValueOff, NSControlStateValueOn));

        view.performActionForItemAtIndex(0);
        view.performActionForItemAtIndex(2);
        f.ui.tick();
        assert!(!sidebar.get_untracked());
        assert_eq!(zoom.get_untracked(), 0);
        assert_eq!(state("Show Sidebar"), NSControlStateValueOff, "the menu follows the signal");
        assert_eq!((state("Small"), state("Large")), (NSControlStateValueOn, NSControlStateValueOff));

        app_menu.performActionForItemAtIndex(2);
        f.ui.tick();
        assert_eq!(settings.get(), 1, "Settings… runs the app's item");
        f.ui.set_menu(MenuBar::new());
    }

    /// Test windows are never main, so the notifications AppKit sends are
    /// posted by hand.
    pub fn window_menus_are_there_while_it_is_main(f: &Fixture) {
        let window = f.ui.create_window("editor", Size::new(400.0, 300.0));
        f.ui.set_menu(MenuBar::new().menu(Menu::new("File").item(MenuItem::new("New"))));
        f.ui.set_window_menu(
            window,
            MenuBar::new()
                .menu(Menu::new("File").item(MenuItem::new("Export…")))
                .menu(Menu::new("Format").item(MenuItem::new("Bold"))),
        );
        f.ui.tick();
        assert_eq!(titles(&main_menu())[1..], ["File", "Edit"], "not main: only the app's menus");

        // AppKit posts these while windows close, which the backend does
        // while it applies commands: here, while a native view is created.
        let ns_window = f.handle.ns_window(window).unwrap();
        let posted = ns_window.clone();
        let view = NativeView::appkit(move |cx| {
            let center = NSNotificationCenter::defaultCenter();
            unsafe { center.postNotificationName_object(NSWindowDidBecomeMainNotification, Some(&posted)) };
            NSView::new(cx.mtm())
        })
        .build(&f.ui);
        f.ui.append_child(window, view);
        pump(&f.ui);
        assert_eq!(titles(&main_menu())[1..], ["File", "Edit", "Format"]);
        assert_eq!(titles(&submenu(&main_menu(), "File")), ["New", "-", "Export…"], "its File joins the app's");

        let center = NSNotificationCenter::defaultCenter();
        unsafe { center.postNotificationName_object(NSWindowDidResignMainNotification, Some(&ns_window)) };
        pump(&f.ui);
        assert_eq!(titles(&main_menu())[1..], ["File", "Edit"]);
        f.ui.destroy(window);
        f.ui.set_menu(MenuBar::new());
        f.ui.tick();
    }

    pub fn alerts_are_answered_through_their_sheet(f: &Fixture) {
        let window = f.ui.create_window("alert host", Size::new(400.0, 300.0));
        f.ui.tick();
        let answer = Rc::new(RefCell::new(None));
        let a = answer.clone();
        let reply = f.ui.alert(Some(window), Alert::new("Proceed?").button("Yes").button("No"));
        f.ui.spawn_local(async move { *a.borrow_mut() = Some(reply.await) });
        pump(&f.ui);

        let ns_window = f.handle.ns_window(window).unwrap();
        let sheet = sheet_of(&ns_window);
        let no = find_button(&sheet.contentView().unwrap(), "No").expect("the No button");
        unsafe { no.performClick(None::<&AnyObject>) };
        pump(&f.ui);

        assert_eq!(*answer.borrow(), Some(1));
        f.ui.destroy(window);
        f.ui.tick();
    }

    pub fn open_panels_report_cancellation(f: &Fixture) {
        let window = f.ui.create_window("panel host", Size::new(600.0, 400.0));
        f.ui.tick();
        let answer = Rc::new(RefCell::new(Some(Some(vec![]))));
        let a = answer.clone();
        let reply = f.ui.open_file(Some(window), OpenFile::new().multiple());
        f.ui.spawn_local(async move { *a.borrow_mut() = Some(reply.await) });
        pump(&f.ui);

        let ns_window = f.handle.ns_window(window).unwrap();
        let sheet = sheet_of(&ns_window);
        let panel = sheet.downcast::<NSSavePanel>().expect("an open panel");
        unsafe { panel.cancel(None) };
        pump(&f.ui);

        assert_eq!(*answer.borrow(), Some(None), "cancelled");
        f.ui.destroy(window);
        f.ui.tick();
    }

    /// A folder panel has New Folder, which AppKit's open panel leaves off;
    /// a file panel keeps AppKit's default.
    pub fn folder_panels_can_make_folders(f: &Fixture) {
        let window = f.ui.create_window("panel host", Size::new(600.0, 400.0));
        f.ui.tick();
        for (request, folders) in [(OpenFile::new().directories(), true), (OpenFile::new(), false)] {
            let reply = f.ui.open_file(Some(window), request);
            f.ui.spawn_local(async move {
                reply.await;
            });
            pump(&f.ui);
            let ns_window = f.handle.ns_window(window).unwrap();
            let panel = sheet_of(&ns_window).downcast::<NSSavePanel>().expect("an open panel");
            assert_eq!(panel.canCreateDirectories(), folders, "New Folder on a {} panel", if folders { "folder" } else { "file" });
            unsafe { panel.cancel(None) };
            pump(&f.ui);
        }
        f.ui.destroy(window);
        f.ui.tick();
    }

    /// Destroying their window ends both sheets with their cancel
    /// response: the alert answers its cancel button, the panel no paths.
    /// A window shows one sheet at a time, so each has its own.
    pub fn sheets_end_with_their_window(f: &Fixture) {
        let first = f.ui.create_window("alert host", Size::new(400.0, 300.0));
        let second = f.ui.create_window("panel host", Size::new(600.0, 400.0));
        f.ui.tick();
        let answers = Rc::new(RefCell::new((None, None)));
        let (a, b) = (answers.clone(), answers.clone());
        let alert = f.ui.alert(Some(first), Alert::new("Proceed?").button("Yes").button("No"));
        let open = f.ui.open_file(Some(second), OpenFile::new());
        f.ui.spawn_local(async move { a.borrow_mut().0 = Some(alert.await) });
        f.ui.spawn_local(async move { b.borrow_mut().1 = Some(open.await) });
        pump(&f.ui);
        sheet_of(&f.handle.ns_window(first).unwrap());
        sheet_of(&f.handle.ns_window(second).unwrap());

        f.ui.destroy(first);
        f.ui.destroy(second);
        f.ui.tick();
        pump_until(&f.ui, || *answers.borrow() == (Some(1), Some(None)));
        assert_eq!(*answers.borrow(), (Some(1), Some(None)));
    }

    /// Trashes a file of its own into the user's trash, then deletes it
    /// from there: this terminal may not list `~/.Trash`, but the name is
    /// unique, so the trashed file keeps it.
    pub fn trash_moves_files_to_the_users_trash(f: &Fixture) {
        let name = format!("mitsuami-trash-check-{}.txt", std::process::id());
        let file = std::env::temp_dir().join(&name);
        std::fs::write(&file, b"trash me").unwrap();
        let answer = Rc::new(RefCell::new(None));
        let a = answer.clone();
        let reply = f.ui.trash(None, vec![file.clone()]);
        f.ui.spawn_local(async move { *a.borrow_mut() = Some(reply.await) });
        pump_until(&f.ui, || answer.borrow().is_some());

        assert_eq!(*answer.borrow(), Some(Ok(())));
        assert!(!file.exists(), "the file left its folder");
        let trashed = std::env::home_dir().unwrap().join(".Trash").join(&name);
        assert!(trashed.exists(), "it's in the trash, where Put Back finds it");
        std::fs::remove_file(trashed).unwrap();

        // A missing item fails with AppKit's reason.
        let a = answer.clone();
        *answer.borrow_mut() = None;
        let reply = f.ui.trash(None, vec![file]);
        f.ui.spawn_local(async move { *a.borrow_mut() = Some(reply.await) });
        pump_until(&f.ui, || answer.borrow().is_some());
        assert!(matches!(*answer.borrow(), Some(Err(ServiceError::Failed(_)))), "{:?}", answer.borrow());
    }
}

#[cfg(target_os = "macos")]
fn main() {
    use std::panic::{AssertUnwindSafe, catch_unwind};

    type Check = (&'static str, fn(&checks::Fixture));
    let checks: [Check; 9] = [
        ("clipboard_round_trips", checks::clipboard_round_trips),
        ("menus_are_installed_and_activate", checks::menus_are_installed_and_activate),
        ("submenus_check_marks_and_roles", checks::submenus_check_marks_and_roles),
        ("window_menus_are_there_while_it_is_main", checks::window_menus_are_there_while_it_is_main),
        ("alerts_are_answered_through_their_sheet", checks::alerts_are_answered_through_their_sheet),
        ("open_panels_report_cancellation", checks::open_panels_report_cancellation),
        ("folder_panels_can_make_folders", checks::folder_panels_can_make_folders),
        ("sheets_end_with_their_window", checks::sheets_end_with_their_window),
        ("trash_moves_files_to_the_users_trash", checks::trash_moves_files_to_the_users_trash),
    ];
    let filter: Vec<String> = std::env::args().skip(1).filter(|a| !a.starts_with('-')).collect();
    let fixture = checks::fixture();
    let mut failed = 0;
    println!("\nrunning {} tests", checks.len());
    for (name, check) in checks {
        if !filter.is_empty() && !filter.iter().any(|f| name.contains(f.as_str())) {
            continue;
        }
        let ok = catch_unwind(AssertUnwindSafe(|| check(&fixture))).is_ok();
        println!("test {name} ... {}", if ok { "ok" } else { "FAILED" });
        failed += usize::from(!ok);
    }
    println!("\ntest result: {}. {failed} failed\n", if failed == 0 { "ok" } else { "FAILED" });
    std::process::exit(if failed == 0 { 0 } else { 101 });
}

#[cfg(not(target_os = "macos"))]
fn main() {}