Skip to main content

mitsuami_headless/
handle.rs

1//! The handle tests keep: the command log, and the user's window and system changes.
2
3use mitsuami_core::a11y::A11yProps;
4use mitsuami_core::backend::PlatformMetrics;
5use mitsuami_core::{
6    ActionError, Command, Insets, NativeAppInfo, NativeIcon, NodeId, Point, Prop, Size, SurfaceInput, UiEvent,
7    WidgetKind, find_prop,
8};
9
10use super::measure::png_size;
11use super::metrics::{SCREEN, WORK_AREA};
12use super::windows::at_least_min;
13use super::{HeadlessHandle, State};
14
15impl HeadlessHandle {
16    /// Records the commands applied from now on, for `command_log` and
17    /// `take_command_log`, or stops and drops them.
18    pub fn record_commands(&self, on: bool) {
19        let mut state = self.state.borrow_mut();
20        state.recording = on;
21        if !on {
22            state.log = Vec::new();
23        }
24    }
25
26    /// Every command applied since recording started (`record_commands`),
27    /// in order.
28    pub fn command_log(&self) -> Vec<Command> {
29        self.state.borrow().log.clone()
30    }
31
32    pub fn take_command_log(&self) -> Vec<Command> {
33        std::mem::take(&mut self.state.borrow_mut().log)
34    }
35
36    /// The app's language as the core last gave it (`Backend::set_locale`),
37    /// and whether it's right to left.
38    pub fn app_locale(&self) -> Option<(String, bool)> {
39        self.state.borrow().locale.as_ref().map(|(language, rtl)| (language.to_string(), *rtl))
40    }
41
42    /// Simulates the user resizing a window, which goes no smaller than
43    /// its minimum size, and keeps its height if its content sets it. A
44    /// window that isn't resizable keeps its size.
45    pub fn resize_window(&self, window: NodeId, size: Size) {
46        let mut state = self.state.borrow_mut();
47        if state.nodes.get(&window).and_then(|n| find_prop!(n.props, Resizable)) == Some(false) {
48            return;
49        }
50        let size = state.nodes.get(&window).map_or(size, |node| {
51            let size = at_least_min(node, size);
52            match find_prop!(node.props, HeightFollowsContent) {
53                Some(true) => Size::new(size.width, node.frame.size.height),
54                _ => size,
55            }
56        });
57        if let Some(node) = state.nodes.get_mut(&window) {
58            node.frame.size = size;
59        }
60        state.emit(window, UiEvent::WindowResized(size));
61    }
62
63    /// The size of the screen a window in full screen fills.
64    pub fn screen(&self) -> Size {
65        SCREEN
66    }
67
68    /// Simulates a window becoming the active one, or another taking over.
69    pub fn set_window_active(&self, window: NodeId, active: bool) {
70        let mut state = self.state.borrow_mut();
71        if active {
72            state.active_window = Some(window);
73        } else if state.active_window == Some(window) {
74            state.active_window = None;
75        }
76        state.emit(window, UiEvent::WindowActiveChanged(active));
77    }
78
79    /// The window taking keys: the last one presented or made active.
80    pub fn active_window(&self) -> Option<NodeId> {
81        self.state.borrow().active_window
82    }
83
84    /// Simulates the user putting a window in full screen, or taking it
85    /// out (the title bar's button, the window manager's key).
86    pub fn set_full_screen(&self, window: NodeId, on: bool) {
87        let mut state = self.state.borrow_mut();
88        if !state.nodes.contains_key(&window) {
89            return;
90        }
91        state.set_prop(window, Prop::FullScreen(on));
92        state.fill_screen(window, on);
93        state.emit(window, UiEvent::FullScreenChanged(on));
94    }
95
96    /// The size of a maximized window's content.
97    pub fn work_area(&self) -> Size {
98        WORK_AREA
99    }
100
101    /// Simulates the user maximizing a window, or restoring it (the title
102    /// bar's button, a double-click on it, the window manager's key).
103    pub fn set_maximized(&self, window: NodeId, on: bool) {
104        let mut state = self.state.borrow_mut();
105        if !state.nodes.contains_key(&window) {
106            return;
107        }
108        state.set_prop(window, Prop::Maximized(on));
109        state.maximize(window, on);
110        state.emit(window, UiEvent::MaximizedChanged(on));
111    }
112
113    /// Simulates the user showing or hiding a window's sidebar (the
114    /// platform's toggle, its divider dragged away).
115    pub fn set_sidebar_shown(&self, sidebar: NodeId, shown: bool) {
116        let mut state = self.state.borrow_mut();
117        let Some(node) = state.nodes.get(&sidebar) else { return };
118        if find_prop!(node.props, SidebarShown).unwrap_or(true) == shown {
119            return;
120        }
121        state.set_prop(sidebar, Prop::SidebarShown(shown));
122        state.emit(sidebar, UiEvent::SidebarShownChanged(shown));
123    }
124
125    /// Simulates a platform whose scroll bars take room from a scroll
126    /// view's content, as classic scroll bars do (the viewport is inside
127    /// these insets).
128    pub fn set_viewport_insets(&self, scroll_view: NodeId, insets: Insets) {
129        let mut state = self.state.borrow_mut();
130        let Some(node) = state.nodes.get_mut(&scroll_view) else { return };
131        if node.kind != WidgetKind::ScrollView || node.viewport_insets == insets {
132            return;
133        }
134        node.viewport_insets = insets;
135        state.emit(scroll_view, UiEvent::ViewportInsets(insets));
136    }
137
138    /// Simulates a change of system settings (text size, dark mode, …).
139    pub fn set_metrics(&self, metrics: PlatformMetrics) {
140        let mut state = self.state.borrow_mut();
141        state.metrics = metrics;
142        let surfaces: Vec<NodeId> =
143            state.nodes.iter().filter(|(_, n)| n.surface.is_some()).map(|(id, _)| *id).collect();
144        for surface in surfaces {
145            state.size_surface(surface);
146        }
147        let windows: Vec<NodeId> =
148            state.nodes.iter().filter(|(_, n)| n.kind == WidgetKind::Window).map(|(id, _)| *id).collect();
149        for window in windows {
150            state.emit(window, UiEvent::MetricsChanged);
151        }
152    }
153
154    pub fn focused(&self) -> Option<NodeId> {
155        self.state.borrow().focused
156    }
157
158    /// Simulates the user switching to another app: the window's GPU
159    /// surfaces lose their pointer lock and keyboard grab, as every
160    /// platform ends them.
161    pub fn deactivate(&self, window: NodeId) {
162        let mut state = self.state.borrow_mut();
163        let surfaces: Vec<NodeId> = state
164            .nodes
165            .iter()
166            .filter(|(id, n)| n.kind == WidgetKind::GpuSurface && state.window_of(**id) == Some(window))
167            .map(|(id, _)| *id)
168            .collect();
169        for surface in surfaces {
170            state.end_lock(surface, Prop::PointerLock(false));
171            state.end_lock(surface, Prop::KeyboardGrab(false));
172        }
173    }
174
175    /// Simulates the mouse moving while a surface holds the pointer: its
176    /// move with the host's acceleration, and before it. Headless has no
177    /// acceleration, and one count to a point.
178    pub fn move_locked_pointer(&self, surface: NodeId, dx: f32, dy: f32) {
179        let state = self.state.borrow();
180        if state.nodes.get(&surface).and_then(|n| find_prop!(n.props, PointerLock)) != Some(true) {
181            return;
182        }
183        state.emit(surface, UiEvent::SurfaceInput(SurfaceInput::Motion { dx, dy }));
184        state.emit(surface, UiEvent::SurfaceInput(SurfaceInput::RawMotion { dx, dy }));
185    }
186
187    pub fn a11y(&self, id: NodeId) -> Option<A11yProps> {
188        self.state.borrow().nodes.get(&id).map(|n| n.a11y.clone())
189    }
190
191    /// Number of live native nodes: a leak detector for tests.
192    pub fn node_count(&self) -> usize {
193        self.state.borrow().nodes.len()
194    }
195}
196
197impl mitsuami_core::TestHooks for HeadlessHandle {
198    fn name(&self) -> &'static str {
199        "headless"
200    }
201
202    fn resize_window(&self, window: NodeId, size: Size) {
203        HeadlessHandle::resize_window(self, window, size);
204    }
205
206    fn close_window(&self, window: NodeId) {
207        self.state.borrow_mut().emit(window, UiEvent::WindowCloseRequested);
208    }
209
210    fn take_command_log(&self) -> Vec<Command> {
211        HeadlessHandle::take_command_log(self)
212    }
213
214    fn node_count(&self) -> usize {
215        HeadlessHandle::node_count(self)
216    }
217
218    /// The topmost node with a frame there (later children are over
219    /// earlier ones), past containers clicks pass through.
220    fn hit(&self, window: NodeId, at: Point) -> Result<Option<NodeId>, ActionError> {
221        fn reach(state: &State, id: NodeId, at: Point) -> Option<NodeId> {
222            let node = &state.nodes[&id];
223            // A scroll view's content is placed from its viewport's top-left.
224            let inside = match node.kind {
225                WidgetKind::ScrollView => Point::new(at.x + node.scroll_offset.x, at.y + node.scroll_offset.y),
226                _ => at,
227            };
228            for child in node.children.iter().rev() {
229                let c = &state.nodes[child];
230                let f = c.frame;
231                if f.width() <= 0.0 || f.height() <= 0.0 || find_prop!(c.props, ClickThrough) == Some(true) {
232                    continue;
233                }
234                if inside.x >= f.x() && inside.x < f.max_x() && inside.y >= f.y() && inside.y < f.max_y() {
235                    let local = Point::new(inside.x - f.x(), inside.y - f.y());
236                    return reach(state, *child, local).or(Some(*child));
237                }
238            }
239            None
240        }
241        let state = self.state.borrow();
242        if !state.nodes.contains_key(&window) {
243            return Err(ActionError::UnknownNode);
244        }
245        Ok(reach(&state, window, at))
246    }
247
248    /// The selected rows' files if the row is selected, else its own, as
249    /// platforms' lists drag.
250    fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
251        let state = self.state.borrow();
252        let host = state.nodes.get(&node)?;
253        let row = find_prop!(host.props, Row).or_else(|| find_prop!(host.props, Cell).map(|cell| cell.row))?;
254        let list = &state.nodes[&host.parent?];
255        let files = find_prop!(list.props, RowFiles)?;
256        let selected = find_prop!(list.props, Selected).unwrap_or_default();
257        let rows = if selected.contains(&row) { selected } else { vec![row] };
258        let dragged: Vec<_> =
259            rows.iter().filter_map(|r| files.iter().find(|(f, _)| f == r).map(|(_, path)| path.clone())).collect();
260        (!dragged.is_empty()).then_some(dragged)
261    }
262
263    /// All of it, as every platform has a place for some of it; the icon's
264    /// size from its PNG header.
265    fn app_info(&self, _window: NodeId) -> NativeAppInfo {
266        let app = self.state.borrow().app.clone();
267        let icon = app.icon.and_then(|icon| icon.read()).and_then(|bytes| png_size(&bytes));
268        NativeAppInfo {
269            id: app.id,
270            name: app.name,
271            icon: icon.map(|size| NativeIcon::Image { width: size.width as u32, height: size.height as u32 }),
272        }
273    }
274}