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    }
135}
136
137impl State {
138    /// Lets toolbars place their items now, and split windows their
139    /// content: a window that was never shown (as in tests) doesn't even
140    /// make its toolbar's views before.
141    pub(super) fn layout_toolbars(&self) {
142        for node in self.nodes.values() {
143            layout_toolbar(&node.widget);
144        }
145    }
146
147    /// Lets tables lay out their rows now rather than at the next display:
148    /// they report the rows they show, and the core builds those in the
149    /// same run-loop turn, before anything is drawn. Their callbacks only
150    /// emit.
151    pub(super) fn layout_lists(&self) {
152        for node in self.nodes.values() {
153            layout_list(&node.widget);
154        }
155    }
156
157    /// Notes the lists and windows a command touched: a list made, given
158    /// props, sized, given or losing rows, or scrolled; a window made,
159    /// given props or sized, or its toolbar items or sidebar changed.
160    /// Anything that can bring a list into view without touching it (a tab
161    /// view's page, a scroll view's offset) touches every list.
162    pub(super) fn note_touched(&mut self, command: &Command) {
163        let ids = match command {
164            Command::Create { id, .. }
165            | Command::SetProp { id, .. }
166            | Command::SetFrame { id, .. }
167            | Command::SetWindowSize { id, .. }
168            | Command::ScrollTo { id, .. }
169            | Command::ScrollToRow { id, .. } => [Some(*id), None],
170            Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
171            _ => return,
172        };
173        for id in ids.into_iter().flatten() {
174            let Some(node) = self.nodes.get(&id) else { continue };
175            match &node.widget {
176                Widget::List(_) => {
177                    self.touched_lists.insert(id);
178                }
179                Widget::Window { .. } => {
180                    self.touched_windows.insert(id);
181                }
182                Widget::Tabs(_) | Widget::Scroll(_) => self.touched_all_lists = true,
183                _ => {}
184            }
185            let parent = node.parent.and_then(|p| Some((p, &self.nodes.get(&p)?.widget)));
186            match parent {
187                // A row or cell host: its height is its row's.
188                Some((list, Widget::List(_))) => {
189                    self.touched_lists.insert(list);
190                }
191                // A sidebar or toolbar item.
192                Some((window, Widget::Window { .. })) => {
193                    self.touched_windows.insert(window);
194                }
195                _ => {}
196            }
197            // In a toolbar item, as its child or grandchild.
198            if let Some(window) = self.toolbar_item_above(id).and_then(|item| self.nodes[&item].parent) {
199                self.touched_windows.insert(window);
200            }
201        }
202    }
203
204    /// Lays out the lists and toolbars the batch touched (see
205    /// `layout_lists` and `layout_toolbars`): every one, after every
206    /// batch, forced each table to lay out again.
207    pub(super) fn layout_touched(&mut self) {
208        if std::mem::take(&mut self.touched_all_lists) {
209            self.touched_lists.clear();
210            self.layout_lists();
211        }
212        for id in std::mem::take(&mut self.touched_lists) {
213            if let Some(node) = self.nodes.get(&id) {
214                layout_list(&node.widget);
215            }
216        }
217        for id in std::mem::take(&mut self.touched_windows) {
218            if let Some(node) = self.nodes.get(&id) {
219                layout_toolbar(&node.widget);
220            }
221        }
222        self.place_headers();
223        self.extend_under_bars();
224    }
225
226    /// Puts each header at the top of a window's content in that window's
227    /// title bar, and takes out those that left it (see `header`). Beside a
228    /// sidebar a header stays where it is: the title bar is over the
229    /// sidebar too.
230    fn place_headers(&mut self) {
231        let headers: Vec<NodeId> = self.nodes.iter().filter(|(_, n)| n.header.is_some()).map(|(id, _)| *id).collect();
232        for id in headers {
233            let want = self.header_window(id);
234            let node = &self.nodes[&id];
235            let (header, placeholder) = (node.header.as_ref().unwrap(), node.widget.view());
236            let height = placeholder.frame().size.height;
237            let had = header.window.get();
238            if had != want {
239                let host_of = |w: Option<NodeId>| match w.and_then(|w| self.nodes.get(&w)).map(|n| &n.widget) {
240                    Some(Widget::Window { host, .. }) => Some(host.clone()),
241                    _ => None,
242                };
243                header.detach(placeholder, host_of(had).as_deref().map(|h| &**h));
244                if let Some(w) = want
245                    && let Some(Widget::Window { window, host, _delegate, .. }) = self.nodes.get(&w).map(|n| &n.widget)
246                {
247                    // As the first toolbar item does: the content keeps its
248                    // size, and the window grows by the bar.
249                    let size = host.frame().size;
250                    crate::sidebar::content_under_bar(self.mtm, window, host);
251                    _delegate.set_detail(Some(host));
252                    header.attach(w, window, host, height);
253                    window.setContentSize(
254                        _delegate.at_least_min(window, Size::new(size.width as f32, size.height as f32)),
255                    );
256                }
257            } else if let Some(w) = want
258                && let Some(Widget::Window { host, .. }) = self.nodes.get(&w).map(|n| &n.widget)
259            {
260                header.set_height(host, height);
261            }
262        }
263    }
264
265    /// The window whose title bar a header goes in: the one it's at the
266    /// top of the content of, if that window has no sidebar.
267    fn header_window(&self, id: NodeId) -> Option<NodeId> {
268        let node = self.nodes.get(&id)?;
269        if !node.header.as_ref()?.on.get() {
270            return None;
271        }
272        let mut parent = node.parent;
273        while let Some(p) = parent {
274            let above = self.nodes.get(&p)?;
275            match &above.widget {
276                Widget::Window { host, split: None, .. } => return at_top(node.widget.view(), host, 0.0).then_some(p),
277                Widget::Window { .. } | Widget::Scroll(_) | Widget::List(_) | Widget::Tabs(_) | Widget::Sidebar(_) => {
278                    return None;
279                }
280                _ if above.kind == WidgetKind::ToolbarItem => return None,
281                _ => parent = above.parent,
282            }
283        }
284        None
285    }
286
287    /// Runs the scroll views, lists and tables at the top of a window with
288    /// a sidebar or a toolbar up under its title bar and toolbar, as
289    /// Finder's content does: the content view is full size there, and the
290    /// host below the bar. One inside a scroll view or a list moves as that scrolls, so
291    /// it stays put. A list that moved lays out the rows now in view. In a
292    /// window with a header in its title bar, the one right under the
293    /// header runs up under it too, and so do the splits it's in, with
294    /// their panes: macOS shows nothing scrolling under its bars from a
295    /// split's pane that doesn't reach them.
296    pub(super) fn extend_under_bars(&self) {
297        // The windows' headers' heights.
298        let headers: std::collections::HashMap<NodeId, f64> = self
299            .nodes
300            .values()
301            .filter_map(|n| Some((n.header.as_ref()?.window.get()?, n.widget.view().frame().size.height)))
302            .collect();
303        // How far up each split runs, for the scroll views at their tops.
304        let mut splits: std::collections::HashMap<NodeId, f64> = std::collections::HashMap::new();
305        for node in self.nodes.values() {
306            let scroll = match &node.widget {
307                Widget::Scroll(scroll) => scroll,
308                Widget::List(list) => &list.scroll,
309                _ => continue,
310            };
311            let mut host = None;
312            let mut around = Vec::new();
313            let mut parent = node.parent;
314            while let Some((id, node)) = parent.and_then(|id| Some((id, self.nodes.get(&id)?))) {
315                match &node.widget {
316                    Widget::SplitView(_) => {
317                        around.push(id);
318                        parent = node.parent;
319                        continue;
320                    }
321                    Widget::Window { host: window, split: Some(_), .. } => host = Some((window, 0.0)),
322                    Widget::Window { host: window, toolbar: Some(_), .. } => {
323                        host = Some((window, headers.get(&id).copied().unwrap_or(0.0)))
324                    }
325                    Widget::Window { host: window, .. } => host = headers.get(&id).map(|h| (window, *h)),
326                    Widget::Scroll(_) | Widget::List(_) => {}
327                    _ => {
328                        parent = node.parent;
329                        continue;
330                    }
331                }
332                break;
333            }
334            // From where the core put it to the window's top: past the
335            // header, if it's right under one, and the bar.
336            let height = match host {
337                Some((host, header)) if at_top(scroll, host, header) => {
338                    unsafe { host.superview() }.map_or(0.0, |v| v.safeAreaInsets().top)
339                }
340                _ => 0.0,
341            };
342            if height > 0.0 {
343                for split in around {
344                    splits.insert(split, height);
345                }
346            }
347            if scroll.set_under_bar(height) {
348                layout_list(&node.widget);
349            }
350        }
351        for (id, node) in &self.nodes {
352            if let Widget::SplitView(split) = &node.widget {
353                split.set_under_bar(splits.get(id).copied().unwrap_or(0.0));
354            }
355        }
356    }
357}
358
359/// Whether the core put the view at `top` in its window's host: its top
360/// (0), or right under a header that high.
361fn at_top(view: &NSView, host: &NSView, top: f64) -> bool {
362    let Some(superview) = unsafe { view.superview() }.filter(|_| view.isDescendantOf(host)) else { return false };
363    let placed = superview.convertRect_toView(view.alignmentRectForFrame(view.frame()), Some(host));
364    (placed.origin.y - top).abs() < 0.5 && placed.size.height > 0.0
365}
366
367fn layout_toolbar(widget: &Widget) {
368    if let Widget::Window { window, toolbar, split, .. } = widget
369        && (toolbar.is_some() || split.is_some())
370    {
371        window.layoutIfNeeded();
372    }
373}
374
375fn layout_list(widget: &Widget) {
376    if let Widget::List(list) = widget {
377        // Scrolling doesn't mark the table as needing layout; its rows
378        // follow at the next display.
379        list.table.setNeedsLayout(true);
380        list.scroll.layoutSubtreeIfNeeded();
381        list.remeasure();
382    }
383}