Skip to main content

compose_rust/
boundary.rs

1use crate::Selection;
2use crate::measure::MeasureResult;
3use crate::protocol::{HostEvent, Mutation, PropertyValue, ProtocolError, decode_event};
4use crate::runtime::Runtime;
5use crate::schema::{
6    AssetKind, EventPayload, IconRole, LoopMode, PROTOCOL_VERSION, SCHEMA_HASH, Theme,
7};
8use std::cell::RefCell;
9use std::ffi::c_int;
10use std::panic::{AssertUnwindSafe, catch_unwind};
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::{Arc, Mutex, OnceLock};
13use std::task::{Context, Wake, Waker};
14
15pub const STATUS_OK: i32 = 0;
16pub const STATUS_PROTOCOL_ERROR: i32 = -1;
17pub const STATUS_NOT_INITIALIZED: i32 = -2;
18pub const STATUS_ALREADY_INITIALIZED: i32 = -3;
19pub const STATUS_PANIC: i32 = -4;
20/// There is no renderer in this build to run. Returned by the loop entry point, never by
21/// a boundary call: a call could not have got this far without a renderer to make it.
22pub const STATUS_NO_RENDERER: i32 = -5;
23/// The application identifier given to `LaunchBuilder::identifier` breaks the rules for one,
24/// so nothing was started. Returned by the loop entry point, never by a boundary call, and
25/// said in a sentence on the standard error first.
26pub const STATUS_INVALID_IDENTIFIER: i32 = -6;
27
28/// What the process exits with when the renderer loop does not finish successfully.
29///
30/// 1, not the status itself: exit codes are a single byte on Unix, so `STATUS_NO_RENDERER`
31/// would reach the shell as 251 and read as a signal rather than an ordinary failure.
32const EXIT_FAILURE: i32 = 1;
33
34#[repr(C)]
35#[derive(Clone, Copy, Debug)]
36pub struct MutationBatch {
37    pub ptr: *const u8,
38    pub len: u32,
39    pub result: i64,
40}
41
42impl Default for MutationBatch {
43    fn default() -> Self {
44        Self {
45            ptr: std::ptr::null(),
46            len: 0,
47            result: 0,
48        }
49    }
50}
51
52/// The Renderer's half of the boundary, as the Host calls it.
53#[derive(Clone, Copy)]
54pub struct RendererApi {
55    pub run: extern "C" fn() -> c_int,
56    pub request_frame: extern "C" fn(),
57    /// Reads `count` request records from the buffer and writes `count` results. Only on
58    /// the UI thread, and normally from inside a Host call the Renderer made.
59    pub measure: unsafe extern "C" fn(*const u8, u32, u32, *mut MeasureResult) -> i32,
60}
61
62static RENDERER_API: OnceLock<RendererApi> = OnceLock::new();
63static FRAME_REQUESTED: AtomicBool = AtomicBool::new(false);
64static EVENT_DISPATCH_ACTIVE: AtomicBool = AtomicBool::new(false);
65static DEFERRED_FRAME_REQUEST: AtomicBool = AtomicBool::new(false);
66/// Set between a stop and the start that follows it. While it is set a worker's frame
67/// request is remembered but not delivered, so a process that is not on screen is never
68/// asked to draw.
69static LIFECYCLE_SUPPRESSED: AtomicBool = AtomicBool::new(false);
70
71pub fn install_renderer_api(api: RendererApi) -> Result<(), RendererApi> {
72    RENDERER_API.set(api)
73}
74
75// `renderer_linked` is set by the build script, and only when a renderer was really
76// linked. That is not the same as the feature being on: a documentation build turns the
77// feature on and links nothing, and the result has to behave like the build it is.
78#[cfg(all(renderer_linked, not(any(test, feature = "mock-renderer"))))]
79unsafe extern "C" {
80    fn compose_rust_renderer_run() -> c_int;
81    fn compose_rust_renderer_request_frame();
82    fn compose_rust_renderer_measure(
83        requests: *const u8,
84        length: u32,
85        count: u32,
86        results: *mut MeasureResult,
87    ) -> i32;
88}
89
90#[cfg(all(renderer_linked, not(any(test, feature = "mock-renderer"))))]
91extern "C" fn native_run() -> c_int {
92    // The Linux static renderer refers to the five Host functions weakly, so that its own
93    // test executable links without a Host, and a weak reference does not make a linker
94    // pull in the code it names. This one does: running the renderer keeps them linked,
95    // whichever object file of this crate the compiler happened to put them in.
96    std::hint::black_box(&BOUNDARY_EXPORTS);
97    // SAFETY: The application links the Renderer implementation of this declared C ABI.
98    unsafe { compose_rust_renderer_run() }
99}
100
101#[cfg(all(renderer_linked, not(any(test, feature = "mock-renderer"))))]
102extern "C" fn native_request_frame() {
103    // SAFETY: The Renderer contract makes request_frame thread-safe.
104    unsafe { compose_rust_renderer_request_frame() }
105}
106
107/// # Safety
108/// As `compose_rust_renderer_measure`: readable requests, writable results.
109#[cfg(all(renderer_linked, not(any(test, feature = "mock-renderer"))))]
110unsafe extern "C" fn native_measure(
111    requests: *const u8,
112    length: u32,
113    count: u32,
114    results: *mut MeasureResult,
115) -> i32 {
116    // SAFETY: The caller's promise is passed on unchanged, and the Renderer refuses a call
117    // from the wrong thread rather than measuring on it.
118    unsafe { compose_rust_renderer_measure(requests, length, count, results) }
119}
120
121// The mock renderer and the crate's own tests drive the boundary directly and never want
122// a window, so doing nothing is the correct answer for them and always has been.
123#[cfg(any(test, feature = "mock-renderer"))]
124extern "C" fn native_run() -> c_int {
125    STATUS_OK
126}
127
128#[cfg(any(test, feature = "mock-renderer"))]
129extern "C" fn native_request_frame() {}
130
131// The mock renderer answers by fixed rules, so a test of the Host can predict every size.
132#[cfg(any(test, feature = "mock-renderer"))]
133use crate::measure::fake_measure as native_measure;
134
135// A real build with no renderer. This used to return success, so an application built
136// this way opened no window, drew nothing, printed nothing and exited 0, and there was
137// no way to tell that from a program that had simply finished.
138#[cfg(all(not(renderer_linked), not(any(test, feature = "mock-renderer"))))]
139extern "C" fn native_run() -> c_int {
140    eprintln!("{}", no_renderer_message());
141    STATUS_NO_RENDERER
142}
143
144#[cfg(all(not(renderer_linked), not(any(test, feature = "mock-renderer"))))]
145extern "C" fn native_request_frame() {}
146
147/// There is nothing to measure with, which the caller hears as a refusal and carries on
148/// past with every size at zero.
149#[cfg(all(not(renderer_linked), not(any(test, feature = "mock-renderer"))))]
150unsafe extern "C" fn native_measure(
151    _requests: *const u8,
152    _length: u32,
153    _count: u32,
154    _results: *mut MeasureResult,
155) -> i32 {
156    crate::measure::MEASURE_UNAVAILABLE
157}
158
159/// What a build with no renderer says on its way out.
160///
161/// Compiled into every build, not only the one that prints it, so that a test can read it
162/// whatever the build it is running in was configured with.
163pub fn no_renderer_message() -> String {
164    format!(
165        "compose-rust: this application was built without a renderer, so there is nothing\n\
166         to draw with and nothing to draw on. Exiting {EXIT_FAILURE} rather than looking like\n\
167         a program that ran and finished.\n\
168         \n\
169         A default `cargo build` links the renderer for the platform it is building for and\n\
170         downloads it if it has to. A build reaches this message by turning that off:\n\
171         \n\
172         \x20   default-features = false, without re-enabling `native-renderer`\n\
173         \x20   a documentation build, which has no network to fetch a renderer with\n\
174         \n\
175         Building for a test or with the `mock-renderer` feature is a third way, and that\n\
176         one is silent on purpose: those builds drive the boundary directly and want no\n\
177         window."
178    )
179}
180
181fn renderer_api() -> RendererApi {
182    RENDERER_API.get().copied().unwrap_or(RendererApi {
183        run: native_run,
184        request_frame: native_request_frame,
185        measure: native_measure,
186    })
187}
188
189/// Asks the Renderer to measure, through whichever Renderer is installed.
190///
191/// Crate-internal: the safe way in is `measure::measurer`, which only hands out the right
192/// to call this inside a Host call. The pointers come from slices that outlive the call.
193pub(crate) fn renderer_measure(
194    requests: *const u8,
195    length: u32,
196    count: u32,
197    results: *mut MeasureResult,
198) -> i32 {
199    // SAFETY: the caller passes a readable buffer of `length` bytes and room for `count`
200    // results, both borrowed for the length of this call.
201    unsafe { (renderer_api().measure)(requests, length, count, results) }
202}
203
204/// Coalesced wake used internally by the runtime's scheduler waker.
205///
206/// The flag spans the moment of delivery, not the wait for the frame that answers it. The
207/// Renderer folds requests into its own frame clock, so however many arrive between two
208/// frames it draws once; holding the flag until the frame came back would instead mean
209/// that one request the Renderer was not yet listening for silenced every later one. That
210/// happens on a cold start, where the first composition can be seconds after the first
211/// worker request, and it leaves the application frozen with nothing to unfreeze it.
212pub fn request_frame_from_worker() {
213    if !FRAME_REQUESTED.swap(true, Ordering::AcqRel) {
214        if LIFECYCLE_SUPPRESSED.load(Ordering::Acquire)
215            || EVENT_DISPATCH_ACTIVE.load(Ordering::Acquire)
216        {
217            DEFERRED_FRAME_REQUEST.store(true, Ordering::Release);
218        } else {
219            (renderer_api().request_frame)();
220            FRAME_REQUESTED.store(false, Ordering::Release);
221        }
222    }
223}
224
225thread_local! {
226    /// How deep this thread is inside a Host call. A notification posted from inside one is
227    /// written into the batch that call returns, so it needs no frame of its own.
228    static HOST_CALL_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
229}
230
231/// Whether this thread is inside `rebuild`, `dispatch` or `render_frame` right now.
232pub(crate) fn in_host_call() -> bool {
233    HOST_CALL_DEPTH.with(std::cell::Cell::get) > 0
234}
235
236/// Marks the span of one Host call on this thread.
237struct HostCallGuard;
238
239impl HostCallGuard {
240    fn enter() -> Self {
241        HOST_CALL_DEPTH.with(|depth| depth.set(depth.get() + 1));
242        Self
243    }
244}
245
246impl Drop for HostCallGuard {
247    fn drop(&mut self) {
248        HOST_CALL_DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
249    }
250}
251
252/// Asks for the frame that carries a queued notification out.
253///
254/// The one request a stopped UI does not hold back. Holding requests while the platform
255/// has the UI off screen is right for timers and animations, which nobody is watching, and
256/// wrong for a notification, whose whole point is the moment nobody is watching. So while
257/// stopped this goes to the Renderer directly, and the Renderer serves it outside its
258/// stopped frame clock. Everything else stays held, and the frame it was waiting for is
259/// still delivered on start.
260pub(crate) fn request_frame_for_notifications() {
261    if LIFECYCLE_SUPPRESSED.load(Ordering::Acquire) {
262        (renderer_api().request_frame)();
263        return;
264    }
265    request_frame_from_worker();
266}
267
268struct EventDispatchGuard;
269
270impl EventDispatchGuard {
271    fn enter() -> Self {
272        EVENT_DISPATCH_ACTIVE.store(true, Ordering::Release);
273        Self
274    }
275}
276
277impl Drop for EventDispatchGuard {
278    fn drop(&mut self) {
279        EVENT_DISPATCH_ACTIVE.store(false, Ordering::Release);
280        if LIFECYCLE_SUPPRESSED.load(Ordering::Acquire) {
281            return;
282        }
283        if DEFERRED_FRAME_REQUEST.swap(false, Ordering::AcqRel) {
284            (renderer_api().request_frame)();
285            FRAME_REQUESTED.store(false, Ordering::Release);
286        }
287    }
288}
289
290struct FrameWake;
291
292impl Wake for FrameWake {
293    fn wake(self: Arc<Self>) {
294        request_frame_from_worker();
295    }
296
297    fn wake_by_ref(self: &Arc<Self>) {
298        request_frame_from_worker();
299    }
300}
301
302/// One streaming Text node's tail, accumulated between frames.
303struct PendingAppend {
304    node_id: u32,
305    text: String,
306    dirty: bool,
307}
308
309/// Makes the runtime a Host drives. Called once per Host, and again on a resync, which
310/// is the one thing a diff against a lost node table cannot answer.
311///
312/// Shared across threads because `launch` runs on the Rust main thread and the Host is
313/// built on the Renderer's UI thread, which is a different one under
314/// `LoopMode::Renderer`. The runtime it makes is not shared: it lives and dies on the UI
315/// thread.
316pub type RuntimeFactory = Arc<dyn Fn() -> Box<dyn Runtime> + Send + Sync>;
317
318pub struct Host {
319    /// Kept so the tree can be built again from nothing when the Renderer asks for a
320    /// resync, which is the one thing a diff against a lost node table cannot answer.
321    factory: RuntimeFactory,
322    theme: Theme,
323    window: crate::schema::Window,
324    runtime: Box<dyn Runtime>,
325    frame_waker: Waker,
326    pending_appends: Vec<PendingAppend>,
327}
328
329impl Host {
330    /// A Host for the runtime `factory` makes, in the theme the application launched with.
331    pub fn new(factory: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static) -> Self {
332        Self::from_factory(Arc::new(factory), launched_theme())
333    }
334
335    /// The theme the application chose. Choosing nothing follows the host platform, with
336    /// Material 3 where the platform has no look of its own.
337    pub fn with_theme(
338        factory: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static,
339        theme: Theme,
340    ) -> Self {
341        Self::from_factory(Arc::new(factory), theme)
342    }
343
344    fn from_factory(factory: RuntimeFactory, theme: Theme) -> Self {
345        // A fresh Host has not been measured yet, and the Renderer that is about to drive
346        // it starts from the same assumption. Leaving a previous Host's last measurement
347        // behind would put the two sides out of step, because the Renderer reports only
348        // differences.
349        crate::window::reset_window_size();
350        // Messages queued against a Host that is going away would otherwise be said by
351        // the one replacing it, out of any context that made them make sense.
352        //
353        crate::message::reset_messages();
354        // A clipboard write is the same: it belongs to the Host that asked for it.
355        crate::clipboard::reset_clipboard();
356        // A question about where a position is on screen was asked of the old Renderer.
357        crate::code::reset_position_queries();
358        // The Renderer reports its zoom again at start, and a level the last Host asked for
359        // and never sent is that Host's business.
360        crate::zoom::reset_zoom();
361        crate::native_view::reset_native_parents();
362        // The density is reported again at start as well, before the first frame.
363        crate::density::reset_density();
364        // The windows' commands and registrations belong to the Host that queued them.
365        crate::windows::reset_windows();
366        // The assets do not go with them. The Renderer this Host is about to talk to has
367        // an empty cache, so every registration has to be made again, which is what this
368        // does: the ids stay as they were and the bytes are queued for the first batch.
369        //
370        // Forgetting them instead is what this used to do, and it was wrong in a way that
371        // only showed on the screen. A theme names its fonts by id and a window names its
372        // icon by id, and both are built by the caller before the Host is made out of
373        // them, so the ids travelled and the bytes they named had been thrown away.
374        crate::asset::requeue_all();
375        // The theme a running application changes from, and nothing queued against the
376        // Host this one replaces.
377        crate::theme::install(theme);
378        let runtime = factory();
379        Self {
380            factory,
381            theme,
382            window: launched_window(),
383            runtime,
384            frame_waker: Waker::from(Arc::new(FrameWake)),
385            pending_appends: Vec::new(),
386        }
387    }
388
389    /// Replaces the window settings this Host was made with, which are the launch's. For a
390    /// test or a tool that builds a Host without launching an application, such as one
391    /// that wants several windows: `Window::new().with_windows()`.
392    pub fn set_window(&mut self, window: crate::schema::Window) {
393        self.window = window;
394    }
395
396    fn batch(&mut self) -> &mut crate::runtime::Batch {
397        self.runtime.batch_mut()
398    }
399
400    pub fn rebuild(&mut self) -> Result<&[u8], ProtocolError> {
401        let _call = HostCallGuard::enter();
402        self.batch().begin();
403        // One record at the root, before any node exists. The Renderer resolves roles to
404        // values, so switching theme or colour scheme costs this one record rather than a
405        // SetProp for every node in the tree.
406        let (theme, window) = (self.theme, self.window);
407        self.batch().set_theme(theme);
408        // Beside the theme, and for the same reason: it is about the window rather than
409        // any node in it, and it is settled once rather than every frame. The Renderer
410        // reads it out of this batch before it stands the window up.
411        self.batch().set_window(window);
412        self.runtime.rebuild();
413        self.flush_messages();
414        self.arm_scheduler_wake();
415        self.runtime.batch_mut().finish()
416    }
417
418    pub fn dispatch_event(&mut self, bytes: &[u8]) -> Result<(&[u8], i64), ProtocolError> {
419        let event = decode_event(bytes)?;
420        self.dispatch(event)
421    }
422
423    /// The batch arena, reported to the Renderer on every boundary call.
424    pub fn arena(&self) -> (*const u8, usize) {
425        self.runtime.batch().arena()
426    }
427
428    /// Answers with the whole tree, for a Renderer that no longer has a node table.
429    ///
430    /// The Host keeps no shadow of what it has already sent, so the only way to produce a
431    /// full-tree batch is to build the application again, and that resets component state.
432    /// A Renderer that keeps its node table across a configuration change never needs
433    /// this call, which is what the Android host does.
434    pub fn resync(&mut self) -> Result<(&[u8], i64), ProtocolError> {
435        *self = Self::from_factory(self.factory.clone(), self.theme);
436        Ok((self.rebuild()?, 0))
437    }
438
439    /// Suppresses timers and animations while the UI is off screen, and releases the
440    /// request that arrived while it was, so nothing is lost by stopping.
441    fn set_lifecycle_running(&mut self, running: bool) -> Result<(&[u8], i64), ProtocolError> {
442        LIFECYCLE_SUPPRESSED.store(!running, Ordering::Release);
443        if running {
444            if DEFERRED_FRAME_REQUEST.swap(false, Ordering::AcqRel) {
445                (renderer_api().request_frame)();
446            }
447            FRAME_REQUESTED.store(false, Ordering::Release);
448        }
449        // An empty batch, not a frame: starting again is the Renderer's cue to draw, and
450        // it asks for that frame itself.
451        self.batch().begin();
452        Ok((self.runtime.batch_mut().finish()?, 0))
453    }
454
455    /// Renders what the runtime has waiting, writes the Host's own records after it, and
456    /// closes the batch. The tail every call that renders shares.
457    fn render_and_finish(&mut self, result: i64) -> Result<(&[u8], i64), ProtocolError> {
458        self.batch().begin();
459        self.runtime.render(None);
460        self.flush_messages();
461        self.arm_scheduler_wake();
462        Ok((self.runtime.batch_mut().finish()?, result))
463    }
464
465    /// An empty batch, for an event that changed nothing anyone is reading.
466    fn empty_batch(&mut self) -> Result<(&[u8], i64), ProtocolError> {
467        self.batch().begin();
468        Ok((self.runtime.batch_mut().finish()?, 0))
469    }
470
471    /// Hands a pressed notification to the components listening for one.
472    ///
473    /// No node and no handler: the notification is not in the tree, and the component that
474    /// posted it may be long gone. What it carries is the key, which the application reads.
475    fn notification_activated(
476        &mut self,
477        action: u32,
478        key: &str,
479    ) -> Result<(&[u8], i64), ProtocolError> {
480        let woke = {
481            let _dispatch_guard = EventDispatchGuard::enter();
482            crate::notification::activate(crate::notification::NotificationActivation {
483                key: key.to_owned(),
484                action,
485            })
486        };
487        self.batch().begin();
488        if woke {
489            self.runtime.render(None);
490        }
491        self.flush_messages();
492        self.arm_scheduler_wake();
493        Ok((self.runtime.batch_mut().finish()?, 0))
494    }
495
496    /// Records whether notifications may be shown, and renders the components that asked.
497    ///
498    /// The same shape as the resolved design system: sent once after start and again only
499    /// when it changes, and a repeat wakes nobody.
500    fn publish_notification_permission(
501        &mut self,
502        state: crate::schema::NotificationPermission,
503    ) -> Result<(&[u8], i64), ProtocolError> {
504        self.batch().begin();
505        if crate::notification::publish_permission(state) {
506            self.runtime.render(None);
507        }
508        self.flush_messages();
509        self.arm_scheduler_wake();
510        Ok((self.runtime.batch_mut().finish()?, 0))
511    }
512
513    /// Records which design system the Renderer resolved the theme to.
514    ///
515    /// The same shape as a size class arriving: it belongs to no node and no handler, and
516    /// a repeat of the same answer wakes nothing, so an application that never asks pays
517    /// a comparison once per change and nothing per frame.
518    fn publish_design_system(
519        &mut self,
520        system: crate::schema::DesignSystem,
521    ) -> Result<(&[u8], i64), ProtocolError> {
522        if crate::design::publish(system) {
523            return self.render_and_finish(0);
524        }
525        self.empty_batch()
526    }
527
528    /// Records how large the Renderer is drawing, and wakes the components that read it.
529    ///
530    /// The level the Renderer reports is also kept as the window's own, so a resync
531    /// rebuilds the window at the level the reader is looking at rather than at one the
532    /// application asked for before the reader changed it.
533    fn publish_zoom(&mut self, k: f32, os: f32, level: i32) -> Result<(&[u8], i64), ProtocolError> {
534        let level = i8::try_from(level).map_err(|_| ProtocolError::InvalidValueKind(0))?;
535        if self.window.zoom_level.is_some() {
536            self.window.zoom_level = Some(level);
537        }
538        if crate::zoom::publish(crate::zoom::Zoom { k, os, level }) {
539            return self.render_and_finish(0);
540        }
541        self.empty_batch()
542    }
543
544    /// Records how large one window is drawing, and wakes the components in that window
545    /// that read it.
546    fn publish_window_zoom(
547        &mut self,
548        window: u32,
549        k: f32,
550        os: f32,
551        level: i32,
552    ) -> Result<(&[u8], i64), ProtocolError> {
553        let level = i8::try_from(level).map_err(|_| ProtocolError::InvalidValueKind(0))?;
554        if crate::zoom::publish_window(window, crate::zoom::Zoom { k, os, level }) {
555            return self.render_and_finish(0);
556        }
557        self.empty_batch()
558    }
559
560    /// Records how many device pixels one dp covers, and wakes whoever reads it.
561    fn publish_density(&mut self, scale: f32) -> Result<(&[u8], i64), ProtocolError> {
562        if crate::density::publish(scale) {
563            return self.render_and_finish(0);
564        }
565        self.empty_batch()
566    }
567
568    /// Records the density of one window, and wakes whoever reads it for that window.
569    fn publish_window_density(
570        &mut self,
571        window: u32,
572        scale: f32,
573    ) -> Result<(&[u8], i64), ProtocolError> {
574        if crate::density::publish_window(window, scale) {
575            return self.render_and_finish(0);
576        }
577        self.empty_batch()
578    }
579
580    /// Hands a window nobody has a node for to the components that listen for one.
581    fn window_requested(&mut self, key: &str, request: u32) -> Result<(&[u8], i64), ProtocolError> {
582        let requested = crate::windows::WindowRequest {
583            key: key.to_owned(),
584            request,
585        };
586        let mut delivered = false;
587        {
588            let _dispatch_guard = EventDispatchGuard::enter();
589            self.runtime
590                .run_in_context(&mut || delivered = crate::windows::deliver_request(&requested));
591        }
592        if !delivered {
593            return self.empty_batch();
594        }
595        self.render_and_finish(0)
596    }
597
598    /// Hands the end of a file dialog to the callback that asked for it.
599    ///
600    /// No node and no handler: a dialog is not in the tree, and the request number names the
601    /// callback. An answer nobody is waiting for is dropped.
602    fn file_dialog_result(
603        &mut self,
604        request: u32,
605        status: crate::schema::FileDialogStatus,
606        filter: u32,
607        paths: &str,
608    ) -> Result<(&[u8], i64), ProtocolError> {
609        let mut delivered = false;
610        {
611            let _dispatch_guard = EventDispatchGuard::enter();
612            self.runtime.run_in_context(&mut || {
613                delivered = crate::file_dialog::deliver(request, status, filter, paths)
614            });
615        }
616        if !delivered {
617            return self.empty_batch();
618        }
619        self.render_and_finish(0)
620    }
621
622    /// Hands what a clipboard read found to the callback that asked for it.
623    ///
624    /// No node and no handler, like a file dialog's end: the request number names the
625    /// callback, and an answer nobody is waiting for is dropped.
626    fn clipboard_text(
627        &mut self,
628        request: u32,
629        status: u32,
630        len: u32,
631        text: &str,
632    ) -> Result<(&[u8], i64), ProtocolError> {
633        let mut delivered = false;
634        {
635            let _dispatch_guard = EventDispatchGuard::enter();
636            self.runtime.run_in_context(&mut || {
637                delivered = crate::clipboard::deliver_read(request, status, len, text)
638            });
639        }
640        if !delivered {
641            return self.empty_batch();
642        }
643        self.render_and_finish(0)
644    }
645
646    /// Hands where a position of a code editor is to the query that asked. The callback
647    /// runs like a handler, and what it changes is in the batch this call returns. An
648    /// answer nobody is waiting for any more is dropped.
649    fn position_rect(
650        &mut self,
651        request: u32,
652        rect: Option<crate::code::CodeRect>,
653    ) -> Result<(&[u8], i64), ProtocolError> {
654        let mut delivered = false;
655        {
656            let _dispatch_guard = EventDispatchGuard::enter();
657            self.runtime.run_in_context(&mut || {
658                delivered = crate::code::deliver_position_rect(request, rect)
659            });
660        }
661        if !delivered {
662            return self.empty_batch();
663        }
664        self.render_and_finish(0)
665    }
666
667    /// Hands the Renderer's answer to whoever asked for it: an operation on a file picked on
668    /// the web when the request number has its top bit set, a storage operation otherwise.
669    ///
670    /// The future that waits for it wakes here, and what the code awaiting it changes is
671    /// in the batch this call returns. An answer nobody is waiting for any more is dropped.
672    fn io_answer(
673        &mut self,
674        request: u32,
675        status: crate::schema::IoStatus,
676        data: &[u8],
677    ) -> Result<(&[u8], i64), ProtocolError> {
678        let mut awaited = false;
679        {
680            let _dispatch_guard = EventDispatchGuard::enter();
681            self.runtime.run_in_context(&mut || {
682                // File operations number their requests with the top bit set and storage
683                // never does, so the number alone says whose answer this is.
684                awaited = if request & crate::picked_file::REQUEST_BIT != 0 {
685                    crate::picked_file::deliver_io(request, status, data)
686                } else {
687                    crate::storage::deliver_answer(request, status, data)
688                }
689            });
690        }
691        if !awaited {
692            return self.empty_batch();
693        }
694        self.render_and_finish(0)
695    }
696
697    /// Hands files the Renderer now holds handles for to whoever asked: a folder's listing or
698    /// child, or a file dialog, which receives them as `webfile:` references.
699    #[allow(clippy::too_many_arguments)]
700    fn file_handles(
701        &mut self,
702        request: u32,
703        status: crate::schema::FileDialogStatus,
704        filter: u32,
705        delivery: crate::schema::FileDelivery,
706        first_handle: u32,
707        names: &str,
708        kinds: &str,
709    ) -> Result<(&[u8], i64), ProtocolError> {
710        let mut delivered = false;
711        {
712            let _dispatch_guard = EventDispatchGuard::enter();
713            self.runtime.run_in_context(&mut || {
714                delivered = crate::picked_file::deliver_handles(
715                    request,
716                    status,
717                    filter,
718                    delivery,
719                    first_handle,
720                    names,
721                    kinds,
722                )
723            });
724        }
725        if !delivered {
726            return self.empty_batch();
727        }
728        self.render_and_finish(0)
729    }
730
731    /// Tells the components that listen that the application was opened with no window.
732    fn application_reopen(&mut self) -> Result<(&[u8], i64), ProtocolError> {
733        let mut delivered = false;
734        {
735            let _dispatch_guard = EventDispatchGuard::enter();
736            self.runtime
737                .run_in_context(&mut || delivered = crate::windows::deliver_reopen());
738        }
739        if !delivered {
740            return self.empty_batch();
741        }
742        self.render_and_finish(0)
743    }
744
745    pub fn dispatch(&mut self, event: HostEvent<'_>) -> Result<(&[u8], i64), ProtocolError> {
746        let _call = HostCallGuard::enter();
747        // These address the Host itself: no node, no handler, and an answer before
748        // anything is looked up.
749        match event.payload {
750            EventPayload::Resync => return self.resync(),
751            EventPayload::DesignSystemResolved(system) => {
752                return self.publish_design_system(system);
753            }
754            EventPayload::LifecycleStart => return self.set_lifecycle_running(true),
755            EventPayload::LifecycleStop => return self.set_lifecycle_running(false),
756            EventPayload::NotificationActivated { action, key } => {
757                if event.node_id != 0 || event.handler_id != 0 {
758                    return Err(ProtocolError::InvalidValueKind(0));
759                }
760                return self.notification_activated(action, key);
761            }
762            EventPayload::NotificationPermissionChanged(state) => {
763                if event.node_id != 0 || event.handler_id != 0 {
764                    return Err(ProtocolError::InvalidValueKind(0));
765                }
766                return self.publish_notification_permission(state);
767            }
768            // About the platform, like the permission above: no node and no handler, and
769            // a repeat of the same answer wakes nobody.
770            EventPayload::ReducedMotionChanged(state) => {
771                if event.node_id != 0 || event.handler_id != 0 {
772                    return Err(ProtocolError::InvalidValueKind(0));
773                }
774                self.batch().begin();
775                if crate::animation::publish_reduced_motion(state) {
776                    self.runtime.render(None);
777                }
778                self.flush_messages();
779                self.arm_scheduler_wake();
780                return Ok((self.runtime.batch_mut().finish()?, 0));
781            }
782            // The system's light or dark appearance, the same kind of report: no node, no
783            // handler, and only a change wakes anyone.
784            EventPayload::ColorSchemeChanged(scheme) => {
785                if event.node_id != 0 || event.handler_id != 0 {
786                    return Err(ProtocolError::InvalidValueKind(0));
787                }
788                self.batch().begin();
789                if crate::theme::publish_system_color_scheme(scheme) {
790                    self.runtime.render(None);
791                }
792                self.flush_messages();
793                self.arm_scheduler_wake();
794                return Ok((self.runtime.batch_mut().finish()?, 0));
795            }
796            // A moment in an animation the Renderer is playing. It names the node the
797            // animation plays on but no handler: whoever registered for animation events
798            // hears about it, and what they change is rendered in the same call, so a
799            // handler that starts the next animation does not leave a frame between them.
800            EventPayload::AnimationEvent {
801                animation_id,
802                kind,
803                property,
804                slot,
805                iteration,
806                elapsed_ms,
807                time_nanos,
808            } => {
809                if event.handler_id != 0 {
810                    return Err(ProtocolError::InvalidValueKind(0));
811                }
812                let moment = crate::animation::AnimationMoment {
813                    node_id: event.node_id,
814                    animation_id,
815                    kind,
816                    property,
817                    slot,
818                    iteration,
819                    elapsed_ms,
820                    time_nanos,
821                };
822                let _dispatch_guard = EventDispatchGuard::enter();
823                let mut delivered = false;
824                self.runtime
825                    .run_in_context(&mut || delivered = crate::animation::deliver(moment));
826                if !delivered {
827                    return self.empty_batch();
828                }
829                return self.render_and_finish(0);
830            }
831            EventPayload::ZoomChanged { k, os, level } => {
832                if event.handler_id != 0 {
833                    return Err(ProtocolError::InvalidValueKind(0));
834                }
835                // In a multi-window application the report names the window it is about
836                //; a single window's is node 0.
837                if event.node_id != 0 {
838                    if !self.runtime.is_window(event.node_id) {
839                        return Err(ProtocolError::InvalidValueKind(0));
840                    }
841                    return self.publish_window_zoom(event.node_id, k, os, level);
842                }
843                return self.publish_zoom(k, os, level);
844            }
845            // The same kind of report as the zoom: no handler, the window it is about in
846            // a multi-window application and node 0 otherwise. The record's decoder
847            // refuses a scale that is not a positive number, and an event built in
848            // process has not been through it, so it is refused here as well.
849            EventPayload::DensityChanged { scale } => {
850                if event.handler_id != 0 || scale.is_nan() || scale <= 0.0 {
851                    return Err(ProtocolError::InvalidValueKind(0));
852                }
853                if event.node_id != 0 {
854                    if !self.runtime.is_window(event.node_id) {
855                        return Err(ProtocolError::InvalidValueKind(0));
856                    }
857                    return self.publish_window_density(event.node_id, scale);
858                }
859                return self.publish_density(scale);
860            }
861            // The two events that belong to the application and to no window: no node and
862            // no handler, and an answer before anything is looked up.
863            EventPayload::WindowRequested { key, request } => {
864                if event.node_id != 0 || event.handler_id != 0 {
865                    return Err(ProtocolError::InvalidValueKind(0));
866                }
867                return self.window_requested(key, request);
868            }
869            EventPayload::ApplicationReopen => {
870                if event.node_id != 0 || event.handler_id != 0 {
871                    return Err(ProtocolError::InvalidValueKind(0));
872                }
873                return self.application_reopen();
874            }
875            // The end of a file dialog: the Host's own business, found by request number.
876            EventPayload::FileDialogResult {
877                request,
878                status,
879                filter,
880                paths,
881            } => {
882                if event.node_id != 0 || event.handler_id != 0 {
883                    return Err(ProtocolError::InvalidValueKind(0));
884                }
885                return self.file_dialog_result(request, status, filter, paths);
886            }
887            // What a clipboard read found: the Host's own business, found by request number.
888            EventPayload::ClipboardText {
889                request,
890                status,
891                len,
892                text,
893            } => {
894                if event.node_id != 0 || event.handler_id != 0 {
895                    return Err(ProtocolError::InvalidValueKind(0));
896                }
897                return self.clipboard_text(request, status, len, text);
898            }
899            // The answer to a storage operation, or to an operation on a file picked on the
900            // web, found by request number like a clipboard read.
901            EventPayload::IoAnswer {
902                request,
903                status,
904                data,
905            } => {
906                if event.node_id != 0 || event.handler_id != 0 {
907                    return Err(ProtocolError::InvalidValueKind(0));
908                }
909                return self.io_answer(request, status, data);
910            }
911            // Files the Renderer holds handles for, for a dialog or a folder that asked.
912            EventPayload::FileHandles {
913                request,
914                status,
915                filter,
916                delivery,
917                first_handle,
918                names,
919                kinds,
920            } => {
921                if event.node_id != 0 || event.handler_id != 0 {
922                    return Err(ProtocolError::InvalidValueKind(0));
923                }
924                return self.file_handles(
925                    request,
926                    status,
927                    filter,
928                    delivery,
929                    first_handle,
930                    names,
931                    kinds,
932                );
933            }
934            // Where a position of a code editor is on screen: the answer to a query an
935            // application asked, found by request number. It names the editor it is about
936            // and no handler.
937            EventPayload::PositionRect { request, rect } => {
938                if event.handler_id != 0 {
939                    return Err(ProtocolError::InvalidValueKind(0));
940                }
941                return self.position_rect(request, rect);
942            }
943            // Where Android keeps the application's files. Operations that were waiting for
944            // it go to the storage thread, which wakes them when they finish.
945            // Where one window's platform views are made: the Host's own business, named by
946            // the window it is about. Whoever subscribed is woken and the change rendered.
947            EventPayload::NativeViewParent {
948                handle,
949                kind,
950                scale,
951            } => {
952                if event.handler_id != 0
953                    || (event.node_id != 0 && !self.runtime.is_window(event.node_id))
954                {
955                    return Err(ProtocolError::InvalidValueKind(0));
956                }
957                let parent = crate::native_view::NativeParent {
958                    window: event.node_id,
959                    handle,
960                    kind,
961                    scale,
962                };
963                if crate::native_view::publish(parent) {
964                    return self.render_and_finish(0);
965                }
966                return self.empty_batch();
967            }
968            EventPayload::StorageLocation(path) => {
969                if event.node_id != 0 || event.handler_id != 0 {
970                    return Err(ProtocolError::InvalidValueKind(0));
971                }
972                crate::storage::set_android_files(path);
973                return self.empty_batch();
974            }
975            _ => {}
976        }
977        // The window's size belongs to no node and no handler: the Renderer measures the
978        // root content and reports it. It takes the same synchronous path as every other
979        // event, so the batch it produces is applied in the frame that asked for it.
980        if let EventPayload::WindowSizeChanged {
981            width_dp,
982            height_dp,
983            class,
984            height_class,
985            safe_area_top,
986            safe_area_leading,
987            safe_area_trailing,
988        } = event.payload
989        {
990            // Node id zero is the window; anything else is one of its nodes. One event
991            // for both, because they are the same fact measured at two scales and a
992            // second way of saying it would be a second thing to keep in step.
993            let size = crate::window::WindowSize::new(width_dp, height_dp, class, height_class)
994                .with_safe_area(crate::window::WindowSafeArea {
995                    top: safe_area_top,
996                    leading: safe_area_leading,
997                    trailing: safe_area_trailing,
998                });
999            // A window's report names the window's node, and that is not an
1000            // observed node: it is the same fact for a window of its own.
1001            if event.node_id != 0 && self.runtime.is_window(event.node_id) {
1002                if !crate::window::publish_window(event.node_id, size) {
1003                    return self.empty_batch();
1004                }
1005                return self.render_and_finish(0);
1006            }
1007            if event.node_id != 0 {
1008                let woke = self
1009                    .runtime
1010                    .size_token(event.node_id)
1011                    .is_some_and(|token| crate::window::publish_node(token, size));
1012                if !woke {
1013                    return self.empty_batch();
1014                }
1015                return self.render_and_finish(0);
1016            }
1017            crate::window::publish(size);
1018            return self.render_and_finish(0);
1019        }
1020        // The action on a transient message. It belongs to no node, because the message is
1021        // not in the tree, so it is found by its handler id alone and the event carries the
1022        // "no node" id the Renderer uses for anything the tree does not own.
1023        let message_action = match event.payload {
1024            EventPayload::Clicked => crate::message::take_action(event.handler_id),
1025            _ => None,
1026        };
1027        if let Some(mut action) = message_action {
1028            if event.node_id != 0 {
1029                return Err(ProtocolError::InvalidValueKind(0));
1030            }
1031            let _dispatch_guard = EventDispatchGuard::enter();
1032            self.runtime.run_in_context(&mut *action);
1033            return self.render_and_finish(0);
1034        }
1035        // Everything else names a handler on a node, and handlers belong to the runtime.
1036        if let EventPayload::ProtocolError { .. } = event.payload {
1037            return Err(ProtocolError::InvalidValueKind(0));
1038        }
1039        let _dispatch_guard = EventDispatchGuard::enter();
1040        let result = self.runtime.handle_event(&event)?;
1041        self.render_and_finish(result)
1042    }
1043
1044    pub fn render_frame(&mut self, frame_time_nanos: u64) -> Result<&[u8], ProtocolError> {
1045        let _call = HostCallGuard::enter();
1046        if LIFECYCLE_SUPPRESSED.load(Ordering::Acquire) {
1047            // The platform has the UI off screen and the Renderer called anyway, which it
1048            // does for one reason: a notification was queued, and a notification is what
1049            // has to get out while nobody is looking. Only that goes. The components are
1050            // not rendered and the held frame request is left held, so timers and
1051            // animations stay suppressed until start delivers it.
1052            self.batch().begin();
1053            self.flush_notifications();
1054            return self.runtime.batch_mut().finish();
1055        }
1056        FRAME_REQUESTED.store(false, Ordering::Release);
1057        EVENT_DISPATCH_ACTIVE.store(false, Ordering::Release);
1058        DEFERRED_FRAME_REQUEST.store(false, Ordering::Release);
1059        // A browser has no thread to wait for midnight on, so the date is checked here,
1060        // before the components render, and a reader it wakes renders in this frame.
1061        #[cfg(target_family = "wasm")]
1062        crate::time::on_frame();
1063        self.batch().begin();
1064        self.runtime.render(Some(frame_time_nanos));
1065        self.flush_pending_appends();
1066        self.flush_messages();
1067        self.arm_scheduler_wake();
1068        self.runtime.batch_mut().finish()
1069    }
1070
1071    /// Queues a streamed tail for the next frame. Tokens arriving inside one frame are
1072    /// merged into a single `AppendText` record, so a token never costs a batch of its own.
1073    pub fn append_text(&mut self, node_id: u32, tail: &str) {
1074        match self
1075            .pending_appends
1076            .iter_mut()
1077            .find(|pending| pending.node_id == node_id)
1078        {
1079            Some(pending) => {
1080                pending.text.push_str(tail);
1081                pending.dirty = true;
1082            }
1083            None => self.pending_appends.push(PendingAppend {
1084                node_id,
1085                text: tail.to_owned(),
1086                dirty: true,
1087            }),
1088        }
1089        // Repeated calls collapse into one frame request; see `request_frame_from_worker`.
1090        request_frame_from_worker();
1091    }
1092
1093    /// Writes whatever the tree asked to say during this call into the batch it produced.
1094    ///
1095    /// A message therefore arrives in the same call as the change it is about, which is
1096    /// what makes "deleted" and the row disappearing one frame rather than two.
1097    fn flush_messages(&mut self) {
1098        // A theme the application changed during this call, one record for the whole
1099        // tree. Kept as the Host's own as well, so a resync rebuilds with it.
1100        if let Some(theme) = crate::theme::take_pending() {
1101            self.theme = theme;
1102            self.batch().set_theme(theme);
1103        }
1104        // A zoom level the application asked for, on the window record that carries it.
1105        if let Some(level) = crate::zoom::take_pending_level() {
1106            self.window.zoom_level = Some(level);
1107            let window = self.window;
1108            self.batch().set_window(window);
1109        }
1110        // What the application asked of a window that happens once: forward, a theme of its
1111        // own, a zoom level of its own.
1112        {
1113            let batch = self.runtime.batch_mut();
1114            crate::windows::drain_commands(|command| match command {
1115                crate::windows::Command::Focus(node_id) => {
1116                    batch.write(Mutation::FocusWindow { node_id });
1117                }
1118                crate::windows::Command::Theme(node_id, theme) => {
1119                    batch.write(Mutation::SetWindowTheme { node_id, theme });
1120                }
1121                crate::windows::Command::ZoomLevel(node_id, level) => {
1122                    batch.write(Mutation::SetProp {
1123                        node_id,
1124                        property: crate::schema::PropertyKind::WindowZoomLevel,
1125                        value: PropertyValue::Integer(i64::from(level)),
1126                    });
1127                }
1128            });
1129        }
1130        let batch = self.runtime.batch_mut();
1131        // Registrations first. Not because the Renderer needs them first, it applies the
1132        // whole batch before drawing any of it, but because a batch read by a person
1133        // debugging one reads in the order the screen was built.
1134        crate::asset::drain(|pending| {
1135            batch.register_asset(pending.asset_id, pending.kind, pending.bytes);
1136        });
1137        crate::asset::drain_releases(|asset_id| batch.release_asset(asset_id));
1138        crate::message::drain(|message| {
1139            batch.show_placed_message(
1140                message.handler_id,
1141                &message.text,
1142                &message.action,
1143                message.duration,
1144                message.placement,
1145                message.offset_dp,
1146            );
1147        });
1148        self.flush_notifications();
1149        // Text the application asked to put on the clipboard, in the order it asked.
1150        let batch = self.runtime.batch_mut();
1151        crate::clipboard::drain(|text| batch.set_clipboard_text(text));
1152        // Clipboard reads, each answered later by one event with its number.
1153        let batch = self.runtime.batch_mut();
1154        crate::clipboard::drain_reads(|request| batch.read_clipboard(request));
1155        // Storage operations the Renderer carries out, on the web, in the order asked.
1156        let batch = self.runtime.batch_mut();
1157        crate::storage::drain_calls(|call| batch.storage_call(call));
1158        // File dialogs an application asked for, from a handler, a component or a worker.
1159        let batch = self.runtime.batch_mut();
1160        crate::file_dialog::drain(|request| batch.file_dialog(request));
1161        // Handles the Host let go of, then the operations asked of the files it holds.
1162        let batch = self.runtime.batch_mut();
1163        let calls = std::cell::RefCell::new(batch);
1164        crate::picked_file::drain(
1165            |handle| calls.borrow_mut().release_file_handle(handle),
1166            |call| calls.borrow_mut().file_call(call),
1167        );
1168        // Animations an application started from a handler, a component or a worker.
1169        let batch = self.runtime.batch_mut();
1170        crate::animation::drain(|mutation| batch.write(mutation));
1171    }
1172
1173    /// Writes the notification commands waiting in the Host into this batch.
1174    ///
1175    /// Workers queue them from their own threads; this is the one place they leave, on the
1176    /// UI thread, inside a call. One atomic read when there are none.
1177    fn flush_notifications(&mut self) {
1178        let batch = self.runtime.batch_mut();
1179        let posts = crate::notification::drain(|command| batch.notification(command));
1180        crate::notification::note_posted(posts);
1181    }
1182
1183    fn flush_pending_appends(&mut self) {
1184        let batch = self.runtime.batch_mut();
1185        for pending in &self.pending_appends {
1186            if pending.dirty {
1187                batch.append_text_node(pending.node_id, &pending.text);
1188            }
1189        }
1190        // Buffers are kept so steady-state streaming reuses their capacity and a streamed
1191        // token does not allocate.
1192        for pending in &mut self.pending_appends {
1193            pending.text.clear();
1194            pending.dirty = false;
1195        }
1196    }
1197
1198    /// Registers one asset and returns the batch that carries it.
1199    ///
1200    /// The bytes are copied once here and once more by the Renderer into its cache. After
1201    /// that the id is all that travels, so drawing the same image every frame costs a
1202    /// fixed-layout property record and nothing else.
1203    pub fn register_asset(
1204        &mut self,
1205        asset_id: u32,
1206        kind: AssetKind,
1207        bytes: &[u8],
1208    ) -> Result<&[u8], ProtocolError> {
1209        let batch = self.runtime.batch_mut();
1210        batch.begin();
1211        batch.register_asset(asset_id, kind, bytes);
1212        batch.finish()
1213    }
1214
1215    /// Registers an icon by the meaning it carries. The Renderer holds the artwork for
1216    /// every design system, so what crosses is the role and not a picture or a name.
1217    pub fn register_icon(&mut self, asset_id: u32, role: IconRole) -> Result<&[u8], ProtocolError> {
1218        self.register_asset(
1219            asset_id,
1220            AssetKind::VectorIcon,
1221            &(role as u16).to_le_bytes(),
1222        )
1223    }
1224
1225    /// Drops the asset from the Renderer's cache. Using the id afterwards is a reported
1226    /// protocol error.
1227    pub fn release_asset(&mut self, asset_id: u32) -> Result<&[u8], ProtocolError> {
1228        let batch = self.runtime.batch_mut();
1229        batch.begin();
1230        batch.release_asset(asset_id);
1231        batch.finish()
1232    }
1233
1234    pub fn set_text(
1235        &mut self,
1236        node_id: u32,
1237        text: &str,
1238        selection: Option<Selection>,
1239    ) -> Result<&[u8], ProtocolError> {
1240        let batch = self.runtime.batch_mut();
1241        batch.begin();
1242        batch.set_text_node(node_id, text, selection);
1243        batch.finish()
1244    }
1245
1246    fn arm_scheduler_wake(&mut self) {
1247        let mut context = Context::from_waker(&self.frame_waker);
1248        if self.runtime.poll_work(&mut context).is_ready() {
1249            request_frame_from_worker();
1250        }
1251    }
1252}
1253
1254/// Holds the thread's `Host` and, crucially, keeps it out of thread-local teardown.
1255///
1256/// Dropping a runtime can reach back into thread-locals of its own: a Dioxus
1257/// `VirtualDom` does. Thread-local destruction order is unspecified, so if the UI thread
1258/// ends without `compose_rust_host_shutdown`, that drop can run after those locals are
1259/// already gone and panic with "cannot access a TLS value during or after destruction".
1260/// A panic in a destructor is non-unwinding: it aborts the process, which
1261/// is exactly what must not happen: a protocol or teardown fault has to stay recoverable.
1262///
1263/// So the slot empties itself and leaks the `Host` when the thread is tearing down. An
1264/// orderly `shutdown` still drops it properly; only the unorderly path leaks, and that
1265/// path is a thread ending anyway.
1266struct HostSlot(RefCell<Option<Host>>);
1267
1268impl Drop for HostSlot {
1269    fn drop(&mut self) {
1270        std::mem::forget(self.0.borrow_mut().take());
1271    }
1272}
1273
1274impl std::ops::Deref for HostSlot {
1275    type Target = RefCell<Option<Host>>;
1276
1277    fn deref(&self) -> &Self::Target {
1278        &self.0
1279    }
1280}
1281
1282/// The launched application, as the factory for its runtime.
1283///
1284/// The runtime and every `compose_rust_host_*` call run on the Renderer UI thread, and
1285/// that thread is not always the one that called `launch`: with `LoopMode::Renderer` on a
1286/// toolkit renderer the Rust main thread blocks inside `compose_rust_renderer_run` while
1287/// Compose composes on the toolkit's own thread, and on Windows the Host runs the loop on
1288/// a thread it makes for its stack (`run_renderer_loop`). So the factory, unlike the `Host` it builds, has to be reachable
1289/// across threads, which is why it is `Send + Sync` and the runtime it makes is not.
1290///
1291/// `shutdown` deliberately leaves this set: it belongs to `launch`, not to one UI thread's
1292/// `Host`. That is also what `LoopMode::Platform` needs, where the Renderer may tear the
1293/// Host down and initialize it again (Android recreates its surface on a configuration
1294/// change) without relaunching.
1295static APP: Mutex<Option<RuntimeFactory>> = Mutex::new(None);
1296
1297/// Chosen by `LaunchBuilder::with_theme`, read once when the Host is built.
1298static THEME: Mutex<Theme> = Mutex::new(Theme::unified(crate::schema::DesignSystem::Material3));
1299
1300/// Chosen by `LaunchBuilder::with_window`, read once when the Host is built.
1301static WINDOW: Mutex<crate::schema::Window> = Mutex::new(crate::schema::Window::new());
1302
1303thread_local! {
1304    static HOST: HostSlot = const { HostSlot(RefCell::new(None)) };
1305}
1306
1307fn launched_app() -> Option<RuntimeFactory> {
1308    APP.lock().map_or(None, |app| (*app).clone())
1309}
1310
1311fn launched_window() -> crate::schema::Window {
1312    WINDOW
1313        .lock()
1314        .map_or_else(|error| *error.into_inner(), |window| *window)
1315}
1316
1317fn launched_theme() -> Theme {
1318    THEME
1319        .lock()
1320        .map_or_else(|error| *error.into_inner(), |theme| *theme)
1321}
1322
1323#[derive(Clone, Copy, Debug)]
1324pub struct LaunchBuilder {
1325    mode: LoopMode,
1326    theme: Theme,
1327    window: crate::schema::Window,
1328    /// Kept as a leaked string so the builder stays `Copy`. It is set once per launch.
1329    identifier: Option<&'static str>,
1330}
1331
1332impl Default for LaunchBuilder {
1333    fn default() -> Self {
1334        Self {
1335            mode: LoopMode::Renderer,
1336            theme: Theme::default(),
1337            window: crate::schema::Window::new(),
1338            identifier: None,
1339        }
1340    }
1341}
1342
1343impl LaunchBuilder {
1344    pub fn new() -> Self {
1345        Self::default()
1346    }
1347
1348    pub fn with_mode(mut self, mode: LoopMode) -> Self {
1349        self.mode = mode;
1350        self
1351    }
1352
1353    /// `Theme::unified` for one design system everywhere, `Theme::adaptive` to follow the
1354    /// host platform. Not calling this follows the host platform, falling back to
1355    /// Material 3.
1356    pub fn with_theme(mut self, theme: Theme) -> Self {
1357        self.theme = theme;
1358        self
1359    }
1360
1361    /// What the application asks of its own window: its size, and whether it wears the
1362    /// platform's title bar or has content run into it.
1363    ///
1364    /// Not calling this gets a modern window that the Renderer sizes. The window belongs
1365    /// to the Renderer and most of what it looks like is the design system's, so what can
1366    /// be said here is short on purpose: nothing names a colour, a corner, or where the
1367    /// window buttons go.
1368    pub fn with_window(mut self, window: crate::schema::Window) -> Self {
1369        let (mode, policy) = (self.window.mode, self.window.last_window_closed);
1370        self.window = window;
1371        // A builder that already asked for windows keeps asking, whichever order the two
1372        // calls came in.
1373        if mode == crate::schema::WindowMode::Windows {
1374            self.window.mode = mode;
1375            self.window.last_window_closed = policy;
1376        }
1377        self
1378    }
1379
1380    /// Runs several windows in one process: the root's children are `Window`
1381    /// nodes, each a platform window, and they share one composition and one set of
1382    /// states. Without this the root's content fills the one window.
1383    ///
1384    /// The window that closes last ends the application, except on macOS where the
1385    /// application stays; [`LaunchBuilder::on_last_window_closed`] chooses.
1386    pub fn windows(mut self) -> Self {
1387        self.window = self.window.with_windows();
1388        self
1389    }
1390
1391    /// What happens when the last `Window` node is removed. Mobile platforms
1392    /// ignore it: the system decides how long the process lives.
1393    pub fn on_last_window_closed(mut self, policy: crate::schema::LastWindowClosed) -> Self {
1394        self.window = self.window.with_last_window_closed(policy);
1395        self
1396    }
1397
1398    /// The application's identifier, which names its storage (`compose_rust::storage`).
1399    ///
1400    /// Use the same value as `[bundle] identifier` in the application's `Dioxus.toml`,
1401    /// such as `"dev.darkpyonix.composerust.samples.todo"`. It is not read from anywhere
1402    /// else: a bundle, a package name or an executable name would give the same program a
1403    /// different storage depending on how it was started, and the web has none of them.
1404    ///
1405    /// It is 1 to 255 bytes of ASCII letters, digits, `.` and `-`, because it names a
1406    /// directory and a browser database as it is. One that is not stops the launch before
1407    /// anything starts, with a sentence that says what is wrong and a failing exit status.
1408    /// An application that never uses storage does not need one.
1409    pub fn identifier(mut self, identifier: impl Into<String>) -> Self {
1410        self.identifier = Some(Box::leak(identifier.into().into_boxed_str()));
1411        self
1412    }
1413
1414    /// Runs the application whose tree `runtime` builds. Does not return while it is
1415    /// running, and ends the process with a failing status if the renderer loop could
1416    /// not run at all.
1417    ///
1418    /// `runtime` is called on the Renderer's UI thread each time a Host is made: once at
1419    /// start, and again whenever the Renderer asks for the whole tree back.
1420    ///
1421    /// On Windows that thread is one this crate makes, named `compose-rust-ui`, with a
1422    /// 64 MB stack, and the calling thread waits for it: a program's main thread there has
1423    /// 1 MB unless its own link asked for more, which a screen of ordinary depth overflows.
1424    /// So what runs before this call is on the main thread and what runs inside it, the
1425    /// composables and their handlers, is not, and a thread-local set before launching is
1426    /// not the one the UI reads. That includes this crate's own: a handler registered or a
1427    /// request made before launching (`notification::on_activation`,
1428    /// `windows::on_window_request`, `clipboard::set_text`, `show_message`, `set_theme`,
1429    /// a storage read) is kept on the main thread and the UI never sees it, so make those
1430    /// from the root composable or later, on every platform. What may come before is state
1431    /// made with `mutable_state_of`, the builder's own choices, and the assets the theme
1432    /// and the window name, which keep their ids. On macOS and Linux the calling thread is the UI thread.
1433    /// An application that runs the renderer loop itself, without launching, has whatever
1434    /// stack its thread has, and on Windows has to ask its own link for more.
1435    ///
1436    /// Exiting rather than returning is the point. Launching is the last statement of
1437    /// `main` in every application that uses this crate, so returning from it means `main`
1438    /// returns, which means the process exits 0. A window that never opened would then be
1439    /// indistinguishable from a program that did its work and stopped.
1440    pub fn launch_runtime(self, runtime: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static) {
1441        let status = self.try_launch_runtime(runtime);
1442        if status != STATUS_OK {
1443            std::process::exit(EXIT_FAILURE);
1444        }
1445    }
1446
1447    /// [`LaunchBuilder::launch_runtime`] without the exit: the status the renderer loop
1448    /// ended with, handed back for a caller that has its own idea of what to do with it.
1449    pub fn try_launch_runtime(
1450        self,
1451        runtime: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static,
1452    ) -> i32 {
1453        self.launch_through(runtime, renderer_api().run, HOST_MAKES_UI_THREAD)
1454    }
1455
1456    /// The launch itself, with the renderer loop and where it runs said by the caller, so a
1457    /// test can drive the loop the way a renderer does on the thread the Host makes.
1458    fn launch_through(
1459        self,
1460        runtime: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static,
1461        run: extern "C" fn() -> c_int,
1462        on_ui_thread: bool,
1463    ) -> i32 {
1464        // Before anything starts: an identifier that cannot name a directory would only
1465        // fail later, at the first save, far from the line that set it.
1466        if let Some(Err(problem)) = self.identifier.map(crate::storage::validate_identifier) {
1467            eprintln!("compose-rust: {problem}");
1468            return STATUS_INVALID_IDENTIFIER;
1469        }
1470        crate::storage::set_identifier(self.identifier);
1471        let factory: RuntimeFactory = Arc::new(runtime);
1472        if let Ok(mut slot) = APP.lock() {
1473            *slot = Some(factory);
1474        }
1475        if let Ok(mut slot) = THEME.lock() {
1476            *slot = self.theme;
1477        }
1478        // A palette that leaves something unreadable is said once, at start, in a debug
1479        // build. It does not stop the launch: a screen whose contrast is a little short is
1480        // better than no screen, and what to do about it is the application's call.
1481        #[cfg(debug_assertions)]
1482        for line in palette_report(&self.theme) {
1483            eprintln!("{line}");
1484        }
1485        if let Ok(mut slot) = WINDOW.lock() {
1486            *slot = self.window;
1487        }
1488        // Under `LoopMode::Platform` the platform owns the loop and calls in through the
1489        // boundary when it is ready. There is nothing to run and nothing to fail.
1490        if self.mode != LoopMode::Renderer {
1491            return STATUS_OK;
1492        }
1493        run_renderer_loop(run, on_ui_thread)
1494    }
1495}
1496
1497/// How much stack the UI thread gets where the Host is the one that makes it: 64 MB.
1498///
1499/// Compose composes, measures and draws a tree by recursion, one group of frames per level
1500/// of nesting and per modifier, and the Kotlin/Native renderer does all of it on the thread
1501/// its loop runs on. On Windows that was the thread that called `launch`, the program's
1502/// main thread, whose stack is whatever the executable's header says: 1 MB unless the
1503/// application's own link asked for more, where macOS and Linux give a main thread 8 MB.
1504/// An ordinary screen overflowed it in the first frames and the application ended with
1505/// "thread 'main' has overflowed its stack" right after its window opened.
1506///
1507/// The number is a reservation of address space and not memory. Windows commits a stack a
1508/// page at a time as it is first touched, so a screen that needs 300 KB still costs 300 KB,
1509/// and 64 MB out of a 64-bit address space is nothing. It is eight times what the other
1510/// desktop platforms give, because the Windows renderer's frames have been the largest of
1511/// the three, and far above what a tree anyone would write needs, so the limit a deep tree
1512/// meets is not this one.
1513const UI_THREAD_STACK_BYTES: usize = 64 * 1024 * 1024;
1514
1515/// What the UI thread is called where the Host makes it. Rust says the name of the thread
1516/// whose stack overflowed or that panicked, so this is what such a line names.
1517const UI_THREAD_NAME: &str = "compose-rust-ui";
1518
1519/// Overrides [`UI_THREAD_STACK_BYTES`], in bytes, where the Host makes the UI thread.
1520///
1521/// For finding out, not for shipping: a check sets it small to show how deep a tree a given
1522/// stack holds, and an application that meets the limit after all can raise it without a
1523/// new build. Anything that is not a whole number above zero is said on the standard error
1524/// and ignored.
1525const UI_THREAD_STACK_VARIABLE: &str = "COMPOSE_RUST_UI_STACK_BYTES";
1526
1527/// Whether the Host makes the thread the renderer loop runs on, or runs it on the caller.
1528///
1529/// Windows only. The window there belongs to whichever thread makes it and pumps its
1530/// messages, and nothing asks for that to be the program's first thread, so the Host is
1531/// free to make one with the stack it wants.
1532///
1533/// macOS stays on the caller, always: AppKit runs on the process main thread and nowhere
1534/// else. Linux stays too. Its main thread has 8 MB by default and the limit is the user's
1535/// to raise (`ulimit -s`), nothing has overflowed there, and moving a working loop to
1536/// another thread for no measured reason would be a risk taken for nothing. Android, iOS
1537/// and the web never come here with a loop to run: the platform owns it.
1538const HOST_MAKES_UI_THREAD: bool = cfg!(windows);
1539
1540/// Runs the renderer loop to its end and gives back the status it ended with.
1541///
1542/// With `on_ui_thread` the loop runs on a thread made here with a stack of its own, and the
1543/// caller waits for it. Everything the renderer does happens inside `run`: it starts, opens
1544/// its window, reads its messages, and calls the Host, which builds the runtime from the
1545/// launched factory on the thread that calls in. So the whole UI is on that one thread, and
1546/// all that crosses to it is `run` itself, a function pointer, and the assets the caller
1547/// registered for its theme and its window: static bytes, ids and kinds. The factory and
1548/// the launch choices were put in statics before this, and the factory is `Send + Sync` by
1549/// its type.
1550///
1551/// The caller sees what it saw before: the same status comes back, and a panic that ends
1552/// the UI thread is raised again here with its own payload. In practice a panic does not
1553/// get that far, as it did not before: the Host's exports catch one and answer
1554/// `STATUS_PANIC`, and one that would leave `run`, a C function, ends the process.
1555///
1556/// If the thread cannot be made at all the loop runs on the caller, which is what it did
1557/// before there was a thread, and the reason is said first.
1558fn run_renderer_loop(run: extern "C" fn() -> c_int, on_ui_thread: bool) -> i32 {
1559    if !on_ui_thread {
1560        return run();
1561    }
1562    let stack_bytes = ui_thread_stack_bytes(
1563        std::env::var(UI_THREAD_STACK_VARIABLE).ok().as_deref(),
1564        |problem| eprintln!("compose-rust: {problem}"),
1565    );
1566    // What the caller registered while it built its theme and its window goes with the
1567    // loop, so the ids those name are the same ids on the thread the Host starts on.
1568    let assets = crate::asset::registrations();
1569    let on_thread = move || {
1570        crate::asset::adopt(assets);
1571        run()
1572    };
1573    match run_on_ui_thread(stack_bytes, on_thread) {
1574        Ok(status) => status,
1575        Err(error) => {
1576            eprintln!(
1577                "compose-rust: could not start the UI thread with a {stack_bytes} byte stack \
1578                 ({error}). Running the renderer on the calling thread, whose stack may be too \
1579                 small for a deep screen."
1580            );
1581            run()
1582        }
1583    }
1584}
1585
1586/// The stack size to make the UI thread with, given what the override variable holds.
1587fn ui_thread_stack_bytes(requested: Option<&str>, mut report: impl FnMut(String)) -> usize {
1588    let Some(requested) = requested else {
1589        return UI_THREAD_STACK_BYTES;
1590    };
1591    match requested.trim().parse::<usize>() {
1592        Ok(bytes) if bytes > 0 => bytes,
1593        _ => {
1594            report(format!(
1595                "{UI_THREAD_STACK_VARIABLE} is {requested:?}, which is not a number of bytes \
1596                 above zero. Using {UI_THREAD_STACK_BYTES}."
1597            ));
1598            UI_THREAD_STACK_BYTES
1599        }
1600    }
1601}
1602
1603/// Runs `work` on a new thread named [`UI_THREAD_NAME`] with `stack_bytes` of stack, waits
1604/// for it, and returns what it returned. `Err` only when the thread could not be made, in
1605/// which case `work` never ran.
1606///
1607/// A panic in `work` is raised again on the calling thread with the same payload, so the
1608/// caller cannot tell it from one of its own. A stack overflow is not a panic: Rust's
1609/// overflow handler covers every thread the standard library makes, this one included, so
1610/// the process still ends with "thread 'compose-rust-ui' has overflowed its stack".
1611fn run_on_ui_thread<T: Send + 'static>(
1612    stack_bytes: usize,
1613    work: impl FnOnce() -> T + Send + 'static,
1614) -> std::io::Result<T> {
1615    let thread = std::thread::Builder::new()
1616        .name(UI_THREAD_NAME.to_owned())
1617        .stack_size(stack_bytes)
1618        .spawn(work)?;
1619    match thread.join() {
1620        Ok(value) => Ok(value),
1621        Err(payload) => std::panic::resume_unwind(payload),
1622    }
1623}
1624
1625/// [`LaunchBuilder::launch_runtime`] with every choice left to its default.
1626pub fn launch_runtime(runtime: impl Fn() -> Box<dyn Runtime> + Send + Sync + 'static) {
1627    LaunchBuilder::new().launch_runtime(runtime);
1628}
1629
1630/// What a theme's palette leaves short of contrast, as lines to print.
1631///
1632/// Every system an adaptive theme could land on is checked, because which one it lands on
1633/// is decided by the Renderer on a machine this code has not seen. A unified theme is
1634/// checked against the one system it names. Empty where there is no palette or nothing is
1635/// short.
1636pub fn palette_report(theme: &Theme) -> Vec<String> {
1637    let Some(palette) = theme.palette else {
1638        return Vec::new();
1639    };
1640    let systems: Vec<crate::schema::DesignSystem> = if theme.adaptive {
1641        crate::schema::DESIGN_SYSTEM_SCHEMA
1642            .iter()
1643            .filter_map(|variant| crate::schema::DesignSystem::try_from(variant.tag).ok())
1644            .collect()
1645    } else {
1646        vec![theme.design_system]
1647    };
1648    systems
1649        .into_iter()
1650        .flat_map(|system| {
1651            palette.check(system).into_iter().map(move |violation| {
1652                format!("compose-rust: palette under {system:?}: {violation}")
1653            })
1654        })
1655        .collect()
1656}
1657
1658fn parse_handshake(bytes: &[u8]) -> Result<LoopMode, ProtocolError> {
1659    if bytes.len() < 12 {
1660        return Err(ProtocolError::Truncated);
1661    }
1662    let hash = u64::from_le_bytes(
1663        bytes[0..8]
1664            .try_into()
1665            .map_err(|_| ProtocolError::Truncated)?,
1666    );
1667    let version = u16::from_le_bytes(
1668        bytes[8..10]
1669            .try_into()
1670            .map_err(|_| ProtocolError::Truncated)?,
1671    );
1672    if hash != SCHEMA_HASH || version != PROTOCOL_VERSION {
1673        // Say what did not match, and say it here rather than leaving the status code to
1674        // carry it. A mismatch means the two halves were generated from different
1675        // versions of the schema, which on a desktop build means a renderer library
1676        // compiled before the last codegen run. The window still opens, because the
1677        // renderer stands it up before it asks, so the only thing on screen is an empty
1678        // page in the default theme: a symptom that looks like a blank application rather
1679        // than like a stale build, and one that cost a morning to read the first time.
1680        eprintln!(
1681            "compose-rust: the renderer was built from a different schema than this              program. It sent hash {hash:#x} version {version}, and this build expects              hash {SCHEMA_HASH:#x} version {PROTOCOL_VERSION}. Rebuild the renderer after              running codegen; if it was already rebuilt, its build directory is holding a              cached copy of the generated protocol and has to be cleared."
1682        );
1683        return Err(ProtocolError::InvalidEnvelope);
1684    }
1685    match bytes[10] {
1686        0 => Ok(LoopMode::Renderer),
1687        1 => Ok(LoopMode::Platform),
1688        other => Err(ProtocolError::InvalidValueKind(u16::from(other))),
1689    }
1690}
1691
1692unsafe fn input_slice<'a>(ptr: *const u8, len: u32) -> Result<&'a [u8], ProtocolError> {
1693    if len == 0 {
1694        return Ok(&[]);
1695    }
1696    if ptr.is_null() {
1697        return Err(ProtocolError::Truncated);
1698    }
1699    // SAFETY: The C caller promises a readable buffer of `len` bytes for this call.
1700    Ok(unsafe { std::slice::from_raw_parts(ptr, len as usize) })
1701}
1702
1703unsafe fn write_batch(
1704    out: *mut MutationBatch,
1705    bytes: &[u8],
1706    result: i64,
1707) -> Result<(), ProtocolError> {
1708    if out.is_null() {
1709        return Err(ProtocolError::Truncated);
1710    }
1711    let len = u32::try_from(bytes.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1712    // SAFETY: Null was rejected and the C caller promises writable storage.
1713    unsafe {
1714        out.write(MutationBatch {
1715            ptr: bytes.as_ptr(),
1716            len,
1717            result,
1718        });
1719    }
1720    Ok(())
1721}
1722
1723/// A call-order failure is not a malformed message: the boundary declares distinct statuses
1724/// so the Renderer can tell "you called me too early" from "your bytes were wrong". The
1725/// closures below therefore yield a status directly.
1726fn ffi_status(operation: impl FnOnce() -> Result<(), i32>) -> i32 {
1727    // There is no channel for the Host to raise a ProtocolError event back to the Renderer:
1728    // the boundary is a synchronous call that returns a status, and events only travel
1729    // Renderer to Host. Malformed calls therefore return STATUS_PROTOCOL_ERROR.
1730    match catch_unwind(AssertUnwindSafe(operation)) {
1731        Ok(Ok(())) => STATUS_OK,
1732        Ok(Err(status)) => status,
1733        Err(_) => STATUS_PANIC,
1734    }
1735}
1736
1737/// Every `ProtocolError` leaving an export is reported as one status code.
1738fn protocol_error(_error: ProtocolError) -> i32 {
1739    STATUS_PROTOCOL_ERROR
1740}
1741
1742#[unsafe(no_mangle)]
1743/// Initializes the UI-thread Host from the handshake and returns the initial batch.
1744///
1745/// # Safety
1746/// `handshake` must address `len` readable bytes and `out` must be writable.
1747pub unsafe extern "C" fn compose_rust_host_init(
1748    handshake: *const u8,
1749    len: u32,
1750    out: *mut MutationBatch,
1751) -> i32 {
1752    ffi_status(|| {
1753        // SAFETY: Validated according to the function's C ABI contract.
1754        let bytes = unsafe { input_slice(handshake, len) }.map_err(protocol_error)?;
1755        let _mode = parse_handshake(bytes).map_err(protocol_error)?;
1756        let factory = launched_app().ok_or(STATUS_NOT_INITIALIZED)?;
1757        HOST.with(|slot| {
1758            let mut host_slot = slot.borrow_mut();
1759            if host_slot.is_some() {
1760                return Err(STATUS_ALREADY_INITIALIZED);
1761            }
1762            let mut host = Host::from_factory(factory, launched_theme());
1763            let batch = host.rebuild().map_err(protocol_error)?;
1764            // SAFETY: `out` is checked before writing.
1765            unsafe { write_batch(out, batch, 0) }.map_err(protocol_error)?;
1766            *host_slot = Some(host);
1767            Ok(())
1768        })
1769    })
1770}
1771
1772#[unsafe(no_mangle)]
1773/// Dispatches one encoded event synchronously and returns its diff batch.
1774///
1775/// # Safety
1776/// `event` must address `len` readable bytes and `out` must be writable.
1777pub unsafe extern "C" fn compose_rust_host_dispatch_event(
1778    event: *const u8,
1779    len: u32,
1780    out: *mut MutationBatch,
1781) -> i32 {
1782    ffi_status(|| {
1783        // SAFETY: Validated according to the function's C ABI contract.
1784        let bytes = unsafe { input_slice(event, len) }.map_err(protocol_error)?;
1785        HOST.with(|slot| {
1786            let mut host_slot = slot.borrow_mut();
1787            let host = host_slot.as_mut().ok_or(STATUS_NOT_INITIALIZED)?;
1788            let (batch, result) = host.dispatch_event(bytes).map_err(protocol_error)?;
1789            // SAFETY: `out` is checked before writing.
1790            unsafe { write_batch(out, batch, result) }.map_err(protocol_error)
1791        })
1792    })
1793}
1794
1795#[unsafe(no_mangle)]
1796/// Renders work scheduled before the current platform frame.
1797///
1798/// # Safety
1799/// `out` must point to writable storage for one [`MutationBatch`].
1800pub unsafe extern "C" fn compose_rust_host_render_frame(
1801    frame_time_nanos: u64,
1802    out: *mut MutationBatch,
1803) -> i32 {
1804    ffi_status(|| {
1805        HOST.with(|slot| {
1806            let mut host_slot = slot.borrow_mut();
1807            let host = host_slot.as_mut().ok_or(STATUS_NOT_INITIALIZED)?;
1808            let batch = host
1809                .render_frame(frame_time_nanos)
1810                .map_err(protocol_error)?;
1811            // SAFETY: `out` is checked before writing.
1812            unsafe { write_batch(out, batch, 0) }.map_err(protocol_error)
1813        })
1814    })
1815}
1816
1817#[unsafe(no_mangle)]
1818/// Releases a batch after the Renderer has applied it on the same call stack.
1819///
1820/// # Safety
1821/// `batch` must be null or point to writable storage for one [`MutationBatch`].
1822pub unsafe extern "C" fn compose_rust_host_release_batch(batch: *mut MutationBatch) {
1823    let _ = catch_unwind(AssertUnwindSafe(|| {
1824        if !batch.is_null() {
1825            // SAFETY: The caller supplied its own writable MutationBatch.
1826            unsafe { batch.write(MutationBatch::default()) };
1827        }
1828    }));
1829}
1830
1831/// The UI thread's batch arena.
1832///
1833/// Not a boundary entry point: it is crate-internal, and the generated Android shims use
1834/// it to tell the Renderer where the arena is so it can map it once instead of per call.
1835pub fn current_arena() -> (*const u8, usize) {
1836    HOST.with(|slot| {
1837        slot.borrow()
1838            .as_ref()
1839            .map_or((std::ptr::null(), 0), Host::arena)
1840    })
1841}
1842
1843#[unsafe(no_mangle)]
1844pub extern "C" fn compose_rust_host_shutdown() {
1845    let _ = catch_unwind(AssertUnwindSafe(|| {
1846        HOST.with(|slot| *slot.borrow_mut() = None);
1847        FRAME_REQUESTED.store(false, Ordering::Release);
1848    }));
1849}
1850
1851#[cfg(test)]
1852mod tests {
1853    use super::*;
1854
1855    /// `APP` is process-global, as launching is, so two tests that launch at the same
1856    /// time would each see the other's. Poisoning is ignored: a failing test has already
1857    /// reported itself, and the rest still need the lock.
1858    static LAUNCH: Mutex<()> = Mutex::new(());
1859
1860    fn launch_guard() -> std::sync::MutexGuard<'static, ()> {
1861        LAUNCH
1862            .lock()
1863            .unwrap_or_else(|poisoned| poisoned.into_inner())
1864    }
1865
1866    #[test]
1867    fn malformed_ffi_input_returns_protocol_error() {
1868        let mut output = MutationBatch::default();
1869        // SAFETY: The test passes a valid output pointer and intentionally null input.
1870        let status = unsafe { compose_rust_host_dispatch_event(std::ptr::null(), 4, &mut output) };
1871        assert_eq!(status, STATUS_PROTOCOL_ERROR);
1872    }
1873
1874    /// How much stack one level of `descend` is made to use.
1875    const LEVEL_BYTES: usize = 16 * 1024;
1876
1877    /// Recurses `levels` deep, holding `LEVEL_BYTES` of stack at every level, and returns
1878    /// how many levels it went. Never inlined and never a tail call, so the stack is really
1879    /// used in an optimised build too.
1880    #[inline(never)]
1881    fn descend(levels: usize) -> usize {
1882        let mut block = [0u8; LEVEL_BYTES];
1883        block[levels % LEVEL_BYTES] = 1;
1884        let block = std::hint::black_box(&mut block);
1885        if levels == 0 {
1886            return usize::from(block[0]) - 1;
1887        }
1888        let below = descend(levels - 1);
1889        below + usize::from(block[levels % LEVEL_BYTES])
1890    }
1891
1892    /// The thread a renderer loop under test found itself on.
1893    static LOOP_THREAD: Mutex<Option<(std::thread::ThreadId, Option<String>)>> = Mutex::new(None);
1894
1895    /// A renderer loop that needs 12 MB of stack, notes its thread, and ends with a status
1896    /// no real loop uses.
1897    extern "C" fn deep_loop() -> c_int {
1898        let current = std::thread::current();
1899        *LOOP_THREAD.lock().unwrap() = Some((current.id(), current.name().map(str::to_owned)));
1900        let levels = 12 * 1024 * 1024 / LEVEL_BYTES;
1901        assert_eq!(descend(levels), levels);
1902        77
1903    }
1904
1905    /// A renderer loop that only notes its thread.
1906    extern "C" fn shallow_loop() -> c_int {
1907        let current = std::thread::current();
1908        *LOOP_THREAD.lock().unwrap() = Some((current.id(), current.name().map(str::to_owned)));
1909        78
1910    }
1911
1912    /// The crash this defends against: the renderer composed and drew on a 1 MB main thread
1913    /// and a screen of ordinary depth overflowed it. The loop here needs 12 MB, more than
1914    /// any thread gets by default (a test's thread has 2 MB, a Windows main thread 1 MB,
1915    /// the others 8 MB), so it only comes back at all if the Host really made the thread
1916    /// with the stack it promises.
1917    #[test]
1918    fn pr3_the_ui_thread_the_host_makes_holds_a_loop_that_needs_twelve_megabytes() {
1919        let _launch = launch_guard();
1920        const { assert!(UI_THREAD_STACK_BYTES >= 32 * 1024 * 1024) };
1921        let status = run_renderer_loop(deep_loop, true);
1922        assert_eq!(
1923            status, 77,
1924            "the loop's status did not come back to the caller"
1925        );
1926        let (thread, name) = LOOP_THREAD.lock().unwrap().take().unwrap();
1927        assert_ne!(
1928            thread,
1929            std::thread::current().id(),
1930            "the loop ran on the calling thread, whose stack is whatever it happened to be"
1931        );
1932        assert_eq!(
1933            name.as_deref(),
1934            Some("compose-rust-ui"),
1935            "an overflow or a panic on this thread would not say whose it was"
1936        );
1937    }
1938
1939    /// Where the Host makes no thread the loop runs on the caller, which on macOS has to be
1940    /// the process main thread and so must never be moved.
1941    #[test]
1942    fn pr3_without_a_ui_thread_the_loop_runs_on_the_caller() {
1943        let _launch = launch_guard();
1944        assert_eq!(run_renderer_loop(shallow_loop, false), 78);
1945        let (thread, _) = LOOP_THREAD.lock().unwrap().take().unwrap();
1946        assert_eq!(thread, std::thread::current().id());
1947    }
1948
1949    /// Only Windows gets the thread. AppKit needs the main thread, and Linux has given no
1950    /// reason to move.
1951    #[test]
1952    fn pr3_the_host_makes_the_ui_thread_on_windows_only() {
1953        assert_eq!(HOST_MAKES_UI_THREAD, cfg!(windows));
1954    }
1955
1956    /// The whole launch, through the entry every other one ends in: the same status as
1957    /// before on every platform, thread or no thread.
1958    #[test]
1959    fn pr3_launching_returns_the_loops_status() {
1960        let _launch = launch_guard();
1961        let status =
1962            LaunchBuilder::new().try_launch_runtime(|| -> Box<dyn Runtime> { unreachable!() });
1963        assert_eq!(status, STATUS_OK);
1964        // Nothing asked the factory for a runtime, and nothing after this test should.
1965        *APP.lock().unwrap() = None;
1966    }
1967
1968    /// A panic on the UI thread reaches the caller as the same panic, not as a join error
1969    /// and not as silence.
1970    #[test]
1971    fn pr3_a_panic_on_the_ui_thread_is_raised_again_on_the_caller() {
1972        let caught = catch_unwind(|| {
1973            run_on_ui_thread(UI_THREAD_STACK_BYTES, || -> i32 {
1974                std::panic::panic_any("the UI thread's own payload")
1975            })
1976        });
1977        let payload = caught.expect_err("the panic stopped at the thread's edge");
1978        assert_eq!(
1979            payload.downcast_ref::<&str>().copied(),
1980            Some("the UI thread's own payload")
1981        );
1982    }
1983
1984    /// A stack the system cannot give is an error the caller can act on, and the work has
1985    /// not run, so the caller may still run it itself.
1986    #[test]
1987    fn pr3_a_ui_thread_that_cannot_be_made_is_an_error_and_runs_nothing() {
1988        static RAN: AtomicBool = AtomicBool::new(false);
1989        let result = run_on_ui_thread(1 << 60, || RAN.store(true, Ordering::SeqCst));
1990        assert!(result.is_err(), "an exabyte was given as a stack");
1991        assert!(!RAN.load(Ordering::SeqCst));
1992    }
1993
1994    /// A state the application made before launching, on the thread that launches.
1995    static BEFORE_LAUNCH: OnceLock<crate::runtime::MutableState<u32>> = OnceLock::new();
1996    /// How many times the root composable ran, and the value it last read.
1997    static COMPOSED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1998    static READ: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
1999    /// Frame requests that reached the renderer.
2000    static FRAMES_ASKED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2001    /// How the UI thread tells the worker to write, and hears that it has.
2002    type Baton = Mutex<Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>>;
2003    static BATON: Baton = Mutex::new(None);
2004
2005    extern "C" fn count_frame_request() {
2006        FRAMES_ASKED.fetch_add(1, Ordering::SeqCst);
2007    }
2008
2009    /// The application: one text that shows the state made before launching.
2010    fn shows_the_state() {
2011        let value = BEFORE_LAUNCH.get().expect("made before launching").get();
2012        COMPOSED.fetch_add(1, Ordering::SeqCst);
2013        READ.store(value, Ordering::SeqCst);
2014        crate::ui::Text(format!("value {value}"));
2015    }
2016
2017    /// Whether a batch the Host returned sets a text to `text`.
2018    fn batch_shows(batch: &MutationBatch, text: &str) -> bool {
2019        if batch.ptr.is_null() {
2020            return false;
2021        }
2022        // SAFETY: the Host returned this batch from the call just made on this thread, and
2023        // it stays readable until the next call.
2024        let bytes = unsafe { std::slice::from_raw_parts(batch.ptr, batch.len as usize) };
2025        crate::protocol::decode_batch(bytes).is_ok_and(|mutations| {
2026            mutations.iter().any(|mutation| {
2027                matches!(
2028                    mutation,
2029                    Mutation::SetProp { value: PropertyValue::String(shown), .. } if *shown == text
2030                )
2031            })
2032        })
2033    }
2034
2035    /// The renderer's part, on the UI thread: start the Host, then use the state made on
2036    /// the launching thread in every way an application does. Returns 0, or the number of
2037    /// the step that failed, because a panic cannot leave a C function.
2038    extern "C" fn loop_using_state_made_before_launch() -> c_int {
2039        let Some(state) = BEFORE_LAUNCH.get().copied() else {
2040            return 1;
2041        };
2042        let mut handshake = Vec::with_capacity(12);
2043        handshake.extend_from_slice(&SCHEMA_HASH.to_le_bytes());
2044        handshake.extend_from_slice(&PROTOCOL_VERSION.to_le_bytes());
2045        handshake.extend_from_slice(&[LoopMode::Renderer as u8, 0]);
2046        let mut batch = MutationBatch::default();
2047        // SAFETY: both buffers are this function's own and live for the call.
2048        let status = unsafe {
2049            compose_rust_host_init(handshake.as_ptr(), handshake.len() as u32, &mut batch)
2050        };
2051        // The first composition reads the value the launching thread gave it.
2052        if status != STATUS_OK || !batch_shows(&batch, "value 1") {
2053            return 2;
2054        }
2055        if COMPOSED.load(Ordering::SeqCst) != 1 || READ.load(Ordering::SeqCst) != 1 {
2056            return 3;
2057        }
2058        // Read and written here, on the UI thread.
2059        if state.get_untracked() != 1 {
2060            return 4;
2061        }
2062        state.set(2);
2063        // SAFETY: `batch` is writable and this is the thread the Host was started on.
2064        let status = unsafe { compose_rust_host_render_frame(1, &mut batch) };
2065        // The composition that read it ran again, and the new value is in the frame.
2066        if status != STATUS_OK || !batch_shows(&batch, "value 2") {
2067            return 5;
2068        }
2069        if COMPOSED.load(Ordering::SeqCst) != 2 {
2070            return 6;
2071        }
2072        // Written by a worker the launching thread started: the write asks for a frame,
2073        // and the frame carries the value.
2074        let asked = FRAMES_ASKED.load(Ordering::SeqCst);
2075        let Some((go, done)) = BATON.lock().unwrap().take() else {
2076            return 7;
2077        };
2078        if go.send(()).is_err() || done.recv().is_err() {
2079            return 8;
2080        }
2081        if FRAMES_ASKED.load(Ordering::SeqCst) == asked {
2082            return 9;
2083        }
2084        // SAFETY: as above.
2085        let status = unsafe { compose_rust_host_render_frame(2, &mut batch) };
2086        if status != STATUS_OK || !batch_shows(&batch, "value 3") {
2087            return 10;
2088        }
2089        if COMPOSED.load(Ordering::SeqCst) != 3 || READ.load(Ordering::SeqCst) != 3 {
2090            return 11;
2091        }
2092        // A frame with nothing written composes nothing.
2093        // SAFETY: as above.
2094        let status = unsafe { compose_rust_host_render_frame(3, &mut batch) };
2095        if status != STATUS_OK || COMPOSED.load(Ordering::SeqCst) != 3 {
2096            return 12;
2097        }
2098        compose_rust_host_shutdown();
2099        0
2100    }
2101
2102    /// An application builds its shared state before it launches, on its main thread, and
2103    /// on Windows the UI then runs on another thread. A `MutableState` has to be the same
2104    /// state on both: its value is in a table of the process and not of the thread that
2105    /// made it, and who observes it is recorded when a composition reads it, not when it
2106    /// is made. So the UI thread reads what was put there, a write on the UI thread runs
2107    /// the composable that read it again, and a write from a worker asks for a frame that
2108    /// carries it.
2109    #[test]
2110    fn pr3_state_made_before_launch_is_the_same_state_on_the_ui_thread() {
2111        let _launch = launch_guard();
2112        // The renderer the rest of these tests use, with frame requests counted. Installed
2113        // for the process, which is all there is, and no different for any other test.
2114        let _ = install_renderer_api(RendererApi {
2115            run: native_run,
2116            request_frame: count_frame_request,
2117            measure: native_measure,
2118        });
2119        let state = *BEFORE_LAUNCH.get_or_init(|| crate::runtime::mutable_state_of(1));
2120        let (go, wait_for_go) = std::sync::mpsc::channel();
2121        let (done, wait_for_done) = std::sync::mpsc::channel();
2122        *BATON.lock().unwrap() = Some((go, wait_for_done));
2123        let worker = std::thread::spawn(move || {
2124            if wait_for_go.recv().is_ok() {
2125                state.set(3);
2126                let _ = done.send(());
2127            }
2128        });
2129        let launching = std::thread::current().id();
2130        let step = LaunchBuilder::new().launch_through(
2131            crate::runtime::recomposer_for(shows_the_state),
2132            loop_using_state_made_before_launch,
2133            true,
2134        );
2135        // Nothing is left waiting if the loop gave up early.
2136        drop(BATON.lock().unwrap().take());
2137        worker.join().unwrap();
2138        *APP.lock().unwrap() = None;
2139        assert_eq!(step, 0, "the loop on the UI thread stopped at step {step}");
2140        assert_eq!(std::thread::current().id(), launching);
2141        // And back on the launching thread it is still the one state.
2142        assert_eq!(state.get_untracked(), 3);
2143    }
2144
2145    static ICON: &[u8] = b"an icon registered before launching";
2146    static LATER: &[u8] = b"a picture the UI registers itself";
2147    static ICON_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
2148
2149    fn draws_nothing() {}
2150
2151    /// The renderer's part: start the Host and see which assets it is told about.
2152    extern "C" fn loop_expecting_the_icon() -> c_int {
2153        let icon = ICON_ID.load(Ordering::SeqCst);
2154        let mut handshake = Vec::with_capacity(12);
2155        handshake.extend_from_slice(&SCHEMA_HASH.to_le_bytes());
2156        handshake.extend_from_slice(&PROTOCOL_VERSION.to_le_bytes());
2157        handshake.extend_from_slice(&[LoopMode::Renderer as u8, 0]);
2158        let mut batch = MutationBatch::default();
2159        // SAFETY: both buffers are this function's own and live for the call.
2160        let status = unsafe {
2161            compose_rust_host_init(handshake.as_ptr(), handshake.len() as u32, &mut batch)
2162        };
2163        if status != STATUS_OK || batch.ptr.is_null() {
2164            return 1;
2165        }
2166        // SAFETY: the Host returned this batch from the call just made on this thread.
2167        let bytes = unsafe { std::slice::from_raw_parts(batch.ptr, batch.len as usize) };
2168        let told = crate::protocol::decode_batch(bytes).is_ok_and(|mutations| {
2169            mutations.iter().any(|mutation| {
2170                matches!(
2171                    mutation,
2172                    Mutation::RegisterAsset { asset_id, bytes, .. }
2173                        if *asset_id == icon && *bytes == ICON
2174                )
2175            })
2176        });
2177        // The Renderer is told the icon under the id the window names it by.
2178        if !told {
2179            return 2;
2180        }
2181        // The same bytes are the same id here, and a new picture does not take it.
2182        if crate::asset::asset(AssetKind::Png, ICON) != icon {
2183            return 3;
2184        }
2185        if crate::asset::asset(AssetKind::Png, LATER) == icon {
2186            return 4;
2187        }
2188        compose_rust_host_shutdown();
2189        0
2190    }
2191
2192    /// An application registers its window's icon and its theme's fonts while it builds
2193    /// its `LaunchBuilder`, before there is a UI, and the window and the theme name them
2194    /// by id. On the thread the Host makes those ids have to name the same bytes, or the
2195    /// window has no icon and the first picture the UI registers takes the icon's id.
2196    #[test]
2197    fn pr3_an_asset_registered_before_launch_keeps_its_id_on_the_ui_thread() {
2198        let _launch = launch_guard();
2199        crate::asset::reset_assets();
2200        let icon = crate::asset::asset(AssetKind::Png, ICON);
2201        ICON_ID.store(icon, Ordering::SeqCst);
2202        let step = LaunchBuilder::new().launch_through(
2203            crate::runtime::recomposer_for(draws_nothing),
2204            loop_expecting_the_icon,
2205            true,
2206        );
2207        *APP.lock().unwrap() = None;
2208        crate::asset::reset_assets();
2209        assert_eq!(step, 0, "the loop on the UI thread stopped at step {step}");
2210    }
2211
2212    #[test]
2213    fn pr3_the_stack_override_is_bytes_and_anything_else_is_said_and_ignored() {
2214        let mut said = Vec::new();
2215        let mut size = |value: Option<&str>| ui_thread_stack_bytes(value, |line| said.push(line));
2216        assert_eq!(size(None), UI_THREAD_STACK_BYTES);
2217        assert_eq!(size(Some("1048576")), 1_048_576);
2218        assert_eq!(size(Some(" 2097152\n")), 2_097_152);
2219        for nonsense in ["", "0", "-1", "64MB", "lots"] {
2220            assert_eq!(size(Some(nonsense)), UI_THREAD_STACK_BYTES, "{nonsense:?}");
2221        }
2222        assert_eq!(said.len(), 5, "{said:?}");
2223        assert!(
2224            said.iter()
2225                .all(|line| line.contains("COMPOSE_RUST_UI_STACK_BYTES")),
2226            "{said:?}"
2227        );
2228    }
2229
2230    #[test]
2231    fn all_exports_isolate_invalid_calls() {
2232        let _launch = launch_guard();
2233        let mut output = MutationBatch::default();
2234        // SAFETY: Each call uses null or valid test-owned pointers as documented.
2235        unsafe {
2236            assert_eq!(
2237                compose_rust_host_init(std::ptr::null(), 1, &mut output),
2238                STATUS_PROTOCOL_ERROR
2239            );
2240            // No handshake has run on this thread, so this is a call-order error.
2241            assert_eq!(
2242                compose_rust_host_render_frame(0, &mut output),
2243                STATUS_NOT_INITIALIZED
2244            );
2245            compose_rust_host_release_batch(std::ptr::null_mut());
2246        }
2247        compose_rust_host_shutdown();
2248    }
2249}
2250
2251/// The design system a demonstration should start in.
2252///
2253/// An application picks its own theme and never needs this. The samples do, because the
2254/// point of a sample is to show what one declaration looks like under each system, and on
2255/// any given machine the adaptive default can only ever show you one of them. Material 3
2256/// and Fluent went unseen for weeks for exactly that reason: everything was checked on a
2257/// Mac, so everything was Cupertino.
2258///
2259/// `DXC_DESIGN` names the system. Anything else, including nothing, adapts to the host.
2260/// `DXC_SCHEME` names `light` or `dark`; anything else leaves the reader's own setting
2261/// alone.
2262pub fn demo_theme() -> Theme {
2263    demo_theme_for(Theme::adaptive(crate::schema::DesignSystem::Material3))
2264}
2265
2266/// The same, for a demonstration that has a theme of its own to start from.
2267///
2268/// A sample whose design is one particular design system in one particular colour scheme
2269/// says so, and that declaration is the sample. But the machine it is being looked at on
2270/// can only draw one of the seven at a time, so without a way to point it somewhere else
2271/// the other six are never seen. This keeps the sample's own theme as the answer and lets
2272/// the two variables override the part they name, so what is on screen is either the
2273/// design the sample chose or exactly the one that was asked for.
2274pub fn demo_theme_for(theme: Theme) -> Theme {
2275    use crate::schema::DesignSystem;
2276    let theme = match std::env::var("DXC_DESIGN").as_deref().map(str::trim) {
2277        Ok("material3") => Theme::unified(DesignSystem::Material3),
2278        Ok("cupertino") => Theme::unified(DesignSystem::Cupertino),
2279        Ok("fluent") => Theme::unified(DesignSystem::Fluent),
2280        Ok("gnome") => Theme::unified(DesignSystem::Gnome),
2281        Ok("breeze") => Theme::unified(DesignSystem::Breeze),
2282        Ok("deepin") => Theme::unified(DesignSystem::Deepin),
2283        // Spelled both ways, because the name is two words everywhere it is written down
2284        // and nobody remembers which one a shell variable wants.
2285        Ok("liquidglass") | Ok("liquid-glass") => Theme::unified(DesignSystem::LiquidGlass),
2286        // Naming a system replaces the sample's design system but keeps its colour
2287        // scheme, so asking to see one design does not also change how light it is.
2288        _ => return with_scheme_override(theme),
2289    }
2290    .with_color_scheme(theme.color_scheme);
2291    with_scheme_override(theme)
2292}
2293
2294/// Applies `DXC_SCHEME` if it names one of the two schemes.
2295fn with_scheme_override(theme: Theme) -> Theme {
2296    match std::env::var("DXC_SCHEME").as_deref().map(str::trim) {
2297        Ok("light") => theme.with_color_scheme(crate::schema::ColorScheme::Light),
2298        Ok("dark") => theme.with_color_scheme(crate::schema::ColorScheme::Dark),
2299        _ => theme,
2300    }
2301}
2302
2303#[cfg(test)]
2304mod demo_theme_tests {
2305    use super::*;
2306    use crate::schema::{ColorScheme, DESIGN_SYSTEM_SCHEMA, DesignSystem};
2307    use std::sync::{Mutex, MutexGuard};
2308
2309    /// Held for the length of any test that sets one of the variables.
2310    ///
2311    /// The variables belong to the process, not to the test, so two of these running at
2312    /// once read each other's settings and fail on a value neither of them asked for.
2313    static ENVIRONMENT: Mutex<()> = Mutex::new(());
2314
2315    /// Clears both variables and keeps everyone else out until the guard is dropped.
2316    fn exclusive_environment() -> MutexGuard<'static, ()> {
2317        let guard = ENVIRONMENT
2318            .lock()
2319            .unwrap_or_else(|error| error.into_inner());
2320        // SAFETY: the lock makes this the only thread touching the environment, and the
2321        // variables are read only by the functions called under the same lock.
2322        unsafe {
2323            std::env::remove_var("DXC_DESIGN");
2324            std::env::remove_var("DXC_SCHEME");
2325        }
2326        guard
2327    }
2328
2329    /// Named for what it defends: a sample that cannot be pointed at a design system
2330    /// leaves five of the six unseen on any one machine.
2331    #[test]
2332    fn fr14_a_named_design_system_is_unified_and_anything_else_adapts() {
2333        let _environment = exclusive_environment();
2334        // SAFETY: `exclusive_environment` holds the lock, so nothing else is reading or
2335        // writing these while this runs.
2336        for (name, system) in [
2337            ("material3", DesignSystem::Material3),
2338            ("cupertino", DesignSystem::Cupertino),
2339            ("fluent", DesignSystem::Fluent),
2340            ("gnome", DesignSystem::Gnome),
2341            ("breeze", DesignSystem::Breeze),
2342            ("deepin", DesignSystem::Deepin),
2343            ("liquidglass", DesignSystem::LiquidGlass),
2344            ("liquid-glass", DesignSystem::LiquidGlass),
2345        ] {
2346            unsafe { std::env::set_var("DXC_DESIGN", name) };
2347            assert_eq!(
2348                demo_theme(),
2349                Theme::unified(system),
2350                "{name} is not selectable"
2351            );
2352        }
2353        assert_eq!(
2354            DESIGN_SYSTEM_SCHEMA.len(),
2355            7,
2356            "a system nobody can select goes unseen"
2357        );
2358
2359        unsafe { std::env::set_var("DXC_DESIGN", "nonsense") };
2360        assert_eq!(demo_theme(), Theme::adaptive(DesignSystem::Material3));
2361
2362        unsafe { std::env::remove_var("DXC_DESIGN") };
2363        assert_eq!(demo_theme(), Theme::adaptive(DesignSystem::Material3));
2364    }
2365
2366    /// Named for what it defends: a machine set to dark draws every sample dark, so a
2367    /// design that is meant to be read light cannot be looked at at all without this.
2368    #[test]
2369    fn fr14_a_named_colour_scheme_is_pinned_and_anything_else_is_left_alone() {
2370        let _environment = exclusive_environment();
2371        // SAFETY: as above.
2372        for (name, scheme) in [("light", ColorScheme::Light), ("dark", ColorScheme::Dark)] {
2373            unsafe { std::env::set_var("DXC_SCHEME", name) };
2374            assert_eq!(
2375                demo_theme().color_scheme,
2376                scheme,
2377                "{name} is not selectable"
2378            );
2379        }
2380
2381        unsafe { std::env::set_var("DXC_SCHEME", "nonsense") };
2382        assert_eq!(demo_theme().color_scheme, ColorScheme::FollowSystem);
2383
2384        unsafe { std::env::remove_var("DXC_SCHEME") };
2385        assert_eq!(demo_theme().color_scheme, ColorScheme::FollowSystem);
2386    }
2387
2388    /// A sample that names its own theme keeps it, and each variable overrides only the
2389    /// half it names. Asking to see Liquid Glass must not also throw away the colour
2390    /// scheme the design was drawn for.
2391    #[test]
2392    fn fr14_a_samples_own_theme_survives_everything_the_variables_do_not_name() {
2393        let _environment = exclusive_environment();
2394        let sample = Theme::unified(DesignSystem::Cupertino).with_color_scheme(ColorScheme::Light);
2395        assert_eq!(demo_theme_for(sample), sample);
2396
2397        unsafe { std::env::set_var("DXC_DESIGN", "liquidglass") };
2398        assert_eq!(
2399            demo_theme_for(sample),
2400            Theme::unified(DesignSystem::LiquidGlass).with_color_scheme(ColorScheme::Light)
2401        );
2402
2403        unsafe { std::env::set_var("DXC_SCHEME", "dark") };
2404        assert_eq!(
2405            demo_theme_for(sample),
2406            Theme::unified(DesignSystem::LiquidGlass).with_color_scheme(ColorScheme::Dark)
2407        );
2408
2409        unsafe {
2410            std::env::remove_var("DXC_DESIGN");
2411            std::env::remove_var("DXC_SCHEME");
2412        };
2413    }
2414    /// A renderer built from a different schema is refused, and says so.
2415    ///
2416    /// The refusal already worked. What did not was finding out why: the renderer stands
2417    /// its window up before it asks the Host anything, so a mismatch leaves an empty page
2418    /// in the default theme and a status code, which reads as an application that draws
2419    /// nothing rather than as a build that is out of date. It cost a morning once.
2420    #[test]
2421    fn pr2_a_handshake_from_another_schema_is_refused() {
2422        let mut wrong = Vec::with_capacity(12);
2423        wrong.extend_from_slice(&SCHEMA_HASH.wrapping_add(1).to_le_bytes());
2424        wrong.extend_from_slice(&PROTOCOL_VERSION.to_le_bytes());
2425        wrong.extend_from_slice(&[LoopMode::Renderer as u8, 0]);
2426        assert!(
2427            matches!(
2428                parse_handshake(&wrong),
2429                Err(crate::protocol::ProtocolError::InvalidEnvelope)
2430            ),
2431            "a handshake carrying another schema's hash was accepted, so the two halves \
2432             would go on to disagree about what every record means"
2433        );
2434
2435        let mut right = Vec::with_capacity(12);
2436        right.extend_from_slice(&SCHEMA_HASH.to_le_bytes());
2437        right.extend_from_slice(&PROTOCOL_VERSION.to_le_bytes());
2438        right.extend_from_slice(&[LoopMode::Renderer as u8, 0]);
2439        assert!(
2440            parse_handshake(&right).is_ok(),
2441            "the handshake this build generates is not one it accepts"
2442        );
2443    }
2444}
2445
2446/// Keeps the five exported boundary functions in the final executable.
2447///
2448/// The Renderer resolves them by name once it is loaded, which means nothing in the
2449/// application ever refers to them and the linker is free to conclude they are dead. It
2450/// does exactly that in any binary whose own code happens not to reach them, a test
2451/// harness for an application being the ordinary case, and the result is a process that
2452/// dies on startup with the dynamic loader unable to bind a symbol that should have been
2453/// right there in the executable.
2454///
2455/// Taking their addresses in a static the compiler is told to keep marks them as roots
2456/// for the dead-code pass, which is the whole job. It costs five pointers.
2457#[used]
2458static BOUNDARY_EXPORTS: BoundaryExports = BoundaryExports([
2459    compose_rust_host_init as *const (),
2460    compose_rust_host_dispatch_event as *const (),
2461    compose_rust_host_render_frame as *const (),
2462    compose_rust_host_release_batch as *const (),
2463    compose_rust_host_shutdown as *const (),
2464]);
2465
2466// The same five names, as a linker directive the object file carries.
2467//
2468// The Renderer finds these with GetProcAddress against the running executable, which
2469// reads the PE export table, and an executable has no export table unless the link is
2470// told to make one. The build script asks for that with `/EXPORT:` arguments, and those
2471// reach the binaries of this package and no further: Cargo does not pass a dependency's
2472// link arguments on to whatever depends on it.
2473//
2474// So every application built on this crate linked without an export table, the Renderer
2475// could not reach back into it, and the window came up empty. It looked like it worked
2476// because the only Windows binaries anyone had run were this package's own examples.
2477//
2478// `.drectve` is how an object file carries linker arguments of its own. The MSVC linker
2479// reads that section out of every object it links, so the directive travels inside the
2480// rlib and applies wherever the rlib ends up.
2481#[cfg(all(target_os = "windows", target_env = "msvc"))]
2482core::arch::global_asm!(
2483    // A section of directives and nothing else, in the COFF flags the MSVC linker reads
2484    // them from: information only ("i") and dropped from the image ("n").
2485    //
2486    // Assembled rather than written as a `static` placed in the section. A static is a
2487    // symbol, and a crate's own DLL asks for every symbol it keeps by name; the LLVM linker
2488    // takes the section's bytes as directives, keeps no symbol for them, and the DLL then
2489    // fails to link on a symbol nobody can define.
2490    ".section .drectve,\"yni\"",
2491    ".ascii \" /EXPORT:compose_rust_host_init\"",
2492    ".ascii \" /EXPORT:compose_rust_host_dispatch_event\"",
2493    ".ascii \" /EXPORT:compose_rust_host_render_frame\"",
2494    ".ascii \" /EXPORT:compose_rust_host_release_batch\"",
2495    ".ascii \" /EXPORT:compose_rust_host_shutdown\"",
2496    ".text",
2497);
2498
2499// Which C runtime an application linking the Kotlin/Native Windows renderer gets, said
2500// where the linker reads it from every object: the build script cannot say it, for the
2501// same reason it cannot ask for the exports above.
2502//
2503// Set by the build script when it links that renderer and the application asked for
2504// nothing (`build/windows_crt.rs` says why each of these is here). The Universal C Runtime
2505// stays the DLL that is part of Windows; vcruntime and the C++ standard library are linked
2506// in, so the executable needs no Visual C++ runtime DLL beside it. An application that asked
2507// for `+crt-static` links all of it statically and needs none of these.
2508#[cfg(all(target_os = "windows", target_env = "msvc", windows_crt_linked_in))]
2509core::arch::global_asm!(
2510    ".section .drectve,\"yni\"",
2511    ".ascii \" /NODEFAULTLIB:vcruntime.lib\"",
2512    ".ascii \" /DEFAULTLIB:libvcruntime.lib\"",
2513    ".ascii \" /NODEFAULTLIB:msvcprt.lib\"",
2514    ".ascii \" /NODEFAULTLIB:libcpmt.lib\"",
2515    ".ascii \" /NODEFAULTLIB:libcmt.lib\"",
2516    ".ascii \" /INCLUDE:longjmp\"",
2517    ".text",
2518);
2519
2520// The same for an application that asked for vcruntime from its DLL
2521// (`DXC_WINDOWS_CRT=dynamic`): the stock static C++ library and C runtime that a prebuilt
2522// object may still name as defaults would define, a second time, what the build script's
2523// blanked copy and the DLLs' import libraries already do.
2524#[cfg(all(target_os = "windows", target_env = "msvc", windows_crt_dynamic))]
2525core::arch::global_asm!(
2526    ".section .drectve,\"yni\"",
2527    ".ascii \" /NODEFAULTLIB:libcpmt.lib\"",
2528    ".ascii \" /NODEFAULTLIB:libcmt.lib\"",
2529    ".text",
2530);
2531
2532// Never read. Being referenced is the entire contract.
2533struct BoundaryExports(#[allow(dead_code)] [*const (); 5]);
2534
2535// SAFETY: The addresses are written once, at compile time, and never read. A static has
2536// to be Sync to exist at all, and raw pointers decline to be only because of what they
2537// might point at; these point at code.
2538unsafe impl Sync for BoundaryExports {}