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