mitsuami_core/backend.rs
1//! The contract every platform backend implements.
2
3use std::cell::RefCell;
4use std::collections::VecDeque;
5use std::rc::Rc;
6
7use crate::a11y::{A11yAction, ActionError};
8use crate::app_info::{AppInfo, NativeAppInfo};
9use crate::command::{Command, UiEvent};
10use crate::geometry::{Insets, Point, Rect, Size};
11use crate::services::Shortcut;
12use crate::units::SpacingScale;
13use crate::widget::{NodeId, Prop, TextStyle, WidgetKind};
14
15/// Space available on one axis while measuring.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub enum AvailableSpace {
18 Definite(f32),
19 MinContent,
20 MaxContent,
21}
22
23/// What the layout engine asks when it measures a leaf widget.
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct MeasureRequest {
26 /// Sizes that are already fixed; measure the other axis given these.
27 pub known_width: Option<f32>,
28 pub known_height: Option<f32>,
29 pub available_width: AvailableSpace,
30 pub available_height: AvailableSpace,
31}
32
33/// Platform facts the core needs for unit resolution and defaults.
34#[derive(Clone, Debug, PartialEq)]
35pub struct PlatformMetrics {
36 pub scale_factor: f32,
37 pub spacing: SpacingScale,
38 pub font_sizes: FontSizes,
39 pub dark_mode: bool,
40 pub high_contrast: bool,
41 pub reduced_motion: bool,
42 /// Where a `Tabs` shows its pages: this far in from its edges, past
43 /// its tab strip and border.
44 pub tab_insets: Insets,
45 /// Where a `Group` shows its content: this far in from its edges,
46 /// past its border and the platform's margins; `titled_group_insets`
47 /// with a heading, which is inside the box on some platforms and above
48 /// it on others.
49 pub group_insets: Insets,
50 pub titled_group_insets: Insets,
51 /// How thick a `Split`'s divider is, between its panes.
52 pub split_divider: f32,
53 /// Where a `TextArea`'s first line starts: this far in from its edges,
54 /// past its border and the text's own margins. What a hint laid over
55 /// it lines up with.
56 pub text_area_insets: Insets,
57}
58
59/// Light or dark. Backends can force one (tests do, so captures don't
60/// depend on the system setting).
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62pub enum Appearance {
63 Light,
64 Dark,
65}
66
67#[derive(Clone, Debug, PartialEq)]
68pub struct FontSizes {
69 pub large_title: f32,
70 pub title: f32,
71 pub headline: f32,
72 pub body: f32,
73 pub callout: f32,
74 pub caption: f32,
75 pub monospace: f32,
76}
77
78impl FontSizes {
79 pub fn get(&self, style: TextStyle) -> f32 {
80 match style {
81 TextStyle::LargeTitle => self.large_title,
82 TextStyle::Title => self.title,
83 TextStyle::Headline => self.headline,
84 TextStyle::Body => self.body,
85 TextStyle::Callout => self.callout,
86 TextStyle::Caption => self.caption,
87 TextStyle::Monospace => self.monospace,
88 }
89 }
90}
91
92/// Raw input for [`Backend::synthesize`].
93#[derive(Clone, Debug, PartialEq)]
94pub enum SyntheticInput {
95 /// A key pressed and released, on its own.
96 Key(Key),
97 /// A key pressed and released with modifiers held: what a node's keys
98 /// (`Prop::Keys`) take, where the focused control doesn't use it.
99 Shortcut(Shortcut),
100 /// An input method commits this text on a `GpuSurface` that takes
101 /// text, as a composition ends.
102 Text(String),
103 /// An input method's composition on a `GpuSurface` that takes text
104 /// shows this text so far (empty: it ends without committing).
105 Compose(String),
106 /// Scroll-wheel / trackpad scroll over a `ScrollView` or `List`, in logical units
107 /// (positive = towards the end of the content).
108 Scroll { dx: f32, dy: f32 },
109 /// A primary-button click (down, then up) at this point, in the node's
110 /// coordinates. Backends support it on drawn custom widgets, whose
111 /// pointer handling is ours.
112 Click(Point),
113 /// The pointer comes over a node with a `Prop::Hover`, through the
114 /// platform's own hover handling where it can be reached.
115 PointerEnter,
116 /// The pointer leaves a node with a `Prop::Hover`.
117 PointerLeave,
118 /// A double click on a node with a `Prop::DoubleClick`, through the
119 /// platform's own handling where it can be reached.
120 DoubleClick,
121 /// A click on a node with a `Prop::Click`, as for `DoubleClick`.
122 SingleClick,
123 /// Files dragged from the file manager, over a node with a
124 /// `Prop::FileDrop`: what the platform's drag handling does when they
125 /// enter it, through the same path.
126 DragFiles(Vec<std::path::PathBuf>),
127 /// The drag leaves the node without dropping.
128 DragLeave,
129 /// The files are dropped on the node (having entered it first, as a
130 /// real drop does).
131 DropFiles(Vec<std::path::PathBuf>),
132 /// Rows of a list with `Prop::RowMoves` dragged within it and dropped
133 /// where the platform proposed, through the list's own drop handling.
134 MoveRows { rows: Vec<crate::RowKey>, to: crate::RowDrop<crate::RowKey> },
135}
136
137/// A key, by what it types or does: a character (`Char(' ')` is the
138/// space bar), or a key that types none. For shortcuts, key bindings and
139/// synthesized input.
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
141pub enum Key {
142 Char(char),
143 Enter,
144 Escape,
145 Tab,
146 /// The key that deletes backwards: Delete (⌫) on Apple keyboards.
147 Backspace,
148 /// The key that deletes forwards: ⌦ on Apple keyboards.
149 Delete,
150 Up,
151 Down,
152 Left,
153 Right,
154 Home,
155 End,
156 PageUp,
157 PageDown,
158 /// A function key, from F1.
159 F(u8),
160}
161
162impl From<char> for Key {
163 fn from(c: char) -> Key {
164 Key::Char(c)
165 }
166}
167
168/// What a native widget actually shows, read back from the platform.
169/// Tests compare this with the core's state to catch backend desyncs.
170#[derive(Clone, Debug, PartialEq)]
171pub struct NativeState {
172 pub kind: WidgetKind,
173 pub props: Vec<Prop>,
174 pub frame: Rect,
175 pub parent: Option<NodeId>,
176 pub children: Vec<NodeId>,
177 /// Has keyboard focus (for text fields: is being edited).
178 pub focused: bool,
179 /// `ScrollView`s, `List`s, `Table`s and `TextArea`s only: the current
180 /// scroll offset (a text area's, in its own scroll view).
181 pub scroll_offset: Option<Point>,
182 /// `ScrollView`s only: where the viewport is in the frame, inside the
183 /// room scroll bars that aren't overlaid take (`UiEvent::ViewportInsets`).
184 pub viewport_insets: Option<Insets>,
185 /// A focused text field's or text area's selection, in characters (an
186 /// empty one is the caret); `None` for anything else.
187 pub selection: Option<std::ops::Range<usize>>,
188}
189
190/// An RGBA8 screenshot in physical pixels.
191#[derive(Clone, Debug, PartialEq)]
192pub struct Image {
193 pub width: u32,
194 pub height: u32,
195 pub scale_factor: f32,
196 pub rgba: Vec<u8>,
197}
198
199#[derive(Clone, Debug, PartialEq, Eq)]
200pub enum CaptureError {
201 UnknownNode,
202 Unsupported,
203 Failed(String),
204}
205
206/// How backends report native events. Events are queued; the [`Ui`](crate::Ui)
207/// drains them when the backend calls [`Ui::process_events`](crate::Ui::process_events)
208/// (or right after a [`Backend::perform`]).
209#[derive(Clone, Default)]
210pub struct EventSink {
211 queue: Rc<RefCell<VecDeque<(NodeId, UiEvent)>>>,
212}
213
214impl EventSink {
215 pub fn emit(&self, id: NodeId, event: UiEvent) {
216 self.queue.borrow_mut().push_back((id, event));
217 }
218
219 pub(crate) fn pop(&self) -> Option<(NodeId, UiEvent)> {
220 self.queue.borrow_mut().pop_front()
221 }
222
223 pub fn is_empty(&self) -> bool {
224 self.queue.borrow().is_empty()
225 }
226}
227
228/// What the test harness (`mitsuami-test`) needs from a backend beyond the
229/// [`Backend`] contract. Implemented by each backend's shareable handle.
230pub trait TestHooks {
231 /// Short name used in snapshot and visual baseline paths: `"appkit"`,
232 /// `"gtk"`, `"winui"`, `"kirigami"`.
233 fn name(&self) -> &'static str;
234 /// Resizes a window's content area the way the user would, so the
235 /// platform reports it back as `WindowResized`.
236 fn resize_window(&self, window: NodeId, size: Size);
237 /// Clicks the window's close button, the way the user would, so the
238 /// platform reports `WindowCloseRequested`. Whether it closes is the
239 /// app's call.
240 fn close_window(&self, window: NodeId);
241 /// Commands applied since the last call (record them when asked to).
242 fn take_command_log(&self) -> Vec<Command>;
243 /// Live native nodes, as a leak detector.
244 fn node_count(&self) -> usize;
245 /// What this window shows of the app's id, name and icon (see
246 /// [`AppInfo`]), read from the platform.
247 fn app_info(&self, window: NodeId) -> NativeAppInfo;
248 /// The files dragging this row out of its `List` or `Table` carries
249 /// (`Prop::RowFiles`), as the platform's drag source gives them: the
250 /// selected rows' when the row is selected, else its own. `node` is the
251 /// row's host (a table's: any of its cells'). `None` if it doesn't drag.
252 /// Nothing here can start a real drag; this goes through the backend's
253 /// own drag handling up to where the platform takes the files.
254 fn dragged_files(&self, node: NodeId) -> Option<Vec<std::path::PathBuf>>;
255 /// The node a click at `at`, in a window's content, reaches as the
256 /// platform hit-tests it: the topmost there, past containers clicks
257 /// pass through (`Prop::ClickThrough`). `None` if it reaches none;
258 /// `Unsupported` where the backend can't tell yet.
259 fn hit(&self, _window: NodeId, _at: Point) -> Result<Option<NodeId>, ActionError> {
260 Err(ActionError::Unsupported)
261 }
262 /// Called after every settle: lets the platform catch up on work it
263 /// does asynchronously (showing windows, allocating, delivering queued
264 /// notifications) without waiting. Every backend has some: AppKit lays
265 /// out tables and toolbars, which make their views in a layout pass.
266 fn settle(&self) {}
267}
268
269pub trait Backend {
270 /// Called once when the backend is attached to a [`Ui`](crate::Ui).
271 fn init(&mut self, events: EventSink);
272
273 fn metrics(&self) -> PlatformMetrics;
274
275 /// Where this `Group` puts its content, if not where the metrics'
276 /// `group_insets` or `titled_group_insets` say: a tweak can move its
277 /// heading or change its border. Asked when the group is measured.
278 fn group_insets(&self, _id: NodeId) -> Option<Insets> {
279 None
280 }
281
282 /// Where this `Tabs` puts its pages, if not where the metrics'
283 /// `tab_insets` say: its style can give it another strip. Asked when
284 /// its strip is measured.
285 fn tab_insets(&self, _id: NodeId) -> Option<Insets> {
286 None
287 }
288
289 /// Applies a batch of commands to the native tree.
290 fn apply(&mut self, batch: &[Command]);
291
292 /// Intrinsic size of a leaf widget. Called synchronously during layout,
293 /// after all commands of the current batch have been applied.
294 fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size;
295
296 /// Performs an accessibility action on the native control, as assistive
297 /// technology would. Resulting events go through the [`EventSink`].
298 fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError>;
299
300 /// Synthesizes raw user input on a native control, as close to real input
301 /// as the platform allows. Used by end-to-end tests.
302 fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError>;
303
304 fn native_state(&self, id: NodeId) -> Option<NativeState>;
305
306 /// Offscreen screenshot of a window or node. Async because some
307 /// platforms render asynchronously (WinUI's `RenderTargetBitmap`);
308 /// reply whenever it's ready, right away if possible.
309 fn capture(&mut self, id: NodeId, reply: crate::services::Reply<Result<Image, CaptureError>>);
310
311 /// The platform's clipboard, dialogs and menus. Called once, when the
312 /// backend is attached; tests may replace the result.
313 fn services(&self) -> Box<dyn crate::services::Services>;
314
315 /// The app's id, name and icon, set before the app's first window, and
316 /// perhaps again later (tests). Apply what the platform has a place
317 /// for, to the windows there are and those to come.
318 fn set_app_info(&mut self, info: &AppInfo);
319
320 /// The user's languages, and how the user's region writes numbers
321 /// and dates. Called once, when the backend is attached.
322 fn locale(&self) -> std::rc::Rc<dyn crate::l10n::PlatformLocale>;
323
324 /// The app's language, which the core chose from the user's, and
325 /// whether it's written right to left: set before the app's first
326 /// window, and again when the app changes it. Make the toolkit's own
327 /// chrome follow it where the platform lets an app choose (the
328 /// direction of title bars, menus and dialogs). Native widgets get
329 /// their direction as `Prop::LayoutDirection`.
330 fn set_locale(&mut self, language: &crate::l10n::LanguageIdentifier, right_to_left: bool);
331}