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