Skip to main content

day_toolkit_winui/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! WinUI 3 backend for `windows-winui`, over the `day-toolkit-xaml-sys` C++/WinRT shim.
5//! The `winui` feature selects Microsoft.UI.Xaml; the deprecated `windows-xaml`
6//! target uses Windows.UI.Xaml through the same shim. Controls live in a
7//! `DesktopWindowXamlSource`, with Day layout placing them inside XAML Canvases.
8//! Toolkit-independent Windows services come from `day-platform-windows`.
9//! The `Xaml` and `xaml_raw` type names remain shared by both target variants.
10
11#![cfg(windows)]
12
13mod controls;
14
15#[cfg(feature = "winui")]
16mod list;
17#[cfg(not(feature = "winui"))]
18#[path = "list_legacy.rs"]
19mod list;
20mod transfer;
21mod tree;
22
23use std::cell::{Cell, RefCell};
24use std::collections::{BTreeSet, HashMap, HashSet};
25use std::ffi::{CStr, CString};
26use std::fmt::Write as _;
27use std::os::raw::{c_char, c_double, c_int, c_void};
28use std::rc::Rc;
29
30use day_toolkit_xaml_sys as ffi;
31use linkme::distributed_slice;
32
33use day_spec::props::*;
34use day_spec::{
35    A11yProps, AnimSpec, Builtin, Cap, Cursor, DrawOp, Event, EventSink, Font, InputPurpose,
36    InputTraits, NodeId, PieceKind, Platform, Point, Proposal, Rect, Registry, Renderer, Size,
37    Support, Toolkit, Transform, WindowOptions, ffi_guard, kinds, props_of,
38};
39
40/// An `AnimSpec` as the shim plays it ([`ffi::DayAnim`]), owning the samples the struct points
41/// at. The shim plays one forward cycle of `AnimSpec::keyframes` as a key-frame animation, so
42/// every curve, the physical spring included, runs exactly as the contract samples it
43/// (docs/tween.md); `None` sets the value outright.
44struct XamlAnim {
45    raw: ffi::DayAnim,
46    _progress: Vec<f64>,
47}
48
49impl XamlAnim {
50    fn new(anim: Option<&AnimSpec>) -> Option<XamlAnim> {
51        let a = anim?;
52        let progress: Vec<f64> = a.keyframes().iter().map(|k| k.progress).collect();
53        let raw = ffi::DayAnim {
54            delay_ms: c_int::try_from(a.delay_ms).unwrap_or(c_int::MAX),
55            duration_ms: c_int::try_from(a.duration_ms).unwrap_or(c_int::MAX),
56            repeat: a.repeat,
57            autoreverse: c_int::from(a.autoreverse),
58            frames: c_int::try_from(progress.len()).unwrap_or(0),
59            progress: progress.as_ptr(),
60        };
61        Some(XamlAnim {
62            raw,
63            _progress: progress,
64        })
65    }
66
67    /// The pointer the shim takes: null for "at once".
68    fn ptr(anim: Option<&XamlAnim>) -> *const ffi::DayAnim {
69        anim.map_or(std::ptr::null(), |a| &raw const a.raw)
70    }
71}
72
73#[derive(Clone, Copy, PartialEq, Eq, Hash)]
74pub struct WinHandle(pub *mut c_void);
75
76// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
77mod picker;
78mod textarea;
79mod toolbar;
80
81pub type Handle = WinHandle;
82
83pub mod ext;
84pub use ext::*;
85
86/// The day-core event sink (node-id keyed).
87type Sink = Rc<dyn Fn(NodeId, Event)>;
88
89day_core::tls_group! {
90    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
91    /// Template loads invalidate intrinsic sizes together on the next UI turn.
92    static LOADED_MEASURES: RefCell<BTreeSet<u64>> = const { RefCell::new(BTreeSet::new()) };
93    /// Label ptr → node id, so a `LabelPatch::Runs` (which carries no id) can still tell a link
94    /// run's Hyperlink which node to report against. Entries drop in `release`.
95    static LABEL_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
96    /// Label ptr → what a label held to one line with head or middle truncation shows
97    /// (docs/text.md "Truncation"): XAML trims the tail only, so the label shows
98    /// `day_spec::elide`'s string and keeps the whole text here for the read-back. Entries drop
99    /// in `release`.
100    static LABEL_ELIDE: RefCell<HashMap<usize, Elided>> = RefCell::new(HashMap::new());
101    /// Node id → the text a selection-reporting label displays, which its UTF-16 selection
102    /// offsets index (docs/text.md "Selection"). Entries drop in `release`.
103    static LABEL_TEXT: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
104    /// Label ptr → its paragraph alignment, re-read when the label is given a reading
105    /// direction of its own (`set_layout_direction`). Entries drop in `release`.
106    static LABEL_ALIGN: RefCell<HashMap<usize, day_spec::props::TextAlign>> =
107        RefCell::new(HashMap::new());
108    /// Labels that currently carry runs. Entries drop in `release`.
109    static LABEL_RUNS: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
110    /// Every applied ink that follows the appearance, by view and slot, with the call that
111    /// applies it again (docs/color.md "Following the appearance"). XAML has no color that
112    /// re-resolves itself outside a `{ThemeResource}`, so a switch re-applies these
113    /// (`repaint_inks`). Fixed inks have no entry. Entries drop in `release`.
114    static INKS: RefCell<HashMap<(usize, InkSlot), Repaint>> = RefCell::new(HashMap::new());
115    /// Container ptr → its surface as last applied (docs/surfaces.md), the role kept from
116    /// realize, and whether it is drawn as a styled surface. Entries drop in `release`.
117    static SURFACES: RefCell<HashMap<usize, Surface>> = RefCell::new(HashMap::new());
118    /// Elements marked `.window_drag_region()` (docs/window-chrome.md), so `release` can drop the
119    /// shim's reference to one before the element goes.
120    static DRAG_REGIONS: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
121    /// Text field ptr → node id. `set_input_traits` carries no id, and a field that turns secure
122    /// is rebuilt as a `PasswordBox` whose callbacks must report against the same node. It is
123    /// also what tells a text field's handle from any other. Entries drop in `release`.
124    static TEXT_FIELD_NODE: RefCell<HashMap<usize, u64>> = RefCell::new(HashMap::new());
125    /// Text field node id → the text day last wrote into it. XAML raises `TextChanged` for a
126    /// programmatic write too, later and asynchronously, so `on_text` drops a report of exactly
127    /// this text as the echo of day's own write instead of handing it back to the app as typing.
128    /// Cleared by the first report that differs, and in `release`.
129    static TEXT_FIELD_ECHO: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
130    /// NAV_MENU widget ptr → (rows, section titles) (for measure).
131    static NAV_MENU_ROWS: RefCell<HashMap<usize, (usize, usize)>> = RefCell::new(HashMap::new());
132    /// NAV host ptr → its native presentation (NavigationView split / two-pane, docs/navigation.md).
133    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
134    /// NAV_PAGE handle ptr → its node id (so region-resize callbacks can emit FrameChanged).
135    static NAV_PAGE_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
136    /// NAV host node id → host handle ptr (the shim's callbacks carry the host node id).
137    static NAV_HOST_BY_ID: RefCell<HashMap<u64, *mut c_void>> = RefCell::new(HashMap::new());
138    /// A split NavigationView whose NAV_MENU hasn't been created yet (nav is app-root-only, so at
139    /// most one is pending). The next NAV_MENU feeds this NavigationView's MenuItems.
140    static PENDING_SPLIT_NAV: Cell<*mut c_void> = const { Cell::new(std::ptr::null_mut()) };
141    /// NAV_MENU placeholder ptr → its NavigationView (split navs drive MenuItems, not a ListView).
142    static NAV_MENU_HOST: RefCell<HashMap<usize, *mut c_void>> = RefCell::new(HashMap::new());
143    /// Split-nav sidebar-page ptrs: the NavigationView's PaneHeader, clipped to a fixed height.
144    static SPLIT_SIDEBAR_PAGES: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
145    /// SCROLL host ptr → its inner content Canvas ptr (children live in the content, docs §7.6).
146    static SCROLL_STATE: RefCell<HashMap<usize, *mut c_void>> = RefCell::new(HashMap::new());
147    /// Handles with a native gesture recognizer wired, keyed by (handle ptr, kind) — idempotent.
148    static GESTURES: RefCell<HashSet<(usize, c_int)>> = RefCell::new(HashSet::new());
149    /// Canvas host ptrs: a wheel pan over a canvas takes every tick, over any other container
150    /// only sideways movement, so vertical scrolling keeps its native behavior
151    /// (docs/canvas.md "Zoom and pan").
152    static CANVASES: RefCell<HashSet<usize>> = RefCell::new(HashSet::new());
153
154    /// INSPECTOR host ptr → its SplitView state.
155    static INSPECTOR_STATE: RefCell<HashMap<usize, XamlInspector>> = RefCell::new(HashMap::new());
156    /// INSPECTOR_PANE ptr → `(its NodeId, is-panel)`, recorded at realize.
157    static INSPECTOR_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> =
158        RefCell::new(HashMap::new());
159    /// INSPECTOR host node id → its panes' node ids (the shim's size callback carries the
160    /// host node id, the NAV_HOST_BY_ID pattern).
161    static INSPECTOR_PANES_BY_HOST: RefCell<HashMap<u64, InspectorPaneNodes>> =
162        RefCell::new(HashMap::new());
163
164        static RESOLVED: RefCell<HashMap<&'static str, Option<CString>>> =
165            RefCell::new(HashMap::new());
166
167    /// Last reported window content size (seeds cover frames at Present).
168    static LAST_WINDOW_SIZE: std::cell::Cell<Size> =
169        const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
170    /// Presented emulated covers: (element, NodeId).
171    static COVERS: RefCell<Vec<(*mut c_void, NodeId)>> = const { RefCell::new(Vec::new()) };
172    /// Cover element → NodeId (set at realize).
173    static COVER_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
174    /// Covers presented as half sheets (`CoverProps::half`, docs/cover.md): the bottom half
175    /// of the window.
176    static COVER_HALF: RefCell<std::collections::HashSet<usize>> =
177        RefCell::new(std::collections::HashSet::new());
178
179}
180
181// Navigation host — always a native `NavigationView` (docs/navigation.md), in one of two modes
182// chosen by NavProps.presentation:
183//  • Split       → the idiomatic Windows sidebar+header nav host (as in Settings): MenuItems are the
184//    destinations, the Header names the current one, Content holds the detail page.
185//  • Stack       → a push/pop stack: no menu, the back button appears once a page is pushed, and
186//    pages stack in the content region.
187// `menu_node` is the NAV_MENU node id whose SelectionChanged the pane synthesizes; `sidebar_page`
188// (day's logo/title piece) is the PaneHeader; detail pages live in `content_host` (nv.Content) kept
189// with their node ids so a region resize can report FrameChanged (mirrors TABS).
190struct SplitNav {
191    node: u64,
192    nav_view: *mut c_void,
193    content_host: *mut c_void,
194    menu_node: u64,
195    sidebar_page: Option<(*mut c_void, NodeId)>,
196    /// (page, node, title) — the title is attached by `NavPatch::Pushed`/`Title` so a pop can
197    /// restore the PREVIOUS page's title into the `NavigationView` header (`stack_sync`).
198    detail_pages: Vec<(*mut c_void, NodeId, String)>,
199    /// A push/pop stack (NavProps.presentation == Stack): no menu/sidebar, every page stacks in the
200    /// content region, and the `NavigationView` back button appears once a page is pushed.
201    is_stack: bool,
202    /// Whether the destinations are RESIDENT — `Tabs` and `Rail`, where the rows are the chrome
203    /// and every page stays realized so `Select` can switch between them. A `Split` nav is not:
204    /// day swaps its detail page on navigation, so `detail_pages` holds only the current one and
205    /// `selected` (a MENU row index) does not index it. Running the selection pass there would
206    /// mean showing row 0's page whatever page is actually up — the two index spaces only
207    /// coincide when the pages are resident.
208    resident: bool,
209    /// The row of `detail_pages` the app has selected — the one resident page that must be
210    /// visible. Kept here because the pages arrive after the selection is known: a destination set
211    /// realizes its menu first (carrying `NavMenuProps.selected`) and its pages one at a time
212    /// after, each landing on top of the last. Without re-applying the selection on every insert,
213    /// what showed was whichever page happened to be added last.
214    selected: usize,
215}
216
217enum NavState {
218    Split(SplitNav),
219}
220
221/// Fixed height (pt) of the `NavigationView` `PaneHeader` that hosts day's sidebar header piece
222/// (logo + app title) — a bare Canvas has no desired size, so the slot needs an explicit one.
223const NAV_PANE_HEADER_H: c_int = 60;
224
225/// Tree and reorderable-list sidebars supply their own rows instead of `MenuItems`.
226/// Move the page out of the 60-point `PaneHeader` and let Day size the whole sidebar:
227/// Canvas children can paint outside that header while remaining unhittable there.
228fn attach_custom_sidebar() {
229    let pending = PENDING_SPLIT_NAV.with(|v| v.replace(std::ptr::null_mut()));
230    if pending.is_null() {
231        return;
232    }
233    let page = NAV_STATE.with(|m| {
234        m.borrow().values().find_map(|state| {
235            let NavState::Split(s) = state;
236            (s.nav_view == pending).then_some(s.sidebar_page).flatten()
237        })
238    });
239    if let Some((page, _)) = page {
240        SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().remove(&(page as usize)));
241        unsafe { ffi::day_xaml_nav_custom_sidebar(pending, page) };
242    }
243}
244
245/// Escape over a presented sheet cover (docs/cover.md "Modal sheet"): the topmost cover hears
246/// it as its back request, whichever sheet's accelerator fired.
247extern "C" fn on_cover_escape(id: u64) {
248    ffi_guard::contain((), || {
249        let node = COVERS
250            .with(|c| c.borrow().last().map(|(_, node)| *node))
251            .unwrap_or(NodeId(id));
252        emit(
253            node,
254            Event::NavBack {
255                already_popped: false,
256            },
257        );
258    });
259}
260
261extern "C" fn nav_menu_changed(id: u64, index: c_int) {
262    // Every extern "C" trampoline in this backend runs its body through `ffi_guard::contain`:
263    // a panic unwinding into the C++/WinRT shim frame is undefined behavior (day-spec's
264    // ffi_guard).
265    ffi_guard::contain((), || {
266        emit(NodeId(id), Event::SelectionChanged(i64::from(index)));
267    });
268}
269
270/// A user pick in a `NavigationView` pane: the shim passes the HOST node id + item index; route it to
271/// the host's `NAV_MENU` node (whose day handler maps the index back to a route).
272extern "C" fn document_event(host_id: u64, kind: c_int, index: c_int, key: *const c_char) {
273    ffi_guard::contain((), || {
274        let tag = match kind {
275            0 => "day:tab-new",
276            1 => "day:tab-close",
277            _ => "day:tab-move",
278        };
279        let text = if key.is_null() {
280            String::new()
281        } else {
282            unsafe { std::ffi::CStr::from_ptr(key) }
283                .to_string_lossy()
284                .into_owned()
285        };
286        emit(
287            NodeId(host_id),
288            Event::Custom {
289                tag,
290                num: f64::from(index),
291                text,
292            },
293        );
294    });
295}
296
297extern "C" fn nav_selection(host_id: u64, index: c_int) {
298    ffi_guard::contain((), || {
299        let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied());
300        let Some(host) = host else { return };
301        let menu = NAV_STATE.with(|m| match m.borrow().get(&(host as usize)) {
302            Some(NavState::Split(s)) if s.menu_node != 0 => Some(s.menu_node),
303            _ => None,
304        });
305        if let Some(menu_node) = menu {
306            emit(NodeId(menu_node), Event::SelectionChanged(i64::from(index)));
307        }
308    });
309}
310
311/// A `NavigationView` region reflowed (window resize, pane open/close): report the true size so day
312/// re-lays the affected page(s). region 0 = content (detail pages), 1 = pane header (sidebar page).
313extern "C" fn nav_region_size(host_id: u64, region: c_int, w: c_int, h: c_int) {
314    ffi_guard::contain((), || {
315        if w <= 0 || h <= 0 {
316            return;
317        }
318        let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied());
319        let Some(host) = host else { return };
320        let size = Size::new(f64::from(w), f64::from(h));
321        let reports: Vec<NodeId> = NAV_STATE.with(|m| {
322            let m = m.borrow();
323            let Some(NavState::Split(s)) = m.get(&(host as usize)) else {
324                return Vec::new();
325            };
326            if region == 1 {
327                s.sidebar_page.map(|(_, id)| id).into_iter().collect()
328            } else {
329                s.detail_pages.iter().map(|(_, id, _)| *id).collect()
330            }
331        });
332        for id in reports {
333            emit(id, Event::FrameChanged(size));
334        }
335    });
336}
337
338/// Resolve a deferred page-size report against the live navigation tree. The host's node id
339/// survives neither teardown nor reuse of its native handle, and a removed page must not receive
340/// the old report even if its host is still alive. Called on the UI thread, immediately before
341/// reading the native size; no side-table borrow is held across native code or event delivery.
342fn nav_page_content_host(host_id: u64, page: NodeId) -> Option<*mut c_void> {
343    let host = NAV_HOST_BY_ID.with(|m| m.borrow().get(&host_id).copied())?;
344    NAV_STATE.with(|m| {
345        let m = m.borrow();
346        let NavState::Split(s) = m.get(&(host as usize))?;
347        (s.node == host_id && s.detail_pages.iter().any(|(_, id, _)| *id == page))
348            .then_some(s.content_host)
349    })
350}
351
352#[cfg(test)]
353mod button_menu_tests {
354    use super::*;
355
356    fn item() -> day_spec::MenuItem {
357        day_spec::MenuItem::Action {
358            id: None,
359            action: 1,
360            label: "Open".into(),
361            shortcut: None,
362            enabled: true,
363            checked: None,
364            role: None,
365            icon: None,
366        }
367    }
368
369    /// A provider that removes its own button (as `release` does when the app's signal write
370    /// rebuilds the tree) still answers items; the press must not hand the freed element on.
371    #[test]
372    fn a_provider_that_releases_its_button_opens_nothing() {
373        let (node, button) = (41_u64, 0x1000_usize);
374        let provider: day_spec::ContextMenuFn = Rc::new(move |_| {
375            BUTTON_MENUS.with(|m| m.borrow_mut().retain(|_, (b, _)| *b != button));
376            vec![item()]
377        });
378        BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (button, provider)));
379        assert_eq!(button_menu_for(node), ButtonMenu::Nothing);
380        assert_eq!(button_menu_for(node), ButtonMenu::NotAMenuButton);
381    }
382
383    /// A provider that releases its button while another button takes the same node id does
384    /// not open the menu on the replacement either: the handle must match too.
385    #[test]
386    fn a_replaced_button_is_not_the_pressed_one() {
387        let node = 42_u64;
388        let provider: day_spec::ContextMenuFn = Rc::new(move |_| {
389            let replacement: day_spec::ContextMenuFn = Rc::new(|_| Vec::new());
390            BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x2000, replacement)));
391            vec![item()]
392        });
393        BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x1000, provider)));
394        assert_eq!(button_menu_for(node), ButtonMenu::Nothing);
395        BUTTON_MENUS.with(|m| m.borrow_mut().remove(&node));
396    }
397
398    #[test]
399    fn a_live_button_shows_its_menu() {
400        let node = 43_u64;
401        let provider: day_spec::ContextMenuFn = Rc::new(|_| vec![item()]);
402        BUTTON_MENUS.with(|m| m.borrow_mut().insert(node, (0x3000, provider)));
403        std::assert_matches!(button_menu_for(node), ButtonMenu::Show(0x3000, items) if items.len() == 1);
404        BUTTON_MENUS.with(|m| m.borrow_mut().remove(&node));
405    }
406}
407
408#[cfg(test)]
409mod deferred_nav_size_tests {
410    use super::*;
411
412    // Opaque test handles are never dereferenced: only a successful live lookup may reach FFI.
413    fn register(host_id: u64, page: NodeId) -> *mut c_void {
414        let host = std::ptr::without_provenance_mut::<c_void>(1);
415        let content = std::ptr::without_provenance_mut::<c_void>(2);
416        NAV_HOST_BY_ID.with(|m| m.borrow_mut().insert(host_id, host));
417        NAV_STATE.with(|m| {
418            m.borrow_mut().insert(
419                host as usize,
420                NavState::Split(SplitNav {
421                    node: host_id,
422                    nav_view: host,
423                    content_host: content,
424                    menu_node: 0,
425                    sidebar_page: None,
426                    detail_pages: vec![(std::ptr::without_provenance_mut(3), page, String::new())],
427                    is_stack: true,
428                    resident: false,
429                    selected: 0,
430                }),
431            );
432        });
433        content
434    }
435
436    #[test]
437    fn removed_page_does_not_receive_a_deferred_size() {
438        let content = register(10, NodeId(20));
439        assert_eq!(nav_page_content_host(10, NodeId(20)), Some(content));
440        NAV_STATE.with(|m| {
441            let mut m = m.borrow_mut();
442            let Some(NavState::Split(s)) = m.get_mut(&1) else {
443                unreachable!();
444            };
445            s.detail_pages.clear();
446        });
447        assert_eq!(nav_page_content_host(10, NodeId(20)), None);
448        NAV_STATE.with(|m| m.borrow_mut().clear());
449        NAV_HOST_BY_ID.with(|m| m.borrow_mut().clear());
450    }
451
452    #[test]
453    fn released_host_and_reused_native_address_do_not_resolve() {
454        register(10, NodeId(20));
455        NAV_STATE.with(|m| m.borrow_mut().clear());
456        NAV_HOST_BY_ID.with(|m| m.borrow_mut().remove(&10));
457        assert_eq!(nav_page_content_host(10, NodeId(20)), None);
458
459        // Another navigation host reuses exactly the same native allocation.
460        let content = register(11, NodeId(21));
461        assert_eq!(nav_page_content_host(10, NodeId(20)), None);
462        assert_eq!(nav_page_content_host(11, NodeId(20)), None);
463        assert_eq!(nav_page_content_host(11, NodeId(21)), Some(content));
464        NAV_STATE.with(|m| m.borrow_mut().clear());
465        NAV_HOST_BY_ID.with(|m| m.borrow_mut().clear());
466    }
467}
468
469// Inspector (docs/inspector.md): a SplitView with its pane placed right — the XAML
470// trailing-pane container, Inline so the open pane sits beside the content. Day's signal is
471// the only visibility driver (Inline panes have no light-dismiss), so this backend never
472// emits `Event::InspectorChanged`.
473struct XamlInspector {
474    content_host: *mut c_void,
475    panel_host: *mut c_void,
476    node: u64,
477}
478
479/// The two pane node ids of one inspector host, for region-size reports.
480#[derive(Default)]
481struct InspectorPaneNodes {
482    content: Option<NodeId>,
483    panel: Option<NodeId>,
484}
485
486/// An inspector region reflowed (window resize, pane open/close): report the true size so day
487/// re-lays that pane's content. region 0 = content, 1 = panel (the shim contract).
488extern "C" fn inspector_region_size(host_id: u64, region: c_int, w: c_int, h: c_int) {
489    ffi_guard::contain((), || {
490        if w <= 0 || h <= 0 {
491            return;
492        }
493        let id = INSPECTOR_PANES_BY_HOST.with(|m| {
494            m.borrow()
495                .get(&host_id)
496                .and_then(|p| if region == 1 { p.panel } else { p.content })
497        });
498        if let Some(id) = id {
499            emit(
500                id,
501                Event::FrameChanged(Size::new(f64::from(w), f64::from(h))),
502            );
503        }
504    });
505}
506
507/// The `NavigationView` back button: pop one level (the stack surface writes it back into its path).
508extern "C" fn nav_back(host_id: u64) {
509    ffi_guard::contain((), || {
510        emit(
511            NodeId(host_id),
512            Event::NavBack {
513                already_popped: false,
514            },
515        );
516    });
517}
518
519/// A stack's pages overlap in the content region; show only the top one so a transparent page
520/// can't reveal those beneath it, and refresh the back button (visible once a page is pushed).
521fn stack_sync(host: *mut c_void) {
522    NAV_STATE.with(|m| {
523        if let Some(NavState::Split(s)) = m.borrow().get(&(host as usize)) {
524            let last = s.detail_pages.len().saturating_sub(1);
525            for (i, (page, _, _)) in s.detail_pages.iter().enumerate() {
526                unsafe { ffi::day_xaml_set_visible(*page, c_int::from(i == last)) };
527            }
528            unsafe {
529                ffi::day_xaml_nav_set_back_visible(
530                    s.nav_view,
531                    c_int::from(s.detail_pages.len() >= 2),
532                );
533            };
534            // Restore the (new) top page's title — without this a pop left the POPPED page's
535            // title in the NavigationView header until the next push.
536            if let Some((_, _, title)) = s.detail_pages.last() {
537                unsafe { ffi::day_xaml_nav_set_header(s.nav_view, cstr(title).as_ptr()) };
538            }
539        }
540    });
541}
542
543/// Show the selected resident page and hide its siblings — the non-stack counterpart to
544/// [`stack_sync`], and the same visibility pass `NavPatch::Select` performs. Run on every insert
545/// and remove as well, because a set of resident pages is built one page at a time and each new
546/// one covers the rest until something says which is current.
547fn select_sync(host: *mut c_void) {
548    // The pages are copied out and the borrow dropped before any FFI: `set_visible` lets XAML lay
549    // out, which raises SizeChanged, which day turns into a FrameChanged patch that comes straight
550    // back through this map and takes it mutably. Holding the borrow across the call is a
551    // RefCell double-borrow panic — and one that only shows on a layout that actually reflows,
552    // which is why it surfaced first in the RTL pass.
553    let pages: Vec<(*mut c_void, bool)> = NAV_STATE.with(|m| {
554        match m.borrow().get(&(host as usize)) {
555            Some(NavState::Split(s)) if !s.detail_pages.is_empty() => {
556                // A removed page can leave the recorded row past the end. The app sends its own
557                // selection right after, but between the two every page must not be hidden.
558                let shown = s.selected.min(s.detail_pages.len() - 1);
559                s.detail_pages
560                    .iter()
561                    .enumerate()
562                    .map(|(i, (page, _, _))| (*page, i == shown))
563                    .collect()
564            }
565            _ => Vec::new(),
566        }
567    });
568    for (page, visible) in pages {
569        unsafe { ffi::day_xaml_set_visible(page, c_int::from(visible)) };
570    }
571}
572
573/// Emit an event into day-core's queue (public for external Day Piece renderers).
574pub fn emit(id: NodeId, ev: Event) {
575    let sink = SINK.with(|s| s.borrow().clone());
576    if let Some(sink) = sink {
577        sink(id, ev);
578    }
579}
580
581fn apply_button_content(
582    h: *mut c_void,
583    title: &str,
584    icon: Option<&day_spec::Icon>,
585    icon_only: bool,
586) {
587    let (glyph, name, geometry) = match icon {
588        Some(day_spec::Icon::Symbol(s)) => (toolbar::glyph_for(*s), String::new(), String::new()),
589        Some(day_spec::Icon::Image(name)) => {
590            ("", name.clone(), vector_geometry(name).unwrap_or_default())
591        }
592        None => ("", String::new(), String::new()),
593    };
594    unsafe {
595        ffi::day_xaml_button_set_content(
596            h,
597            cstr(title).as_ptr(),
598            cstr(glyph).as_ptr(),
599            cstr(&name).as_ptr(),
600            cstr(&geometry).as_ptr(),
601            c_int::from(icon_only),
602        );
603    };
604}
605
606/// Hand a [`day_spec::props::ButtonStyleSpec`] to the shim, which styles the Button in place.
607/// The element stays a `Button`, so focus, keyboard activation and its automation peer are
608/// unaffected by the style.
609fn apply_button_style(h: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
610    use day_spec::props::ButtonStyleSpec as S;
611    let (kind, tint) = match style {
612        // A XAML Button pads a one-glyph title modestly; Compact takes the stock look.
613        S::Automatic | S::Compact => (0, day_spec::Ink::CLEAR),
614        S::Bordered => (1, day_spec::Ink::CLEAR),
615        S::Prominent => (2, day_spec::Ink::CLEAR),
616        S::Tinted(c) => (3, c),
617        // Borderless: no fill or border at rest, the template's hover and pressed fills kept.
618        S::Plain => (4, day_spec::Ink::CLEAR),
619    };
620    // The readable title color is computed from the fill on each side (docs/color.md).
621    paint_inks(
622        h,
623        InkSlot::ButtonTint,
624        tint.is_dynamic(),
625        move |h, palette| {
626            let fill = tint.resolve(palette);
627            // SAFETY: `h` is a live Button handle from `day_xaml_button_new`; the shim only reads
628            // the packed colors.
629            unsafe {
630                ffi::day_xaml_button_set_style(h, kind, argb(fill), argb(S::on_tint(fill)));
631            };
632        },
633    );
634}
635
636/// Send a label's runs across as a begin + one add per run (docs/text-runs.md).
637///
638/// Runs become `Inline`s in the one `TextBlock`, so the paragraph still wraps and selects as a
639/// unit. Flags pack the styling so each run is a single call with no marshaling.
640/// A label that shows an elided string ([`LABEL_ELIDE`]): the whole text, the mode, and the
641/// width it was last elided for (0 before its first frame).
642struct Elided {
643    full: String,
644    mode: day_spec::props::Truncation,
645    width: f64,
646}
647
648/// The paragraph attributes on a label (docs/text.md), from `realize` and from
649/// `LabelPatch::Paragraph`. `plain` is false for a label with runs, which keeps XAML's tail
650/// trimming whatever the mode (elision cuts characters and knows nothing about runs).
651fn apply_paragraph(
652    h: *mut c_void,
653    wraps: bool,
654    para: &day_spec::props::LabelParagraph,
655    text: &str,
656    plain: bool,
657) {
658    unsafe {
659        ffi::day_xaml_label_set_paragraph(
660            h,
661            c_int::from(wraps),
662            c_int::try_from(para.max_lines).unwrap_or(c_int::MAX),
663            para.letter_spacing,
664            para.line_height,
665        );
666    }
667    let one_line = !wraps || para.max_lines == 1;
668    let elides = plain && one_line && para.truncation != day_spec::props::Truncation::Tail;
669    let key = h as usize;
670    if elides {
671        let width = LABEL_ELIDE.with(|m| {
672            let mut m = m.borrow_mut();
673            let e = m.entry(key).or_insert_with(|| Elided {
674                full: text.to_owned(),
675                mode: para.truncation,
676                width: 0.0,
677            });
678            e.mode = para.truncation;
679            text.clone_into(&mut e.full);
680            e.width
681        });
682        if width > 0.0 {
683            elide_label(h, width);
684        }
685    } else if LABEL_ELIDE.with(|m| m.borrow_mut().remove(&key)).is_some() {
686        // Back to the platform's own trimming: show the whole text again.
687        let whole = cstr(text);
688        unsafe { ffi::day_xaml_label_show_elided(h, whole.as_ptr(), whole.as_ptr()) };
689    }
690}
691
692/// Show an elided label's text cut to `width` (a no-op for every other label).
693fn elide_label(h: *mut c_void, width: f64) {
694    let Some((full, mode)) = LABEL_ELIDE.with(|m| {
695        let mut m = m.borrow_mut();
696        let e = m.get_mut(&(h as usize))?;
697        e.width = width;
698        Some((e.full.clone(), e.mode))
699    }) else {
700        return;
701    };
702    let shown = day_spec::elide(&full, mode, width, |s| unsafe {
703        ffi::day_xaml_label_text_width(h, cstr(s).as_ptr())
704    });
705    unsafe { ffi::day_xaml_label_show_elided(h, cstr(&shown).as_ptr(), cstr(&full).as_ptr()) };
706}
707
708/// A label's text changed: the stored copies follow, and an elided label is cut again at its
709/// last width.
710fn note_label_text(h: *mut c_void, text: &str) {
711    if let Some(node) = LABEL_NODE.with(|m| m.borrow().get(&(h as usize)).copied()) {
712        LABEL_TEXT.with(|m| {
713            if let Some(t) = m.borrow_mut().get_mut(&node) {
714                text.clone_into(t);
715            }
716        });
717    }
718    let width = LABEL_ELIDE.with(|m| {
719        m.borrow_mut().get_mut(&(h as usize)).map(|e| {
720            text.clone_into(&mut e.full);
721            e.width
722        })
723    });
724    if let Some(width) = width
725        && width > 0.0
726    {
727        elide_label(h, width);
728    }
729}
730
731/// The label's current text, and whether it is plain (no runs), for a paragraph patch.
732fn label_text_of(h: *mut c_void) -> (String, bool) {
733    if let Some(full) = LABEL_ELIDE.with(|m| m.borrow().get(&(h as usize)).map(|e| e.full.clone()))
734    {
735        return (full, true);
736    }
737    // SAFETY: the shim returns a heap string (or null) released here through its own free.
738    let text = unsafe {
739        let p = ffi::day_xaml_label_text(h);
740        if p.is_null() {
741            String::new()
742        } else {
743            let s = CStr::from_ptr(p).to_string_lossy().into_owned();
744            ffi::day_xaml_string_free(p);
745            s
746        }
747    };
748    (
749        text,
750        !LABEL_RUNS.with(|m| m.borrow().contains(&(h as usize))),
751    )
752}
753
754/// A label's alignment as the shim's code: 0 leading, 1 center, 2 trailing, 3 justified, read in
755/// the app's direction (a label with no reading direction of its own is laid out in it).
756fn label_align_code(align: day_spec::props::TextAlign) -> c_int {
757    let rtl = day_core::layout_direction() == day_spec::LayoutDirection::Rtl;
758    match align {
759        day_spec::props::TextAlign::Center => 1,
760        day_spec::props::TextAlign::Trailing => {
761            if rtl {
762                0
763            } else {
764                2
765            }
766        }
767        day_spec::props::TextAlign::Leading => {
768            if rtl {
769                2
770            } else {
771                0
772            }
773        }
774        day_spec::props::TextAlign::Justified => 3,
775    }
776}
777
778/// `FontSpec::{small_caps, oldstyle_figures}` on a label.
779fn apply_label_features(h: *mut c_void, f: day_spec::FontSpec) {
780    unsafe {
781        ffi::day_xaml_label_set_features(
782            h,
783            c_int::from(f.small_caps),
784            c_int::from(f.oldstyle_figures),
785        );
786    }
787}
788
789/// A selection-reporting label's selection changed (`day_xaml_label_report_selection`):
790/// UTF-16 offsets into the text it displays, converted to byte offsets for
791/// `Event::TextSelected`.
792extern "C" fn on_label_selection(id: u64, start: c_int, end: c_int) {
793    ffi_guard::contain((), || {
794        let text = LABEL_TEXT
795            .with(|m| m.borrow().get(&id).cloned())
796            .unwrap_or_default();
797        let to_byte = |units: c_int| utf16_to_byte(&text, usize::try_from(units).unwrap_or(0));
798        emit(
799            NodeId(id),
800            Event::TextSelected {
801                start: to_byte(start),
802                end: to_byte(end),
803            },
804        );
805    });
806}
807
808/// The byte offset in `text` of the character boundary at `units` UTF-16 code units, clamped
809/// to the text.
810fn utf16_to_byte(text: &str, units: usize) -> usize {
811    let mut seen = 0usize;
812    for (byte, ch) in text.char_indices() {
813        if seen >= units {
814            return byte;
815        }
816        seen += ch.len_utf16();
817    }
818    text.len()
819}
820
821#[cfg(test)]
822mod label_text_tests {
823    use super::*;
824
825    #[test]
826    fn utf16_offsets_land_on_char_boundaries() {
827        let text = "a\u{e9}\u{1f600}b";
828        assert_eq!(utf16_to_byte(text, 0), 0);
829        assert_eq!(utf16_to_byte(text, 1), 1);
830        assert_eq!(utf16_to_byte(text, 2), 3);
831        // The emoji is two UTF-16 units and four bytes.
832        assert_eq!(utf16_to_byte(text, 4), 7);
833        assert_eq!(utf16_to_byte(text, 5), 8);
834        assert_eq!(utf16_to_byte(text, 99), 8);
835    }
836
837    #[test]
838    fn justified_has_its_own_code() {
839        assert_eq!(label_align_code(day_spec::props::TextAlign::Justified), 3);
840        assert_eq!(label_align_code(day_spec::props::TextAlign::Center), 1);
841    }
842}
843
844/// An image's tint, kept for the appearance when it follows it; the shim already shows it.
845fn keep_image_tint(h: *mut c_void, tint: Option<day_spec::Ink>) {
846    let ink = tint.unwrap_or(day_spec::Ink::CLEAR);
847    keep_inks(
848        h,
849        InkSlot::ImageTint,
850        ink.is_dynamic(),
851        move |h, palette| {
852            // SAFETY: the handle is a live image (see `repaint_inks`), on the UI thread.
853            unsafe { ffi::day_xaml_image_retint(h, ink_argb(ink, palette)) };
854        },
855    );
856}
857
858/// A label's text color, kept for the appearance when it follows it.
859fn paint_label_color(h: *mut c_void, ink: day_spec::Ink) {
860    paint_inks(
861        h,
862        InkSlot::LabelColor,
863        ink.is_dynamic(),
864        move |h, palette| {
865            // SAFETY: the handle is a live label (see `repaint_inks`), on the UI thread.
866            unsafe { ffi::day_xaml_label_set_color(h, ink_argb(ink, palette)) };
867        },
868    );
869}
870
871/// Show a label's runs, and keep them for the appearance when a run's color follows it.
872fn set_label_runs(h: *mut c_void, node: u64, text: &str, runs: &[day_spec::TextRun]) {
873    let dynamic = runs.iter().any(|r| {
874        r.color.is_some_and(day_spec::Ink::is_dynamic)
875            || r.background.is_some_and(day_spec::Ink::is_dynamic)
876    });
877    if dynamic {
878        let (text, runs) = (text.to_owned(), runs.to_vec());
879        paint_inks(h, InkSlot::LabelRuns, true, move |h, palette| {
880            apply_label_runs(h, node, &text, &runs, palette);
881        });
882    } else {
883        keep_inks(h, InkSlot::LabelRuns, false, |_, _| {});
884        apply_label_runs(h, node, text, runs, &day_spec::Palette::current());
885    }
886}
887
888/// Send a label's runs, their colors resolved against `palette`.
889fn apply_label_runs(
890    h: *mut c_void,
891    node: u64,
892    text: &str,
893    runs: &[day_spec::TextRun],
894    palette: &day_spec::Palette,
895) {
896    LABEL_RUNS.with(|m| {
897        if runs.is_empty() {
898            m.borrow_mut().remove(&(h as usize));
899        } else {
900            m.borrow_mut().insert(h as usize);
901        }
902    });
903    if runs.is_empty() {
904        // The plain setter also clears the Inlines, so a label losing its runs stops rendering
905        // the styled version.
906        unsafe { ffi::day_xaml_label_set_text(h, cstr(text).as_ptr()) };
907        return;
908    }
909    unsafe { ffi::day_xaml_label_runs_begin(h, node) };
910    let mut at = 0usize;
911    let add = |slice: &str, run: Option<&day_spec::TextRun>| {
912        let mut flags = 0i32;
913        let mut argb = 0u32;
914        let mut bg_argb = 0u32;
915        let mut scale_permille = 1000i32;
916        let mut link = String::new();
917        if let Some(r) = run {
918            scale_permille = (r.font.scale * 1000.0).round() as i32;
919            if r.font
920                .weight
921                .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
922            {
923                flags |= 1;
924            }
925            if r.font.italic {
926                flags |= 2;
927            }
928            if r.font.monospace {
929                flags |= 4;
930            }
931            if r.strikethrough.is_some() {
932                flags |= 8;
933            }
934            if let Some(c) = r.color.map(|c| c.resolve(palette)) {
935                flags |= 16;
936                let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
937                argb = (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b);
938            }
939            let pack = |c: day_spec::Color| {
940                let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
941                (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)
942            };
943            if let Some(c) = r.background.map(|c| c.resolve(palette)) {
944                flags |= 32;
945                bg_argb = pack(c);
946            }
947            if r.underline.is_some() {
948                flags |= 64;
949            }
950            if r.font.small_caps {
951                flags |= 128;
952            }
953            if r.font.oldstyle_figures {
954                flags |= 256;
955            }
956            if let Some(u) = r.link.as_deref() {
957                link = u.to_string();
958            }
959        }
960        unsafe {
961            ffi::day_xaml_label_runs_add(
962                h,
963                cstr(slice).as_ptr(),
964                flags,
965                argb,
966                bg_argb,
967                scale_permille,
968                cstr(&link).as_ptr(),
969            );
970        };
971    };
972    for r in runs {
973        let Some(styled) = text.get(r.range.clone()) else {
974            continue;
975        };
976        if r.range.start > at
977            && let Some(plain) = text.get(at..r.range.start)
978        {
979            add(plain, None);
980        }
981        add(styled, Some(r));
982        at = r.range.end;
983    }
984    if let Some(tail) = text.get(at..) {
985        add(tail, None);
986    }
987}
988
989thread_local! {
990    /// `BitmapId` → what the container's header stated (docs/images.md). Only the METADATA lives
991    /// here; the encoded bytes are the shim's, held under the same id until `release_image`.
992    static BITMAP_INFO: std::cell::RefCell<std::collections::HashMap<u64, day_spec::BitmapInfo>> =
993        std::cell::RefCell::new(std::collections::HashMap::new());
994}
995
996fn cstr(s: &str) -> CString {
997    // An interior NUL must not blank the whole string — a label, a menu item, a window title
998    // would silently vanish. Strip the NULs and keep the visible text.
999    CString::new(s).unwrap_or_else(|_| CString::new(s.replace('\0', "")).unwrap_or_default())
1000}
1001
1002/// A styled run's link was clicked (docs/text-runs.md). The Hyperlink carries no `NavigateUri`,
1003/// so nothing has opened anything yet: the label's `.on_link()` decides.
1004extern "C" fn on_link(id: u64, url: *const c_char) {
1005    ffi_guard::contain((), || {
1006        let url = unsafe { CStr::from_ptr(url) }
1007            .to_string_lossy()
1008            .into_owned();
1009        emit(NodeId(id), Event::LinkActivated(url));
1010    });
1011}
1012
1013thread_local! {
1014    /// Menu buttons (`set_button_menu`, docs/menus.md "Menu buttons"): node → (button handle,
1015    /// provider). The click reports only the node, and the flyout needs the element to anchor
1016    /// to. Entries leave with their button in `release`.
1017    static BUTTON_MENUS: RefCell<HashMap<u64, (usize, day_spec::ContextMenuFn)>> =
1018        RefCell::new(HashMap::new());
1019}
1020
1021/// What a press on node `id` does when it may be a menu button.
1022#[derive(Debug, PartialEq)]
1023enum ButtonMenu {
1024    /// No menu is registered: an ordinary press.
1025    NotAMenuButton,
1026    /// A menu button whose menu is empty, or whose provider released the button.
1027    Nothing,
1028    /// Show these items under this (still registered) button element.
1029    Show(usize, Vec<day_spec::MenuItem>),
1030}
1031
1032/// Ask the provider for node `id`'s menu. The provider is app code: a signal it writes can
1033/// rebuild the tree synchronously, and `release` then drops this button's entry and the shim
1034/// frees the element. The registry is read again after the provider returns, and only a button
1035/// that is still the one registered for `id` is handed back (`day_spec::resolve_button_menu`).
1036fn button_menu_for(id: u64) -> ButtonMenu {
1037    let Some((button, f)) = BUTTON_MENUS.with(|m| m.borrow().get(&id).cloned()) else {
1038        return ButtonMenu::NotAMenuButton;
1039    };
1040    let still_registered =
1041        || BUTTON_MENUS.with(|m| m.borrow().get(&id).is_some_and(|(b, _)| *b == button));
1042    match day_spec::resolve_button_menu(&f, still_registered) {
1043        Some(items) => ButtonMenu::Show(button, items),
1044        None => ButtonMenu::Nothing,
1045    }
1046}
1047
1048extern "C" fn on_press(id: u64) {
1049    ffi_guard::contain((), || {
1050        // A menu button's click opens its menu instead of reporting a press. The provider is
1051        // app code; XAML's Click runs from the message loop, outside any day-core borrow.
1052        match button_menu_for(id) {
1053            ButtonMenu::NotAMenuButton => emit(NodeId(id), Event::Pressed),
1054            ButtonMenu::Nothing => {}
1055            ButtonMenu::Show(button, items) => {
1056                let mut spec = String::new();
1057                serialize_menu_xaml(&items, &mut spec);
1058                // SAFETY: `button_menu_for` re-read the registry after the provider (app code)
1059                // returned, and `release` drops a button's entry before the shim frees the
1060                // element, so `button` is still the live element registered for this node.
1061                unsafe {
1062                    ffi::day_xaml_show_button_menu(button as *mut c_void, cstr(&spec).as_ptr());
1063                };
1064            }
1065        }
1066    });
1067}
1068extern "C" fn on_toggle(id: u64, on: c_int) {
1069    ffi_guard::contain((), || emit(NodeId(id), Event::ToggleChanged(on != 0)));
1070}
1071extern "C" fn on_text(id: u64, s: *const c_char) {
1072    ffi_guard::contain((), || {
1073        let text = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1074        // The late echo of day's own write (an address bar's completion) is not typing.
1075        let echo = TEXT_FIELD_ECHO.with(|m| {
1076            let mut m = m.borrow_mut();
1077            if m.get(&id) == Some(&text) {
1078                return true;
1079            }
1080            m.remove(&id);
1081            false
1082        });
1083        if echo {
1084            return;
1085        }
1086        emit(NodeId(id), Event::TextChanged(text));
1087    });
1088}
1089extern "C" fn on_slider(id: u64, v: f64, committed: c_int) {
1090    // XAML's Slider is driven in the app's real f64 units, so its Value is the event value as-is.
1091    // The live value always; the settled one additionally, so a drag records once (the shim
1092    // decides which is which — see `day_xaml_slider_new`).
1093    ffi_guard::contain((), || {
1094        emit(NodeId(id), Event::ValueChanged(v));
1095        if committed != 0 {
1096            emit(NodeId(id), Event::ValueCommitted(v));
1097        }
1098    });
1099}
1100/// Whether this node has a `Decorate::on_key` handler (docs/menus.md). The shim asks before it
1101/// marks a key handled, so an arrow nobody wanted stays XAML's — its own directional focus
1102/// navigation still moves between controls.
1103#[cfg(feature = "winui")]
1104extern "C" fn on_key_handled(id: u64) -> c_int {
1105    ffi_guard::contain(0, || c_int::from(day_spec::keys::handled(NodeId(id))))
1106}
1107
1108/// Whether this node took the whole keyboard (`Decorate::keyboard`, docs/menus.md "The full
1109/// route"): the shim asks before it names a letter.
1110#[cfg(feature = "winui")]
1111extern "C" fn on_text_handled(id: u64) -> c_int {
1112    ffi_guard::contain(0, || c_int::from(day_spec::keys::text(NodeId(id))))
1113}
1114
1115/// A key that reached a focused canvas or focusable container (docs/menus.md): `key` is the day
1116/// name, `text` what it typed on the full route (null for a key that typed nothing),
1117/// `modifiers` the [`day_spec::Modifiers`] mask with the phase bits above it. Both strings are
1118/// valid for the call.
1119#[cfg(feature = "winui")]
1120extern "C" fn on_key(id: u64, key: *const c_char, text: *const c_char, modifiers: c_int) {
1121    ffi_guard::contain((), || {
1122        if key.is_null() {
1123            return;
1124        }
1125        // SAFETY: the shim passes NUL-terminated UTF-8 strings (or null) that outlive the call.
1126        let read = |p: *const c_char| unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned();
1127        let key = read(key);
1128        // The low byte is the modifier mask; bits 8 and 9 the phase (docs/menus.md "Key phases").
1129        let phase = day_spec::KeyPhase::from_wire(f64::from(modifiers));
1130        let modifiers = (modifiers & 0xff) as u8;
1131        let event = if text.is_null() {
1132            day_spec::KeyEvent::named(key, modifiers)
1133        } else {
1134            day_spec::KeyEvent::typed_by(key, read(text), modifiers)
1135        };
1136        emit(NodeId(id), Event::Key(event.with_phase(phase)));
1137    });
1138}
1139
1140/// A text field's Up, Down or Escape (docs/textfield.md "Keys"): reported, and claimed, when
1141/// the field has a key handler and no modifier is held; repeats and the release of a claimed
1142/// key arrive with their phase bits above the modifier mask.
1143extern "C" fn on_field_key(id: u64, name: *const c_char, modifiers: c_int) -> c_int {
1144    ffi_guard::contain(0, || {
1145        if name.is_null() {
1146            return 0;
1147        }
1148        // SAFETY: the shim passes one of its own NUL-terminated literals.
1149        let name = unsafe { CStr::from_ptr(name) }.to_string_lossy();
1150        let node = NodeId(id);
1151        let phase = day_spec::KeyPhase::from_wire(f64::from(modifiers));
1152        let mods = (modifiers & 0xff) as u8;
1153        // The release of a claimed key is claimed with it: the shim only asks for those.
1154        if phase != day_spec::KeyPhase::Up && !day_spec::keys::field_claims(node, &name, mods) {
1155            return 0;
1156        }
1157        emit(
1158            node,
1159            Event::Key(day_spec::KeyEvent::named(name, 0).with_phase(phase)),
1160        );
1161        1
1162    })
1163}
1164
1165/// Focus callback from the shim (docs/focus.md). kind: 0 = lost, 1 = gained, 2 = submitted.
1166extern "C" fn on_focus(id: u64, kind: c_int) {
1167    ffi_guard::contain((), || {
1168        let ev = match kind {
1169            2 => Event::Submitted,
1170            k => Event::FocusChanged(k != 0),
1171        };
1172        emit(NodeId(id), ev);
1173    });
1174}
1175
1176/// A `0.0..=1.0` fraction as `ProgressBar` ticks (0..1000), clamped.
1177fn progress_ticks(fraction: f64) -> c_int {
1178    (fraction.clamp(0.0, 1.0) * 1000.0).round() as c_int
1179}
1180
1181/// Renderers registered by external Day Piece crates (§8.2).
1182#[distributed_slice]
1183pub static RENDERERS: [fn() -> Renderer<Xaml>];
1184
1185/// A live secondary window (docs/windows.md): the shim's `SecWindow` plus the day content
1186/// root the tree adopted.
1187struct XamlWin {
1188    win: *mut c_void,
1189    content: *mut c_void,
1190    /// A Preferences panel, which carries no menu bar (docs/windows.md). Recorded because the
1191    /// app menu is re-installed on a locale change, and that pass walks every open window — it
1192    /// would put a File/Edit/View bar back on the settings panel.
1193    menuless: bool,
1194}
1195
1196pub struct Xaml {
1197    registry: Registry<Xaml>,
1198    window: *mut c_void,
1199    secondary: Vec<XamlWin>,
1200    /// The app menu's serialized spec, replayed into each window that opens after it was set
1201    /// (docs/menus.md): one menu for the app, but Windows draws it per window.
1202    menu_spec: String,
1203    /// The primary window's root container. Held so `release` can recognize it and destroy the
1204    /// host — the primary is an ordinary window now (docs/windows.md close policy), torn down
1205    /// on the same released-root signal as any other.
1206    primary_root: *mut c_void,
1207}
1208
1209impl Xaml {
1210    /// The shim-side window token owning `h` — the primary window, or the secondary whose content
1211    /// canvas this is. `None` when the handle belongs to no window day opened, which is how a
1212    /// chrome call for an unknown host is dropped rather than landing on the wrong window.
1213    fn window_token(&self, h: &WinHandle) -> Option<*mut c_void> {
1214        if let Some(w) = self.secondary.iter().find(|w| w.content == h.0) {
1215            return Some(w.win);
1216        }
1217        (!self.window.is_null()).then_some(self.window)
1218    }
1219}
1220
1221impl Xaml {
1222    #[must_use]
1223    pub fn new() -> Self {
1224        let mut registry = Registry::default();
1225        for f in RENDERERS {
1226            registry.register(f());
1227        }
1228        // Data resources (§18.3): no custom opener registered. Unlike Android/GTK/Qt/ArkUI — whose
1229        // bytes live inside a packaged store (AAssetManager/GResource/QResource/rawfile) and so need
1230        // a backend opener — an unpackaged Win32 app reaches loose files next to its exe directly.
1231        // `day build` stages data under `assets/` there, which is exactly what day-spec's default
1232        // opener mmaps (env `DAY_ASSET_ROOT`, then exe-relative `assets/`), so `resource("name")`
1233        // works with zero backend wiring. A custom opener would only earn its keep for embedded
1234        // RCDATA, which this backend does not use.
1235        Xaml {
1236            registry,
1237            window: std::ptr::null_mut(),
1238            secondary: Vec::new(),
1239            menu_spec: String::new(),
1240            primary_root: std::ptr::null_mut(),
1241        }
1242    }
1243}
1244
1245impl Default for Xaml {
1246    fn default() -> Self {
1247        Self::new()
1248    }
1249}
1250
1251/// Day font intents → (XAML `FontSize` in DIPs, bold).
1252/// Point size + the style's inherent weight for a logical [`Font`]. XAML's `TextBlock.FontSize`
1253/// auto-scales with the OS text-scale-factor (Settings ▸ Accessibility ▸ Text size), so these sizes
1254/// honor accessibility.
1255///
1256/// The sizes are the Windows 11 (Fluent) type ramp WinUI's own text styles use, so a Day label
1257/// sits beside the controls' text as a native one would: Caption 12, Body 14 (the controls'
1258/// `ControlContentThemeFontSize`), `BodyStrong` 14 semibold, `BodyLarge` 18, Subtitle 20 semibold,
1259/// Title 28 semibold. Fluent has nothing below 12 px; Caption2 alone goes to 11, as the
1260/// smallest Windows UI text (the taskbar clock's) does.
1261fn xaml_style(f: Font) -> (f64, day_spec::FontWeight) {
1262    use day_spec::FontWeight::{Regular, Semibold};
1263    match f {
1264        Font::LargeTitle => (28.0, Semibold), // TitleTextBlockStyle
1265        Font::Title => (20.0, Semibold),      // SubtitleTextBlockStyle
1266        Font::Title2 => (18.0, Regular),      // BodyLargeTextBlockStyle
1267        Font::Title3 => (16.0, Semibold),
1268        Font::Headline => (14.0, Semibold), // BodyStrongTextBlockStyle
1269        Font::Subheadline | Font::Footnote | Font::Caption => (12.0, Regular), // CaptionTextBlockStyle
1270        Font::Body => (14.0, Regular),                                         // BodyTextBlockStyle
1271        Font::Callout => (13.0, Regular),
1272        Font::Caption2 => (11.0, Regular),
1273        Font::System(pt) | Font::Custom(_, pt) => (pt, Regular),
1274    }
1275}
1276
1277/// Apply a `Font::Custom` family on top of `day_xaml_label_set_font` (which set size/weight).
1278/// Unpackaged Win32 XAML can't load a font by file path — a raw path isn't a valid `Uri` and
1279/// `file://` is rejected (exactly like `BitmapImage`; see the image-loading path). The one font
1280/// location system XAML *does* resolve is `ms-appx:///`, which maps to the executable's directory
1281/// and its subtree, so `stage_bundled_fonts` copies each font under `<exe>/fonts/` and here we
1282/// reference it as `ms-appx:///fonts/<file>#<family>`. Resolution parses font name tables, so it is
1283/// cached per family; an unknown family logs once and leaves the system font in place.
1284fn apply_custom_family(h: *mut c_void, spec: day_spec::FontSpec) {
1285    let Font::Custom(family, _) = spec.style else {
1286        return;
1287    };
1288
1289    RESOLVED.with(|cache| {
1290        let mut cache = cache.borrow_mut();
1291        let entry = cache.entry(family).or_insert_with(|| {
1292            if let Some(file) = day_spec::fonts::resolve_font_file(family)
1293                .as_deref()
1294                .and_then(|p| p.file_name())
1295                .and_then(|n| n.to_str())
1296            {
1297                Some(cstr(&format!("ms-appx:///fonts/{file}#{family}")))
1298            } else {
1299                log::warn!(
1300                    "unknown font family {family:?} — falling back to the system font \
1301                     (is the file in the project's fonts/ directory?)"
1302                );
1303                None
1304            }
1305        });
1306        if let Some(s) = entry {
1307            unsafe { ffi::day_xaml_label_set_font_family(h, s.as_ptr()) };
1308        }
1309    });
1310}
1311
1312/// `Win2D` resolves bundled fonts through file URIs. Unlike XAML's `FontFamily`, its ms-appx
1313/// resolver requires package identity and throws `ERROR_NOT_FOUND` in an unpackaged app.
1314/// Use Windows' file-URI conversion to match the `StorageFile` resolver used by `Win2D`.
1315#[cfg(feature = "winui")]
1316fn win2d_font_family(path: &std::path::Path, family: &str) -> Option<String> {
1317    use std::os::windows::ffi::OsStrExt;
1318
1319    #[link(name = "shlwapi")]
1320    unsafe extern "system" {
1321        fn UrlCreateFromPathW(path: *const u16, url: *mut u16, len: *mut u32, flags: u32) -> i32;
1322    }
1323
1324    let path = std::path::absolute(path).ok()?;
1325    let path = path.to_str()?;
1326    // The shell converter does not accept the verbatim prefixes returned by canonicalize.
1327    let path = if let Some(unc) = path.strip_prefix(r"\\?\UNC\") {
1328        format!(r"\\{unc}")
1329    } else {
1330        path.strip_prefix(r"\\?\").unwrap_or(path).to_string()
1331    };
1332    let path: Vec<u16> = std::ffi::OsStr::new(&path)
1333        .encode_wide()
1334        .chain(Some(0))
1335        .collect();
1336    let mut url = vec![0u16; path.len() * 3 + 16];
1337    let mut len = u32::try_from(url.len()).ok()?;
1338    let hr = unsafe { UrlCreateFromPathW(path.as_ptr(), url.as_mut_ptr(), &raw mut len, 0) };
1339    if hr < 0 {
1340        return None;
1341    }
1342    let uri = String::from_utf16(&url[..len as usize]).ok()?;
1343    Some(format!("{uri}#{family}"))
1344}
1345
1346#[cfg(all(test, feature = "winui"))]
1347#[test]
1348fn win2d_font_paths_are_windows_file_uris() {
1349    for (path, expected) in [
1350        (
1351            r"C:\Font fixtures\é #100%.ttf",
1352            "file:///C:/Font%20fixtures/%E9%20%23100%25.ttf#Pacifico",
1353        ),
1354        (
1355            r"\\server\fonts\Pacifico.ttf",
1356            "file://server/fonts/Pacifico.ttf#Pacifico",
1357        ),
1358        (
1359            r"\\?\C:\fonts\Pacifico.ttf",
1360            "file:///C:/fonts/Pacifico.ttf#Pacifico",
1361        ),
1362        (
1363            r"\\?\UNC\server\fonts\Pacifico.ttf",
1364            "file://server/fonts/Pacifico.ttf#Pacifico",
1365        ),
1366    ] {
1367        assert_eq!(
1368            win2d_font_family(std::path::Path::new(path), "Pacifico").as_deref(),
1369            Some(expected)
1370        );
1371    }
1372}
1373
1374/// A bundled canvas family names its file as well as its family, so it cannot silently fall
1375/// back to a system face. `Win2D` uses file URIs; the deprecated XAML renderer uses ms-appx.
1376/// System families stay as bare names. Cached because resolution parses font name tables.
1377fn canvas_family(family: &str) -> String {
1378    thread_local! {
1379        static CANVAS_FAMILIES: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
1380    }
1381    CANVAS_FAMILIES.with(|cache| {
1382        cache
1383            .borrow_mut()
1384            .entry(family.to_string())
1385            .or_insert_with(|| {
1386                let Some(path) = day_spec::fonts::resolve_font_file(family) else {
1387                    return family.to_string();
1388                };
1389                #[cfg(feature = "winui")]
1390                {
1391                    win2d_font_family(&path, family).unwrap_or_else(|| family.to_string())
1392                }
1393                #[cfg(not(feature = "winui"))]
1394                {
1395                    path.file_name()
1396                        .and_then(|n| n.to_str())
1397                        .map(|file| format!("ms-appx:///fonts/{file}#{family}"))
1398                        .unwrap_or_else(|| family.to_string())
1399                }
1400            })
1401            .clone()
1402    })
1403}
1404
1405/// The display list with every text font's family in the form the canvas renderer resolves
1406/// ([`canvas_family`]); ops without a named family are untouched.
1407fn resolve_canvas_fonts(ops: &[DrawOp]) -> Vec<DrawOp> {
1408    ops.iter()
1409        .cloned()
1410        .map(|op| match op {
1411            DrawOp::Text {
1412                text,
1413                at,
1414                size,
1415                color,
1416                anchor,
1417                font,
1418            } if font.family.is_some() => DrawOp::Text {
1419                text,
1420                at,
1421                size,
1422                color,
1423                anchor,
1424                font: day_spec::CanvasFont {
1425                    family: font.family.as_deref().map(canvas_family),
1426                    weight: font.weight,
1427                    italic: font.italic,
1428                },
1429            },
1430            op => op,
1431        })
1432        .collect()
1433}
1434
1435/// Stage the bundled font files (§18.4) next to the executable so XAML can load them. Unpackaged
1436/// system XAML only resolves fonts under `ms-appx:///` (the exe directory and its subtree), so copy
1437/// every `DAY_FONT_ROOT` font into `<exe>/fonts/` — a no-op when packed, where `day pack` already
1438/// ships them there (`font_dir()` returns that same directory, so src == dst). `apply_custom_family`
1439/// then references each as `ms-appx:///fonts/<file>#<family>`.
1440fn stage_bundled_fonts() {
1441    let Some(dir) = std::env::current_exe()
1442        .ok()
1443        .and_then(|exe| exe.parent().map(|d| d.join("fonts")))
1444    else {
1445        return;
1446    };
1447    for src in day_spec::fonts::bundled_fonts() {
1448        let Some(dst) = src.file_name().map(|n| dir.join(n)) else {
1449            continue;
1450        };
1451        if src == dst {
1452            continue; // already staged next to the exe (packed apps)
1453        }
1454        if let Err(e) =
1455            std::fs::create_dir_all(&dir).and_then(|()| std::fs::copy(&src, &dst).map(|_| ()))
1456        {
1457            log::warn!(
1458                "day-toolkit-winui: could not stage bundled font {}: {e}",
1459                src.display()
1460            );
1461        }
1462    }
1463}
1464
1465/// Stage bundled images (`DAY_IMAGE_ROOT`, plus the vector raster cache `DAY_VECTOR_RASTER_ROOT` —
1466/// docs/vectors.md) next to the exe under `images/` so a `BitmapIcon` can load them via
1467/// `ms-appx:///images/<file>` (same unpackaged-islands workaround as the fonts). Only nav
1468/// icons need this today (regular `image()` loads bytes via a stream); a no-op when packed
1469/// (`day pack` already merges both trees into the exe-relative `images/`) or when neither
1470/// root is set.
1471fn stage_bundled_images() {
1472    let Some(dst_dir) = std::env::current_exe()
1473        .ok()
1474        .and_then(|exe| exe.parent().map(|d| d.join("images")))
1475    else {
1476        return;
1477    };
1478    let src_dirs: Vec<std::path::PathBuf> = ["DAY_IMAGE_ROOT", "DAY_VECTOR_RASTER_ROOT"]
1479        .iter()
1480        .filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from))
1481        .collect();
1482    for src_dir in src_dirs {
1483        let Ok(entries) = std::fs::read_dir(&src_dir) else {
1484            continue;
1485        };
1486        for entry in entries.flatten() {
1487            let src = entry.path();
1488            if !src.is_file() {
1489                continue;
1490            }
1491            let Some(dst) = src.file_name().map(|n| dst_dir.join(n)) else {
1492                continue;
1493            };
1494            if src == dst {
1495                continue;
1496            }
1497            let _ = std::fs::create_dir_all(&dst_dir)
1498                .and_then(|()| std::fs::copy(&src, &dst).map(|_| ()));
1499        }
1500    }
1501}
1502
1503/// Day weight → Windows.UI.Text.FontWeight numeric value (Thin=100 … Black=900).
1504fn xaml_weight(w: day_spec::FontWeight) -> c_int {
1505    use day_spec::FontWeight as W;
1506    match w {
1507        W::Thin => 100,
1508        W::UltraLight => 200,
1509        W::Light => 300,
1510        W::Regular => 400,
1511        W::Medium => 500,
1512        W::Semibold => 600,
1513        W::Bold => 700,
1514        W::Heavy => 800,
1515        W::Black => 900,
1516    }
1517}
1518
1519/// (point size, `FontWeight` numeric, italic) for the C++/WinRT shim.
1520fn font_params(spec: day_spec::FontSpec) -> (f64, c_int, c_int, c_int) {
1521    let (pt, inherent) = xaml_style(spec.style);
1522    let weight = xaml_weight(spec.weight.unwrap_or(inherent));
1523    (
1524        pt,
1525        weight,
1526        c_int::from(spec.italic),
1527        c_int::from(spec.tabular),
1528    )
1529}
1530
1531/// Natural (unconstrained) desired size from the shim's XAML Measure.
1532fn natural(h: *mut c_void) -> Size {
1533    let mut w = 0.0;
1534    let mut hh = 0.0;
1535    unsafe { ffi::day_xaml_measure(h, -1.0, -1.0, &raw mut w, &raw mut hh) };
1536    Size::new(w, hh)
1537}
1538
1539// ---- menus (docs/menus.md) -------------------------------------------------
1540
1541extern "C" fn on_menu_action(id: u64) {
1542    ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::MenuAction(id)));
1543}
1544
1545/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
1546/// `const` so `day::require_lifecycle!` can reject unsupported phases at compile time.
1547#[must_use]
1548pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
1549    phase.is_universal()
1550}
1551
1552/// Phase codes (from the shim's `WndProc`) → day lifecycle events.
1553extern "C" fn on_lifecycle(code: c_int) {
1554    use day_spec::Lifecycle::{DidBecomeActive, WillResignActive, WillTerminate};
1555    ffi_guard::contain((), || {
1556        let phase = match code {
1557            2 => DidBecomeActive,
1558            3 => WillResignActive,
1559            7 => WillTerminate,
1560            _ => return,
1561        };
1562        emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase));
1563    });
1564}
1565
1566fn win_role_label(role: day_spec::MenuRole) -> String {
1567    use day_spec::MenuRole::{
1568        About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
1569        Paste, Preferences, Quit, Redo, SelectAll, Undo,
1570    };
1571    match role {
1572        Cut => "Cut",
1573        Copy => "Copy",
1574        Paste => "Paste",
1575        SelectAll => "Select All",
1576        Undo => "Undo",
1577        Redo => "Redo",
1578        Delete => "Delete",
1579        About => "About",
1580        Quit => "Exit",
1581        Preferences => "Settings",
1582        Minimize => "Minimize",
1583        CloseWindow => "Close",
1584        Fullscreen => "Full Screen",
1585        NewWindow => "New Window",
1586        CheckForUpdates => "Check for Updates…",
1587    }
1588    .to_string()
1589}
1590
1591/// Standard (keycode, modifier-bitmask) for a role: bit0 Control, bit1 Shift, bit2 Alt.
1592fn win_role_keymods(role: day_spec::MenuRole) -> (i32, i32) {
1593    use day_spec::MenuRole::{CloseWindow, Copy, Cut, NewWindow, Paste, Redo, SelectAll, Undo};
1594    match role {
1595        Cut => (i32::from(b'X'), 1),
1596        Copy => (i32::from(b'C'), 1),
1597        Paste => (i32::from(b'V'), 1),
1598        SelectAll => (i32::from(b'A'), 1),
1599        Undo => (i32::from(b'Z'), 1),
1600        Redo => (i32::from(b'Y'), 1),
1601        NewWindow => (i32::from(b'N'), 1),
1602        CloseWindow => (i32::from(b'W'), 1),
1603        _ => (0, 0),
1604    }
1605}
1606
1607fn win_mods(sc: &day_spec::Shortcut) -> i32 {
1608    let mut m = 0;
1609    if sc.primary || sc.control {
1610        m |= 1; // Control is the primary modifier on Windows
1611    }
1612    if sc.shift {
1613        m |= 2;
1614    }
1615    if sc.alt {
1616        m |= 4;
1617    }
1618    m
1619}
1620
1621/// Windows `VirtualKey` code for a shortcut key string (0 = none/unmapped).
1622fn win_keycode(key: &str) -> i32 {
1623    let mut chars = key.chars();
1624    if let (Some(c), None) = (chars.next(), chars.clone().next()) {
1625        if c.is_ascii_alphabetic() {
1626            return c.to_ascii_uppercase() as i32;
1627        }
1628        if c.is_ascii_digit() {
1629            return c as i32;
1630        }
1631        return match c {
1632            ',' => 0xBC,
1633            '.' => 0xBE,
1634            '-' => 0xBD,
1635            '=' => 0xBB,
1636            '/' => 0xBF,
1637            _ => 0,
1638        };
1639    }
1640    match key {
1641        "Return" | "Enter" => 0x0D,
1642        "Delete" | "Del" => 0x2E,
1643        "Space" => 0x20,
1644        "Escape" | "Esc" => 0x1B,
1645        "Tab" => 0x09,
1646        "Backspace" | "Back" => 0x08,
1647        "Left" => 0x25,
1648        "Up" => 0x26,
1649        "Right" => 0x27,
1650        "Down" => 0x28,
1651        "Home" => 0x24,
1652        "End" => 0x23,
1653        _ => key
1654            .strip_prefix('F')
1655            .and_then(|n| n.parse::<i32>().ok())
1656            .filter(|n| (1..=12).contains(n))
1657            .map_or(0, |n| 0x70 + (n - 1)),
1658    }
1659}
1660
1661/// Serialize the day-neutral tree to the shim's line format:
1662/// `kind \t action \t role \t key \t mods \t enabled \t label \t glyph \t checked`
1663/// (kinds A/R/S/E/`-`). Fields are APPENDED, never reordered, so a shim reading only the first
1664/// seven is unaffected by the two that came later.
1665fn serialize_menu_xaml(items: &[day_spec::MenuItem], out: &mut String) {
1666    fn clean(s: &str) -> String {
1667        s.replace(['\t', '\n'], " ")
1668    }
1669    for item in items {
1670        match item {
1671            day_spec::MenuItem::Separator => out.push_str("-\t0\t-1\t0\t0\t1\t\n"),
1672            day_spec::MenuItem::Submenu { label, items, .. } => {
1673                let _ = writeln!(out, "S\t0\t-1\t0\t0\t1\t{}", clean(label));
1674                serialize_menu_xaml(items, out);
1675                out.push_str("E\t0\t-1\t0\t0\t1\t\n");
1676            }
1677            day_spec::MenuItem::Action {
1678                action,
1679                label,
1680                shortcut,
1681                enabled,
1682                checked,
1683                role,
1684                icon,
1685                ..
1686            } => {
1687                let en = i32::from(*enabled);
1688                // Label/shortcut fall back to the role's platform defaults; the DISPATCH
1689                // is chosen separately below.
1690                let text = match role {
1691                    Some(r) if label.is_empty() => win_role_label(*r),
1692                    _ => clean(label),
1693                };
1694                let (key, mods) = match (shortcut, role) {
1695                    (Some(sc), _) => (win_keycode(&sc.key), win_mods(sc)),
1696                    (None, Some(r)) => win_role_keymods(*r),
1697                    (None, None) => (0, 0),
1698                };
1699                // A nonzero id always wins (the appkit precedence, docs/menus.md): the item
1700                // dispatches the day action and the role only decorates it. day-core's auto
1701                // Preferences item and `MenuRole::NewWindow` arrive exactly this way — routing
1702                // them through the role-only path dropped the id, leaving visible-but-DEAD
1703                // menu items (the same bug macos-qt had).
1704                // An 8th field carries the item's glyph (docs/menus.md). Appended after the
1705                // label, so a shim reading only the first seven fields is unaffected — the
1706                // parser indexes, and the label's own tabs are already cleaned away. Only
1707                // SYMBOLS cross: a MenuFlyoutItem takes a Segoe Fluent glyph, where a bundled
1708                // image would need the toolbar's three-field icon channel.
1709                let glyph = match icon {
1710                    Some(day_spec::Icon::Symbol(s)) => toolbar::glyph_for(*s),
1711                    _ => "",
1712                };
1713                // A 9th field: -1 a plain command, 0/1 a ToggleMenuFlyoutItem sitting off/on.
1714                let chk = checked.map_or(-1, i32::from);
1715                match role {
1716                    Some(r) if *action == 0 => {
1717                        let _ = writeln!(
1718                            out,
1719                            "R\t0\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
1720                            *r as i32,
1721                            key,
1722                            mods,
1723                            en,
1724                            clean(&text),
1725                            glyph,
1726                            chk
1727                        );
1728                    }
1729                    _ => {
1730                        let _ = writeln!(
1731                            out,
1732                            "A\t{}\t-1\t{}\t{}\t{}\t{}\t{}\t{}",
1733                            action,
1734                            key,
1735                            mods,
1736                            en,
1737                            clean(&text),
1738                            glyph,
1739                            chk
1740                        );
1741                    }
1742                }
1743            }
1744        }
1745    }
1746}
1747
1748/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
1749/// a visible placeholder. A missing renderer usually means the piece's `xaml` feature wasn't enabled
1750/// (Tier A.2 derives it automatically under `day build`). Deduped per kind so a placeholder rendered
1751/// every frame doesn't spam the log.
1752fn warn_missing_renderer(kind: PieceKind) {
1753    day_spec::placeholder::report(kind, "xaml");
1754}
1755
1756/// The visible placeholder a realize arm degrades to when its props payload has the wrong type
1757/// (`props_of` has already reported the mismatch) — the same label the missing-renderer arm shows.
1758pub(crate) fn placeholder_handle(kind: PieceKind) -> WinHandle {
1759    WinHandle(unsafe { ffi::day_xaml_label_new(cstr(&format!("⟨{kind}⟩")).as_ptr(), 1) })
1760}
1761
1762/// The shim's cursor code for a [`Cursor`] (docs/cursor.md): 0 releases the element, 1..=16
1763/// name an `IDC_*` shape in the shim's table, 17 hides the pointer.
1764fn win_cursor_code(c: &Cursor) -> c_int {
1765    match c {
1766        Cursor::Default => 0,
1767        Cursor::ContextMenu | Cursor::Copy | Cursor::Alias | Cursor::ZoomIn | Cursor::ZoomOut => 1, // arrow
1768        Cursor::Text | Cursor::VerticalText => 2, // IDC_IBEAM
1769        Cursor::Wait => 3,                        // IDC_WAIT
1770        Cursor::Crosshair | Cursor::Cell => 4,    // IDC_CROSS
1771        Cursor::NwseResize => 6,                  // IDC_SIZENWSE
1772        Cursor::NeswResize => 7,                  // IDC_SIZENESW
1773        Cursor::EwResize | Cursor::ColResize => 8, // IDC_SIZEWE
1774        Cursor::NsResize | Cursor::RowResize => 9, // IDC_SIZENS
1775        Cursor::Move => 10,                       // IDC_SIZEALL
1776        Cursor::NotAllowed => 11,                 // IDC_NO
1777        Cursor::Pointer | Cursor::Grab | Cursor::Grabbing => 12, // IDC_HAND
1778        Cursor::Progress => 13,                   // IDC_APPSTARTING
1779        Cursor::Help => 14,                       // IDC_HELP
1780        Cursor::None => 17,
1781        Cursor::Native(name) => match &**name {
1782            "uparrow" => 5,
1783            "appstarting" => 13,
1784            "pin" => 15,
1785            "person" => 16,
1786            _ => 0,
1787        },
1788    }
1789}
1790
1791impl Toolkit for Xaml {
1792    type Handle = WinHandle;
1793
1794    fn set_drag_source(&mut self, h: &WinHandle, source: day_spec::transfer::Source) {
1795        transfer::source(h, source);
1796    }
1797    fn set_drop_target(&mut self, h: &WinHandle, target: day_spec::transfer::Target) {
1798        transfer::target(h, target);
1799    }
1800
1801    #[cfg(feature = "winui")]
1802    fn list_scroll(&mut self, h: &WinHandle, to: day_spec::ListScroll) -> bool {
1803        list::list_scroll(h, to);
1804        true
1805    }
1806
1807    /// Settled once no list's own scroll is still on its way and no list owes its pass of row
1808    /// binds and viewport report (`list::settled`): a scripted step after "scroll to row" or a
1809    /// row change then sees the rows the list shows now (docs/list.md "Visible rows").
1810    #[cfg(feature = "winui")]
1811    fn ui_idle(&mut self) -> bool {
1812        list::settled()
1813    }
1814
1815    // Holding plus a timed mouse hold, DoubleTapped, the observed pointer down, and the
1816    // contacts by pointer id: every kind is the platform's own (docs/gestures.md).
1817    fn gesture_support(&self, _kind: day_spec::GestureKind) -> Support {
1818        Support::Native
1819    }
1820
1821    fn set_hit_slop(&mut self, h: &WinHandle, _node: NodeId, slop: day_spec::Insets) {
1822        // Leading and trailing follow the app's reading direction.
1823        let (left, right) = if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
1824            (slop.trailing, slop.leading)
1825        } else {
1826            (slop.leading, slop.trailing)
1827        };
1828        unsafe { ffi::day_xaml_set_hit_slop(h.0, left, slop.top, right, slop.bottom) };
1829    }
1830
1831    fn set_drag_axis(&mut self, h: &WinHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
1832        let code = match axis {
1833            None => 0,
1834            Some(day_spec::DragAxis::Horizontal) => 1,
1835            Some(day_spec::DragAxis::Vertical) => 2,
1836        };
1837        unsafe { ffi::day_xaml_set_drag_axis(h.0, code) };
1838    }
1839
1840    fn set_subtree_enabled(&mut self, h: &WinHandle, _node: NodeId, enabled: bool) {
1841        unsafe { ffi::day_xaml_set_subtree_enabled(h.0, c_int::from(enabled)) };
1842    }
1843
1844    fn primary_pointer(&self) -> day_spec::PointerKind {
1845        pointer_kind(unsafe { ffi::day_xaml_primary_pointer() })
1846    }
1847
1848    // Windows' one "Text size" factor (`UISettings.TextScaleFactor`), which XAML applies to
1849    // every text element itself; the style does not matter (docs/text.md "System text size").
1850    fn text_scale(&mut self, _style: Font) -> f64 {
1851        let f = unsafe { ffi::day_xaml_text_scale() };
1852        if f.is_finite() && f > 0.0 { f } else { 1.0 }
1853    }
1854
1855    fn set_layout_direction(
1856        &mut self,
1857        h: &WinHandle,
1858        kind: PieceKind,
1859        direction: day_spec::LayoutDirection,
1860    ) {
1861        let rtl = c_int::from(direction == day_spec::LayoutDirection::Rtl);
1862        if kind == kinds::LABEL {
1863            // The label's own flow, its alignment re-read against it: XAML's Left and Right
1864            // are that flow's start and end.
1865            let align = LABEL_ALIGN.with(|m| m.borrow().get(&(h.0 as usize)).copied());
1866            let code = match align.unwrap_or_default() {
1867                day_spec::props::TextAlign::Leading => 0,
1868                day_spec::props::TextAlign::Center => 1,
1869                day_spec::props::TextAlign::Trailing => 2,
1870                day_spec::props::TextAlign::Justified => 3,
1871            };
1872            unsafe { ffi::day_xaml_label_set_direction(h.0, rtl, code) };
1873            return;
1874        }
1875        // Leaf controls only: a panel's FlowDirection would mirror Day's frames inside it.
1876        if matches!(
1877            kind,
1878            kinds::CONTAINER | kinds::SCROLL | kinds::LIST | kinds::NAV | kinds::NAV_PAGE
1879        ) {
1880            return;
1881        }
1882        unsafe { ffi::day_xaml_set_flow_direction(h.0, rtl) };
1883    }
1884
1885    #[cfg(feature = "winui")]
1886    fn set_focusable(&mut self, h: &WinHandle, node: NodeId, focusable: bool) {
1887        if focusable {
1888            unsafe {
1889                ffi::day_xaml_set_focusable(
1890                    h.0,
1891                    node.0,
1892                    on_key_handled,
1893                    on_text_handled,
1894                    on_key,
1895                    on_focus,
1896                );
1897            };
1898        }
1899    }
1900
1901    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
1902        unsafe {
1903            day_toolkit_xaml_sys::day_xaml_set_visible(handle.0, i32::from(visible));
1904        }
1905    }
1906
1907    fn capability(&self, cap: Cap) -> Support {
1908        match cap {
1909            Cap::SearchField => Support::Native,
1910            Cap::ComboBox => Support::Native,
1911            Cap::Stepper => Support::Emulated,
1912            Cap::DateTimePicker => Support::Native,
1913            Cap::ColorPicker => Support::Native,
1914            Cap::PullRefresh => Support::Emulated,
1915            Cap::Pager => Support::Emulated,
1916            Cap::PullRefreshGesture => Support::Unsupported,
1917            Cap::DragDrop
1918            | Cap::DragExternalImport
1919            | Cap::DragExternalExport
1920            | Cap::DragMultipleItems
1921            | Cap::DragFileReferences
1922            | Cap::DragDeferredReceipt => Support::Native,
1923            // PointerEntered/Exited per element plus WM_SETCURSOR on the host; several CSS
1924            // shapes take their nearest IDC_* shape (docs/cursor.md).
1925            Cap::Cursor => Support::Emulated,
1926            // DirectWrite's system font collection (docs/fonts.md).
1927            Cap::FontList => Support::Native,
1928            Cap::Snapshot => Support::Native,
1929            #[cfg(feature = "winui")]
1930            Cap::CanvasBitmap | Cap::ImageEncode => Support::Native,
1931            // A `BitmapImage` decodes every container WIC reads, and the canvas draws it
1932            // (docs/images.md). WinUI encodes PNG through WIC; system XAML remains decode-only.
1933            Cap::ImageDecode => Support::Native,
1934            // TextBlock.BaselineOffset for text, font-derived for templated controls
1935            // (docs/baseline.md).
1936            Cap::BaselineAlignment => Support::Emulated,
1937            // Runs are TextBlock inlines; a link run is a Hyperlink whose Click reports back
1938            // (docs/text-runs.md).
1939            Cap::TextRuns | Cap::TextLinks => Support::Native,
1940            // text_area attributes (docs/textarea.md): editable and spell-check are plain TextBox
1941            // properties (IsReadOnly / IsSpellCheckEnabled).
1942            Cap::TextEditable | Cap::TextSpellCheck => Support::Native,
1943            // Selection is emulated: IsTextSelectionEnabled is TextBlock's, not TextBox's, so the
1944            // shim collapses selections as they form and suppresses the context menu instead.
1945            Cap::TextSelectable => Support::Emulated,
1946            #[cfg(feature = "winui")]
1947            Cap::ListRecycling | Cap::ListDelete | Cap::ListSwipeActions => Support::Native,
1948            #[cfg(not(feature = "winui"))]
1949            Cap::ListRecycling => Support::Emulated,
1950            // ItemsRepeater has no group headers: header rows are plain unselectable elements,
1951            // and the shim pins a bound copy of the current one over the viewport, pushed up by
1952            // the next (docs/list.md "Sections").
1953            #[cfg(feature = "winui")]
1954            Cap::ListSections => Support::Emulated,
1955            // The real WinRT drag pipeline (CanDrag/DragOver/Drop) over the emulated list —
1956            // system drag visuals + live no-drop cursor from the app's guard (docs/list.md).
1957            Cap::ListReorder => Support::Native,
1958            // A reordering sidebar is Day's own list standing in for the NavigationView
1959            // (docs/navigation.md).
1960            Cap::NavReorder => Support::Emulated,
1961            // A second Win32 host + its own XAML island per window (docs/windows.md).
1962            Cap::MultiWindow => Support::Native,
1963            // Window properties (docs/windows.md): ShowWindow for minimize, maximize and restore,
1964            // reported from WM_SIZE; borderless fullscreen over the monitor (WS_POPUP in place of
1965            // the frame styles); SetWindowDisplayAffinity(WDA_EXCLUDEFROMCAPTURE).
1966            Cap::WindowStates | Cap::WindowFullscreen | Cap::ContentProtection => Support::Native,
1967            // Window chrome (docs/window-chrome.md). Frameless keeps the frame styles and answers
1968            // WM_NCCALCSIZE with the whole window, so DWM keeps the shadow and Aero Snap; the
1969            // overlay title bar is DWM's custom-frame method, its caption buttons cut out of the
1970            // island; drag regions answer HTCAPTION from WM_NCHITTEST through the island's hooked
1971            // windows.
1972            Cap::FramelessWindow | Cap::OverlayTitleBar | Cap::DragRegion => Support::Native,
1973            // Mica, Mica Alt and Acrylic through DWMWA_SYSTEMBACKDROP_TYPE, Windows 11 22621+.
1974            Cap::WindowMaterial => {
1975                if unsafe { ffi::day_xaml_materials_supported() } != 0 {
1976                    Support::Native
1977                } else {
1978                    Support::Unsupported
1979                }
1980            }
1981            // The app outside its windows (docs/status-item.md): notification-area icons, and
1982            // progress and an overlay badge on the first window's taskbar button.
1983            Cap::StatusItem | Cap::AppProgress | Cap::AppBadgeCount | Cap::AppBadgeDot => {
1984                Support::Native
1985            }
1986            // Window properties (docs/windows.md): SetWindowPos and WM_GETMINMAXINFO; topmost
1987            // and the taskbar tab (a window on every virtual desktop has no API); the per-window
1988            // dark title bar and root theme; FlashWindowEx; EnumDisplayMonitors.
1989            // The jump list's Tasks (ICustomDestinationList); a task starts a second process,
1990            // which forwards its route to this one (docs/deep-links.md).
1991            Cap::DynamicShortcuts => Support::Native,
1992            Cap::WindowGeometry
1993            | Cap::WindowPosition
1994            | Cap::WindowLevel
1995            | Cap::WindowAppearance
1996            | Cap::RequestAttention
1997            | Cap::Monitors => Support::Native,
1998            // `Cap::TransparentWindow` stays Unsupported: a desktop showing through needs a host
1999            // with no redirection surface, and a XAML island's DirectComposition content inside
2000            // such a host is not something this backend can promise. The window stays opaque.
2001            // A Fluent CommandBar under the menu bar (docs/toolbars.md).
2002            // The CommandBar holds an AutoSuggestBox (docs/search.md).
2003            Cap::AppMenu | Cap::Toolbar | Cap::ToolbarSearch => Support::Native,
2004            // Present `nav()` as split panes: NAV/NAV_PAGE are plain Canvases and day-core's
2005            // NavLayout positions the sidebar + detail (no native split control needed).
2006            Cap::NavSplit => Support::Native,
2007            // A SplitView with PanePlacement=Right — the XAML trailing-pane container
2008            // (docs/inspector.md).
2009            Cap::Inspector => Support::Native,
2010            // The same NavigationView with a different pane: `Top` is WinUI's tab bar and
2011            // `LeftCompact` a real icon rail (docs/navigation.md).
2012            //
2013            // `Cap::NavTabsAdaptive` is deliberately not here: a Windows app may PIN a tab bar,
2014            // but a narrowing window collapses its pane rather than growing one — the same rule
2015            // every other desktop follows.
2016            Cap::NavTabs => Support::Native,
2017            // Native modals (ContentDialog) + WinRT file and folder pickers (docs/dialogs.md,
2018            // docs/files.md).
2019            Cap::Dialogs | Cap::FileDialogs | Cap::FolderDialog => Support::Native,
2020            // The system light/dark setting, read live and re-reported when the user changes it
2021            // (docs/settings.md). XAML's own controls follow theme resources by themselves; this
2022            // is what makes DAY's palette follow too.
2023            Cap::Appearance => Support::Native,
2024            // Windows' "Show animations" switch (`UISettings.AnimationsEnabled`), read live and
2025            // re-reported when the user flips it (docs/accessibility.md).
2026            Cap::ReduceMotion => Support::Native,
2027            // XAML Storyboards play the whole AnimSpec (delay, repeat, auto-reverse, the spring as
2028            // its own samples) on opacity, the transform channels, the frame and a fill
2029            // (docs/tween.md).
2030            Cap::Animation => Support::Native,
2031            // A topmost child of the content Canvas — not a system modal (docs/cover.md).
2032            Cap::Cover => Support::Emulated,
2033            // Native TreeView/TreeViewNode disclosure and selection with Day Canvas rows.
2034            // Native tree drag-to-move is not wired yet.
2035            Cap::Tree | Cap::TreeSections => Support::Native,
2036            // The NavigationView shows the current destination in its Header, so pages needn't
2037            // repeat their title in-content (docs/navigation.md).
2038            Cap::NavHeader => Support::Native,
2039            // A UIA notification (AutomationPeer.RaiseNotificationEvent) raised from the
2040            // primary window's tree (docs/accessibility.md).
2041            Cap::Announce => Support::Native,
2042            // KeyStatus.WasKeyDown for repeats and KeyUp for releases on every key route
2043            // (docs/menus.md "Key phases").
2044            Cap::KeyPhases => Support::Native,
2045            // TextBlock.SelectionChanged, with the TextPointer offsets read as UTF-16 units of the
2046            // displayed text (docs/text.md "Selection").
2047            Cap::LabelSelection => Support::Native,
2048            // ScrollViewer.ViewChanged for the offset and the zoom; DirectManipulation started,
2049            // inertial and completed (and a wheel burst) for the phases; ZoomMode with
2050            // Min/MaxZoomFactor (docs/scroll.md).
2051            Cap::ScrollOffset | Cap::ScrollPhases | Cap::ScrollZoom => Support::Native,
2052            // A ScrollViewer over Day's canvas has no snap points of its own: the shim settles on
2053            // the nearest stop when a scroll comes to rest.
2054            Cap::ScrollSnap => Support::Emulated,
2055            // The ItemsRepeater host reports its realized rows and the ScrollViewer's extent, and
2056            // brings a row into view with an alignment ratio and the platform's animation.
2057            #[cfg(feature = "winui")]
2058            Cap::ListViewport | Cap::ListScrollAlign => Support::Native,
2059            // The reader's scrolls, told from the list's own BringIntoView: a wheel or a
2060            // scrolling key that moves the view, a DirectManipulation started under a touch or
2061            // pen contact, and the scroll bar's user-only Scroll (docs/list.md "Following the
2062            // end").
2063            #[cfg(feature = "winui")]
2064            Cap::ListReaderScroll => Support::Native,
2065            // Transparent bands around a container, which its recognizers hear (docs/gestures.md
2066            // "Hit slop").
2067            Cap::HitSlop => Support::Native,
2068            // WinUI 3's UIElement tab stop on the container (docs/focus.md).
2069            #[cfg(feature = "winui")]
2070            Cap::Focusable => Support::Native,
2071            _ => Support::Unsupported,
2072        }
2073    }
2074
2075    fn realize(&mut self, kind: PieceKind, props: &dyn std::any::Any, id: NodeId) -> WinHandle {
2076        unsafe {
2077            let handle = match Builtin::from_key(kind) {
2078                Some(Builtin::Container) => {
2079                    let h = ffi::day_xaml_container_new();
2080                    if let Some(p) = props.downcast_ref::<ContainerProps>() {
2081                        realize_surface(h, p);
2082                    }
2083                    WinHandle(h)
2084                }
2085                Some(Builtin::Scroll) => {
2086                    let p = props
2087                        .downcast_ref::<day_spec::props::ScrollProps>()
2088                        .cloned()
2089                        .unwrap_or_default();
2090                    let mut content: *mut c_void = std::ptr::null_mut();
2091                    let sv = ffi::day_xaml_scroll_new(&raw mut content, c_int::from(p.horizontal));
2092                    SCROLL_STATE.with(|m| m.borrow_mut().insert(sv as usize, content));
2093                    configure_scroll(sv, id, &p);
2094                    WinHandle(sv)
2095                }
2096                Some(Builtin::Canvas) => {
2097                    #[cfg(feature = "winui")]
2098                    {
2099                        // Win2D paints; a persistent control owns focus and pointer input.
2100                        let h =
2101                            ffi::day_xaml_canvas_new(id.0, on_key_handled, on_text_handled, on_key);
2102                        ffi::day_xaml_enable_focus(h, id.0, on_focus);
2103                        CANVASES.with(|c| c.borrow_mut().insert(h as usize));
2104                        WinHandle(h)
2105                    }
2106                    #[cfg(not(feature = "winui"))]
2107                    {
2108                        placeholder_handle(kind)
2109                    }
2110                }
2111                Some(Builtin::Nav) => {
2112                    let Some(p) = props_of::<NavProps>(kind, "xaml", props) else {
2113                        return placeholder_handle(kind);
2114                    };
2115                    // Both presentations are a native NavigationView: a sidebar+header nav host
2116                    // (split) or a push/pop stack with a back button (docs/navigation.md).
2117                    // Only a real push/pop stack stacks. `Tabs` and `Rail` are this same
2118                    // NavigationView wearing a different pane (`rows_are_chrome`), and their pages
2119                    // are RESIDENT: `Select` switches which one shows. Folding them in with Stack
2120                    // — which `!is_split()` does — sent every insert through `stack_sync`, whose
2121                    // answer is "show the last page added", so a tab set opened on its final tab.
2122                    let is_stack =
2123                        matches!(p.presentation, day_spec::props::NavPresentation::Stack);
2124                    let mut content: *mut c_void = std::ptr::null_mut();
2125                    // Where the rows are the CHROME the same NavigationView wears a different
2126                    // pane: `Top` is WinUI's tab bar and `LeftCompact` a real icon rail, so a
2127                    // rail lands on a rail here rather than rounding to a sidebar the way it must
2128                    // on macOS (docs/navigation.md). Pages stay resident and `Select` switches
2129                    // them, exactly as the tab presentation does everywhere else.
2130                    let pane_mode = match p.presentation {
2131                        day_spec::props::NavPresentation::Tabs => 2,
2132                        day_spec::props::NavPresentation::Rail => 3,
2133                        // Split and Stack keep the NavigationView's own pane display mode, which
2134                        // is what `is_stack` above already configured.
2135                        _ => -1,
2136                    };
2137                    let nav = ffi::day_xaml_nav_new(
2138                        id.0,
2139                        nav_selection,
2140                        nav_region_size,
2141                        nav_back,
2142                        &raw mut content,
2143                        c_int::from(is_stack),
2144                        c_int::from(day_core::layout_direction() == day_spec::LayoutDirection::Rtl),
2145                        c_int::from(p.documents.is_some()),
2146                        c_int::from(p.documents.as_ref().is_some_and(|d| d.can_add)),
2147                        cstr(p.documents.as_ref().map_or("", |d| d.new_label.as_str())).as_ptr(),
2148                        document_event,
2149                    );
2150                    if pane_mode >= 0 {
2151                        ffi::day_xaml_nav_set_pane_mode(nav, pane_mode);
2152                    }
2153                    NAV_STATE.with(|m| {
2154                        m.borrow_mut().insert(
2155                            nav as usize,
2156                            NavState::Split(SplitNav {
2157                                node: id.0,
2158                                nav_view: nav,
2159                                content_host: content,
2160                                menu_node: 0,
2161                                sidebar_page: None,
2162                                detail_pages: Vec::new(),
2163                                is_stack,
2164                                resident: p.presentation.rows_are_chrome(),
2165                                selected: 0,
2166                            }),
2167                        )
2168                    });
2169                    NAV_HOST_BY_ID.with(|m| m.borrow_mut().insert(id.0, nav));
2170                    if !is_stack {
2171                        // The next NAV_MENU (built into the sidebar page) feeds this pane's items.
2172                        PENDING_SPLIT_NAV.with(|c| c.set(nav));
2173                    }
2174                    WinHandle(nav)
2175                }
2176                Some(Builtin::NavPage) => {
2177                    let page = ffi::day_xaml_container_new();
2178                    NAV_PAGE_IDS.with(|m| m.borrow_mut().insert(page as usize, id));
2179                    WinHandle(page)
2180                }
2181                Some(Builtin::Inspector) => {
2182                    let (visible, width, leading) =
2183                        props
2184                            .downcast_ref::<InspectorProps>()
2185                            .map_or((false, 280.0, false), |p| {
2186                                (
2187                                    p.visible,
2188                                    p.width,
2189                                    p.edge == day_spec::props::PaneEdge::Leading,
2190                                )
2191                            });
2192                    let mut content: *mut c_void = std::ptr::null_mut();
2193                    let mut panel: *mut c_void = std::ptr::null_mut();
2194                    let sv = ffi::day_xaml_inspector_new(
2195                        id.0,
2196                        width,
2197                        c_int::from(visible),
2198                        c_int::from(leading),
2199                        inspector_region_size,
2200                        &raw mut content,
2201                        &raw mut panel,
2202                    );
2203                    INSPECTOR_STATE.with(|m| {
2204                        m.borrow_mut().insert(
2205                            sv as usize,
2206                            XamlInspector {
2207                                content_host: content,
2208                                panel_host: panel,
2209                                node: id.0,
2210                            },
2211                        )
2212                    });
2213                    INSPECTOR_PANES_BY_HOST
2214                        .with(|m| m.borrow_mut().insert(id.0, InspectorPaneNodes::default()));
2215                    WinHandle(sv)
2216                }
2217                Some(Builtin::InspectorPane) => {
2218                    let pane = ffi::day_xaml_container_new();
2219                    let panel = props
2220                        .downcast_ref::<InspectorPaneProps>()
2221                        .is_some_and(|p| p.panel);
2222                    INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().insert(pane as usize, (id, panel)));
2223                    WinHandle(pane)
2224                }
2225                // Emulated fullscreen cover (docs/cover.md): parked hidden; Present re-homes
2226                // it onto the window's content Canvas, appended last (= topmost), at the
2227                // content size.
2228                Some(Builtin::Cover) => {
2229                    let cover = ffi::day_xaml_container_new();
2230                    ffi::day_xaml_set_visible(cover, 0);
2231                    COVER_IDS.with(|m| m.borrow_mut().insert(cover as usize, id));
2232                    let p = props_of::<CoverProps>(kind, "xaml", props);
2233                    if p.is_some_and(|p| p.half) {
2234                        COVER_HALF.with(|s| s.borrow_mut().insert(cover as usize));
2235                    }
2236                    if p.is_some_and(|p| (p.sheet || p.large) && !p.half) {
2237                        ffi::day_xaml_cover_escape(cover, id.0, on_cover_escape);
2238                    }
2239                    WinHandle(cover)
2240                }
2241                Some(Builtin::NavMenu) => {
2242                    let Some(p) = props_of::<NavMenuProps>(kind, "xaml", props) else {
2243                        return placeholder_handle(kind);
2244                    };
2245                    let pending = PENDING_SPLIT_NAV.with(std::cell::Cell::get);
2246                    if pending.is_null() {
2247                        // Standalone ListView (non-split fallback).
2248                        let w = ffi::day_xaml_navlist_new(id.0, nav_menu_changed);
2249                        ffi::day_xaml_navlist_set_items(
2250                            w,
2251                            cstr(&p.items.join("\n")).as_ptr(),
2252                            cstr(&join_sections(&p.sections)).as_ptr(),
2253                        );
2254                        ffi::day_xaml_navlist_set_selected(
2255                            w,
2256                            p.selected.map_or(-1, |i| i as c_int),
2257                        );
2258                        let headings = p.sections.iter().filter(|s| s.is_some()).count();
2259                        NAV_MENU_ROWS
2260                            .with(|m| m.borrow_mut().insert(w as usize, (p.items.len(), headings)));
2261                        WinHandle(w)
2262                    } else {
2263                        // Split nav: the destinations become the NavigationView's own MenuItems, so
2264                        // the menu node is just an invisible placeholder inside the sidebar page.
2265                        let icons_joined = p
2266                            .icons
2267                            .iter()
2268                            .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2269                            .collect::<Vec<_>>()
2270                            .join("\n");
2271                        // The trailing status glyph rides the same three channels the leading
2272                        // icon does: staged file name, vector geometry, tint.
2273                        let badge_icons_joined = p
2274                            .badge_icons
2275                            .iter()
2276                            .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2277                            .collect::<Vec<_>>()
2278                            .join("\n");
2279                        ffi::day_xaml_document_items(
2280                            pending,
2281                            cstr(&p.items.join("\u{1f}")).as_ptr(),
2282                            cstr(&p.document_keys.join("\u{1f}")).as_ptr(),
2283                        );
2284                        ffi::day_xaml_nav_set_items(
2285                            pending,
2286                            cstr(&p.items.join("\n")).as_ptr(),
2287                            cstr(&icons_joined).as_ptr(),
2288                            cstr(&join_geoms(&p.icons)).as_ptr(),
2289                            cstr(&join_tints(&p.tints)).as_ptr(),
2290                            cstr(&badge_icons_joined).as_ptr(),
2291                            cstr(&join_geoms(&p.badge_icons)).as_ptr(),
2292                            cstr(&join_tints(&p.badge_tints)).as_ptr(),
2293                            cstr(&join_sections(&p.sections)).as_ptr(),
2294                        );
2295                        ffi::day_xaml_nav_set_selected(
2296                            pending,
2297                            p.selected.map_or(-1, |i| i as c_int),
2298                        );
2299                        NAV_STATE.with(|m| {
2300                            if let Some(NavState::Split(s)) =
2301                                m.borrow_mut().get_mut(&(pending as usize))
2302                            {
2303                                s.menu_node = id.0;
2304                                s.selected = p.selected.unwrap_or(0);
2305                            }
2306                        });
2307                        // Pages realized before their menu (order is the tree's, not ours) are
2308                        // still showing whichever came last.
2309                        select_sync(pending);
2310                        PENDING_SPLIT_NAV.with(|c| c.set(std::ptr::null_mut()));
2311                        let placeholder = ffi::day_xaml_container_new();
2312                        NAV_MENU_HOST
2313                            .with(|m| m.borrow_mut().insert(placeholder as usize, pending));
2314                        WinHandle(placeholder)
2315                    }
2316                }
2317                Some(Builtin::Label) => {
2318                    let Some(p) = props_of::<LabelProps>(kind, "xaml", props) else {
2319                        return placeholder_handle(kind);
2320                    };
2321                    let h = ffi::day_xaml_label_new(cstr(&p.text).as_ptr(), c_int::from(p.wraps));
2322                    let (pt, weight, italic, tabular) = font_params(p.font);
2323                    ffi::day_xaml_label_set_font(h, pt, weight, italic, tabular);
2324                    apply_custom_family(h, p.font);
2325                    apply_label_features(h, p.font);
2326                    // Realize-only, as on Qt: `LabelPatch` carries no `Align`, so a label whose
2327                    // alignment changes is rebuilt rather than patched.
2328                    ffi::day_xaml_label_set_align(h, label_align_code(p.align));
2329                    LABEL_ALIGN.with(|m| m.borrow_mut().insert(h as usize, p.align));
2330                    if p.reports_selection {
2331                        LABEL_TEXT.with(|m| m.borrow_mut().insert(id.0, p.text.clone()));
2332                        ffi::day_xaml_label_report_selection(h, id.0, on_label_selection);
2333                    }
2334                    if p.role == day_spec::props::TextRole::Secondary {
2335                        ffi::day_xaml_label_set_secondary(h);
2336                    }
2337                    if let Some(c) = p.color {
2338                        paint_label_color(h, c);
2339                    }
2340                    LABEL_NODE.with(|m| m.borrow_mut().insert(h as usize, id.0));
2341                    if !p.runs.is_empty() {
2342                        set_label_runs(h, id.0, &p.text, &p.runs);
2343                    }
2344                    apply_paragraph(h, p.wraps, &p.paragraph(), &p.text, p.runs.is_empty());
2345                    WinHandle(h)
2346                }
2347                Some(Builtin::Button) => {
2348                    let Some(p) = props_of::<ButtonProps>(kind, "xaml", props) else {
2349                        return placeholder_handle(kind);
2350                    };
2351                    let h = ffi::day_xaml_button_new(cstr(&p.title).as_ptr(), id.0, on_press);
2352                    apply_button_style(h, p.style);
2353                    if p.icon.is_some() {
2354                        apply_button_content(h, &p.title, p.icon.as_ref(), p.icon_only);
2355                    }
2356                    ffi::day_xaml_enable_focus(h, id.0, on_focus);
2357                    ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2358                    ffi::day_xaml_button_set_selected(h, c_int::from(p.selected));
2359                    WinHandle(h)
2360                }
2361                Some(Builtin::Toggle) => {
2362                    let Some(p) = props_of::<ToggleProps>(kind, "xaml", props) else {
2363                        return placeholder_handle(kind);
2364                    };
2365                    let h = ffi::day_xaml_toggle_new(c_int::from(p.on), id.0, on_toggle);
2366                    ffi::day_xaml_enable_focus(h, id.0, on_focus);
2367                    ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2368                    WinHandle(h)
2369                }
2370                Some(Builtin::Slider) => {
2371                    let Some(p) = props_of::<SliderProps>(kind, "xaml", props) else {
2372                        return placeholder_handle(kind);
2373                    };
2374                    // Default to a fine 1/1000-of-range step (matching the GTK backend) when the app
2375                    // leaves it unset, so the slider stays effectively continuous.
2376                    let step = p.step.unwrap_or((p.max - p.min) / 1000.0).max(1e-9);
2377                    let h = ffi::day_xaml_slider_new(p.value, p.min, p.max, step, id.0, on_slider);
2378                    ffi::day_xaml_enable_focus(h, id.0, on_focus);
2379                    ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2380                    WinHandle(h)
2381                }
2382                Some(Builtin::Picker) => picker::realize_any(self, props, id),
2383                Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
2384                Some(Builtin::TextField) => {
2385                    let Some(p) = props_of::<TextFieldProps>(kind, "xaml", props) else {
2386                        return placeholder_handle(kind);
2387                    };
2388                    ffi::day_xaml_set_field_keys(on_field_key);
2389                    let h = ffi::day_xaml_textbox_new(
2390                        cstr(&p.text).as_ptr(),
2391                        cstr(&p.placeholder).as_ptr(),
2392                        id.0,
2393                        on_text,
2394                    );
2395                    ffi::day_xaml_enable_focus(h, id.0, on_focus);
2396                    ffi::day_xaml_set_enabled(h, c_int::from(p.enabled));
2397                    TEXT_FIELD_NODE.with(|m| m.borrow_mut().insert(h as usize, id.0));
2398                    WinHandle(h)
2399                }
2400                Some(Builtin::Divider) => {
2401                    let vertical = day_spec::props_of::<DividerProps>(kind, "xaml", props)
2402                        .is_some_and(|p| p.vertical);
2403                    WinHandle(ffi::day_xaml_divider_new(c_int::from(vertical)))
2404                }
2405                Some(Builtin::List) => {
2406                    let Some(p) = props_of::<ListProps>(kind, "xaml", props) else {
2407                        return placeholder_handle(kind);
2408                    };
2409                    attach_custom_sidebar();
2410                    WinHandle(list::new(id, p))
2411                }
2412                Some(Builtin::Progress) => {
2413                    let Some(p) = props_of::<ProgressProps>(kind, "xaml", props) else {
2414                        return placeholder_handle(kind);
2415                    };
2416                    if p.value.is_none() {
2417                        return crate::controls::spinner::make(self, p, id);
2418                    }
2419                    match p.value {
2420                        Some(v) => WinHandle(ffi::day_xaml_progress_new(1, progress_ticks(v))),
2421                        None => WinHandle(ffi::day_xaml_progress_new(0, 0)),
2422                    }
2423                }
2424                Some(Builtin::Image) => {
2425                    let Some(p) = props_of::<ImageProps>(kind, "xaml", props) else {
2426                        return placeholder_handle(kind);
2427                    };
2428                    // Scaling: 0=fit, 1=fill (crop), 2=stretch.
2429                    let mode = match p.content_mode {
2430                        ContentMode::Fit => 0,
2431                        ContentMode::Fill => 1,
2432                        ContentMode::Stretch => 2,
2433                    };
2434                    // A `vector(…)` glyph draws as real geometry (docs/vectors.md) — vector at
2435                    // any size, and its tint composed as a brush at realize time. Tried first,
2436                    // tinted or not; `vector_geometry` is None for a raster `image(…)` name and
2437                    // for art the CLI could not convert, which is what falls through below.
2438                    // Bytes and shared decodes arrive through `decode_image` (docs/images.md);
2439                    // this arm is the staged-asset path, unchanged.
2440                    let named = match &p.source {
2441                        day_spec::ImageSource::Named(name) => name.clone(),
2442                        _ => String::new(),
2443                    };
2444                    // Bytes and shared decodes (docs/images.md) never resolve to a staged file:
2445                    // the shim builds a `BitmapImage` over the buffer instead, so an `image()`
2446                    // piece can show a download or a pasted PNG with no resource behind it. The
2447                    // vector/raster resolution below is NAMED-only, so it stays inside that arm
2448                    // rather than running for sources that have no name to resolve.
2449                    match &p.source {
2450                        // A raster takes its tint after it exists (docs/images.md "Tinting"):
2451                        // the shim recolors the pixels it holds, as it does for a later patch.
2452                        day_spec::ImageSource::Bytes(bytes) => {
2453                            let h = ffi::day_xaml_image_bytes_new(
2454                                bytes.as_ptr(),
2455                                bytes.len() as c_int,
2456                                mode,
2457                            );
2458                            if let Some(tint) = p.tint {
2459                                ffi::day_xaml_image_set_tint(h, argb(tint), 1);
2460                            }
2461                            WinHandle(h)
2462                        }
2463                        day_spec::ImageSource::Decoded(id) => {
2464                            let h = ffi::day_xaml_image_bitmap_new(id.0, mode);
2465                            if let Some(tint) = p.tint {
2466                                ffi::day_xaml_image_set_tint(h, argb(tint), 1);
2467                            }
2468                            WinHandle(h)
2469                        }
2470                        day_spec::ImageSource::Named(_) => {
2471                            // The shim's tint mode: 0 draws the art as authored, 1 composes
2472                            // `argb`, 2 is a template glyph in the theme foreground
2473                            // (docs/vectors.md "Template"), which follows a theme switch.
2474                            let tinted = match p.tint {
2475                                Some(_) if p.template => 3,
2476                                Some(_) => 1,
2477                                None if p.template => 2,
2478                                None => 0,
2479                            };
2480                            let geometry = vector_geometry(&named).and_then(|spec| {
2481                                let h = ffi::day_xaml_vector_new(
2482                                    cstr(&spec).as_ptr(),
2483                                    mode,
2484                                    p.tint.map_or(0, argb),
2485                                    tinted,
2486                                );
2487                                (!h.is_null()).then_some(h)
2488                            });
2489                            // A tinted raster that is not a template: the image itself,
2490                            // recolored by the shim, so it keeps its content mode. WinUI
2491                            // only; system XAML has no Win2D to recolor with and falls
2492                            // through to the icon below.
2493                            let recolored = || {
2494                                let uri = image_uri(&named);
2495                                if tinted != 1 || uri.is_empty() || !cfg!(feature = "winui") {
2496                                    return None;
2497                                }
2498                                let h = ffi::day_xaml_image_new(cstr(&uri).as_ptr(), mode);
2499                                ffi::day_xaml_image_set_tint(h, p.tint.map_or(0, argb), 1);
2500                                Some(h)
2501                            };
2502                            // Raster fallbacks: a monochrome BitmapIcon still honors a tint (or
2503                            // the theme foreground), and a plain Image carries the art as
2504                            // authored.
2505                            let tinted = || {
2506                                if tinted == 0 {
2507                                    return None;
2508                                }
2509                                let file = icon_file_name(&named);
2510                                if file.is_empty() {
2511                                    return None;
2512                                }
2513                                let h = ffi::day_xaml_image_tinted_new(
2514                                    cstr(&file).as_ptr(),
2515                                    mode,
2516                                    p.tint.map_or(0, argb),
2517                                    tinted,
2518                                );
2519                                (!h.is_null()).then_some(h)
2520                            };
2521                            WinHandle(geometry.or_else(recolored).or_else(tinted).unwrap_or_else(
2522                                || ffi::day_xaml_image_new(cstr(&image_uri(&named)).as_ptr(), mode),
2523                            ))
2524                        }
2525                    }
2526                }
2527                Some(Builtin::Tree) => {
2528                    let Some(p) = props_of::<TreeProps>(kind, "xaml", props) else {
2529                        return placeholder_handle(kind);
2530                    };
2531                    attach_custom_sidebar();
2532                    WinHandle(tree::new(id, p))
2533                }
2534                // A recycled list cell is ADOPTED from the native list, never realized
2535                // through this path; anything else is an extension piece.
2536                Some(
2537                    Builtin::ListCell | Builtin::ListItem | Builtin::Split | Builtin::SplitPane,
2538                )
2539                | None => {
2540                    if let Some(make) = self.registry.get(kind).map(|r| r.make) {
2541                        return make(self, props, id);
2542                    }
2543                    warn_missing_renderer(kind);
2544                    placeholder_handle(kind)
2545                }
2546            };
2547            match Builtin::from_key(kind) {
2548                // Pass-through (docs/gestures.md): no pointer input until something that takes
2549                // it is attached.
2550                Some(Builtin::Image) => {
2551                    ffi::day_xaml_set_passive(handle.0);
2552                    if let Some(p) = props.downcast_ref::<day_spec::props::ImageProps>() {
2553                        keep_image_tint(handle.0, p.tint);
2554                    }
2555                }
2556                Some(Builtin::Divider) => ffi::day_xaml_set_passive(handle.0),
2557                _ => {}
2558            }
2559            ffi::day_xaml_on_control_loaded(handle.0, id.0, control_loaded);
2560            handle
2561        }
2562    }
2563
2564    fn update(
2565        &mut self,
2566        h: &WinHandle,
2567        kind: PieceKind,
2568        patch: &dyn std::any::Any,
2569        anim: Option<&AnimSpec>,
2570    ) {
2571        if let Some(patch) = patch.downcast_ref::<TreePatch>() {
2572            tree::patch(h.0 as usize, patch);
2573            return;
2574        }
2575        unsafe {
2576            match kind {
2577                kinds::IMAGE => {
2578                    if let Some(patch) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
2579                        match patch {
2580                            day_spec::props::ImagePatch::Tint(tint) => {
2581                                ffi::day_xaml_image_set_tint(
2582                                    h.0,
2583                                    tint.map_or(0, argb),
2584                                    i32::from(tint.is_some()),
2585                                );
2586                                keep_image_tint(h.0, *tint);
2587                            }
2588                            day_spec::props::ImagePatch::Source(source) => match source {
2589                                day_spec::ImageSource::Named(name) => {
2590                                    if let Some(spec) = vector_geometry(name) {
2591                                        ffi::day_xaml_image_set_vector(h.0, cstr(&spec).as_ptr());
2592                                    } else {
2593                                        ffi::day_xaml_image_set_uri(
2594                                            h.0,
2595                                            cstr(&image_uri(name)).as_ptr(),
2596                                        );
2597                                    }
2598                                }
2599                                day_spec::ImageSource::Bytes(b) => {
2600                                    ffi::day_xaml_image_set_bytes(
2601                                        h.0,
2602                                        b.as_ptr(),
2603                                        b.len() as c_int,
2604                                    );
2605                                }
2606                                day_spec::ImageSource::Decoded(id) => {
2607                                    ffi::day_xaml_image_set_bitmap(h.0, id.0);
2608                                }
2609                            },
2610                        }
2611                    }
2612                }
2613                kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
2614                    Some(ContainerPatch::Fill(fill)) => patch_fill(h.0, fill.as_ref(), anim),
2615                    Some(ContainerPatch::Surface(p)) => patch_surface(h.0, p),
2616                    None => {}
2617                },
2618                kinds::LABEL => {
2619                    if let Some(p) = patch.downcast_ref::<LabelPatch>() {
2620                        match p {
2621                            LabelPatch::Paragraph(para) => {
2622                                // `wraps` is realize-time; the shim keeps it on the block.
2623                                let wraps = ffi::day_xaml_label_wraps(h.0) != 0;
2624                                let (text, plain) = label_text_of(h.0);
2625                                apply_paragraph(h.0, wraps, para, &text, plain);
2626                            }
2627                            LabelPatch::Text(t) => {
2628                                // Plain text replaces the runs, and their colors with them.
2629                                keep_inks(h.0, InkSlot::LabelRuns, false, |_, _| {});
2630                                ffi::day_xaml_label_set_text(h.0, cstr(t).as_ptr());
2631                                note_label_text(h.0, t);
2632                            }
2633                            LabelPatch::Font(f) => {
2634                                let (pt, weight, italic, tabular) = font_params(*f);
2635                                ffi::day_xaml_label_set_font(h.0, pt, weight, italic, tabular);
2636                                apply_custom_family(h.0, *f);
2637                                apply_label_features(h.0, *f);
2638                                // An elided string was cut for the old font.
2639                                let width = LABEL_ELIDE.with(|m| {
2640                                    m.borrow().get(&(h.0 as usize)).map_or(0.0, |e| e.width)
2641                                });
2642                                if width > 0.0 {
2643                                    elide_label(h.0, width);
2644                                }
2645                            }
2646                            LabelPatch::Runs(text, runs) => {
2647                                let node = LABEL_NODE
2648                                    .with(|m| m.borrow().get(&(h.0 as usize)).copied())
2649                                    .unwrap_or(0);
2650                                set_label_runs(h.0, node, text, runs);
2651                                note_label_text(h.0, text);
2652                            }
2653                            LabelPatch::Color(c) => {
2654                                paint_label_color(h.0, c.unwrap_or(day_spec::Ink::CLEAR));
2655                            }
2656                        }
2657                    }
2658                }
2659                kinds::BUTTON => {
2660                    if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
2661                        match p {
2662                            ButtonPatch::Content(c) => {
2663                                apply_button_content(h.0, &c.title, c.icon.as_ref(), c.icon_only);
2664                            }
2665                            ButtonPatch::Title(t) => {
2666                                ffi::day_xaml_button_set_title(h.0, cstr(t).as_ptr());
2667                            }
2668                            ButtonPatch::Enabled(e) => {
2669                                ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2670                            }
2671                            ButtonPatch::Selected(on) => {
2672                                ffi::day_xaml_button_set_selected(h.0, c_int::from(*on));
2673                            }
2674                            ButtonPatch::Style(s) => apply_button_style(h.0, *s),
2675                        }
2676                    }
2677                }
2678                kinds::TOGGLE => {
2679                    if let Some(p) = patch.downcast_ref::<TogglePatch>() {
2680                        match p {
2681                            TogglePatch::On(on) => ffi::day_xaml_toggle_set(h.0, c_int::from(*on)),
2682                            TogglePatch::Enabled(e) => {
2683                                ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2684                            }
2685                        }
2686                    }
2687                }
2688                kinds::SLIDER => {
2689                    if let Some(p) = patch.downcast_ref::<SliderPatch>() {
2690                        match p {
2691                            SliderPatch::Value(v) => ffi::day_xaml_slider_set(h.0, *v),
2692                            SliderPatch::Enabled(e) => {
2693                                ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2694                            }
2695                        }
2696                    }
2697                }
2698                kinds::PROGRESS => {
2699                    if let Some(p @ ProgressPatch::Animating(_)) =
2700                        patch.downcast_ref::<ProgressPatch>()
2701                    {
2702                        crate::controls::spinner::update(self, h, p);
2703                        return;
2704                    }
2705
2706                    if let Some(ProgressPatch::Value(Some(v))) =
2707                        patch.downcast_ref::<ProgressPatch>()
2708                    {
2709                        ffi::day_xaml_progress_set(h.0, progress_ticks(*v));
2710                    }
2711                }
2712                kinds::LIST => {
2713                    if let Some(patch) = patch.downcast_ref::<ListPatch>() {
2714                        list::patch(h, patch);
2715                    }
2716                }
2717                kinds::SCROLL => {
2718                    // Zoom is WinUI's: system XAML builds no zooming scroll view.
2719                    #[cfg(feature = "winui")]
2720                    if let Some(day_spec::props::ScrollPatch::Zoom { scale, animated }) =
2721                        patch.downcast_ref::<day_spec::props::ScrollPatch>()
2722                    {
2723                        ffi::day_xaml_scroll_zoom(h.0, *scale, c_int::from(*animated));
2724                    }
2725                }
2726                kinds::NAV_MENU => {
2727                    // Split navs drive the NavigationView pane; a plain ListView otherwise.
2728                    let host = NAV_MENU_HOST.with(|m| m.borrow().get(&(h.0 as usize)).copied());
2729                    match patch.downcast_ref::<NavMenuPatch>() {
2730                        Some(NavMenuPatch::Selected(sel)) => {
2731                            let idx = sel.map_or(-1, |i| i as c_int);
2732                            match host {
2733                                Some(nav) => ffi::day_xaml_nav_set_selected(nav, idx),
2734                                None => ffi::day_xaml_navlist_set_selected(h.0, idx),
2735                            }
2736                        }
2737                        // The row set changed (a filtered sidebar, a data-driven list). Without
2738                        // this the pane kept its original rows for the life of the window, and
2739                        // NAV_MENU_ROWS — which `measure` sizes the list from — went stale.
2740                        // Text badges still have no NavigationView counterpart and are dropped
2741                        // here as at realize; the trailing status GLYPH does have one (it
2742                        // composes into the item's Content) and rides along below, as do the
2743                        // section titles (a NavigationViewItemHeader ahead of the group).
2744                        Some(NavMenuPatch::Items {
2745                            items,
2746                            icons,
2747                            tints,
2748                            badge_icons,
2749                            badge_tints,
2750                            sections,
2751                            selected,
2752                            document_keys,
2753                            ..
2754                        }) => {
2755                            let idx = selected.map_or(-1, |i| i as c_int);
2756                            let joined = cstr(&items.join("\n"));
2757                            let sections_joined = cstr(&join_sections(sections));
2758                            if let Some(nav) = host {
2759                                let icons_joined = icons
2760                                    .iter()
2761                                    .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2762                                    .collect::<Vec<_>>()
2763                                    .join("\n");
2764                                ffi::day_xaml_document_items(
2765                                    nav,
2766                                    cstr(&items.join("\u{1f}")).as_ptr(),
2767                                    cstr(&document_keys.join("\u{1f}")).as_ptr(),
2768                                );
2769                                ffi::day_xaml_nav_set_items(
2770                                    nav,
2771                                    joined.as_ptr(),
2772                                    cstr(&icons_joined).as_ptr(),
2773                                    cstr(&join_geoms(icons)).as_ptr(),
2774                                    cstr(&join_tints(tints)).as_ptr(),
2775                                    cstr(
2776                                        &badge_icons
2777                                            .iter()
2778                                            .map(|ic| ic.as_deref().map_or_default(icon_file_name))
2779                                            .collect::<Vec<_>>()
2780                                            .join("\n"),
2781                                    )
2782                                    .as_ptr(),
2783                                    cstr(&join_geoms(badge_icons)).as_ptr(),
2784                                    cstr(&join_tints(badge_tints)).as_ptr(),
2785                                    sections_joined.as_ptr(),
2786                                );
2787                                ffi::day_xaml_nav_set_selected(nav, idx);
2788                            } else {
2789                                ffi::day_xaml_navlist_set_items(
2790                                    h.0,
2791                                    joined.as_ptr(),
2792                                    sections_joined.as_ptr(),
2793                                );
2794                                ffi::day_xaml_navlist_set_selected(h.0, idx);
2795                                let headings = sections.iter().filter(|s| s.is_some()).count();
2796                                NAV_MENU_ROWS.with(|m| {
2797                                    m.borrow_mut().insert(h.0 as usize, (items.len(), headings))
2798                                });
2799                            }
2800                        }
2801                        Some(NavMenuPatch::IconProgress(_)) | None => {}
2802                    }
2803                }
2804                // Split navs show the current destination in the NavigationView Header (the whole
2805                // point of the Settings-like presentation); Pushed/Title carry that title. Two-pane
2806                // navs need no native work — NavLayout re-places the pages.
2807                // Emulated cover (docs/cover.md): present = re-home onto the content Canvas
2808                // (appended last = topmost) with an opaque theme-background surface; dismiss =
2809                // hide + report `CoverHidden` at once. No interactive dismissal here.
2810                kinds::COVER => {
2811                    if let Some(p) = patch.downcast_ref::<CoverPatch>() {
2812                        let node = COVER_IDS
2813                            .with(|m| m.borrow().get(&(h.0 as usize)).copied())
2814                            .unwrap_or(day_spec::WINDOW_NODE);
2815                        match p {
2816                            CoverPatch::Present { background, .. } => {
2817                                // The cover takes every press over the content beneath it.
2818                                ffi::day_xaml_hit_on(h.0);
2819                                // Its ground follows the appearance: an ink, or the page
2820                                // background of the scheme in force.
2821                                match *background {
2822                                    Some(bg) => paint_inks(
2823                                        h.0,
2824                                        InkSlot::Surface,
2825                                        bg.is_dynamic(),
2826                                        // A live cover handle, on the UI thread.
2827                                        move |h, palette| {
2828                                            ffi::day_xaml_container_set_bg(
2829                                                h,
2830                                                ink_argb(bg, palette),
2831                                            );
2832                                        },
2833                                    ),
2834                                    None => paint_inks(h.0, InkSlot::Surface, true, |h, _| {
2835                                        ffi::day_xaml_cover_ground(h);
2836                                    }),
2837                                }
2838                                // The ROOT canvas, not the content one: a cover parented to the
2839                                // content canvas is bounded by the page area, leaving the menu
2840                                // bar, toolbar and nav pane on show and still clickable — so the
2841                                // "fullscreen" cover covered neither the chrome nor the user's
2842                                // ability to navigate out from under it.
2843                                let root = ffi::day_xaml_window_chrome_root(self.window);
2844                                // Reparent, not add: the cover is realized under its day parent
2845                                // in the content canvas, and XAML refuses a second logical parent
2846                                // (the throw is swallowed), so an `add_child` here moved nothing.
2847                                ffi::day_xaml_reparent(root, h.0);
2848                                let (y, size) = cover_frame(h.0, cover_extent(self.window));
2849                                ffi::day_xaml_set_geometry(
2850                                    h.0,
2851                                    0,
2852                                    y.round() as c_int,
2853                                    size.width.round() as c_int,
2854                                    size.height.round() as c_int,
2855                                );
2856                                ffi::day_xaml_set_visible(h.0, 1);
2857                                COVERS.with(|c| c.borrow_mut().push((h.0, node)));
2858                                emit(node, Event::FrameChanged(size));
2859                            }
2860                            CoverPatch::DismissDisabled(_) => {}
2861                            CoverPatch::Dismiss => {
2862                                ffi::day_xaml_set_visible(h.0, 0);
2863                                COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
2864                                emit(node, Event::CoverHidden);
2865                            }
2866                        }
2867                    }
2868                }
2869                kinds::INSPECTOR => {
2870                    if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>()
2871                    {
2872                        ffi::day_xaml_inspector_set_open(h.0, c_int::from(*v));
2873                    }
2874                }
2875                kinds::NAV => {
2876                    if let Some(p) = patch.downcast_ref::<day_spec::props::DocumentTabsPatch>() {
2877                        ffi::day_xaml_document_chrome(h.0, c_int::from(p.native));
2878                        return;
2879                    }
2880                    if let Some(np) = patch.downcast_ref::<NavPatch>() {
2881                        #[expect(
2882                            clippy::match_same_arms,
2883                            reason = "each variant that sets no title keeps its own explanation"
2884                        )]
2885                        let title = match np {
2886                            NavPatch::Pushed { title, .. } => Some(title.as_str()),
2887                            NavPatch::Title(t) => Some(t.as_str()),
2888                            // The pop's header restore happens in stack_sync (after the page
2889                            // leaves detail_pages), where the new top's title is known.
2890                            NavPatch::Popped => None,
2891                            // NavigationView BackRequested already routes back through Day
2892                            // (never a native auto-pop), so nothing to suppress here.
2893                            NavPatch::GuardTop(_) => None,
2894                            NavPatch::Reorder(order) => {
2895                                NAV_STATE.with(|m| {
2896                                    if let Some(NavState::Split(st)) =
2897                                        m.borrow_mut().get_mut(&(h.0 as usize))
2898                                    {
2899                                        let old = st.detail_pages.clone();
2900                                        st.detail_pages = order
2901                                            .iter()
2902                                            .filter_map(|i| old.get(*i).cloned())
2903                                            .collect();
2904                                    }
2905                                });
2906                                None
2907                            }
2908                            // Unreachable: this backend answers `Cap::NavRepresent =
2909                            // Unsupported`, so the pieces layer never sends it. A NavigationView
2910                            // owns its own PaneDisplayMode, so re-presenting here means driving
2911                            // that rather than re-homing pages (docs/size-classes.md).
2912                            NavPatch::Presentation(_) => None,
2913                            // The resident-page switch (docs/navigation.md): show that
2914                            // destination and hide its siblings — the same visibility pass
2915                            // `stack_sync` makes, driven by the app's selection rather than depth.
2916                            // No header change: a tab bar names the destination itself.
2917                            NavPatch::Select(i) => {
2918                                // Recorded, not just applied: pages inserted later (a data-driven
2919                                // tab set growing) have to land on the same answer.
2920                                NAV_STATE.with(|m| {
2921                                    if let Some(NavState::Split(st)) =
2922                                        m.borrow_mut().get_mut(&(h.0 as usize))
2923                                    {
2924                                        st.selected = *i;
2925                                    }
2926                                });
2927                                select_sync(h.0);
2928                                None
2929                            }
2930                            // Never arrive: this backend answers `Cap::NavContentList`
2931                            // Unsupported, so the pieces layer composes the pane itself
2932                            // (docs/navigation.md) — the qt twin's arm.
2933                            NavPatch::ListVisible(_) | NavPatch::ListInStack(_) => None,
2934                        };
2935                        if let Some(title) = title {
2936                            let nav = NAV_STATE.with(|m| {
2937                                let mut m = m.borrow_mut();
2938                                match m.get_mut(&(h.0 as usize)) {
2939                                    Some(NavState::Split(s)) => {
2940                                        // Record on the top entry so a later pop can restore it.
2941                                        if let Some(top) = s.detail_pages.last_mut() {
2942                                            top.2 = title.to_string();
2943                                        }
2944                                        Some(s.nav_view)
2945                                    }
2946                                    _ => None,
2947                                }
2948                            });
2949                            if let Some(nav) = nav {
2950                                ffi::day_xaml_nav_set_header(nav, cstr(title).as_ptr());
2951                            }
2952                        }
2953                    }
2954                }
2955                kinds::PICKER => picker::update_any(self, h, patch),
2956                kinds::TEXT_AREA => textarea::update_any(self, h, patch),
2957                kinds::TEXT_FIELD => {
2958                    if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
2959                        match p {
2960                            TextFieldPatch::Text { text, from_native } => {
2961                                if !*from_native {
2962                                    let node = TEXT_FIELD_NODE
2963                                        .with(|m| m.borrow().get(&(h.0 as usize)).copied());
2964                                    if let Some(node) = node {
2965                                        TEXT_FIELD_ECHO
2966                                            .with(|m| m.borrow_mut().insert(node, text.clone()));
2967                                    }
2968                                    ffi::day_xaml_textbox_set_text(h.0, cstr(text).as_ptr());
2969                                }
2970                            }
2971                            TextFieldPatch::Placeholder(t) => {
2972                                ffi::day_xaml_textbox_set_placeholder(h.0, cstr(t).as_ptr());
2973                            }
2974                            TextFieldPatch::Enabled(e) => {
2975                                ffi::day_xaml_set_enabled(h.0, c_int::from(*e));
2976                            }
2977                            TextFieldPatch::Select(sel) => {
2978                                let at = |n: usize| n.min(c_int::MAX as usize) as c_int;
2979                                ffi::day_xaml_textbox_select(h.0, at(sel.start), at(sel.end));
2980                            }
2981                        }
2982                    }
2983                }
2984                _ => {
2985                    if let Some(update) = self.registry.get(kind).map(|r| r.update) {
2986                        update(self, h, patch);
2987                    }
2988                }
2989            }
2990        }
2991    }
2992
2993    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
2994    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
2995        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
2996        // the hook needs it mutably.
2997        let f = self.registry.get(kind).and_then(|r| r.release);
2998        if let Some(f) = f {
2999            f(self, h);
3000        }
3001    }
3002    fn release(&mut self, h: WinHandle) {
3003        tree::release(h.0 as usize);
3004        // A drag region's element is held by the shim's hit test; let it go with the node.
3005        if DRAG_REGIONS.with(|d| d.borrow_mut().remove(&(h.0 as usize))) {
3006            unsafe { ffi::day_xaml_set_drag_region(h.0, 0) };
3007        }
3008        // A released window content = that window is gone (docs/windows.md teardown): Now
3009        // destroy the whole secondary window, never before (child releases come first).
3010        self.secondary.retain(|w| {
3011            if w.content == h.0 {
3012                unsafe { ffi::day_xaml_window_destroy2(w.win) };
3013                false
3014            } else {
3015                true
3016            }
3017        });
3018        // The PRIMARY window's root, released the same way now that it is an ordinary window
3019        // (docs/windows.md close policy). day-core has finished with its content, so the host
3020        // can go — and if that was the last primary, `quit_app` follows right behind.
3021        if !self.primary_root.is_null() && self.primary_root == h.0 {
3022            self.primary_root = std::ptr::null_mut();
3023            unsafe { ffi::day_xaml_destroy_primary() };
3024        }
3025        let key = h.0 as usize;
3026        BUTTON_MENUS.with(|m| m.borrow_mut().retain(|_, (button, _)| *button != key));
3027        if let Some(node) = LABEL_NODE.with(|m| m.borrow_mut().remove(&key)) {
3028            LABEL_TEXT.with(|m| m.borrow_mut().remove(&node));
3029        }
3030        LABEL_ELIDE.with(|m| m.borrow_mut().remove(&key));
3031        LABEL_ALIGN.with(|m| m.borrow_mut().remove(&key));
3032        LABEL_RUNS.with(|m| m.borrow_mut().remove(&key));
3033        INKS.with(|m| m.borrow_mut().retain(|(view, _), _| *view != key));
3034        SURFACES.with(|m| m.borrow_mut().remove(&key));
3035        if let Some(node) = TEXT_FIELD_NODE.with(|m| m.borrow_mut().remove(&key)) {
3036            TEXT_FIELD_ECHO.with(|m| m.borrow_mut().remove(&node));
3037        }
3038        NAV_MENU_ROWS.with(|m| m.borrow_mut().remove(&key));
3039        NAV_PAGE_IDS.with(|m| m.borrow_mut().remove(&key));
3040        // A disposed inspector host drops its state AND its by-node-id pane map, so a recycled
3041        // address (or node id) can't inherit the dead split's panes.
3042        if let Some(insp) = INSPECTOR_STATE.with(|m| m.borrow_mut().remove(&key)) {
3043            INSPECTOR_PANES_BY_HOST.with(|m| {
3044                m.borrow_mut().remove(&insp.node);
3045            });
3046        }
3047        INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().remove(&key));
3048        NAV_MENU_HOST.with(|m| m.borrow_mut().remove(&key));
3049        SPLIT_SIDEBAR_PAGES.with(|m| m.borrow_mut().remove(&key));
3050        if let Some(NavState::Split(s)) = NAV_STATE.with(|m| m.borrow_mut().remove(&key)) {
3051            NAV_HOST_BY_ID.with(|m| m.borrow_mut().retain(|_, v| *v != s.nav_view));
3052            unsafe { ffi::day_xaml_delete(s.content_host) };
3053        }
3054        list::release(key);
3055        // The scroll host's content Canvas is boxed separately from the ScrollViewer handle.
3056        if let Some(content) = SCROLL_STATE.with(|m| m.borrow_mut().remove(&key)) {
3057            unsafe { ffi::day_xaml_delete(content) };
3058        }
3059        GESTURES.with(|g| g.borrow_mut().retain(|(ptr, _)| *ptr != key));
3060        CANVASES.with(|c| c.borrow_mut().remove(&key));
3061        // A cover torn down while presented (no Dismiss patch first) must leave the
3062        // presented set — `window_resized` writes through every entry's raw pointer, and a
3063        // stale one is a use-after-free once `day_xaml_delete` runs below.
3064        COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
3065        COVER_HALF.with(|s| s.borrow_mut().remove(&(h.0 as usize)));
3066        COVER_IDS.with(|m| {
3067            m.borrow_mut().remove(&key);
3068        });
3069        // One sweep drops this handle from every SideTable registered on this thread — the
3070        // textarea line bands today, and any table added later — so an element recycling the
3071        // freed address can't inherit the dead element's entries. (The explicit purges above
3072        // stay: they key by node id / value pairs, not this address.)
3073        day_spec::sidetable::sweep(key);
3074        unsafe { ffi::day_xaml_delete(h.0) };
3075    }
3076
3077    fn insert(&mut self, parent: &WinHandle, child: &WinHandle, index: usize) {
3078        // Nav host: for a nav host, page index 0 = sidebar (PaneHeader), the rest = detail. For a
3079        // stack, every page stacks in the content region.
3080        enum NavInsert {
3081            No,
3082            Done,
3083            /// A page landed in the content region: seed its frame. `nav_stack` also re-syncs the
3084            /// stack's top-page visibility + back button.
3085            Content {
3086                node: NodeId,
3087                host_id: u64,
3088                stack: bool,
3089                resident: bool,
3090            },
3091        }
3092        let nav = NAV_STATE.with(|m| {
3093            let mut m = m.borrow_mut();
3094            let Some(NavState::Split(s)) = m.get_mut(&(parent.0 as usize)) else {
3095                return NavInsert::No;
3096            };
3097            let node = NAV_PAGE_IDS
3098                .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
3099                .unwrap_or(NodeId(0));
3100            if !s.is_stack && index == 0 {
3101                // The sidebar page (day's logo/title header piece) → the NavigationView's
3102                // PaneHeader; clipped to a fixed height by set_frame.
3103                unsafe { ffi::day_xaml_nav_set_pane_header(s.nav_view, child.0) };
3104                s.sidebar_page = Some((child.0, node));
3105                SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().insert(child.0 as usize));
3106                NavInsert::Done
3107            } else {
3108                // Detail / stack page → nv.Content (day positions it by absolute frame).
3109                unsafe { ffi::day_xaml_add_child(s.content_host, child.0) };
3110                s.detail_pages.push((child.0, node, String::new()));
3111                NavInsert::Content {
3112                    node,
3113                    host_id: s.node,
3114                    stack: s.is_stack,
3115                    resident: s.resident,
3116                }
3117            }
3118        });
3119        match nav {
3120            NavInsert::No => {}
3121            NavInsert::Done => return,
3122            NavInsert::Content {
3123                node,
3124                host_id,
3125                stack,
3126                resident,
3127            } => {
3128                // The NavigationView content region is already sized, and adding a child won't
3129                // refire its SizeChanged — so seed the new page with the current content bounds
3130                // (else NavLayout would fall back to the split size). Emitted outside the NAV_STATE
3131                // borrow (FrameChanged re-enters the tree).
3132                //
3133                // Posted to the next loop turn, not emitted here: the page is inserted while Day
3134                // is still building it, before its FrameChanged handler exists, so an event sent
3135                // now was dropped and the page kept NavLayout's fallback, the whole host height.
3136                // Under WinUI 3 that is wrong by the NavigationView's header (the page title band
3137                // above the content), so every newly opened page overhung the window by that
3138                // much, clipped at the bottom and short of its scroll extent until a resize
3139                // re-reported the size. (System XAML shows no header there, so the fallback
3140                // happened to be right.) Resolve by node ids when the post runs: the host can
3141                // be released before then, freeing content_host, or this page can be removed
3142                // while the host stays alive. Capturing the raw handle would use freed memory.
3143                let boxed: Box<dyn FnOnce() + Send> = Box::new(move || {
3144                    let Some(host) = nav_page_content_host(host_id, node) else {
3145                        return;
3146                    };
3147                    let (mut w, mut h) = (0.0, 0.0);
3148                    unsafe { ffi::day_xaml_widget_size(host, &raw mut w, &raw mut h) };
3149                    if w > 0.0 && h > 0.0 {
3150                        emit(node, Event::FrameChanged(Size::new(w, h)));
3151                    }
3152                });
3153                let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
3154                unsafe { ffi::day_xaml_post(run_posted, data) };
3155                if stack {
3156                    stack_sync(parent.0);
3157                } else if resident {
3158                    select_sync(parent.0);
3159                }
3160                return;
3161            }
3162        }
3163        // Inspector host: each pane's content lands in its side's Canvas, and the pane's node
3164        // id is recorded so region-size reports can reach it (docs/inspector.md).
3165        let inspected = INSPECTOR_STATE.with(|m| {
3166            let m = m.borrow();
3167            let state = m.get(&(parent.0 as usize))?;
3168            let (pane_id, panel) = INSPECTOR_PANE_IDS
3169                .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
3170                .unwrap_or((NodeId(0), index == 1));
3171            let host = if panel {
3172                state.panel_host
3173            } else {
3174                state.content_host
3175            };
3176            unsafe { ffi::day_xaml_add_child(host, child.0) };
3177            INSPECTOR_PANES_BY_HOST.with(|p| {
3178                if let Some(nodes) = p.borrow_mut().get_mut(&state.node) {
3179                    if panel {
3180                        nodes.panel = Some(pane_id);
3181                    } else {
3182                        nodes.content = Some(pane_id);
3183                    }
3184                }
3185            });
3186            Some((host, pane_id))
3187        });
3188        if let Some((host, pane_id)) = inspected {
3189            // Seed the pane with the host's current bounds — adding a child does not refire
3190            // SizeChanged (the nav content-region rule above).
3191            let (mut w, mut h) = (0.0, 0.0);
3192            unsafe { ffi::day_xaml_widget_size(host, &raw mut w, &raw mut h) };
3193            if w > 0.0 && h > 0.0 && pane_id.0 != 0 {
3194                emit(pane_id, Event::FrameChanged(Size::new(w, h)));
3195            }
3196            return;
3197        }
3198        // Scroll host: children live in the inner content Canvas, not the ScrollViewer itself.
3199        let target = SCROLL_STATE
3200            .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
3201            .unwrap_or(parent.0);
3202        unsafe { ffi::day_xaml_add_child(target, child.0) };
3203    }
3204
3205    fn remove(&mut self, parent: &WinHandle, child: &WinHandle) {
3206        // Nav pages live in a pane / the NavigationView content — remove from wherever they landed.
3207        let removed = NAV_STATE.with(|m| {
3208            let mut m = m.borrow_mut();
3209            let Some(NavState::Split(s)) = m.get_mut(&(parent.0 as usize)) else {
3210                return None;
3211            };
3212            s.detail_pages.retain(|&(p, _, _)| p != child.0);
3213            SPLIT_SIDEBAR_PAGES.with(|p| p.borrow_mut().remove(&(child.0 as usize)));
3214            unsafe { ffi::day_xaml_remove_child(s.content_host, child.0) };
3215            Some((s.is_stack, s.resident))
3216        });
3217        match removed {
3218            Some((true, _)) => {
3219                // A stack page popped: re-show the new top + refresh the back button.
3220                stack_sync(parent.0);
3221                return;
3222            }
3223            Some((false, true)) => {
3224                // A resident page went away (a data-driven tab set shrinking): the survivors have
3225                // shifted, so re-apply the selection rather than leave a hidden page on screen.
3226                select_sync(parent.0);
3227                return;
3228            }
3229            // A split nav's page was swapped out. Its successor is shown as it arrives, exactly
3230            // as before this pass existed — there is no resident set here to choose among.
3231            Some((false, false)) => return,
3232            None => {}
3233        }
3234        // Inspector pane content: remove from whichever side's Canvas it landed in.
3235        let inspected = INSPECTOR_STATE.with(|m| {
3236            m.borrow().get(&(parent.0 as usize)).map(|state| {
3237                let panel = INSPECTOR_PANE_IDS
3238                    .with(|ids| ids.borrow().get(&(child.0 as usize)).map(|(_, p)| *p))
3239                    .unwrap_or(false);
3240                if panel {
3241                    state.panel_host
3242                } else {
3243                    state.content_host
3244                }
3245            })
3246        });
3247        if let Some(host) = inspected {
3248            unsafe { ffi::day_xaml_remove_child(host, child.0) };
3249            return;
3250        }
3251        let target = SCROLL_STATE
3252            .with(|m| m.borrow().get(&(parent.0 as usize)).copied())
3253            .unwrap_or(parent.0);
3254        unsafe { ffi::day_xaml_remove_child(target, child.0) };
3255    }
3256
3257    fn move_child(&mut self, _parent: &WinHandle, _child: &WinHandle, _to: usize) {
3258        // Absolute frames don't overlap: sibling z-order is irrelevant.
3259    }
3260
3261    fn measure(&mut self, h: &WinHandle, kind: PieceKind, p: Proposal) -> Size {
3262        match kind {
3263            kinds::LABEL => {
3264                let nat = natural(h.0);
3265                match p.width {
3266                    Some(pw) if nat.width > pw => {
3267                        // Height-for-width: re-measure wrapped at the proposed width.
3268                        let mut w = 0.0;
3269                        let mut hh = 0.0;
3270                        unsafe { ffi::day_xaml_measure(h.0, pw, -1.0, &raw mut w, &raw mut hh) };
3271                        Size::new(pw.ceil(), hh.ceil())
3272                    }
3273                    _ => Size::new(nat.width.ceil(), nat.height.ceil()),
3274                }
3275            }
3276            // Buttons hug their text like every other toolkit: the generic arm would take a
3277            // COLUMN's cross-axis width proposal and stretch the button across the full span.
3278            kinds::BUTTON => {
3279                let nat = natural(h.0);
3280                Size::new(nat.width.ceil(), nat.height.ceil())
3281            }
3282            kinds::SLIDER => Size::new(p.width.unwrap_or(180.0), natural(h.0).height.max(24.0)),
3283            kinds::PICKER => picker::measure_any(self, h, p),
3284            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
3285            kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(180.0), natural(h.0).height.max(28.0)),
3286            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
3287            // The list host fills whatever frame layout gives it; cells fill its width.
3288            kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
3289            kinds::NAV_MENU => {
3290                // Split navs render the menu as the NavigationView's own pane, so the day node is an
3291                // invisible placeholder that must take no layout space.
3292                if NAV_MENU_HOST.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
3293                    return Size::new(0.0, 0.0);
3294                }
3295                let (rows, headings) = NAV_MENU_ROWS
3296                    .with(|m| m.borrow().get(&(h.0 as usize)).copied().unwrap_or((0, 0)));
3297                Size::new(
3298                    p.width.unwrap_or(220.0),
3299                    p.height
3300                        .unwrap_or(rows as f64 * 40.0 + headings as f64 * 32.0 + 8.0),
3301                )
3302            }
3303            kinds::PROGRESS => {
3304                // Determinate bar fills the proposed width; the indeterminate ring is square.
3305                let nat = natural(h.0);
3306                if unsafe { ffi::day_xaml_progress_is_ring(h.0) } != 0 {
3307                    let side = nat.width.max(nat.height).max(20.0);
3308                    Size::new(side, side)
3309                } else {
3310                    Size::new(p.width.unwrap_or(nat.width.max(20.0)), nat.height.max(6.0))
3311                }
3312            }
3313            _ => {
3314                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
3315                    return measure(self, h, p);
3316                }
3317                let nat = natural(h.0);
3318                Size::new(
3319                    p.width.unwrap_or(nat.width).ceil(),
3320                    p.height.unwrap_or(nat.height).ceil(),
3321                )
3322            }
3323        }
3324    }
3325
3326    fn set_cursor(&mut self, h: &WinHandle, cursor: Cursor) {
3327        // The shim hooks PointerEntered/Exited on the element and the host window answers
3328        // WM_SETCURSOR with a Win32 `IDC_*` shape (docs/cursor.md). Grab, zoom, column/row
3329        // resize, copy, alias, cell, and vertical text take their nearest, so `Cap::Cursor`
3330        // answers Emulated.
3331        unsafe { ffi::day_xaml_set_cursor(h.0, win_cursor_code(&cursor)) };
3332    }
3333
3334    fn set_selectable(&mut self, h: &WinHandle, selectable: bool) -> Option<WinHandle> {
3335        // The shim try_as's to a TextBlock, so a non-label handle is a safe no-op (docs/text.md).
3336        unsafe { ffi::day_xaml_label_set_selectable(h.0, c_int::from(selectable)) };
3337        None
3338    }
3339
3340    /// XAML hides characters with a class of its own, so `secure` rebuilds the field: a `TextBox`
3341    /// becomes a `PasswordBox` and back, in the shim, which builds the replacement through the
3342    /// calls `realize` makes and hands it the old control's text, state, place and focus
3343    /// (docs/textfield.md). Everything else is a property of whichever class is live.
3344    fn set_input_traits(&mut self, h: &WinHandle, traits: &InputTraits) -> Option<WinHandle> {
3345        let key = h.0 as usize;
3346        let node = TEXT_FIELD_NODE.with(|m| m.borrow().get(&key).copied())?;
3347        let swapped = unsafe {
3348            ffi::day_xaml_field_set_secure(h.0, c_int::from(traits.secure), node, on_text, on_focus)
3349        };
3350        let live = if swapped.is_null() { h.0 } else { swapped };
3351        // The shim declines the rebuild when the field hangs somewhere it cannot take the
3352        // replacement's place. A password left in a `TextBox` is worth saying out loud.
3353        if traits.secure && unsafe { ffi::day_xaml_field_is_secure(live) } == 0 {
3354            log::error!(
3355                "day-toolkit-winui: a secure text field could not be rebuilt as a PasswordBox; its \
3356                 characters are showing"
3357            );
3358        }
3359        // The InputScope the touch keyboard lays itself out from, and whether the text is an
3360        // identifier, which is never spell-checked or predicted. A password or a one-time code
3361        // has no scope of its own on a `TextBox`; a secure field takes the PIN pad for the
3362        // numeric ones and is otherwise XAML's own password scope.
3363        let (scope, plain) = match traits.purpose {
3364            InputPurpose::Text => (0, false),
3365            InputPurpose::Name => (1, true),
3366            InputPurpose::Email => (2, true),
3367            InputPurpose::Url => (3, true),
3368            InputPurpose::Phone => (4, true),
3369            InputPurpose::Number | InputPurpose::Decimal => (5, false),
3370            InputPurpose::OneTimeCode => (5, true),
3371            InputPurpose::Username | InputPurpose::Password | InputPurpose::NewPassword => {
3372                (0, true)
3373            }
3374        };
3375        // No native length limit: `MaxLength` counts UTF-16 units where the bound counts
3376        // characters, so it would refuse text the bound allows. day-pieces holds the bound. The
3377        // action key's label has no counterpart on this keyboard.
3378        unsafe {
3379            ffi::day_xaml_field_set_traits(
3380                live,
3381                c_int::from(traits.read_only),
3382                scope,
3383                c_int::from(plain),
3384            );
3385        };
3386        if swapped.is_null() {
3387            return None;
3388        }
3389        let new = WinHandle(swapped);
3390        // day-core adopts the replacement and drops the old handle without a `release`, so
3391        // everything keyed by the old pointer moves or goes here.
3392        TEXT_FIELD_NODE.with(|m| m.borrow_mut().insert(swapped as usize, node));
3393        let gestures: Vec<c_int> = GESTURES.with(|g| {
3394            g.borrow()
3395                .iter()
3396                .filter(|(ptr, _)| *ptr == key)
3397                .map(|(_, k)| *k)
3398                .collect()
3399        });
3400        for k in gestures {
3401            GESTURES.with(|g| g.borrow_mut().insert((swapped as usize, k)));
3402            unsafe { ffi::day_xaml_enable_gesture(swapped, node, k, on_gesture) };
3403        }
3404        transfer::migrate(key, &new);
3405        // The replacement's template is not built yet, and its height is the template's.
3406        unsafe { ffi::day_xaml_on_control_loaded(swapped, node, control_loaded) };
3407        self.release(*h);
3408        Some(new)
3409    }
3410
3411    // Animatable visual channels (DESIGN.md §8.4): cheap per-node opacity + transform that don't
3412    // relayout. `anim = Some` hands the target to XAML's compositor as a Storyboard; `None` sets it
3413    // outright. Day never ticks these frames itself (§0.3).
3414    fn set_opacity(&mut self, h: &WinHandle, opacity: f64, anim: Option<&AnimSpec>) {
3415        let anim = XamlAnim::new(anim);
3416        unsafe { ffi::day_xaml_set_opacity(h.0, opacity, XamlAnim::ptr(anim.as_ref())) };
3417    }
3418
3419    fn set_transform(&mut self, h: &WinHandle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
3420        // A CompositeTransform about the element's center — the same anchor AppKit's layer and
3421        // Qt's painter transform use, so a rotated/scaled box matches across backends.
3422        let anim = XamlAnim::new(anim);
3423        unsafe {
3424            ffi::day_xaml_set_transform(
3425                h.0,
3426                t.tx,
3427                t.ty,
3428                t.sx,
3429                t.sy,
3430                t.rotation.degrees(),
3431                XamlAnim::ptr(anim.as_ref()),
3432            );
3433        };
3434    }
3435
3436    /// A `TextBlock` publishes `BaselineOffset`; every other control keeps its text inside a
3437    /// template that is not built until the control is in the visual tree, so the shim derives
3438    /// those from the control's font size and its own padding/border (docs/baseline.md). Hence
3439    /// `Emulated` — accurate for the Segoe faces XAML ships, not read off the platform.
3440    fn first_baseline(&mut self, h: &WinHandle, kind: PieceKind, size: Size) -> Option<f64> {
3441        if !day_spec::kind_has_baseline(kind) {
3442            return None;
3443        }
3444        let b = unsafe { ffi::day_xaml_baseline(h.0, size.height) };
3445        (b >= 0.0).then_some(b)
3446    }
3447
3448    fn set_frame(&mut self, h: &WinHandle, frame: Rect, anim: Option<&AnimSpec>) {
3449        // A split nav's sidebar page IS the NavigationView's PaneHeader: clip it to a fixed header
3450        // height (a Canvas has no desired size) so day's logo/title piece sits at the pane top; the
3451        // NavigationView owns everything below it. Width follows the frame day proposes.
3452        if SPLIT_SIDEBAR_PAGES.with(|m| m.borrow().contains(&(h.0 as usize))) {
3453            unsafe {
3454                ffi::day_xaml_set_geometry(
3455                    h.0,
3456                    0,
3457                    0,
3458                    frame.size.width.round() as c_int,
3459                    NAV_PANE_HEADER_H,
3460                );
3461            };
3462            return;
3463        }
3464        if let Some(anim) = XamlAnim::new(anim) {
3465            // Position and size played from the frame shown now (docs/tween.md).
3466            unsafe {
3467                ffi::day_xaml_set_geometry_animated(
3468                    h.0,
3469                    frame.origin.x.round(),
3470                    frame.origin.y.round(),
3471                    frame.size.width.round(),
3472                    frame.size.height.round(),
3473                    &raw const anim.raw,
3474                );
3475            }
3476        } else {
3477            unsafe {
3478                ffi::day_xaml_set_geometry(
3479                    h.0,
3480                    frame.origin.x.round() as c_int,
3481                    frame.origin.y.round() as c_int,
3482                    frame.size.width.round() as c_int,
3483                    frame.size.height.round() as c_int,
3484                );
3485            };
3486        }
3487        // (Nav hosts are NavigationViews — they reflow their own regions, which report FrameChanged.)
3488        list::frame(h, frame);
3489        // A head- or middle-truncated label is cut again for its new width.
3490        let elided_at = LABEL_ELIDE.with(|m| m.borrow().get(&(h.0 as usize)).map(|e| e.width));
3491        if let Some(width) = elided_at
3492            && (width - frame.size.width).abs() > 0.25
3493        {
3494            elide_label(h.0, frame.size.width);
3495        }
3496    }
3497
3498    // Scroll (docs §7.6): size the ScrollViewer's inner content Canvas to the content extent so it
3499    // clips + scrolls; the offset/scroll-to operate on the ScrollViewer handle directly.
3500    fn set_scroll_content(&mut self, h: &WinHandle, content: Size) {
3501        if let Some(c) = SCROLL_STATE.with(|m| m.borrow().get(&(h.0 as usize)).copied()) {
3502            unsafe {
3503                ffi::day_xaml_scroll_set_content_size(
3504                    c,
3505                    content.width.round() as c_int,
3506                    content.height.round() as c_int,
3507                );
3508            };
3509        }
3510    }
3511
3512    /// A WinUI `ListViewItem`: 12px horizontal padding and a 40px minimum height.
3513    fn list_row_metrics(&mut self, _h: &WinHandle) -> day_spec::RowMetrics {
3514        day_spec::RowMetrics {
3515            insets: day_spec::Insets {
3516                top: 0.0,
3517                leading: 12.0,
3518                bottom: 0.0,
3519                trailing: 12.0,
3520            },
3521            min_height: 40.0,
3522        }
3523    }
3524
3525    fn scroll_to(&mut self, h: &WinHandle, target: Rect, animated: bool) {
3526        unsafe {
3527            ffi::day_xaml_scroll_to(
3528                h.0,
3529                target.origin.y.round() as c_int,
3530                target.size.height.round() as c_int,
3531                c_int::from(animated),
3532            );
3533        };
3534    }
3535
3536    fn scroll_offset(&mut self, h: &WinHandle) -> Point {
3537        let (mut x, mut y) = (0.0_f64, 0.0_f64);
3538        unsafe { ffi::day_xaml_scroll_offset(h.0, &raw mut x, &raw mut y) };
3539        Point::new(x, y)
3540    }
3541
3542    fn enable_gesture(&mut self, h: &WinHandle, node: NodeId, kind: day_spec::GestureKind) {
3543        let k = match kind {
3544            // DoubleTapped, with the single tap held for the double-click time while both are
3545            // enabled; the pointer down observed with handledEventsToo; every contact by pointer
3546            // id (docs/gestures.md).
3547            day_spec::GestureKind::DoubleTap => 8,
3548            day_spec::GestureKind::Press => 9,
3549            day_spec::GestureKind::Touches => 10,
3550            day_spec::GestureKind::Tap => 0,
3551            day_spec::GestureKind::LongPress => 1,
3552            day_spec::GestureKind::Drag => 2,
3553            day_spec::GestureKind::Hover => 3,
3554            // A scale manipulation plus ctrl+wheel, and wheel ticks: every tick over a canvas,
3555            // sideways ones over any other container (docs/canvas.md "Zoom and pan").
3556            day_spec::GestureKind::Pinch => 4,
3557            // The same manipulation's rotation, so it runs alongside the pinch and the drag.
3558            day_spec::GestureKind::Rotate => 7,
3559            day_spec::GestureKind::Pan => {
3560                if CANVASES.with(|c| c.borrow().contains(&(h.0 as usize))) {
3561                    5
3562                } else {
3563                    6
3564                }
3565            }
3566        };
3567        // Idempotent per (handle, kind) — day-core may re-enable on rebuild.
3568        if !GESTURES.with(|g| g.borrow_mut().insert((h.0 as usize, k))) {
3569            return;
3570        }
3571        unsafe { ffi::day_xaml_enable_gesture(h.0, node.0, k, on_gesture) };
3572    }
3573
3574    fn focus(&mut self, h: &WinHandle, _node: NodeId, focused: bool) {
3575        // The shim resigns to the window's invisible focus sink — system XAML has no
3576        // "focus nothing" — and only while this control still owns focus.
3577        unsafe { ffi::day_xaml_control_focus(h.0, c_int::from(focused)) };
3578    }
3579
3580    fn set_event_sink(&mut self, sink: EventSink) {
3581        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
3582    }
3583
3584    fn set_a11y(&mut self, h: &WinHandle, a11y: &A11yProps) {
3585        use day_spec::Role;
3586        if let Some(id) = &a11y.identifier {
3587            unsafe { ffi::day_xaml_set_name(h.0, cstr(id).as_ptr()) };
3588        }
3589        // The rest crosses in one call; an unset member goes over as an empty string / 0 and
3590        // the shim leaves that property alone (docs/accessibility.md). Role codes are `Role`'s
3591        // declaration order, the table the shim's `day_xaml_set_a11y` documents too.
3592        let (role, level) = match a11y.role {
3593            Role::None => (0, 0),
3594            Role::Button => (1, 0),
3595            Role::Toggle => (2, 0),
3596            Role::Slider => (3, 0),
3597            Role::TextInput => (4, 0),
3598            Role::Heading(n) => (5, c_int::from(n)),
3599            Role::Image => (6, 0),
3600            Role::Meter => (7, 0),
3601            Role::Group => (8, 0),
3602            Role::Tree => (9, 0),
3603            Role::TreeItem => (10, 0),
3604            Role::Tab => (11, 0),
3605            Role::TabList => (12, 0),
3606        };
3607        let label = cstr(a11y.label.as_deref().unwrap_or(""));
3608        let hint = cstr(a11y.hint.as_deref().unwrap_or(""));
3609        let value = cstr(a11y.value.as_deref().unwrap_or(""));
3610        let hidden = c_int::from(a11y.hidden || a11y.decorative);
3611        unsafe {
3612            ffi::day_xaml_set_a11y(
3613                h.0,
3614                label.as_ptr(),
3615                hint.as_ptr(),
3616                value.as_ptr(),
3617                role,
3618                level,
3619                hidden,
3620            );
3621        };
3622    }
3623
3624    fn announce(&mut self, text: &str, urgent: bool) {
3625        unsafe { ffi::day_xaml_announce(cstr(text).as_ptr(), c_int::from(urgent)) };
3626    }
3627
3628    /// The element's own answers, read back by the shim: the automation peer's name, `ItemStatus`
3629    /// (where `set_a11y` puts a value), `AutomationId` and the role `set_a11y` wrote; the text a
3630    /// `TextBlock`, `TextBox` or Button shows; a Slider's value or a progress bar's fraction; a
3631    /// toggle's state; `IsEnabled`; Visibility up to the content canvas and the bounds in it.
3632    fn read_native(&self, h: &WinHandle) -> day_spec::NativeSnapshot {
3633        use day_spec::Role;
3634        let mut raw = ffi::DayXamlNative {
3635            found: 0,
3636            role: 0,
3637            level: 0,
3638            label: std::ptr::null_mut(),
3639            value: std::ptr::null_mut(),
3640            identifier: std::ptr::null_mut(),
3641            text: std::ptr::null_mut(),
3642            has_number: 0,
3643            number: 0.0,
3644            checked: -1,
3645            enabled: -1,
3646            visible: -1,
3647            has_frame: 0,
3648            x: 0.0,
3649            y: 0.0,
3650            w: 0.0,
3651            h: 0.0,
3652        };
3653        // SAFETY: `raw` is a live, writable `DayXamlNative`; the shim fills it in place.
3654        unsafe { ffi::day_xaml_read_native(h.0, &raw mut raw) };
3655        // Takes ownership of one of the shim's heap strings: copied out, then released.
3656        let take = |p: *mut c_char| -> Option<String> {
3657            if p.is_null() {
3658                return None;
3659            }
3660            // SAFETY: a non-null string from the shim is NUL-terminated and released exactly
3661            // once, here, through the shim's own free.
3662            unsafe {
3663                let s = CStr::from_ptr(p).to_string_lossy().into_owned();
3664                ffi::day_xaml_string_free(p);
3665                Some(s)
3666            }
3667        };
3668        let tri = |v: c_int| (v >= 0).then_some(v != 0);
3669        let found = raw.found != 0;
3670        let role = match raw.role {
3671            1 => Role::Button,
3672            2 => Role::Toggle,
3673            3 => Role::Slider,
3674            4 => Role::TextInput,
3675            5 => Role::Heading(raw.level.clamp(1, 9) as u8),
3676            6 => Role::Image,
3677            7 => Role::Meter,
3678            8 => Role::Group,
3679            9 => Role::Tree,
3680            10 => Role::TreeItem,
3681            11 => Role::Tab,
3682            12 => Role::TabList,
3683            _ => Role::None,
3684        };
3685        let (label, value, identifier) = (take(raw.label), take(raw.value), take(raw.identifier));
3686        // An elided label reads back whole (docs/text.md "Truncation").
3687        let shown = take(raw.text);
3688        let text = LABEL_ELIDE
3689            .with(|m| m.borrow().get(&(h.0 as usize)).map(|e| e.full.clone()))
3690            .or(shown);
3691        day_spec::NativeSnapshot {
3692            found,
3693            role: if found { role } else { Role::None },
3694            label: label.filter(|_| found),
3695            value: value.filter(|_| found),
3696            identifier: identifier.filter(|_| found),
3697            text,
3698            number: (raw.has_number != 0).then_some(raw.number),
3699            checked: tri(raw.checked),
3700            enabled: tri(raw.enabled),
3701            visible: tri(raw.visible),
3702            frame: (raw.has_frame != 0).then(|| Rect::new(raw.x, raw.y, raw.w, raw.h)),
3703        }
3704    }
3705
3706    // The values the storyboards write through the property system as they play, read on the
3707    // UI thread: opacity, the CompositeTransform's translation, the frame from Canvas.Left/Top
3708    // and Width/Height, and the fill brush's color (docs/tween.md "Mid-flight read-back").
3709    fn read_displayed(&self, h: &WinHandle) -> day_spec::Displayed {
3710        let mut out = [0.0f64; 11];
3711        // SAFETY: `out` has the eleven slots the shim writes.
3712        let read = unsafe { ffi::day_xaml_read_displayed(h.0, out.as_mut_ptr()) };
3713        let mut shown = day_spec::Displayed::default();
3714        if read & 1 != 0 {
3715            shown.opacity = Some(out[0]);
3716        }
3717        if read & 2 != 0 {
3718            shown.translation = Some(Point::new(out[1], out[2]));
3719        }
3720        if read & 4 != 0 {
3721            shown.frame = Some(Rect::new(out[3], out[4], out[5], out[6]));
3722        }
3723        if read & 8 != 0 {
3724            shown.background = Some(day_spec::Color::rgba(out[7], out[8], out[9], out[10]));
3725        }
3726        shown
3727    }
3728
3729    fn attach_tree(&mut self, host: &WinHandle, source: day_spec::TreeSource) {
3730        tree::attach(host.0 as usize, source);
3731    }
3732
3733    fn attach_list(&mut self, host: &WinHandle, source: day_spec::ListSource) {
3734        list::attach(host, source);
3735    }
3736
3737    fn set_context_menu(&mut self, h: &WinHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
3738        // The RAW items, verbatim: a right-click menu is the app's own tree, never the menu
3739        // bar — `standard_menu_bar_for` here (a copy-paste from `set_app_menu`) injected
3740        // File/Edit/View/Help slot-filling into every context menu.
3741        let mut spec = String::new();
3742        serialize_menu_xaml(items, &mut spec);
3743        unsafe { ffi::day_xaml_set_context_menu(h.0, cstr(&spec).as_ptr()) };
3744    }
3745
3746    fn set_button_menu(&mut self, h: &WinHandle, node: NodeId, f: day_spec::ContextMenuFn) {
3747        // The click arrives through `on_press`, which opens the menu (docs/menus.md).
3748        BUTTON_MENUS.with(|m| m.borrow_mut().insert(node.0, (h.0 as usize, f)));
3749    }
3750
3751    fn edit_toolbar(&mut self, h: &WinHandle, ops: &[day_spec::ToolbarOp]) -> bool {
3752        self.edit_toolbar(h, ops)
3753    }
3754
3755    fn update_toolbar(&mut self, h: &WinHandle, patch: &day_spec::ToolbarPatch) {
3756        self.patch_toolbar(h, patch);
3757    }
3758
3759    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
3760        if self.window.is_null() {
3761            return;
3762        }
3763        // Windows' bar: File, Edit, View, the app's own menus, then Help. No Window menu (MDI
3764        // is long gone) and no app menu — Exit lives in File, About in Help.
3765        let items = day_core::menu::standard_menu_bar_for(
3766            day_core::menu::MenuBarStyle::Windows,
3767            items.to_vec(),
3768        );
3769        let mut spec = String::new();
3770        serialize_menu_xaml(&items, &mut spec);
3771        // Kept, because day's app menu is installed once but Windows draws it per window: a
3772        // window opened later has to be given the menu that was set before it existed
3773        // (see `open_window`). Re-set on a locale change, so the stored spec stays current.
3774        self.menu_spec.clone_from(&spec);
3775        let c = cstr(&spec);
3776        unsafe { ffi::day_xaml_set_app_menu(self.window, c.as_ptr()) };
3777        // Every window already open shows the same bar — the menu is app-level, not per-window.
3778        // A Preferences panel is the exception and stays bare.
3779        for w in self.secondary.iter().filter(|w| !w.menuless) {
3780            unsafe { ffi::day_xaml_window_set_menu2(w.win, c.as_ptr()) };
3781        }
3782    }
3783
3784    fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
3785        use day_spec::present::PresentSpec;
3786        match spec {
3787            PresentSpec::Dialog { .. } => unsafe {
3788                ffi::day_xaml_present_dialog(
3789                    req,
3790                    cstr(spec.title()).as_ptr(),
3791                    cstr(spec.message().unwrap_or("")).as_ptr(),
3792                    cstr(&spec.buttons_joined()).as_ptr(),
3793                    cstr(&spec.roles_joined()).as_ptr(),
3794                    self.window,
3795                );
3796            },
3797            PresentSpec::Prompt {
3798                placeholder,
3799                initial,
3800                ok,
3801                cancel,
3802                ..
3803            } => unsafe {
3804                ffi::day_xaml_present_prompt(
3805                    req,
3806                    cstr(spec.title()).as_ptr(),
3807                    cstr(spec.message().unwrap_or("")).as_ptr(),
3808                    cstr(placeholder).as_ptr(),
3809                    cstr(initial).as_ptr(),
3810                    cstr(ok).as_ptr(),
3811                    cstr(cancel).as_ptr(),
3812                    self.window,
3813                );
3814            },
3815            PresentSpec::OpenFile { multiple, .. } => unsafe {
3816                ffi::day_xaml_present_file_open(
3817                    req,
3818                    cstr(spec.title()).as_ptr(),
3819                    cstr(&spec.filters_joined()).as_ptr(),
3820                    c_int::from(*multiple),
3821                    self.window,
3822                );
3823            },
3824            PresentSpec::OpenFolder { .. } => unsafe {
3825                ffi::day_xaml_present_folder_open(req, cstr(spec.title()).as_ptr(), self.window);
3826            },
3827            PresentSpec::SaveFile { suggested_name, .. } => unsafe {
3828                // The pieces layer copies the staged bytes to the chosen path (docs/files.md).
3829                ffi::day_xaml_present_file_save(
3830                    req,
3831                    cstr(spec.title()).as_ptr(),
3832                    cstr(suggested_name).as_ptr(),
3833                    cstr(&spec.filters_joined()).as_ptr(),
3834                    self.window,
3835                );
3836            },
3837        }
3838    }
3839
3840    fn dismiss(&mut self, req: u64) {
3841        unsafe { ffi::day_xaml_dismiss_present(req) };
3842    }
3843
3844    #[cfg(windows)]
3845    fn share_support(&self) -> day_spec::Support {
3846        day_spec::Support::Native
3847    }
3848    #[cfg(windows)]
3849    fn share(&mut self, spec: &day_spec::share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
3850        let (url, title) = (spec.url.as_str(), spec.title.as_str());
3851        day_platform_windows::share::share(url, title)
3852    }
3853    fn open_url(&mut self, url: &str) {
3854        let c = cstr(url);
3855        unsafe { ffi::day_xaml_open_url(c.as_ptr()) };
3856    }
3857
3858    fn adopt(&mut self, raw: day_spec::RawHandle) -> WinHandle {
3859        // A recycling-list cell (a plain Canvas) — Day builds/rebinds its row content in place.
3860        WinHandle(raw)
3861    }
3862
3863    fn request_frame(
3864        &mut self,
3865        _host: &WinHandle,
3866        cb: day_spec::FrameCallback,
3867    ) -> day_spec::CancelFrame {
3868        extern "C" fn fire(token: u64, timestamp: f64) {
3869            // XAML can raise Rendering inside the nested layout/screenshot pump while
3870            // day-core holds its tree borrow. Deliver through WM_APP+1, which those pumps
3871            // exclude, so reactive frame work runs only after that borrow has ended.
3872            Xaml::post(Box::new(move || {
3873                day_core::frame::native::deliver(token, day_spec::FrameStamp::new(timestamp));
3874            }));
3875        }
3876        let token = day_core::frame::native::register(cb);
3877        unsafe { ffi::day_xaml_request_frame(token, fire) };
3878        Box::new(move || {
3879            day_core::frame::native::cancel(token);
3880            unsafe { ffi::day_xaml_cancel_frame(token) };
3881        })
3882    }
3883
3884    fn replay(&mut self, h: &WinHandle, ops: &[DrawOp], _size: Size) {
3885        // Bundled families name a file URI for Win2D (ms-appx for the legacy XAML renderer).
3886        let ops = resolve_canvas_fonts(ops);
3887        let (nums, texts) = day_spec::encode_ops(&ops);
3888        let joined = cstr(&texts.join("\u{1f}"));
3889        unsafe {
3890            ffi::day_xaml_canvas_set_ops(h.0, nums.as_ptr(), nums.len() as c_int, joined.as_ptr());
3891        };
3892    }
3893
3894    fn native_document_tabs(&self) -> bool {
3895        cfg!(feature = "winui")
3896    }
3897
3898    fn open_window(
3899        &mut self,
3900        id: NodeId,
3901        options: &WindowOptions,
3902        kind: day_spec::WindowKind,
3903    ) -> day_spec::WindowOpenReply<WinHandle> {
3904        let fixed = c_int::from(kind.is_panel());
3905        let chrome = window_chrome(options);
3906        let win = unsafe {
3907            ffi::day_xaml_window_new2(
3908                cstr(&options.title).as_ptr(),
3909                options.size.width as c_int,
3910                options.size.height as c_int,
3911                id.0,
3912                fixed,
3913                &raw const chrome,
3914            )
3915        };
3916        if win.is_null() {
3917            return day_spec::WindowOpenReply::Unsupported;
3918        }
3919        if options.min_size.is_some() || options.max_size.is_some() {
3920            set_limits(win, options.min_size, options.max_size);
3921        }
3922        let content = unsafe { ffi::day_xaml_window_content2(win) };
3923        // The app menu was installed before this window existed, and Windows draws one per
3924        // window — so replay it here rather than leaving the new window bare.
3925        //
3926        // Except into a Preferences window: that is a panel, not a second main window
3927        // (docs/windows.md), and a settings dialog carrying File/Edit/View is not an idiom
3928        // Windows has. It keeps the menu-less frame the shim gives it.
3929        let menuless = kind.is_panel();
3930        if !menuless && !self.menu_spec.is_empty() {
3931            unsafe { ffi::day_xaml_window_set_menu2(win, cstr(&self.menu_spec).as_ptr()) };
3932        }
3933        self.secondary.push(XamlWin {
3934            win,
3935            content,
3936            menuless,
3937        });
3938        day_spec::WindowOpenReply::Open(WinHandle(content))
3939    }
3940
3941    fn close_window(&mut self, host: &WinHandle) {
3942        if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
3943            unsafe { ffi::day_xaml_window_close2(w.win) };
3944        }
3945    }
3946
3947    fn quit_app(&mut self) {
3948        // Just the platform's exit: day-core has already disposed the other windows and
3949        // delivered WillTerminate (docs/windows.md close policy).
3950        unsafe { ffi::day_xaml_quit() };
3951    }
3952
3953    fn focus_window(&mut self, host: &WinHandle) {
3954        // The primary too: a forwarded launch focuses whichever window is in front.
3955        if let Some(win) = self.window_token(host) {
3956            unsafe { ffi::day_xaml_window_raise2(win) };
3957        }
3958    }
3959
3960    fn set_window_title(&mut self, host: &WinHandle, title: &str) {
3961        // `window_token` covers the primary too — it is an ordinary window (docs/windows.md),
3962        // and `day::window_title` in the first window's shell arrives here like any other.
3963        if let Some(win) = self.window_token(host) {
3964            unsafe { ffi::day_xaml_window_set_title2(win, cstr(title).as_ptr()) };
3965        }
3966    }
3967
3968    /// `.window_drag_region()` (docs/window-chrome.md): the window's `WM_NCHITTEST` answers
3969    /// HTCAPTION over the element's own background, so Windows runs its own title-bar move
3970    /// (Aero Snap included), double-click maximize and window menu. Controls inside keep their
3971    /// clicks: the hit test stops at the first Control above the region.
3972    fn set_drag_region(&mut self, h: &WinHandle, drag: bool) {
3973        DRAG_REGIONS.with(|d| {
3974            let mut d = d.borrow_mut();
3975            if drag {
3976                d.insert(h.0 as usize);
3977            } else {
3978                d.remove(&(h.0 as usize));
3979            }
3980        });
3981        unsafe { ffi::day_xaml_set_drag_region(h.0, c_int::from(drag)) };
3982    }
3983
3984    fn apply_window(&mut self, host: &WinHandle, change: &day_spec::WindowChange) {
3985        use day_spec::WindowChange as C;
3986        // `window_token` covers the primary too, as for the title.
3987        let Some(win) = self.window_token(host) else {
3988            return;
3989        };
3990        match change {
3991            // ShowWindow for minimize, maximize and restore; fullscreen is borderless, over the
3992            // window's whole monitor. The shim reports the outcome through `win_state`.
3993            C::State(state) => unsafe { ffi::day_xaml_window_set_state(win, state.code()) },
3994            // Captures, recordings and screen sharing leave the window out; the user still sees it.
3995            C::ContentProtected(on) => unsafe {
3996                ffi::day_xaml_window_set_protected(win, c_int::from(*on));
3997            },
3998            // SetWindowPos: the outer frame's origin, the content size around which the frame
3999            // and the docked chrome are added.
4000            C::Frame { origin, size } => unsafe {
4001                let p = origin.unwrap_or(Point::ZERO);
4002                let z = size.unwrap_or(Size::new(0.0, 0.0));
4003                ffi::day_xaml_window_set_frame(
4004                    win,
4005                    c_int::from(origin.is_some()),
4006                    p.x,
4007                    p.y,
4008                    c_int::from(size.is_some()),
4009                    z.width,
4010                    z.height,
4011                );
4012            },
4013            // WM_GETMINMAXINFO's track sizes.
4014            C::Limits { min, max } => set_limits(win, *min, *max),
4015            C::Level(level) => unsafe {
4016                ffi::day_xaml_window_set_flag(
4017                    win,
4018                    0,
4019                    c_int::from(*level == day_spec::WindowLevel::Floating),
4020                );
4021            },
4022            // ITaskbarList::DeleteTab / AddTab.
4023            C::SkipTaskbar(skip) => unsafe {
4024                ffi::day_xaml_window_set_flag(win, 1, c_int::from(*skip));
4025            },
4026            C::Resizable(on) => unsafe { ffi::day_xaml_window_set_flag(win, 2, c_int::from(*on)) },
4027            C::Minimizable(on) => unsafe {
4028                ffi::day_xaml_window_set_flag(win, 3, c_int::from(*on));
4029            },
4030            C::Maximizable(on) => unsafe {
4031                ffi::day_xaml_window_set_flag(win, 4, c_int::from(*on));
4032            },
4033            C::Closable(on) => unsafe { ffi::day_xaml_window_set_flag(win, 5, c_int::from(*on)) },
4034            C::Visible(on) => unsafe { ffi::day_xaml_window_set_flag(win, 6, c_int::from(*on)) },
4035            // The title bar's DWM dark flag and the island root's RequestedTheme.
4036            C::Appearance(dark) => {
4037                unsafe { ffi::day_xaml_window_set_appearance(win, dark.map_or(-1, c_int::from)) };
4038                // The window's inks, for its own scheme.
4039                repaint_inks();
4040            }
4041            // FlashWindowEx.
4042            C::RequestAttention(a) => unsafe {
4043                ffi::day_xaml_window_attention(
4044                    win,
4045                    c_int::from(*a == day_spec::Attention::Critical),
4046                );
4047            },
4048            // Windows has no API to put a window on every virtual desktop.
4049            C::OnAllWorkspaces(_) => {}
4050        }
4051    }
4052
4053    fn window_frame(&self, host: &WinHandle) -> Option<day_spec::Rect> {
4054        let win = self.window_token(host)?;
4055        let mut r = [0.0f64; 4];
4056        (unsafe { ffi::day_xaml_window_frame(win, r.as_mut_ptr()) } != 0)
4057            .then(|| day_spec::Rect::new(r[0], r[1], r[2], r[3]))
4058    }
4059
4060    fn monitors(&self) -> Vec<day_spec::Monitor> {
4061        let count = unsafe { ffi::day_xaml_monitors(std::ptr::null_mut(), 0) }.max(0);
4062        let mut raw: Vec<ffi::DayXamlMonitor> = (0..count)
4063            .map(|_| ffi::DayXamlMonitor {
4064                frame: [0.0; 4],
4065                work: [0.0; 4],
4066                scale: 1.0,
4067                primary: 0,
4068                id: [0; 160],
4069                name: [0; 128],
4070            })
4071            .collect();
4072        let filled = unsafe { ffi::day_xaml_monitors(raw.as_mut_ptr(), count) }.clamp(0, count);
4073        raw.truncate(filled as usize);
4074        let text = |chars: &[c_char]| {
4075            // SAFETY: the shim NUL-terminates both fields inside their arrays.
4076            unsafe { CStr::from_ptr(chars.as_ptr()) }
4077                .to_string_lossy()
4078                .into_owned()
4079        };
4080        let rect = |r: [f64; 4]| day_spec::Rect::new(r[0], r[1], r[2], r[3]);
4081        raw.iter()
4082            .map(|m| day_spec::Monitor {
4083                id: text(&m.id),
4084                name: text(&m.name),
4085                frame: rect(m.frame),
4086                work_area: rect(m.work),
4087                scale: m.scale,
4088                primary: m.primary != 0,
4089            })
4090            .collect()
4091    }
4092
4093    /// Notification-area icons (docs/status-item.md): `Shell_NotifyIconW` on the shim's hidden
4094    /// shell window; a left click runs `activate` (or opens the menu), a right click opens the
4095    /// menu as a Win32 popup lowered from the app menu's spec.
4096    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
4097        for item in items {
4098            let (glyph, image) = match &item.icon {
4099                Some(day_spec::Icon::Symbol(sym)) => {
4100                    (toolbar::glyph_for(*sym).to_owned(), String::new())
4101                }
4102                // A raster file; a vector-only name has no file to load and shows the app icon.
4103                Some(day_spec::Icon::Image(name)) => (String::new(), image_uri(name)),
4104                None => (String::new(), String::new()),
4105            };
4106            let tip = if item.tooltip.is_empty() {
4107                &item.title
4108            } else {
4109                &item.tooltip
4110            };
4111            let mut menu = String::new();
4112            serialize_menu_xaml(&item.menu, &mut menu);
4113            unsafe {
4114                ffi::day_xaml_status_set(
4115                    cstr(&item.id).as_ptr(),
4116                    cstr(tip).as_ptr(),
4117                    cstr(&glyph).as_ptr(),
4118                    cstr(&image).as_ptr(),
4119                    c_int::from(item.template),
4120                    item.activate,
4121                    cstr(&menu).as_ptr(),
4122                );
4123            };
4124        }
4125        let ids = items
4126            .iter()
4127            .map(|i| i.id.as_str())
4128            .collect::<Vec<_>>()
4129            .join("\n");
4130        unsafe { ffi::day_xaml_status_retain(cstr(&ids).as_ptr()) };
4131    }
4132
4133    /// The jump list's Tasks, rebuilt with the app's declared shortcuts after these.
4134    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
4135        set_jump_tasks(shortcuts);
4136    }
4137
4138    /// `ITaskbarList3::SetProgressState` / `SetProgressValue` on the first window's button.
4139    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
4140        use day_spec::AppProgress as P;
4141        let (kind, value) = match progress {
4142            P::None => (0, 0.0),
4143            P::Indeterminate => (1, 0.0),
4144            P::Value(v) => (2, v),
4145            P::Paused(v) => (3, v),
4146            P::Error(v) => (4, v),
4147        };
4148        unsafe { ffi::day_xaml_set_app_progress(kind, value) };
4149    }
4150
4151    /// `ITaskbarList3::SetOverlayIcon` with a drawn disc: a count or a dot. Text has no overlay
4152    /// that would read (`Cap::AppBadgeText` is Unsupported), so it is ignored, never substituted.
4153    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
4154        use day_spec::AppBadge as B;
4155        let (kind, count) = match badge {
4156            B::None => (0, 0),
4157            B::Count(n) => (1, *n),
4158            B::Dot => (2, 0),
4159            B::Text(_) => return,
4160        };
4161        unsafe { ffi::day_xaml_set_app_badge(kind, count) };
4162    }
4163
4164    /// The primary's close is already reported, never acted on (`WM_CLOSE` → `WindowClosed`), so
4165    /// day-core decides about quitting; what keeping the app alive needs here is somewhere for
4166    /// Day's posts to go once that window is gone.
4167    fn set_keep_running(&mut self, keep: bool) {
4168        unsafe { ffi::day_xaml_set_keep_running(c_int::from(keep)) };
4169    }
4170
4171    /// A SECONDARY window's own pixels (docs/windows.md). Previously this kept the trait default,
4172    /// which captures the primary — so a `screenshot: { window: day.preferences }` step passed
4173    /// while writing an image of the main window, with nothing to indicate the target was ignored.
4174    fn snapshot_window_of(&mut self, host: &WinHandle) -> Result<Vec<u8>, String> {
4175        let Some(w) = self.secondary.iter().find(|w| w.content == host.0) else {
4176            // Not one of ours: the primary's own root arrives here too.
4177            return self.snapshot_window();
4178        };
4179        let win = w.win;
4180        snapshot_via(|path| unsafe { ffi::day_xaml_snapshot_png2(win, path) })
4181    }
4182
4183    fn toggle_sidebar(&mut self, _host: &WinHandle) -> bool {
4184        // The primary window's NavigationView is the only split here (secondary windows carry
4185        // no chrome), so the host is implied. The same call the toolbar's own AppBarButton
4186        // makes, so a dayscript walkthrough drives the real path (docs/toolbars.md).
4187        unsafe { ffi::day_xaml_toggle_sidebar() != 0 }
4188    }
4189
4190    /// The app's appearance override (docs/settings.md) — what the showcase's Preferences
4191    /// Appearance picker drives. Without this the backend took the trait default, which ignores
4192    /// the call: picking Light or Dark changed nothing at all, while `Cap::Appearance` promised
4193    /// the opposite. `dark_mode` below answers from the same override, so day's palette and the
4194    /// native controls agree.
4195    fn set_appearance(&mut self, dark: Option<bool>) {
4196        let mode = match dark {
4197            None => 0,        // follow the system again
4198            Some(false) => 1, // light
4199            Some(true) => 2,  // dark
4200        };
4201        unsafe { ffi::day_xaml_set_appearance(mode) };
4202        // Every ink that follows the appearance, for the scheme now shown (docs/color.md).
4203        repaint_inks();
4204    }
4205
4206    /// The Fluent theme resource of each role (docs/color.md "Roles"), read for the app's
4207    /// appearance from the theme dictionaries; Day's fallback where the resource set has none.
4208    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
4209        theme_color(role, self.dark_mode())
4210    }
4211
4212    /// The system's light/dark setting (a `DAY_THEME` force wins). Previously this took the trait
4213    /// default, which reads `DAY_THEME` and nothing else — so on Windows every palette closure day
4214    /// evaluated resolved LIGHT no matter what the system was set to, while the XAML controls
4215    /// around it themed themselves correctly. That mismatch is what made a dark-mode window show
4216    /// app-painted surfaces in light colors.
4217    fn dark_mode(&mut self) -> bool {
4218        unsafe { ffi::day_xaml_is_dark() != 0 }
4219    }
4220
4221    /// Windows' "Show animations" switch, off (docs/accessibility.md): `UISettings` publishes it
4222    /// as `AnimationsEnabled`, and the shim re-reads it on every call so the answer is current
4223    /// after each change report.
4224    fn reduce_motion(&mut self) -> bool {
4225        unsafe { ffi::day_xaml_reduce_motion() != 0 }
4226    }
4227
4228    /// Hold the bytes and answer from their HEADER (docs/images.md).
4229    ///
4230    /// XAML decodes lazily: a `BitmapImage` reports `PixelWidth`/`PixelHeight` only after the
4231    /// element it feeds has been shown, so there is nothing to ask at this point. Reading the
4232    /// container's own header gives the same numbers the decoder would, synchronously — and it
4233    /// is the one part of this backend that is testable off Windows (`ImageFormat::dimensions`).
4234    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
4235        let held =
4236            unsafe { ffi::day_xaml_image_decode(id.0, bytes.as_ptr(), bytes.len() as c_int) != 0 };
4237        let format = day_spec::ImageFormat::sniff(bytes);
4238        let event = if let (true, Some((w, h))) = (held, day_spec::ImageFormat::dimensions(bytes)) {
4239            let info = day_spec::BitmapInfo {
4240                pixels: Size::new(f64::from(w), f64::from(h)),
4241                // Decoded bytes carry no density — a PNG is simply its pixels.
4242                scale: 1.0,
4243                format,
4244                // Derived from the container rather than measured: nothing here decodes far
4245                // enough to inspect an alpha channel.
4246                has_alpha: !matches!(
4247                    format,
4248                    Some(day_spec::ImageFormat::Jpeg | day_spec::ImageFormat::Bmp)
4249                ),
4250            };
4251            BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
4252            Event::ImageDecoded {
4253                req,
4254                result: Ok(info),
4255            }
4256        } else {
4257            // A container whose header this does not parse would leave the caller with no size
4258            // to lay out against, so it is refused rather than answered with zeros.
4259            unsafe { ffi::day_xaml_image_release(id.0) };
4260            Event::ImageDecoded {
4261                req,
4262                result: Err(day_spec::ImageError::Decode),
4263            }
4264        };
4265        emit(day_spec::WINDOW_NODE, event);
4266    }
4267
4268    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
4269        BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
4270    }
4271
4272    #[cfg(feature = "winui")]
4273    fn render_bitmap(
4274        &mut self,
4275        req: u64,
4276        id: day_spec::BitmapId,
4277        ops: &[DrawOp],
4278        size: Size,
4279        scale: f64,
4280    ) {
4281        let (width, height) = day_spec::export_pixels(size, scale);
4282        let (nums, texts) = day_spec::encode_ops(&resolve_canvas_fonts(ops));
4283        let texts = cstr(&texts.join("\u{1f}"));
4284        // Core validated dimensions and limits; all borrowed buffers outlive this synchronous call.
4285        let rc = unsafe {
4286            ffi::day_xaml_canvas_bitmap(
4287                id.0,
4288                nums.as_ptr(),
4289                nums.len() as c_int,
4290                texts.as_ptr(),
4291                width as c_int,
4292                height as c_int,
4293                scale,
4294            )
4295        };
4296        let result = if rc == 0 {
4297            let info = day_spec::BitmapInfo {
4298                pixels: Size::new(f64::from(width), f64::from(height)),
4299                scale,
4300                format: None,
4301                has_alpha: true,
4302            };
4303            BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
4304            Ok(info)
4305        } else {
4306            Err(day_spec::ExportError::Failed(format!(
4307                "Win2D bitmap rendering failed ({rc})"
4308            )))
4309        };
4310        emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
4311    }
4312
4313    #[cfg(feature = "winui")]
4314    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
4315        vec![day_spec::ImageFormat::Png]
4316    }
4317
4318    #[cfg(feature = "winui")]
4319    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
4320        let mut result = Err(day_spec::ImageError::Encode);
4321        if spec.format == day_spec::ImageFormat::Png {
4322            let fit = spec.fit.unwrap_or(Size::ZERO);
4323            let mut len = 0;
4324            // The shim allocates the returned bytes; copy before freeing through its allocator.
4325            unsafe {
4326                let bytes = ffi::day_xaml_encode_png(
4327                    id.0,
4328                    fit.width as c_int,
4329                    fit.height as c_int,
4330                    &raw mut len,
4331                );
4332                if !bytes.is_null() {
4333                    result = Ok(std::slice::from_raw_parts(bytes, len as usize).to_vec());
4334                    ffi::day_xaml_bytes_free(bytes);
4335                }
4336            }
4337        }
4338        emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
4339    }
4340
4341    fn release_image(&mut self, id: day_spec::BitmapId) {
4342        BITMAP_INFO.with(|m| {
4343            m.borrow_mut().remove(&id.0);
4344        });
4345        // SAFETY: an id the shim either knows or does not; releasing an absent one is a no-op.
4346        unsafe { ffi::day_xaml_image_release(id.0) };
4347    }
4348
4349    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
4350        if self.window.is_null() {
4351            return Err("no window".into());
4352        }
4353        let win = self.window;
4354        snapshot_via(|path| unsafe { ffi::day_xaml_snapshot_png(win, path) })
4355    }
4356
4357    /// The content's offset in the capture: the system-XAML capture is the whole window rect,
4358    /// title bar and resize borders included (the shim's `day_xaml_snapshot_origin`). WinUI
4359    /// reports its visible-frame offset, or zero for the XAML-tree capture fallback.
4360    fn snapshot_origin(&mut self, _root: &WinHandle) -> Option<Point> {
4361        if self.window.is_null() {
4362            return None;
4363        }
4364        let mut out = [0.0f64; 2];
4365        // SAFETY: `window` is the live AppWindow token the shim handed out, and `out` holds the
4366        // two doubles the shim writes.
4367        let rc = unsafe { ffi::day_xaml_snapshot_origin(self.window, out.as_mut_ptr()) };
4368        (rc == 0).then(|| Point::new(out[0], out[1]))
4369    }
4370
4371    /// DirectWrite's system font collection, decoded from the shim's list text
4372    /// (docs/fonts.md).
4373    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
4374        // SAFETY: the shim returns a NUL-terminated heap string (or null); it is read once and
4375        // released through the shim's own free.
4376        unsafe {
4377            let p = ffi::day_xaml_font_families();
4378            if p.is_null() {
4379                return Vec::new();
4380            }
4381            let text = std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned();
4382            ffi::day_xaml_string_free(p);
4383            day_spec::parse_font_list(&text)
4384        }
4385    }
4386
4387    /// `Win2D` text layout measured with the font the canvas draws with (docs/fonts.md).
4388    fn measure_text(
4389        &mut self,
4390        text: &str,
4391        size: f64,
4392        font: &day_spec::CanvasFont,
4393    ) -> Option<day_spec::TextMetrics> {
4394        let text = cstr(text);
4395        // The same family form `replay` draws with, so the measurement is of the same face.
4396        let family = cstr(&font.family.as_deref().map_or_default(canvas_family));
4397        let mut out = [0.0f64; 8];
4398        // SAFETY: both strings outlive the call and `out` has the eight slots the shim fills.
4399        let rc = unsafe {
4400            ffi::day_xaml_measure_text(
4401                text.as_ptr(),
4402                size,
4403                c_int::from(font.css_weight()),
4404                c_int::from(font.italic),
4405                family.as_ptr(),
4406                out.as_mut_ptr(),
4407            )
4408        };
4409        (rc == 0).then(|| day_spec::TextMetrics::from_slots(&out))
4410    }
4411}
4412
4413/// Run one of the shim's PNG writers into a temp file and hand back the bytes. The primary and
4414/// secondary captures differ only in which entry point they call, so the file dance lives here.
4415/// One name per process is enough: captures are sequential, and the file is read and removed
4416/// before the next one starts.
4417fn snapshot_via(capture: impl FnOnce(*const c_char) -> c_int) -> Result<Vec<u8>, String> {
4418    let path = std::env::temp_dir().join(format!("day-xaml-snap-{}.png", std::process::id()));
4419    let cpath = cstr(&path.to_string_lossy());
4420    let rc = capture(cpath.as_ptr());
4421    if rc != 0 {
4422        return Err(format!("snapshot failed (rc={rc})"));
4423    }
4424    let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
4425    let _ = std::fs::remove_file(&path);
4426    Ok(bytes)
4427}
4428
4429/// An ink as the shim's packed ARGB, resolved for the app's current appearance.
4430fn argb(c: impl Into<day_spec::Ink>) -> u32 {
4431    ink_argb(c.into(), &day_spec::Palette::current())
4432}
4433
4434/// An ink as the shim's packed ARGB, resolved against `palette`.
4435fn ink_argb(ink: day_spec::Ink, palette: &day_spec::Palette) -> u32 {
4436    let c = ink.resolve(palette);
4437    let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
4438    let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
4439    let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
4440    let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
4441    (a << 24) | (r << 16) | (g << 8) | b
4442}
4443
4444/// A packed ARGB from the shim as a color.
4445fn color_of_argb(argb: u32) -> day_spec::Color {
4446    let channel = |shift: u32| f64::from((argb >> shift) & 0xff) / 255.0;
4447    day_spec::Color::rgba(channel(16), channel(8), channel(0), channel(24))
4448}
4449
4450/// The Fluent theme resources a role reads, first found wins, and the alpha its color is
4451/// multiplied by (docs/color.md "Roles"). `HyperlinkForeground`, `TextControlPlaceholderForeground`
4452/// and `TextControlSelectionHighlightColor` are what XAML's own controls draw with; the accent
4453/// text brush is the link color where the first is missing.
4454fn role_keys(role: day_spec::SystemColor) -> (&'static [&'static CStr], f64) {
4455    use day_spec::SystemColor as R;
4456    match role {
4457        R::Accent => (&[c"AccentFillColorDefaultBrush"], 1.0),
4458        R::Text => (&[c"TextFillColorPrimaryBrush"], 1.0),
4459        R::SecondaryText => (&[c"TextFillColorSecondaryBrush"], 1.0),
4460        R::TertiaryText => (&[c"TextFillColorTertiaryBrush"], 1.0),
4461        R::Placeholder => (
4462            &[
4463                c"TextControlPlaceholderForeground",
4464                c"TextFillColorSecondaryBrush",
4465            ],
4466            1.0,
4467        ),
4468        R::Link => (
4469            &[c"HyperlinkForeground", c"AccentTextFillColorPrimaryBrush"],
4470            1.0,
4471        ),
4472        R::Separator => (&[c"DividerStrokeColorDefaultBrush"], 1.0),
4473        R::ControlFill => (&[c"ControlFillColorDefaultBrush"], 1.0),
4474        R::Background | R::GroupedBackground => (&[c"SolidBackgroundFillColorBaseBrush"], 1.0),
4475        R::Surface => (&[c"CardBackgroundFillColorDefaultBrush"], 1.0),
4476        R::ElevatedSurface => (&[c"SolidBackgroundFillColorTertiaryBrush"], 1.0),
4477        R::Selection => (
4478            &[
4479                c"TextControlSelectionHighlightColor",
4480                c"AccentFillColorDefaultBrush",
4481            ],
4482            0.35,
4483        ),
4484        R::Destructive => (&[c"SystemFillColorCriticalBrush"], 1.0),
4485        R::Success => (&[c"SystemFillColorSuccessBrush"], 1.0),
4486        R::Warning => (&[c"SystemFillColorCautionBrush"], 1.0),
4487    }
4488}
4489
4490/// A role's color in one appearance: its theme resource, or Day's fallback where the resource
4491/// set has none (system XAML without WinUI's Fluent resources).
4492fn theme_color(role: day_spec::SystemColor, dark: bool) -> day_spec::Color {
4493    let (keys, alpha) = role_keys(role);
4494    for key in keys {
4495        let mut packed: std::os::raw::c_uint = 0;
4496        // SAFETY: `key` is NUL-terminated and `packed` outlives the call, which only writes it.
4497        let found =
4498            unsafe { ffi::day_xaml_theme_color(key.as_ptr(), c_int::from(dark), &raw mut packed) };
4499        if found != 0 {
4500            let mut c = color_of_argb(packed);
4501            c.a *= alpha;
4502            return c;
4503        }
4504    }
4505    role.fallback(dark)
4506}
4507
4508/// Every role in one appearance, as `system_color` answers them.
4509fn theme_palette(dark: bool) -> day_spec::Palette {
4510    day_spec::Palette {
4511        dark,
4512        colors: day_spec::SystemColor::ALL.map(|role| theme_color(role, dark)),
4513    }
4514}
4515
4516/// Which inks of a view an entry in [`INKS`] applies.
4517#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4518enum InkSlot {
4519    /// A container's fill, border and shadow, or a cover's ground.
4520    Surface,
4521    /// A label's text color.
4522    LabelColor,
4523    /// A label's runs (their colors and highlights).
4524    LabelRuns,
4525    /// A tinted button's fill and title.
4526    ButtonTint,
4527    /// An image's tint.
4528    ImageTint,
4529}
4530
4531/// What applies one view's inks again for a palette.
4532type Repaint = Rc<dyn Fn(*mut c_void, &day_spec::Palette)>;
4533
4534/// Apply a view's inks with the current palette and keep the call for the next appearance switch
4535/// when any of them follows the appearance (`dynamic`); otherwise the slot is forgotten.
4536fn paint_inks(
4537    h: *mut c_void,
4538    slot: InkSlot,
4539    dynamic: bool,
4540    apply: impl Fn(*mut c_void, &day_spec::Palette) + 'static,
4541) {
4542    apply(h, &day_spec::Palette::current());
4543    keep_inks(h, slot, dynamic, apply);
4544}
4545
4546/// Keep (when `dynamic`) or forget the call that applies a view's inks, without applying them now:
4547/// for a value the caller has just applied its own way (an animated fill).
4548fn keep_inks(
4549    h: *mut c_void,
4550    slot: InkSlot,
4551    dynamic: bool,
4552    apply: impl Fn(*mut c_void, &day_spec::Palette) + 'static,
4553) {
4554    let key = (h as usize, slot);
4555    INKS.with(|m| {
4556        let mut m = m.borrow_mut();
4557        if dynamic {
4558            m.insert(key, Rc::new(apply));
4559        } else {
4560            m.remove(&key);
4561        }
4562    });
4563}
4564
4565/// The appearance changed (the system's, the app's override or one window's): every kept ink
4566/// again, each for the appearance its view is shown in. Runs where the shim has already
4567/// re-themed the windows, before or after day-core refreshes `Palette::current`, so it reads the
4568/// palettes from the theme resources itself.
4569fn repaint_inks() {
4570    let entries: Vec<(usize, Repaint)> = INKS.with(|m| {
4571        m.borrow()
4572            .iter()
4573            .map(|(&(h, _), apply)| (h, Rc::clone(apply)))
4574            .collect()
4575    });
4576    if entries.is_empty() {
4577        return;
4578    }
4579    let palettes = [theme_palette(false), theme_palette(true)];
4580    for (h, apply) in entries {
4581        let h = h as *mut c_void;
4582        // SAFETY: a kept view is live; `release` forgets its entries.
4583        let dark = unsafe { ffi::day_xaml_element_dark(h) } != 0;
4584        apply(h, &palettes[usize::from(dark)]);
4585    }
4586}
4587
4588/// Per-row section titles (docs/navigation.md) as one line-joined list, parallel to the rows: the
4589/// title that opens before a row, an empty line for none.
4590fn join_sections(sections: &[Option<String>]) -> String {
4591    sections
4592        .iter()
4593        .map(|s| s.as_deref().unwrap_or_default())
4594        .collect::<Vec<_>>()
4595        .join("\n")
4596}
4597
4598/// A container's surface as last applied (docs/surfaces.md).
4599#[derive(Clone, Debug, Default)]
4600struct Surface {
4601    /// The styling; `role` is the realize-time one and never changes.
4602    props: ContainerProps,
4603    /// Drawn by the shim's styled surface (a `Border`) rather than the plain fill rectangle.
4604    styled: bool,
4605}
4606
4607/// Whether a container needs the styled-surface path (docs/surfaces.md): a border, a gradient,
4608/// a shadow, or a corner radius on some corners only. Everything else, role surfaces included,
4609/// keeps the plain fill and uniform corner path it has always had.
4610fn styled_surface(p: &ContainerProps) -> bool {
4611    p.role.is_none()
4612        && (p.border.is_some()
4613            || p.fill
4614                .as_ref()
4615                .is_some_and(|f| !matches!(f, day_spec::Paint::Solid(_)))
4616            || p.shadow.is_some()
4617            || (p.corner_radius > 0.0 && p.corners != day_spec::Corners::ALL))
4618}
4619
4620/// Whether any color of a surface follows the appearance.
4621fn surface_is_dynamic(p: &ContainerProps) -> bool {
4622    p.fill.as_ref().is_some_and(day_spec::Paint::is_dynamic)
4623        || p.border.is_some_and(|b| b.color.is_dynamic())
4624        || p.shadow.is_some_and(|s| s.color.is_dynamic())
4625}
4626
4627/// A gradient's stops as the two parallel arrays the shim takes: offsets clamped to 0..=1,
4628/// and ARGB colors resolved against `palette`.
4629fn gradient_stops(
4630    stops: &[(f64, day_spec::Ink)],
4631    palette: &day_spec::Palette,
4632) -> (Vec<c_double>, Vec<u32>) {
4633    stops
4634        .iter()
4635        .map(|&(at, color)| (at.clamp(0.0, 1.0), ink_argb(color, palette)))
4636        .unzip()
4637}
4638
4639/// Realize a container's surface on `h`: the plain fill and corner path, or a styled surface,
4640/// and its colors.
4641///
4642/// # Safety
4643///
4644/// `h` is a live container handle and this runs on the UI thread, like every shim call.
4645unsafe fn realize_surface(h: *mut c_void, p: &ContainerProps) {
4646    let styled = styled_surface(p);
4647    // SAFETY: `h` is live per this function's contract.
4648    unsafe {
4649        if styled {
4650            shape_surface(h, p);
4651        } else {
4652            if p.role == Some(day_spec::SurfaceRole::SectionCard) {
4653                // Theme-resource card brush — tracks light/dark automatically.
4654                ffi::day_xaml_container_set_card(h, p.corner_radius);
4655            }
4656            if p.role == Some(day_spec::SurfaceRole::Window) {
4657                // The page background an opaque cover is grounded in.
4658                ffi::day_xaml_cover_ground(h);
4659            }
4660            if p.corner_radius > 0.0 && p.role != Some(day_spec::SurfaceRole::SectionCard) {
4661                ffi::day_xaml_container_set_corner(h, p.corner_radius);
4662            }
4663        }
4664    }
4665    let surface = Surface {
4666        props: p.clone(),
4667        styled,
4668    };
4669    SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface.clone()));
4670    paint_surface(h, surface, true);
4671}
4672
4673/// Apply a surface's colors now and keep them for the appearance. `realize`: nothing was
4674/// applied before, so an absent fill, border or shadow has nothing to clear.
4675fn paint_surface(h: *mut c_void, surface: Surface, realize: bool) {
4676    let dynamic = surface_is_dynamic(&surface.props);
4677    paint_inks(h, InkSlot::Surface, dynamic, move |h, palette| {
4678        // SAFETY: the handle is live (see `repaint_inks`) and this runs on the UI thread.
4679        unsafe { surface_colors(h, &surface, palette, realize) };
4680    });
4681}
4682
4683/// The shape of a styled surface: corners, which corners, and the clip.
4684///
4685/// # Safety
4686///
4687/// `h` is a live container handle and this runs on the UI thread.
4688unsafe fn shape_surface(h: *mut c_void, p: &ContainerProps) {
4689    // SAFETY: `h` is live per this function's contract.
4690    unsafe {
4691        ffi::day_xaml_container_set_surface(
4692            h,
4693            p.corner_radius,
4694            c_int::from(p.corners.bits()),
4695            c_int::from(p.clips),
4696        );
4697    }
4698}
4699
4700/// A surface's fill, border and shadow, resolved against `palette`. A plain surface has a
4701/// solid fill at most.
4702///
4703/// # Safety
4704///
4705/// `h` is a live container handle and this runs on the UI thread. Every pointer passed below
4706/// names a local that outlives its call, with the length passed beside it.
4707unsafe fn surface_colors(
4708    h: *mut c_void,
4709    surface: &Surface,
4710    palette: &day_spec::Palette,
4711    realize: bool,
4712) {
4713    use day_spec::Paint;
4714    let p = &surface.props;
4715    // SAFETY: per this function's contract.
4716    unsafe {
4717        if !surface.styled {
4718            if let Some(Paint::Solid(ink)) = p.fill {
4719                ffi::day_xaml_container_set_bg(h, ink_argb(ink, palette));
4720            }
4721            return;
4722        }
4723        match &p.fill {
4724            Some(Paint::Solid(ink)) => ffi::day_xaml_container_set_bg(h, ink_argb(*ink, palette)),
4725            Some(Paint::Linear(g)) => {
4726                let line = [g.start.x, g.start.y, g.end.x, g.end.y];
4727                let (offsets, colors) = gradient_stops(&g.stops, palette);
4728                ffi::day_xaml_container_set_gradient(
4729                    h,
4730                    line.as_ptr(),
4731                    offsets.as_ptr(),
4732                    colors.as_ptr(),
4733                    offsets.len() as c_int,
4734                );
4735            }
4736            Some(Paint::Radial(g)) => {
4737                let (offsets, colors) = gradient_stops(&g.stops, palette);
4738                ffi::day_xaml_container_set_radial(
4739                    h,
4740                    g.center.x,
4741                    g.center.y,
4742                    g.radius,
4743                    offsets.as_ptr(),
4744                    colors.as_ptr(),
4745                    offsets.len() as c_int,
4746                );
4747            }
4748            Some(Paint::Conic(g)) => {
4749                let (offsets, colors) = gradient_stops(&g.stops, palette);
4750                ffi::day_xaml_container_set_conic(
4751                    h,
4752                    g.center.x,
4753                    g.center.y,
4754                    g.start.degrees(),
4755                    offsets.as_ptr(),
4756                    colors.as_ptr(),
4757                    offsets.len() as c_int,
4758                );
4759            }
4760            None if !realize => ffi::day_xaml_container_set_bg(h, 0),
4761            None => {}
4762        }
4763        match p.border {
4764            Some(border) => {
4765                ffi::day_xaml_container_set_border(
4766                    h,
4767                    ink_argb(border.color, palette),
4768                    border.width,
4769                );
4770            }
4771            None if !realize => ffi::day_xaml_container_set_border(h, 0, 0.0),
4772            None => {}
4773        }
4774        let shadow = p.shadow.filter(|s| s.color.resolve(palette).a > 0.0);
4775        match shadow {
4776            Some(s) => ffi::day_xaml_container_set_shadow(
4777                h,
4778                ink_argb(s.color, palette),
4779                s.blur,
4780                s.dx,
4781                s.dy,
4782            ),
4783            None if !realize => ffi::day_xaml_container_set_shadow(h, 0, 0.0, 0.0, 0.0),
4784            None => {}
4785        }
4786    }
4787}
4788
4789/// `ContainerPatch::Fill`: a solid fill (or none) keeps the motion contract (docs/tween.md rule
4790/// 8: animated with `anim`, appearing or going away at once); a gradient applies at once and
4791/// makes the container a styled surface.
4792///
4793/// # Safety
4794///
4795/// `h` is a live container handle and this runs on the UI thread.
4796unsafe fn patch_fill(h: *mut c_void, fill: Option<&day_spec::Paint>, anim: Option<&AnimSpec>) {
4797    let mut surface = SURFACES
4798        .with(|m| m.borrow().get(&(h as usize)).cloned())
4799        .unwrap_or_default();
4800    surface.props.fill = fill.cloned();
4801    let solid = match fill {
4802        None => Some(None),
4803        Some(day_spec::Paint::Solid(ink)) => Some(Some(*ink)),
4804        Some(_) => None,
4805    };
4806    if let Some(solid) = solid {
4807        // Unlike the other desktop backends this one INTERPOLATES an animated fill (DESIGN.md
4808        // §8.4): the fill is a SolidColorBrush we own, and XAML tweens brush color given
4809        // EnableDependentAnimation. A cleared background maps to fully transparent.
4810        let anim = XamlAnim::new(anim.filter(|_| solid.is_some()));
4811        // SAFETY: `h` is live per this function's contract; `anim` outlives the call.
4812        unsafe {
4813            ffi::day_xaml_container_animate_bg(
4814                h,
4815                argb(solid.unwrap_or(day_spec::Ink::CLEAR)),
4816                XamlAnim::ptr(anim.as_ref()),
4817            );
4818        }
4819        let dynamic = surface_is_dynamic(&surface.props);
4820        let kept = surface.clone();
4821        keep_inks(h, InkSlot::Surface, dynamic, move |h, palette| {
4822            // SAFETY: the handle is live (see `repaint_inks`) and this runs on the UI thread.
4823            unsafe { surface_colors(h, &kept, palette, false) };
4824        });
4825    } else {
4826        if !surface.styled {
4827            // SAFETY: `h` is live per this function's contract.
4828            unsafe { shape_surface(h, &surface.props) };
4829            surface.styled = true;
4830        }
4831        paint_surface(h, surface.clone(), false);
4832    }
4833    SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface));
4834}
4835
4836/// `ContainerPatch::Surface`: every styling field at once (docs/surfaces.md "Reactive
4837/// surfaces"), applied in place by reshaping the container as a styled surface. XAML cannot
4838/// animate a `CornerRadius`, so the change applies at once. A role surface (a section card, a
4839/// cover's ground) keeps its realize-time look.
4840///
4841/// # Safety
4842///
4843/// `h` is a live container handle and this runs on the UI thread.
4844unsafe fn patch_surface(h: *mut c_void, p: &ContainerProps) {
4845    let mut surface = SURFACES
4846        .with(|m| m.borrow().get(&(h as usize)).cloned())
4847        .unwrap_or_default();
4848    if surface.props.role.is_some() {
4849        return;
4850    }
4851    surface.props = ContainerProps {
4852        role: None,
4853        ..p.clone()
4854    };
4855    surface.styled = true;
4856    // SAFETY: `h` is live per this function's contract.
4857    unsafe { shape_surface(h, &surface.props) };
4858    SURFACES.with(|m| m.borrow_mut().insert(h as usize, surface.clone()));
4859    paint_surface(h, surface, false);
4860}
4861
4862#[cfg(test)]
4863mod styled_surface_tests {
4864    use super::*;
4865    use day_spec::{Border, Color, Corners, LinearGradient, Shadow, SurfaceRole};
4866
4867    fn plain() -> ContainerProps {
4868        ContainerProps {
4869            fill: Some(Color::rgb(0.0, 0.0, 1.0).into()),
4870            corner_radius: 12.0,
4871            clips: true,
4872            ..Default::default()
4873        }
4874    }
4875
4876    #[test]
4877    fn plain_fill_and_uniform_corners_keep_the_plain_path() {
4878        assert!(!styled_surface(&ContainerProps::default()));
4879        assert!(!styled_surface(&plain()));
4880        // A corner selection with nothing to round is not a styled surface either.
4881        let square = ContainerProps {
4882            corner_radius: 0.0,
4883            corners: Corners::TOP,
4884            ..plain()
4885        };
4886        assert!(!styled_surface(&square));
4887    }
4888
4889    #[test]
4890    fn each_new_property_takes_the_styled_path() {
4891        let border = ContainerProps {
4892            border: Some(Border::new(Color::BLACK, 2.0)),
4893            ..plain()
4894        };
4895        let gradient = ContainerProps {
4896            fill: Some(LinearGradient::vertical(Color::WHITE, Color::BLACK).into()),
4897            ..plain()
4898        };
4899        let shadow = ContainerProps {
4900            shadow: Some(Shadow::new(Color::BLACK, 4.0)),
4901            clips: false,
4902            ..plain()
4903        };
4904        let corners = ContainerProps {
4905            corners: Corners::TOP,
4906            ..plain()
4907        };
4908        for props in [border, gradient, shadow, corners] {
4909            assert!(styled_surface(&props));
4910        }
4911    }
4912
4913    #[test]
4914    fn a_role_surface_keeps_its_theme_material() {
4915        let card = ContainerProps {
4916            role: Some(SurfaceRole::SectionCard),
4917            border: Some(Border::new(Color::BLACK, 2.0)),
4918            ..plain()
4919        };
4920        assert!(!styled_surface(&card));
4921    }
4922
4923    #[test]
4924    fn gradient_stops_split_into_clamped_offsets_and_argb() {
4925        let (offsets, colors) = gradient_stops(
4926            &[
4927                (-0.5, Color::rgb(1.0, 0.0, 0.0).into()),
4928                (0.5, Color::rgba(0.0, 1.0, 0.0, 0.0).into()),
4929                (1.5, Color::rgb(0.0, 0.0, 1.0).into()),
4930            ],
4931            &day_spec::Palette::fallback(false),
4932        );
4933        assert_eq!(offsets, [0.0, 0.5, 1.0]);
4934        assert_eq!(colors, [0xffff_0000, 0x0000_ff00, 0xff00_00ff]);
4935    }
4936
4937    #[test]
4938    fn radial_and_conic_fills_take_the_styled_path() {
4939        let stops = [(0.0, Color::WHITE), (1.0, Color::BLACK)];
4940        let radial = ContainerProps {
4941            fill: Some(
4942                day_spec::RadialGradient::new(day_spec::UnitPoint::CENTER, 0.5, stops).into(),
4943            ),
4944            ..plain()
4945        };
4946        let conic = ContainerProps {
4947            fill: Some(day_spec::ConicGradient::centered(day_spec::Angle::ZERO, stops).into()),
4948            ..plain()
4949        };
4950        assert!(styled_surface(&radial));
4951        assert!(styled_surface(&conic));
4952    }
4953
4954    #[test]
4955    fn an_ink_resolves_per_palette_and_only_dynamic_surfaces_are_kept() {
4956        let pair = day_spec::Ink::adaptive(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
4957        assert_eq!(
4958            ink_argb(pair, &day_spec::Palette::fallback(false)),
4959            0xffff_0000
4960        );
4961        assert_eq!(
4962            ink_argb(pair, &day_spec::Palette::fallback(true)),
4963            0xff00_00ff
4964        );
4965        assert!(!surface_is_dynamic(&plain()));
4966        let role = ContainerProps {
4967            border: Some(Border::new(day_spec::SystemColor::Separator, 1.0)),
4968            ..plain()
4969        };
4970        assert!(surface_is_dynamic(&role));
4971        assert_eq!(color_of_argb(0x80ff_0000).r, 1.0);
4972        assert!((color_of_argb(0x80ff_0000).a - 128.0 / 255.0).abs() < 1e-9);
4973    }
4974
4975    #[test]
4976    fn every_role_names_a_theme_resource() {
4977        for role in day_spec::SystemColor::ALL {
4978            let (keys, alpha) = role_keys(role);
4979            assert_ne!(keys.len(), 0);
4980            assert!(alpha > 0.0 && alpha <= 1.0);
4981        }
4982    }
4983}
4984
4985/// Per-row nav icon tints (docs/vectors.md) as one line-joined ARGB list, parallel to the rows.
4986/// `0` is the untinted row — fully transparent is not a color anyone can mean, and it keeps the
4987/// list positional so a row without a tint cannot shift the ones after it.
4988fn join_tints(tints: &[Option<day_spec::Ink>]) -> String {
4989    tints
4990        .iter()
4991        .map(|t| t.map_or(0, argb).to_string())
4992        .collect::<Vec<_>>()
4993        .join("\n")
4994}
4995
4996/// A vector NAME's staged XAML geometry (docs/vectors.md), or `None` when the name is not a
4997/// vector or its art was outside the convertible subset — the caller then draws the raster.
4998pub(crate) fn vector_geometry(name: &str) -> Option<String> {
4999    let path = day_spec::resource::resolve_vector_xaml(name)?;
5000    std::fs::read_to_string(path).ok()
5001}
5002
5003/// Per-row nav geometry, parallel to the rows. The specs are multi-line, and the FFI carries one
5004/// row per line, so each spec's newlines ride as `\x1f` (a unit separator cannot occur in path
5005/// data or a color) and the shim puts them back.
5006fn join_geoms(icons: &[Option<String>]) -> String {
5007    icons
5008        .iter()
5009        .map(|ic| {
5010            ic.as_deref()
5011                .and_then(vector_geometry)
5012                .map_or_default(|s| s.replace('\n', "\x1f"))
5013        })
5014        .collect::<Vec<_>>()
5015        .join("\n")
5016}
5017
5018/// Resolve an image NAME to a `file:///` URI the XAML `BitmapImage` can load (§18.3).
5019///
5020/// Unpackaged Win32 + XAML has no MRT/`.pri` resource store (that path is packaged/MSIX-only), so
5021/// images resolve to the loose files `day build` stages next to the exe under `images/` then
5022/// `assets/`. The shared [`resolve_image_file`](day_spec::resource::resolve_image_file) does that
5023/// lookup (probing `DAY_IMAGE_ROOT`/`DAY_ASSET_ROOT` for dev/`day launch` runs, then the exe-relative
5024/// dirs, inferring the extension), exactly as the AppKit/GTK/Qt backends do. An unresolved name
5025/// yields `""`, which `day_xaml_image_new` renders as an empty placeholder — the prior behavior.
5026/// A nav-icon name → the bundled file's NAME (e.g. "`nav_controls`" → "`nav_controls.png`"), which the
5027/// shim loads as `ms-appx:///images/<file>` (staged by `stage_bundled_images`). Empty if unresolved.
5028fn icon_file_name(name: &str) -> String {
5029    day_spec::resource::resolve_image_file(name)
5030        .as_deref()
5031        .and_then(|p| p.file_name())
5032        .map_or_default(|n| n.to_string_lossy().into_owned())
5033}
5034
5035fn image_uri(source: &str) -> String {
5036    // Pass the resolved NATIVE path to the shim, which reads the bytes and `SetSource`s a
5037    // BitmapImage — the system-XAML image loader does NOT accept `file://` (or bare-path) URIs (a
5038    // UWP restriction that carries into XAML Islands), so the old `file:///…` Uri silently loaded
5039    // nothing. An http(s) source (if ever resolved to one) is passed through and loaded as a Uri.
5040    match day_spec::resource::resolve_image_file(source) {
5041        Some(p) => p.to_string_lossy().into_owned(),
5042        None => String::new(),
5043    }
5044}
5045
5046// Secondary-window event trampolines (docs/windows.md). Sizes arrive in points: the shim divides
5047// the client pixels by the window's DPI scale, as for `window_resized`.
5048extern "C" fn win_resized(node: u64, w: c_int, h: c_int) {
5049    ffi_guard::contain((), || {
5050        emit(
5051            day_spec::NodeId(node),
5052            Event::WindowResized(Size::new(f64::from(w), f64::from(h))),
5053        );
5054    });
5055}
5056extern "C" fn win_closed(node: u64) {
5057    ffi_guard::contain((), || emit(day_spec::NodeId(node), Event::WindowClosed));
5058}
5059/// The primary window's close — the same event a secondary window reports, addressed to the
5060/// root node day-core adopted it under (docs/windows.md close policy).
5061extern "C" fn primary_closed() {
5062    ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::WindowClosed));
5063}
5064/// The user flipped Windows between light and dark: re-read the setting into day's dark signal so
5065/// palette closures recolor live, the same way GTK's `StyleManager` `dark` notify drives it.
5066extern "C" fn appearance_changed() {
5067    ffi_guard::contain((), || {
5068        day_core::note_appearance_changed();
5069        repaint_inks();
5070    });
5071}
5072/// The user flipped Windows' "Show animations" switch: re-read it into day's reduce-motion gate
5073/// (docs/accessibility.md). The shim has already crossed from `UISettings`' thread-pool thread
5074/// to the UI thread, so this runs where the gate lives, like `appearance_changed`.
5075extern "C" fn motion_changed() {
5076    ffi_guard::contain((), day_core::note_motion_changed);
5077}
5078extern "C" fn win_focused(node: u64, active: c_int) {
5079    ffi_guard::contain((), || {
5080        emit(day_spec::NodeId(node), Event::WindowFocused(active != 0));
5081    });
5082}
5083/// A window's display state changed, or a request for one did not land (docs/windows.md "Window
5084/// properties"): `node` is the secondary window's root node, or `WINDOW_NODE` for the primary,
5085/// which the shim reports as `u64::MAX`.
5086extern "C" fn win_state(node: u64, state: c_int) {
5087    ffi_guard::contain((), || {
5088        let state = day_spec::WindowState::from_code(state);
5089        log::debug!("xaml: window state now {state:?}");
5090        emit(day_spec::NodeId(node), Event::WindowStateChanged(state));
5091    });
5092}
5093/// An overlay window's title bar now covers `top` DIPs of its content (docs/window-chrome.md):
5094/// the window's safe-area top inset. The content reads it while it builds, so the first report
5095/// has to land before that: a secondary window's comes from inside `open_window` and is written
5096/// straight away (only a signal write: safe inside the tree's borrow, its readers run at turn
5097/// end); the primary's comes before `ready` and seeds the first window's ambient. A later
5098/// primary change looks the root up in the tree, which the caller may hold, so it is posted.
5099extern "C" fn chrome_inset(node: u64, top: c_double) {
5100    ffi_guard::contain((), || {
5101        log::debug!("xaml: overlay title bar inset {top}");
5102        let insets = day_spec::Insets {
5103            top,
5104            ..Default::default()
5105        };
5106        if node != day_spec::WINDOW_NODE.0 {
5107            day_core::set_window_safe_area(day_core::id_to_rnode(NodeId(node)), insets);
5108        } else if !day_core::has_tree() {
5109            day_core::seed_safe_area(insets);
5110        } else {
5111            Xaml::post(Box::new(move || day_core::set_safe_area(insets)));
5112        }
5113    });
5114}
5115
5116/// The app's id (Day.toml `[app] id`): `DAY_APP_ID` from `day launch`, else the value `day build`
5117/// baked into the binary, as day-core's remembered frames read it. Empty when neither has one.
5118fn app_id() -> String {
5119    std::env::var("DAY_APP_ID")
5120        .ok()
5121        .filter(|s| !s.is_empty())
5122        .or_else(|| option_env!("DAY_APP_ID").map(str::to_owned))
5123        .unwrap_or_default()
5124}
5125
5126/// Launch arguments a second instance forwarded (docs/deep-links.md "Single-instance
5127/// forwarding"). Posted: this runs inside a sent message, which a nested pump can deliver while
5128/// day-core holds its tree.
5129extern "C" fn forwarded_args(data: *const c_char, len: c_int) {
5130    ffi_guard::contain((), || {
5131        if data.is_null() || len <= 0 {
5132            return;
5133        }
5134        // SAFETY: the shim passes `len` bytes it owns for the duration of this call.
5135        let bytes = unsafe { std::slice::from_raw_parts(data.cast::<u8>(), len as usize) };
5136        let args: Vec<String> = bytes
5137            .split(|b| *b == 0)
5138            .map(|a| String::from_utf8_lossy(a).into_owned())
5139            .collect();
5140        Xaml::post(Box::new(move || day_core::forward_launch_args(args)));
5141    });
5142}
5143
5144/// Put the jump list's Tasks up (docs/deep-links.md "Launcher shortcuts"): the shortcuts the app
5145/// set while running first, then the ones Day.toml declares, each opening its route through
5146/// `--day-open-url`.
5147fn set_jump_tasks(dynamic: &[day_spec::LauncherShortcut]) {
5148    let id = app_id();
5149    let clean = |s: &str| s.replace(['\t', '\n'], " ");
5150    let spec = dynamic
5151        .iter()
5152        .map(|s| (s.route.clone(), s.label.clone()))
5153        .chain(
5154            day_core::shortcuts::launcher_shortcuts()
5155                .into_iter()
5156                .map(|(route, key)| (route.to_owned(), day_localization::t(key))),
5157        )
5158        .map(|(route, label)| {
5159            format!(
5160                "{}\t{}",
5161                clean(&label),
5162                clean(&day_core::launch_link(&route))
5163            )
5164        })
5165        .collect::<Vec<_>>()
5166        .join("\n");
5167    unsafe { ffi::day_xaml_set_jump_tasks(cstr(&id).as_ptr(), cstr(&spec).as_ptr()) };
5168}
5169
5170/// Content-size limits for one window, in points; an absent bound is 0 (none) to the shim.
5171fn set_limits(win: *mut c_void, min: Option<Size>, max: Option<Size>) {
5172    let min = min.unwrap_or(Size::new(0.0, 0.0));
5173    let max = max.unwrap_or(Size::new(0.0, 0.0));
5174    unsafe { ffi::day_xaml_window_set_limits(win, min.width, min.height, max.width, max.height) };
5175}
5176
5177/// A status item's click action or menu choice (docs/status-item.md): dispatched straight to
5178/// day-core, which needs no window to be open; `kind` 1 is the menu's Quit role.
5179extern "C" fn status_action(kind: c_int, id: u64) {
5180    ffi_guard::contain((), || {
5181        if kind == 1 {
5182            day_core::quit();
5183        } else {
5184            day_core::dispatch_menu_action(id);
5185        }
5186    });
5187}
5188
5189/// `WindowOptions`' chrome fields as the shim takes them (docs/window-chrome.md).
5190fn window_chrome(options: &WindowOptions) -> ffi::DayXamlChrome {
5191    use day_spec::WindowPlacement as P;
5192    use day_spec::{WindowBackground as B, WindowChrome as C, WindowMaterial as M};
5193    let (background, material) = match options.background {
5194        B::Opaque => (0, 0),
5195        B::Transparent => (1, 0),
5196        B::Material(M::Window) => (2, 0),
5197        B::Material(M::Sidebar) => (2, 1),
5198        B::Material(M::Transient) => (2, 2),
5199    };
5200    let (placement, x, y) = match options.placement {
5201        P::Automatic => (0, 0.0, 0.0),
5202        P::Centered => (1, 0.0, 0.0),
5203        P::At(p) => (2, p.x, p.y),
5204    };
5205    ffi::DayXamlChrome {
5206        chrome: match options.chrome {
5207            C::Standard => 0,
5208            C::Overlay => 1,
5209            C::Frameless => 2,
5210        },
5211        background,
5212        material,
5213        shadow: c_int::from(options.shadow),
5214        resizable: c_int::from(options.resizable),
5215        placement,
5216        x,
5217        y,
5218    }
5219}
5220
5221/// The area a presented cover has to fill: the whole client area, docked chrome included.
5222///
5223/// Read from the root element rather than from `LAST_WINDOW_SIZE`, which the resize callback
5224/// fills with the CONTENT size — what day's layout wants, and smaller than the window by exactly
5225/// the chrome a cover must hide. Falls back to the content size if the root has not been laid out
5226/// yet (a cover presented before the first frame), which is no worse than the old behavior.
5227/// A presented cover's place in a window `area` large: the whole area, or the bottom half for
5228/// a half sheet (docs/cover.md). Answers the y offset and the cover's own size.
5229fn cover_frame(cover: *mut c_void, area: Size) -> (f64, Size) {
5230    if COVER_HALF.with(|s| s.borrow().contains(&(cover as usize))) {
5231        let h = (area.height * 0.5).floor();
5232        (area.height - h, Size::new(area.width, h))
5233    } else {
5234        (0.0, area)
5235    }
5236}
5237
5238fn cover_extent(window: *mut c_void) -> Size {
5239    let (mut w, mut h) = (0.0f64, 0.0f64);
5240    unsafe { ffi::day_xaml_window_chrome_size(window, &raw mut w, &raw mut h) };
5241    if w > 0.0 && h > 0.0 {
5242        Size::new(w, h)
5243    } else {
5244        LAST_WINDOW_SIZE.with(std::cell::Cell::get)
5245    }
5246}
5247
5248extern "C" fn window_resized(w: c_int, h: c_int) {
5249    // The content size in points (DIPs): the shim divides the client pixels by the window's
5250    // DPI scale. Window creation still takes `WindowOptions::size` as pixels, so a window opens
5251    // smaller than asked above 100% scale, but day's layout and the XAML elements it places
5252    // agree at every scale.
5253    ffi_guard::contain((), || {
5254        let size = Size::new(f64::from(w), f64::from(h));
5255        LAST_WINDOW_SIZE.with(|c| c.set(size));
5256        emit(day_spec::WINDOW_NODE, Event::WindowResized(size));
5257        // Presented emulated covers track the WHOLE window, chrome included (docs/cover.md) —
5258        // `size` above is the content area, which is what day's layout wants and what a cover
5259        // must not be limited to. Null = the primary window (this callback carries no handle).
5260        let full = cover_extent(std::ptr::null_mut());
5261        COVERS.with(|c| {
5262            for (cover, node) in c.borrow().iter() {
5263                let (y, full) = cover_frame(*cover, full);
5264                unsafe {
5265                    ffi::day_xaml_set_geometry(
5266                        *cover,
5267                        0,
5268                        y.round() as c_int,
5269                        full.width.round() as c_int,
5270                        full.height.round() as c_int,
5271                    );
5272                };
5273                emit(*node, Event::FrameChanged(full));
5274            }
5275        });
5276    });
5277}
5278
5279extern "C" fn control_loaded(id: u64) {
5280    ffi_guard::contain((), || {
5281        let post = LOADED_MEASURES.with(|pending| {
5282            let mut pending = pending.borrow_mut();
5283            let first = pending.is_empty();
5284            pending.insert(id);
5285            first
5286        });
5287        if !post {
5288            return;
5289        }
5290        // Loaded can fire inside Measure/UpdateLayout while Day holds its tree borrow.
5291        // Defer, batch the invalidations, and retain only generational node ids: a control
5292        // may be removed before this runs, and its native address may already be reused.
5293        let boxed: Box<dyn FnOnce() + Send> = Box::new(|| {
5294            let nodes = LOADED_MEASURES.with(|p| std::mem::take(&mut *p.borrow_mut()));
5295            day_core::try_with_tree(|t| {
5296                for id in nodes {
5297                    let node = day_core::id_to_rnode(NodeId(id));
5298                    if t.node_exists(node) {
5299                        t.mark_needs_measure(node);
5300                    }
5301                }
5302                t.layout_if_needed();
5303            });
5304        });
5305        let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
5306        unsafe { ffi::day_xaml_post(run_posted, data) };
5307    });
5308}
5309
5310extern "C" fn run_posted(data: *mut c_void) {
5311    // The posted-closure trampoline runs arbitrary Rust (deferred emits, list populates) —
5312    // contained like every other FFI entry (day-spec's ffi_guard).
5313    let f: Box<Box<dyn FnOnce() + Send>> = unsafe { Box::from_raw(data.cast()) };
5314    ffi_guard::contain((), f);
5315}
5316
5317// A native modal answered (docs/dialogs.md): the shim reports (req, tag, index, text); decode into a
5318// PresentResult and route it to the window node, where day-core's executor resolves the future.
5319extern "C" fn present_cb(req: u64, tag: c_int, index: i64, text: *const c_char) {
5320    ffi_guard::contain((), || {
5321        let text = if text.is_null() {
5322            String::new()
5323        } else {
5324            unsafe { CStr::from_ptr(text) }
5325                .to_string_lossy()
5326                .into_owned()
5327        };
5328        let result = day_spec::present::PresentResult::decode(tag, index, text);
5329        emit(day_spec::WINDOW_NODE, Event::PresentResult { req, result });
5330    });
5331}
5332
5333// A native pointer recognizer fired (docs/shapes.md). Phase codes match the shim's
5334// day_xaml_enable_gesture: 0 Tap, 1/2/3 Drag Began/Changed/Ended, 4 LongPress, 5/6/7 Pinch
5335// Began/Changed/Ended, 8 Pan, 10/11/12 Hover, 13/14/15 Rotate Began/Changed/Ended. `x,y` are the
5336// node-local location; `tx,ty` the cumulative drag translation, or for a pinch `tx` the scale
5337// (cumulative since Began for a manipulation, the tick's own factor for a lone ctrl+wheel
5338// Changed), for a rotation `tx` the cumulative radians, for a pan the tick's delta
5339// (docs/canvas.md "Zoom and pan").
5340extern "C" fn on_gesture(
5341    id: u64,
5342    phase: c_int,
5343    x: c_double,
5344    y: c_double,
5345    tx: c_double,
5346    ty: c_double,
5347) {
5348    use day_spec::DragPhase;
5349    ffi_guard::contain((), || {
5350        let at = Point::new(x, y);
5351        let ev = match phase {
5352            0 => Event::Tap(at),
5353            4 => Event::LongPress(at),
5354            16 => Event::DoubleTap(at),
5355            17 | 18 => Event::Press {
5356                pressed: phase == 17,
5357                location: at,
5358            },
5359            // The manipulation's own release velocity, already in DIPs per second.
5360            19 => Event::GestureVelocity {
5361                kind: day_spec::GestureKind::Drag,
5362                velocity: Point::new(tx, ty),
5363            },
5364            5..=7 => Event::Pinch {
5365                phase: match phase {
5366                    5 => DragPhase::Began,
5367                    7 => DragPhase::Ended,
5368                    _ => DragPhase::Changed,
5369                },
5370                scale: tx,
5371                location: at,
5372            },
5373            13..=15 => Event::Rotate {
5374                phase: match phase {
5375                    13 => DragPhase::Began,
5376                    15 => DragPhase::Ended,
5377                    _ => DragPhase::Changed,
5378                },
5379                rotation: tx,
5380                location: at,
5381            },
5382            8 => Event::Pan {
5383                phase: DragPhase::Changed,
5384                delta: Point::new(tx, ty),
5385                location: at,
5386            },
5387            10..=12 => Event::Hover {
5388                phase: match phase {
5389                    10 => DragPhase::Began,
5390                    12 => DragPhase::Ended,
5391                    _ => DragPhase::Changed,
5392                },
5393                location: at,
5394            },
5395            1 => Event::Drag {
5396                phase: DragPhase::Began,
5397                location: at,
5398                translation: Point::ZERO,
5399            },
5400            3 => Event::Drag {
5401                phase: DragPhase::Ended,
5402                location: at,
5403                translation: Point::new(tx, ty),
5404            },
5405            _ => Event::Drag {
5406                phase: DragPhase::Changed,
5407                location: at,
5408                translation: Point::new(tx, ty),
5409            },
5410        };
5411        emit(NodeId(id), ev);
5412    });
5413}
5414
5415/// The touches recognizer's report (`day_xaml_set_touches_cb`): every contact on the node as
5416/// `"id,phase,x,y,pressure,kind;…"`.
5417extern "C" fn on_touches(id: u64, encoded: *const c_char) {
5418    ffi_guard::contain((), || {
5419        if encoded.is_null() {
5420            return;
5421        }
5422        // SAFETY: the shim passes a NUL-terminated string that outlives the call.
5423        let encoded = unsafe { CStr::from_ptr(encoded) }.to_string_lossy();
5424        let touches = parse_touches(&encoded);
5425        if !touches.is_empty() {
5426            emit(NodeId(id), Event::Touches(touches));
5427        }
5428    });
5429}
5430
5431/// The shim's touches wire, contact by contact; a malformed contact is skipped.
5432fn parse_touches(encoded: &str) -> Vec<day_spec::Touch> {
5433    use day_spec::{Touch, TouchPhase};
5434    encoded
5435        .split(';')
5436        .filter_map(|contact| {
5437            let mut f = contact.split(',');
5438            let id = f.next()?.parse::<u64>().ok()?;
5439            let phase = match f.next()?.parse::<u8>().ok()? {
5440                0 => TouchPhase::Began,
5441                1 => TouchPhase::Moved,
5442                2 => TouchPhase::Stationary,
5443                3 => TouchPhase::Ended,
5444                _ => TouchPhase::Cancelled,
5445            };
5446            let x = f.next()?.parse::<f64>().ok()?;
5447            let y = f.next()?.parse::<f64>().ok()?;
5448            let pressure = f.next()?.parse::<f64>().ok()?;
5449            let kind = pointer_kind(f.next()?.parse::<c_int>().ok()?);
5450            Some(
5451                Touch::new(id, phase, Point::new(x, y))
5452                    .with_pressure(pressure)
5453                    .with_kind(kind),
5454            )
5455        })
5456        .collect()
5457}
5458
5459/// The shim's input-kind code: 0 touch, 1 mouse, 2 stylus.
5460fn pointer_kind(code: c_int) -> day_spec::PointerKind {
5461    match code {
5462        0 => day_spec::PointerKind::Touch,
5463        2 => day_spec::PointerKind::Stylus,
5464        _ => day_spec::PointerKind::Mouse,
5465    }
5466}
5467
5468/// A scroll view's realize-time preferences (docs/scroll.md): hidden bars, snapping, zoom and
5469/// the reports the app asked for. `bounce` stays the platform's: a `ScrollViewer` has no
5470/// switch for its overscroll.
5471#[cfg(feature = "winui")]
5472fn configure_scroll(sv: *mut c_void, id: NodeId, p: &day_spec::props::ScrollProps) {
5473    use day_spec::props::{ScrollIndicators, ScrollSnap};
5474    let (snap, interval) = match p.snap {
5475        ScrollSnap::None => (0, 0.0),
5476        ScrollSnap::Page => (1, 0.0),
5477        ScrollSnap::Interval(points) => (2, points),
5478    };
5479    let (zoom_min, zoom_max) = p.zoom.map_or((0.0, 0.0), |z| (z.min, z.max));
5480    unsafe {
5481        ffi::day_xaml_scroll_configure(
5482            sv,
5483            id.0,
5484            c_int::from(p.indicators == ScrollIndicators::Hidden),
5485            snap,
5486            interval,
5487            zoom_min,
5488            zoom_max,
5489            c_int::from(p.track_offset),
5490            c_int::from(p.track_phase),
5491            on_scroll_event,
5492        );
5493    }
5494}
5495
5496/// System XAML keeps its scroll view as realized: the preferences above are WinUI's.
5497#[cfg(not(feature = "winui"))]
5498fn configure_scroll(_sv: *mut c_void, _id: NodeId, _p: &day_spec::props::ScrollProps) {}
5499
5500/// A scroll view's report (`day_xaml_scroll_configure`): kind 0 the offset, 1 the phase, 2 the
5501/// zoom scale.
5502#[cfg(feature = "winui")]
5503extern "C" fn on_scroll_event(id: u64, kind: c_int, a: c_double, b: c_double) {
5504    ffi_guard::contain((), || {
5505        let event = match kind {
5506            0 => Event::ScrollChanged(Point::new(a, b)),
5507            1 => Event::ScrollPhase(match a as i32 {
5508                1 => day_spec::ScrollPhase::Dragging,
5509                2 => day_spec::ScrollPhase::Coasting,
5510                _ => day_spec::ScrollPhase::Idle,
5511            }),
5512            _ => Event::ScrollZoomed(a),
5513        };
5514        emit(NodeId(id), event);
5515    });
5516}
5517
5518/// Windows' "Text size" changed; XAML has re-scaled its text already (docs/text.md).
5519extern "C" fn text_scale_changed() {
5520    ffi_guard::contain((), day_core::note_text_size_changed);
5521}
5522
5523/// The device behind the latest pointer input changed (docs/gestures.md "Input kind").
5524extern "C" fn on_pointer_kind(code: c_int) {
5525    ffi_guard::contain((), || {
5526        emit(
5527            day_spec::WINDOW_NODE,
5528            Event::PointerKindChanged(pointer_kind(code)),
5529        );
5530    });
5531}
5532
5533#[cfg(test)]
5534mod touches_tests {
5535    use super::*;
5536
5537    #[test]
5538    fn the_wire_reads_every_contact() {
5539        let t = parse_touches("0,0,1.500,2.000,1.0000,1;7,3,3.000,4.000,0.5000,0");
5540        assert_eq!(t.len(), 2);
5541        assert_eq!(t[0].id, 0);
5542        assert_eq!(t[0].phase, day_spec::TouchPhase::Began);
5543        assert_eq!(t[0].location, Point::new(1.5, 2.0));
5544        assert_eq!(t[0].kind, day_spec::PointerKind::Mouse);
5545        assert_eq!(t[1].id, 7);
5546        assert_eq!(t[1].phase, day_spec::TouchPhase::Ended);
5547        assert!((t[1].pressure - 0.5).abs() < 1e-9);
5548        assert_eq!(t[1].kind, day_spec::PointerKind::Touch);
5549    }
5550
5551    #[test]
5552    fn a_malformed_contact_is_skipped() {
5553        let t = parse_touches("x;1,1,0,0,1,2;");
5554        assert_eq!(t.len(), 1);
5555        assert_eq!(t[0].kind, day_spec::PointerKind::Stylus);
5556        assert_eq!(t[0].phase, day_spec::TouchPhase::Moved);
5557    }
5558}
5559
5560impl Platform for Xaml {
5561    // One backend serves both targets; `winui` is its WinUI 3 build (docs/winui.md).
5562    const TARGET: &'static str = if cfg!(feature = "winui") {
5563        "windows-winui"
5564    } else {
5565        "windows-xaml"
5566    };
5567    const TOOLKIT: &'static str = if cfg!(feature = "winui") {
5568        "winui"
5569    } else {
5570        "xaml"
5571    };
5572
5573    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, WinHandle, Size)>) {
5574        unsafe {
5575            let (min_w, min_h) = options
5576                .min_size
5577                .map_or((0, 0), |s| (s.width as c_int, s.height as c_int));
5578            // One process per app (docs/deep-links.md "Single-instance forwarding"): a second
5579            // launch hands its arguments to the running one and ends here, before any window.
5580            ffi::day_xaml_set_forward_cb(forwarded_args);
5581            if ffi::day_xaml_claim_instance(cstr(&app_id()).as_ptr()) == 0 {
5582                std::process::exit(0);
5583            }
5584            // Before the window exists: an overlay primary reports its inset as it lays out.
5585            ffi::day_xaml_set_chrome_inset_cb(chrome_inset);
5586            let chrome = window_chrome(&options);
5587            let win = ffi::day_xaml_window_new(
5588                cstr(&options.title).as_ptr(),
5589                options.size.width as c_int,
5590                options.size.height as c_int,
5591                min_w,
5592                min_h,
5593                &raw const chrome,
5594            );
5595            if win.is_null() {
5596                log::error!(
5597                    "day-toolkit-winui: could not create the XAML window (see error above)"
5598                );
5599                return;
5600            }
5601            self.window = win;
5602            // Bundled fonts (§18.4): stage every file into `<exe>/fonts/` before the app builds its
5603            // tree, so `Font::Custom` families resolve via `ms-appx:///fonts/…` inside XAML.
5604            stage_bundled_fonts();
5605            // Nav icons load as ms-appx BitmapIcons, so stage the project's images/ next to the exe.
5606            stage_bundled_images();
5607            // Taskbar/title icon (§18.2): the .ico `day launch` resolved from icons/windows/.
5608            if let Ok(icon) = std::env::var("DAY_APP_ICON") {
5609                ffi::day_xaml_set_app_icon(win, cstr(&icon).as_ptr());
5610            }
5611            // A maximum (the minimum alone keeps the shim's original WindowOptions path).
5612            if options.max_size.is_some() {
5613                set_limits(win, options.min_size, options.max_size);
5614            }
5615            ffi::day_xaml_set_status_cb(status_action);
5616            // COM is up with the window; the catalog was installed before `run`.
5617            set_jump_tasks(&[]);
5618            ffi::day_xaml_set_menu_cb(on_menu_action);
5619            ffi::day_xaml_label_link_cb(on_link);
5620            ffi::day_xaml_set_toolbar_cb(toolbar::on_toolbar_value);
5621            ffi::day_xaml_set_lifecycle_cb(on_lifecycle);
5622            ffi::day_xaml_set_touches_cb(on_touches);
5623            ffi::day_xaml_set_pointer_kind_cb(on_pointer_kind);
5624            ffi::day_xaml_watch_text_scale(text_scale_changed);
5625            ffi::day_xaml_set_present_cb(present_cb);
5626            // Before `ready`: the app's first build may already ask for a window state.
5627            ffi::day_xaml_set_window_state_cb(win_state);
5628            let root = ffi::day_xaml_window_root(win);
5629            self.primary_root = root;
5630            ready(self, WinHandle(root), options.size);
5631            ffi::day_xaml_window_on_resize(win, window_resized);
5632            ffi::day_xaml_set_primary_closed_cb(primary_closed);
5633            ffi::day_xaml_set_appearance_cb(appearance_changed);
5634            ffi::day_xaml_watch_reduce_motion(motion_changed);
5635            ffi::day_xaml_set_window_events_cb(win_resized, win_closed, win_focused);
5636            ffi::day_xaml_window_show(win);
5637            ffi::day_xaml_run(win);
5638        }
5639    }
5640
5641    fn post(f: Box<dyn FnOnce() + Send>) {
5642        let data = Box::into_raw(Box::new(f)).cast::<c_void>();
5643        unsafe { ffi::day_xaml_post(run_posted, data) };
5644    }
5645
5646    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
5647        // The timer door behind `day::sleep` (docs/async.md): a Win32 timer on the UI thread's
5648        // message queue (the shim hops there first), no helper thread. `SetTimer` caps a delay
5649        // at USER_TIMER_MAXIMUM (0x7FFFFFFF ms); a longer one runs as a chain of timers.
5650        const STEP: u32 = 0x7FFF_FFFF;
5651        if ms > STEP {
5652            Self::post_delayed(STEP, Box::new(move || Self::post_delayed(ms - STEP, f)));
5653            return;
5654        }
5655        let data = Box::into_raw(Box::new(f)).cast::<c_void>();
5656        unsafe { ffi::day_xaml_post_delayed(ms, run_posted, data) };
5657    }
5658}