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