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