Skip to main content

day_toolkit_arkui/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-arkui: the HarmonyOS Next **ArkUI** backend (target `harmony-arkui`; DESIGN.md §9).
5//!
6//! HarmonyOS has no AOSP layer; its UI framework is ArkUI. Day drives it through the **ArkUI
7//! Native `NodeAPI`**, bound by openharmony-rs's `ohos-sys` (src/node.rs): every Piece becomes a
8//! real `ArkUI_NodeHandle` (Text / Button / `TextInput` / Toggle / Slider / Stack), built natively
9//! and mounted into an ArkTS `NodeContent` slot. The ArkTS host reaches the native side through
10//! the NAPI module ohos-rs's `napi-ohos` registers (`src/host_api.rs`). Architecturally it mirrors
11//! `day-toolkit-material`: a managed UI runtime (ArkTS) hosts the window, native code (Rust) builds the
12//! tree, and **day owns absolute layout**: containers are `ARKUI_NODE_STACK` and each child gets
13//! an explicit position + size (in vp = day points).
14//!
15//! Off HarmonyOS the crate is empty (`cfg(target_env = "ohos")`), so the workspace still
16//! type-checks on the host.
17
18#![allow(clippy::missing_safety_doc)]
19
20#[cfg(target_env = "ohos")]
21pub use imp::*;
22
23#[cfg(target_env = "ohos")]
24mod controls;
25
26#[cfg(target_env = "ohos")]
27mod anim;
28#[cfg(target_env = "ohos")]
29mod bridge;
30#[cfg(target_env = "ohos")]
31mod canvas;
32#[cfg(target_env = "ohos")]
33mod events;
34#[cfg(target_env = "ohos")]
35pub mod ext;
36#[cfg(target_env = "ohos")]
37mod fonts;
38#[cfg(target_env = "ohos")]
39mod gesture;
40#[cfg(target_env = "ohos")]
41mod hilog;
42#[cfg(target_env = "ohos")]
43mod host;
44#[cfg(target_env = "ohos")]
45mod host_api;
46#[cfg(target_env = "ohos")]
47mod images;
48#[cfg(target_env = "ohos")]
49mod list;
50#[cfg(target_env = "ohos")]
51mod main_thread;
52/// Schedule a native piece callback after ArkUI has unwound the current event.
53#[cfg(target_env = "ohos")]
54pub use main_thread::post_local;
55/// The ArkUI node API for standalone pieces (docs/extending.md): create a node, set its
56/// attributes, register its events, and the raw bindings behind them.
57#[cfg(target_env = "ohos")]
58pub mod node;
59// Pure arithmetic with no NDK in it, so it is also built for the host's unit tests.
60#[cfg(any(target_env = "ohos", test))]
61mod paint;
62#[cfg(target_env = "ohos")]
63mod resources;
64#[cfg(target_env = "ohos")]
65mod transfer;
66#[cfg(target_env = "ohos")]
67mod vsync;
68#[cfg(target_env = "ohos")]
69pub use ext::*;
70/// The NDK's ArkUI bindings, for a piece that needs an attribute or event `node` does not wrap.
71#[cfg(target_env = "ohos")]
72pub use ohos_sys::arkui as arkui_sys;
73
74// One pthread key for the whole crate (`day_reactive::tls_root!`): OpenHarmony's musl, like
75// Android's bionic, allows a process 128, and Rust spends one per `thread_local!` static on
76// these targets. Each module keeps its statics in a `tls_slots!` block named here.
77#[cfg(target_env = "ohos")]
78day_reactive::tls_root! {
79    anim: crate::anim::TlsGroupSlots,
80    canvas: crate::canvas::TlsGroupSlots,
81    datetime: crate::controls::datetime::TlsGroupSlots,
82    events: crate::events::TlsGroupSlots,
83    fonts: crate::fonts::TlsGroupSlots,
84    gesture: crate::gesture::TlsGroupSlots,
85    host_api: crate::host_api::TlsGroupSlots,
86    images: crate::images::TlsGroupSlots,
87    imp: crate::imp::TlsGroupSlots,
88    list: crate::list::TlsGroupSlots,
89    main_thread: crate::main_thread::TlsGroupSlots,
90    node: crate::node::TlsGroupSlots,
91    pager: crate::controls::pager::TlsGroupSlots,
92    spinner: crate::controls::spinner::TlsGroupSlots,
93    transfer: crate::transfer::TlsGroupSlots,
94    vsync: crate::vsync::TlsGroupSlots,
95}
96
97#[cfg(target_env = "ohos")]
98mod imp {
99    use std::cell::{Cell, RefCell};
100    use std::collections::HashMap;
101    use std::rc::Rc;
102
103    use linkme::distributed_slice;
104
105    use day_spec::props::*;
106    use day_spec::{
107        A11yProps, AnimSpec, Builtin, Cap, DrawOp, Event, EventSink, Font, FontSpec, GestureKind,
108        NodeId, PieceKind, Platform, Point, Proposal, Rect, Registry, Renderer, Size, Support,
109        Toolkit, WindowOptions, kinds,
110    };
111
112    use crate::node::{self, Handle};
113
114    /// An `ArkUI_NodeHandle`. day owns the tree, so the raw pointer is the identity.
115    #[derive(Clone, Copy, PartialEq, Eq, Hash)]
116    pub struct AHandle(pub Handle);
117
118    type Sink = Rc<dyn Fn(NodeId, Event)>;
119
120    day_reactive::tls_slots! {
121        imp;
122        static BUTTON_INK: day_spec::sidetable::SideTable<u32> = day_spec::sidetable::SideTable::new();
123        /// Each surface's gradient fill (linear, radial or conic) and the frame size it was last
124        /// resolved against (docs/surfaces.md): `set_frame` resolves it again when the size
125        /// changes, and an appearance switch when a stop is a dynamic ink.
126        static SURFACE_GRADIENTS: day_spec::sidetable::SideTable<(day_spec::Paint, Size)> =
127            day_spec::sidetable::SideTable::new();
128        /// Surfaces whose fill comes from their realize-time role (a section card, a window
129        /// ground): a `ContainerPatch::Surface` leaves that fill alone.
130        static SURFACE_ROLE: day_spec::sidetable::SideTable<()> = day_spec::sidetable::SideTable::new();
131        static BUTTON_CHILDREN: RefCell<HashMap<usize, Vec<AHandle>>> = RefCell::new(HashMap::new());
132        /// Each button's style and selected state (`ButtonProps::selected`), so the selected
133        /// look (the prominent fill) can give way to the button's own style again, and
134        /// `read_native` can report the state as `checked`.
135        static BUTTON_STYLE: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> = RefCell::new(HashMap::new());
136        static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
137        /// Navigation state is keyed by host pointer; page keys are globally unique Day NodeIds.
138        /// Each host owns its pending children and path. Creating another host must never
139        /// clear a sibling tab's state or redirect its Back/search/title callbacks.
140        static NAV_HOSTS: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
141        /// The primary window's toolbar (docs/toolbars.md) as Day's edits and patches left it:
142        /// what the Navigation's title-bar actions are painted from.
143        static WINDOW_BAR: RefCell<day_spec::ToolbarMirror> = RefCell::new(day_spec::ToolbarMirror::default());
144        static NAV_ATTACHED: RefCell<HashMap<usize, Vec<(usize, u64)>>> = RefCell::new(HashMap::new());
145        static NAV_OWNERS: RefCell<HashMap<u64, usize>> = RefCell::new(HashMap::new());
146        static NAV_PUSHED: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
147        /// Keys whose NavDestination already disappeared (`nav_popped`) while the page is
148        /// still mounted; its Remove must not touch the torn-down ArkTS content.
149        static NAV_POPPED_KEYS: RefCell<std::collections::HashSet<u64>> =
150            RefCell::new(std::collections::HashSet::new());
151        /// Keys whose next `navPopped` acknowledges a Day-initiated pop (must not sync back
152        /// as a native back). Keyed, not counted: a page pushed and popped within one frame
153        /// never mounts, so ArkUI fires no disappear for it, and a counter would wait forever
154        /// on an acknowledgment that never comes (the CI post-stack blank-screenshot wedge).
155        static NAV_EXPECT_POP: RefCell<std::collections::HashSet<u64>> =
156            RefCell::new(std::collections::HashSet::new());
157        /// Rust's order of pushed page keys: what a `NavPatch::Popped` pops, so the pop
158        /// handler knows which key it retired (ArkTS only reports keys on disappear).
159        static NAV_STACK: RefCell<HashMap<usize, Vec<u64>>> = RefCell::new(HashMap::new());
160        /// NAV_PAGE node ptr → day NodeId (recorded at realize; consumed by insert/push).
161        static NAV_PAGE_IDS: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
162        /// The page search field (docs/search.md) as each navigation host last drew it, by the
163        /// host's day id: `(page, prompt, text)`, `page` the destination key it rides, -1 for the
164        /// host's root page. A host without an entry shows none.
165        static PAGE_SEARCH: RefCell<HashMap<u64, (i64, String, String)>> = RefCell::new(HashMap::new());
166        static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
167        /// The window root Stack + content size, set by [`init`] before `run`.
168        static ROOT: RefCell<Option<(AHandle, Size)>> = const { RefCell::new(None) };
169        /// Dark mode (docs/localization + theming): resolved once at init. DAY_THEME (the CI
170        /// forced theme) wins, else DAY_ARKUI_DARK (the system color mode the ArkTS host reports
171        /// via setEnv before start()). ArkUI's C-API nodes do not re-theme hardcoded colors, so
172        /// every neutral day-toolkit-arkui paint branches on this flag.
173        static IS_DARK: Cell<bool> = const { Cell::new(false) };
174        /// Slider NodeId → (min, max), so ArkUI's 0..100 maps back to day's range. Keyed by the
175        /// id, not the node pointer, because the change event carries only the id: a
176        /// pointer-keyed map missed there, and every drag landed in the fallback 0..1.
177        static SLIDER_RANGE: RefCell<HashMap<u64, (f64, f64)>> = RefCell::new(HashMap::new());
178        /// ArkTS-built piece nodes (docs/extending.md): wrapper Stack ptr → (day NodeId, the
179        /// ArkTS FrameNode inside it). Release detaches the FrameNode, sends the ArkTS side its
180        /// disposal (ArkTS owns that node), and disposes only the native wrapper.
181        static PIECE_NODES: RefCell<HashMap<usize, (u64, usize)>> = RefCell::new(HashMap::new());
182        /// ArkTS picker size by wrapper: Some(chrome) is a menu, None is a segmented row.
183        /// Both reserve room for every option, so selecting another label never resizes them.
184        static MENU_PICKER_SIZE: RefCell<HashMap<usize, (Option<f64>, Size)>> = RefCell::new(HashMap::new());
185        /// The size each ArkTS piece was last told it has (see `set_frame`), by wrapper handle.
186        static PIECE_FRAME: RefCell<HashMap<usize, Size>> = RefCell::new(HashMap::new());
187        /// The paints that follow the color mode (see [`themed`] and [`paint_ink`]), by the
188        /// node whose lifetime bounds them: each owner's (node, paint, tone).
189        static THEMED: RefCell<HashMap<usize, Vec<(usize, Paint, Tone)>>> =
190            RefCell::new(HashMap::new());
191        /// The system theme's role colors per color mode (`[light, dark]`), read once through
192        /// the ArkTS arm (`host::system_colors`); `None` until first asked.
193        static SYSTEM_COLORS: RefCell<[Option<[Option<u32>; day_spec::SystemColor::COUNT]>; 2]> =
194            const { RefCell::new([None, None]) };
195        /// The palette of the current color mode, built from [`SYSTEM_COLORS`] and Day's
196        /// fallbacks: what every ink this backend applies resolves against.
197        static PALETTE: Cell<Option<day_spec::Palette>> = const { Cell::new(None) };
198        // Text-area (min_lines, max_lines) by handle, for the measure band (docs/textarea.md).
199        static TEXTAREA_LINES: RefCell<HashMap<usize, (u32, u32)>> = RefCell::new(HashMap::new());
200        /// A NAV_MENU row's synthetic click id → (menu node, row index). A tap on a menu row is a
201        /// plain NODE_ON_CLICK, so we register it against a fresh synthetic id and translate the
202        /// click back into `SelectionChanged(index)` against the menu host (day-toolkit-material does the
203        /// same with a per-row listener). See [`on_event`].
204        static MENU_ROWS: RefCell<HashMap<u64, (NodeId, i64)>> = RefCell::new(HashMap::new());
205        /// NAV_MENU scroll node ptr → its day NodeId, so `NavMenuPatch::Items` (which only gets
206        /// the handle) can rebuild the rows against the right menu id, and `release` can purge
207        /// the menu's synthetic-row entries from [`MENU_ROWS`].
208        static NAV_MENU_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
209        /// Monotonic synthetic-id counter for menu rows (kept out of day's NodeId space by using the
210        /// high bit, which day-core never allocates).
211        static SYNTH: Cell<u64> = const { Cell::new(1u64 << 63) };
212        /// List host node ptr → its day NodeId, so `attach_list` (which only gets the handle) can
213        /// key the source by the id the native adapter callbacks report.
214        static LIST_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
215        /// List host NodeId → its injected row-pull source (docs/list.md).
216        /// Programmatic selection per list (docs/list.md `ListPatch::Selected`): the list
217        /// module paints from this at bind and on a sync (`list::paint_selection`).
218        static LIST_SELECTED: RefCell<HashMap<u64, std::collections::BTreeSet<usize>>> =
219            RefCell::new(HashMap::new());
220        /// Lists with a posted reload not yet run (see the Reload arm): one data change often
221        /// fires several watches (shape + expansion + selection), and back-to-back
222        /// ReloadAllItems bursts dropped adapter ADDs, so coalesce to one per drain.
223        static LIST_RELOAD_PENDING: RefCell<std::collections::HashSet<usize>> =
224            RefCell::new(std::collections::HashSet::new());
225        /// Control/label handle → day node, for echo cells and rebuilt link spans (a patch
226        /// sees only the handle; the event carries only the node).
227        static CTRL_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
228        /// Programmatic-set echo cells (§4.4): ArkUI fires onChange for programmatic sets
229        /// too, so a value day just wrote comes straight back as a change event, and a
230        /// two-way binding then re-writes the app state (on Day-Sketch, phantom "style"
231        /// undo units on every selection change). The cell holds the last programmatic
232        /// value; a matching event is the echo and is swallowed, a differing one is the
233        /// user and clears the cell.
234        static TEXT_ECHO: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
235        /// Text inputs and areas, by day node (docs/textfield.md, docs/textarea.md). ArkUI has
236        /// no read-only attribute, so the backend refuses edits itself; see [`InputField`].
237        static INPUT_FIELDS: RefCell<HashMap<u64, InputField>> = RefCell::new(HashMap::new());
238        static SLIDER_ECHO: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
239        /// Toggle gates (§4.4), by day node. A value-match cell is not enough for a switch:
240        /// ArkUI can report a programmatic set late, after day has already written the
241        /// opposite value, and that stale event flipped the app state back. So a native
242        /// change reaches the app only when the user touched or keyed the switch since
243        /// day's last write; any other differing event is stale and the switch is repainted.
244        static TOGGLE_GATE: RefCell<HashMap<u64, ToggleGate>> = RefCell::new(HashMap::new());
245        static LIST_SOURCES: RefCell<HashMap<u64, day_spec::ListSource>> =
246            RefCell::new(HashMap::new());
247        /// Node ids with a Tap gesture (docs/shapes.md): a NODE_ON_CLICK on these emits `Event::Tap`
248        /// (not `Event::Pressed`), which is how a canvas/shape `.on_tap` (e.g. day-piece-rating's
249        /// stars) receives taps on ArkUI. See [`Toolkit::enable_gesture`] + [`on_event`].
250        static TAP_NODES: RefCell<std::collections::HashSet<u64>> =
251            RefCell::new(std::collections::HashSet::new());
252        /// Tap-node handle ptr → its node id, so `release` (which only gets the handle) can drop the
253        /// matching TAP_NODES entry (else a recycling list would grow the set unbounded).
254        static TAP_HANDLES: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
255        /// Each label's paragraph attributes and whether it wraps, kept so a font change can
256        /// recompute the spacing and line height it scales (`apply_paragraph`).
257        static LABEL_PARA: day_spec::sidetable::SideTable<(day_spec::props::LabelParagraph, bool)> =
258            day_spec::sidetable::SideTable::new();
259        /// How many disabled subtree roots hold each node disabled (`set_subtree_enabled`).
260        static SUBTREE_DISABLED: day_spec::sidetable::SideTable<u32> =
261            day_spec::sidetable::SideTable::new();
262        /// Menu buttons (`set_button_menu`, docs/menus.md "Menu buttons"): node id → button
263        /// handle ptr. The NDK has no menu to bind, so a press reports `Event::ContextMenu` at the
264        /// button's bottom-leading corner and day-pieces presents the composed menu there.
265        static MENU_BUTTONS: RefCell<HashMap<u64, usize>> = RefCell::new(HashMap::new());
266        /// Fullscreen covers (docs/cover.md): handle ptr → day NodeId. A cover's frame is
267        /// native-owned (full window while presented), so `set_frame` skips these.
268        static COVER_NODES: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
269        /// Covers presented as half sheets (`CoverProps::half`, docs/cover.md): the bottom
270        /// half of the cover layer.
271        static COVER_HALF: RefCell<std::collections::HashSet<usize>> =
272            RefCell::new(std::collections::HashSet::new());
273        /// A cover's current native parent (its parked tree slot, or the dedicated cover
274        /// layer while presented). Presenting re-homes it, so removals must target this.
275        static COVER_PARENTS: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
276        /// Covers currently presented (topped on the cover layer). Separate from
277        /// COVER_PARENTS, which records the parked tree slot; on the cover-fallback
278        /// tier (docs/windows.md) that slot is the root itself, so parent-comparison cannot
279        /// stand in for presented-ness.
280        static COVER_PRESENTED: RefCell<std::collections::HashSet<usize>> =
281            RefCell::new(std::collections::HashSet::new());
282        /// The root-page Stack + its size, kept for the app's lifetime (unlike [`ROOT`],
283        /// which `run` consumes).
284        static ROOT_KEEP: Cell<Option<(usize, f64, f64)>> = const { Cell::new(None) };
285        /// Separate host slot above ArkTS Navigation; the root page is below NavDestinations.
286        static COVER_ROOT: Cell<Option<(usize, f64, f64)>> = const { Cell::new(None) };
287        /// Whether day-core armed the system back for the app's handlers
288        /// ([`Toolkit::set_system_back`]): the entry page's `onBackPress` consumes the back.
289        static SYSTEM_BACK: Cell<bool> = const { Cell::new(false) };
290        /// Nav transitions in flight, for [`Toolkit::ui_idle`] (dayscript screenshots wait on
291        /// it): pushed page keys awaiting their destination's first area report, and popped
292        /// page keys awaiting their `navPopped` acknowledgment. Both hold only keys whose
293        /// native event is still coming: a pop retires its own pending-push entry (a
294        /// never-mounted page reports neither), and only lands in the pending-pop set when
295        /// the page had mounted.
296        static NAV_PENDING_PUSH: RefCell<std::collections::HashSet<u64>> =
297            RefCell::new(std::collections::HashSet::new());
298        static NAV_PENDING_POP: RefCell<std::collections::HashSet<u64>> =
299            RefCell::new(std::collections::HashSet::new());
300        /// Each `scroll()`'s backend-owned content Stack (scroll ptr → stack ptr), sized by
301        /// `set_scroll_content`. Day's content nodes are layout-only (no native child of
302        /// their own), and an ArkUI Scroll whose children are absolutely-placed leaves
303        /// measures a content extent of 0, so offsets clamp to nothing and neither touch nor
304        /// programmatic scrolling moves. `insert`/`remove` re-route the scroll's day
305        /// children into the container so the Scroll measures the real extent.
306        static SCROLL_CONTENT: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
307
308        /// Each picker wheel's live selection, so a change of options can keep it: the
309        /// range attribute is set whole, and the selected index goes with it. A
310        /// [`SideTable`], so the backend's release sweep drops a dead picker's entry.
311        static PICKER_SELECTED: day_spec::sidetable::SideTable<usize> =
312            day_spec::sidetable::SideTable::new();
313
314        /// Every live suite, by host node pointer. Suites nest (a tab whose page holds tabs of
315        /// its own), so each host keeps its own pages, bar and layout.
316        static NAV_SUITES: RefCell<HashMap<usize, NavSuite>> = RefCell::new(HashMap::new());
317        /// The suite whose rows have not arrived yet: its host is realized before its sidebar
318        /// page, so the next navigation menu realized is that suite's, and no later one is.
319        static SUITE_AWAITING_MENU: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
320        /// Each suite's navigation menu (menu node → suite host), for a data-driven rows patch.
321        static MENU_SUITE: RefCell<HashMap<u64, usize>> = RefCell::new(HashMap::new());
322
323        /// Secondary window roots (docs/windows.md): (day node, the window's Stack node
324        /// pointer): the multiton DayWindowAbility instances' content.
325        static SECONDARY: RefCell<Vec<(u64, usize)>> = const { RefCell::new(Vec::new()) };
326        /// Each window's display state as the ArkTS host last reported it, keyed by the node its
327        /// `WindowStateChanged` goes to (`WINDOW_NODE` for the primary): what a declined
328        /// request reports back (docs/windows.md "Window properties").
329        static WINDOW_STATES: RefCell<HashMap<u64, day_spec::WindowState>> = RefCell::new(HashMap::new());
330        /// `BitmapId` → what the decode reported (docs/images.md). Only the METADATA lives here;
331        /// the pixels are the image module's, in a pixelmap registry under the same id.
332        static BITMAP_INFO: RefCell<HashMap<u64, day_spec::BitmapInfo>> =
333            RefCell::new(HashMap::new());
334        /// Whether `ensure_canvas_fonts` has run in this process.
335        static CANVAS_FONTS_REGISTERED: Cell<bool> = const { Cell::new(false) };
336    }
337
338    /// Height of the composed bottom bar, in vp (HarmonyOS's tab-bar metric).
339    const NAV_BAR_H: f64 = 56.0;
340    /// The rail's width (Medium): an icon over a short label per destination.
341    const NAV_RAIL_W: f64 = 80.0;
342    /// The sidebar's width (Expanded): an icon beside a label per destination.
343    const NAV_SIDEBAR_W: f64 = 240.0;
344
345    /// Where a suite draws its rows, by the host's width (docs/size-classes.md): the bottom bar
346    /// of a phone, a rail on a portrait tablet, a sidebar on a landscape one. The same
347    /// resident-page model at every width (the pieces layer lowers `Tabs` and the chrome is
348    /// this backend's own), which is what Material's navigation suite and iOS 18's tab sidebar
349    /// do natively.
350    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
351    enum SuitePlacement {
352        Bottom,
353        Rail,
354        Sidebar,
355    }
356
357    fn suite_placement(width: f64) -> SuitePlacement {
358        // The width classes' own boundaries (docs/size-classes.md): Compact < 600, Medium < 840.
359        if width < 600.0 {
360            SuitePlacement::Bottom
361        } else if width < 840.0 {
362            SuitePlacement::Rail
363        } else {
364            SuitePlacement::Sidebar
365        }
366    }
367
368    /// The navigation suite (`NavPresentation::Tabs`): resident pages over a bottom bar.
369    ///
370    /// ArkUI's native node set has no tab container (`ARKUI_NODE_TABS` is an ArkTS-only
371    /// component, and the NDK exposes a swiper at most), so the bar is composed from the same
372    /// primitives every other Day piece is built from (docs/navigation.md). One implementation,
373    /// the platform's own metrics, and the rows keep their meaning: a bar item reports through
374    /// the same synthetic-click table a sidebar row uses, so a tap is one event either way.
375    struct NavSuite {
376        documents: bool,
377        pages: AHandle,
378        bar: AHandle,
379        /// Destination pages in bar order; index i is the `Select(i)` index.
380        items: Vec<(AHandle, NodeId)>,
381        /// The bar's item nodes, so a rebuild can take the old ones out first.
382        bar_items: Vec<AHandle>,
383        bar_inks: Vec<(Handle, Paint, usize)>,
384        selected: usize,
385        /// The pages area, so a page joining later can be sized without waiting for a resize.
386        page_size: Size,
387        /// Where the rows are drawn now; a width crossing a class boundary rebuilds the bar.
388        placement: SuitePlacement,
389        /// The rows the bar was last filled from, so a placement change can refill it.
390        menu: Option<NodeId>,
391        labels: Vec<String>,
392        icons: Vec<Option<String>>,
393    }
394
395    fn next_synth() -> u64 {
396        SYNTH.with(|c| {
397            let v = c.get();
398            c.set(v + 1);
399            v
400        })
401    }
402
403    /// The staged image for a name (docs/vectors.md): a vector's SVG (recolorable), else the
404    /// raster PNG, as a `resource://RAWFILE` URI.
405    fn named_image(name: &str) -> (String, bool) {
406        let svg = format!("day/{name}.svg");
407        if crate::resources::rawfile_exists(&svg) {
408            (format!("resource://RAWFILE/{svg}"), true)
409        } else {
410            (format!("resource://RAWFILE/day/{name}.png"), false)
411        }
412    }
413
414    /// An icon node for a nav row or bar item: a vector tinted with `tint` or the themed
415    /// secondary color, a raster drawn as authored.
416    fn row_icon(owner: usize, name: &str, tint: Option<day_spec::Ink>, size: f64) -> AHandle {
417        let icon = new_node(node::IMAGE);
418        let (src, is_vector) = named_image(name);
419        node::set_image_src(icon.0, &src);
420        if is_vector {
421            match tint {
422                Some(c) => paint_ink(owner, icon.0, Paint::ImageFill, c),
423                None => themed(owner, icon.0, Paint::ImageFill, 0x9900_0000, 0x99FF_FFFF),
424            }
425        }
426        node::set_image_fit(icon.0, 0);
427        node::set_size(icon.0, size, size);
428        icon
429    }
430
431    /// Build the bar's items from the host's rows: an icon over a label per destination, each
432    /// registering a synthetic click that reports `SelectionChanged(i)` against the menu node.
433    fn suite_fill_bar(
434        host: usize,
435        menu: NodeId,
436        items: &[String],
437        icons: &[Option<String>],
438        selected: usize,
439    ) {
440        NAV_SUITES.with(|c| {
441            let mut c = c.borrow_mut();
442            let Some(suite) = c.get_mut(&host) else {
443                return;
444            };
445            suite.menu = Some(menu);
446            suite.labels = items.to_vec();
447            suite.icons = icons.to_vec();
448            if suite.documents {
449                return;
450            }
451            let placement = suite.placement;
452            for old in std::mem::take(&mut suite.bar_items) {
453                node::remove_child(suite.bar.0, old.0);
454                // Removed alone, every refill (a retitled or re-badged row) left the old cells,
455                // their icons and their labels allocated.
456                node::dispose_tree(old.0);
457            }
458            suite.bar_inks.clear();
459            forget_themed(host);
460            // The bar's ground, kept across refills.
461            themed(
462                host,
463                suite.bar.0,
464                Paint::Background,
465                0xFFF1_F3F5,
466                0xFF1C_1C1E,
467            );
468            for (i, title) in items.iter().enumerate() {
469                // A bottom bar's and a rail's cell stacks the icon over the label; a sidebar's
470                // row puts them side by side, the way the rows list draws them.
471                let cell = new_node(if placement == SuitePlacement::Sidebar {
472                    node::ROW
473                } else {
474                    node::COLUMN
475                });
476                let synth = next_synth();
477                MENU_ROWS.with(|m| m.borrow_mut().insert(synth, (menu, i as i64)));
478                // The selected destination takes the accent; the rest the secondary label color,
479                // which is how a HarmonyOS bottom bar reads.
480                let on = i == selected;
481                let (tint_light, tint_dark) = if on {
482                    (0xFF00_7DFF, 0xFF3E_9BFF)
483                } else {
484                    (0x9900_0000, 0x99FF_FFFF)
485                };
486                let mut child = 0;
487                if let Some(Some(name)) = icons.get(i) {
488                    let icon = new_node(node::IMAGE);
489                    let (src, is_vector) = named_image(name);
490                    node::set_image_src(icon.0, &src);
491                    if is_vector {
492                        themed(host, icon.0, Paint::ImageFill, tint_light, tint_dark);
493                        suite.bar_inks.push((icon.0, Paint::ImageFill, i));
494                    }
495                    node::set_image_fit(icon.0, 0);
496                    node::set_size(icon.0, 24.0, 24.0);
497                    if placement == SuitePlacement::Sidebar {
498                        node::set_margin(icon.0, 8.0);
499                    }
500                    node::insert_child(cell.0, icon.0, child);
501                    child += 1;
502                }
503                let label = new_node(node::TEXT);
504                node::set_text(label.0, title);
505                node::set_font_size(
506                    label.0,
507                    if placement == SuitePlacement::Sidebar {
508                        15.0
509                    } else {
510                        10.0
511                    },
512                );
513                themed(host, label.0, Paint::Font, tint_light, tint_dark);
514                suite.bar_inks.push((label.0, Paint::Font, i));
515                node::insert_child(cell.0, label.0, child);
516                match placement {
517                    // The bar's cells share its width.
518                    SuitePlacement::Bottom => node::set_flex_grow(cell.0, 1.0),
519                    SuitePlacement::Rail => node::set_size(cell.0, NAV_RAIL_W, 64.0),
520                    SuitePlacement::Sidebar => node::set_size(cell.0, NAV_SIDEBAR_W, 48.0),
521                }
522                node::register_event(cell.0, node::EV_CLICK, synth);
523                node::insert_child(suite.bar.0, cell.0, i as i32);
524                suite.bar_items.push(cell);
525            }
526        });
527    }
528
529    /// Lay the suite out inside `size` and tell every page how much room it has.
530    ///
531    /// The pages area and the bar are sized here rather than by day-core, which sees one host
532    /// node and gives it one frame: the same division of labor every other backend's native
533    /// nav container performs for itself.
534    fn suite_layout(host: usize, size: Size) {
535        // The rows' placement follows the width. A change swaps the bar for one of the other
536        // orientation (a Row for the bottom bar, a Column for a rail or sidebar) and refills
537        // it from the rows it was last given; the pages never notice beyond their new frame.
538        let placement = suite_placement(size.width);
539        let refill = NAV_SUITES.with(|c| {
540            let mut c = c.borrow_mut();
541            let suite = c.get_mut(&host)?;
542            if suite.documents || suite.placement == placement {
543                return None;
544            }
545            suite.placement = placement;
546            for old in std::mem::take(&mut suite.bar_items) {
547                node::remove_child(suite.bar.0, old.0);
548                node::dispose_tree(old.0);
549            }
550            suite.bar_inks.clear();
551            node::remove_child(host as Handle, suite.bar.0);
552            node::dispose(suite.bar.0);
553            let bar = new_node(if placement == SuitePlacement::Bottom {
554                node::ROW
555            } else {
556                node::COLUMN
557            });
558            if placement == SuitePlacement::Sidebar {
559                // Rows start at the leading edge, like the list they stand in for.
560                node::set_i32(
561                    bar.0,
562                    ohos_sys::arkui::native_node::ArkUI_NodeAttributeType::NODE_COLUMN_ALIGN_ITEMS,
563                    ohos_sys::arkui::native_type::ArkUI_HorizontalAlignment::ARKUI_HORIZONTAL_ALIGNMENT_START.0 as i32,
564                );
565            }
566            node::insert_child(host as Handle, bar.0, 1);
567            suite.bar = bar;
568            suite
569                .menu
570                .map(|menu| (menu, suite.labels.clone(), suite.icons.clone(), suite.selected))
571        });
572        if let Some((menu, labels, icons, selected)) = refill {
573            suite_fill_bar(host, menu, &labels, &icons, selected);
574            suite_select(host, selected);
575        }
576        let reports: Vec<(NodeId, Size)> = NAV_SUITES.with(|c| {
577            let mut c = c.borrow_mut();
578            let Some(suite) = c.get_mut(&host) else {
579                return Vec::new();
580            };
581            let (page_x, page, bar) = if suite.documents {
582                (0.0, size, (0.0, 0.0, 0.0, 0.0))
583            } else {
584                match placement {
585                    SuitePlacement::Bottom => {
586                        let page = Size::new(size.width, (size.height - NAV_BAR_H).max(0.0));
587                        (0.0, page, (0.0, page.height, size.width, NAV_BAR_H))
588                    }
589                    SuitePlacement::Rail => (
590                        NAV_RAIL_W,
591                        Size::new((size.width - NAV_RAIL_W).max(0.0), size.height),
592                        (0.0, 0.0, NAV_RAIL_W, size.height),
593                    ),
594                    SuitePlacement::Sidebar => (
595                        NAV_SIDEBAR_W,
596                        Size::new((size.width - NAV_SIDEBAR_W).max(0.0), size.height),
597                        (0.0, 0.0, NAV_SIDEBAR_W, size.height),
598                    ),
599                }
600            };
601            suite.page_size = page;
602            node::set_frame(suite.pages.0, page_x, 0.0, page.width, page.height);
603            node::set_frame(suite.bar.0, bar.0, bar.1, bar.2, bar.3);
604            suite
605                .items
606                .iter()
607                .map(|(h, id)| {
608                    node::set_size(h.0, page.width, page.height);
609                    (*id, page)
610                })
611                .collect()
612        });
613        for (id, size) in reports {
614            emit(id, Event::FrameChanged(size));
615        }
616    }
617
618    /// Show destination `i` and hide the rest (the resident-page switch, docs/navigation.md).
619    fn suite_select(host: usize, i: usize) {
620        NAV_SUITES.with(|c| {
621            let mut c = c.borrow_mut();
622            let Some(suite) = c.get_mut(&host) else {
623                return;
624            };
625            suite.selected = i;
626            forget_themed(host);
627            themed(
628                host,
629                suite.bar.0,
630                Paint::Background,
631                0xFFF1_F3F5,
632                0xFF1C_1C1E,
633            );
634            for &(node, paint, index) in &suite.bar_inks {
635                let (light, dark) = if index == i {
636                    (0xFF00_7DFF, 0xFF3E_9BFF)
637                } else {
638                    (0x9900_0000, 0x99FF_FFFF)
639                };
640                themed(host, node, paint, light, dark);
641            }
642            for (n, (h, _)) in suite.items.iter().enumerate() {
643                node::set_visibility(h.0, n == i);
644            }
645        });
646    }
647
648    /// Build a `NAV_MENU`: a scrollable column of conventional navigation rows (an optional
649    /// leading icon, leading-aligned label, trailing chevron, hairline separators, the
650    /// HarmonyOS settings-list idiom), not buttons. Each row's tap becomes a synthetic click
651    /// that [`on_event`] translates to `SelectionChanged(index)` against `menu`.
652    ///
653    /// Icons (docs/vectors.md): a vector name resolves to its staged rawfile SVG
654    /// (`day/<name>.svg`), which ArkUI renders natively and `NODE_IMAGE_FILL_COLOR` recolors:
655    /// the row's tint when given, else a secondary theme foreground. A raster name falls
656    /// back to `day/<name>.png`, drawn as authored (fill color has no effect on rasters).
657    #[allow(clippy::too_many_arguments)]
658    fn build_nav_menu(
659        menu: NodeId,
660        items: &[String],
661        icons: &[Option<String>],
662        tints: &[Option<day_spec::Ink>],
663        badges: &[Option<String>],
664        badge_icons: &[Option<String>],
665        badge_tints: &[Option<day_spec::Ink>],
666        sections: &[Option<String>],
667    ) -> AHandle {
668        let scroll = new_node(node::SCROLL);
669        let col = build_nav_menu_rows(
670            menu,
671            items,
672            icons,
673            tints,
674            badges,
675            badge_icons,
676            badge_tints,
677            sections,
678        );
679        node::insert_child(scroll.0, col.0, 0);
680        // The rows column is owned content: registering it here lets `NavMenuPatch::Items`
681        // swap it wholesale and `release` dispose it with the scroll.
682        SCROLL_CONTENT.with(|m| m.borrow_mut().insert(scroll.0 as usize, col.0 as usize));
683        NAV_MENU_IDS.with(|m| m.borrow_mut().insert(scroll.0 as usize, menu));
684        scroll
685    }
686
687    /// The rows column for a `NAV_MENU` (see [`build_nav_menu`]): registers one synthetic click
688    /// id per row in [`MENU_ROWS`]. Rebuilt wholesale on `NavMenuPatch::Items`.
689    ///
690    /// A section title (docs/navigation.md) is a plain text node ahead of its group's first row.
691    /// It registers no click id, so [`MENU_ROWS`] keeps Day's own row indices however many titles
692    /// sit above a row, and the hairline a title replaces is left out.
693    #[allow(clippy::too_many_arguments)]
694    fn build_nav_menu_rows(
695        menu: NodeId,
696        items: &[String],
697        icons: &[Option<String>],
698        tints: &[Option<day_spec::Ink>],
699        badges: &[Option<String>],
700        badge_icons: &[Option<String>],
701        badge_tints: &[Option<day_spec::Ink>],
702        sections: &[Option<String>],
703    ) -> AHandle {
704        let col = new_node(node::COLUMN);
705        let owner = col.0 as usize;
706        let mut pos = 0;
707        for (i, title) in items.iter().enumerate() {
708            if let Some(Some(section)) = sections.get(i) {
709                let heading = new_node(node::TEXT);
710                node::set_text(heading.0, section);
711                node::set_font_size(heading.0, 14.0);
712                themed(owner, heading.0, Paint::Font, 0x9900_0000, 0x99FF_FFFF);
713                node::style_nav_heading(heading.0, pos == 0);
714                node::insert_child(col.0, heading.0, pos);
715                pos += 1;
716            }
717            // A Row (vertically centered children) carries the whole-row click target.
718            let row = new_node(node::ROW);
719            let label = new_node(node::TEXT);
720            let chevron = new_node(node::TEXT);
721            let synth = next_synth();
722            MENU_ROWS.with(|m| m.borrow_mut().insert(synth, (menu, i as i64)));
723            let mut child = 0;
724            if let Some(Some(name)) = icons.get(i) {
725                let icon = row_icon(owner, name, tints.get(i).copied().flatten(), 20.0);
726                node::set_margin(icon.0, 4.0);
727                node::insert_child(row.0, icon.0, child);
728                child += 1;
729            }
730            node::set_text(label.0, title);
731            node::set_font_size(label.0, 16.0);
732            themed(owner, label.0, Paint::Font, TEXT_LIGHT, TEXT_DARK);
733            node::set_flex_grow(label.0, 1.0);
734            node::set_text(chevron.0, "\u{203a}");
735            node::set_font_size(chevron.0, 20.0);
736            themed(owner, chevron.0, Paint::Font, 0x4D00_0000, 0x66FF_FFFF);
737            node::insert_child(row.0, label.0, child);
738            // The trailing status glyph (docs/navigation.md), between the growing label and the
739            // chevron so it sits at the row's end without displacing the disclosure arrow.
740            let mut after_label = child + 1;
741            if let Some(text) = badges
742                .get(i)
743                .and_then(|v| v.as_deref())
744                .filter(|v| !v.is_empty())
745            {
746                let count = new_node(node::TEXT);
747                node::set_text(count.0, text);
748                node::set_font_size(count.0, 14.0);
749                themed(owner, count.0, Paint::Font, 0x9900_0000, 0x99FF_FFFF);
750                node::set_margin(count.0, 4.0);
751                node::insert_child(row.0, count.0, after_label);
752                after_label += 1;
753            }
754            if let Some(Some(name)) = badge_icons.get(i) {
755                let badge = row_icon(owner, name, badge_tints.get(i).copied().flatten(), 16.0);
756                node::set_margin(badge.0, 4.0);
757                node::insert_child(row.0, badge.0, after_label);
758                after_label += 1;
759            }
760            node::insert_child(row.0, chevron.0, after_label);
761            node::style_row(row.0, 52.0);
762            node::register_event(row.0, node::EV_CLICK, synth);
763            node::insert_child(col.0, row.0, pos);
764            pos += 1;
765            if i + 1 < items.len() && !matches!(sections.get(i + 1), Some(Some(_))) {
766                let sep = new_node(node::STACK);
767                themed(owner, sep.0, Paint::Separator, 0x1400_0000, 0x24FF_FFFF);
768                node::insert_child(col.0, sep.0, pos);
769                pos += 1;
770            }
771        }
772        col
773    }
774
775    /// Re-encode a decoded bitmap (docs/images.md).
776    ///
777    /// A free function rather than the duty's body so each refusal reads as an early return
778    /// instead of another copy of the same emit.
779    fn encode_bitmap(
780        id: day_spec::BitmapId,
781        spec: &day_spec::EncodeSpec,
782    ) -> Result<Vec<u8>, day_spec::ImageError> {
783        use day_spec::ImageFormat as F;
784        let mime = match spec.format {
785            F::Png => "image/png",
786            F::Jpeg => "image/jpeg",
787            // The image packer writes nothing else here; `encode_formats` says so up front.
788            _ => return Err(day_spec::ImageError::Encode),
789        };
790        if !BITMAP_INFO.with(|m| m.borrow().contains_key(&id.0)) {
791            return Err(day_spec::ImageError::Gone);
792        }
793        // OpenHarmony takes quality as 0..=100; none means the format's own default.
794        let quality = spec
795            .quality
796            .map(|q| (q.clamp(0.0, 1.0) * 100.0).round() as u32);
797        crate::images::encode(id.0, mime, quality).ok_or(day_spec::ImageError::Encode)
798    }
799
800    /// Point an image node at an [`day_spec::ImageSource`] (docs/images.md): shared by realize
801    /// and the `Source` patch, so a swap loads exactly what a fresh realize would have.
802    ///
803    /// Named is the staged-rawfile path: a vector's SVG first (docs/vectors.md), then the PNG.
804    /// Bytes and Decoded need no file at all. `tint` recolors any of them by its own alpha
805    /// (docs/images.md "Tinting"); `None` leaves whatever tint the node already has, so a
806    /// source swap keeps it.
807    /// Whether a named source resolves to a staged SVG: the form a template glyph takes.
808    fn arkui_image_is_svg(source: &day_spec::ImageSource) -> bool {
809        match source {
810            day_spec::ImageSource::Named(named) => {
811                crate::resources::rawfile_exists(&format!("day/{named}.svg"))
812            }
813            _ => false,
814        }
815    }
816
817    fn arkui_apply_image_source(
818        n: Handle,
819        source: &day_spec::ImageSource,
820        tint: Option<day_spec::Ink>,
821    ) {
822        match source {
823            day_spec::ImageSource::Named(named) => {
824                let svg = format!("day/{named}.svg");
825                if crate::resources::rawfile_exists(&svg) {
826                    node::set_image_src(n, &format!("resource://RAWFILE/{svg}"));
827                } else if !named.is_empty() {
828                    node::set_image_src(n, &format!("resource://RAWFILE/day/{named}.png"));
829                }
830            }
831            day_spec::ImageSource::Bytes(bytes) => crate::images::node_set_bytes(n, bytes),
832            day_spec::ImageSource::Decoded(id) => crate::images::node_set_bitmap(n, id.0),
833        }
834        if let Some(t) = tint {
835            paint_ink(n as usize, n, Paint::ImageTint, t);
836        }
837    }
838
839    /// Give a surface its gradient fill for a frame of `size` (docs/surfaces.md), each stop's ink
840    /// resolved for the current color mode. Before the first frame arrives the unit square
841    /// stands in, which is already exact for a vertical or horizontal linear gradient and a
842    /// centered radial or conic one.
843    ///
844    /// Linear: the gradient's unit points resolve against the frame, and ArkUI takes an angle
845    /// and stops along its own line, so both depend on the frame's shape. Radial: ArkUI's
846    /// circle (`NODE_RADIAL_GRADIENT`), the radius along the frame's shorter side
847    /// (`paint::radial_circle`). Conic: ArkUI's sweep gradient (`NODE_SWEEP_GRADIENT`), the
848    /// start angle folded into the stops (`paint::sweep_stops`).
849    fn apply_surface_gradient(n: Handle, fill: &day_spec::Paint, size: Size) {
850        let palette = palette_now();
851        let resolve = |stops: &[(f64, day_spec::Ink)]| -> Vec<(f64, u32)> {
852            stops
853                .iter()
854                .map(|(at, c)| (*at, argb(c.resolve(&palette))))
855                .collect()
856        };
857        let narrow = |stops: Vec<(f64, u32)>| -> Vec<(f32, u32)> {
858            stops.into_iter().map(|(at, c)| (at as f32, c)).collect()
859        };
860        let (w, h) = if size.width > 0.0 && size.height > 0.0 {
861            (size.width, size.height)
862        } else {
863            (1.0, 1.0)
864        };
865        match fill {
866            day_spec::Paint::Linear(g) => {
867                let (angle, stops) = crate::paint::css_linear_gradient(
868                    (g.start.x, g.start.y),
869                    (g.end.x, g.end.y),
870                    &resolve(&g.stops),
871                    w,
872                    h,
873                );
874                node::set_linear_gradient(n, angle, &stops);
875            }
876            day_spec::Paint::Radial(g) => {
877                let (cx, cy, r) =
878                    crate::paint::radial_circle((g.center.x, g.center.y), g.radius, w, h);
879                let stops = crate::paint::spanning(&narrow(resolve(&g.stops)));
880                node::set_radial_gradient(n, cx, cy, r, &stops);
881            }
882            day_spec::Paint::Conic(g) => {
883                let stops =
884                    crate::paint::sweep_stops(g.start.degrees() as f32, &narrow(resolve(&g.stops)));
885                node::set_sweep_gradient(
886                    n,
887                    (g.center.x * w) as f32,
888                    (g.center.y * h) as f32,
889                    &stops,
890                );
891            }
892            day_spec::Paint::Solid(_) => {}
893        }
894    }
895
896    /// Style a surface from its props (docs/surfaces.md): fill, corners, border, shadow and
897    /// clipping. What realize runs on a `fresh` node, and what `ContainerPatch::Surface` runs
898    /// again on the same node, where every field is set or cleared, never left as it was. Each
899    /// ink is recorded to follow the appearance (see [`paint_ink`]).
900    fn apply_surface(n: Handle, p: &ContainerProps, fresh: bool) {
901        let owner = n as usize;
902        // A role's own fill (a section card, a window ground) is realize-time and stays.
903        if !SURFACE_ROLE.with(|m| m.contains(owner)) && (p.fill.is_some() || !fresh) {
904            apply_fill(n, p.fill.as_ref(), None);
905        }
906        if fresh && p.corner_radius <= 0.0 && p.border.is_none() && p.shadow.is_none() && !p.clips {
907            return;
908        }
909        // NODE_BORDER_RADIUS in vp rounds this node's own background, and with it the
910        // gradient, the border, the shadow and the clip. A selection of corners is the
911        // attribute's four-value form.
912        if p.corners == day_spec::Corners::ALL {
913            node::set_corner_radius(n, p.corner_radius.max(0.0));
914        } else {
915            node::set_corner_radii(
916                n,
917                crate::paint::border_radii(p.corners.bits(), p.corner_radius.max(0.0) as f32),
918            );
919        }
920        if let Some(b) = p.border.filter(|b| b.width > 0.0) {
921            // Inside the frame (an ArkUI size includes its border) and painted after the
922            // children, so over the content (docs/surfaces.md "Rules"). Day places children by
923            // absolute position, so the border's inset of ArkUI's content box moves nothing.
924            node::set_border(n, b.width, ink_argb(b.color));
925            if b.color.is_dynamic() {
926                remember(owner, n, Paint::BorderColor, Tone::Ink(b.color));
927            } else {
928                forget_paint(owner, n, Paint::BorderColor);
929            }
930        } else {
931            forget_paint(owner, n, Paint::BorderColor);
932            node::clear_border(n);
933        }
934        if let Some(s) = p.shadow {
935            // The node's own shadow: any color, blur and offset, in the shape of its
936            // rounded rectangle, outside layout and hit testing. ArkUI takes the blur radius
937            // in vp and the offsets in px (`NODE_CUSTOM_SHADOW` in native_node.h).
938            let paint = move || {
939                let color = ink_argb(s.color);
940                if color >> 24 == 0 {
941                    node::clear_shadow(n);
942                    return;
943                }
944                let density = node::density();
945                node::set_shadow(
946                    n,
947                    crate::paint::shadow_radius_px(s.blur, density) / density as f32,
948                    (s.dx * density) as f32,
949                    (s.dy * density) as f32,
950                    color,
951                );
952            };
953            paint();
954            repaint_with(
955                owner,
956                n,
957                Paint::Shadow,
958                s.color.is_dynamic(),
959                Rc::new(paint),
960            );
961        } else {
962            forget_paint(owner, n, Paint::Shadow);
963            node::clear_shadow(n);
964        }
965        // `.corner_radius` wraps the piece, whose fill is an inner node, so rounding shows only
966        // when this node clips it; a patch that stops clipping stops it here.
967        node::set_clip(n, p.clips);
968    }
969
970    /// A surface's fill (docs/surfaces.md): a solid ink as the background color (under `anim`,
971    /// the color animates), a gradient over a clear background (at once), or nothing.
972    fn apply_fill(n: Handle, fill: Option<&day_spec::Paint>, anim: Option<&AnimSpec>) {
973        let owner = n as usize;
974        match fill {
975            Some(day_spec::Paint::Solid(ink)) => {
976                let ink = *ink;
977                if SURFACE_GRADIENTS.with(|m| m.remove(owner)).is_some() {
978                    forget_paint(owner, n, Paint::Gradient);
979                    node::clear_gradients(n);
980                }
981                crate::anim::animate(n, crate::anim::Channel::Background, anim, move || {
982                    node::set_bg_color(n, ink_argb(ink));
983                });
984                if ink.is_dynamic() {
985                    remember(owner, n, Paint::Background, Tone::Ink(ink));
986                } else {
987                    forget_paint(owner, n, Paint::Background);
988                }
989            }
990            Some(gradient) => {
991                forget_paint(owner, n, Paint::Background);
992                crate::anim::animate(n, crate::anim::Channel::Background, None, move || {
993                    node::set_bg_color(n, 0);
994                });
995                node::clear_gradients(n);
996                // Kept so `set_frame` can resolve it against each new size; the size it was
997                // last resolved at carries over from the fill it replaces.
998                let size = SURFACE_GRADIENTS
999                    .with(|m| m.get(owner))
1000                    .map_or_else(Size::default, |(_, size)| size);
1001                apply_surface_gradient(n, gradient, size);
1002                SURFACE_GRADIENTS.with(|m| m.insert(owner, (gradient.clone(), size)));
1003                repaint_with(
1004                    owner,
1005                    n,
1006                    Paint::Gradient,
1007                    gradient.is_dynamic(),
1008                    Rc::new(move || {
1009                        if let Some((g, size)) = SURFACE_GRADIENTS.with(|m| m.get(owner)) {
1010                            apply_surface_gradient(n, &g, size);
1011                        }
1012                    }),
1013                );
1014            }
1015            None => {
1016                forget_paint(owner, n, Paint::Background);
1017                if SURFACE_GRADIENTS.with(|m| m.remove(owner)).is_some() {
1018                    forget_paint(owner, n, Paint::Gradient);
1019                    node::clear_gradients(n);
1020                }
1021                // A fill going away goes at once (docs/tween.md rule 8).
1022                crate::anim::animate(n, crate::anim::Channel::Background, None, move || {
1023                    node::set_bg_color(n, 0);
1024                });
1025            }
1026        }
1027    }
1028
1029    pub fn emit(id: NodeId, ev: Event) {
1030        let sink = SINK.with(|s| s.borrow().clone());
1031        if let Some(sink) = sink {
1032            sink(id, ev);
1033        }
1034    }
1035
1036    /// Emit `ev` on the next loop turn: for events produced inside a toolkit duty (which runs
1037    /// under the tree borrow, so a synchronous emit would re-enter it).
1038    fn post_emit(id: NodeId, ev: Event) {
1039        crate::main_thread::post_local(Box::new(move || emit(id, ev)));
1040    }
1041
1042    /// Pieces whose component exists only in ArkTS (docs/extending.md).
1043    ///
1044    /// The ArkUI C node API has no node kind for the declarative `Web` or `Map` components, so a
1045    /// piece wrapping one ships an `.ets` (staged into the hvigor project by `day build`) that
1046    /// builds it in a `BuilderNode`; this module mounts that `FrameNode` in a native Stack and hands
1047    /// the Stack back as an [`AHandle`] Day mounts like any other node.
1048    ///
1049    /// The wrapper is what makes Day's layout reach the component. The C API refuses to set
1050    /// attributes on a BuilderNode-generated node (`ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE`),
1051    /// so `set_frame` on the `FrameNode` itself was silently dropped: the component kept ArkUI's
1052    /// default layout, filling its parent from (0, 0) and covering the siblings Day had laid out
1053    /// around it (the web view over its URL bar). Day positions and sizes the wrapper, which it
1054    /// created, and the component fills it. `props`, `cmd`, and `arg` are opaque strings the piece
1055    /// defines; the bridge stays generic, so a new piece needs no host change.
1056    pub mod piece {
1057        use super::{AHandle, PIECE_NODES, node};
1058        use day_spec::NodeId;
1059
1060        /// Build the ArkTS component registered for `kind`. A null handle means no ArkTS piece
1061        /// factory is registered (or it declined `kind`); the caller should fall back to Day's
1062        /// placeholder leaf, exactly as an unregistered renderer does.
1063        #[must_use]
1064        pub fn make(kind: day_spec::PieceKind, id: NodeId, props: &str) -> AHandle {
1065            try_make(kind, id, props).unwrap_or_else(|| {
1066                // No ArkTS module claimed the kind (or building it threw). Hand back a real empty
1067                // node, never a null handle: the tree mounts this like any leaf, and a null would
1068                // take its whole parent's layout down instead of leaving one blank rectangle.
1069                // Reported so `assert_no_placeholders` sees it, exactly like a missing renderer.
1070                day_spec::placeholder::report(kind, "arkui");
1071                super::new_node(node::STACK)
1072            })
1073        }
1074
1075        /// [`make`], answering `None` where no ArkTS module claims `kind`, for a caller with a
1076        /// native fallback of its own (the menu-style picker keeps the wheel on a host too old
1077        /// to register its `Select`).
1078        #[must_use]
1079        pub fn try_make(kind: &str, id: NodeId, props: &str) -> Option<AHandle> {
1080            let h = crate::host_api::piece_make(kind, id.0, props);
1081            if h.is_null() {
1082                return None;
1083            }
1084            let wrapper = super::new_node(node::STACK);
1085            node::add_child(wrapper.0, h);
1086            // Remembered so `release` can send the ArkTS side its disposal, and so it knows
1087            // NOT to dispose the ArkTS-owned node itself.
1088            PIECE_NODES.with(|m| {
1089                m.borrow_mut()
1090                    .insert(wrapper.0 as usize, (id.0, h as usize))
1091            });
1092            Some(wrapper)
1093        }
1094
1095        /// Whether `h` is an ArkTS-built piece node.
1096        pub(crate) fn is_piece(h: &AHandle) -> bool {
1097            PIECE_NODES.with(|m| m.borrow().contains_key(&(h.0 as usize)))
1098        }
1099
1100        /// Send a command to a piece's ArkTS component. Takes the handle rather than the node id
1101        /// because that is what a `Renderer`'s `update` is handed; the id it was made with is
1102        /// remembered here. A handle that isn't an ArkTS piece node is a no-op.
1103        pub fn update(h: &AHandle, cmd: &str, arg: &str) {
1104            let Some((id, _)) = PIECE_NODES.with(|m| m.borrow().get(&(h.0 as usize)).copied())
1105            else {
1106                return;
1107            };
1108            crate::host_api::piece_update(id, cmd, arg);
1109        }
1110    }
1111
1112    /// day `Color` (0..1 components) → ArkUI ARGB `u32`.
1113    fn argb(c: day_spec::Color) -> u32 {
1114        let f = |x: f64| (x.clamp(0.0, 1.0) * 255.0).round() as u32;
1115        (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)
1116    }
1117
1118    /// Semantic [`Font`] → a vp point size (ArkUI's default length unit is vp ≈ day points).
1119    /// Public for standalone pieces (docs/extending.md), which resolve the same scale.
1120    #[must_use]
1121    pub fn font_vp(f: FontSpec) -> f64 {
1122        match f.style {
1123            Font::LargeTitle => 34.0,
1124            Font::Title => 28.0,
1125            Font::Title2 => 22.0,
1126            Font::Title3 => 20.0,
1127            #[expect(
1128                clippy::match_same_arms,
1129                reason = "one row per text style, in the order of the type scale it mirrors"
1130            )]
1131            Font::Headline => 17.0,
1132            Font::Body => 17.0,
1133            Font::Callout => 16.0,
1134            Font::Subheadline => 15.0,
1135            Font::Footnote => 13.0,
1136            Font::Caption => 12.0,
1137            Font::Caption2 => 11.0,
1138            Font::System(pt) | Font::Custom(_, pt) => pt,
1139        }
1140    }
1141
1142    /// A label's font size in fp: its style's size times its own scale
1143    /// ([`FontSpec::resolved_points`]). ArkUI's fp follows the system text size itself.
1144    fn label_fp(f: FontSpec) -> f64 {
1145        f.resolved_points(font_vp(f))
1146    }
1147
1148    /// ArkUI's font feature string for `spec` (`"tnum" on, "smcp" on`), empty for none.
1149    fn feature_string(spec: FontSpec) -> String {
1150        spec.feature_tags()
1151            .iter()
1152            .map(|tag| format!("\"{tag}\" on"))
1153            .collect::<Vec<_>>()
1154            .join(", ")
1155    }
1156
1157    /// ArkUI's line style for a Day decoration style: every style has a native form.
1158    fn decoration_style(
1159        style: day_spec::DecorationStyle,
1160    ) -> ohos_sys::arkui::native_type::ArkUI_TextDecorationStyle {
1161        use ohos_sys::arkui::native_type::ArkUI_TextDecorationStyle as S;
1162        match style {
1163            day_spec::DecorationStyle::Single => S::ARKUI_TEXT_DECORATION_STYLE_SOLID,
1164            day_spec::DecorationStyle::Double => S::ARKUI_TEXT_DECORATION_STYLE_DOUBLE,
1165            day_spec::DecorationStyle::Dotted => S::ARKUI_TEXT_DECORATION_STYLE_DOTTED,
1166            day_spec::DecorationStyle::Wavy => S::ARKUI_TEXT_DECORATION_STYLE_WAVY,
1167        }
1168    }
1169
1170    /// A label's paragraph (docs/text.md): the line limit (one line when it does not wrap), the
1171    /// truncation mode, and the letter spacing and line height, both multiples of the label's
1172    /// font size, which is read back from the node so a font change recomputes them.
1173    fn apply_paragraph(n: Handle, para: day_spec::props::LabelParagraph, wraps: bool) {
1174        use ohos_sys::arkui::native_node::ArkUI_NodeAttributeType as Attr;
1175        let _ = LABEL_PARA.with(|t| t.insert(n as usize, (para, wraps)));
1176        let size = f64::from(node::get_f32(n, Attr::NODE_FONT_SIZE, 0).unwrap_or(17.0));
1177        let lines = if wraps { para.max_lines } else { 1 };
1178        let spacing = (para.letter_spacing.is_finite() && para.letter_spacing != 0.0)
1179            .then_some((para.letter_spacing * size) as f32);
1180        let height = (para.line_height.is_finite() && para.line_height > 0.0)
1181            .then_some((para.line_height * size) as f32);
1182        node::label_paragraph(n, lines, para.truncation, spacing, height);
1183    }
1184
1185    /// Apply a `Font::Custom` family (§18.4): the family was registered by the
1186    /// platform/harmony scaffold's `EntryAbility` (from rawfile `day/fonts.json`), so `NODE_FONT_FAMILY` resolves it
1187    /// by name; ArkUI falls back to the default family when it doesn't.
1188    fn apply_font_attrs(n: Handle, spec: FontSpec) {
1189        if let Font::Custom(family, _) = spec.style {
1190            node::set_font_family(n, family);
1191        }
1192        // Tabular figures, small capitals, old-style figures. Set unconditionally (an empty
1193        // string clears it) so a label that stops asking for them goes back on the next patch.
1194        node::set_font_feature(n, &feature_string(spec));
1195        // Weight and italic, also unconditional. An explicit weight wins; otherwise the style's
1196        // own (a headline is semibold, as on Android and Apple).
1197        let weight = spec.weight.unwrap_or(match spec.style {
1198            Font::Headline => day_spec::FontWeight::Semibold,
1199            _ => day_spec::FontWeight::Regular,
1200        });
1201        node::set_font_weight_style(n, i32::from(weight.css()), spec.italic);
1202    }
1203
1204    /// Rebuild a label's SPAN children from its runs (docs/text-runs.md).
1205    ///
1206    /// ArkUI is the one backend where runs are child NODES rather than attributes on one widget: a
1207    /// styled Text is a small subtree. Day's own layout still treats the label as a leaf, because
1208    /// ArkUI measures the spans itself and reports the Text's size.
1209    ///
1210    /// A span's colors are concrete, so runs with a pair or a role among their inks (a link's
1211    /// `SystemColor::Link` included) are rebuilt on every appearance switch.
1212    fn set_label_runs(n: Handle, text: &str, runs: &[day_spec::TextRun]) {
1213        let id = CTRL_NODE.with(|m| m.borrow().get(&(n as usize)).copied());
1214        if runs.is_empty() {
1215            forget_paint(n as usize, n, Paint::Runs);
1216            // Plain text goes back on the Text itself; `runs_begin` cleared it when runs arrived.
1217            // Any spans go first: a Text still holding them would keep drawing them.
1218            node::label_runs_clear(n);
1219            node::set_text(n, text);
1220            return;
1221        }
1222        let dynamic = runs.iter().any(|r| {
1223            r.link.is_some()
1224                || [r.color, r.background]
1225                    .into_iter()
1226                    .chain(
1227                        [&r.underline, &r.strikethrough].map(|d| d.as_ref().and_then(|d| d.color)),
1228                    )
1229                    .flatten()
1230                    .any(day_spec::Ink::is_dynamic)
1231        });
1232        let (owned_text, owned_runs) = (text.to_owned(), runs.to_vec());
1233        repaint_with(
1234            n as usize,
1235            n,
1236            Paint::Runs,
1237            dynamic,
1238            Rc::new(move || set_label_runs(n, &owned_text, &owned_runs)),
1239        );
1240        node::label_runs_begin(n);
1241        let add = |slice: &str, run: Option<&day_spec::TextRun>| {
1242            let mut style = node::RunStyle::default();
1243            if let Some(r) = run {
1244                // The span's size is absolute in ArkUI, so a relative scale multiplies against
1245                // the size this run's own style resolves to: the same `font_vp` ramp the label
1246                // itself uses.
1247                let base_fp = font_vp(r.font);
1248                let scale_permille = (r.font.scale * 1000.0).round() as i32;
1249                if scale_permille != 1000 && scale_permille > 0 && base_fp > 0.0 {
1250                    style.size_fp = Some(base_fp * f64::from(scale_permille) / 1000.0);
1251                }
1252                style.bold = r
1253                    .font
1254                    .weight
1255                    .is_some_and(|w| w >= day_spec::FontWeight::Semibold);
1256                style.italic = r.font.italic;
1257                style.monospace = r.font.monospace;
1258                let line =
1259                    |d: &day_spec::Decoration| (decoration_style(d.style), d.color.map(ink_argb));
1260                style.strikethrough = r.strikethrough.as_ref().map(line);
1261                style.underline = r.underline.as_ref().map(line);
1262                let features = feature_string(r.font);
1263                style.features = (!features.is_empty()).then_some(features);
1264                style.color = r.color.map(ink_argb);
1265                style.background = r.background.map(ink_argb);
1266                if r.link.is_some() {
1267                    // SPAN click handlers do not supply link styling: the theme's link color,
1268                    // while preserving an author's explicit run color.
1269                    style
1270                        .color
1271                        .get_or_insert_with(|| ink_argb(day_spec::SystemColor::Link.into()));
1272                    style
1273                        .underline
1274                        .get_or_insert((decoration_style(day_spec::DecorationStyle::Single), None));
1275                }
1276            }
1277            let link = id.zip(run.and_then(|r| r.link.as_deref()));
1278            node::label_runs_add(n, slice, &style, link);
1279        };
1280        let mut at = 0usize;
1281        for r in runs {
1282            let Some(styled) = text.get(r.range.clone()) else {
1283                continue;
1284            };
1285            if r.range.start > at
1286                && let Some(plain) = text.get(at..r.range.start)
1287            {
1288                add(plain, None);
1289            }
1290            add(styled, Some(r));
1291            at = r.range.end;
1292        }
1293        if let Some(tail) = text.get(at..) {
1294            add(tail, None);
1295        }
1296    }
1297
1298    fn clear_button_content(n: AHandle) {
1299        if let Some(children) = BUTTON_CHILDREN.with(|m| m.borrow_mut().remove(&(n.0 as usize))) {
1300            if let Some(root) = children.first() {
1301                node::remove_child(n.0, root.0);
1302                for child in children.iter().skip(1) {
1303                    node::remove_child(root.0, child.0);
1304                }
1305            }
1306            for child in children.into_iter().rev() {
1307                node::dispose(child.0);
1308            }
1309        }
1310    }
1311
1312    /// An icon as an image URI ArkUI loads: a standard symbol staged into the app's sandbox
1313    /// cache (a file URI, since `NODE_IMAGE_SRC` reads a bare path as the name of a bundled asset:
1314    /// "`GetAsset` failed"), or a bundled image from the app's rawfiles.
1315    fn icon_source(icon: &day_spec::Icon) -> Option<String> {
1316        match icon {
1317            day_spec::Icon::Symbol(s) => day_spec::resource::stage_symbol_svg(*s)
1318                .map(|p| format!("file://{}", p.to_string_lossy())),
1319            day_spec::Icon::Image(name) => {
1320                let vector = crate::resources::rawfile_exists(&format!("day/{name}.svg"));
1321                let raster = crate::resources::rawfile_exists(&format!("day/{name}.png"));
1322                (vector || raster).then(|| {
1323                    format!(
1324                        "resource://RAWFILE/day/{name}.{}",
1325                        if vector { "svg" } else { "png" }
1326                    )
1327                })
1328            }
1329        }
1330    }
1331
1332    fn apply_button_content(
1333        n: AHandle,
1334        title: &str,
1335        icon: Option<&day_spec::Icon>,
1336        icon_only: bool,
1337    ) {
1338        clear_button_content(n);
1339        let source = icon.and_then(icon_source);
1340        node::set_a11y_text(n.0, title);
1341        node::set_button_label(n.0, if source.is_some() { "" } else { title });
1342        if let Some(source) = source {
1343            let ink = BUTTON_INK
1344                .with(|m| m.get(n.0 as usize))
1345                .unwrap_or(0xFFFF_FFFF);
1346            let row = new_node(node::ROW);
1347            let image = new_node(node::IMAGE);
1348            let mut children = vec![row, image];
1349            node::set_image_src(image.0, &source);
1350            node::set_image_fill(image.0, ink);
1351            node::set_size(image.0, 20.0, 20.0);
1352            node::insert_child(row.0, image.0, 0);
1353            if !icon_only {
1354                let label = new_node(node::TEXT);
1355                node::set_text(label.0, &format!("  {title}"));
1356                node::set_font_color(label.0, ink);
1357                node::insert_child(row.0, label.0, 1);
1358                children.push(label);
1359            }
1360            node::insert_child(n.0, row.0, 0);
1361            BUTTON_CHILDREN.with(|m| m.borrow_mut().insert(n.0 as usize, children));
1362        }
1363    }
1364
1365    /// `ButtonProps::selected`: ArkUI's Button has no checked state, so the selected look is
1366    /// the prominent fill and ink over the button's own style, which deselecting restores.
1367    fn apply_button_selected(n: Handle, on: bool) {
1368        BUTTON_SELECTED.with(|m| {
1369            m.borrow_mut().insert(n as usize, on);
1370        });
1371        let style = BUTTON_STYLE
1372            .with(|m| m.borrow().get(&(n as usize)).copied())
1373            .unwrap_or_default();
1374        apply_button_style(n, style);
1375    }
1376
1377    fn apply_button_style(n: Handle, style: day_spec::props::ButtonStyleSpec) {
1378        use day_spec::props::ButtonStyleSpec as S;
1379        BUTTON_STYLE.with(|m| {
1380            m.borrow_mut().insert(n as usize, style);
1381        });
1382        let selected = BUTTON_SELECTED
1383            .with(|m| m.borrow().get(&(n as usize)).copied())
1384            .unwrap_or(false);
1385        let (fill, ink, border) = match style {
1386            _ if selected => (0xFF33_7DFF, 0xFFFF_FFFF, 0.0),
1387            S::Automatic | S::Compact | S::Plain => (0, 0xFF33_7DFF, 0.0),
1388            S::Bordered => (0, 0xFF33_7DFF, 1.0),
1389            S::Prominent => (0xFF33_7DFF, 0xFFFF_FFFF, 0.0),
1390            S::Tinted(c) => (
1391                ink_argb(c),
1392                argb(S::on_tint(c.resolve(&palette_now()))),
1393                0.0,
1394            ),
1395        };
1396        // A tint that is a pair or a role restyles the button on an appearance switch; the
1397        // style is read back from `BUTTON_STYLE` then, so a later style change wins.
1398        let dynamic = matches!(style, S::Tinted(c) if c.is_dynamic()) && !selected;
1399        repaint_with(
1400            n as usize,
1401            n,
1402            Paint::Button,
1403            dynamic,
1404            Rc::new(move || {
1405                if let Some(style) = BUTTON_STYLE.with(|m| m.borrow().get(&(n as usize)).copied()) {
1406                    apply_button_style(n, style);
1407                }
1408            }),
1409        );
1410        BUTTON_INK.with(|m| {
1411            m.insert(n as usize, ink);
1412        });
1413        BUTTON_CHILDREN.with(|m| {
1414            if let Some(children) = m.borrow().get(&(n as usize)) {
1415                if let Some(image) = children.get(1) {
1416                    node::set_image_fill(image.0, ink);
1417                }
1418                if let Some(label) = children.get(2) {
1419                    node::set_font_color(label.0, ink);
1420                }
1421            }
1422        });
1423        // Reset all style attributes, including when changing away from a tint or border.
1424        // Keep the native button so press, focus, accessibility and disabled behavior survive.
1425        node::set_bg_color(n, fill);
1426        node::set_font_color(n, ink);
1427        node::set_button_border(n, border, ink);
1428    }
1429
1430    fn new_node(kind: ohos_sys::arkui::native_node::ArkUI_NodeType) -> AHandle {
1431        AHandle(if kind == node::IMAGE {
1432            node::create_image()
1433        } else {
1434            node::create(kind)
1435        })
1436    }
1437
1438    /// The ArkTS hosts for menu and segmented pickers (DaySelect.ets).
1439    const MENU_PICKER_KIND: &str = "day.picker.menu";
1440    const SEGMENTED_PICKER_KIND: &str = "day.picker.segmented";
1441
1442    /// A menu picker's props and `options` command: the selected index (empty to keep the
1443    /// current one), then each option, 0x1F-separated (DaySelect.ets parses it). An option can't
1444    /// contain the separator, a control character no label carries; one that does loses it
1445    /// rather than splitting.
1446    fn select_props(selected: Option<usize>, options: &[String]) -> String {
1447        let mut out = selected.map_or_default(|i| i.to_string());
1448        for o in options {
1449            out.push('\u{1F}');
1450            out.extend(o.chars().filter(|c| *c != '\u{1F}'));
1451        }
1452        out
1453    }
1454
1455    /// The application's color mode changed (docs/settings.md): repaint every paint that
1456    /// follows it for the new mode, then let `dark_mode()` readers recolor. The system theme's
1457    /// colors are read again, in case the theme itself changed, and a change there repaints
1458    /// even when the mode did not.
1459    fn appearance_changed(dark: bool) {
1460        let before = palette_now();
1461        SYSTEM_COLORS.with(|c| *c.borrow_mut() = [None, None]);
1462        PALETTE.with(|p| p.set(None));
1463        let after = palette_for(before.dark);
1464        repaint_themed(dark, after != before);
1465        day_core::note_appearance_changed();
1466    }
1467
1468    /// The animation scale changed under the app (docs/accessibility.md): day-core re-reads
1469    /// `reduce_motion()` and re-gates its transitions.
1470    fn motion_changed() {
1471        day_core::note_motion_changed();
1472    }
1473
1474    /// Move `IS_DARK` to `dark`, repainting every theme-following paint if it changed (or
1475    /// `force`, when the theme's colors changed under the same mode).
1476    fn repaint_themed(dark: bool, force: bool) {
1477        if IS_DARK.with(|d| d.replace(dark)) == dark && !force {
1478            return;
1479        }
1480        PALETTE.with(|p| p.set(None));
1481        // A snapshot: a repaint can record its paint again (a label's runs, a tinted button).
1482        let paints: Vec<(usize, Paint, Tone)> =
1483            THEMED.with(|t| t.borrow().values().flatten().cloned().collect());
1484        for (n, paint, tone) in paints {
1485            tone.apply(n as Handle, paint);
1486        }
1487    }
1488
1489    /// The system theme's color for `role` in one color mode, read once per mode.
1490    fn system_argb(role: day_spec::SystemColor, dark: bool) -> Option<u32> {
1491        SYSTEM_COLORS.with(|c| {
1492            let mut c = c.borrow_mut();
1493            let slot = &mut c[usize::from(dark)];
1494            if slot.is_none() {
1495                *slot = Some(
1496                    crate::host::system_colors(dark)
1497                        .unwrap_or([None; day_spec::SystemColor::COUNT]),
1498                );
1499            }
1500            slot.and_then(|colors| colors[usize::from(role.wire())])
1501        })
1502    }
1503
1504    /// Every role in one color mode: the system theme's color where it has one, Day's own pair
1505    /// (`SystemColor::fallback`) where it has none.
1506    fn palette_for(dark: bool) -> day_spec::Palette {
1507        day_spec::Palette {
1508            dark,
1509            colors: day_spec::SystemColor::ALL
1510                .map(|role| system_argb(role, dark).map_or_else(|| role.fallback(dark), color_of)),
1511        }
1512    }
1513
1514    /// The palette of the current color mode (`IS_DARK`), what this backend resolves inks
1515    /// against. The same answer `system_color` gives day-core, so `day::resolve` agrees.
1516    fn palette_now() -> day_spec::Palette {
1517        if let Some(p) = PALETTE.with(Cell::get) {
1518            return p;
1519        }
1520        let p = palette_for(IS_DARK.with(Cell::get));
1521        PALETTE.with(|c| c.set(Some(p)));
1522        p
1523    }
1524
1525    /// `0xAARRGGBB` as a day `Color`.
1526    fn color_of(argb: u32) -> day_spec::Color {
1527        let ch = |shift: u32| f64::from((argb >> shift) & 0xff) / 255.0;
1528        day_spec::Color::rgba(ch(16), ch(8), ch(0), ch(24))
1529    }
1530
1531    /// An ink as the ARGB it shows in the current color mode.
1532    fn ink_argb(ink: day_spec::Ink) -> u32 {
1533        argb(ink.resolve(&palette_now()))
1534    }
1535
1536    /// Which attribute a theme-following paint sets. The first five take one color; the rest
1537    /// are repainted by running their apply again ([`Tone::Again`]).
1538    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1539    enum Paint {
1540        Background,
1541        Font,
1542        ImageFill,
1543        /// A raster's or vector's `.tint` (the color filter `set_image_tint` sets).
1544        ImageTint,
1545        Separator,
1546        /// A surface's border color; its width stays.
1547        BorderColor,
1548        Shadow,
1549        /// A surface's gradient fill.
1550        Gradient,
1551        /// A label's styled runs.
1552        Runs,
1553        /// A tinted button's fill and title.
1554        Button,
1555    }
1556
1557    impl Paint {
1558        fn apply(self, n: Handle, argb: u32) {
1559            match self {
1560                Paint::Background => node::set_bg_color(n, argb),
1561                Paint::Font => node::set_font_color(n, argb),
1562                Paint::ImageFill => node::set_image_fill(n, argb),
1563                Paint::ImageTint => node::set_image_tint(n, argb),
1564                Paint::Separator => node::menu_separator(n, argb),
1565                Paint::BorderColor => node::set_border_color(n, argb),
1566                // Several attributes at once: only ever a `Tone::Again`.
1567                Paint::Shadow | Paint::Gradient | Paint::Runs | Paint::Button => {}
1568            }
1569        }
1570    }
1571
1572    /// How a theme-following paint picks its color for the current mode.
1573    #[derive(Clone)]
1574    enum Tone {
1575        /// This backend's own neutral pair (light ARGB, dark ARGB).
1576        Pair(u32, u32),
1577        /// An app's dynamic ink: a light/dark pair or a system role (docs/color.md).
1578        Ink(day_spec::Ink),
1579        /// Run the paint's apply again: it resolves its inks as it goes.
1580        Again(Rc<dyn Fn()>),
1581    }
1582
1583    impl Tone {
1584        fn apply(&self, n: Handle, paint: Paint) {
1585            match self {
1586                Tone::Pair(light, dark) => paint.apply(n, theme_color(*light, *dark)),
1587                Tone::Ink(ink) => paint.apply(n, ink_argb(*ink)),
1588                Tone::Again(f) => f(),
1589            }
1590        }
1591    }
1592
1593    /// Remember `tone` for `n`'s `paint`, replacing what that attribute followed before.
1594    fn remember(owner: usize, n: Handle, paint: Paint, tone: Tone) {
1595        THEMED.with(|t| {
1596            let mut t = t.borrow_mut();
1597            let paints = t.entry(owner).or_default();
1598            paints.retain(|(p, k, _)| !(*p == n as usize && *k == paint));
1599            paints.push((n as usize, paint, tone));
1600        });
1601    }
1602
1603    /// Paint `n` with the color mode's pick of `light`/`dark`, and repaint it whenever the
1604    /// mode changes (the C nodes don't re-theme an explicit color). `owner` is the node whose
1605    /// release or rebuild ends the paint ([`forget_themed`]): the node itself for a Day node, the
1606    /// rows column or suite host for the chrome this backend builds inside one.
1607    fn themed(owner: usize, n: Handle, paint: Paint, light: u32, dark: u32) {
1608        paint.apply(n, theme_color(light, dark));
1609        remember(owner, n, paint, Tone::Pair(light, dark));
1610    }
1611
1612    /// Paint `n` with an app's ink (docs/color.md "How a toolkit follows the appearance"): its
1613    /// color now, and again on every appearance switch when it is a pair or a role. A fixed
1614    /// ink ends whatever that attribute followed before.
1615    fn paint_ink(owner: usize, n: Handle, paint: Paint, ink: day_spec::Ink) {
1616        paint.apply(n, ink_argb(ink));
1617        if ink.is_dynamic() {
1618            remember(owner, n, paint, Tone::Ink(ink));
1619        } else {
1620            forget_paint(owner, n, paint);
1621        }
1622    }
1623
1624    /// Follow the appearance by running `again` (which resolves its own inks) on every switch
1625    /// while `dynamic`; otherwise stop following. The caller has already applied it once.
1626    fn repaint_with(owner: usize, n: Handle, paint: Paint, dynamic: bool, again: Rc<dyn Fn()>) {
1627        if dynamic {
1628            remember(owner, n, paint, Tone::Again(again));
1629        } else {
1630            forget_paint(owner, n, paint);
1631        }
1632    }
1633
1634    /// Stop repainting what `owner` holds: it is being released or rebuilt.
1635    fn forget_themed(owner: usize) {
1636        THEMED.with(|t| t.borrow_mut().remove(&owner));
1637    }
1638
1639    /// Stop repainting one attribute of one node (an app color replaced the neutral one).
1640    fn forget_paint(owner: usize, n: Handle, paint: Paint) {
1641        THEMED.with(|t| {
1642            if let Some(paints) = t.borrow_mut().get_mut(&owner) {
1643                paints.retain(|(p, k, _)| !(*p == n as usize && *k == paint));
1644            }
1645        });
1646    }
1647
1648    /// The primary text color a label without one of its own takes.
1649    const TEXT_LIGHT: u32 = 0xE500_0000;
1650    const TEXT_DARK: u32 = 0xE6FF_FFFF;
1651
1652    /// The width of `text` in the Select's own face (16 vp, medium weight).
1653    fn select_label_width(text: &str) -> f64 {
1654        crate::fonts::measure_text(
1655            text,
1656            16.0,
1657            i32::from(day_spec::FontWeight::Medium.css()),
1658            false,
1659            "",
1660        )[0]
1661    }
1662
1663    /// Size a freshly built menu picker for its widest option. The button's chrome (padding and
1664    /// arrow) is what its first measure reports beyond the label it shows; a Select sized to its
1665    /// current label would clip a longer choice until something else relaid the row.
1666    fn size_menu_picker(h: &AHandle, shown: Option<&str>, options: &[String]) {
1667        let (w, hh) = node::measure(h.0, 0.0, 0.0);
1668        let chrome = (w - shown.map_or(0.0, select_label_width)).max(40.0);
1669        let size = Size::new(chrome + widest_label(options), hh.max(40.0));
1670        MENU_PICKER_SIZE.with(|m| m.borrow_mut().insert(h.0 as usize, (Some(chrome), size)));
1671        piece::update(h, "width", &size.width.to_string());
1672    }
1673
1674    /// Re-size a menu picker for new options.
1675    fn resize_menu_picker(h: &AHandle, options: &[String]) {
1676        let Some((chrome, size)) =
1677            MENU_PICKER_SIZE.with(|m| m.borrow().get(&(h.0 as usize)).copied())
1678        else {
1679            return;
1680        };
1681        let width = chrome.map_or_else(
1682            || segmented_width(options),
1683            |chrome| chrome + widest_label(options),
1684        );
1685        if (width - size.width).abs() >= 0.5 {
1686            let size = Size::new(width, size.height);
1687            MENU_PICKER_SIZE.with(|m| m.borrow_mut().insert(h.0 as usize, (chrome, size)));
1688            piece::update(h, "width", &width.to_string());
1689        }
1690    }
1691
1692    fn segmented_width(options: &[String]) -> f64 {
1693        (widest_label(options) + 24.0).max(48.0) * options.len() as f64 + 8.0
1694    }
1695
1696    fn size_segmented_picker(h: &AHandle, options: &[String]) {
1697        let size = Size::new(segmented_width(options), 40.0);
1698        MENU_PICKER_SIZE.with(|m| m.borrow_mut().insert(h.0 as usize, (None, size)));
1699        piece::update(h, "width", &size.width.to_string());
1700    }
1701
1702    /// Enable or disable a menu or segmented picker. The C API cannot set attributes on the
1703    /// ArkTS-built Select or buttons, so DaySelect.ets applies `.enabled()` to each of them; the
1704    /// wrapper Day created carries `NODE_ENABLED` too, which is what `read_native` reports.
1705    fn set_picker_piece_enabled(h: &AHandle, enabled: bool) {
1706        node::set_enabled(h.0, enabled);
1707        piece::update(h, "enabled", if enabled { "1" } else { "0" });
1708    }
1709
1710    fn widest_label(options: &[String]) -> f64 {
1711        options
1712            .iter()
1713            .map(|o| select_label_width(o))
1714            .fold(0.0, f64::max)
1715            .ceil()
1716    }
1717
1718    /// The theme-adaptive pick: `light` under the light theme, `dark` under dark.
1719    fn theme_color(light: u32, dark: u32) -> u32 {
1720        if IS_DARK.with(std::cell::Cell::get) {
1721            dark
1722        } else {
1723            light
1724        }
1725    }
1726
1727    /// Set up the window root and density from the ArkTS host, before `launch_with`. Called by
1728    /// `day::arkui::start` (via the `day::day_start_arkui!` entry macro) with the `NodeContent`
1729    /// handle the host's `start` export received.
1730    #[allow(clippy::not_unsafe_ptr_arg_deref)] // `content` is a trusted NodeContent handle
1731    pub fn init(content: *mut std::ffi::c_void, w_vp: f64, h_vp: f64, density: f64) {
1732        // Reached from the ArkTS host's NAPI start call: contained like every FFI entry.
1733        day_spec::ffi_guard::contain((), || {
1734            node::set_density(density);
1735            let dark = match std::env::var("DAY_THEME").ok().as_deref() {
1736                Some("dark") => true,
1737                Some("light") => false,
1738                _ => std::env::var("DAY_ARKUI_DARK").ok().as_deref() == Some("1"),
1739            };
1740            IS_DARK.with(|d| d.set(dark));
1741            // Follow the color mode live (a system switch, or the app's own override coming
1742            // back): neutral paints branch on IS_DARK, and `dark_mode()` closures recolor.
1743            crate::host::watch_appearance(appearance_changed);
1744            // And the user's animation scale, the reduce-motion setting here; `launch_with`
1745            // does the first read once the tree stands.
1746            crate::host::watch_reduce_motion(motion_changed);
1747            // And the text-size setting: fp sizes follow it natively, Day re-measures.
1748            crate::host::watch_font_scale(day_core::note_text_size_changed);
1749            // Serve bundled data resources (§18.3) from the app's rawfile store. Registered once
1750            // here; the opener is a no-op until the ArkTS host hands us its resourceManager.
1751            day_spec::resource::set_resource_opener(open_resource);
1752            // A Stack fills the window; day mounts its tree under it and positions children
1753            // absolutely.
1754            let root = new_node(node::STACK);
1755            node::set_frame(root.0, 0.0, 0.0, w_vp, h_vp);
1756            node::content_add(content.cast(), root.0);
1757            ROOT.with(|r| *r.borrow_mut() = Some((root, Size::new(w_vp, h_vp))));
1758            ROOT_KEEP.with(|r| r.set(Some((root.0 as usize, w_vp, h_vp))));
1759            // Every touch bubbles here, which is where the device kind behind it is read
1760            // (docs/gestures.md "Input kind"); observed, never consumed.
1761            node::register_event(root.0, node::EV_TOUCH, day_spec::WINDOW_NODE.0);
1762        });
1763    }
1764
1765    pub(crate) fn cover_layer_init(content: ohos_sys::arkui::native_type::ArkUI_NodeContentHandle) {
1766        if content.is_null() || COVER_ROOT.with(|r| r.get().is_some()) {
1767            return;
1768        }
1769        let root = new_node(node::STACK);
1770        node::content_add(content, root.0);
1771        COVER_ROOT.with(|r| r.set(Some((root.0 as usize, 0.0, 0.0))));
1772    }
1773
1774    pub(crate) fn cover_layer_resized(w: f64, h: f64) {
1775        if w <= 0.0 || h <= 0.0 {
1776            return;
1777        }
1778        COVER_ROOT.with(|r| {
1779            if let Some((root, _, _)) = r.get() {
1780                r.set(Some((root, w, h)));
1781                node::set_frame(root as Handle, 0.0, 0.0, w, h);
1782            }
1783        });
1784        let covers: Vec<usize> = COVER_PRESENTED.with(|s| s.borrow().iter().copied().collect());
1785        for cover in covers {
1786            let (y, h) = cover_frame(cover, h);
1787            node::set_frame(cover as Handle, 0.0, y, w, h);
1788            if let Some(id) = COVER_NODES.with(|m| m.borrow().get(&cover).copied()) {
1789                post_emit(NodeId(id), Event::FrameChanged(Size::new(w, h)));
1790            }
1791        }
1792    }
1793
1794    /// A presented cover's vertical frame in a layer `layer_h` tall: the whole layer, or the
1795    /// bottom half for a half sheet (docs/cover.md).
1796    fn cover_frame(cover: usize, layer_h: f64) -> (f64, f64) {
1797        if COVER_HALF.with(|s| s.borrow().contains(&cover)) {
1798            let h = (layer_h * 0.5).floor();
1799            (layer_h - h, h)
1800        } else {
1801            (0.0, layer_h)
1802        }
1803    }
1804
1805    /// The entry page's `onBackPress`, after Navigation popped nothing and no cover took the
1806    /// back: while an app handler armed the system back, hand the press to it (`NavBack` on
1807    /// `WINDOW_NODE`) and consume it; otherwise let the system leave the app
1808    /// (docs/navigation.md "Handling the system Back").
1809    pub(crate) fn app_back_requested() -> bool {
1810        if !SYSTEM_BACK.with(std::cell::Cell::get) {
1811            return false;
1812        }
1813        emit(
1814            day_spec::WINDOW_NODE,
1815            Event::NavBack {
1816                already_popped: false,
1817            },
1818        );
1819        true
1820    }
1821
1822    /// Native back targets the top cover, leaving the underlying navigation path intact.
1823    pub(crate) fn cover_back_requested() -> bool {
1824        let Some((root, _, _)) = COVER_ROOT.with(std::cell::Cell::get) else {
1825            return false;
1826        };
1827        let count = node::child_count(root as Handle);
1828        if count == 0 {
1829            return false;
1830        }
1831        let top = node::child_at(root as Handle, count as i32 - 1) as usize;
1832        let Some(id) = COVER_NODES.with(|m| m.borrow().get(&top).copied()) else {
1833            return false;
1834        };
1835        emit(
1836            NodeId(id),
1837            Event::NavBack {
1838                already_popped: false,
1839            },
1840        );
1841        true
1842    }
1843
1844    /// A secondary `DayWindowAbility`'s page connected (the host's `windowStart` export): mount a
1845    /// Stack into its `NodeContent` and complete the pending open (docs/windows.md). False = closed
1846    /// before connecting; the ability terminates itself.
1847    pub fn window_start(
1848        node_id: u64,
1849        content: ohos_sys::arkui::native_type::ArkUI_NodeContentHandle,
1850        w_vp: f64,
1851        h_vp: f64,
1852    ) -> bool {
1853        // Every host entry runs contained (day_spec::ffi_guard): a panic unwinding into the
1854        // runtime's frame is an abort, so a caught panic reports, runs the recovery hook, and
1855        // returns the arm's safe default instead.
1856        day_spec::ffi_guard::contain(false, || {
1857            let root = new_node(node::STACK);
1858            node::set_frame(root.0, 0.0, 0.0, w_vp, h_vp);
1859            node::content_add(content, root.0);
1860            SECONDARY.with(|s| s.borrow_mut().push((node_id, root.0 as usize)));
1861            let ok = day_core::finish_window_open(
1862                day_spec::NodeId(node_id),
1863                root.0 as day_spec::RawHandle,
1864                Size::new(w_vp, h_vp),
1865            );
1866            if !ok {
1867                SECONDARY.with(|s| s.borrow_mut().retain(|(n, _)| *n != node_id));
1868                node::dispose(root.0);
1869            }
1870            ok
1871        })
1872    }
1873
1874    /// The secondary window's content area changed (freeform resize, rotation), in vp.
1875    pub fn window_resized(node_id: u64, w_vp: f64, h_vp: f64) {
1876        day_spec::ffi_guard::contain((), || {
1877            emit(
1878                day_spec::NodeId(node_id),
1879                Event::WindowResized(Size::new(w_vp, h_vp)),
1880            );
1881        });
1882    }
1883
1884    /// The ability instance is going away (back, recents swipe, terminateSelf): confirm to
1885    /// day-core, which tears the window's subtree down.
1886    pub fn window_closed(node_id: u64) {
1887        day_spec::ffi_guard::contain((), || {
1888            SECONDARY.with(|s| s.borrow_mut().retain(|(n, _)| *n != node_id));
1889            WINDOW_STATES.with(|m| m.borrow_mut().remove(&node_id));
1890            emit(day_spec::NodeId(node_id), Event::WindowClosed);
1891        });
1892    }
1893
1894    /// Foreground/background transitions of a secondary ability instance.
1895    pub fn window_focused(node_id: u64, active: bool) {
1896        day_spec::ffi_guard::contain((), || {
1897            emit(day_spec::NodeId(node_id), Event::WindowFocused(active));
1898        });
1899    }
1900
1901    /// An app lifecycle phase from the entry ability (docs/lifecycle.md), coded in
1902    /// `day_spec::Lifecycle` order like the Android bridge: 2 `DidBecomeActive`, 3
1903    /// `WillResignActive`, 4 `WillEnterForeground`, 5 `DidEnterBackground`, 6 `DidReceiveMemoryWarning`,
1904    /// 7 `WillTerminate`, 8 `DidExit`. The launch phases are day-core's own. Delivered on the primary window
1905    /// node, where the tree turns it into the app's `on_lifecycle` handlers and pauses the
1906    /// frame clock across the background.
1907    pub fn lifecycle(code: i32) {
1908        use day_spec::Lifecycle::{
1909            DidBecomeActive, DidEnterBackground, DidExit, DidReceiveMemoryWarning,
1910            WillEnterForeground, WillResignActive, WillTerminate,
1911        };
1912        let phase = match code {
1913            2 => DidBecomeActive,
1914            3 => WillResignActive,
1915            4 => WillEnterForeground,
1916            5 => DidEnterBackground,
1917            6 => DidReceiveMemoryWarning,
1918            7 => WillTerminate,
1919            8 => DidExit,
1920            _ => return,
1921        };
1922        day_spec::ffi_guard::contain((), || {
1923            emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase));
1924        });
1925    }
1926
1927    /// The entry ability reports every phase (docs/lifecycle.md). `const` for
1928    /// `day::require_lifecycle!` compile-time guards.
1929    #[must_use]
1930    pub const fn lifecycle_supported(_phase: day_spec::Lifecycle) -> bool {
1931        true
1932    }
1933
1934    /// The hilog sink for Day's logger (docs/logging.md): std's stderr goes nowhere in an
1935    /// OHOS ability, so the facade installs this at start, one already-formatted line per call.
1936    pub fn hilog_sink(level: log::Level, line: &str) {
1937        crate::hilog::print(level, line);
1938    }
1939
1940    /// One switch's gate (see `TOGGLE_GATE`).
1941    struct ToggleGate {
1942        /// The switch's node handle, to repaint it after a stale event.
1943        handle: usize,
1944        /// The value day last wrote, or the user's last accepted change.
1945        written: bool,
1946        /// Whether the user touched or keyed the switch since `written` was set.
1947        armed: bool,
1948    }
1949
1950    /// A text field's read-only state (see `INPUT_FIELDS`). ArkUI asks before each insertion
1951    /// and deletion once a field is `watched`, and the answer is no while `held` is set. A
1952    /// paste, a cut or an input method's composition can change the text without asking, so
1953    /// `held` also carries the text to put back when a change slips through.
1954    #[derive(Default)]
1955    struct InputField {
1956        /// The will-insert and will-delete events are registered. They stay for the node's
1957        /// life: a field that leaves read-only answers yes.
1958        watched: bool,
1959        /// The text a read-only field shows; `None` while the field takes edits.
1960        held: Option<String>,
1961        /// `Some` for a `TextArea`, carrying its live selection policy; `None` for `TextInput`.
1962        area_selectable: Option<bool>,
1963        /// Only `TextAreas` built with `.on_submit` handle the native submit action.
1964        submit_on_enter: bool,
1965    }
1966
1967    /// Whether node `id` is a text field that refuses edits now.
1968    pub(crate) fn is_read_only(id: u64) -> bool {
1969        INPUT_FIELDS.with(|m| m.borrow().get(&id).is_some_and(|f| f.held.is_some()))
1970    }
1971
1972    /// A change event from text input `n`: when node `id` is read-only, put its text back if
1973    /// the change got past the will-edit events, and say the event is not the app's to see.
1974    pub(crate) fn hold_read_only(n: Handle, id: u64, text: &str) -> bool {
1975        let held = INPUT_FIELDS.with(|m| {
1976            m.borrow().get(&id).and_then(|f| {
1977                f.held
1978                    .clone()
1979                    .map(|text| (text, f.area_selectable.is_some()))
1980            })
1981        });
1982        match held {
1983            Some((held, area)) => {
1984                if held != text {
1985                    if area {
1986                        node::set_textarea_text(n, &held);
1987                    } else {
1988                        node::set_input_text(n, &held);
1989                    }
1990                }
1991                true
1992            }
1993            None => false,
1994        }
1995    }
1996
1997    pub(crate) fn area_unselectable(id: u64) -> bool {
1998        INPUT_FIELDS.with(|m| {
1999            m.borrow()
2000                .get(&id)
2001                .is_some_and(|f| f.area_selectable == Some(false))
2002        })
2003    }
2004
2005    pub(crate) fn area_can_submit(id: u64) -> bool {
2006        INPUT_FIELDS.with(|m| {
2007            m.borrow()
2008                .get(&id)
2009                .is_some_and(|f| f.submit_on_enter && f.held.is_none())
2010        })
2011    }
2012
2013    /// API 18 has no Shift+Enter binding. Dispatch Enter through the native editor under
2014    /// its newline action, preserving selection, IME handling and native undo history.
2015    #[allow(deprecated)] // API 18 has NODE_UNIQUE_ID, not the newer node-ID accessor.
2016    pub(crate) fn area_newline(n: Handle, id: u64) {
2017        use ohos_sys::arkui::native_node::ArkUI_NodeAttributeType as Attr;
2018        use ohos_sys::arkui::native_type::ArkUI_EnterKeyType as Key;
2019        if let Some(unique) = node::get_i32(n, Attr::NODE_UNIQUE_ID, 0) {
2020            node::set_i32(
2021                n,
2022                Attr::NODE_TEXT_AREA_ENTER_KEY_TYPE,
2023                Key::ARKUI_ENTER_KEY_TYPE_NEW_LINE.0 as i32,
2024            );
2025            let handled = crate::host_api::textarea_enter(unique);
2026            // Native editing may call app code that removes the editor. Never touch a
2027            // released/reused handle on the way back out of the dispatch.
2028            if CTRL_NODE.with(|m| m.borrow().get(&(n as usize)).copied()) == Some(id) {
2029                node::set_i32(
2030                    n,
2031                    Attr::NODE_TEXT_AREA_ENTER_KEY_TYPE,
2032                    Key::ARKUI_ENTER_KEY_TYPE_SEND.0 as i32,
2033                );
2034            }
2035            if !handled {
2036                log::warn!(
2037                    "day-toolkit-arkui: Shift+Enter requires the staged ArkTS key-dispatch host"
2038                );
2039            }
2040        }
2041    }
2042
2043    fn set_area_editable(n: Handle, id: u64, editable: bool) {
2044        let held = (!editable).then(|| node::textarea_text(n));
2045        INPUT_FIELDS.with(|m| {
2046            if let Some(f) = m.borrow_mut().get_mut(&id) {
2047                f.held = held;
2048            }
2049        });
2050        node::set_textarea_editable(n, editable);
2051    }
2052
2053    fn set_area_selectable(n: Handle, id: u64, selectable: bool) {
2054        INPUT_FIELDS.with(|m| {
2055            if let Some(f) = m.borrow_mut().get_mut(&id) {
2056                f.area_selectable = Some(selectable);
2057            }
2058        });
2059        node::set_textarea_selectable(n, selectable);
2060    }
2061
2062    /// User input reached node `id`: if it is a switch, its next change is the user's.
2063    pub(crate) fn arm_toggle(id: u64) {
2064        TOGGLE_GATE.with(|m| {
2065            if let Some(gate) = m.borrow_mut().get_mut(&id) {
2066                gate.armed = true;
2067            }
2068        });
2069    }
2070
2071    /// Record a programmatic write to switch `id`, which disarms its gate.
2072    fn toggle_written(id: u64, on: bool) {
2073        TOGGLE_GATE.with(|m| {
2074            if let Some(gate) = m.borrow_mut().get_mut(&id) {
2075                gate.written = on;
2076                gate.armed = false;
2077            }
2078        });
2079    }
2080
2081    /// The native event trampoline: `kind` is `day_spec::bridge::BridgeKind`, the same wire
2082    /// table as the Android bridge; `id` is the day `NodeId` the event was registered against.
2083    pub fn on_event(id: u64, kind: i32, num: f64, text: &str) {
2084        day_spec::ffi_guard::contain((), || on_event_inner(id, kind, num, text));
2085    }
2086
2087    /// [`on_event`]'s C form, for pieces built against it (day-piece-camera reports its ArkTS
2088    /// surface through it): `text` is a C string or null.
2089    #[unsafe(no_mangle)]
2090    #[allow(clippy::not_unsafe_ptr_arg_deref)] // `text` is a valid C string or null, per the caller
2091    pub extern "C" fn day_arkui_on_event(
2092        id: u64,
2093        kind: std::ffi::c_int,
2094        num: f64,
2095        text: *const std::ffi::c_char,
2096    ) {
2097        on_event(id, kind, num, &node::text_of(text));
2098    }
2099
2100    /// A menu button's bottom-leading corner in the content root's coordinates, in vp: where
2101    /// the composed menu opens (docs/menus.md "Menu buttons"). The origin when the layout
2102    /// cannot be read, so the menu still opens.
2103    fn menu_button_anchor(button: usize) -> Point {
2104        let root = ROOT_KEEP.with(std::cell::Cell::get).map(|(ptr, _, _)| ptr);
2105        if let Some(root) = root
2106            && let Some((x, y, _, h)) = node::layout_frame_px(button as Handle)
2107            && let Some((rx, ry, _, _)) = node::layout_frame_px(root as Handle)
2108        {
2109            let d = node::density();
2110            return Point::new((x - rx) / d, (y + h - ry) / d);
2111        }
2112        Point::ZERO
2113    }
2114
2115    fn on_event_inner(id: u64, kind: i32, num: f64, text: &str) {
2116        use day_spec::bridge::BridgeKind as K;
2117        if kind == K::Custom as i32 && text == "day-list-first-visible" {
2118            let source = LIST_SOURCES.with(|map| map.borrow().get(&id).cloned());
2119            if let Some(source) = source
2120                && source.viewport.is_none()
2121                && let Some(report) = &source.first_visible
2122            {
2123                report((num.max(0.0) as usize).min((source.len)().saturating_sub(1)));
2124            }
2125            return;
2126        }
2127        // A NAV_MENU row click arrives with a synthetic id: translate it to a SelectionChanged
2128        // against the menu host before the normal per-node dispatch.
2129        if kind == K::Pressed as i32
2130            && let Some((menu, index)) = MENU_ROWS.with(|m| m.borrow().get(&id).copied())
2131        {
2132            emit(menu, Event::SelectionChanged(index));
2133            return;
2134        }
2135        // A menu button's press opens its menu: the composed one, placed under the button.
2136        if kind == K::Pressed as i32
2137            && let Some(button) = MENU_BUTTONS.with(|m| m.borrow().get(&id).copied())
2138        {
2139            emit(
2140                NodeId(id),
2141                Event::ContextMenu {
2142                    local: Point::ZERO,
2143                    window: menu_button_anchor(button),
2144                },
2145            );
2146            return;
2147        }
2148        // A node with a registered Tap gesture emits `Event::Tap`, not `Event::Pressed`.
2149        // The click's point (vp, node-local) rides in `text`.
2150        if kind == K::Pressed as i32 && TAP_NODES.with(|s| s.borrow().contains(&id)) {
2151            let mut xy = text.split(',').filter_map(|v| v.parse::<f64>().ok());
2152            let at = match (xy.next(), xy.next()) {
2153                (Some(x), Some(y)) => Point::new(x, y),
2154                _ => Point::ZERO,
2155            };
2156            emit(NodeId(id), Event::Tap(at));
2157            return;
2158        }
2159        let node_id = NodeId(id);
2160        let ev = match kind {
2161            k if k == K::Pressed as i32 => Event::Pressed,
2162            k if k == K::LinkActivated as i32 => Event::LinkActivated(text.to_owned()),
2163            // SelectionChanged (swiper tab / menu row), carried as the index in `num`.
2164            k if k == K::SelectionChanged as i32 => Event::SelectionChanged(num as i64),
2165            k if k == K::ListActivated as i32 => Event::ListActivated(num as usize),
2166            k if k == K::TextChanged as i32 => {
2167                // The programmatic-set echo (see TEXT_ECHO): a change carrying exactly what
2168                // day just wrote is ArkUI reporting the set back, not the user typing.
2169                let is_echo =
2170                    TEXT_ECHO.with(|m| m.borrow().get(&id).is_some_and(|last| *last == text));
2171                if is_echo {
2172                    return;
2173                }
2174                TEXT_ECHO.with(|m| m.borrow_mut().remove(&id));
2175                Event::TextChanged(text.to_owned())
2176            }
2177            k if k == K::ToggleChanged as i32 => {
2178                let on = num != 0.0;
2179                // The gate (see TOGGLE_GATE): `Some(handle)` is a stale event to repaint over.
2180                let stale = TOGGLE_GATE.with(|m| {
2181                    let mut m = m.borrow_mut();
2182                    let Some(gate) = m.get_mut(&id) else {
2183                        return Some(None);
2184                    };
2185                    if gate.written == on {
2186                        // The echo of day's own write, or no change at all.
2187                        return None;
2188                    }
2189                    if gate.armed {
2190                        gate.written = on;
2191                        gate.armed = false;
2192                        return Some(None);
2193                    }
2194                    Some(Some((gate.handle, gate.written)))
2195                });
2196                match stale {
2197                    None => return,
2198                    Some(Some((handle, written))) => {
2199                        // Out of the borrow: the set below may report back synchronously.
2200                        node::set_toggle(handle as node::Handle, written);
2201                        return;
2202                    }
2203                    Some(None) => Event::ToggleChanged(on),
2204                }
2205            }
2206            // Focus pair + text-input submit (docs/focus.md).
2207            k if k == K::FocusChanged as i32 => Event::FocusChanged(num != 0.0),
2208            k if k == K::Submitted as i32 => Event::Submitted,
2209            // A non-text key from a focused node (docs/menus.md): `text` is the day key name,
2210            // `num` the modifier mask. The receiver already asked whether this node claims keys.
2211            // The phase rides in bits 8 and 9 of `num` (events.rs): a repeat or a release.
2212            k if k == K::Key as i32 => Event::Key(
2213                day_spec::KeyEvent::named(text, (num as u32 & 0xFF) as u8)
2214                    .with_phase(day_spec::KeyPhase::from_wire(num)),
2215            ),
2216            // Text the full route committed (docs/menus.md "The full route"): what the key
2217            // typed, with the modifier mask in `num` (and the repeat bit while held).
2218            k if k == K::Text as i32 => Event::Key(
2219                day_spec::KeyEvent::typed_text(text, (num as u32 & 0xFF) as u8)
2220                    .with_phase(day_spec::KeyPhase::from_wire(num)),
2221            ),
2222            // Gestures (docs/shapes.md, docs/canvas.md "Zoom and pan"): `num` = phase (1/2/3
2223            // drag began/changed/ended, 4/5/6 pinch, 7/8/9 viewport pan, 13/14/15 rotation),
2224            // `text` = "x,y,tx,ty" in px, converted to vp like the Android bridge; a pinch's
2225            // `tx` is its scale, a rotation's its cumulative radians.
2226            k if k == K::Gesture as i32 => {
2227                let p: Vec<f64> = text.split(',').filter_map(|s| s.parse().ok()).collect();
2228                if p.len() < 4 {
2229                    return;
2230                }
2231                let d = node::density();
2232                let at = Point::new(p[0] / d, p[1] / d);
2233                let tr = Point::new(p[2] / d, p[3] / d);
2234                match num as i32 {
2235                    4..=6 => Event::Pinch {
2236                        phase: match num as i32 {
2237                            4 => day_spec::DragPhase::Began,
2238                            6 => day_spec::DragPhase::Ended,
2239                            _ => day_spec::DragPhase::Changed,
2240                        },
2241                        scale: p[2],
2242                        location: at,
2243                    },
2244                    13..=15 => Event::Rotate {
2245                        phase: match num as i32 {
2246                            13 => day_spec::DragPhase::Began,
2247                            15 => day_spec::DragPhase::Ended,
2248                            _ => day_spec::DragPhase::Changed,
2249                        },
2250                        rotation: p[2],
2251                        location: at,
2252                    },
2253                    7..=9 => Event::Pan {
2254                        phase: match num as i32 {
2255                            7 => day_spec::DragPhase::Began,
2256                            9 => day_spec::DragPhase::Ended,
2257                            _ => day_spec::DragPhase::Changed,
2258                        },
2259                        delta: tr,
2260                        location: at,
2261                    },
2262                    1 => Event::Drag {
2263                        phase: day_spec::DragPhase::Began,
2264                        location: at,
2265                        translation: Point::ZERO,
2266                    },
2267                    3 => Event::Drag {
2268                        phase: day_spec::DragPhase::Ended,
2269                        location: at,
2270                        translation: tr,
2271                    },
2272                    _ => Event::Drag {
2273                        phase: day_spec::DragPhase::Changed,
2274                        location: at,
2275                        translation: tr,
2276                    },
2277                }
2278            }
2279            k if k == K::ValueChanged as i32 || k == K::ValueCommitted as i32 => {
2280                // ArkUI slider reports 0..100; map back to the node's day range. ValueCommitted
2281                // is the same value once the interaction settled.
2282                let (min, max) = SLIDER_RANGE
2283                    .with(|m| m.borrow().get(&id).copied())
2284                    .unwrap_or((0.0, 1.0));
2285                let value = min + (num / 100.0) * (max - min);
2286                // The programmatic-set echo (see SLIDER_ECHO), compared with the slack the
2287                // percent round-trip costs.
2288                let eps = ((max - min).abs()).max(1e-9) * 1e-4;
2289                let is_echo = SLIDER_ECHO
2290                    .with(|m| m.borrow().get(&id).copied())
2291                    .is_some_and(|last| (last - value).abs() <= eps);
2292                if is_echo {
2293                    return;
2294                }
2295                SLIDER_ECHO.with(|m| m.borrow_mut().remove(&id));
2296                if kind == K::ValueCommitted as i32 {
2297                    Event::ValueCommitted(value)
2298                } else {
2299                    Event::ValueChanged(value)
2300                }
2301            }
2302            // An ArkTS-built piece component reporting back (docs/extending.md), through the
2303            // host's `pieceEvent`. Like the Android bridge's Custom, the payload IS the event:
2304            // a cross-boundary Custom carries no tag, and the piece owns the whole channel.
2305            k if k == K::Custom as i32 => Event::Custom {
2306                tag: "",
2307                num,
2308                text: text.to_owned(),
2309            },
2310            // A window's display state after a fullscreen request settled (the host's
2311            // `windowStateChanged`): `num` is the `WindowState` code, `id` the window's root node
2312            // or `WINDOW_NODE` for the primary (docs/windows.md "Window properties").
2313            k if k == K::WindowStateChanged as i32 => {
2314                let state = day_spec::WindowState::from_code(num as i32);
2315                WINDOW_STATES.with(|m| m.borrow_mut().insert(id, state));
2316                log::debug!("arkui: window state now {state:?}");
2317                Event::WindowStateChanged(state)
2318            }
2319            // File-picker answer (docs/files.md): `id` is the request id, `text` the chosen local
2320            // path (a cache copy for open, a docs URI for save); empty means the user cancelled.
2321            k if k == K::PresentFile as i32 => {
2322                let result = day_spec::present::PresentResult::decode(3, 0, text.to_owned());
2323                emit(node_id, Event::PresentResult { req: id, result });
2324                return;
2325            }
2326            _ => return,
2327        };
2328        emit(node_id, ev);
2329    }
2330
2331    /// Recycling-list row count, asked by the `NodeAdapter` (docs/list.md).
2332    pub(crate) fn list_count(host_id: u64) -> u32 {
2333        day_spec::ffi_guard::contain(0, || {
2334            LIST_SOURCES.with(|m| m.borrow().get(&host_id).map_or(0, |s| (s.len)() as u32))
2335        })
2336    }
2337
2338    /// Build (or rebind) row `index`'s content into the native cell `cell` (an inner Stack). The
2339    /// adapter reuses cells, so a repeat `cell` pointer is a rebind (day-core keys its cell cache
2340    /// by the raw handle). Called on the JS/main thread from the adapter's add callback.
2341    pub(crate) fn list_bind(host_id: u64, index: u32, cell: Handle) {
2342        day_spec::ffi_guard::contain((), || {
2343            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2344            if let Some(source) = source {
2345                (source.bind_row)(index as usize, cell as day_spec::RawHandle);
2346            }
2347        });
2348    }
2349
2350    /// [`list_bind`] for the list's pinned header copy (`ListSource::bind_pinned`, docs/list.md
2351    /// "Sections"): the copy carries no element ids, so lookups find the real header row.
2352    pub(crate) fn list_bind_pinned(host_id: u64, index: u32, cell: Handle) {
2353        day_spec::ffi_guard::contain((), || {
2354            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2355            if let Some(source) = source {
2356                (source.bind_pinned)(index as usize, cell as day_spec::RawHandle);
2357            }
2358        });
2359    }
2360
2361    /// The height, in vp, Day laid the row bound to `cell` (an inner Stack) at: what a
2362    /// content-sized list gives the cell right after `list_bind`. `0.0` before the row's first
2363    /// layout or inside a day-core borrow.
2364    pub(crate) fn list_cell_height(host_id: u64, cell: Handle) -> f64 {
2365        day_spec::ffi_guard::contain(0.0, || {
2366            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2367            source.map_or(0.0, |source| {
2368                (source.cell_height)(cell as day_spec::RawHandle)
2369            })
2370        })
2371    }
2372
2373    /// Whether display row `index` of a sectioned list is a section header (docs/list.md
2374    /// "Sections"); false on every other list.
2375    /// Whether row `index` of list `host_id` is a supplementary row (a header, footer, empty
2376    /// state or padding row, docs/list.md).
2377    pub(crate) fn list_is_supplement(host_id: u64, index: u32) -> bool {
2378        day_spec::ffi_guard::contain(false, || {
2379            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2380            source
2381                .and_then(|s| s.is_supplement)
2382                .is_some_and(|is_supplement| is_supplement(index as usize))
2383        })
2384    }
2385
2386    /// Hand list `host_id`'s viewport to the app (`ListSource::viewport`, docs/list.md).
2387    pub(crate) fn list_viewport(host_id: u64, first: usize, last: usize, end_distance: f64) {
2388        day_spec::ffi_guard::contain((), || {
2389            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2390            if let Some(report) = source.and_then(|s| s.viewport) {
2391                report(day_spec::ListViewport {
2392                    first,
2393                    last,
2394                    end_distance,
2395                });
2396            }
2397        });
2398    }
2399
2400    /// Tell list `host_id`'s app the reader moved it (`ListSource::reader_scroll`,
2401    /// docs/list.md "Following the end").
2402    pub(crate) fn list_reader_scroll(host_id: u64) {
2403        day_spec::ffi_guard::contain((), || {
2404            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2405            if let Some(report) = source.and_then(|s| s.reader_scroll) {
2406                report();
2407            }
2408        });
2409    }
2410
2411    pub(crate) fn list_is_header(host_id: u64, index: u32) -> bool {
2412        day_spec::ffi_guard::contain(false, || {
2413            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2414            source
2415                .and_then(|s| s.is_header)
2416                .is_some_and(|is_header| is_header(index as usize))
2417        })
2418    }
2419
2420    /// Give a section-header cell (a header row's `LIST_ITEM`, or the pinned copy) the header
2421    /// band's opaque ground, following the color mode for as long as the list `owner` lives:
2422    /// the rows scrolling under the pin must not show through it (docs/list.md "Sections").
2423    pub(crate) fn list_header_ground(owner: Handle, cell: Handle) {
2424        themed(
2425            owner as usize,
2426            cell,
2427            Paint::Background,
2428            0xFFF1_F3F5,
2429            0xFF1C_1C1E,
2430        );
2431    }
2432
2433    /// A pooled cell left the adapter's visible set: clear the cell subtree's dayscript ids so
2434    /// hidden rows stop answering lookups (day-core's `list_recycle_cell`), keyed by the same
2435    /// inner-Stack pointer `list_bind` binds with.
2436    pub(crate) fn list_recycle(host_id: u64, cell: Handle) {
2437        day_spec::ffi_guard::contain((), || {
2438            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2439            if let Some(source) = source {
2440                (source.recycle)(cell as day_spec::RawHandle);
2441            }
2442        });
2443    }
2444
2445    /// Whether row `index` is in the list's programmatic selection: newly bound cells are
2446    /// painted from this (docs/list.md `ListPatch::Selected`).
2447    pub(crate) fn list_is_selected(host_id: u64, index: u32) -> bool {
2448        day_spec::ffi_guard::contain(false, || {
2449            LIST_SELECTED.with(|m| {
2450                m.borrow()
2451                    .get(&host_id)
2452                    .is_some_and(|set| set.contains(&(index as usize)))
2453            })
2454        })
2455    }
2456
2457    /// The reorder guard's verdict for a hovered drop (docs/list.md): the accepted target index,
2458    /// or -1. Called synchronously from the list's drop handler; the source is cloned out before
2459    /// the app's guard runs, so no thread-local borrow is held.
2460    pub(crate) fn list_can_move(host_id: u64, from: u32, to: u32) -> i32 {
2461        day_spec::ffi_guard::contain(-1, || {
2462            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2463            let Some(source) = source else { return -1 };
2464            let Some(r) = source.reorder.as_ref() else {
2465                return -1;
2466            };
2467            let len = (source.len)();
2468            let (from, to) = (from as usize, to as usize);
2469            if from >= len || to >= len {
2470                return -1;
2471            }
2472            ((r.can_move)(from, to) as i32).min(len.saturating_sub(1) as i32)
2473        })
2474    }
2475
2476    /// Commit an accepted drop through the sync seam (rotates day's snapshot, defers the app
2477    /// callback); the list reloads the adapter afterwards.
2478    pub(crate) fn list_move(host_id: u64, from: u32, to: u32) {
2479        day_spec::ffi_guard::contain((), || {
2480            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2481            let Some(r) = source.and_then(|s| s.reorder) else {
2482                return;
2483            };
2484            if from != to {
2485                (r.move_row)(from as usize, to as usize);
2486            }
2487        });
2488    }
2489
2490    /// May this row be swiped away? A guarded row is refused at delete time (docs/list.md).
2491    pub(crate) fn list_can_delete(host_id: u64, index: u32) -> bool {
2492        day_spec::ffi_guard::contain(false, || {
2493            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2494            let Some(source) = source else { return false };
2495            let Some(d) = source.delete.as_ref() else {
2496                return false;
2497            };
2498            let index = index as usize;
2499            index < (source.len)() && (d.can_delete)(index)
2500        })
2501    }
2502
2503    /// Commit a swipe-to-delete through the sync seam (shortens day's snapshot, defers the app
2504    /// callback); the list reloads the adapter afterwards. True on commit.
2505    pub(crate) fn list_delete(host_id: u64, index: u32) -> bool {
2506        day_spec::ffi_guard::contain(false, || {
2507            if !list_can_delete(host_id, index) {
2508                return false;
2509            }
2510            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2511            let Some(d) = source.and_then(|s| s.delete) else {
2512                return false;
2513            };
2514            (d.delete_row)(index as usize);
2515            true
2516        })
2517    }
2518
2519    /// A `NavDestination` disappeared on the ArkTS side (docs/navigation.md). For a pop DAY
2520    /// initiated (`NavPatch::Popped`) this is just the acknowledgment; for a NATIVE back
2521    /// (system gesture / title-bar back button) sync the route state: the toolkit already
2522    /// popped, so the host receives `NavBack { already_popped: true }`.
2523    pub fn nav_popped(owner: u64, key: u64) {
2524        day_spec::ffi_guard::contain((), || nav_popped_inner(owner, key));
2525    }
2526
2527    /// An adaptive host's Navigation decided its presentation (docs/size-classes.md): the
2528    /// toolkit tells Day (`Cap::NavRepresent = Emulated`), and the pieces layer reconciles its
2529    /// model to what ArkUI already drew, the way it does for `SlidingPaneLayout` on Android.
2530    pub fn nav_presented(owner: u64, split: bool) {
2531        use day_spec::props::NavPresentation;
2532        day_spec::ffi_guard::contain((), || {
2533            let next = if split {
2534                NavPresentation::Split
2535            } else {
2536                NavPresentation::Stack
2537            };
2538            emit(day_spec::NodeId(owner), Event::NavPresentationChanged(next));
2539        });
2540    }
2541
2542    fn nav_popped_inner(owner: u64, key: u64) {
2543        let host = NAV_OWNERS.with(|m| m.borrow().get(&key).copied());
2544        let Some(host) =
2545            host.filter(|h| NAV_HOSTS.with(|m| m.borrow().get(h).copied()) == Some(owner))
2546        else {
2547            return;
2548        };
2549        // The destination's content tree is gone: if the page is still mounted (its Remove
2550        // patch hasn't landed yet), mark the key so that Remove skips the dead slot.
2551        if NAV_PUSHED.with(|m| m.borrow().values().any(|k| *k == key)) {
2552            NAV_POPPED_KEYS.with(|s| s.borrow_mut().insert(key));
2553        }
2554        // A destination that never landed can no longer be waited on.
2555        NAV_PENDING_PUSH.with(|s| {
2556            s.borrow_mut().remove(&key);
2557        });
2558        // Day-initiated pops retired their key from NAV_STACK already; a NATIVE back is the
2559        // toolkit popping on its own, so drop the key here (keeping Rust's order in sync
2560        // before the NavBack sync writes the pop into the route state).
2561        NAV_STACK.with(|s| {
2562            if let Some(stack) = s.borrow_mut().get_mut(&host) {
2563                stack.retain(|k| *k != key);
2564            }
2565        });
2566        // The page under it shows now: a page search field follows (docs/search.md).
2567        paint_page_search(false);
2568        let expected = NAV_EXPECT_POP.with(|e| e.borrow_mut().remove(&key));
2569        if expected {
2570            // The acknowledgment of a Day-initiated pop (`ui_idle`'s pending-pop signal).
2571            NAV_PENDING_POP.with(|p| {
2572                p.borrow_mut().remove(&key);
2573            });
2574        }
2575        if !NAV_PAGE_IDS.with(|m| m.borrow().values().any(|id| *id == key)) {
2576            NAV_OWNERS.with(|m| m.borrow_mut().remove(&key));
2577        }
2578        if !expected {
2579            emit(
2580                NodeId(owner),
2581                Event::NavBack {
2582                    already_popped: true,
2583                },
2584            );
2585        }
2586    }
2587
2588    /// A guarded `NavDestination` consumed its back (ArkTS onBackPressed) and asks Day's guard to
2589    /// decide: emit `NavBack { already_popped: false }` (the native stack did NOT pop, unlike an
2590    /// unguarded back's [`nav_popped`]).
2591    pub fn nav_back_requested(owner: u64) {
2592        day_spec::ffi_guard::contain((), || {
2593            if NAV_HOSTS.with(|m| m.borrow().values().any(|id| *id == owner)) {
2594                emit(
2595                    NodeId(owner),
2596                    Event::NavBack {
2597                        already_popped: false,
2598                    },
2599                );
2600            }
2601        });
2602    }
2603
2604    /// A destination's content area changed (vp): relayout that page in its real bounds. The
2605    /// first report for a key is also the push-landed signal `ui_idle` waits on.
2606    pub fn nav_area(key: u64, w: f64, h: f64) {
2607        day_spec::ffi_guard::contain((), || {
2608            if w > 0.0 && h > 0.0 {
2609                NAV_PENDING_PUSH.with(|s| {
2610                    s.borrow_mut().remove(&key);
2611                });
2612                if let Some(ptr) = NAV_PAGE_IDS.with(|m| {
2613                    m.borrow()
2614                        .iter()
2615                        .find(|(_, id)| **id == key)
2616                        .map(|(p, _)| *p)
2617                }) {
2618                    node::set_frame(ptr as Handle, 0.0, 0.0, w, h);
2619                }
2620                emit(NodeId(key), Event::FrameChanged(Size::new(w, h)));
2621            }
2622        });
2623    }
2624
2625    /// A title-bar action was tapped (docs/toolbars.md). The bar's menu items carry only an
2626    /// action id and an optional segment index. A toggle flips; an explicit choice selects
2627    /// that segment (the legacy action-only path cycles); other items run their command.
2628    /// Recheck enablement and index bounds because an open popup may outlive a model patch.
2629    pub fn nav_menu_action(action: u64, selection: i32) {
2630        day_spec::ffi_guard::contain((), || {
2631            use day_spec::{ToolbarItemKind as K, ToolbarValue as V};
2632            let item = WINDOW_BAR.with(|b| b.borrow().by_action(action).cloned());
2633            if item.as_ref().is_some_and(|i| !i.enabled) {
2634                return;
2635            }
2636            if selection >= 0 {
2637                if let Some(day_spec::ToolbarItem {
2638                    kind: K::Segmented { segments, .. },
2639                    ..
2640                }) = item
2641                    && (selection as usize) < segments.len()
2642                {
2643                    emit(
2644                        day_spec::WINDOW_NODE,
2645                        Event::ToolbarChanged {
2646                            action,
2647                            value: V::Selected(selection as usize),
2648                        },
2649                    );
2650                }
2651                return;
2652            }
2653            let ev = match item.map(|i| i.kind) {
2654                Some(K::Toggle { on }) => Event::ToolbarChanged {
2655                    action,
2656                    value: V::On(!on),
2657                },
2658                Some(K::Segmented { segments, selected }) if !segments.is_empty() => {
2659                    Event::ToolbarChanged {
2660                        action,
2661                        value: V::Selected((selected + 1) % segments.len()),
2662                    }
2663                }
2664                _ => Event::MenuAction(action),
2665            };
2666            emit(day_spec::WINDOW_NODE, ev);
2667        });
2668    }
2669
2670    /// The user edited the navigation surface's search field (docs/search.md): reported against
2671    /// the nav host, where the `.searchable()` surface listens, whatever its placement asked for.
2672    pub fn nav_search_changed(owner: u64, text: &str) {
2673        day_spec::ffi_guard::contain((), || {
2674            if NAV_HOSTS.with(|m| m.borrow().values().any(|id| *id == owner)) {
2675                emit(NodeId(owner), Event::SearchChanged(text.to_owned()));
2676            }
2677        });
2678    }
2679
2680    /// The user pressed the navigation surface's search key (docs/search.md). The host reported
2681    /// the text through [`nav_search_changed`] first, so this follows the last edit.
2682    pub fn nav_search_submitted(owner: u64, text: &str) {
2683        day_spec::ffi_guard::contain((), || {
2684            if NAV_HOSTS.with(|m| m.borrow().values().any(|id| *id == owner)) {
2685                emit(NodeId(owner), Event::SearchSubmitted(text.to_owned()));
2686            }
2687        });
2688    }
2689
2690    /// The user edited (or, with `submit`, submitted) a page's search field (docs/search.md):
2691    /// the window bar's `day::search` item, drawn on host `owner`'s page by
2692    /// [`paint_page_search`]. Reported as that item's value: the text when it differs from what
2693    /// Day last had, then the submission, so a submit always follows the text it carries.
2694    pub fn nav_page_search(owner: u64, text: &str, submit: bool) {
2695        day_spec::ffi_guard::contain((), || {
2696            use day_spec::{ToolbarItemKind as K, ToolbarValue as V};
2697            if !PAGE_SEARCH.with(|m| m.borrow().get(&owner).is_some_and(|(page, ..)| *page != 0)) {
2698                return;
2699            }
2700            let Some((action, had)) = WINDOW_BAR.with(|b| {
2701                b.borrow()
2702                    .get(day_spec::SEARCH_ITEM_ID)
2703                    .and_then(|i| match &i.kind {
2704                        K::Search { text, .. } => Some((i.action, text.clone())),
2705                        _ => None,
2706                    })
2707            }) else {
2708                return;
2709            };
2710            if had != text {
2711                // Day does not echo the user's own edit back, so the mirror takes it here: a
2712                // later repaint must not put the old text back in the field.
2713                WINDOW_BAR.with(|b| {
2714                    b.borrow_mut().patch(&day_spec::ToolbarPatch::Text {
2715                        item: day_spec::SEARCH_ITEM_ID.to_owned(),
2716                        text: text.to_owned(),
2717                    })
2718                });
2719                emit(
2720                    day_spec::WINDOW_NODE,
2721                    Event::ToolbarChanged {
2722                        action,
2723                        value: V::Text(text.to_owned()),
2724                    },
2725                );
2726                // Every other host drawing the field (a hidden tab's) takes the text too.
2727                paint_page_search(false);
2728            }
2729            if submit {
2730                emit(
2731                    day_spec::WINDOW_NODE,
2732                    Event::ToolbarChanged {
2733                        action,
2734                        value: V::Submit(text.to_owned()),
2735                    },
2736                );
2737            }
2738        });
2739    }
2740
2741    /// The navigation host `host` sits inside, and the key of the page it sits in: a nested
2742    /// `nav_stack`'s Navigation is mounted in a page of the one around it. Walks the C-API
2743    /// parents up to the first page an enclosing host owns.
2744    fn nav_enclosing(host: usize) -> Option<(usize, u64)> {
2745        let mut n = node::parent(host as Handle);
2746        // Bounded: a tree is never this deep, and a cycle must not hang the UI thread.
2747        for _ in 0..1024 {
2748            if n.is_null() {
2749                return None;
2750            }
2751            let outer = NAV_PAGE_IDS
2752                .with(|m| m.borrow().get(&(n as usize)).copied())
2753                .and_then(|key| {
2754                    NAV_OWNERS
2755                        .with(|m| m.borrow().get(&key).copied())
2756                        .filter(|o| *o != host)
2757                        .map(|o| (o, key))
2758                });
2759            if outer.is_some() {
2760                return outer;
2761            }
2762            n = node::parent(n);
2763        }
2764        None
2765    }
2766
2767    /// The page host `host` shows on top: its last pushed destination's key, else -1 for its
2768    /// root page.
2769    fn nav_top(host: usize) -> i64 {
2770        NAV_STACK
2771            .with(|s| s.borrow().get(&host).and_then(|s| s.last().copied()))
2772            .map_or(-1, |k| k as i64)
2773    }
2774
2775    /// Draw the window bar's `day::search` item (docs/search.md, "Page search") as an ArkUI
2776    /// `Search` at the top of the page that declared it, under its title bar, the place the
2777    /// navigation surface's inline field takes on the root page.
2778    ///
2779    /// The bar is one merged model and says nothing of which page contributed the item; Day
2780    /// merges only the showing pages, so the field goes on the page each host shows. A sidebar
2781    /// column's item rides the outermost hosts' root pages; any other the innermost showing
2782    /// hosts' top pages, so a `nav_stack` nested in a detail page carries the field rather than
2783    /// the destination around it as well. Each host is told only what changed; `focus` asks the
2784    /// drawn fields for focus.
2785    fn paint_page_search(focus: bool) {
2786        use day_spec::ToolbarItemKind as K;
2787        let item = WINDOW_BAR.with(|b| b.borrow().get(day_spec::SEARCH_ITEM_ID).cloned());
2788        let mut wanted: HashMap<u64, (i64, String, String)> = HashMap::new();
2789        if let Some(day_spec::ToolbarItem {
2790            kind: K::Search {
2791                text, placeholder, ..
2792            },
2793            column,
2794            ..
2795        }) = item
2796        {
2797            let hosts: Vec<(usize, u64)> =
2798                NAV_HOSTS.with(|m| m.borrow().iter().map(|(h, o)| (*h, *o)).collect());
2799            let enclosing: Vec<Option<(usize, u64)>> =
2800                hosts.iter().map(|(h, _)| nav_enclosing(*h)).collect();
2801            for (at, (host, owner)) in hosts.iter().enumerate() {
2802                let page = if column == day_spec::ToolbarColumn::Sidebar {
2803                    enclosing[at].is_none().then_some(-1)
2804                } else {
2805                    // A host whose showing page holds another host leaves the field to it.
2806                    let top = nav_top(*host);
2807                    let covered = enclosing
2808                        .iter()
2809                        .flatten()
2810                        .any(|(outer, key)| outer == host && (top == -1 || top == *key as i64));
2811                    (!covered).then_some(top)
2812                };
2813                if let Some(page) = page {
2814                    wanted.insert(*owner, (page, placeholder.clone(), text.clone()));
2815                }
2816            }
2817        }
2818        // Decided under the borrow, drawn after it: the host may call back in synchronously.
2819        let calls: Vec<(u64, i64, String, String)> = PAGE_SEARCH.with(|m| {
2820            let mut drawn = m.borrow_mut();
2821            let mut calls: Vec<_> = drawn
2822                .keys()
2823                .filter(|o| !wanted.contains_key(o))
2824                .map(|o| (*o, 0, String::new(), String::new()))
2825                .collect();
2826            calls.extend(
2827                wanted
2828                    .iter()
2829                    .filter(|(o, w)| focus || drawn.get(o) != Some(w))
2830                    .map(|(o, (page, prompt, text))| (*o, *page, prompt.clone(), text.clone())),
2831            );
2832            *drawn = wanted;
2833            calls
2834        });
2835        for (owner, page, prompt, text) in calls {
2836            crate::host_api::nav_set_page_search(owner, page, &prompt, &text, focus && page != 0);
2837        }
2838    }
2839
2840    /// Paint the window toolbar onto the Navigation's title bars (docs/toolbars.md): one
2841    /// `.menus()` item per action, shown on the root page and every pushed page alike. The bar
2842    /// uses native buttons and popup menus through Navigation's custom builder. Page actions
2843    /// precede window actions. The host tints template icons using system colors, preserves
2844    /// toggle state, and exposes segment choices rather than silently cycling on a tap.
2845    /// A pull-down's entries remain flattened; separators, labels and search draw nothing here.
2846    /// Wire format: five newline-separated parallel fields. Segment addresses are `id:index`
2847    /// and their label field is `current title` followed by U+001F-separated choices. Enabled
2848    /// carries bit 0 = enabled, bit 1 = checked. User text is stripped of wire separators.
2849    fn paint_window_bar() {
2850        use day_spec::ToolbarItemKind as K;
2851        let (mut icons, mut labels, mut actions, mut enabled) =
2852            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
2853        let mut scopes = Vec::new();
2854        WINDOW_BAR.with(|b| {
2855            // No sidebar toggle here: Navigation's own nav bar shows and hides itself.
2856            let bar = b.borrow();
2857            let (page, window): (Vec<_>, Vec<_>) = bar
2858                .items()
2859                .iter()
2860                .filter(|i| i.id != day_spec::SIDEBAR_TOGGLE_ID)
2861                .partition(|i| {
2862                    matches!(
2863                        i.column,
2864                        day_spec::ToolbarColumn::Detail | day_spec::ToolbarColumn::List
2865                    )
2866                });
2867            for item in page.into_iter().chain(window) {
2868                // Which title bars carry the item (docs/toolbars.md): a detail or list
2869                // column's over its page (1), the sidebar column's over the root page (0),
2870                // the window's over both (2). Stacked, only one bar shows at a time, so this
2871                // changes nothing there; tiled, both show, and each column's commands sit
2872                // over that column, the way a desktop toolbar spans its panes.
2873                let scope = match item.column {
2874                    day_spec::ToolbarColumn::Detail | day_spec::ToolbarColumn::List => "1",
2875                    day_spec::ToolbarColumn::Sidebar => "0",
2876                    day_spec::ToolbarColumn::Window => "2",
2877                };
2878                let mut add =
2879                    |icon: Option<&day_spec::Icon>, label: &str, action: u64, on: bool| {
2880                        if action == 0 {
2881                            return;
2882                        }
2883                        icons.push(icon.and_then(icon_source).unwrap_or_default());
2884                        let clean = |text: &str| text.replace(['\n', '\u{1f}'], " ");
2885                        if let K::Segmented { segments, selected } = &item.kind {
2886                            let mut titles = vec![clean(label)];
2887                            titles.extend(segments.iter().map(|s| clean(&s.title)));
2888                            labels.push(titles.join("\u{1f}"));
2889                            actions.push(format!("{action}:{selected}"));
2890                        } else {
2891                            labels.push(clean(label));
2892                            actions.push(action.to_string());
2893                        }
2894                        // Bit 0: enabled; bit 1: checked. Preserve disabled checked state too.
2895                        let checked = matches!(item.kind, K::Toggle { on: true });
2896                        enabled.push((u8::from(on) | (u8::from(checked) << 1)).to_string());
2897                        scopes.push(scope);
2898                    };
2899                match &item.kind {
2900                    K::Button | K::Toggle { .. } => {
2901                        add(item.icon.as_ref(), &item.label, item.action, item.enabled);
2902                    }
2903                    // The choice in force names the control and lends it its glyph, the way a
2904                    // Material bar folds one (day-toolkit-material).
2905                    K::Segmented { segments, selected } => {
2906                        let seg = segments.get(*selected);
2907                        add(
2908                            seg.and_then(|s| s.icon.as_ref()).or(item.icon.as_ref()),
2909                            seg.map_or(item.label.as_str(), |s| s.title.as_str()),
2910                            item.action,
2911                            item.enabled,
2912                        );
2913                    }
2914                    K::Menu { items } => {
2915                        for entry in items {
2916                            if let day_spec::MenuItem::Action {
2917                                label,
2918                                action,
2919                                enabled: on,
2920                                ..
2921                            } = entry
2922                            {
2923                                add(None, label, *action, *on && item.enabled);
2924                            }
2925                        }
2926                    }
2927                    K::Search { .. } | K::Label | K::Separator => {}
2928                }
2929            }
2930        });
2931        crate::host_api::nav_set_menu(
2932            &icons.join("\n"),
2933            &labels.join("\n"),
2934            &actions.join("\n"),
2935            &scopes.join("\n"),
2936            &enabled.join("\n"),
2937        );
2938    }
2939
2940    /// Whether `h` is a secondary window's root (a `DayWindowAbility` page). The title-bar actions
2941    /// belong to the primary window's `Navigation`; a secondary page has no such bar, so its
2942    /// toolbar is not drawn, and its edits must not land in the primary's model (docs/toolbars.md).
2943    fn is_secondary_root(h: &AHandle) -> bool {
2944        let ptr = h.0 as usize;
2945        SECONDARY.with(|s| s.borrow().iter().any(|(_, stack)| *stack == ptr))
2946    }
2947
2948    /// What a node shows, read back from ArkUI's own attributes (`Toolkit::read_native`). Only
2949    /// what is read is reported; the accessibility group stays unread (`found: false`), since
2950    /// ArkUI reports a component's default announcement nowhere a getter reaches.
2951    fn read_native(n: Handle) -> day_spec::NativeSnapshot {
2952        use ohos_sys::arkui::native_node::ArkUI_NodeAttributeType as Attr;
2953        use ohos_sys::arkui::native_type::{ArkUI_TextInputType as Type, ArkUI_Visibility};
2954        let mut snap = day_spec::NativeSnapshot::default();
2955        if n.is_null() {
2956            return snap;
2957        }
2958        // An item without a string is an unread attribute, not an empty one.
2959        let string = |n: Handle, attr: Attr| {
2960            node::get_item(n, attr)
2961                .filter(|it| !it.string.is_null())
2962                .map(|it| node::text_of(it.string))
2963        };
2964        match node::node_type(n) {
2965            Some(node::TEXT) => {
2966                // A label with runs keeps its text in SPAN children (`set_label_runs`), the
2967                // Text's own content cleared.
2968                // The spans come from the backend's own list: ArkUI's child walk does not return a
2969                // Text's spans (`node::label_spans`).
2970                let own = string(n, Attr::NODE_TEXT_CONTENT);
2971                let spans = node::label_spans(n);
2972                snap.text = match own {
2973                    Some(own) if own.is_empty() && !spans.is_empty() => spans
2974                        .iter()
2975                        .map(|&c| string(c, Attr::NODE_SPAN_CONTENT))
2976                        .collect::<Option<String>>(),
2977                    own => own,
2978                };
2979            }
2980            Some(node::BUTTON) => {
2981                // An icon button's title is a Text beside the image (`apply_button_content`),
2982                // padded with two spaces; an icon-only one shows no text.
2983                let content = BUTTON_CHILDREN.with(|m| {
2984                    m.borrow()
2985                        .get(&(n as usize))
2986                        .map(|children| children.get(2).map(|label| label.0))
2987                });
2988                snap.text = match content {
2989                    Some(Some(label)) => string(label, Attr::NODE_TEXT_CONTENT)
2990                        .map(|s| s.strip_prefix("  ").map(str::to_owned).unwrap_or(s)),
2991                    Some(None) => None,
2992                    None => string(n, Attr::NODE_BUTTON_LABEL),
2993                };
2994                // The selected state (`apply_button_selected`), which the node itself has no
2995                // attribute for.
2996                snap.checked = BUTTON_SELECTED.with(|m| m.borrow().get(&(n as usize)).copied());
2997            }
2998            Some(node::TEXT_INPUT) => {
2999                // A password type masks the text: nothing is reported, nor for an unread type.
3000                let masked = node::get_i32(n, Attr::NODE_TEXT_INPUT_TYPE, 0).is_none_or(|t| {
3001                    [
3002                        Type::ARKUI_TEXTINPUT_TYPE_PASSWORD,
3003                        Type::ARKUI_TEXTINPUT_TYPE_NUMBER_PASSWORD,
3004                        Type::ARKUI_TEXTINPUT_TYPE_NEW_PASSWORD,
3005                    ]
3006                    .iter()
3007                    .any(|ty| ty.0 as i32 == t)
3008                });
3009                if !masked {
3010                    snap.text = string(n, Attr::NODE_TEXT_INPUT_TEXT);
3011                }
3012            }
3013            Some(node::TEXT_AREA) => snap.text = string(n, Attr::NODE_TEXT_AREA_TEXT),
3014            Some(node::TOGGLE) => {
3015                snap.checked = node::get_i32(n, Attr::NODE_TOGGLE_VALUE, 0).map(|v| v != 0);
3016            }
3017            Some(node::SLIDER) => {
3018                // ArkUI's 0..100, mapped back onto the range Day gave (`normalize`).
3019                let range = CTRL_NODE
3020                    .with(|m| m.borrow().get(&(n as usize)).copied())
3021                    .and_then(|id| SLIDER_RANGE.with(|m| m.borrow().get(&id).copied()));
3022                snap.number = node::get_f32(n, Attr::NODE_SLIDER_VALUE, 0)
3023                    .zip(range)
3024                    .map(|(v, (min, max))| min + f64::from(v) / 100.0 * (max - min));
3025            }
3026            Some(node::TEXT_PICKER) => {
3027                // The wheel's option at its selected index, split the way `set_picker` joined
3028                // the range. A menu or segmented picker is an ArkTS piece, out of a getter's reach.
3029                // The index slot is a u32, read as i32: the same bits for any real index.
3030                let selected = node::get_i32(n, Attr::NODE_TEXT_PICKER_OPTION_SELECTED, 0)
3031                    .and_then(|i| usize::try_from(i).ok());
3032                snap.text = string(n, Attr::NODE_TEXT_PICKER_OPTION_RANGE)
3033                    .zip(selected)
3034                    .and_then(|(range, i)| range.split(';').nth(i).map(str::to_owned));
3035            }
3036            Some(node::PROGRESS) => {
3037                // The fraction over the total `set_progress` wrote; a spinner has no value.
3038                let total = node::get_f32(n, Attr::NODE_PROGRESS_TOTAL, 0).filter(|t| *t > 0.0);
3039                snap.number = node::get_f32(n, Attr::NODE_PROGRESS_VALUE, 0)
3040                    .zip(total)
3041                    .map(|(v, total)| f64::from(v) / f64::from(total));
3042            }
3043            _ => {}
3044        }
3045        snap.enabled = node::get_i32(n, Attr::NODE_ENABLED, 0).map(|v| v != 0);
3046
3047        // Walk the C-API ancestors up to a window root: the primary root, the cover layer above
3048        // it, or a secondary window's. The walk stops short of one where a node sits in an
3049        // ArkTS host (a Navigation page, a piece), whose own visibility is out of reach.
3050        // `Platform::run` consumes ROOT when it hands the handle to day-core. Native
3051        // inspection runs after that handoff, so use the lifetime-long root record,
3052        // as window snapshots do, or every primary-window frame stays unread.
3053        let primary = ROOT_KEEP.with(|r| r.get().map(|(root, _, _)| root));
3054        let cover = COVER_ROOT.with(std::cell::Cell::get).map(|(p, _, _)| p);
3055        let secondaries: Vec<usize> =
3056            SECONDARY.with(|s| s.borrow().iter().map(|(_, p)| *p).collect());
3057        let visible = ArkUI_Visibility::ARKUI_VISIBILITY_VISIBLE.0 as i32;
3058        let (mut hidden, mut unread, mut window) = (false, false, None);
3059        let mut at = n;
3060        // Bounded: a tree is never this deep, and a cycle must not hang the reader.
3061        for _ in 0..4096 {
3062            if at.is_null() {
3063                break;
3064            }
3065            match node::get_i32(at, Attr::NODE_VISIBILITY, 0) {
3066                Some(v) if v != visible => hidden = true,
3067                Some(_) => {}
3068                None => unread = true,
3069            }
3070            let ptr = at as usize;
3071            if Some(ptr) == primary || Some(ptr) == cover {
3072                window = primary;
3073                break;
3074            }
3075            if secondaries.contains(&ptr) {
3076                window = Some(ptr);
3077                break;
3078            }
3079            at = node::parent(at);
3080        }
3081        snap.visible = if hidden {
3082            Some(false)
3083        } else if window.is_some() && !unread {
3084            Some(true)
3085        } else {
3086            None
3087        };
3088
3089        // The frame against its window's root, Day's content area there. A node the walk did
3090        // not place still has one window to be in while no secondary is open.
3091        let base = window.or_else(|| primary.filter(|_| secondaries.is_empty()));
3092        if let Some(base) = base
3093            && let Some((x, y, w, h)) = node::layout_frame_px(n)
3094            && let Some((bx, by, _, _)) = node::layout_frame_px(base as Handle)
3095        {
3096            let d = node::density();
3097            snap.frame = Some(Rect::new((x - bx) / d, (y - by) / d, w / d, h / d));
3098        }
3099        snap
3100    }
3101
3102    /// The ArkTS host reports a ROOT area change after start (keyboard RESIZE avoidance,
3103    /// rotation, window resize), routed to Day as a window resize, the shared rail
3104    /// (docs/focus.md; same shape as Android's kind-15 event). `keyboard` is the keyboard's
3105    /// avoid-area height, which the size class adds back: a tablet typing is still a tablet.
3106    pub fn resized(w: f64, h: f64, keyboard: f64) {
3107        day_spec::ffi_guard::contain((), || {
3108            if w > 0.0 && h > 0.0 {
3109                ROOT_KEEP.with(|r| {
3110                    if let Some((ptr, _, _)) = r.get() {
3111                        r.set(Some((ptr, w, h)));
3112                    }
3113                });
3114                let size = Size::new(w, h);
3115                day_core::note_keyboard_overlap(day_spec::WINDOW_NODE, size, keyboard.max(0.0));
3116                emit(day_spec::WINDOW_NODE, Event::WindowResized(size));
3117            }
3118        });
3119    }
3120
3121    /// The permission seam for `day-part-permissions` (docs/permissions.md): the part reaches this
3122    /// by `dlsym` rather than a link-time dependency on this toolkit, and it forwards to the
3123    /// host's ArkTS-registered prompter. 1 when the request went out (`cb` then runs on the JS
3124    /// thread with the request id and a bit mask of the grants), 0 when no prompter is
3125    /// registered, in which case `cb` is never called.
3126    #[unsafe(no_mangle)]
3127    #[allow(clippy::not_unsafe_ptr_arg_deref)] // `names` is a valid C string from the part
3128    pub extern "C" fn day_arkui_request_permissions(
3129        req: u64,
3130        names: *const std::ffi::c_char,
3131        cb: extern "C" fn(u64, u64),
3132    ) -> std::ffi::c_int {
3133        day_spec::ffi_guard::contain(0, || {
3134            let names = node::text_of(names);
3135            std::ffi::c_int::from(crate::host_api::request_permissions(req, &names, cb))
3136        })
3137    }
3138
3139    /// daybridge's door to an ArkTS arm (docs/bridge.md "Callbacks"): `day_bridge::arkts::invoke`
3140    /// finds this by `dlsym` rather than a link-time dependency on this toolkit, and it runs the
3141    /// registered function on the JS thread.
3142    #[unsafe(no_mangle)]
3143    #[allow(clippy::not_unsafe_ptr_arg_deref)] // `symbol`/`args` are valid for the call, per the bridge
3144    pub extern "C" fn day_arkui_bridge_invoke(
3145        symbol: *const std::ffi::c_char,
3146        args: *const std::ffi::c_void,
3147        n: usize,
3148        done: u64,
3149        ret: *mut std::ffi::c_void,
3150    ) -> std::ffi::c_int {
3151        day_spec::ffi_guard::contain(2, || {
3152            // SAFETY: the bridge passes `n` `Arg`s of the layout `bridge::Arg` mirrors.
3153            unsafe { crate::bridge::invoke(symbol, args.cast(), n, done, ret.cast()) }
3154        })
3155    }
3156
3157    /// Whether the caller is the JS thread, the UI thread of a Day app here, where a bridged
3158    /// crate's blocking call cannot wait for an ArkTS answer.
3159    #[unsafe(no_mangle)]
3160    pub extern "C" fn day_arkui_bridge_on_js_thread() -> std::ffi::c_int {
3161        std::ffi::c_int::from(crate::main_thread::on_js_thread())
3162    }
3163
3164    /// The ArkTS host reports the app cache dir here (docs/files.md); it's the app-writable staging
3165    /// area for `save_file(..)`, since HarmonyOS's OS temp dir isn't writable by the app.
3166    pub fn set_cache_dir(path: &str) {
3167        day_spec::ffi_guard::contain((), || {
3168            if !path.is_empty() {
3169                day_spec::present::set_app_temp_dir(path.to_owned());
3170            }
3171        });
3172    }
3173
3174    /// The ArkUI backend. `new` collects any externally-registered renderers (§8.2), like the others.
3175    pub struct ArkUi {
3176        registry: Registry<ArkUi>,
3177    }
3178
3179    #[distributed_slice]
3180    pub static RENDERERS: [fn() -> Renderer<ArkUi>];
3181
3182    impl ArkUi {
3183        #[must_use]
3184        pub fn new() -> Self {
3185            let mut registry = Registry::default();
3186            for f in RENDERERS {
3187                registry.register(f());
3188            }
3189            ArkUi { registry }
3190        }
3191    }
3192
3193    impl Default for ArkUi {
3194        fn default() -> Self {
3195            Self::new()
3196        }
3197    }
3198
3199    /// Warn once per kind that this backend has no registered renderer for `kind`, before falling
3200    /// back to a placeholder (an empty stack node). A missing renderer usually means the piece's
3201    /// `arkui` feature wasn't enabled. Deduped per kind so it doesn't spam the log.
3202    fn warn_missing_renderer(kind: PieceKind) {
3203        day_spec::placeholder::report(kind, "arkui");
3204    }
3205
3206    impl Toolkit for ArkUi {
3207        type Handle = AHandle;
3208
3209        fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> AHandle {
3210            match Builtin::from_key(kind) {
3211                Some(Builtin::Container) => {
3212                    let n = new_node(node::STACK);
3213                    // No input of its own until something attaches it (docs/gestures.md
3214                    // "Pass-through"); its children keep theirs.
3215                    node::make_passive(n.0);
3216                    if let Some(p) = props.downcast_ref::<ContainerProps>() {
3217                        if p.role == Some(day_spec::SurfaceRole::SectionCard) {
3218                            // A translucent neutral fill reads as a subtle card on both the
3219                            // light and dark ArkUI themes (no public semantic-fill API).
3220                            SURFACE_ROLE.with(|m| m.insert(n.0 as usize, ()));
3221                            themed(
3222                                n.0 as usize,
3223                                n.0,
3224                                Paint::Background,
3225                                0x1480_8080,
3226                                0x2EFF_FFFF,
3227                            );
3228                        } else if p.role == Some(day_spec::SurfaceRole::Window) {
3229                            // The window background an opaque cover paints.
3230                            SURFACE_ROLE.with(|m| m.insert(n.0 as usize, ()));
3231                            themed(
3232                                n.0 as usize,
3233                                n.0,
3234                                Paint::Background,
3235                                0xFFFF_FFFF,
3236                                0xFF1A_1A1C,
3237                            );
3238                        }
3239                        apply_surface(n.0, p, true);
3240                    }
3241                    n
3242                }
3243                Some(Builtin::Scroll) => {
3244                    let n = new_node(node::SCROLL);
3245                    let scroll = props.downcast_ref::<day_spec::props::ScrollProps>();
3246                    let horizontal = scroll.is_some_and(|p| p.horizontal);
3247                    node::scroll_direction(n.0, horizontal);
3248                    if let Some(p) = scroll {
3249                        node::scroll_preferences(n.0, p);
3250                        // Offsets and phases only for an app that observes them
3251                        // (docs/scroll.md).
3252                        crate::events::track_scroll(n.0, id.0, p.track_offset, p.track_phase);
3253                    }
3254                    // The one real child ArkUI's Scroll measures its extent from (see
3255                    // [`SCROLL_CONTENT`]); day children land inside it via `insert`.
3256                    let content = new_node(node::STACK);
3257                    node::insert_child(n.0, content.0, 0);
3258                    SCROLL_CONTENT
3259                        .with(|m| m.borrow_mut().insert(n.0 as usize, content.0 as usize));
3260                    n
3261                }
3262                Some(Builtin::Image) => {
3263                    // Here and in every arm below: a props-type mismatch degrades to the same
3264                    // empty-stack placeholder a missing renderer gets (`props_of` reported it):
3265                    // realize runs inside native up-calls, where a panic is a process kill.
3266                    let Some(p) = day_spec::props_of::<ImageProps>(kind, "arkui", props) else {
3267                        return new_node(node::STACK);
3268                    };
3269                    let n = new_node(node::IMAGE);
3270                    // Resolve `image("name")` through the app's rawfile store, the only resource
3271                    // root the OpenHarmony NDK can address from native code (app.media is ArkTS-only,
3272                    // §18.3). The CLI stages each image uncompressed to resources/rawfile/day/<name>
3273                    // normalized to PNG, so a bare `source` (no extension) maps to `day/<source>.png`.
3274                    // A vector name resolves to its staged SVG instead (docs/vectors.md): ArkUI
3275                    // renders it natively at display size, and `.tint(…)` recolors it via
3276                    // SourceIn compositing (untinted = as authored, matching every backend). A
3277                    // TEMPLATE glyph with no tint takes the mode's primary text color instead,
3278                    // repainted on a switch like an un-colored label (docs/vectors.md
3279                    // "Template"); a raster template with no tint draws as authored.
3280                    // Bytes and Decoded arrive from `day::decode_image` (docs/images.md), so an
3281                    // `image()` piece can show a download or a pasted PNG with no staged resource
3282                    // behind it. A tint recolors every one of them the same way: the color layer
3283                    // composites over whatever the image node drew.
3284                    node::make_passive(n.0);
3285                    arkui_apply_image_source(n.0, &p.source, p.tint);
3286                    if p.template && p.tint.is_none() && arkui_image_is_svg(&p.source) {
3287                        themed(n.0 as usize, n.0, Paint::ImageFill, TEXT_LIGHT, TEXT_DARK);
3288                    }
3289                    // Scaling (§18.3): ArkUI_ObjectFit CONTAIN=0 (fit) / COVER=1 (fill) / FILL=3.
3290                    let fit = match p.content_mode {
3291                        ContentMode::Fit => 0,
3292                        ContentMode::Fill => 1,
3293                        ContentMode::Stretch => 3,
3294                    };
3295                    node::set_image_fit(n.0, fit);
3296                    n
3297                }
3298                Some(Builtin::Label) => {
3299                    let Some(p) = day_spec::props_of::<LabelProps>(kind, "arkui", props) else {
3300                        return new_node(node::STACK);
3301                    };
3302                    let n = new_node(node::TEXT);
3303                    CTRL_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3304                    node::set_text(n.0, &p.text);
3305                    node::set_font_size(n.0, label_fp(p.font));
3306                    if let Some(c) = p.color {
3307                        paint_ink(n.0 as usize, n.0, Paint::Font, c);
3308                    } else {
3309                        // Text defaults don't re-theme through the C API: an un-colored
3310                        // label takes the mode's primary text color, repainted on a switch.
3311                        themed(n.0 as usize, n.0, Paint::Font, TEXT_LIGHT, TEXT_DARK);
3312                    }
3313                    apply_font_attrs(n.0, p.font);
3314                    if !p.runs.is_empty() {
3315                        set_label_runs(n.0, &p.text, &p.runs);
3316                    }
3317                    if p.align != day_spec::props::TextAlign::Leading {
3318                        node::label_align(n.0, p.align);
3319                    }
3320                    // After the font: spacing and line height are multiples of its size.
3321                    apply_paragraph(n.0, p.paragraph(), p.wraps);
3322                    n
3323                }
3324                Some(Builtin::Button) => {
3325                    let Some(p) = day_spec::props_of::<ButtonProps>(kind, "arkui", props) else {
3326                        return new_node(node::STACK);
3327                    };
3328                    let n = new_node(node::BUTTON);
3329                    node::set_button_label(n.0, &p.title);
3330                    node::register_event(n.0, node::EV_CLICK, id.0);
3331                    node::enable_focus(n.0, id.0, false);
3332                    apply_button_style(n.0, p.style);
3333                    if p.icon.is_some() {
3334                        apply_button_content(n, &p.title, p.icon.as_ref(), p.icon_only);
3335                    }
3336                    node::set_enabled(n.0, p.enabled);
3337                    apply_button_selected(n.0, p.selected);
3338                    n
3339                }
3340                Some(Builtin::TextField) => {
3341                    let Some(p) = day_spec::props_of::<TextFieldProps>(kind, "arkui", props) else {
3342                        return new_node(node::STACK);
3343                    };
3344                    let n = new_node(node::TEXT_INPUT);
3345                    CTRL_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3346                    TEXT_ECHO.with(|m| m.borrow_mut().insert(id.0, p.text.clone()));
3347                    INPUT_FIELDS.with(|m| m.borrow_mut().insert(id.0, InputField::default()));
3348                    node::set_input_text(n.0, &p.text);
3349                    node::set_placeholder(n.0, &p.placeholder);
3350                    node::register_event(n.0, node::EV_TEXT_INPUT_CHANGE, id.0);
3351                    node::enable_focus(n.0, id.0, true);
3352                    node::set_enabled(n.0, p.enabled);
3353                    n
3354                }
3355                // Multi-line editor (docs/textarea.md): ARKUI_NODE_TEXT_AREA. min/max-lines
3356                // aren't a native attribute here: the node grows with content and the measure
3357                // arm bounds it.
3358                Some(Builtin::TextArea) => {
3359                    let Some(p) = day_spec::props_of::<TextAreaProps>(kind, "arkui", props) else {
3360                        return new_node(node::STACK);
3361                    };
3362                    let n = new_node(node::TEXT_AREA);
3363                    CTRL_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3364                    TEXT_ECHO.with(|m| m.borrow_mut().insert(id.0, p.text.clone()));
3365                    INPUT_FIELDS.with(|m| {
3366                        m.borrow_mut().insert(
3367                            id.0,
3368                            InputField {
3369                                held: (!p.editable).then(|| p.text.clone()),
3370                                area_selectable: Some(p.selectable),
3371                                submit_on_enter: p.submit_on_enter,
3372                                ..Default::default()
3373                            },
3374                        )
3375                    });
3376                    TEXTAREA_LINES.with(|m| {
3377                        m.borrow_mut()
3378                            .insert(n.0 as usize, (p.min_lines, p.max_lines))
3379                    });
3380                    node::set_textarea_text(n.0, &p.text);
3381                    node::set_textarea_placeholder(n.0, &p.placeholder);
3382                    node::register_event(n.0, node::EV_TEXT_AREA_CHANGE, id.0);
3383                    node::watch_textarea_edits(n.0, id.0);
3384                    if p.submit_on_enter {
3385                        node::enable_textarea_submit(n.0, id.0);
3386                    }
3387                    node::set_textarea_editable(n.0, p.editable);
3388                    node::set_textarea_selectable(n.0, p.selectable);
3389                    node::enable_focus(n.0, id.0, false);
3390                    n
3391                }
3392                // Option picker (docs/picker.md). A menu picker is HarmonyOS's own dropdown, the
3393                // ArkTS `Select` the host registers (DaySelect.ets; the C node API has no select
3394                // kind). The same host builds a compact button row for segmented pickers.
3395                // Inline pickers and hosts without the built-in piece use the TEXT_PICKER wheel.
3396                Some(Builtin::Picker) => {
3397                    let Some(p) = day_spec::props_of::<PickerProps>(kind, "arkui", props) else {
3398                        return new_node(node::STACK);
3399                    };
3400                    if matches!(p.style, PickerStyle::Menu | PickerStyle::Segmented)
3401                        && let Some(n) = piece::try_make(
3402                            if p.style == PickerStyle::Segmented {
3403                                SEGMENTED_PICKER_KIND
3404                            } else {
3405                                MENU_PICKER_KIND
3406                            },
3407                            id,
3408                            &select_props(Some(p.selected), &p.options),
3409                        )
3410                    {
3411                        if !p.enabled {
3412                            set_picker_piece_enabled(&n, false);
3413                        }
3414                        if p.style == PickerStyle::Segmented {
3415                            size_segmented_picker(&n, &p.options);
3416                        } else {
3417                            size_menu_picker(
3418                                &n,
3419                                p.options.get(p.selected).map(String::as_str),
3420                                &p.options,
3421                            );
3422                        }
3423                        return n;
3424                    }
3425                    let n = new_node(node::TEXT_PICKER);
3426                    let joined = p.options.join(";");
3427                    PICKER_SELECTED.with(|m| m.insert(n.0 as usize, p.selected));
3428                    node::set_picker(n.0, &joined, p.selected as u32);
3429                    node::register_event(n.0, node::EV_TEXT_PICKER_CHANGE, id.0);
3430                    node::enable_focus(n.0, id.0, false);
3431                    node::set_enabled(n.0, p.enabled);
3432                    n
3433                }
3434                Some(Builtin::Toggle) => {
3435                    let Some(p) = day_spec::props_of::<ToggleProps>(kind, "arkui", props) else {
3436                        return new_node(node::STACK);
3437                    };
3438                    let n = new_node(node::TOGGLE);
3439                    // ArkUI's SwitchPattern adds theme hot-zone margins by default. Day
3440                    // already allocates and positions the control's box; those margins
3441                    // otherwise shift the painted switch down/right into the next row.
3442                    // Keep the native switch and its hit handling, but own its outer spacing.
3443                    node::set_margin(n.0, 0.0);
3444                    CTRL_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3445                    TOGGLE_GATE.with(|m| {
3446                        m.borrow_mut().insert(
3447                            id.0,
3448                            ToggleGate {
3449                                handle: n.0 as usize,
3450                                written: p.on,
3451                                armed: false,
3452                            },
3453                        )
3454                    });
3455                    node::set_toggle(n.0, p.on);
3456                    node::register_event(n.0, node::EV_TOGGLE_CHANGE, id.0);
3457                    // What arms the gate: the user's touch, or a key on the focused switch.
3458                    node::register_event(n.0, node::EV_TOUCH, id.0);
3459                    node::register_event(n.0, node::EV_KEY, id.0);
3460                    node::enable_focus(n.0, id.0, false);
3461                    node::set_enabled(n.0, p.enabled);
3462                    n
3463                }
3464                Some(Builtin::Slider) => {
3465                    let Some(p) = day_spec::props_of::<SliderProps>(kind, "arkui", props) else {
3466                        return new_node(node::STACK);
3467                    };
3468                    let n = new_node(node::SLIDER);
3469                    CTRL_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3470                    SLIDER_ECHO.with(|m| m.borrow_mut().insert(id.0, p.value));
3471                    SLIDER_RANGE.with(|m| m.borrow_mut().insert(id.0, (p.min, p.max)));
3472                    node::set_slider(n.0, normalize(p.value, p.min, p.max));
3473                    node::register_event(n.0, node::EV_SLIDER_CHANGE, id.0);
3474                    node::enable_focus(n.0, id.0, false);
3475                    node::set_enabled(n.0, p.enabled);
3476                    n
3477                }
3478                // A 1-vp hairline: a thin Stack tinted with a faint separator color.
3479                Some(Builtin::Divider) => {
3480                    let n = new_node(node::STACK);
3481                    node::make_passive(n.0);
3482                    themed(
3483                        n.0 as usize,
3484                        n.0,
3485                        Paint::Background,
3486                        0x3300_0000,
3487                        0x33FF_FFFF,
3488                    );
3489                    n
3490                }
3491                // Determinate bar (ARKUI_NODE_PROGRESS) vs indeterminate spinner (LOADING_PROGRESS).
3492                Some(Builtin::Progress) => {
3493                    let Some(p) = day_spec::props_of::<ProgressProps>(kind, "arkui", props) else {
3494                        return new_node(node::STACK);
3495                    };
3496                    if p.value.is_none() {
3497                        return crate::controls::spinner::make(self, p, id);
3498                    }
3499                    match p.value {
3500                        Some(v) => {
3501                            let n = new_node(node::PROGRESS);
3502                            node::set_progress(n.0, v);
3503                            n
3504                        }
3505                        None => new_node(node::LOADING),
3506                    }
3507                }
3508                // Each stack is its own ArkTS Navigation, mounted through the piece bridge.
3509                // Root and pushed pages use that host's content slots, with native title bars,
3510                // transitions and Back. Tabs remain resident-page ownership boundaries.
3511                Some(Builtin::Nav) => {
3512                    let Some(p) = day_spec::props_of::<NavProps>(kind, "arkui", props) else {
3513                        return new_node(node::STACK);
3514                    };
3515                    // Rows as CHROME: a composed bottom bar over resident pages (see NavSuite).
3516                    // A compact window gets here through `Automatic`.
3517                    if p.presentation.rows_are_chrome() {
3518                        let host = new_node(node::COLUMN);
3519                        let pages = new_node(node::STACK);
3520                        let bar = new_node(node::ROW);
3521                        node::insert_child(host.0, pages.0, 0);
3522                        node::insert_child(host.0, bar.0, 1);
3523                        themed(
3524                            host.0 as usize,
3525                            bar.0,
3526                            Paint::Background,
3527                            0xFFF1_F3F5,
3528                            0xFF1C_1C1E,
3529                        );
3530                        SUITE_AWAITING_MENU.with(|c| c.set(Some(host.0 as usize)));
3531                        NAV_SUITES.with(|c| {
3532                            c.borrow_mut().insert(
3533                                host.0 as usize,
3534                                NavSuite {
3535                                    documents: p.documents.is_some(),
3536                                    pages,
3537                                    bar,
3538                                    items: Vec::new(),
3539                                    bar_items: Vec::new(),
3540                                    bar_inks: Vec::new(),
3541                                    selected: 0,
3542                                    page_size: Size::ZERO,
3543                                    placement: SuitePlacement::Bottom,
3544                                    menu: None,
3545                                    labels: Vec::new(),
3546                                    icons: Vec::new(),
3547                                },
3548                            )
3549                        });
3550                        // Told once and never revised: the chrome is the same at every width.
3551                        emit(
3552                            id,
3553                            Event::NavPresentationChanged(day_spec::props::NavPresentation::Tabs),
3554                        );
3555                        return host;
3556                    }
3557                    let n = piece::make("day.navigation.stack", id, &p.title);
3558                    NAV_HOSTS.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3559                    // An adaptive host follows the window: ArkUI's Navigation runs in Auto
3560                    // mode, tiling the rows beside the detail where both fit (a tablet, a wide
3561                    // window) and stacking them where they do not, and reports which through
3562                    // `navModeChanged` (docs/size-classes.md). `Stack` in props is literal, a
3563                    // host that stacks at every width (a nested `nav_stack`), so it is not.
3564                    if p.adaptive && p.presentation != day_spec::props::NavPresentation::Stack {
3565                        piece::update(&n, "day.adaptive", "1");
3566                    }
3567                    match p
3568                        .search
3569                        .as_ref()
3570                        .filter(|sp| sp.placement == SearchPlacement::Inline)
3571                    {
3572                        Some(sp) => crate::host_api::nav_set_search(id.0, 1, &sp.prompt, &sp.text),
3573                        None => crate::host_api::nav_set_search(id.0, 0, "", ""),
3574                    }
3575                    n
3576                }
3577                Some(Builtin::NavPage) => {
3578                    let n = new_node(node::STACK);
3579                    themed(
3580                        n.0 as usize,
3581                        n.0,
3582                        Paint::Background,
3583                        0xFFFF_FFFF,
3584                        0xFF1A_1A1C,
3585                    );
3586                    NAV_PAGE_IDS.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3587                    n
3588                }
3589                // Fullscreen cover (docs/cover.md): a Stack that CoverPatch::Present re-homes
3590                // onto the host's cover layer above Navigation, at full-window bounds.
3591                Some(Builtin::Cover) => {
3592                    let n = new_node(node::STACK);
3593                    COVER_NODES.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3594                    if day_spec::props_of::<CoverProps>(kind, "arkui", props)
3595                        .is_some_and(|p| p.half)
3596                    {
3597                        COVER_HALF.with(|s| s.borrow_mut().insert(n.0 as usize));
3598                    }
3599                    n
3600                }
3601                // A scrollable column of tappable rows; each row's tap becomes SelectionChanged(index)
3602                // against this menu host (via a synthetic click id, see on_event).
3603                Some(Builtin::NavMenu) => {
3604                    let Some(p) = day_spec::props_of::<NavMenuProps>(kind, "arkui", props) else {
3605                        return new_node(node::STACK);
3606                    };
3607                    // Inside a suite the rows are the bar. The list is still built (it lives in
3608                    // the sidebar page, which the suite keeps but never shows) so nothing else
3609                    // has to know which presentation it is in.
3610                    if let Some(host) = SUITE_AWAITING_MENU.with(std::cell::Cell::take) {
3611                        MENU_SUITE.with(|m| m.borrow_mut().insert(id.0, host));
3612                        suite_fill_bar(host, id, &p.items, &p.icons, 0);
3613                    }
3614                    build_nav_menu(
3615                        id,
3616                        &p.items,
3617                        &p.icons,
3618                        &p.tints,
3619                        &p.badges,
3620                        &p.badge_icons,
3621                        &p.badge_tints,
3622                        &p.sections,
3623                    )
3624                }
3625                // Canvas: a focus-holding host around the custom node whose on-draw callback
3626                // replays the encoded display list (src/canvas.rs).
3627                Some(Builtin::Canvas) => {
3628                    let n = AHandle(crate::canvas::create(id.0));
3629                    node::make_passive(n.0);
3630                    n
3631                }
3632                // Recycling list: an ARKUI_NODE_LIST driven by a NodeAdapter (attach_list injects the
3633                // row source; the adapter binds cells on demand). See attach_list / src/list.rs.
3634                Some(Builtin::List) => {
3635                    let Some(p) = day_spec::props_of::<ListProps>(kind, "arkui", props) else {
3636                        return new_node(node::STACK);
3637                    };
3638                    let row_h = match p.row_height {
3639                        RowHeight::Uniform(h) => h,
3640                        RowHeight::Automatic => 0.0,
3641                    };
3642                    // A sectioned list is a Stack around the LIST and its pinned header
3643                    // (docs/list.md "Sections"); list.rs builds both inside it.
3644                    let n = new_node(if p.sections { node::STACK } else { node::LIST });
3645                    LIST_NODE.with(|m| m.borrow_mut().insert(n.0 as usize, id.0));
3646                    crate::list::init(n.0, id.0, row_h, p);
3647                    n
3648                }
3649                // A recycled list cell is ADOPTED from the native list, never realized
3650                // through this path; anything else is an extension piece.
3651                Some(
3652                    Builtin::ListCell
3653                    | Builtin::ListItem
3654                    | Builtin::Tree
3655                    | Builtin::Inspector
3656                    | Builtin::InspectorPane
3657                    | Builtin::Split
3658                    | Builtin::SplitPane,
3659                )
3660                | None => {
3661                    if let Some(r) = self.registry.get(kind) {
3662                        let make = r.make;
3663                        return make(self, props, id);
3664                    }
3665                    warn_missing_renderer(kind);
3666                    new_node(node::STACK)
3667                }
3668            }
3669        }
3670
3671        fn update(
3672            &mut self,
3673            h: &AHandle,
3674            kind: PieceKind,
3675            patch: &dyn Any,
3676            anim: Option<&AnimSpec>,
3677        ) {
3678            match kind {
3679                // Navigation (docs/navigation.md): drive the ArkTS Navigation/NavPathStack.
3680                kinds::NAV => {
3681                    let owner = NAV_HOSTS.with(|m| m.borrow().get(&(h.0 as usize)).copied());
3682                    // Inline search (docs/search.md): the app writing its query fills the field.
3683                    if let Some(owner) = owner {
3684                        match patch.downcast_ref::<day_spec::props::SearchPatch>() {
3685                            Some(day_spec::props::SearchPatch::Focus) => {
3686                                crate::host_api::nav_set_search(owner, -2, "", "");
3687                            }
3688                            Some(day_spec::props::SearchPatch::Text(t)) => {
3689                                crate::host_api::nav_set_search(owner, -1, "", t);
3690                            }
3691                            _ => {}
3692                        }
3693                    }
3694                    if let Some(p) = patch.downcast_ref::<NavPatch>() {
3695                        match p {
3696                            NavPatch::Pushed { title, .. } => {
3697                                // Consume this host's pending child and mount it in a native
3698                                // destination. It is deliberately not attached to the wrapper:
3699                                // doing so would paint it on top of the native Navigation.
3700                                let last = NAV_ATTACHED.with(|v| {
3701                                    v.borrow_mut()
3702                                        .get_mut(&(h.0 as usize))
3703                                        .and_then(std::vec::Vec::pop)
3704                                });
3705                                if let Some((page, key)) = last {
3706                                    let page = page as Handle;
3707                                    if owner.is_some_and(|owner| {
3708                                        crate::host_api::nav_push(owner, page, key, title, true)
3709                                            == 0
3710                                    }) {
3711                                        NAV_PUSHED
3712                                            .with(|m| m.borrow_mut().insert(page as usize, key));
3713                                        NAV_STACK.with(|s| {
3714                                            s.borrow_mut()
3715                                                .entry(h.0 as usize)
3716                                                .or_default()
3717                                                .push(key);
3718                                        });
3719                                        NAV_PENDING_PUSH.with(|s| s.borrow_mut().insert(key));
3720                                    } else {
3721                                        // No ArkTS bridge (old host page): fall back to the
3722                                        // stacked-children presentation.
3723                                        node::add_child(h.0, page);
3724                                    }
3725                                }
3726                            }
3727                            NavPatch::Popped => {
3728                                // Pop natively only if a destination is actually up and not
3729                                // already popped by a native back (the NavBack sync path:
3730                                // `nav_popped` removed its key from NAV_STACK).
3731                                let popped = NAV_STACK.with(|s| {
3732                                    s.borrow_mut()
3733                                        .get_mut(&(h.0 as usize))
3734                                        .and_then(std::vec::Vec::pop)
3735                                });
3736                                if let Some(key) = popped {
3737                                    NAV_EXPECT_POP.with(|e| e.borrow_mut().insert(key));
3738                                    // A page popped before it ever landed (pushed and popped
3739                                    // within one frame) mounts nothing: ArkUI will fire
3740                                    // neither its area report nor its disappear. Retire the
3741                                    // pending push and wait on no acknowledgment; only a
3742                                    // LANDED page's pop blocks `ui_idle`.
3743                                    let landed =
3744                                        NAV_PENDING_PUSH.with(|s| !s.borrow_mut().remove(&key));
3745                                    if landed {
3746                                        NAV_PENDING_POP.with(|p| p.borrow_mut().insert(key));
3747                                    }
3748                                    if let Some(owner) = owner {
3749                                        crate::host_api::nav_pop(owner);
3750                                    }
3751                                }
3752                            }
3753                            NavPatch::Title(t) => {
3754                                if let Some(owner) = owner {
3755                                    crate::host_api::nav_set_title(owner, t);
3756                                }
3757                            }
3758                            NavPatch::GuardTop(on) => {
3759                                if let Some(owner) = owner {
3760                                    crate::host_api::nav_set_guard(owner, *on);
3761                                }
3762                            }
3763                            // Never arrives: this backend answers `Cap::NavRepresent =
3764                            // Emulated`. `Navigation.mode(Auto)` decides at its own threshold
3765                            // and is OBSERVED through `onNavigationModeChange`
3766                            // (`nav_presented`), never told (docs/size-classes.md).
3767                            #[expect(
3768                                clippy::match_same_arms,
3769                                reason = "each group of no-op patches keeps its own arm and the comment saying why"
3770                            )]
3771                            NavPatch::Presentation(_) => {}
3772                            // The resident-page switch (docs/navigation.md): show that
3773                            // destination and move the bar's accent to it.
3774                            NavPatch::Select(i) => suite_select(h.0 as usize, *i),
3775                            NavPatch::Reorder(order) => {
3776                                NAV_SUITES.with(|m| {
3777                                    if let Some(s) = m.borrow_mut().get_mut(&(h.0 as usize)) {
3778                                        let old = s.items.clone();
3779                                        s.items = order
3780                                            .iter()
3781                                            .filter_map(|i| old.get(*i).copied())
3782                                            .collect();
3783                                    }
3784                                });
3785                            }
3786                            // Never arrives: this backend answers `Cap::NavContentList`
3787                            // Unsupported, so the pieces layer composes the pane itself
3788                            // (docs/navigation.md).
3789                            NavPatch::ListVisible(_) | NavPatch::ListInStack(_) => {}
3790                        }
3791                        // A page search field rides whichever page now shows (docs/search.md).
3792                        if matches!(p, NavPatch::Pushed { .. } | NavPatch::Popped) {
3793                            paint_page_search(false);
3794                        }
3795                    }
3796                }
3797                kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
3798                    // Under `with_animation` a solid fill fades to the new color (§8.4); a
3799                    // gradient, or no fill, applies at once (docs/tween.md rule 8).
3800                    Some(ContainerPatch::Fill(fill)) => apply_fill(h.0, fill.as_ref(), anim),
3801                    // A reactive surface, radius, border or shadow, or a frame-relative radius
3802                    // re-resolved (docs/surfaces.md "Reactive surfaces"): the realize-time
3803                    // styling again, every field. Under an animation ArkUI interpolates the
3804                    // radius, the border and the colors.
3805                    Some(ContainerPatch::Surface(p)) => {
3806                        let (n, p) = (h.0, p.clone());
3807                        crate::anim::animate(
3808                            n,
3809                            crate::anim::Channel::Background,
3810                            anim,
3811                            move || {
3812                                apply_surface(n, &p, false);
3813                            },
3814                        );
3815                    }
3816                    None => {}
3817                },
3818                // Data-driven sidebar rebuild (docs/navigation.md): swap the rows column for a
3819                // freshly built one. Without this arm the patch was silently dropped: stale
3820                // rows kept rendering and their synthetic ids kept firing old indices (the same
3821                // bug the Android path documents fixing). Old synthetic ids are retired first so
3822                // a late tap on a recycled row cannot emit a wrong SelectionChanged.
3823                kinds::NAV_MENU => {
3824                    if let Some(NavMenuPatch::Items {
3825                        items,
3826                        icons,
3827                        tints,
3828                        badges,
3829                        badge_icons,
3830                        badge_tints,
3831                        sections,
3832                        ..
3833                    }) = patch.downcast_ref::<NavMenuPatch>()
3834                    {
3835                        let key = h.0 as usize;
3836                        let Some(menu) = NAV_MENU_IDS.with(|m| m.borrow().get(&key).copied())
3837                        else {
3838                            return;
3839                        };
3840                        MENU_ROWS.with(|m| m.borrow_mut().retain(|_, v| v.0 != menu));
3841                        // Data-driven rows: a suite's bar is those rows, so it is rebuilt from
3842                        // the same set rather than left showing the old destinations.
3843                        if let Some(host) = MENU_SUITE.with(|m| m.borrow().get(&menu.0).copied()) {
3844                            let selected = NAV_SUITES
3845                                .with(|m| m.borrow().get(&host).map_or(0, |s| s.selected));
3846                            suite_fill_bar(host, menu, items, icons, selected);
3847                        }
3848                        if let Some(old) = SCROLL_CONTENT.with(|m| m.borrow_mut().remove(&key)) {
3849                            forget_themed(old);
3850                            node::remove_child(h.0, old as Handle);
3851                            // The rows are this backend's own nodes: the whole column goes.
3852                            node::dispose_tree(old as Handle);
3853                        }
3854                        let col = build_nav_menu_rows(
3855                            menu,
3856                            items,
3857                            icons,
3858                            tints,
3859                            badges,
3860                            badge_icons,
3861                            badge_tints,
3862                            sections,
3863                        );
3864                        node::insert_child(h.0, col.0, 0);
3865                        SCROLL_CONTENT.with(|m| m.borrow_mut().insert(key, col.0 as usize));
3866                    }
3867                    // NavMenuPatch::Selected: no native highlight on the conventional-rows
3868                    // menu (realize renders no selected state either).
3869                }
3870                kinds::COVER => {
3871                    if let Some(p) = patch.downcast_ref::<CoverPatch>() {
3872                        let node_id = COVER_NODES
3873                            .with(|m| m.borrow().get(&(h.0 as usize)).copied())
3874                            .map(NodeId);
3875                        let Some(node_id) = node_id else { return };
3876                        match p {
3877                            CoverPatch::Present { background, .. } => {
3878                                let Some((root, w, hgt)) = COVER_ROOT.with(std::cell::Cell::get)
3879                                else {
3880                                    return;
3881                                };
3882                                let key = h.0 as usize;
3883                                if COVER_PRESENTED.with(|s| s.borrow().contains(&key)) {
3884                                    return; // already presented
3885                                }
3886                                let prev = COVER_PARENTS.with(|m| m.borrow().get(&key).copied());
3887                                // The cover's ground follows the appearance like any ink; the
3888                                // default is the window's own neutral pair.
3889                                match background {
3890                                    Some(c) => paint_ink(key, h.0, Paint::Background, *c),
3891                                    None => {
3892                                        themed(
3893                                            key,
3894                                            h.0,
3895                                            Paint::Background,
3896                                            0xFFFF_FFFF,
3897                                            0xFF1A_1A1C,
3898                                        );
3899                                    }
3900                                }
3901                                // Detach from the tree slot it was parked in, then top the
3902                                // cover layer at full bounds. Navigation's root page is NOT
3903                                // the window root: its pushed destinations occlude that slot.
3904                                match prev {
3905                                    Some(p) => node::remove_child(p as Handle, h.0),
3906                                    None => node::remove_child(root as Handle, h.0),
3907                                }
3908                                node::add_child(root as Handle, h.0);
3909                                let (y, hgt) = cover_frame(key, hgt);
3910                                node::set_frame(h.0, 0.0, y, w, hgt);
3911                                COVER_PARENTS.with(|m| m.borrow_mut().insert(key, root));
3912                                COVER_PRESENTED.with(|s| s.borrow_mut().insert(key));
3913                                crate::host_api::show_cover_layer(true);
3914                                // Report the content size outside this tree borrow.
3915                                post_emit(node_id, Event::FrameChanged(Size::new(w, hgt)));
3916                            }
3917                            // No interactive dismissal on this backend: nothing to disable.
3918                            CoverPatch::DismissDisabled(_) => {}
3919                            CoverPatch::Dismiss => {
3920                                let key = h.0 as usize;
3921                                if !COVER_PRESENTED.with(|s| s.borrow_mut().remove(&key)) {
3922                                    // Never presented (or already dismissed): still answer
3923                                    // the hide confirmation so the piece can dispose.
3924                                    post_emit(node_id, Event::CoverHidden);
3925                                    return;
3926                                }
3927                                let cur = COVER_PARENTS.with(|m| m.borrow_mut().remove(&key));
3928                                if let Some(p) = cur {
3929                                    node::remove_child(p as Handle, h.0);
3930                                }
3931                                crate::host_api::show_cover_layer(
3932                                    COVER_PRESENTED.with(|s| !s.borrow().is_empty()),
3933                                );
3934                                // No hide transition: the content can go immediately.
3935                                post_emit(node_id, Event::CoverHidden);
3936                            }
3937                        }
3938                    }
3939                }
3940                kinds::IMAGE => {
3941                    if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
3942                        match p {
3943                            // The recolor realize applies, for a vector or a raster
3944                            // (docs/vectors.md, docs/images.md "Tinting"). An app color
3945                            // replaces a template's themed tint.
3946                            day_spec::props::ImagePatch::Tint(Some(c)) => {
3947                                forget_paint(h.0 as usize, h.0, Paint::ImageFill);
3948                                paint_ink(h.0 as usize, h.0, Paint::ImageTint, *c);
3949                            }
3950                            // A raster goes back to its own colors. A vector keeps what it
3951                            // has, including a template's themed tint.
3952                            day_spec::props::ImagePatch::Tint(None) => {
3953                                forget_paint(h.0 as usize, h.0, Paint::ImageTint);
3954                                node::clear_raster_tint(h.0);
3955                            }
3956                            // A source swap repaints the same node (docs/images.md).
3957                            day_spec::props::ImagePatch::Source(source) => {
3958                                arkui_apply_image_source(h.0, source, None);
3959                            }
3960                        }
3961                    }
3962                }
3963                kinds::LABEL => {
3964                    if let Some(p) = patch.downcast_ref::<LabelPatch>() {
3965                        match p {
3966                            // The paragraph attributes are not applied on this toolkit yet.
3967                            LabelPatch::Paragraph(para) => {
3968                                let wraps = LABEL_PARA
3969                                    .with(|t| t.get(h.0 as usize))
3970                                    .is_none_or(|(_, wraps)| wraps);
3971                                apply_paragraph(h.0, *para, wraps);
3972                            }
3973                            LabelPatch::Text(t) => node::set_text(h.0, t),
3974                            LabelPatch::Color(c) => match c {
3975                                Some(c) => paint_ink(h.0 as usize, h.0, Paint::Font, *c),
3976                                None => {
3977                                    themed(h.0 as usize, h.0, Paint::Font, TEXT_LIGHT, TEXT_DARK);
3978                                }
3979                            },
3980                            LabelPatch::Font(f) => {
3981                                node::set_font_size(h.0, label_fp(*f));
3982                                apply_font_attrs(h.0, *f);
3983                                // The spacing and line height scale with the new size.
3984                                if let Some((para, wraps)) =
3985                                    LABEL_PARA.with(|t| t.get(h.0 as usize))
3986                                {
3987                                    apply_paragraph(h.0, para, wraps);
3988                                }
3989                            }
3990                            LabelPatch::Runs(text, runs) => set_label_runs(h.0, text, runs),
3991                        }
3992                    }
3993                }
3994                kinds::BUTTON => match patch.downcast_ref::<ButtonPatch>() {
3995                    Some(ButtonPatch::Content(c)) => {
3996                        apply_button_content(*h, &c.title, c.icon.as_ref(), c.icon_only);
3997                    }
3998                    Some(ButtonPatch::Enabled(on)) => node::set_enabled(h.0, *on),
3999                    Some(ButtonPatch::Selected(on)) => apply_button_selected(h.0, *on),
4000                    Some(ButtonPatch::Title(t)) => node::set_button_label(h.0, t),
4001                    Some(ButtonPatch::Style(s)) => apply_button_style(h.0, *s),
4002                    _ => {}
4003                },
4004                kinds::TOGGLE => match patch.downcast_ref::<TogglePatch>() {
4005                    Some(TogglePatch::On(on)) => {
4006                        // The gate (see TOGGLE_GATE): this write's echo is not the user's.
4007                        if let Some(nid) =
4008                            CTRL_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied())
4009                        {
4010                            toggle_written(nid, *on);
4011                        }
4012                        node::set_toggle(h.0, *on);
4013                    }
4014                    Some(TogglePatch::Enabled(on)) => node::set_enabled(h.0, *on),
4015                    None => {}
4016                },
4017                kinds::SLIDER => match patch.downcast_ref::<SliderPatch>() {
4018                    Some(SliderPatch::Value(v)) => {
4019                        let nid = CTRL_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied());
4020                        let (min, max) = nid
4021                            .and_then(|nid| SLIDER_RANGE.with(|m| m.borrow().get(&nid).copied()))
4022                            .unwrap_or((0.0, 1.0));
4023                        // The echo cell (see SLIDER_ECHO): the set below comes back as an
4024                        // onChange, which must not reach the app as the user's change.
4025                        if let Some(nid) = nid {
4026                            SLIDER_ECHO.with(|m| m.borrow_mut().insert(nid, *v));
4027                        }
4028                        node::set_slider(h.0, normalize(*v, min, max));
4029                    }
4030                    Some(SliderPatch::Enabled(on)) => node::set_enabled(h.0, *on),
4031                    None => {}
4032                },
4033                kinds::TEXT_FIELD => match patch.downcast_ref::<TextFieldPatch>() {
4034                    // A from_native echo would fight the user's caret: skip it (§4.4).
4035                    Some(TextFieldPatch::Text { text, from_native }) if !from_native => {
4036                        if let Some(nid) =
4037                            CTRL_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied())
4038                        {
4039                            TEXT_ECHO.with(|m| m.borrow_mut().insert(nid, text.clone()));
4040                            // The app's own write is the text a read-only field holds.
4041                            INPUT_FIELDS.with(|m| {
4042                                if let Some(f) = m.borrow_mut().get_mut(&nid)
4043                                    && f.held.is_some()
4044                                {
4045                                    f.held = Some(text.clone());
4046                                }
4047                            });
4048                        }
4049                        node::set_input_text(h.0, text);
4050                    }
4051                    Some(TextFieldPatch::Enabled(on)) => node::set_enabled(h.0, *on),
4052                    Some(TextFieldPatch::Select(sel)) => node::select_input(h.0, *sel),
4053                    _ => {}
4054                },
4055                kinds::TEXT_AREA => {
4056                    let nid = CTRL_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied());
4057                    match patch.downcast_ref::<TextAreaPatch>() {
4058                        Some(TextAreaPatch::SetText(text)) => {
4059                            if let Some(nid) = nid {
4060                                TEXT_ECHO.with(|m| m.borrow_mut().insert(nid, text.clone()));
4061                                INPUT_FIELDS.with(|m| {
4062                                    if let Some(f) = m.borrow_mut().get_mut(&nid)
4063                                        && f.held.is_some()
4064                                    {
4065                                        f.held = Some(text.clone());
4066                                    }
4067                                });
4068                            }
4069                            node::set_textarea_text(h.0, text);
4070                        }
4071                        Some(TextAreaPatch::SetEditable(on)) => {
4072                            if let Some(nid) = nid {
4073                                set_area_editable(h.0, nid, *on);
4074                            }
4075                        }
4076                        Some(TextAreaPatch::SetSelectable(on)) => {
4077                            if let Some(nid) = nid {
4078                                set_area_selectable(h.0, nid, *on);
4079                            }
4080                        }
4081                        _ => {}
4082                    }
4083                }
4084                kinds::PICKER if piece::is_piece(h) => match patch.downcast_ref::<PickerPatch>() {
4085                    Some(PickerPatch::Selected(i)) => piece::update(h, "selected", &i.to_string()),
4086                    // The Select keeps its own live choice across new options, clamped to the list;
4087                    // its width follows the new widest option (an options patch re-measures).
4088                    Some(PickerPatch::Options(opts)) => {
4089                        piece::update(h, "options", &select_props(None, opts));
4090                        resize_menu_picker(h, opts);
4091                    }
4092                    Some(PickerPatch::Enabled(on)) => set_picker_piece_enabled(h, *on),
4093                    None => {}
4094                },
4095                kinds::PICKER => match patch.downcast_ref::<PickerPatch>() {
4096                    Some(PickerPatch::Selected(i)) => {
4097                        PICKER_SELECTED.with(|m| m.insert(h.0 as usize, *i));
4098                        node::set_picker_selected(h.0, *i as u32);
4099                    }
4100                    // The wheel's whole option RANGE, re-set: the same attribute realize
4101                    // seeds. The selection rides along, clamped to the new list.
4102                    Some(PickerPatch::Options(opts)) => {
4103                        let joined = opts.join(";");
4104                        let selected = PICKER_SELECTED
4105                            .with(|m| m.get(h.0 as usize))
4106                            .unwrap_or(0)
4107                            .min(opts.len().saturating_sub(1));
4108                        node::set_picker(h.0, &joined, selected as u32);
4109                    }
4110                    Some(PickerPatch::Enabled(on)) => node::set_enabled(h.0, *on),
4111                    None => {}
4112                },
4113                kinds::PROGRESS => {
4114                    if let Some(p @ ProgressPatch::Animating(_)) =
4115                        patch.downcast_ref::<ProgressPatch>()
4116                    {
4117                        crate::controls::spinner::update(self, h, p);
4118                        return;
4119                    }
4120
4121                    if let Some(ProgressPatch::Value(Some(v))) =
4122                        patch.downcast_ref::<ProgressPatch>()
4123                    {
4124                        node::set_progress(h.0, *v);
4125                    }
4126                }
4127                kinds::LIST => match patch.downcast_ref::<ListPatch>() {
4128                    Some(ListPatch::Reload | ListPatch::Splice(_)) => {
4129                        // Deferred out of the day-core borrow: ReloadAllItems fires the
4130                        // adapter's ADD/REMOVE synchronously, and a bind pulled while the
4131                        // borrow is held SKIPS (try_with_tree) and never retries, the
4132                        // deferred-native-mutation rule (docs/tree.md M1). Coalesced: one
4133                        // change fires several watches, and adapter reload bursts drop ADDs.
4134                        let n = h.0 as usize;
4135                        let fresh = LIST_RELOAD_PENDING.with(|p| p.borrow_mut().insert(n));
4136                        if fresh {
4137                            crate::main_thread::post_local(Box::new(move || {
4138                                LIST_RELOAD_PENDING.with(|p| p.borrow_mut().remove(&n));
4139                                crate::list::reload(n as Handle);
4140                            }));
4141                        }
4142                    }
4143                    Some(p @ (ListPatch::ScrollToEnd | ListPatch::ScrollToRow(_))) => {
4144                        // Scrolling can synchronously ask the adapter to bind cells, just
4145                        // like a reload. Inside update the core tree is borrowed, so those
4146                        // binds would be skipped permanently. Queue after pending reloads
4147                        // and reject work for a disposed/replaced list at the same address.
4148                        let n = h.0 as usize;
4149                        let owner = LIST_NODE.with(|m| m.borrow().get(&n).copied());
4150                        let row = match p {
4151                            ListPatch::ScrollToRow(row) => Some(*row as u32),
4152                            _ => None,
4153                        };
4154                        if let Some(owner) = owner {
4155                            crate::list::scroll_posted();
4156                            crate::main_thread::post_local(Box::new(move || {
4157                                crate::list::scroll_taken();
4158                                if LIST_NODE.with(|m| m.borrow().get(&n).copied()) != Some(owner) {
4159                                    return;
4160                                }
4161                                match row {
4162                                    Some(row) => crate::list::scroll_to_row(n as Handle, row),
4163                                    None => crate::list::scroll_to_end(n as Handle),
4164                                }
4165                            }));
4166                        }
4167                    }
4168                    Some(ListPatch::RowSizeInvalidated { cell, height }) => {
4169                        // A content-sized row re-laid at a new height: resize its cell, posted
4170                        // out of the day-core layout pass this arrives from.
4171                        let (n, cell, height) = (h.0 as usize, *cell, *height);
4172                        crate::main_thread::post_local(Box::new(move || {
4173                            crate::list::resize_row(n as Handle, cell as Handle, height);
4174                        }));
4175                    }
4176                    Some(ListPatch::Selected(rows)) => {
4177                        // Record, then repaint the live cells; newly bound cells pick the
4178                        // state up in the adapter's add path. Paint only, no echo.
4179                        if let Some(nid) =
4180                            LIST_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied())
4181                        {
4182                            LIST_SELECTED.with(|m| {
4183                                m.borrow_mut().insert(nid, rows.iter().copied().collect());
4184                            });
4185                            crate::list::paint_selection(h.0);
4186                        }
4187                    }
4188                    Some(ListPatch::Editing(_)) | None => {}
4189                },
4190                // An external piece's own arkui renderer, if one registered for this kind. Without
4191                // this, every registered piece realized correctly and then ignored every patch:
4192                // realize and measure consulted the registry but update did not.
4193                _ => {
4194                    if let Some(update) = self.registry.get(kind).map(|r| r.update) {
4195                        update(self, h, patch);
4196                    }
4197                }
4198            }
4199        }
4200
4201        /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
4202        fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
4203            // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
4204            // the hook needs it mutably.
4205            let f = self.registry.get(kind).and_then(|r| r.release);
4206            if let Some(f) = f {
4207                f(self, h);
4208            }
4209        }
4210
4211        fn release(&mut self, h: AHandle) {
4212            clear_button_content(h);
4213            let key = h.0 as usize;
4214            BUTTON_STYLE.with(|m| m.borrow_mut().remove(&key));
4215            BUTTON_SELECTED.with(|m| m.borrow_mut().remove(&key));
4216            // One sweep drops this node's entry from every registered `SideTable`, present
4217            // and future, before the manual purges below (day_spec::sidetable; the existing
4218            // maps predate it and keep their explicit lines).
4219            day_spec::sidetable::sweep(key);
4220            forget_themed(key);
4221            // The control's echo cells go with it (a recycled address must not alias them).
4222            if let Some(nid) = CTRL_NODE.with(|m| m.borrow_mut().remove(&key)) {
4223                TEXT_ECHO.with(|m| m.borrow_mut().remove(&nid));
4224                INPUT_FIELDS.with(|m| m.borrow_mut().remove(&nid));
4225                SLIDER_ECHO.with(|m| m.borrow_mut().remove(&nid));
4226                SLIDER_RANGE.with(|m| m.borrow_mut().remove(&nid));
4227                TOGGLE_GATE.with(|m| m.borrow_mut().remove(&nid));
4228            }
4229            // A pushed page released without a Remove patch (whole-host teardown) must not
4230            // leave its re-home bookkeeping behind: a recycled node address would alias it.
4231            // The ArkTS side still holds the destination slot's keep-alive ref; drop that
4232            // too (nav_forget touches only the bookkeeping, never the content tree).
4233            if let Some(nav_key) = NAV_PUSHED.with(|m| m.borrow_mut().remove(&key)) {
4234                crate::host_api::nav_forget(nav_key);
4235            }
4236            NAV_ATTACHED.with(|v| {
4237                for pages in v.borrow_mut().values_mut() {
4238                    pages.retain(|(p, _)| *p != key);
4239                }
4240            });
4241            if let Some(owner) = NAV_HOSTS.with(|m| m.borrow_mut().remove(&key)) {
4242                PAGE_SEARCH.with(|m| m.borrow_mut().remove(&owner));
4243                NAV_ATTACHED.with(|m| m.borrow_mut().remove(&key));
4244                NAV_STACK.with(|m| m.borrow_mut().remove(&key));
4245                let pages: Vec<u64> = NAV_OWNERS.with(|m| {
4246                    let mut m = m.borrow_mut();
4247                    let pages = m
4248                        .iter()
4249                        .filter(|(_, host)| **host == key)
4250                        .map(|(page, _)| *page)
4251                        .collect();
4252                    m.retain(|_, host| *host != key);
4253                    pages
4254                });
4255                for page in pages {
4256                    NAV_PENDING_PUSH.with(|m| m.borrow_mut().remove(&page));
4257                    NAV_PENDING_POP.with(|m| m.borrow_mut().remove(&page));
4258                    NAV_EXPECT_POP.with(|m| m.borrow_mut().remove(&page));
4259                    NAV_POPPED_KEYS.with(|m| m.borrow_mut().remove(&page));
4260                }
4261            }
4262            // A cover released while presented, and a secondary window root released after
4263            // its ability went away, drop their records too (same aliasing hazard).
4264            COVER_PRESENTED.with(|s| {
4265                s.borrow_mut().remove(&key);
4266            });
4267            if COVER_NODES.with(|m| m.borrow().contains_key(&key)) {
4268                crate::host_api::show_cover_layer(COVER_PRESENTED.with(|s| !s.borrow().is_empty()));
4269            }
4270            SECONDARY.with(|s| s.borrow_mut().retain(|(_, ptr)| *ptr != key));
4271            if let Some(page) = NAV_PAGE_IDS.with(|m| m.borrow_mut().remove(&key)) {
4272                // A landed pop retains its owner until ArkTS acknowledges the transition.
4273                // Unmounted/same-frame pages will never produce that acknowledgment.
4274                if !NAV_PENDING_POP.with(|m| m.borrow().contains(&page)) {
4275                    NAV_OWNERS.with(|m| m.borrow_mut().remove(&page));
4276                    NAV_EXPECT_POP.with(|m| m.borrow_mut().remove(&page));
4277                    NAV_POPPED_KEYS.with(|m| m.borrow_mut().remove(&page));
4278                    NAV_PENDING_PUSH.with(|m| m.borrow_mut().remove(&page));
4279                }
4280            }
4281            COVER_NODES.with(|m| {
4282                m.borrow_mut().remove(&key);
4283            });
4284            COVER_PARENTS.with(|m| {
4285                m.borrow_mut().remove(&key);
4286            });
4287            TEXTAREA_LINES.with(|m| {
4288                m.borrow_mut().remove(&key);
4289            });
4290            // A host that is gone takes its suite with it: a stale suite would route the next
4291            // host at that address's children into freed nodes.
4292            if let Some(suite) = NAV_SUITES.with(|c| c.borrow_mut().remove(&key)) {
4293                // The pages area, the bar and its items are this backend's own nodes, which day
4294                // never releases: dispose them here. Day's pages come out of the pages area
4295                // first, so their own release frees them. Left attached under a container nobody
4296                // disposes, each page's whole native subtree stayed resident, and every visit to
4297                // a tabbed page (Showcase's grid, five demos deep) grew the process for good.
4298                for (page, _) in &suite.items {
4299                    node::remove_child(suite.pages.0, page.0);
4300                }
4301                for item in &suite.bar_items {
4302                    node::remove_child(suite.bar.0, item.0);
4303                    node::dispose_tree(item.0);
4304                }
4305                for part in [suite.bar, suite.pages] {
4306                    node::remove_child(h.0, part.0);
4307                    node::dispose(part.0);
4308                }
4309                MENU_SUITE.with(|m| m.borrow_mut().retain(|_, host| *host != key));
4310                SUITE_AWAITING_MENU.with(|c| {
4311                    if c.get() == Some(key) {
4312                        c.set(None);
4313                    }
4314                });
4315            }
4316            MENU_BUTTONS.with(|m| m.borrow_mut().retain(|_, button| *button != key));
4317            if let Some(nid) = TAP_HANDLES.with(|m| m.borrow_mut().remove(&key)) {
4318                TAP_NODES.with(|s| {
4319                    s.borrow_mut().remove(&nid);
4320                });
4321            }
4322            if let Some(nid) = LIST_NODE.with(|m| m.borrow_mut().remove(&key)) {
4323                LIST_SELECTED.with(|m| {
4324                    m.borrow_mut().remove(&nid);
4325                });
4326                let source = LIST_SOURCES.with(|m| m.borrow_mut().remove(&nid));
4327                // A sectioned list's pinned header is a cell outside the adapter: hand it
4328                // back so Day disposes the header copy it built there (docs/list.md
4329                // "Sections"). The node itself goes with the list (`list::forget`).
4330                if let (Some(source), Some(pin)) = (source, crate::list::pin_cell(h.0)) {
4331                    (source.release)(pin as day_spec::RawHandle);
4332                }
4333            }
4334            // A released NAV_MENU retires its rows' synthetic click ids: without this every
4335            // menu rebuild leaked its row entries for the process lifetime.
4336            let nav_menu = NAV_MENU_IDS.with(|m| m.borrow().contains_key(&key));
4337            if let Some(menu) = NAV_MENU_IDS.with(|m| m.borrow_mut().remove(&key)) {
4338                MENU_ROWS.with(|m| m.borrow_mut().retain(|_, v| v.0 != menu));
4339            }
4340            // A scroll owns its content container (realize): dispose it with the scroll.
4341            if let Some(stack) = SCROLL_CONTENT.with(|m| m.borrow_mut().remove(&key)) {
4342                forget_themed(stack);
4343                if nav_menu {
4344                    // A nav menu's content is the rows column this backend built whole.
4345                    node::remove_child(h.0, stack as Handle);
4346                    node::dispose_tree(stack as Handle);
4347                } else {
4348                    // An ordinary scroll's content holds day's nodes, which day releases itself.
4349                    node::dispose(stack as Handle);
4350                }
4351            }
4352            // An ArkTS-built piece node belongs to its BuilderNode: detach it from the native
4353            // wrapper, ask ArkTS to release it, and dispose only the wrapper; a native dispose
4354            // of the FrameNode would free a node ArkTS still holds.
4355            if let Some((id, inner)) = PIECE_NODES.with(|m| m.borrow_mut().remove(&key)) {
4356                MENU_PICKER_SIZE.with(|m| m.borrow_mut().remove(&key));
4357                PIECE_FRAME.with(|m| m.borrow_mut().remove(&key));
4358                node::remove_child(h.0, inner as Handle);
4359                crate::host_api::piece_dispose(id);
4360            }
4361            node::dispose(h.0);
4362        }
4363
4364        fn insert(&mut self, parent: &AHandle, child: &AHandle, index: usize) {
4365            // A suite's own pages. The one at index 0 is the SIDEBAR page, whose rows became the
4366            // bar: it is kept so nothing downstream has to special-case a missing page, but never
4367            // shown; drawing the rows again as a list would be the same navigation twice.
4368            let mut report_page = None;
4369            let into_suite = NAV_SUITES.with(|c| {
4370                let mut c = c.borrow_mut();
4371                let Some(suite) = c.get_mut(&(parent.0 as usize)) else {
4372                    return false;
4373                };
4374                let page = suite.page_size;
4375                node::insert_child(suite.pages.0, child.0, index as i32);
4376                node::set_size(child.0, page.width, page.height);
4377                if index == 0 {
4378                    node::set_visibility(child.0, false);
4379                } else {
4380                    let id = NodeId(
4381                        NAV_PAGE_IDS
4382                            .with(|m| m.borrow().get(&(child.0 as usize)).copied())
4383                            .unwrap_or(0),
4384                    );
4385                    let position = (index - 1).min(suite.items.len());
4386                    suite.items.insert(position, (*child, id));
4387                    node::set_visibility(child.0, position == suite.selected);
4388                    report_page = Some(id);
4389                }
4390                true
4391            });
4392            if into_suite {
4393                if let Some(id) = report_page {
4394                    let host = parent.0 as usize;
4395                    // The host can be laid out before any pages join it. Report a new
4396                    // page's usable bounds after its FrameChanged listener is installed;
4397                    // otherwise NavLayout keeps the full host-height fallback forever.
4398                    // Read the current size when delivered: a resize/removal may intervene.
4399                    crate::main_thread::post_local(Box::new(move || {
4400                        let size = NAV_SUITES.with(|m| {
4401                            let m = m.borrow();
4402                            m.get(&host)
4403                                .filter(|s| s.items.iter().any(|(_, page)| *page == id))
4404                                .map(|s| s.page_size)
4405                        });
4406                        if let Some(size) = size.filter(|s| s.width > 0.0 && s.height > 0.0) {
4407                            emit(id, Event::FrameChanged(size));
4408                        }
4409                    }));
4410                }
4411                return;
4412            }
4413            // Root and pushed pages belong to this host's slots, never to a window singleton.
4414            let owner = NAV_HOSTS.with(|m| m.borrow().get(&(parent.0 as usize)).copied());
4415            if let Some(owner) = owner
4416                && let Some(id) =
4417                    NAV_PAGE_IDS.with(|m| m.borrow().get(&(child.0 as usize)).copied())
4418            {
4419                NAV_OWNERS.with(|m| m.borrow_mut().insert(id, parent.0 as usize));
4420                if index == 0 {
4421                    if crate::host_api::nav_push(owner, child.0, id, "", false) == 0 {
4422                        NAV_PUSHED.with(|m| m.borrow_mut().insert(child.0 as usize, id));
4423                    }
4424                } else {
4425                    NAV_ATTACHED.with(|v| {
4426                        v.borrow_mut()
4427                            .entry(parent.0 as usize)
4428                            .or_default()
4429                            .push((child.0 as usize, id));
4430                    });
4431                }
4432                return;
4433            }
4434            // A scroll's day children live in its content container (see [`SCROLL_CONTENT`]).
4435            let native_parent = SCROLL_CONTENT
4436                .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
4437                .unwrap_or(parent.0 as usize);
4438            // A cover's current parent starts as its tree slot (Present re-homes it).
4439            if COVER_NODES.with(|m| m.borrow().contains_key(&(child.0 as usize))) {
4440                COVER_PARENTS.with(|m| m.borrow_mut().insert(child.0 as usize, native_parent));
4441            }
4442            node::insert_child(native_parent as Handle, child.0, index as i32);
4443        }
4444
4445        fn remove(&mut self, parent: &AHandle, child: &AHandle) {
4446            let cp = child.0 as usize;
4447            if NAV_SUITES.with(|m| {
4448                let mut m = m.borrow_mut();
4449                let Some(suite) = m.get_mut(&(parent.0 as usize)) else {
4450                    return false;
4451                };
4452                node::remove_child(suite.pages.0, child.0);
4453                suite.items.retain(|(page, _)| page.0 != child.0);
4454                true
4455            }) {
4456                return;
4457            }
4458            NAV_ATTACHED.with(|v| {
4459                for pages in v.borrow_mut().values_mut() {
4460                    pages.retain(|(p, _)| *p != cp);
4461                }
4462            });
4463            // A presented cover lives under the window root, not its tree parent.
4464            if let Some(cur) = COVER_PARENTS.with(|m| m.borrow_mut().remove(&cp)) {
4465                node::remove_child(cur as Handle, child.0);
4466                return;
4467            }
4468            if let Some(key) = NAV_PUSHED.with(|m| m.borrow_mut().remove(&cp)) {
4469                // The page lives in an ArkTS NodeContent (NavDestination), not under the host.
4470                // Detach it only while that destination is still alive (a Day-initiated pop:
4471                // the Remove patch lands before the pop transition finishes). Once the ArkTS
4472                // side reported the disappearance (native back: the destination and its
4473                // content tree are already torn down), touching the slot would walk freed
4474                // FrameNodes: drop the bookkeeping instead.
4475                if NAV_POPPED_KEYS.with(|s| s.borrow_mut().remove(&key)) {
4476                    crate::host_api::nav_forget(key);
4477                } else {
4478                    crate::host_api::nav_remove(key, child.0);
4479                }
4480                return;
4481            }
4482            // Mirror `insert`'s re-routing for scroll children (see [`SCROLL_CONTENT`]).
4483            let native_parent = SCROLL_CONTENT
4484                .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
4485                .unwrap_or(parent.0 as usize);
4486            node::remove_child(native_parent as Handle, child.0);
4487        }
4488
4489        fn move_child(&mut self, parent: &AHandle, child: &AHandle, to: usize) {
4490            self.remove(parent, child);
4491            self.insert(parent, child, to);
4492        }
4493
4494        fn measure(&mut self, h: &AHandle, kind: PieceKind, p: Proposal) -> Size {
4495            match kind {
4496                kinds::LABEL => {
4497                    // A label measures on a fresh copy: ArkUI answers a Text whose content
4498                    // changed with the old content's size (see node::measure_label).
4499                    let (w, hh) =
4500                        node::measure_label(h.0, p.width.unwrap_or(-1.0), p.height.unwrap_or(-1.0));
4501                    Size::new(w, hh)
4502                }
4503                kinds::BUTTON => {
4504                    // An icon button is sized from its content Row (see `apply_button_content`),
4505                    // a title button from a fresh copy (see node::measure_button).
4506                    let content = BUTTON_CHILDREN
4507                        .with(|m| {
4508                            m.borrow()
4509                                .get(&(h.0 as usize))
4510                                .and_then(|c| c.first().copied())
4511                        })
4512                        .map_or(std::ptr::null_mut(), |row| row.0);
4513                    let (w, hh) = node::measure_button(
4514                        h.0,
4515                        content,
4516                        p.width.unwrap_or(-1.0),
4517                        p.height.unwrap_or(-1.0),
4518                    );
4519                    Size::new(w, hh)
4520                }
4521                kinds::TEXT_FIELD | kinds::SLIDER => Size::new(p.width.unwrap_or(200.0), 40.0),
4522                kinds::TEXT_AREA => {
4523                    // Grow with content between the min/max line band (line ≈ 24 vp + padding).
4524                    let (min_lines, max_lines) = TEXTAREA_LINES
4525                        .with(|m| m.borrow().get(&(h.0 as usize)).copied())
4526                        .unwrap_or((1, 0));
4527                    let line = 24.0;
4528                    let min_h = f64::from(min_lines) * line + 16.0;
4529                    let nat = node::measure(h.0, p.width.unwrap_or(0.0), 0.0).1;
4530                    let capped = if max_lines == 0 {
4531                        nat.max(min_h)
4532                    } else {
4533                        nat.clamp(min_h, f64::from(max_lines) * line + 16.0)
4534                    };
4535                    Size::new(p.width.unwrap_or(200.0), capped)
4536                }
4537                // The Select button's own size (a wrapper measures its ArkTS child), with a floor
4538                // for a first measure before the component has laid out.
4539                kinds::PICKER if piece::is_piece(h) => MENU_PICKER_SIZE
4540                    .with(|m| m.borrow().get(&(h.0 as usize)).map(|(_, size)| *size))
4541                    .unwrap_or(Size::new(120.0, 40.0)),
4542                kinds::PICKER => Size::new(p.width.unwrap_or(200.0), 200.0),
4543                kinds::TOGGLE => Size::new(50.0, 30.0),
4544                kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
4545                kinds::PROGRESS => match crate::controls::spinner::side(h) {
4546                    Some(side) => Size::new(side, side),
4547                    None => Size::new(p.width.unwrap_or(40.0), p.height.unwrap_or(20.0)),
4548                },
4549                // These fill their container (host owns scroll/paging; content is laid out inside).
4550                kinds::NAV_MENU => Size::new(p.width.unwrap_or(240.0), p.height.unwrap_or(400.0)),
4551                kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
4552                _ => {
4553                    if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
4554                        return measure(self, h, p);
4555                    }
4556                    Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
4557                }
4558            }
4559        }
4560
4561        fn set_selectable(&mut self, h: &AHandle, selectable: bool) -> Option<AHandle> {
4562            // NODE_TEXT_COPY_OPTION on the Text node; a non-text node ignores it (docs/text.md).
4563            node::label_set_selectable(h.0, selectable);
4564            None
4565        }
4566
4567        fn set_input_traits(
4568            &mut self,
4569            h: &AHandle,
4570            traits: &day_spec::InputTraits,
4571        ) -> Option<AHandle> {
4572            // Attribute flips on the one TextInput node, so there is never a replacement.
4573            let nid = CTRL_NODE.with(|m| m.borrow().get(&(h.0 as usize)).copied())?;
4574            let watched = INPUT_FIELDS.with(|m| m.borrow().get(&nid).map(|f| f.watched))?;
4575            node::set_input_traits(h.0, traits);
4576            // Read-only (see `InputField`): the first time a field asks for it, start
4577            // answering its edits; from then on the flag alone decides the answer.
4578            if traits.read_only && !watched {
4579                node::watch_input_edits(h.0, nid);
4580            }
4581            let held = traits.read_only.then(|| node::input_text(h.0));
4582            INPUT_FIELDS.with(|m| {
4583                if let Some(f) = m.borrow_mut().get_mut(&nid) {
4584                    f.watched |= traits.read_only;
4585                    f.held = held;
4586                }
4587            });
4588            None
4589        }
4590
4591        /// Derived from the node's font size (docs/baseline.md): the ArkUI C API publishes no
4592        /// baseline, so `Cap::BaselineAlignment` is `Emulated` here.
4593        fn first_baseline(&mut self, h: &AHandle, kind: PieceKind, size: Size) -> Option<f64> {
4594            if !day_spec::kind_has_baseline(kind) {
4595                return None;
4596            }
4597            node::baseline(h.0, size.height)
4598        }
4599
4600        fn set_frame(&mut self, h: &AHandle, frame: Rect, anim: Option<&AnimSpec>) {
4601            // The suite divides its own frame between the pages area and the bar, then tells each
4602            // page how much room it has: day-core sees one host node and gives it one frame.
4603            if NAV_SUITES.with(|c| c.borrow().contains_key(&(h.0 as usize))) {
4604                node::set_frame(
4605                    h.0,
4606                    frame.origin.x,
4607                    frame.origin.y,
4608                    frame.size.width,
4609                    frame.size.height,
4610                );
4611                suite_layout(h.0 as usize, frame.size);
4612                return;
4613            }
4614            // All navigation pages have native-owned frames, including resident tab
4615            // pages. Day's initial fallback must not overwrite the suite's allocation
4616            // and extend a scroll viewport underneath the tab bar.
4617            if NAV_PAGE_IDS.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
4618                return;
4619            }
4620            // A cover's frame is native-owned: full window while presented, parked otherwise.
4621            if COVER_NODES.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
4622                return;
4623            }
4624            // Under an animation ArkUI interpolates the position and size (docs/tween.md).
4625            let n = h.0;
4626            crate::anim::animate(n, crate::anim::Channel::Frame, anim, move || {
4627                node::set_frame(
4628                    n,
4629                    frame.origin.x,
4630                    frame.origin.y,
4631                    frame.size.width,
4632                    frame.size.height,
4633                );
4634            });
4635            // A hit slop's response region is a percentage of the node's size.
4636            crate::gesture::resized(h.0, frame.size.width, frame.size.height);
4637            // A surface's gradient follows its frame (docs/surfaces.md).
4638            let resized = SURFACE_GRADIENTS.with(|m| {
4639                m.with(h.0 as usize, |(g, size)| {
4640                    (*size != frame.size).then(|| {
4641                        *size = frame.size;
4642                        g.clone()
4643                    })
4644                })
4645                .flatten()
4646            });
4647            if let Some(g) = resized {
4648                apply_surface_gradient(h.0, &g, frame.size);
4649            }
4650            // An ArkTS piece is built detached, so a percentage size inside it resolves against
4651            // the window rather than this wrapper: tell it the size it was laid out at, when that
4652            // changes, as `day.frame` "<w>,<h>" (vp). A component that fills its frame sizes
4653            // itself from that; one that doesn't ignores the command.
4654            if piece::is_piece(h) {
4655                let key = h.0 as usize;
4656                let changed = PIECE_FRAME.with(|m| m.borrow_mut().insert(key, frame.size))
4657                    != Some(frame.size);
4658                if changed {
4659                    let size = format!("{},{}", frame.size.width, frame.size.height);
4660                    piece::update(h, "day.frame", &size);
4661                }
4662            }
4663        }
4664
4665        fn set_opacity(&mut self, h: &AHandle, opacity: f64, anim: Option<&AnimSpec>) {
4666            let n = h.0;
4667            crate::anim::animate(n, crate::anim::Channel::Opacity, anim, move || {
4668                node::set_opacity(n, opacity);
4669            });
4670        }
4671
4672        fn set_transform(
4673            &mut self,
4674            h: &AHandle,
4675            t: day_spec::Transform,
4676            _size: Size,
4677            anim: Option<&AnimSpec>,
4678        ) {
4679            // ArkUI takes the pivot as a fraction of the node's own size, so the laid-out size
4680            // isn't needed. The pivot is not animated: only where the node moves to is.
4681            let n = h.0;
4682            node::set_transform_center(n, t.anchor_x, t.anchor_y);
4683            crate::anim::animate(n, crate::anim::Channel::Transform, anim, move || {
4684                node::set_transform(n, t.tx, t.ty, t.sx, t.sy, t.rotation.degrees());
4685            });
4686        }
4687
4688        fn set_scroll_content(&mut self, h: &AHandle, content: Size) {
4689            // Size the backend-owned container (see [`SCROLL_CONTENT`]) so ArkUI's Scroll
4690            // measures the real extent; that extent is what makes touch and programmatic
4691            // offsets take effect. Size without position: `NODE_POSITION` removes a child
4692            // from layout flow, and the Scroll's measure ignores positioned children.
4693            if let Some(stack) = SCROLL_CONTENT.with(|m| m.borrow().get(&(h.0 as usize)).copied()) {
4694                node::set_size(stack as Handle, content.width, content.height);
4695            }
4696        }
4697
4698        /// A HarmonyOS list item: 12vp sides, 48vp tall for a single line.
4699        fn list_row_metrics(&mut self, _h: &AHandle) -> day_spec::RowMetrics {
4700            day_spec::RowMetrics {
4701                insets: day_spec::Insets {
4702                    top: 8.0,
4703                    leading: 12.0,
4704                    bottom: 8.0,
4705                    trailing: 12.0,
4706                },
4707                min_height: 48.0,
4708            }
4709        }
4710
4711        fn scroll_offset(&mut self, h: &AHandle) -> Point {
4712            let (x, y) = node::scroll_offset(h.0);
4713            Point::new(x, y)
4714        }
4715
4716        fn list_scroll(&mut self, h: &AHandle, to: day_spec::ListScroll) -> bool {
4717            // Posted like the row patches: scrolling binds cells, which a bind under the
4718            // day-core borrow would skip; queued behind any pending reload.
4719            let n = h.0 as usize;
4720            let Some(owner) = LIST_NODE.with(|m| m.borrow().get(&n).copied()) else {
4721                return false;
4722            };
4723            crate::list::scroll_posted();
4724            crate::main_thread::post_local(Box::new(move || {
4725                crate::list::scroll_taken();
4726                if LIST_NODE.with(|m| m.borrow().get(&n).copied()) == Some(owner) {
4727                    crate::list::scroll_aligned(n as Handle, to.row, to.align, to.animated);
4728                }
4729            }));
4730            true
4731        }
4732
4733        fn scroll_to(&mut self, h: &AHandle, target: Rect, animated: bool) {
4734            // The node module owns the minimal-reveal math (it can read the offset + size).
4735            node::scroll_to_rect(
4736                h.0,
4737                target.origin.x as f32,
4738                target.origin.y as f32,
4739                target.size.width as f32,
4740                target.size.height as f32,
4741                animated,
4742            );
4743        }
4744
4745        fn focus(&mut self, h: &AHandle, _node: NodeId, focused: bool) {
4746            // The UI context's focus is cleared only while this node still owns it, and typed
4747            // non-focusable errors are swallowed: no event, and the signal snaps back.
4748            node::focus(h.0, focused);
4749        }
4750
4751        fn set_event_sink(&mut self, sink: EventSink) {
4752            SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
4753        }
4754
4755        fn set_a11y(&mut self, h: &AHandle, a11y: &A11yProps) {
4756            // Every member is an ArkUI accessibility attribute (node.rs says which).
4757            node::set_a11y(h.0, a11y);
4758        }
4759
4760        fn read_native(&self, h: &AHandle) -> day_spec::NativeSnapshot {
4761            read_native(h.0)
4762        }
4763
4764        fn announce(&mut self, text: &str, urgent: bool) {
4765            // The accessibility kit's announcement event (src/host.rs); nothing when the ArkTS
4766            // arm is not staged, which is also what `Cap::Announce` reports.
4767            crate::host::announce(text, urgent);
4768        }
4769
4770        fn set_button_menu(&mut self, h: &AHandle, node: NodeId, _f: day_spec::ContextMenuFn) {
4771            // The press arrives in `on_event_inner`, which reports the summon; the provider
4772            // stays with day-pieces' composed presenter, which asks it then.
4773            MENU_BUTTONS.with(|m| m.borrow_mut().insert(node.0, h.0 as usize));
4774        }
4775
4776        fn enable_gesture(&mut self, h: &AHandle, node_id: NodeId, kind: GestureKind) {
4777            // Tap is a NODE_ON_CLICK that emits `Event::Tap` (tracked in TAP_NODES so the shared
4778            // click receiver knows to send Tap, not Pressed). Drag is a native pan recognizer
4779            // (docs/shapes.md) whose phases arrive on the shared gesture wire.
4780            match kind {
4781                GestureKind::Tap => {
4782                    TAP_NODES.with(|s| s.borrow_mut().insert(node_id.0));
4783                    TAP_HANDLES.with(|m| m.borrow_mut().insert(h.0 as usize, node_id.0));
4784                    node::register_event(h.0, node::EV_CLICK, node_id.0);
4785                    // With a double tap on the node too, its single taps move to a group.
4786                    crate::gesture::enable_tap(h.0, node_id.0, false);
4787                }
4788                GestureKind::Drag => crate::gesture::enable_pan(h.0, node_id.0),
4789                GestureKind::LongPress => crate::gesture::enable_long_press(h.0, node_id.0),
4790                // ArkUI's two-tap recognizer (docs/gestures.md "Double tap").
4791                GestureKind::DoubleTap => crate::gesture::enable_tap(h.0, node_id.0, true),
4792                // Both observe the node's touch stream without consuming it.
4793                GestureKind::Press => crate::gesture::enable_touch(h.0, node_id.0, true),
4794                GestureKind::Touches => crate::gesture::enable_touch(h.0, node_id.0, false),
4795                // Two-finger recognizers plus the axis events of a wheel or a touchpad
4796                // (docs/canvas.md "Zoom and pan").
4797                GestureKind::Pinch => crate::gesture::enable_pinch(h.0, node_id.0),
4798                GestureKind::Rotate => crate::gesture::enable_rotation(h.0, node_id.0),
4799                GestureKind::Pan => crate::gesture::enable_viewport_pan(h.0, node_id.0),
4800                // Hover is deliberately unwired here (docs/canvas.md "Interaction"): the C node
4801                // API's `NODE_ON_HOVER` reports only entered/exited with no coordinates, and the
4802                // contract is a POINT. `NODE_ON_MOUSE` carries one, but this is the one target
4803                // nothing here can run, and a HarmonyOS phone has no pointer to hover with, so
4804                // it degrades to no gesture rather than to a guessed position.
4805                GestureKind::Hover => {}
4806            }
4807        }
4808
4809        /// Every kind but hover is ArkUI's own: the long-press and two-tap recognizers, and the
4810        /// touch stream for presses and contacts (docs/gestures.md "Recognizers"). Hover is
4811        /// unwired (see `enable_gesture`), so it never fires.
4812        fn gesture_support(&self, kind: GestureKind) -> Support {
4813            match kind {
4814                GestureKind::Hover => Support::Unsupported,
4815                _ => Support::Native,
4816            }
4817        }
4818
4819        fn set_hit_slop(&mut self, h: &AHandle, _node: NodeId, slop: day_spec::Insets) {
4820            // The response region (docs/gestures.md "Hit slop"); ArkUI's parent hit test still
4821            // stops at the parent's own bounds.
4822            crate::gesture::set_hit_slop(h.0, slop);
4823        }
4824
4825        fn set_drag_axis(&mut self, h: &AHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
4826            crate::gesture::set_drag_axis(h.0, axis);
4827        }
4828
4829        fn text_scale(&mut self, _style: Font) -> f64 {
4830            // One global factor (the configuration's `fontSizeScale`), which ArkUI's fp sizes
4831            // already apply.
4832            crate::host::font_scale()
4833        }
4834
4835        fn set_layout_direction(
4836            &mut self,
4837            h: &AHandle,
4838            kind: PieceKind,
4839            direction: day_spec::LayoutDirection,
4840        ) {
4841            // Leaves only: on a container NODE_DIRECTION would also mirror the children Day
4842            // placed itself.
4843            if matches!(
4844                kind,
4845                kinds::LABEL
4846                    | kinds::TEXT_FIELD
4847                    | kinds::TEXT_AREA
4848                    | kinds::BUTTON
4849                    | kinds::TOGGLE
4850                    | kinds::SLIDER
4851                    | kinds::PICKER
4852                    | kinds::PROGRESS
4853            ) {
4854                node::set_direction(h.0, direction == day_spec::LayoutDirection::Rtl);
4855            }
4856        }
4857
4858        fn set_subtree_enabled(&mut self, h: &AHandle, _node: NodeId, enabled: bool) {
4859            // `NODE_ENABLED` on the container: ArkUI stops input to it and its descendants and
4860            // reports it disabled. Counted, so a node under two disabled roots stays disabled
4861            // until both are enabled again.
4862            let key = h.0 as usize;
4863            let depth = SUBTREE_DISABLED.with(|t| {
4864                let depth = t.get(key).unwrap_or(0);
4865                let depth = if enabled {
4866                    depth.saturating_sub(1)
4867                } else {
4868                    depth + 1
4869                };
4870                if depth == 0 {
4871                    let _ = t.remove(key);
4872                } else {
4873                    let _ = t.insert(key, depth);
4874                }
4875                depth
4876            });
4877            if !enabled {
4878                // Focus inside the subtree is resigned with it.
4879                node::resign_focus_within(h.0);
4880            }
4881            node::set_enabled(h.0, depth == 0);
4882        }
4883
4884        fn set_focusable(&mut self, h: &AHandle, node: NodeId, focusable: bool) {
4885            if !focusable {
4886                return;
4887            }
4888            if crate::canvas::is_canvas(h.0) {
4889                // A canvas keeps focus in its own focus button (canvas.rs), which reports focus
4890                // and keys already; it takes touches now, and focus from them.
4891                crate::canvas::make_focusable(h.0);
4892            } else {
4893                // Joins the focus order, takes focus on a touch before its recognizers see the
4894                // press, reports focus both ways and hears keys while focused (docs/focus.md).
4895                node::make_focusable(h.0, node.0);
4896            }
4897        }
4898
4899        fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool {
4900            lifecycle_supported(phase)
4901        }
4902
4903        fn request_frame(
4904            &mut self,
4905            host: &AHandle,
4906            cb: day_spec::FrameCallback,
4907        ) -> day_spec::CancelFrame {
4908            fn fire(token: u64, timestamp: f64) {
4909                day_core::frame::native::deliver(token, day_spec::FrameStamp::new(timestamp));
4910            }
4911            let token = day_core::frame::native::register(cb);
4912            if !crate::vsync::request_frame(host.0 as usize, token, fire) {
4913                day_core::frame::native::cancel(token);
4914                log::error!("NativeVSync frame request failed");
4915            }
4916            Box::new(move || {
4917                day_core::frame::native::cancel(token);
4918                crate::vsync::cancel_frame(token);
4919            })
4920        }
4921
4922        fn replay(&mut self, h: &AHandle, ops: &[DrawOp], _size: Size) {
4923            ensure_canvas_fonts();
4924            // Encode the display list the shared way (day-toolkit-material uses the same encoder) and hand
4925            // it to the custom node; its on-draw callback replays it with OH_Drawing (§11).
4926            let (nums, texts) = day_spec::encode_ops(ops);
4927            crate::canvas::set_ops(h.0, &nums, &texts);
4928        }
4929
4930        fn adopt(&mut self, raw: day_spec::RawHandle) -> AHandle {
4931            // A recycling LIST cell's inner Stack, created natively and handed back through the
4932            // adapter's bind callback: day mounts + rebinds the row's content into it.
4933            AHandle(raw.cast())
4934        }
4935
4936        fn attach_list(&mut self, host: &AHandle, source: day_spec::ListSource) {
4937            // A list whose app observes the viewport reports it whole (docs/list.md), and never
4938            // the first-row-only report, which would overwrite it with a one-row range.
4939            if source.viewport.is_some() {
4940                crate::list::observe_viewport(host.0);
4941            } else if let Some(report) = &source.first_visible {
4942                report(0);
4943            }
4944            // A list that follows its end hears which scrolls the reader starts.
4945            if source.reader_scroll.is_some() {
4946                crate::list::observe_reader(host.0);
4947            }
4948            if let Some(nid) = LIST_NODE.with(|m| m.borrow().get(&(host.0 as usize)).copied()) {
4949                LIST_SOURCES.with(|m| m.borrow_mut().insert(nid, source));
4950            }
4951            crate::list::reload(host.0);
4952        }
4953
4954        /// `OH_Drawing_FontMgr` families and faces (docs/fonts.md).
4955        fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
4956            let Some(text) = crate::fonts::families_text() else {
4957                return Vec::new();
4958            };
4959            let mut list = day_spec::parse_font_list(&text);
4960            // The bundled families the ability registered from `day/fonts.json`
4961            // (`[{"family": …, "file": …}]`): one Regular face each, appended when the
4962            // manager's own list did not report them.
4963            if let Some(res) = open_resource("fonts.json") {
4964                let json = String::from_utf8_lossy(res.as_slice()).into_owned();
4965                for family in manifest_families(&json) {
4966                    if !list.iter().any(|f| f.family.eq_ignore_ascii_case(&family)) {
4967                        list.push(day_spec::FontFamilyInfo {
4968                            family,
4969                            faces: vec![day_spec::FontFace {
4970                                name: "Regular".to_string(),
4971                                weight: day_spec::FontWeight::Regular,
4972                                italic: false,
4973                            }],
4974                        });
4975                    }
4976                }
4977            }
4978            list
4979        }
4980
4981        /// `OH_Drawing_FontMeasureText` + the font metrics of the face the canvas draws with
4982        /// (docs/fonts.md).
4983        fn measure_text(
4984            &mut self,
4985            text: &str,
4986            size: f64,
4987            font: &day_spec::CanvasFont,
4988        ) -> Option<day_spec::TextMetrics> {
4989            ensure_canvas_fonts();
4990            let out = crate::fonts::measure_text(
4991                text,
4992                size,
4993                i32::from(font.css_weight()),
4994                font.italic,
4995                font.family_str(),
4996            );
4997            Some(day_spec::TextMetrics::from_slots(&out))
4998        }
4999
5000        /// Decode bytes with `OH_ImageSourceNative` (docs/images.md), which reads every container
5001        /// the platform's image framework knows.
5002        fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
5003            let event = match crate::images::decode(id.0, bytes) {
5004                Some((w, h, has_alpha)) => {
5005                    let info = day_spec::BitmapInfo {
5006                        pixels: Size::new(w, h),
5007                        // Decoded bytes carry no density: a PNG is simply its pixels.
5008                        scale: 1.0,
5009                        format: day_spec::ImageFormat::sniff(bytes),
5010                        // Read from the pixelmap's alpha type, not inferred from the container.
5011                        has_alpha,
5012                    };
5013                    BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5014                    Event::ImageDecoded {
5015                        req,
5016                        result: Ok(info),
5017                    }
5018                }
5019                None => Event::ImageDecoded {
5020                    req,
5021                    result: Err(day_spec::ImageError::Decode),
5022                },
5023            };
5024            emit(day_spec::WINDOW_NODE, event);
5025        }
5026
5027        fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
5028            BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
5029        }
5030
5031        /// Replay a drawing into an offscreen pixelmap (docs/canvas.md "Exporting"): a CPU
5032        /// `OH_Drawing_Bitmap` under the canvas node's own painter, kept in the pixelmap registry
5033        /// a decode fills, so the image piece, `DrawOp::Image` and encoding take it as they are.
5034        fn render_bitmap(
5035            &mut self,
5036            req: u64,
5037            id: day_spec::BitmapId,
5038            ops: &[DrawOp],
5039            size: Size,
5040            scale: f64,
5041        ) {
5042            ensure_canvas_fonts();
5043            let (pw, ph) = day_spec::export_pixels(size, scale);
5044            let (nums, texts) = day_spec::encode_ops(ops);
5045            let result = match crate::canvas::render_bitmap(nums, texts, pw, ph, scale) {
5046                Ok(pm) => {
5047                    crate::images::insert(id.0, pm);
5048                    let info = day_spec::BitmapInfo {
5049                        pixels: Size::new(f64::from(pw), f64::from(ph)),
5050                        scale,
5051                        format: None,
5052                        has_alpha: true,
5053                    };
5054                    BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5055                    Ok(info)
5056                }
5057                Err(why) => Err(day_spec::ExportError::Failed(why)),
5058            };
5059            emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
5060        }
5061
5062        fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
5063            let result = encode_bitmap(id, spec);
5064            emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
5065        }
5066
5067        /// What the image packer WRITES. The platform READS more, and the asymmetry is its own,
5068        /// which is why this duty exists rather than letting `Cap::ImageEncode` imply symmetry.
5069        fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
5070            use day_spec::ImageFormat::{Jpeg, Png};
5071            vec![Png, Jpeg]
5072        }
5073
5074        fn release_image(&mut self, id: day_spec::BitmapId) {
5075            BITMAP_INFO.with(|m| {
5076                m.borrow_mut().remove(&id.0);
5077            });
5078            crate::images::release(id.0);
5079        }
5080
5081        /// In-process capture of the window root (docs/window-image.md). `hdc shell
5082        /// snapshot_display` remains what a dayscript screenshot uses on a device (it is the
5083        /// whole display, including the system status bar this cannot see), but the app itself
5084        /// needs an answer that does not shell out, and this is it.
5085        fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
5086            let (root, _, _) = ROOT_KEEP
5087                .with(std::cell::Cell::get)
5088                .ok_or("no window root to capture")?;
5089            crate::images::snapshot_png(root as Handle)
5090                .ok_or_else(|| "the node has no snapshot".into())
5091        }
5092
5093        /// The color mode resolved at startup (`DAY_THEME` override, else the host-reported
5094        /// system mode): the same flag every neutral day-toolkit-arkui paint branches on.
5095        fn dark_mode(&mut self) -> bool {
5096            IS_DARK.with(std::cell::Cell::get)
5097        }
5098
5099        /// The system theme's `sys.color` resource for `role` in the current color mode
5100        /// (docs/color.md), or Day's own pair for a role the theme has no color for (success,
5101        /// warning) and wherever the ArkTS arm is not staged.
5102        fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
5103            palette_now().color(role)
5104        }
5105
5106        /// The settings data's animation duration scale at zero (docs/accessibility.md), read
5107        /// through the ArkTS arm in src/host.rs; false where the arm is not staged, which is
5108        /// also what `Cap::ReduceMotion` reports.
5109        fn reduce_motion(&mut self) -> bool {
5110            crate::host::reduce_motion()
5111        }
5112
5113        /// The application context's color mode (docs/settings.md). ArkTS components and
5114        /// the C nodes' theme colors restyle in place, and this backend repaints its own neutral
5115        /// paints (see [`themed`]). A return to the system mode has no answer until the
5116        /// environment callback `init` subscribed reports the mode it resolved to.
5117        fn set_appearance(&mut self, dark: Option<bool>) {
5118            crate::host::set_color_mode(dark);
5119            // An override repaints now (day-core reads `dark_mode()` right after this returns);
5120            // the environment callback that follows then finds nothing changed.
5121            if let Some(dark) = dark {
5122                repaint_themed(dark, false);
5123            }
5124        }
5125
5126        /// `NotificationKit`'s `setBadgeNumber` (docs/badge.md): a count, which the launcher
5127        /// draws on the icon; text and a bare dot have no HarmonyOS form.
5128        fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
5129            match badge {
5130                day_spec::AppBadge::None => crate::host::set_badge(0),
5131                day_spec::AppBadge::Count(n) => crate::host::set_badge(*n),
5132                day_spec::AppBadge::Text(_) | day_spec::AppBadge::Dot => {}
5133            }
5134        }
5135
5136        /// Whether nav transitions have settled: dayscript screenshots poll this, so a shot
5137        /// taken right after a section switch waits for the pushed destination's first area
5138        /// report (content laid out) and for Day-initiated pops to be acknowledged.
5139        fn prepare_snapshot(
5140            &mut self,
5141            host: Option<&Self::Handle>,
5142            revision: u32,
5143        ) -> Result<day_spec::capture::Readiness, String> {
5144            let window = match host {
5145                None => 0,
5146                Some(host) => SECONDARY
5147                    .with(|s| {
5148                        s.borrow()
5149                            .iter()
5150                            .find(|(_, ptr)| *ptr == host.0 as usize)
5151                            .map(|(n, _)| *n)
5152                    })
5153                    .ok_or("capture window is gone")?,
5154            };
5155            crate::host_api::prepare_capture(revision, window)
5156        }
5157
5158        /// Armed, the entry page's `onBackPress` hands a back Navigation did not pop to the
5159        /// app's handlers ([`app_back_requested`]).
5160        fn set_system_back(&mut self, armed: bool) {
5161            SYSTEM_BACK.with(|b| b.set(armed));
5162        }
5163
5164        /// dayscript's `nav_back: { native: true }`: the path a back takes once Navigation and
5165        /// the covers have passed on it, the entry page's `onBackPress`, which reaches the
5166        /// app's handlers while they arm it. ArkUI has no call that presses the system back
5167        /// itself, so a pushed destination or a cover is not popped this way.
5168        fn native_back(&mut self) -> bool {
5169            app_back_requested()
5170        }
5171
5172        /// Settled once no nav push or pop is still landing, no list reload is still posted, and
5173        /// every list has settled (`list::settled`): no programmatic scroll waits to be applied
5174        /// or is still moving, and no list owes the viewport report of a change ArkUI has not
5175        /// laid out yet. A scripted step after "scroll to row" or a row change then sees the
5176        /// rows the list shows now (docs/list.md "Visible rows").
5177        fn ui_idle(&mut self) -> bool {
5178            NAV_PENDING_PUSH.with(|s| s.borrow().is_empty())
5179                && NAV_PENDING_POP.with(|p| p.borrow().is_empty())
5180                && LIST_RELOAD_PENDING.with(|p| p.borrow().is_empty())
5181                && crate::list::settled()
5182        }
5183
5184        /// Native file open/save via the ArkTS `@kit.CoreFileKit` `DocumentViewPicker` (docs/files.md).
5185        /// Dialogs/prompts use the ArkTS native modal host (docs/dialogs.md).
5186        fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
5187            use day_spec::present::PresentSpec;
5188            match spec {
5189                // Mode 0 picks one file, mode 2 several (`DocumentSelectOptions.maxSelectNumber`).
5190                PresentSpec::OpenFile { multiple, .. } => {
5191                    let mode = if *multiple { 2 } else { 0 };
5192                    crate::host_api::present_file(req, mode, "", "", &spec.filters_joined());
5193                }
5194                // No folder chooser on HarmonyOS (`Cap::FolderDialog` is Unsupported): the
5195                // request resolves at once.
5196                PresentSpec::OpenFolder { .. } => emit(
5197                    day_spec::NodeId(req),
5198                    Event::PresentResult {
5199                        req,
5200                        result: day_spec::present::PresentResult::Dismissed,
5201                    },
5202                ),
5203                PresentSpec::SaveFile {
5204                    suggested_name,
5205                    src_path,
5206                    ..
5207                } => {
5208                    crate::host_api::present_file(
5209                        req,
5210                        1,
5211                        suggested_name,
5212                        src_path,
5213                        &spec.filters_joined(),
5214                    );
5215                }
5216                PresentSpec::Dialog { .. } | PresentSpec::Prompt { .. } => {
5217                    crate::host_api::present_dialog(req, spec);
5218                }
5219            }
5220        }
5221
5222        fn dismiss(&mut self, req: u64) {
5223            crate::host_api::dismiss_dialog(req);
5224        }
5225
5226        fn open_url(&mut self, url: &str) {
5227            crate::host_api::open_url(url);
5228        }
5229
5230        fn set_status_bar_hidden(&mut self, hidden: bool) {
5231            // The ArkTS host hides it with `setSpecificSystemBarEnabled('status', …)`; the page's
5232            // onAreaChange then reports the taller content area (docs/cover.md).
5233            crate::host_api::set_status_bar_hidden(hidden);
5234        }
5235
5236        fn set_drag_source(&mut self, h: &AHandle, source: day_spec::transfer::Source) {
5237            crate::transfer::source(h, source);
5238        }
5239        fn set_drop_target(&mut self, h: &AHandle, target: day_spec::transfer::Target) {
5240            crate::transfer::target(h, target);
5241        }
5242        fn edit_toolbar(&mut self, h: &AHandle, ops: &[day_spec::ToolbarOp]) -> bool {
5243            if is_secondary_root(h) {
5244                return true;
5245            }
5246            WINDOW_BAR.with(|b| {
5247                let mut b = b.borrow_mut();
5248                for op in ops {
5249                    b.apply(op);
5250                }
5251            });
5252            paint_window_bar();
5253            paint_page_search(false);
5254            true
5255        }
5256
5257        fn update_toolbar(&mut self, h: &AHandle, patch: &day_spec::ToolbarPatch) {
5258            use day_spec::ToolbarPatch as P;
5259            if is_secondary_root(h) {
5260                return;
5261            }
5262            match patch {
5263                // A page's search field (docs/search.md, "Page search"): the app writing its
5264                // query re-texts the drawn field; the host compares, so an echo of the user's
5265                // own edit changes nothing.
5266                P::Text { item, .. } if item == day_spec::SEARCH_ITEM_ID => {
5267                    WINDOW_BAR.with(|b| b.borrow_mut().patch(patch));
5268                    paint_page_search(false);
5269                }
5270                P::Focus { item } if item == day_spec::SEARCH_ITEM_ID => paint_page_search(true),
5271                // No other search is on this bar (`Cap::ToolbarSearch`, docs/search.md), and
5272                // ArkUI's `Search` has no completion list to show suggestions in.
5273                P::Text { .. } | P::Suggestions { .. } | P::Focus { .. } => {}
5274                _ => {
5275                    if WINDOW_BAR.with(|b| b.borrow_mut().patch(patch)) {
5276                        paint_window_bar();
5277                    }
5278                }
5279            }
5280        }
5281
5282        #[expect(
5283            clippy::match_same_arms,
5284            reason = "one arm per capability, each documented with the ArkUI mechanism behind it"
5285        )]
5286        fn capability(&self, cap: Cap) -> Support {
5287            match cap {
5288                Cap::SearchField => Support::Native,
5289                Cap::ComboBox => Support::Native,
5290                Cap::Stepper => Support::Emulated,
5291                Cap::DateTimePicker => Support::Native,
5292                Cap::ColorPicker => Support::Emulated,
5293                Cap::PullRefresh => Support::Native,
5294                Cap::Pager => Support::Native,
5295                Cap::PullRefreshGesture => Support::Native,
5296                Cap::DragDrop
5297                | Cap::DragExternalImport
5298                | Cap::DragExternalExport
5299                | Cap::DragMultipleItems => Support::Native,
5300                Cap::FileDialogs => Support::Native,
5301                Cap::Dialogs => Support::Native,
5302                // `animateTo` interpolates opacity, transform, background color and frames on
5303                // ArkUI's compositor (§8.4, docs/tween.md).
5304                Cap::Animation => Support::Native,
5305                // docs/focus.md, docs/menus.md "Keys", docs/gestures.md "Hit slop": NODE_FOCUSABLE
5306                // with focus on touch; key repeats read from held keys, releases forwarded; the
5307                // node's response region.
5308                Cap::Focusable | Cap::KeyPhases | Cap::HitSlop => Support::Native,
5309                // docs/list.md, docs/scroll.md, docs/pager.md: the list's index and scroll
5310                // events, NODE_LIST_SCROLL_TO_INDEX with alignment and animation, the Scroll's
5311                // scroll events and states, its paging and snap attributes, the Swiper's
5312                // content-scroll event. The keyboard is dismissed by the shared layer from the
5313                // phases; the C API's Scroll has no zoom.
5314                Cap::ListViewport
5315                | Cap::ListScrollAlign
5316                | Cap::ScrollOffset
5317                | Cap::ScrollPhases
5318                | Cap::ScrollSnap
5319                | Cap::PagerProgress => Support::Native,
5320                // The list's will-scroll frames name their `ArkUI_ScrollSource`: a drag, other
5321                // user input (a wheel, a key) or the scroll bar is the reader's, reported with
5322                // the first viewport report it moved; the scroller and its animation are the
5323                // app's (docs/list.md "Following the end").
5324                Cap::ListReaderScroll => Support::Native,
5325                Cap::ScrollKeyboardDismiss => Support::Emulated,
5326                // `OH_Drawing_FontMgr` lists every family and style set (docs/fonts.md).
5327                Cap::FontList => Support::Native,
5328                // `OH_ImageSourceNative` decodes every container the platform reads, and the
5329                // image packer writes back PNG and JPEG (docs/images.md). `Cap::ImageProperties`
5330                // is deliberately NOT here: the platform does expose
5331                // `OH_ImageSourceNative_GetImageProperty`, but nothing reads it yet, and an empty
5332                // struct would read as "this file records nothing" rather than "nobody looked".
5333                Cap::ImageDecode | Cap::ImageEncode => Support::Native,
5334                // A drawing replays into a CPU `OH_Drawing_Bitmap` through the canvas node's own
5335                // painter and lands in the pixelmap registry (docs/canvas.md "Exporting"). No
5336                // PDF: the platform's PDF Kit edits documents and offers no drawing context.
5337                Cap::CanvasBitmap => Support::Native,
5338                // OH_ArkUI_GetNodeSnapshot + the native image packer, both synchronous
5339                // (docs/window-image.md).
5340                Cap::Snapshot => Support::Native,
5341                // Every pushed page is an ArkTS NavDestination with a native title bar
5342                // (DayNavigation.ets); content needn't repeat the title (docs/navigation.md).
5343                Cap::NavHeader => Support::Native,
5344                // `Navigation` in `NavigationMode.Auto` tiles the nav bar (the sidebar rows)
5345                // beside the content where both fit: a native split (docs/size-classes.md).
5346                Cap::NavSplit => Support::Native,
5347                // `Emulated`: Auto mode decides at layout, so the platform owns the presentation
5348                // and Day observes it through `Event::NavPresentationChanged` rather than
5349                // pushing one in, the Android/UIKit policy.
5350                Cap::NavRepresent => Support::Emulated,
5351                // A `Navigation`'s title bar carries `.menus()` items, which is where a page's
5352                // toolbar commands go here (docs/toolbars.md). Emulated rather than Native: the
5353                // bar belongs to the navigation destination, not to the window, so an app that
5354                // asks whether there is persistent window chrome gets the honest answer.
5355                Cap::Toolbar => Support::Emulated,
5356                // The composed bottom bar (see NavSuite): ArkUI's native node set has no tab
5357                // container, so this one is built from Day's own primitives; Emulated says so.
5358                Cap::NavTabs => Support::Emulated,
5359                // And HarmonyOS should grow one as it narrows: a bottom bar is the phone idiom
5360                // here as it is on iOS and Android (docs/navigation.md).
5361                Cap::NavTabsAdaptive => Support::Emulated,
5362                // ArkUI's own drag pipeline (SetNodeDraggable + NODE_ON_DROP): long-press lift
5363                // with the system preview; a denied drop springs back natively (docs/list.md).
5364                Cap::ListReorder => Support::Native,
5365                // A reordering sidebar is Day's own list standing in for the native one
5366                // (docs/navigation.md).
5367                Cap::NavReorder => Support::Emulated,
5368                // The List's NodeAdapter pools its item nodes: a row scrolling in rebinds a
5369                // pooled cell, one scrolling out parks it (docs/list.md).
5370                Cap::ListRecycling => Support::Native,
5371                // `NODE_LIST_ITEM_SWIPE_ACTION`: the row slides to reveal the app's delete
5372                // button, ArkUI's own idiom for the gesture (docs/list.md).
5373                Cap::ListDelete => Support::Native,
5374                // Header rows are inert, content-sized cells pooled apart from the items; the
5375                // pinned header is one overlay cell over the list, rebound as the section at
5376                // the top changes. ArkUI's own sticky headers need `ListItemGroup`s, which the
5377                // single adapter-fed row space does not have (docs/list.md "Sections").
5378                Cap::ListSections => Support::Emulated,
5379                // Emulated: a topmost full-window child of the root, not a system modal.
5380                Cap::Cover => Support::Emulated,
5381                // The window's `setSpecificSystemBarEnabled('status', …)` (docs/cover.md).
5382                Cap::StatusBarHidden => Support::Native,
5383                // The COMPOSED tree (docs/tree.md M2/M4): the piece flattens onto this
5384                // backend's NodeAdapter list; disclosure, indentation and row content are
5385                // day pieces. No native drag wiring, so `Cap::TreeMove` stays Unsupported
5386                // (`tree_move:` drives the seam synthetically).
5387                Cap::Tree | Cap::TreeSections => Support::Emulated,
5388                // Derived from NODE_FONT_SIZE: ArkUI publishes no baseline (docs/baseline.md).
5389                Cap::BaselineAlignment => Support::Emulated,
5390                // Native spans own link hit testing, including spans wrapped across lines.
5391                Cap::TextRuns | Cap::TextLinks => Support::Native,
5392                // Native TextArea, with edit vetoes and selection collapse enforced by Day.
5393                Cap::TextEditable | Cap::TextSelectable => Support::Emulated,
5394                // ArkTS arms (src/host.rs): present wherever `day build` staged them.
5395                Cap::Appearance => crate::host::color_mode_support(),
5396                Cap::AppBadgeCount => crate::host::badge_support(),
5397                // The ArkTS host decides: Native once its announce arm is staged.
5398                Cap::Announce => {
5399                    if crate::host::announce_support() == Support::Native {
5400                        Support::Native
5401                    } else {
5402                        Support::Unsupported
5403                    }
5404                }
5405                // Likewise: the settings data's animation scale, read and watched from ArkTS.
5406                Cap::ReduceMotion => {
5407                    if crate::host::reduce_motion_support() == Support::Native {
5408                        Support::Native
5409                    } else {
5410                        Support::Unsupported
5411                    }
5412                }
5413                // The window's own calls, made by the ArkTS host (docs/windows.md "Window
5414                // properties"): `setWindowLayoutFullScreen` with the system bars hidden. Native
5415                // once the host registered the control; an older host has none. Minimize and
5416                // maximize stay Unsupported: the phone OS sizes the window.
5417                Cap::WindowFullscreen => {
5418                    if crate::host_api::has_window_control() {
5419                        Support::Native
5420                    } else {
5421                        Support::Unsupported
5422                    }
5423                }
5424                // `setWindowPrivacyMode`, which blanks the window in screenshots, recordings and
5425                // casting. It needs `ohos.permission.PRIVACY_WINDOW`, which an app opts into with
5426                // `screen-privacy` in Day.toml's `[permissions]` (docs/permissions.md); the host
5427                // checks the grant when it registers.
5428                Cap::ContentProtection => {
5429                    if crate::host_api::can_protect_content() {
5430                        Support::Native
5431                    } else {
5432                        Support::Unsupported
5433                    }
5434                }
5435                // The default display from the NDK display manager, as the one monitor a phone or
5436                // tablet has (docs/windows.md "Monitors"): no position and no work area of its own.
5437                Cap::Monitors => Support::Emulated,
5438                // Multiton DayWindowAbility instances (docs/windows.md): Native only when
5439                // the ArkTS host registered the launchers; an older host degrades to the
5440                // cover fallback.
5441                Cap::MultiWindow => {
5442                    if crate::host_api::has_windows() {
5443                        Support::Native
5444                    } else {
5445                        Support::Unsupported
5446                    }
5447                }
5448                _ => Support::Unsupported,
5449            }
5450        }
5451
5452        fn open_window(
5453            &mut self,
5454            id: NodeId,
5455            options: &day_spec::WindowOptions,
5456            kind: day_spec::WindowKind,
5457        ) -> day_spec::WindowOpenReply<AHandle> {
5458            // Preferences stay modal on mobile (docs/windows.md); Normal windows become
5459            // multiton ability instances (their own task cards; freeform on tablets).
5460            if kind.is_panel() {
5461                return day_spec::WindowOpenReply::Unsupported;
5462            }
5463            if crate::host_api::open_window(id.0, &options.title) {
5464                day_spec::WindowOpenReply::Pending
5465            } else {
5466                day_spec::WindowOpenReply::Unsupported
5467            }
5468        }
5469
5470        fn close_window(&mut self, host: &AHandle) {
5471            let node_id = SECONDARY.with(|s| {
5472                s.borrow()
5473                    .iter()
5474                    .find(|(_, ptr)| *ptr == host.0 as usize)
5475                    .map(|(n, _)| *n)
5476            });
5477            if let Some(node_id) = node_id {
5478                crate::host_api::close_window(node_id);
5479            }
5480        }
5481
5482        /// The default display (`OH_NativeDisplayManager_GetDefaultDisplay*`, API 12), in vp:
5483        /// the whole screen as both frame and work area, since this API level reports no bars.
5484        fn monitors(&self) -> Vec<day_spec::Monitor> {
5485            display::default_monitor().into_iter().collect()
5486        }
5487
5488        fn apply_window(&mut self, host: &AHandle, change: &day_spec::WindowChange) {
5489            use crate::host_api::{WindowOp, window_control};
5490            use day_spec::{WindowChange as C, WindowState as S};
5491            // The host addresses a secondary window by its day node and the primary as 0; the
5492            // state report goes to the secondary's node or to WINDOW_NODE.
5493            let secondary = SECONDARY.with(|s| {
5494                s.borrow()
5495                    .iter()
5496                    .find(|(_, ptr)| *ptr == host.0 as usize)
5497                    .map(|(n, _)| *n)
5498            });
5499            let (node, target) = match secondary {
5500                Some(n) => (n, NodeId(n)),
5501                None => (0, day_spec::WINDOW_NODE),
5502            };
5503            match change {
5504                C::State(state) => {
5505                    // Sent: the host reports the outcome through `windowStateChanged` once its
5506                    // calls settled, success or not.
5507                    let sent = matches!(state, S::Fullscreen | S::Normal)
5508                        && window_control(node, WindowOp::Fullscreen, *state == S::Fullscreen);
5509                    if sent {
5510                        return;
5511                    }
5512                    // Declined: a phone window cannot be minimized or zoomed, and a host without
5513                    // the control cannot go fullscreen. Report the state the window is really
5514                    // in, so day-core's optimistic `state()` settles back to it.
5515                    let current = WINDOW_STATES
5516                        .with(|m| m.borrow().get(&target.0).copied())
5517                        .unwrap_or_default();
5518                    log::debug!("arkui: window state request declined, still {current:?}");
5519                    post_emit(target, Event::WindowStateChanged(current));
5520                }
5521                // Without the permission the call would only fail; the Cap already says no.
5522                C::ContentProtected(on) if crate::host_api::can_protect_content() => {
5523                    window_control(node, WindowOp::Privacy, *on);
5524                }
5525                _ => {}
5526            }
5527        }
5528    }
5529
5530    /// The NDK's display manager (`window_manager/oh_display_manager.h`), for `Toolkit::monitors`.
5531    mod display {
5532        use std::ffi::c_int;
5533
5534        #[link(name = "native_display_manager")]
5535        unsafe extern "C" {
5536            // Each returns a `NativeDisplayManager_ErrorCode`, `DISPLAY_MANAGER_OK` (0) on success.
5537            fn OH_NativeDisplayManager_GetDefaultDisplayId(id: *mut u64) -> c_int;
5538            fn OH_NativeDisplayManager_GetDefaultDisplayWidth(width: *mut i32) -> c_int;
5539            fn OH_NativeDisplayManager_GetDefaultDisplayHeight(height: *mut i32) -> c_int;
5540            fn OH_NativeDisplayManager_GetDefaultDisplayDensityPixels(density: *mut f32) -> c_int;
5541        }
5542
5543        /// The default display as a [`day_spec::Monitor`] in vp, or `None` if the service fails.
5544        pub(super) fn default_monitor() -> Option<day_spec::Monitor> {
5545            let (mut id, mut w, mut h, mut density) = (0u64, 0i32, 0i32, 0f32);
5546            // SAFETY: each call writes one value through a pointer to a live local.
5547            let ok = unsafe {
5548                OH_NativeDisplayManager_GetDefaultDisplayId(&raw mut id) == 0
5549                    && OH_NativeDisplayManager_GetDefaultDisplayWidth(&raw mut w) == 0
5550                    && OH_NativeDisplayManager_GetDefaultDisplayHeight(&raw mut h) == 0
5551                    && OH_NativeDisplayManager_GetDefaultDisplayDensityPixels(&raw mut density) == 0
5552            };
5553            if !ok || w <= 0 || h <= 0 {
5554                return None;
5555            }
5556            let scale = if density > 0.0 {
5557                f64::from(density)
5558            } else {
5559                1.0
5560            };
5561            let frame = day_spec::Rect::new(0.0, 0.0, f64::from(w) / scale, f64::from(h) / scale);
5562            Some(day_spec::Monitor {
5563                id: id.to_string(),
5564                name: format!("Display {id}"),
5565                frame,
5566                work_area: frame,
5567                scale,
5568                primary: true,
5569            })
5570        }
5571    }
5572
5573    impl Platform for ArkUi {
5574        const TARGET: &'static str = "harmony-arkui";
5575        const TOOLKIT: &'static str = "arkui";
5576        // The host owns the loop: `run` hands back at once, and DidExit is its last callback.
5577        const RUN_ENDS_APP: bool = false;
5578
5579        fn run(self, _options: WindowOptions, ready: Box<dyn FnOnce(Self, AHandle, Size)>) {
5580            // The ArkTS ability owns the loop; init() already created + mounted the root.
5581            let (root, size) = ROOT
5582                .with(|r| r.borrow_mut().take())
5583                .expect("day-toolkit-arkui: init() not called before run()");
5584            ready(self, root, size);
5585        }
5586
5587        fn post(f: Box<dyn FnOnce() + Send>) {
5588            crate::main_thread::post(f);
5589        }
5590
5591        fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
5592            crate::main_thread::post_delayed(ms, f);
5593        }
5594    }
5595
5596    /// Map a day slider value into ArkUI's default 0..100 range.
5597    fn normalize(v: f64, min: f64, max: f64) -> f64 {
5598        if max <= min {
5599            0.0
5600        } else {
5601            ((v - min) / (max - min) * 100.0).clamp(0.0, 100.0)
5602        }
5603    }
5604
5605    /// The `"family"` values of the staged font manifest, by a scan rather than a JSON parser:
5606    /// the CLI writes the file (plain strings, no escapes beyond `\"`), and this backend takes no
5607    /// JSON dependency for one key.
5608    fn manifest_families(json: &str) -> Vec<String> {
5609        manifest_entries(json).into_iter().map(|(f, _)| f).collect()
5610    }
5611
5612    /// The manifest's `(family, file)` pairs, in order: each staged font's family name and the
5613    /// rawfile it was staged as under `day/fonts/`. The same key scan, one object at a time.
5614    fn manifest_entries(json: &str) -> Vec<(String, String)> {
5615        fn value_after(rest: &str, key: &str) -> Option<(String, usize)> {
5616            let i = rest.find(key)?;
5617            let after = &rest[i + key.len()..];
5618            let q = after.find('"')?;
5619            let value = &after[q + 1..];
5620            let end = value.find('"')?;
5621            let text = value[..end].replace("\\\"", "\"").replace("\\\\", "\\");
5622            Some((text, i + key.len() + q + 1 + end + 1))
5623        }
5624        let mut out = Vec::new();
5625        let mut rest = json;
5626        while let Some(open) = rest.find('{') {
5627            let Some(close) = rest[open..].find('}') else {
5628                break;
5629            };
5630            let object = &rest[open..open + close];
5631            let family = value_after(object, "\"family\"").map(|(v, _)| v);
5632            let file = value_after(object, "\"file\"").map(|(v, _)| v);
5633            if let (Some(family), Some(file)) = (family, file)
5634                && !family.is_empty()
5635                && !file.is_empty()
5636            {
5637                out.push((family, file));
5638            }
5639            rest = &rest[open + close + 1..];
5640        }
5641        out
5642    }
5643
5644    /// Hand every bundled font's bytes to the drawing layer, once per process, so canvas text
5645    /// can draw in it (docs/fonts.md). The ability's ArkTS `font.registerFont` reaches the
5646    /// text engine that labels use and not `OH_Drawing`'s font manager, which is why the
5647    /// showcase's canvas came out in the system face while its labels were right.
5648    fn ensure_canvas_fonts() {
5649        if CANVAS_FONTS_REGISTERED.with(|d| d.replace(true)) {
5650            return;
5651        }
5652        let Some(manifest) = open_resource("fonts.json") else {
5653            return;
5654        };
5655        let json = String::from_utf8_lossy(manifest.as_slice()).into_owned();
5656        for (family, file) in manifest_entries(&json) {
5657            let Some(res) = open_resource(&format!("fonts/{file}")) else {
5658                log::warn!("bundled font {file:?} ({family:?}) is not in the rawfile store");
5659                continue;
5660            };
5661            if !crate::fonts::register_canvas_font(&family, res.as_slice()) {
5662                log::warn!("bundled font {file:?} ({family:?}) did not parse as a font");
5663            }
5664        }
5665    }
5666
5667    /// The rawfile-backed data-resource opener (§18.3), registered once in [`init`]. Serves
5668    /// `resource("numbers.bin")` from the app's `resources/rawfile/day/<name>` store via the
5669    /// OpenHarmony `OH_ResourceManager_*` API: zero-copy where the entry is mmap-able, else a copy.
5670    ///
5671    /// Returns `None` until the ArkTS entry ability has handed the native side its `resourceManager`
5672    /// (the host's `registerResourceManager`); without it there is no `NativeResourceManager` to
5673    /// read through, so no data resources are available.
5674    fn open_resource(name: &str) -> Option<day_spec::resource::Resource> {
5675        if !crate::resources::available() {
5676            return None;
5677        }
5678        // OpenRawFile addresses entries relative to the rawfile root, so the lookup key for a staged
5679        // resource is `day/<name>` (the CLI stages data uncompressed under resources/rawfile/day/).
5680        let mapped = crate::resources::open(&format!("day/{name}"))?;
5681        let (data, len) = mapped.as_ptr_len();
5682        if data.is_null() {
5683            return None;
5684        }
5685        // Safety: `data`/`len` describe a valid immutable region owned by `mapped`, which the
5686        // Resource keeps until it drops, unmapping or freeing it then.
5687        Some(unsafe { day_spec::resource::Resource::from_raw(data, len, Box::new(mapped)) })
5688    }
5689
5690    use std::any::Any;
5691}