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::command::{Command, UiEvent};
9use crate::geometry::{Point, Rect, Size};
10use crate::units::SpacingScale;
11use crate::widget::{NodeId, Prop, TextStyle, WidgetKind};
12
13/// Space available on one axis while measuring.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub enum AvailableSpace {
16    Definite(f32),
17    MinContent,
18    MaxContent,
19}
20
21/// What the layout engine asks when it measures a leaf widget.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct MeasureRequest {
24    /// Sizes that are already fixed; measure the other axis given these.
25    pub known_width: Option<f32>,
26    pub known_height: Option<f32>,
27    pub available_width: AvailableSpace,
28    pub available_height: AvailableSpace,
29}
30
31/// Platform facts the core needs for unit resolution and defaults.
32#[derive(Clone, Debug, PartialEq)]
33pub struct PlatformMetrics {
34    pub scale_factor: f32,
35    pub spacing: SpacingScale,
36    pub font_sizes: FontSizes,
37    pub dark_mode: bool,
38    pub high_contrast: bool,
39    pub reduced_motion: bool,
40}
41
42#[derive(Clone, Debug, PartialEq)]
43pub struct FontSizes {
44    pub large_title: f32,
45    pub title: f32,
46    pub headline: f32,
47    pub body: f32,
48    pub callout: f32,
49    pub caption: f32,
50    pub monospace: f32,
51}
52
53impl FontSizes {
54    pub fn get(&self, style: TextStyle) -> f32 {
55        match style {
56            TextStyle::LargeTitle => self.large_title,
57            TextStyle::Title => self.title,
58            TextStyle::Headline => self.headline,
59            TextStyle::Body => self.body,
60            TextStyle::Callout => self.callout,
61            TextStyle::Caption => self.caption,
62            TextStyle::Monospace => self.monospace,
63        }
64    }
65}
66
67/// Raw input for [`Backend::synthesize`].
68#[derive(Clone, Debug, PartialEq)]
69pub enum SyntheticInput {
70    Key(Key),
71    /// Scroll-wheel / trackpad scroll over a `ScrollView`, in logical units
72    /// (positive = towards the end of the content).
73    Scroll {
74        dx: f32,
75        dy: f32,
76    },
77    /// A primary-button click (down, then up) at this point, in the node's
78    /// coordinates. Backends support it on drawn custom widgets, whose
79    /// pointer handling is ours.
80    Click(Point),
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq)]
84pub enum Key {
85    Char(char),
86    Enter,
87    Escape,
88    Tab,
89    Backspace,
90}
91
92/// What a native widget actually shows, read back from the platform.
93/// Tests compare this with the core's state to catch backend desyncs.
94#[derive(Clone, Debug, PartialEq)]
95pub struct NativeState {
96    pub kind: WidgetKind,
97    pub props: Vec<Prop>,
98    pub frame: Rect,
99    pub parent: Option<NodeId>,
100    pub children: Vec<NodeId>,
101    /// Has keyboard focus (for text fields: is being edited).
102    pub focused: bool,
103    /// `ScrollView`s only: the current scroll offset.
104    pub scroll_offset: Option<Point>,
105}
106
107/// An RGBA8 screenshot in physical pixels.
108#[derive(Clone, Debug, PartialEq)]
109pub struct Image {
110    pub width: u32,
111    pub height: u32,
112    pub scale_factor: f32,
113    pub rgba: Vec<u8>,
114}
115
116#[derive(Clone, Debug, PartialEq, Eq)]
117pub enum CaptureError {
118    UnknownNode,
119    Unsupported,
120    Failed(String),
121}
122
123/// How backends report native events. Events are queued; the [`Ui`](crate::Ui)
124/// drains them when the backend calls [`Ui::process_events`](crate::Ui::process_events)
125/// (or right after a [`Backend::perform`]).
126#[derive(Clone, Default)]
127pub struct EventSink {
128    queue: Rc<RefCell<VecDeque<(NodeId, UiEvent)>>>,
129}
130
131impl EventSink {
132    pub fn emit(&self, id: NodeId, event: UiEvent) {
133        self.queue.borrow_mut().push_back((id, event));
134    }
135
136    pub(crate) fn pop(&self) -> Option<(NodeId, UiEvent)> {
137        self.queue.borrow_mut().pop_front()
138    }
139
140    pub fn is_empty(&self) -> bool {
141        self.queue.borrow().is_empty()
142    }
143}
144
145/// What the test harness (`mitsuami-test`) needs from a backend beyond the
146/// [`Backend`] contract. Implemented by each backend's shareable handle.
147pub trait TestHooks {
148    /// Short name used in snapshot and visual baseline paths: `"appkit"`,
149    /// `"gtk"`, `"winui"`.
150    fn name(&self) -> &'static str;
151    /// Resizes a window's content area the way the user would, so the
152    /// platform reports it back as `WindowResized`.
153    fn resize_window(&self, window: NodeId, size: Size);
154    /// Commands applied since the last call (record them when asked to).
155    fn take_command_log(&self) -> Vec<Command>;
156    /// Live native nodes, as a leak detector.
157    fn node_count(&self) -> usize;
158    /// Called after every settle: lets the platform catch up on work it
159    /// does asynchronously (showing windows, allocating, delivering queued
160    /// notifications) without waiting. Platforms that do it all
161    /// synchronously, like AppKit, need nothing here.
162    fn settle(&self) {}
163}
164
165pub trait Backend {
166    /// Called once when the backend is attached to a [`Ui`](crate::Ui).
167    fn init(&mut self, events: EventSink);
168
169    fn metrics(&self) -> PlatformMetrics;
170
171    /// Applies a batch of commands to the native tree.
172    fn apply(&mut self, batch: &[Command]);
173
174    /// Intrinsic size of a leaf widget. Called synchronously during layout,
175    /// after all commands of the current batch have been applied.
176    fn measure(&mut self, id: NodeId, request: MeasureRequest) -> Size;
177
178    /// Performs an accessibility action on the native control, as assistive
179    /// technology would. Resulting events go through the [`EventSink`].
180    fn perform(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError>;
181
182    /// Synthesizes raw user input on a native control, as close to real input
183    /// as the platform allows. Used by end-to-end tests.
184    fn synthesize(&mut self, id: NodeId, input: &SyntheticInput) -> Result<(), ActionError>;
185
186    fn native_state(&self, id: NodeId) -> Option<NativeState>;
187
188    /// Offscreen screenshot of a window or node. Async because some
189    /// platforms render asynchronously (WinUI's `RenderTargetBitmap`);
190    /// reply whenever it's ready, right away if possible.
191    fn capture(&mut self, id: NodeId, reply: crate::services::Reply<Result<Image, CaptureError>>);
192
193    /// The platform's clipboard, dialogs and menus. Called once, when the
194    /// backend is attached; tests may replace the result.
195    fn services(&self) -> Box<dyn crate::services::Services>;
196}