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