Skip to main content

mitsuami_headless/
lib.rs

1//! An in-memory backend for integration tests.
2//!
3//! It keeps a mirror of the native tree like a real backend would, validates
4//! every command against the protocol (panicking on violations), and measures
5//! text with fixed, platform-independent metrics so layouts are deterministic:
6//! each character is `0.5em` wide and lines are `1.25em` tall.
7
8mod apply;
9mod handle;
10mod input;
11mod lists;
12mod measure;
13mod metrics;
14mod native_state;
15mod perform;
16mod services;
17mod state;
18mod windows;
19
20pub use metrics::metrics;
21pub use services::{
22    FakeServices, FakeServicesHandle, Pending, PendingAlert, PendingLaunch, PendingOpen, PendingSave, PendingTrash,
23};
24
25use std::cell::RefCell;
26use std::collections::{BTreeMap, BTreeSet};
27use std::rc::Rc;
28
29use mitsuami_core::a11y::{A11yAction, A11yProps, ActionError};
30use mitsuami_core::backend::{
31    Backend, CaptureError, EventSink, Image, MeasureRequest, NativeState, PlatformMetrics, SyntheticInput,
32};
33use mitsuami_core::l10n::{DateTimeFormat, LanguageIdentifier, NumberFormat, PlatformLocale};
34use mitsuami_core::raw_window_handle::{HandleError, RawDisplayHandle, RawWindowHandle};
35use mitsuami_core::{
36    AppInfo, Command, Insets, NativeSurface, NodeId, Point, Prop, Rect, RowKey, Size, SurfaceHandle, WidgetKind,
37};
38
39struct HeadlessNode {
40    kind: WidgetKind,
41    props: Vec<Prop>,
42    a11y: A11yProps,
43    frame: Rect,
44    parent: Option<NodeId>,
45    children: Vec<NodeId>,
46    scroll_offset: Point,
47    /// Scroll views only: the room their scroll bars take, as a test set it
48    /// (`HeadlessHandle::set_viewport_insets`). None otherwise: headless
49    /// scroll bars overlay the content.
50    viewport_insets: Insets,
51    /// Lists only: the rows realised, as reported.
52    shown: BTreeSet<RowKey>,
53    /// Lists only: where the rows are, and each row's index in it.
54    placed: Vec<Placed>,
55    placed_index: std::collections::HashMap<RowKey, usize>,
56    /// Lists only: the heights of the rows measured so far, kept when
57    /// they're let go, as native lists keep them.
58    heights: BTreeMap<RowKey, f32>,
59    /// Lists only: how high their rows and header are, as last placed.
60    natural_height: f32,
61    /// Tables only: their columns' widths, the room between cells in.
62    column_widths: Vec<f32>,
63    /// Tables only: their rows' heights without their cells that fill
64    /// them, as reported.
65    bare_heights: BTreeMap<RowKey, f32>,
66    /// GPU surfaces only: what the app got.
67    surface: Option<SurfaceHandle>,
68    /// Windows in full screen only: their size before, to go back to.
69    windowed: Option<Size>,
70    /// Maximized windows only: their size before, to go back to.
71    restored: Option<Size>,
72    /// Windows only: their top-left corner on the screen, title bar
73    /// included; `None` until placed, at the end of the batch that made
74    /// them.
75    position: Option<Point>,
76    /// Windows only: centred as it's placed (`CentreWindow` before it was).
77    centre_on_place: bool,
78}
79
80/// A user who reads US English, and numbers and dates written as
81/// mitsuami writes them (US English, dates in UTC), whatever the machine's
82/// settings: tests ask for other languages with `Ui::set_languages`.
83struct HeadlessLocale;
84
85impl PlatformLocale for HeadlessLocale {
86    fn languages(&self) -> Vec<String> {
87        vec!["en-US".into()]
88    }
89
90    fn format_number(&self, _: f64, _: &NumberFormat) -> Option<String> {
91        None
92    }
93
94    fn format_date_time(&self, _: std::time::SystemTime, _: &DateTimeFormat) -> Option<String> {
95        None
96    }
97}
98
99/// A `GpuSurface` with nothing to present to: the app gets it, and its
100/// sizes, but no window handle.
101struct HeadlessSurface;
102
103// SAFETY: it returns no handles.
104unsafe impl NativeSurface for HeadlessSurface {
105    fn window_handle(&self) -> Result<RawWindowHandle, HandleError> {
106        Err(HandleError::NotSupported)
107    }
108
109    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError> {
110        Err(HandleError::NotSupported)
111    }
112}
113
114/// Where a list placed a row.
115#[derive(Clone, Copy)]
116struct Placed {
117    key: RowKey,
118    top: f32,
119    height: f32,
120}
121
122struct State {
123    nodes: BTreeMap<NodeId, HeadlessNode>,
124    events: Option<EventSink>,
125    metrics: PlatformMetrics,
126    /// Whether commands go into `log`: only once a test asks for them
127    /// (`HeadlessHandle::record_commands`), so it doesn't grow without end.
128    recording: bool,
129    log: Vec<Command>,
130    focused: Option<NodeId>,
131    /// The window taking keys, as `Present` and `set_window_active` left it.
132    active_window: Option<NodeId>,
133    /// Whether an input method's composition is going on, on the focused
134    /// surface (`SyntheticInput::Compose`).
135    composing: bool,
136    /// The focused text field's selection, in characters; `None` is the
137    /// caret at the end, where focusing puts it.
138    selection: Option<std::ops::Range<usize>>,
139    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
140    app: AppInfo,
141    /// The node files being dragged are over, if it takes them.
142    drop_hover: Option<NodeId>,
143    /// The app's language and whether it's right to left, as the core set it.
144    locale: Option<(LanguageIdentifier, bool)>,
145}
146
147/// The backend. Hand it to [`Ui::new`](mitsuami_core::Ui::new); keep a
148/// [`HeadlessHandle`] to inspect it afterwards.
149pub struct HeadlessBackend {
150    state: Rc<RefCell<State>>,
151}
152
153/// Shared access to a [`HeadlessBackend`] after it was moved into a `Ui`.
154#[derive(Clone)]
155pub struct HeadlessHandle {
156    state: Rc<RefCell<State>>,
157}
158
159impl Default for HeadlessBackend {
160    fn default() -> Self {
161        HeadlessBackend::new()
162    }
163}
164
165impl HeadlessBackend {
166    pub fn new() -> HeadlessBackend {
167        HeadlessBackend {
168            state: Rc::new(RefCell::new(State {
169                nodes: BTreeMap::new(),
170                events: None,
171                metrics: metrics(),
172                recording: false,
173                log: Vec::new(),
174                focused: None,
175                active_window: None,
176                composing: false,
177                selection: None,
178                drop_hover: None,
179                focus_orders: BTreeMap::new(),
180                app: AppInfo::default(),
181                locale: None,
182            })),
183        }
184    }
185
186    pub fn handle(&self) -> HeadlessHandle {
187        HeadlessHandle { state: self.state.clone() }
188    }
189}
190
191impl Backend for HeadlessBackend {
192    fn init(&mut self, events: EventSink) {
193        self.state.borrow_mut().events = Some(events);
194    }
195
196    fn metrics(&self) -> PlatformMetrics {
197        self.state.borrow().metrics.clone()
198    }
199
200    fn apply(&mut self, batch: &[Command]) {
201        self.apply_batch(batch);
202    }
203
204    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
205        self.measure_node(id, request)
206    }
207
208    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
209        self.perform_action(id, action)
210    }
211
212    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
213        self.synthesize_input(id, input)
214    }
215
216    fn native_state(&self, id: NodeId) -> Option<NativeState> {
217        self.read_native_state(id)
218    }
219
220    fn work_area(&self, _window: Option<NodeId>) -> Option<Size> {
221        Some(metrics::WORK_AREA)
222    }
223
224    fn locale(&self) -> Rc<dyn PlatformLocale> {
225        Rc::new(HeadlessLocale)
226    }
227
228    fn set_locale(&mut self, language: &LanguageIdentifier, right_to_left: bool) {
229        self.state.borrow_mut().locale = Some((language.clone(), right_to_left));
230    }
231
232    fn capture(&mut self, _id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
233        reply(Err(CaptureError::Unsupported));
234    }
235
236    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
237        Box::new(FakeServices::default())
238    }
239
240    fn set_app_info(&mut self, info: &AppInfo) {
241        self.state.borrow_mut().app = info.clone();
242    }
243}