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, WindowFrame, 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        state.report_frames();
62    }
63
64    /// The size of the screen a window in full screen fills.
65    pub fn screen(&self) -> Size {
66        SCREEN
67    }
68
69    /// Simulates a window becoming the active one, or another taking over.
70    pub fn set_window_active(&self, window: NodeId, active: bool) {
71        let mut state = self.state.borrow_mut();
72        if active {
73            state.active_window = Some(window);
74        } else if state.active_window == Some(window) {
75            state.active_window = None;
76        }
77        state.emit(window, UiEvent::WindowActiveChanged(active));
78    }
79
80    /// The window taking keys: the last one presented or made active.
81    pub fn active_window(&self) -> Option<NodeId> {
82        self.state.borrow().active_window
83    }
84
85    /// Simulates the user putting a window in full screen, or taking it
86    /// out (the title bar's button, the window manager's key).
87    pub fn set_full_screen(&self, window: NodeId, on: bool) {
88        let mut state = self.state.borrow_mut();
89        if !state.nodes.contains_key(&window) {
90            return;
91        }
92        state.set_prop(window, Prop::FullScreen(on));
93        state.fill_screen(window, on);
94        state.emit(window, UiEvent::FullScreenChanged(on));
95    }
96
97    /// The size of a maximized window's content.
98    pub fn work_area(&self) -> Size {
99        WORK_AREA
100    }
101
102    /// Where a new window opens when nothing places it.
103    pub fn new_window_at(&self) -> Point {
104        super::metrics::NEW_WINDOW_AT
105    }
106
107    /// Simulates the user moving a window by its title bar; it stays on
108    /// the screen.
109    pub fn move_window(&self, window: NodeId, to: Point) {
110        let mut state = self.state.borrow_mut();
111        let Some(node) = state.nodes.get(&window) else { return };
112        let size = super::windows::restored_size(node);
113        state.place(window, WindowFrame { position: Some(to), size });
114        state.report_frames();
115    }
116
117    /// Simulates the user maximizing a window, or restoring it (the title
118    /// bar's button, a double-click on it, the window manager's key).
119    pub fn set_maximized(&self, window: NodeId, on: bool) {
120        let mut state = self.state.borrow_mut();
121        if !state.nodes.contains_key(&window) {
122            return;
123        }
124        state.set_prop(window, Prop::Maximized(on));
125        state.maximize(window, on);
126        state.emit(window, UiEvent::MaximizedChanged(on));
127    }
128
129    /// Simulates the user showing or hiding a window's sidebar (the
130    /// platform's toggle, its divider dragged away).
131    pub fn set_sidebar_shown(&self, sidebar: NodeId, shown: bool) {
132        let mut state = self.state.borrow_mut();
133        let Some(node) = state.nodes.get(&sidebar) else { return };
134        if find_prop!(node.props, SidebarShown).unwrap_or(true) == shown {
135            return;
136        }
137        state.set_prop(sidebar, Prop::SidebarShown(shown));
138        state.emit(sidebar, UiEvent::SidebarShownChanged(shown));
139    }
140
141    /// Simulates a platform whose scroll bars take room from a scroll
142    /// view's content, as classic scroll bars do (the viewport is inside
143    /// these insets).
144    pub fn set_viewport_insets(&self, scroll_view: NodeId, insets: Insets) {
145        let mut state = self.state.borrow_mut();
146        let Some(node) = state.nodes.get_mut(&scroll_view) else { return };
147        if node.kind != WidgetKind::ScrollView || node.viewport_insets == insets {
148            return;
149        }
150        node.viewport_insets = insets;
151        state.emit(scroll_view, UiEvent::ViewportInsets(insets));
152    }
153
154    /// Simulates a change of system settings (text size, dark mode, …).
155    pub fn set_metrics(&self, metrics: PlatformMetrics) {
156        let mut state = self.state.borrow_mut();
157        state.metrics = metrics;
158        let surfaces: Vec<NodeId> =
159            state.nodes.iter().filter(|(_, n)| n.surface.is_some()).map(|(id, _)| *id).collect();
160        for surface in surfaces {
161            state.size_surface(surface);
162        }
163        let windows: Vec<NodeId> =
164            state.nodes.iter().filter(|(_, n)| n.kind == WidgetKind::Window).map(|(id, _)| *id).collect();
165        for window in windows {
166            state.emit(window, UiEvent::MetricsChanged);
167        }
168    }
169
170    pub fn focused(&self) -> Option<NodeId> {
171        self.state.borrow().focused
172    }
173
174    /// Simulates the user switching to another app: the window's GPU
175    /// surfaces lose their pointer lock and keyboard grab, as every
176    /// platform ends them.
177    pub fn deactivate(&self, window: NodeId) {
178        let mut state = self.state.borrow_mut();
179        let surfaces: Vec<NodeId> = state
180            .nodes
181            .iter()
182            .filter(|(id, n)| n.kind == WidgetKind::GpuSurface && state.window_of(**id) == Some(window))
183            .map(|(id, _)| *id)
184            .collect();
185        for surface in surfaces {
186            state.end_lock(surface, Prop::PointerLock(false));
187            state.end_lock(surface, Prop::KeyboardGrab(false));
188        }
189    }
190
191    /// Simulates the mouse moving while a surface holds the pointer: its
192    /// move with the host's acceleration, and before it. Headless has no
193    /// acceleration, and one count to a point.
194    pub fn move_locked_pointer(&self, surface: NodeId, dx: f32, dy: f32) {
195        let state = self.state.borrow();
196        if state.nodes.get(&surface).and_then(|n| find_prop!(n.props, PointerLock)) != Some(true) {
197            return;
198        }
199        state.emit(surface, UiEvent::SurfaceInput(SurfaceInput::Motion { dx, dy }));
200        state.emit(surface, UiEvent::SurfaceInput(SurfaceInput::RawMotion { dx, dy }));
201    }
202
203    pub fn a11y(&self, id: NodeId) -> Option<A11yProps> {
204        self.state.borrow().nodes.get(&id).map(|n| n.a11y.clone())
205    }
206
207    /// Number of live native nodes: a leak detector for tests.
208    pub fn node_count(&self) -> usize {
209        self.state.borrow().nodes.len()
210    }
211}
212
213impl mitsuami_core::TestHooks for HeadlessHandle {
214    fn name(&self) -> &'static str {
215        "headless"
216    }
217
218    fn resize_window(&self, window: NodeId, size: Size) {
219        HeadlessHandle::resize_window(self, window, size);
220    }
221
222    fn close_window(&self, window: NodeId) {
223        self.state.borrow_mut().emit(window, UiEvent::WindowCloseRequested);
224    }
225
226    fn take_command_log(&self) -> Vec<Command> {
227        HeadlessHandle::take_command_log(self)
228    }
229
230    fn node_count(&self) -> usize {
231        HeadlessHandle::node_count(self)
232    }
233
234    /// The topmost node with a frame there (later children are over
235    /// earlier ones), past containers clicks pass through.
236    fn hit(&self, window: NodeId, at: Point) -> Result<Option<NodeId>, ActionError> {
237        fn reach(state: &State, id: NodeId, at: Point) -> Option<NodeId> {
238            let node = &state.nodes[&id];
239            // A scroll view's content is placed from its viewport's top-left.
240            let inside = match node.kind {
241                WidgetKind::ScrollView => Point::new(at.x + node.scroll_offset.x, at.y + node.scroll_offset.y),
242                _ => at,
243            };
244            for child in node.children.iter().rev() {
245                let c = &state.nodes[child];
246                let f = c.frame;
247                if f.width() <= 0.0 || f.height() <= 0.0 || find_prop!(c.props, ClickThrough) == Some(true) {
248                    continue;
249                }
250                if inside.x >= f.x() && inside.x < f.max_x() && inside.y >= f.y() && inside.y < f.max_y() {
251                    let local = Point::new(inside.x - f.x(), inside.y - f.y());
252                    return reach(state, *child, local).or(Some(*child));
253                }
254            }
255            None
256        }
257        let state = self.state.borrow();
258        if !state.nodes.contains_key(&window) {
259            return Err(ActionError::UnknownNode);
260        }
261        Ok(reach(&state, window, at))
262    }
263
264    /// The selected rows' files if the row is selected, else its own, as
265    /// platforms' lists drag.
266    fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>> {
267        let state = self.state.borrow();
268        let host = state.nodes.get(&node)?;
269        let row = find_prop!(host.props, Row).or_else(|| find_prop!(host.props, Cell).map(|cell| cell.row))?;
270        let list = &state.nodes[&host.parent?];
271        let files = find_prop!(list.props, RowFiles)?;
272        let selected = find_prop!(list.props, Selected).unwrap_or_default();
273        let rows = if selected.contains(&row) { selected } else { vec![row] };
274        let dragged: Vec<_> =
275            rows.iter().filter_map(|r| files.iter().find(|(f, _)| f == r).map(|(_, path)| path.clone())).collect();
276        (!dragged.is_empty()).then_some(dragged)
277    }
278
279    /// All of it, as every platform has a place for some of it; the icon's
280    /// size from its PNG header.
281    fn app_info(&self, _window: NodeId) -> NativeAppInfo {
282        let app = self.state.borrow().app.clone();
283        let icon = app.icon.and_then(|icon| icon.read()).and_then(|bytes| png_size(&bytes));
284        NativeAppInfo {
285            id: app.id,
286            name: app.name,
287            icon: icon.map(|size| NativeIcon::Image { width: size.width as u32, height: size.height as u32 }),
288        }
289    }
290}