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    /// Whether an input method's composition is going on, on the focused
126    /// surface (`SyntheticInput::Compose`).
127    composing: bool,
128    /// The focused text field's selection, in characters; `None` is the
129    /// caret at the end, where focusing puts it.
130    selection: Option<std::ops::Range<usize>>,
131    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
132    app: AppInfo,
133    /// The node files being dragged are over, if it takes them.
134    drop_hover: Option<NodeId>,
135    /// The app's language and whether it's right to left, as the core set it.
136    locale: Option<(LanguageIdentifier, bool)>,
137}
138
139/// The backend. Hand it to [`Ui::new`](mitsuami_core::Ui::new); keep a
140/// [`HeadlessHandle`] to inspect it afterwards.
141pub struct HeadlessBackend {
142    state: Rc<RefCell<State>>,
143}
144
145/// Shared access to a [`HeadlessBackend`] after it was moved into a `Ui`.
146#[derive(Clone)]
147pub struct HeadlessHandle {
148    state: Rc<RefCell<State>>,
149}
150
151impl Default for HeadlessBackend {
152    fn default() -> Self {
153        HeadlessBackend::new()
154    }
155}
156
157impl HeadlessBackend {
158    pub fn new() -> HeadlessBackend {
159        HeadlessBackend {
160            state: Rc::new(RefCell::new(State {
161                nodes: BTreeMap::new(),
162                events: None,
163                metrics: metrics(),
164                recording: false,
165                log: Vec::new(),
166                focused: None,
167                composing: false,
168                selection: None,
169                drop_hover: None,
170                focus_orders: BTreeMap::new(),
171                app: AppInfo::default(),
172                locale: None,
173            })),
174        }
175    }
176
177    pub fn handle(&self) -> HeadlessHandle {
178        HeadlessHandle { state: self.state.clone() }
179    }
180}
181
182impl Backend for HeadlessBackend {
183    fn init(&mut self, events: EventSink) {
184        self.state.borrow_mut().events = Some(events);
185    }
186
187    fn metrics(&self) -> PlatformMetrics {
188        self.state.borrow().metrics.clone()
189    }
190
191    fn apply(&mut self, batch: &[Command]) {
192        self.apply_batch(batch);
193    }
194
195    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size {
196        self.measure_node(id, request)
197    }
198
199    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
200        self.perform_action(id, action)
201    }
202
203    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError> {
204        self.synthesize_input(id, input)
205    }
206
207    fn native_state(&self, id: NodeId) -> Option<NativeState> {
208        self.read_native_state(id)
209    }
210
211    fn locale(&self) -> Rc<dyn PlatformLocale> {
212        Rc::new(HeadlessLocale)
213    }
214
215    fn set_locale(&mut self, language: &LanguageIdentifier, right_to_left: bool) {
216        self.state.borrow_mut().locale = Some((language.clone(), right_to_left));
217    }
218
219    fn capture(&mut self, _id: NodeId, reply: mitsuami_core::services::Reply<Result<Image, CaptureError>>) {
220        reply(Err(CaptureError::Unsupported));
221    }
222
223    fn services(&self) -> Box<dyn mitsuami_core::services::Services> {
224        Box::new(FakeServices::default())
225    }
226
227    fn set_app_info(&mut self, info: &AppInfo) {
228        self.state.borrow_mut().app = info.clone();
229    }
230}