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