Skip to main content

mitsuami_appkit/backend/
handle.rs

1//! The backend's handle: its command log and test hooks.
2
3use mitsuami_core::{Command, NativeAppInfo, NativeIcon, NodeId, Size, WidgetKind};
4use objc2::Message;
5use objc2::rc::Retained;
6use objc2_app_kit::{NSApplication, NSView};
7use objc2_foundation::{NSBundle, NSDate, NSDefaultRunLoopMode, NSProcessInfo, NSRunLoop};
8
9use super::{AppKitHandle, State, Widget};
10
11impl AppKitHandle {
12    /// The app's name as its menu shows it: the app's, or else the
13    /// process's (a bundled app's executable).
14    pub(crate) fn app_name(&self) -> String {
15        let name = self.state.borrow().app_name.clone();
16        name.unwrap_or_else(|| NSProcessInfo::processInfo().processName().to_string())
17    }
18
19    pub fn command_log(&self) -> Vec<Command> {
20        self.state.borrow().log.clone()
21    }
22
23    pub fn take_command_log(&self) -> Vec<Command> {
24        std::mem::take(&mut self.state.borrow_mut().log)
25    }
26
27    /// Number of live native nodes.
28    pub fn node_count(&self) -> usize {
29        self.state.borrow().nodes.len()
30    }
31
32    /// Escape hatch: the native view of any node (a window's content view).
33    pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
34        let state = self.state.borrow();
35        let view = state.nodes.get(&id)?.widget.view();
36        Some(view.retain())
37    }
38}
39
40impl mitsuami_core::TestHooks for AppKitHandle {
41    fn name(&self) -> &'static str {
42        "appkit"
43    }
44
45    fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
46        let state = self.state.borrow();
47        let host = state.nodes.get(&node)?;
48        match &state.nodes.get(&host.parent?)?.widget {
49            Widget::List(list) => list.dragged_files(host.row?),
50            _ => None,
51        }
52    }
53
54    fn resize_window(&self, window: NodeId, size: Size) {
55        AppKitHandle::resize_window(self, window, size);
56    }
57
58    /// As the close button does: the window asks its delegate.
59    fn close_window(&self, window: NodeId) {
60        if let Some(window) = self.ns_window(window) {
61            window.performClose(None);
62        }
63    }
64
65    fn take_command_log(&self) -> Vec<Command> {
66        AppKitHandle::take_command_log(self)
67    }
68
69    fn node_count(&self) -> usize {
70        AppKitHandle::node_count(self)
71    }
72
73    /// The id is the bundle's; the name is kept, as only the menus show
74    /// it; the icon is the Dock's, in points.
75    fn app_info(&self, _window: NodeId) -> NativeAppInfo {
76        let mtm = self.state.borrow().mtm;
77        let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
78        // In points: AppKit keeps a snapshot at the screen's scale.
79        let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
80            let size = image.size();
81            NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
82        });
83        NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
84    }
85
86    /// Offscreen windows get no display cycle, where tables add the rows
87    /// scrolling brought into view and toolbars place their items. While a
88    /// search field is shown, timers that are due fire, as in the app's run
89    /// loop: it searches once typing pauses. Not always yet: tables and tab
90    /// views run timers too, which change what their tests capture.
91    fn settle(&self) {
92        if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
93            NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
94        }
95        // Thumbnails arrive through the main queue: run the run loop until
96        // they're shown, as the app's would, so captures have them.
97        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
98        while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
99            let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
100            NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
101        }
102        let state = self.state.borrow();
103        state.layout_lists();
104        state.layout_toolbars();
105    }
106}
107
108impl State {
109    /// Lets toolbars place their items now, and split windows their
110    /// content: a window that was never shown (as in tests) doesn't even
111    /// make its toolbar's views before.
112    pub(super) fn layout_toolbars(&self) {
113        for node in self.nodes.values() {
114            layout_toolbar(&node.widget);
115        }
116    }
117
118    /// Lets tables lay out their rows now rather than at the next display:
119    /// they report the rows they show, and the core builds those in the
120    /// same run-loop turn, before anything is drawn. Their callbacks only
121    /// emit.
122    pub(super) fn layout_lists(&self) {
123        for node in self.nodes.values() {
124            layout_list(&node.widget);
125        }
126    }
127
128    /// Notes the lists and windows a command touched: a list made, given
129    /// props, sized, given or losing rows, or scrolled; a window made,
130    /// given props or sized, or its toolbar items or sidebar changed.
131    /// Anything that can bring a list into view without touching it (a tab
132    /// view's page, a scroll view's offset) touches every list.
133    pub(super) fn note_touched(&mut self, command: &Command) {
134        let ids = match command {
135            Command::Create { id, .. }
136            | Command::SetProp { id, .. }
137            | Command::SetFrame { id, .. }
138            | Command::SetWindowSize { id, .. }
139            | Command::ScrollTo { id, .. }
140            | Command::ScrollToRow { id, .. } => [Some(*id), None],
141            Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
142            _ => return,
143        };
144        for id in ids.into_iter().flatten() {
145            let Some(node) = self.nodes.get(&id) else { continue };
146            match &node.widget {
147                Widget::List(_) => {
148                    self.touched_lists.insert(id);
149                }
150                Widget::Window { .. } => {
151                    self.touched_windows.insert(id);
152                }
153                Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
154                _ => {}
155            }
156            let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
157            match parent {
158                // A row or cell host: its height is its row's.
159                Some((list, Widget::List(_))) => {
160                    self.touched_lists.insert(list);
161                }
162                // A sidebar or toolbar item.
163                Some((window, Widget::Window { .. })) => {
164                    self.touched_windows.insert(window);
165                }
166                _ => {}
167            }
168            // In a toolbar item, as its child or grandchild.
169            if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
170                self.touched_windows.insert(window);
171            }
172        }
173    }
174
175    /// Lays out the lists and toolbars the batch touched (see
176    /// `layout_lists` and `layout_toolbars`): every one, after every
177    /// batch, forced each table to lay out again.
178    pub(super) fn layout_touched(&mut self) {
179        if std::mem::take(&mut self.touched_all_lists) {
180            self.touched_lists.clear();
181            self.layout_lists();
182        }
183        for id in std::mem::take(&mut self.touched_lists) {
184            if let Some(node) = self.nodes.get(&id) {
185                layout_list(&node.widget);
186            }
187        }
188        for id in std::mem::take(&mut self.touched_windows) {
189            if let Some(node) = self.nodes.get(&id) {
190                layout_toolbar(&node.widget);
191            }
192        }
193    }
194}
195
196fn layout_toolbar(widget: &Widget) {
197    if let Widget::Window { window, toolbar, split, .. } = widget
198        && (toolbar.is_some() || split.is_some())
199    {
200        window.layoutIfNeeded();
201    }
202}
203
204fn layout_list(widget: &Widget) {
205    if let Widget::List(list) = widget {
206        // Scrolling doesn't mark the table as needing layout; its rows
207        // follow at the next display.
208        list.table.setNeedsLayout(true);
209        list.scroll.layoutSubtreeIfNeeded();
210    }
211}