Skip to main content

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