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    /// Tables only: the widths their columns give their cells, as reported.
60    column_widths: Vec<f32>,
61    /// GPU surfaces only: what the app got.
62    surface: Option<SurfaceHandle>,
63    /// Windows in full screen only: their size before, to go back to.
64    windowed: Option<Size>,
65    /// Maximized windows only: their size before, to go back to.
66    restored: Option<Size>,
67}
68
69/// A user who reads US English, and numbers and dates written as
70/// mitsuami writes them (US English, dates in UTC), whatever the machine's
71/// settings: tests ask for other languages with `Ui::set_languages`.
72struct HeadlessLocale;
73
74impl PlatformLocale for HeadlessLocale {
75    fn languages(&self) -> Vec<String> {
76        vec!["en-US".into()]
77    }
78
79    fn format_number(&self, _: f64, _: &NumberFormat) -> Option<String> {
80        None
81    }
82
83    fn format_date_time(&self, _: std::time::SystemTime, _: &DateTimeFormat) -> Option<String> {
84        None
85    }
86}
87
88/// A `GpuSurface` with nothing to present to: the app gets it, and its
89/// sizes, but no window handle.
90struct HeadlessSurface;
91
92// SAFETY: it returns no handles.
93unsafe impl NativeSurface for HeadlessSurface {
94    fn window_handle(&self) -> Result<RawWindowHandle, HandleError> {
95        Err(HandleError::NotSupported)
96    }
97
98    fn display_handle(&self) -> Result<RawDisplayHandle, HandleError> {
99        Err(HandleError::NotSupported)
100    }
101}
102
103/// Where a list placed a row.
104#[derive(Clone, Copy)]
105struct Placed {
106    key: RowKey,
107    top: f32,
108    height: f32,
109}
110
111struct State {
112    nodes: BTreeMap<NodeId, HeadlessNode>,
113    events: Option<EventSink>,
114    metrics: PlatformMetrics,
115    /// Whether commands go into `log`: only once a test asks for them
116    /// (`HeadlessHandle::record_commands`), so it doesn't grow without end.
117    recording: bool,
118    log: Vec<Command>,
119    focused: Option<NodeId>,
120    /// Whether an input method's composition is going on, on the focused
121    /// surface (`SyntheticInput::Compose`).
122    composing: bool,
123    /// The focused text field's selection, in characters; `None` is the
124    /// caret at the end, where focusing puts it.
125    selection: Option<std::ops::Range<usize>>,
126    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
127    app: AppInfo,
128    /// The node files being dragged are over, if it takes them.
129    drop_hover: Option<NodeId>,
130    /// The app's language and whether it's right to left, as the core set it.
131    locale: Option<(LanguageIdentifier, bool)>,
132}
133
134/// The backend. Hand it to [`Ui::new`](mitsuami_core::Ui::new); keep a
135/// [`HeadlessHandle`] to inspect it afterwards.
136pub struct HeadlessBackend {
137    state: Rc<RefCell<State>>,
138}
139
140/// Shared access to a [`HeadlessBackend`] after it was moved into a `Ui`.
141#[derive(Clone)]
142pub struct HeadlessHandle {
143    state: Rc<RefCell<State>>,
144}
145
146impl Default for HeadlessBackend {
147    fn default() -> Self {
148        HeadlessBackend::new()
149    }
150}
151
152impl HeadlessBackend {
153    pub fn new() -> HeadlessBackend {
154        HeadlessBackend {
155            state: Rc::new(RefCell::new(State {
156                nodes: BTreeMap::new(),
157                events: None,
158                metrics: metrics(),
159                recording: false,
160                log: Vec::new(),
161                focused: None,
162                composing: false,
163                selection: None,
164                drop_hover: None,
165                focus_orders: BTreeMap::new(),
166                app: AppInfo::default(),
167                locale: None,
168            })),
169        }
170    }
171
172    pub fn handle(&self) -> HeadlessHandle {
173        HeadlessHandle { state: self.state.clone() }
174    }
175}
176
177impl Backend for HeadlessBackend {
178    fn init(&mut self, events: EventSink) {
179        self.state.borrow_mut().events = Some(events);
180    }
181
182    fn metrics(&self) -> PlatformMetrics {
183        self.state.borrow().metrics.clone()
184    }
185
186    fn apply(&mut self, batch: &[Command]) {
187        self.apply_batch(batch);
188    }
189
190    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
191        self.measure_node(id, request)
192    }
193
194    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
195        self.perform_action(id, action)
196    }
197
198    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
199        self.synthesize_input(id, input)
200    }
201
202    fn native_state(&self, id: NodeId) -> Option<NativeState> {
203        self.read_native_state(id)
204    }
205
206    fn locale(&self) -> Rc<dyn PlatformLocale> {
207        Rc::new(HeadlessLocale)
208    }
209
210    fn set_locale(&mut self, language: &LanguageIdentifier, right_to_left: bool) {
211        self.state.borrow_mut().locale = Some((language.clone(), right_to_left));
212    }
213
214    fn capture(&mut self, _id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
215        reply(Err(CaptureError::Unsupported));
216    }
217
218    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
219        Box::new(FakeServices::default())
220    }
221
222    fn set_app_info(&mut self, info: &AppInfo) {
223        self.state.borrow_mut().app = info.clone();
224    }
225}