Skip to main content

compose_rust/runtime/
seam.rs

1//! The seam between the boundary and whatever builds the tree.
2//!
3//! The boundary entry points, the batch arena, the theme and window records, assets,
4//! messages, notifications, streaming appends and the frame request all belong to this
5//! crate and behave the same whatever authoring model produced the tree. What differs is
6//! how a tree is built and changed: a Dioxus `VirtualDom` diffs one, a recomposition
7//! runtime re-runs the scopes that read a changed state. That part is a [`Runtime`].
8//!
9//! An application registers one with [`LaunchBuilder::launch_runtime`], and every
10//! `compose_rust_host_*` call is answered by a [`Host`] that drives it. Nothing about
11//! the boundary changes with the runtime: the same five entry points, the same records,
12//! the same batch.
13//!
14//! [`LaunchBuilder::launch_runtime`]: crate::LaunchBuilder::launch_runtime
15//! [`Host`]: crate::Host
16
17use crate::protocol::{BatchEncoder, HostEvent, Mutation, ProtocolError};
18use crate::schema::{AssetKind, MessageDuration, MessagePlacement, Selection, Theme, Window};
19use std::task::{Context, Poll};
20
21/// One batch, written by the runtime and by the Host into the same arena.
22///
23/// The Host opens it with [`Batch::begin`], writes the records that are its own (the theme,
24/// the window, assets, messages, notifications, streamed tails) and has the runtime write
25/// the tree's records between them, then closes it with [`Batch::finish`]. The bytes that
26/// come back are what the boundary hands the Renderer.
27///
28/// A runtime has no fallible way to report a bad record from the middle of a diff, so
29/// [`Batch::fail`] keeps the error and `finish` returns it in place of the batch.
30pub struct Batch {
31    encoder: BatchEncoder,
32    error: Option<ProtocolError>,
33    /// Where a grouped edit is encoded before it is copied into the arena. Kept, so a warm
34    /// batch encodes one without allocating.
35    edit_group: Vec<u8>,
36}
37
38impl Default for Batch {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl Batch {
45    /// Sized so that an ordinary screen's batches never grow it: once warm, writing a
46    /// frame allocates nothing.
47    pub fn new() -> Self {
48        Self {
49            encoder: BatchEncoder::with_capacity(16 * 1024, 4 * 1024, 256),
50            error: None,
51            edit_group: Vec::new(),
52        }
53    }
54
55    /// The batch arena, so a Renderer that reads Host memory through a mapped view can be
56    /// handed one.
57    pub fn arena(&self) -> (*const u8, usize) {
58        self.encoder.arena()
59    }
60
61    /// Starts a new batch, discarding the previous one and any error it carried.
62    pub fn begin(&mut self) {
63        self.encoder.clear();
64        self.error = None;
65    }
66
67    /// Closes the batch and returns its bytes, or the first error written into it.
68    pub fn finish(&mut self) -> Result<&[u8], ProtocolError> {
69        if let Some(error) = self.error.take() {
70            return Err(error);
71        }
72        self.encoder.finish()
73    }
74
75    /// Writes one record. After an error nothing more is written: the batch is already
76    /// going to be refused.
77    pub fn write(&mut self, mutation: Mutation<'_>) {
78        if self.error.is_none() {
79            if let Err(error) = self.encoder.encode(&mutation) {
80                self.error = Some(error);
81            }
82        }
83    }
84
85    /// Records an error found while building the batch. `finish` returns it.
86    pub fn fail(&mut self, error: ProtocolError) {
87        self.error = Some(error);
88    }
89
90    /// The root theme record. Written once per rebuild, never per frame.
91    pub fn set_theme(&mut self, theme: Theme) {
92        self.write(Mutation::SetTheme(theme));
93        if let Some(overlay) = theme.overlay {
94            self.write(Mutation::SetOverlayTokens(*overlay));
95        }
96    }
97
98    /// Sets application-level overlay theme tokens for Dialog, Menu, Dropdown and Sheet.
99    pub fn set_overlay_tokens(&mut self, tokens: crate::schema::OverlayTokens) {
100        self.write(Mutation::SetOverlayTokens(tokens));
101    }
102
103    /// The root window record. Written once per rebuild, never per frame.
104    pub fn set_window(&mut self, window: Window) {
105        self.write(Mutation::SetWindow(window));
106    }
107
108    pub fn set_text_node(&mut self, node_id: u32, text: &str, selection: Option<Selection>) {
109        self.write(Mutation::SetText {
110            node_id,
111            text,
112            selection,
113        });
114    }
115
116    /// Copies one asset into the batch. The bytes ride behind the records, and the
117    /// Renderer takes its own copy inside the call that carries them.
118    pub fn register_asset(&mut self, asset_id: u32, kind: AssetKind, bytes: &[u8]) {
119        self.write(Mutation::RegisterAsset {
120            asset_id,
121            kind,
122            bytes,
123        });
124    }
125
126    pub fn release_asset(&mut self, asset_id: u32) {
127        self.write(Mutation::ReleaseAsset { asset_id });
128    }
129
130    /// Writes one transient message into the batch.
131    ///
132    /// It names no node, because a message is not in the tree: it is a sentence with a
133    /// lifetime, and that lifetime belongs to the Renderer.
134    pub fn show_message(
135        &mut self,
136        handler_id: u64,
137        text: &str,
138        action: &str,
139        duration: MessageDuration,
140    ) {
141        self.show_placed_message(handler_id, text, action, duration, None, None);
142    }
143
144    /// Writes one transient message that names where it is drawn: along which edge and at
145    /// which end of it, and how far from that edge in dp. `None` for either leaves it to
146    /// the design system, which is what [`Batch::show_message`] does for both.
147    pub fn show_placed_message(
148        &mut self,
149        handler_id: u64,
150        text: &str,
151        action: &str,
152        duration: MessageDuration,
153        placement: Option<MessagePlacement>,
154        offset_dp: Option<f32>,
155    ) {
156        self.write(Mutation::ShowMessage {
157            handler_id,
158            text,
159            action,
160            duration,
161            placement,
162            offset_dp,
163        });
164    }
165
166    /// Writes one notification command into the batch.
167    ///
168    /// Like a message it names no node: what it asks for happens outside the window, and
169    /// the Renderer is the side that owns the platform it happens on.
170    pub(crate) fn notification(&mut self, command: &crate::notification::NotificationCommand) {
171        use crate::notification::NotificationCommand;
172        match command {
173            NotificationCommand::Post(notification) => {
174                self.write(Mutation::PostNotification {
175                    key: &notification.key,
176                    title: &notification.title,
177                    body: &notification.body,
178                    channel: &notification.channel,
179                    action_1: &notification.actions[0],
180                    action_2: &notification.actions[1],
181                    importance: notification.importance,
182                    presentation: notification.presentation,
183                });
184            }
185            NotificationCommand::Withdraw(key) => {
186                self.write(Mutation::WithdrawNotification { key });
187            }
188            NotificationCommand::RequestPermission => {
189                self.write(Mutation::RequestNotificationPermission);
190            }
191        }
192    }
193
194    /// Writes one clipboard write. It names no node: the clipboard is the platform's.
195    pub fn set_clipboard_text(&mut self, text: &str) {
196        self.write(Mutation::SetClipboardText { text });
197    }
198
199    /// Writes one clipboard read request. It names no node either.
200    pub fn read_clipboard(&mut self, request: u32) {
201        self.write(Mutation::ReadClipboard { request });
202    }
203
204    /// Writes one operation on a file the Renderer holds a handle for.
205    pub(crate) fn file_call(&mut self, call: &crate::picked_file::Call) {
206        self.write(Mutation::FileCall {
207            request: call.request,
208            op: call.op,
209            create: call.create,
210            handle: call.handle,
211            name: &call.name,
212            data: &call.data,
213        });
214    }
215
216    /// Writes one storage operation for the Renderer to carry out. It names no node either.
217    pub(crate) fn storage_call(&mut self, call: &crate::storage::RendererCall) {
218        self.write(Mutation::StorageCall {
219            request: call.request,
220            op: call.op,
221            store: &call.store,
222            key: &call.key,
223            data: &call.data,
224        });
225    }
226
227    /// Lets the Renderer go of a file handle nothing on this side names any more.
228    pub(crate) fn release_file_handle(&mut self, handle: u32) {
229        self.write(Mutation::ReleaseFileHandle { handle });
230    }
231
232    /// Writes one request to scroll the container `node_id` to an offset in physical
233    /// pixels. An axis left `None` is not touched; a request that names neither axis is
234    /// refused when the batch is finished.
235    ///
236    /// A request, not a command: the Renderer owns the position. It keeps the offset
237    /// inside what the content allows, ignores the request while the user is dragging or
238    /// flinging, and says where the container ended up in `ScrollChanged`.
239    pub fn scroll_to(&mut self, node_id: u32, request: crate::schema::ScrollTo) {
240        use crate::schema::scroll_to_flags as flag;
241        let mut flags = 0;
242        if request.animate {
243            flags |= flag::ANIMATE;
244        }
245        if request.x_px.is_some() {
246            flags |= flag::X;
247        }
248        if request.y_px.is_some() {
249            flags |= flag::Y;
250        }
251        let x_px = request.x_px.unwrap_or(0.0);
252        let y_px = request.y_px.unwrap_or(0.0);
253        if flags & (flag::X | flag::Y) == 0 || !x_px.is_finite() || !y_px.is_finite() {
254            // The Renderer would refuse it with a protocol error after the batch had
255            // crossed. Refusing it here names the mistake where it was made.
256            self.fail(ProtocolError::InvalidValueKind(0));
257            return;
258        }
259        self.write(Mutation::ScrollTo {
260            node_id,
261            item: request.item,
262            flags,
263            x_px,
264            y_px,
265        });
266    }
267
268    /// Writes one request to bring a rectangle into view in the container `node_id`. One
269    /// request moves one container: to show something inside nested containers, write one
270    /// for each of them, innermost first.
271    pub fn scroll_into_view(&mut self, node_id: u32, request: crate::schema::ScrollIntoView) {
272        use crate::schema::{ScrollTarget, scroll_into_view_flags, scroll_target_kind};
273        let (target_kind, target, rect) = match request.target {
274            ScrollTarget::Content(rect) => (scroll_target_kind::CONTENT, 0, rect),
275            ScrollTarget::Node(node, rect) => (scroll_target_kind::NODE, node, rect),
276            ScrollTarget::Item(item, rect) => (scroll_target_kind::ITEM, item, rect),
277        };
278        let numbers = [rect.x_px, rect.y_px, rect.width_px, rect.height_px];
279        if numbers.iter().any(|value| !value.is_finite())
280            || rect.width_px < 0.0
281            || rect.height_px < 0.0
282        {
283            self.fail(ProtocolError::InvalidValueKind(0));
284            return;
285        }
286        self.write(Mutation::ScrollIntoView {
287            node_id,
288            target,
289            target_kind,
290            align_x: request.align_x as u16,
291            align_y: request.align_y as u16,
292            flags: if request.animate {
293                scroll_into_view_flags::ANIMATE
294            } else {
295                0
296            },
297            rect,
298        });
299    }
300
301    /// Writes one request to put the platform view `handle` in the place of the
302    /// `NativeView` node `node_id`. A view the node already had is taken out first, and
303    /// `NativeHandle::NONE` takes the node's view out and puts nothing in.
304    ///
305    /// The view stays the caller's. The Renderer places, clips and focuses it and never
306    /// destroys it; once a batch that took it out has been applied, the caller destroys it.
307    /// Make the view against the handle `NativeViewParent` reported for the node's window.
308    pub fn attach_native_view(&mut self, node_id: u32, handle: crate::schema::NativeHandle) {
309        self.write(Mutation::AttachNativeView { node_id, handle });
310    }
311
312    /// Writes one request to give keyboard focus to the platform view of the `NativeView`
313    /// node `node_id` (`focus` true), or to hand it back to the scene (false). What the
314    /// focus did is reported to the node's focus handler.
315    pub fn focus_native_view(&mut self, node_id: u32, focus: bool) {
316        self.write(Mutation::FocusNativeView { node_id, focus });
317    }
318
319    /// Writes one file dialog request. Like a notification it names no node: the dialog is
320    /// not in the tree, and `window` only says which window it is modal for.
321    pub(crate) fn file_dialog(&mut self, request: &crate::file_dialog::Request) {
322        self.write(Mutation::ShowFileDialog {
323            request: request.id,
324            window: request.window,
325            kind: request.kind,
326            default_filter: request.default_filter,
327            title: &request.title,
328            directory: &request.directory,
329            name: &request.name,
330            filters: &request.filters,
331        });
332    }
333
334    /// Writes one edit the application asked of a code editor: replace `range` of the
335    /// document as it stood at `base_version` with `text`. The Renderer moves it past what
336    /// the reader typed since, or refuses it and reports `request_id` back.
337    pub fn edit_code(
338        &mut self,
339        node_id: u32,
340        request_id: u32,
341        base_version: u32,
342        range: crate::code::CodeRange,
343        text: &str,
344    ) {
345        self.write(Mutation::EditCode {
346            node_id,
347            request_id,
348            base_version,
349            start_line: range.start.line,
350            start_column: range.start.column,
351            end_line: range.end.line,
352            end_column: range.end.column,
353            text,
354        });
355    }
356
357    /// Writes one grouped edit the application asked of a code editor: replace every range
358    /// in `edits` with its text, all of them or none.
359    ///
360    /// Every range is in the document as it stood at `base_version`, so an edit never moves
361    /// the ranges of the others, and the edits may be listed in any order. They must not
362    /// overlap; two insertions at the same place go in in the order they are listed. Where
363    /// the reader has typed since, the Renderer moves every range past what they typed, and
364    /// refuses the whole group where any range meets it. It answers the group with exactly
365    /// one `CodeEditGroupResult` carrying `request_id`, and the whole group undoes as one
366    /// step. A group with no edits writes nothing at all.
367    pub fn edit_group(
368        &mut self,
369        node_id: u32,
370        request_id: u32,
371        base_version: u32,
372        edits: &[(crate::code::CodeRange, &str)],
373    ) {
374        if edits.is_empty() {
375            return;
376        }
377        let mut blob = std::mem::take(&mut self.edit_group);
378        blob.clear();
379        match crate::code::encode_edit_group(edits, &mut blob) {
380            Ok(()) => self.write(Mutation::EditCodeGroup {
381                node_id,
382                request_id,
383                base_version,
384                edits: &blob,
385            }),
386            Err(error) => self.fail(error),
387        }
388        self.edit_group = blob;
389    }
390
391    /// Writes one request to put a code editor's selection between two places in the
392    /// document as it stood at `base_version`. The Renderer moves both ends past what the
393    /// reader typed since and drops the request, with a protocol error, where an end is not
394    /// a place in the document.
395    pub fn set_selection(
396        &mut self,
397        node_id: u32,
398        base_version: u32,
399        anchor: crate::code::Position,
400        active: crate::code::Position,
401    ) {
402        self.write(Mutation::SetSelection {
403            node_id,
404            base_version,
405            anchor_line: anchor.line,
406            anchor_column: anchor.column,
407            active_line: active.line,
408            active_column: active.column,
409        });
410    }
411
412    /// Writes one request to scroll a code editor until `range`, as the document stood at
413    /// `base_version`, is on screen. A range inside a folded stretch unfolds it.
414    pub fn reveal_range(
415        &mut self,
416        node_id: u32,
417        base_version: u32,
418        range: crate::code::CodeRange,
419        align: crate::schema::RevealAlign,
420    ) {
421        self.write(Mutation::RevealRange {
422            node_id,
423            base_version,
424            start_line: range.start.line,
425            start_column: range.start.column,
426            end_line: range.end.line,
427            end_column: range.end.column,
428            align,
429        });
430    }
431
432    /// Writes one request to fold or unfold the stretch of a code editor that starts on
433    /// `start_line`.
434    pub fn set_folded(&mut self, node_id: u32, start_line: u32, collapsed: bool) {
435        self.write(Mutation::SetFolded {
436            node_id,
437            start_line,
438            collapsed,
439        });
440    }
441
442    /// Writes one request to scroll a code editor so that `offset_px` physical pixels of its
443    /// document are above the top of its view. The offset is the unit `CodeScrolled`
444    /// reports, so what one editor reported can be given to another to keep the two level.
445    /// The Renderer keeps it inside what the document allows.
446    pub fn set_scroll_offset(&mut self, node_id: u32, offset_px: f64) {
447        self.write(Mutation::SetScrollOffset { node_id, offset_px });
448    }
449
450    /// Writes one question to a code editor: where would a caret at `position` be drawn.
451    /// `request` is the number [`crate::code::position_query`] gave the callback that waits
452    /// for the answer. The Renderer answers it exactly once, with a rectangle in the
453    /// window's dp, or with none where the position is not on screen.
454    pub fn query_position_rect(
455        &mut self,
456        node_id: u32,
457        request: u32,
458        position: crate::code::Position,
459    ) {
460        self.write(Mutation::QueryPositionRect {
461            node_id,
462            request,
463            line: position.line,
464            column: position.column,
465        });
466    }
467
468    /// Writes one request to set every selection of a code editor, each an anchor and an
469    /// active end in the document as it stood at `base_version`, the first the primary one.
470    /// The Renderer moves every end past what the reader typed since, and drops the request,
471    /// with a protocol error, where an end is not a place in the document or the list is
472    /// empty. Typing, deleting and pasting then happen at every selection as one step, and
473    /// Escape goes back to the primary one.
474    pub fn set_selections(
475        &mut self,
476        node_id: u32,
477        base_version: u32,
478        selections: &[(crate::code::Position, crate::code::Position)],
479    ) {
480        let mut blob = std::mem::take(&mut self.edit_group);
481        blob.clear();
482        crate::code::encode_selections(selections, &mut blob);
483        self.write(Mutation::SetSelections {
484            node_id,
485            base_version,
486            selections: &blob,
487        });
488        self.edit_group = blob;
489    }
490
491    /// Writes one request to replace `range` of a code editor's document, as it stood at
492    /// `base_version`, with `snippet`, and to open its tab stops.
493    ///
494    /// The snippet is in the subset of VS Code's syntax the editor reads: `$1`,
495    /// `${1:placeholder}`, `${1|one,two|}`, `$0`, and `\$` for a dollar sign
496    /// ([`crate::code::escape_snippet_text`] escapes plain text). The caret selects the first
497    /// stop; Tab and Shift+Tab move between the stops, the places with the same number change
498    /// together, and a stop with choices opens a list. The session ends at `$0`, on Escape, or
499    /// when the caret leaves the snippet. The text it leaves arrives as ordinary changes and
500    /// undoes as one step. Where the reader has typed over the range since `base_version`,
501    /// the Renderer drops the request with a protocol error.
502    pub fn insert_snippet(
503        &mut self,
504        node_id: u32,
505        base_version: u32,
506        range: crate::code::CodeRange,
507        snippet: &str,
508    ) {
509        self.write(Mutation::InsertSnippet {
510            node_id,
511            base_version,
512            start_line: range.start.line,
513            start_column: range.start.column,
514            end_line: range.end.line,
515            end_column: range.end.column,
516            snippet,
517        });
518    }
519
520    /// Appends the streamed tail to a Text node without resending its whole value.
521    pub fn append_text_node(&mut self, node_id: u32, text: &str) {
522        self.write(Mutation::AppendText { node_id, text });
523    }
524
525    /// Requests input focus for `node_id`, or clears focus when `node_id` is 0.
526    pub fn request_focus(&mut self, node_id: u32) {
527        self.write(Mutation::RequestFocus { node_id });
528    }
529}
530
531/// What builds and changes the tree, seen from the boundary.
532///
533/// The Host owns everything that is not the tree and calls in here for the rest. Every
534/// method runs on the Renderer's UI thread, inside a boundary call, between a
535/// [`Batch::begin`] and a [`Batch::finish`] the Host makes on [`Runtime::batch_mut`], so a
536/// runtime writes its records and returns; it never opens or closes a batch itself.
537pub trait Runtime {
538    /// The batch this runtime writes the tree's records into. The Host writes its own
539    /// records into the same one, before and after the runtime's.
540    fn batch(&self) -> &Batch;
541
542    fn batch_mut(&mut self) -> &mut Batch;
543
544    /// Writes the whole tree. Called once on a fresh runtime, which is also what a resync
545    /// gets: the Host makes a new runtime and rebuilds it.
546    fn rebuild(&mut self);
547
548    /// Writes whatever changed since the last call: state a worker wrote, a scope that a
549    /// size class or a design system woke, the consequences of an event.
550    ///
551    /// `frame_time_nanos` is the time of the frame the Renderer is serving, when this call
552    /// is serving one, and `None` when it answers an event. A runtime whose animations and
553    /// timers run on the frame clock reads it here; one that has no clock of its own
554    /// ignores it.
555    fn render(&mut self, frame_time_nanos: Option<u64>);
556
557    /// Runs the handler an event names, and nothing else: the Host renders afterwards.
558    ///
559    /// Returns the value the boundary hands back as the call's result, which is how a key
560    /// handler says it consumed the key. An event naming a handler or a node this runtime
561    /// does not have is an error, and so is a payload that no handler can receive.
562    fn handle_event(&mut self, event: &HostEvent<'_>) -> Result<i64, ProtocolError>;
563
564    /// The application's name for a node it asked to have measured, if it asked.
565    fn size_token(&self, node_id: u32) -> Option<u32> {
566        let _ = node_id;
567        None
568    }
569
570    /// Whether `node_id` is a `Window` node. A window's size and zoom reports name
571    /// it, and nothing else, so a runtime without windows has none.
572    fn is_window(&self, node_id: u32) -> bool {
573        let _ = node_id;
574        false
575    }
576
577    /// Whether the runtime has work waiting that a frame should run. A runtime that is
578    /// woken by something outside a boundary call (a timer, a task it spawned) wakes the
579    /// context's waker, and the Host turns that into a frame request.
580    fn poll_work(&mut self, context: &mut Context<'_>) -> Poll<()> {
581        let _ = context;
582        Poll::Pending
583    }
584
585    /// Runs code the application handed to the Host, a message's action for one, inside
586    /// whatever context this runtime's state writes need.
587    fn run_in_context(&mut self, action: &mut dyn FnMut()) {
588        action();
589    }
590}