Skip to main content

mitsuami_appkit/backend/
handle.rs

1//! The backend's handle: its command log and test hooks.
2
3use mitsuami_core::{ActionError, Command, NativeAppInfo, NativeIcon, NodeId, Point, Size, WidgetKind};
4use objc2::Message;
5use objc2::rc::Retained;
6use objc2_app_kit::{NSApplication, NSView};
7use objc2_foundation::{NSBundle, NSDate, NSDefaultRunLoopMode, NSPoint, NSProcessInfo, NSRunLoop};
8
9use super::{AppKitHandle, State, Widget};
10
11impl AppKitHandle {
12    /// The app's id: `AppInfo::id`, else its bundle's.
13    pub(crate) fn app_id(&self) -> Option<String> {
14        let id = self.state.borrow().app_id.clone();
15        id.or_else(|| objc2_foundation::NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string()))
16    }
17
18    /// The app's name as its menu shows it: the app's, or else the
19    /// process's (a bundled app's executable).
20    pub(crate) fn app_name(&self) -> String {
21        let name = self.state.borrow().app_name.clone();
22        name.unwrap_or_else(|| NSProcessInfo::processInfo().processName().to_string())
23    }
24
25    pub fn command_log(&self) -> Vec<Command> {
26        self.state.borrow().log.clone()
27    }
28
29    pub fn take_command_log(&self) -> Vec<Command> {
30        std::mem::take(&mut self.state.borrow_mut().log)
31    }
32
33    /// Number of live native nodes.
34    pub fn node_count(&self) -> usize {
35        self.state.borrow().nodes.len()
36    }
37
38    /// Escape hatch: the native view of any node (a window's content view).
39    pub fn ns_view(&self, id: NodeId) -> Option<Retained<NSView>> {
40        let state = self.state.borrow();
41        let view = state.nodes.get(&id)?.widget.view();
42        Some(view.retain())
43    }
44}
45
46impl mitsuami_core::TestHooks for AppKitHandle {
47    fn name(&self) -> &'static str {
48        "appkit"
49    }
50
51    fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
52        let state = self.state.borrow();
53        let host = state.nodes.get(&node)?;
54        match &state.nodes.get(&host.parent?)?.widget {
55            Widget::List(list) => list.dragged_files(host.row?),
56            _ => None,
57        }
58    }
59
60    /// AppKit's own `hitTest:` from the window's content view, then the
61    /// nearest view up from what it hit that's a node's.
62    fn hit(&self, window: NodeId, at: Point) -> Result<Option<NodeId>, ActionError> {
63        let state = self.state.borrow();
64        let content = state.nodes.get(&window).ok_or(ActionError::UnknownNode)?.widget.view().retain();
65        let height = content.bounds().size.height;
66        let local = NSPoint::new(at.x as f64, if content.isFlipped() { at.y as f64 } else { height - at.y as f64 });
67        // `hitTest:` takes a point in the view's superview.
68        let point = match unsafe { content.superview() } {
69            Some(parent) => content.convertPoint_toView(local, Some(&parent)),
70            None => local,
71        };
72        let mut view = content.hitTest(point);
73        while let Some(v) = view {
74            if let Some((id, _)) = state.nodes.iter().find(|(_, n)| *n.widget.view() == *v) {
75                return Ok(Some(*id));
76            }
77            view = unsafe { v.superview() };
78        }
79        Ok(None)
80    }
81
82    fn resize_window(&self, window: NodeId, size: Size) {
83        AppKitHandle::resize_window(self, window, size);
84    }
85
86    /// As the close button does: the window asks its delegate.
87    fn close_window(&self, window: NodeId) {
88        if let Some(window) = self.ns_window(window) {
89            window.performClose(None);
90        }
91    }
92
93    fn take_command_log(&self) -> Vec<Command> {
94        AppKitHandle::take_command_log(self)
95    }
96
97    fn node_count(&self) -> usize {
98        AppKitHandle::node_count(self)
99    }
100
101    /// The id is the bundle's; the name is kept, as only the menus show
102    /// it; the icon is the Dock's, in points.
103    fn app_info(&self, _window: NodeId) -> NativeAppInfo {
104        let mtm = self.state.borrow().mtm;
105        let id = NSBundle::mainBundle().bundleIdentifier().map(|id| id.to_string());
106        // In points: AppKit keeps a snapshot at the screen's scale.
107        let icon = NSApplication::sharedApplication(mtm).applicationIconImage().map(|image| {
108            let size = image.size();
109            NativeIcon::Image { width: size.width.round() as u32, height: size.height.round() as u32 }
110        });
111        NativeAppInfo { id, name: self.state.borrow().app_name.clone(), icon }
112    }
113
114    /// Offscreen windows get no display cycle, where tables add the rows
115    /// scrolling brought into view and toolbars place their items. While a
116    /// search field is shown, timers that are due fire, as in the app's run
117    /// loop: it searches once typing pauses. Not always yet: tables and tab
118    /// views run timers too, which change what their tests capture.
119    fn settle(&self) {
120        if self.state.borrow().nodes.values().any(|n| n.kind == WidgetKind::SearchInput) {
121            NSRunLoop::currentRunLoop().limitDateForMode(unsafe { NSDefaultRunLoopMode });
122        }
123        // Thumbnails arrive through the main queue: run the run loop until
124        // they're shown, as the app's would, so captures have them.
125        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
126        while super::images::thumbnails_pending() && std::time::Instant::now() < deadline {
127            let until = NSDate::dateWithTimeIntervalSinceNow(0.01);
128            NSRunLoop::currentRunLoop().runMode_beforeDate(unsafe { NSDefaultRunLoopMode }, &until);
129        }
130        let state = self.state.borrow();
131        state.layout_lists();
132        state.layout_toolbars();
133        state.extend_under_bars();
134        // Windows never shown report their frame here, once laid out, as a
135        // shown window does as it shows.
136        if !state.options.show_windows {
137            for node in state.nodes.values() {
138                if let Widget::Window { window, _delegate, .. } = &node.widget {
139                    _delegate.report_frame(window);
140                }
141            }
142        }
143    }
144}
145
146impl State {
147    /// Lets toolbars place their items now, and split windows their
148    /// content: a window that was never shown (as in tests) doesn't even
149    /// make its toolbar's views before.
150    pub(super) fn layout_toolbars(&self) {
151        for node in self.nodes.values() {
152            layout_toolbar(&node.widget);
153        }
154    }
155
156    /// Lets tables lay out their rows now rather than at the next display:
157    /// they report the rows they show, and the core builds those in the
158    /// same run-loop turn, before anything is drawn. Their callbacks only
159    /// emit.
160    pub(super) fn layout_lists(&self) {
161        for node in self.nodes.values() {
162            layout_list(&node.widget);
163        }
164    }
165
166    /// Notes the lists and windows a command touched: a list made, given
167    /// props, sized, given or losing rows, or scrolled; a window made,
168    /// given props or sized, or its toolbar items or sidebar changed.
169    /// Anything that can bring a list into view without touching it (a tab
170    /// view's page, a scroll view's offset) touches every list.
171    pub(super) fn note_touched(&mut self, command: &Command) {
172        let ids = match command {
173            Command::Create { id, .. }
174            | Command::SetProp { id, .. }
175            | Command::SetFrame { id, .. }
176            | Command::SetWindowSize { id, .. }
177            | Command::ScrollTo { id, .. }
178            | Command::ScrollToRow { id, .. } => [Some(*id), None],
179            Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
180            _ => return,
181        };
182        for id in ids.into_iter().flatten() {
183            let Some(node) = self.nodes.get(&id) else { continue };
184            match &node.widget {
185                Widget::List(_) => {
186                    self.touched_lists.insert(id);
187                }
188                Widget::Window { .. } => {
189                    self.touched_windows.insert(id);
190                }
191                Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
192                _ => {}
193            }
194            let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
195            match parent {
196                // A row or cell host: its height is its row's.
197                Some((list, Widget::List(_))) => {
198                    self.touched_lists.insert(list);
199                }
200                // A sidebar or toolbar item.
201                Some((window, Widget::Window { .. })) => {
202                    self.touched_windows.insert(window);
203                }
204                _ => {}
205            }
206            // In a toolbar item, as its child or grandchild.
207            if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
208                self.touched_windows.insert(window);
209            }
210        }
211    }
212
213    /// Lays out the lists and toolbars the batch touched (see
214    /// `layout_lists` and `layout_toolbars`): every one, after every
215    /// batch, forced each table to lay out again.
216    pub(super) fn layout_touched(&mut self) {
217        if std::mem::take(&mut self.touched_all_lists) {
218            self.touched_lists.clear();
219            self.layout_lists();
220        }
221        for id in std::mem::take(&mut self.touched_lists) {
222            if let Some(node) = self.nodes.get(&id) {
223                layout_list(&node.widget);
224            }
225        }
226        for id in std::mem::take(&mut self.touched_windows) {
227            if let Some(node) = self.nodes.get(&id) {
228                layout_toolbar(&node.widget);
229            }
230        }
231        self.place_headers();
232        self.extend_under_bars();
233    }
234
235    /// Puts each header at the top of a window's content in that window's
236    /// title bar, and takes out those that left it (see `header`). Beside a
237    /// sidebar a header stays where it is: the title bar is over the
238    /// sidebar too.
239    fn place_headers(&mut self) {
240        let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
241        for id in headers {
242            let want = self.header_window(id);
243            let node = &self.nodes[&id];
244            let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
245            let height = placeholder.frame().size.height;
246            let had = header.window.get();
247            if had != want {
248                let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
249                    Some(Widget::Window { host, .. }) => Some(host.clone()),
250                    _ => None,
251                };
252                header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
253                if let Some(w) = want
254                    && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
255                {
256                    // As the first toolbar item does: the content keeps its
257                    // size, and the window grows by the bar.
258                    let size = host.frame().size;
259                    crate::sidebar::content_under_bar(self.mtm, window, host);
260                    _delegate.set_detail(Some(host));
261                    header.attach(w, window, host, height);
262                    window.setContentSize(
263                        _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
264                    );
265                }
266            } else if let Some(w) = want
267                && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
268            {
269                header.set_height(host, height);
270            }
271        }
272    }
273
274    /// The window whose title bar a header goes in: the one it's at the
275    /// top of the content of, if that window has no sidebar.
276    fn header_window(&self, id: NodeId) -> Option<NodeId> {
277        let node = self.nodes.get(&id)?;
278        if !node.header.as_ref()?.on.get() {
279            return None;
280        }
281        let mut parent = node.parent;
282        while let Some(p) = parent {
283            let above = self.nodes.get(&p)?;
284            match &above.widget {
285                Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
286                Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
287                    return None;
288                }
289                _ if above.kind == WidgetKind::ToolbarItem => return None,
290                _ => parent = above.parent,
291            }
292        }
293        None
294    }
295
296    /// Runs the scroll views, lists and tables at the top of a window with
297    /// a sidebar or a toolbar up under its title bar and toolbar, as
298    /// Finder's content does: the content view is full size there, and the
299    /// host below the bar. One inside a scroll view or a list moves as that scrolls, so
300    /// it stays put. A list that moved lays out the rows now in view. In a
301    /// window with a header in its title bar, the one right under the
302    /// header runs up under it too, and so do the splits it's in, with
303    /// their panes: macOS shows nothing scrolling under its bars from a
304    /// split's pane that doesn't reach them.
305    pub(super) fn extend_under_bars(&self) {
306        // The windows' headers' heights.
307        let headers: std::collections::HashMap<NodeId, f64> = self
308            .nodes
309            .values()
310            .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
311            .collect();
312        // How far up each split runs, for the scroll views at their tops.
313        let mut splits: std::collections::HashMap<NodeId, f64> = std::collections::HashMap::new();
314        for node in self.nodes.values() {
315            let scroll = match &node.widget {
316                Widget::Scroll(scroll) => scroll,
317                Widget::List(list) => &list.scroll,
318                _ => continue,
319            };
320            let mut host = None;
321            let mut around = Vec::new();
322            let mut parent = node.parent;
323            while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
324                match &node.widget {
325                    Widget::SplitView(_) => {
326                        around.push(id);
327                        parent = node.parent;
328                        continue;
329                    }
330                    Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
331                    Widget::Window { host: window, toolbar: Some(_), .. } => {
332                        host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
333                    }
334                    Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
335                    Widget::Scroll(_) | Widget::List(_) => {}
336                    _ => {
337                        parent = node.parent;
338                        continue;
339                    }
340                }
341                break;
342            }
343            // From where the core put it to the window's top: past the
344            // header, if it's right under one, and the bar.
345            let height = match host {
346                Some((host, header)) if at_top(scroll, host, header) => {
347                    unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
348                }
349                _ => 0.0,
350            };
351            if height > 0.0 {
352                for split in around {
353                    splits.insert(split, height);
354                }
355            }
356            if scroll.set_under_bar(height) {
357                layout_list(&node.widget);
358            }
359        }
360        for (id, node) in &self.nodes {
361            if let Widget::SplitView(split) = &node.widget {
362                split.set_under_bar(splits.get(id).copied().unwrap_or(0.0));
363            }
364        }
365    }
366}
367
368/// Whether the core put the view at `top` in its window's host: its top
369/// (0), or right under a header that high.
370fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
371    let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
372    let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
373    (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
374}
375
376fn layout_toolbar(widget: &Widget) {
377    if let Widget::Window { window, toolbar, split, .. } = widget
378        && (toolbar.is_some() || split.is_some())
379    {
380        window.layoutIfNeeded();
381    }
382}
383
384fn layout_list(widget: &Widget) {
385    if let Widget::List(list) = widget {
386        // Scrolling doesn't mark the table as needing layout; its rows
387        // follow at the next display.
388        list.table.setNeedsLayout(true);
389        list.scroll.layoutSubtreeIfNeeded();
390        list.remeasure();
391    }
392}