Skip to main content

day_toolkit_qt/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-qt — the Qt 6 Widgets backend (linux-qt / macos-qt; DESIGN.md §9), over
5//! the day-toolkit-qt-sys C++ shim. `Handle = QtHandle(*mut QWidget)`; absolute geometry; toggle is a
6//! `QCheckBox` (Qt Widgets has no native switch — an explicitly documented divergence).
7
8mod controls;
9
10use std::cell::RefCell;
11use std::collections::HashMap;
12use std::ffi::{CStr, CString};
13use std::os::raw::{c_char, c_double, c_int, c_void};
14use std::rc::Rc;
15
16use day_toolkit_qt_sys as ffi;
17use linkme::distributed_slice;
18
19use day_spec::props::*;
20use day_spec::{
21    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
22    InputTraits, NodeId, PieceKind, Platform, Proposal, Rect, Registry, Renderer, Role, Size,
23    Support, Toolkit, Transform, WindowOptions, ffi_guard, kinds, props_of, sidetable::SideTable,
24};
25
26#[derive(Clone, Copy, PartialEq, Eq, Hash)]
27pub struct QtHandle(pub *mut c_void);
28
29/// An `AnimSpec` lowered for the shim's animation runs (`ffi::DayQtAnim`, docs/tween.md "The
30/// animation contract"): the shim plays the delay as a `QPauseAnimation`, the cycles as a looped
31/// `QVariantAnimation` (a forward-and-backward pair under autoreverse) whose key values are
32/// these samples of one cycle, so a spring and every easing curve are drawn exactly.
33#[derive(Clone, Debug, PartialEq)]
34struct QtAnim {
35    delay_ms: c_int,
36    duration_ms: c_int,
37    /// `-1` until the property is next set.
38    cycles: c_int,
39    autoreverse: bool,
40    /// One forward cycle's progress at evenly spaced offsets (`AnimSpec::keyframes`); the two
41    /// ends alone for a linear cycle, which Qt's interpolation already draws exactly.
42    keys: Vec<f64>,
43}
44
45impl QtAnim {
46    fn new(spec: &AnimSpec) -> Self {
47        let ms = |v: u32| c_int::try_from(v).unwrap_or(c_int::MAX);
48        let keys = if spec.curve == Curve::Linear {
49            vec![0.0, 1.0]
50        } else {
51            spec.keyframes().iter().map(|k| k.progress).collect()
52        };
53        QtAnim {
54            delay_ms: ms(spec.delay_ms),
55            duration_ms: ms(spec.duration_ms),
56            cycles: spec.cycles().map_or(-1, ms),
57            autoreverse: spec.autoreverse,
58            keys,
59        }
60    }
61
62    /// The shim's view of this run, borrowing `keys`.
63    fn raw(&self) -> ffi::DayQtAnim {
64        ffi::DayQtAnim {
65            delay_ms: self.delay_ms,
66            duration_ms: self.duration_ms,
67            cycles: self.cycles,
68            autoreverse: c_int::from(self.autoreverse),
69            keys: self.keys.as_ptr(),
70            n_keys: c_int::try_from(self.keys.len()).unwrap_or(0),
71        }
72    }
73}
74
75/// Calls `f` with the shim's run for `anim`, or a null pointer (apply at once) for `None`. The
76/// pointer and its samples are alive for the call.
77fn with_qt_anim<R>(anim: Option<&AnimSpec>, f: impl FnOnce(*const ffi::DayQtAnim) -> R) -> R {
78    match anim {
79        None => f(std::ptr::null()),
80        Some(spec) => {
81            let run = QtAnim::new(spec);
82            let raw = run.raw();
83            f(&raw const raw)
84        }
85    }
86}
87
88/// An `InputPurpose` as the code `day_qt_lineedit_set_traits` takes (the shim's switch is the
89/// other half of this table): 0 text, 1 name, 2 email, 3 url, 4 phone, 5 number, 6 decimal,
90/// 7 username, 8 password, 9 new password, 10 one-time code.
91fn qt_input_purpose(purpose: InputPurpose) -> c_int {
92    match purpose {
93        InputPurpose::Text => 0,
94        InputPurpose::Name => 1,
95        InputPurpose::Email => 2,
96        InputPurpose::Url => 3,
97        InputPurpose::Phone => 4,
98        InputPurpose::Number => 5,
99        InputPurpose::Decimal => 6,
100        InputPurpose::Username => 7,
101        InputPurpose::Password => 8,
102        InputPurpose::NewPassword => 9,
103        InputPurpose::OneTimeCode => 10,
104    }
105}
106
107// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
108#[cfg(target_os = "linux")]
109mod linux;
110mod picker;
111mod textarea;
112mod toolbar;
113mod transfer;
114mod tree;
115
116pub type Handle = QtHandle;
117
118pub mod ext;
119pub use ext::*;
120/// The icon spec a piece shim hands `day_qt_icon_new` (docs/extending.md): see
121/// [`toolbar::icon_args`].
122pub use toolbar::icon_args;
123
124/// The day-core event sink (node-id keyed).
125type Sink = Rc<dyn Fn(NodeId, Event)>;
126
127day_core::tls_group! {
128    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
129    /// Slider f64 range, keyed by node id (event callbacks) AND widget ptr (patch application).
130    /// SideTables: `release`'s sweep retires the widget-ptr entry with the widget, so a later
131    /// widget recycling the address can't read the dead slider's range. (The node-id side is
132    /// generation-keyed by day-core and never reused, so it cannot mis-hit.)
133    static RANGES: SideTable<(f64, f64)> = SideTable::new();
134    static RANGES_BY_PTR: SideTable<(f64, f64)> = SideTable::new();
135    /// (widget_ptr, kind) pairs already wired, so enable_gesture is idempotent.
136    static GESTURES: RefCell<std::collections::HashSet<(usize, day_spec::GestureKind)>> =
137        RefCell::new(std::collections::HashSet::new());
138
139    /// Menu button widget ptr → the provider its click opens (`set_button_menu`, docs/menus.md
140    /// "Menu buttons"). Swept on release with the widget.
141    static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
142    /// Summon-time context-menu providers by node (docs/menus.md "Dynamic context menus").
143    static CTX_MENU_FNS: RefCell<HashMap<u64, day_spec::ContextMenuFn>> =
144        RefCell::new(HashMap::new());
145
146    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
147    /// List NODE id → host key, so the cell-click callback (which carries the node) can
148    /// find its entry.
149    static LIST_BY_NODE: RefCell<HashMap<u64, usize>> = RefCell::new(HashMap::new());
150
151    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
152    static NAV_PAGE_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
153    /// Each nav page's pane, recorded at realize because `insert` sees only handles
154    /// (docs/size-classes.md).
155    static PAGE_PANE: RefCell<HashMap<usize, day_spec::props::Pane>> = RefCell::new(HashMap::new());
156
157    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
158    /// INSPECTOR_PANE widget → `(its NodeId, is-panel)`, recorded at realize because `insert`
159    /// sees only handles — the PAGE_PANE pattern.
160    static INSPECTOR_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> =
161        RefCell::new(HashMap::new());
162    /// Split host (the QSplitter, docs/split.md) → its state.
163    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
164    /// SPLIT_PANE widget → `(its NodeId, is-second)`, recorded at realize.
165    static SPLIT_PANE_IDS: RefCell<HashMap<usize, (NodeId, bool)>> = RefCell::new(HashMap::new());
166
167    /// Each label's own resolved point size, so a RELATIVE-size run can be written as the
168    /// absolute `pt` Qt's rich-text CSS understands (a percentage is silently ignored there).
169    ///
170    /// A side table because the patch that carries runs does not carry the font: `LabelPatch`
171    /// splits them, and by the time `Runs` arrives the `Font` it should scale against is
172    /// whatever the last `Font` patch set. Swept with the widget in `release`.
173    static LABEL_PT: SideTable<f64> = SideTable::new();
174
175    static NAV_SUITES: RefCell<HashMap<usize, NavSuite>> = RefCell::new(HashMap::new());
176    /// Suite page widgets, so a released one drops out of its suite. Unlike the `tabs()` piece's
177    /// pages these are framed by Day: NavLayout computes exactly the content rect the tab widget
178    /// would give them, and letting Qt's stacked layout do it instead left them at zero size.
179    static NAV_SUITE_PAGES: RefCell<std::collections::HashSet<usize>> =
180        RefCell::new(std::collections::HashSet::new());
181    /// A realized NAV_MENU's rows by widget: `(node, titles, icon names)`, kept until the menu is
182    /// inserted and a suite above it can be found and handed them.
183    static NAV_SUITE_ROWS: RefCell<HashMap<usize, NavRow>> = RefCell::new(HashMap::new());
184
185    /// The last reported window content size (seeds cover frames at Present).
186    static LAST_WINDOW_SIZE: std::cell::Cell<Size> =
187        const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
188    /// Presented emulated covers: (widget, NodeId).
189    static COVERS: RefCell<Vec<(*mut c_void, NodeId)>> = const { RefCell::new(Vec::new()) };
190    /// Cover widget → NodeId (set at realize).
191    static COVER_IDS: RefCell<HashMap<usize, NodeId>> = RefCell::new(HashMap::new());
192    /// Covers presented as half sheets (`CoverProps::half`, docs/cover.md): the bottom half
193    /// of the window content.
194    static COVER_HALF: RefCell<std::collections::HashSet<usize>> =
195        RefCell::new(std::collections::HashSet::new());
196
197    /// NAV_MENU widget → (row count, section heading count), for measure: the shim draws each
198    /// heading as a band of its own above its row.
199    static NAV_MENU_ROWS: RefCell<HashMap<usize, (usize, usize)>> = RefCell::new(HashMap::new());
200
201    /// `BitmapId` → what the decode reported (docs/images.md). Only the METADATA lives here;
202    /// the pixels are the shim's, in a `QImage` registry keyed by the same id.
203    static BITMAP_INFO: RefCell<HashMap<u64, day_spec::BitmapInfo>> = RefCell::new(HashMap::new());
204
205}
206
207pub fn emit(id: NodeId, ev: Event) {
208    let sink = SINK.with(|s| s.borrow().clone());
209    if let Some(sink) = sink {
210        sink(id, ev);
211    }
212}
213
214/// Deliver an event to day-core on the next event-loop turn — a genuine "safe point" (§8.3) —
215/// instead of inline. A native list selection rebuilds the sidebar detail *synchronously*
216/// (dispose old widgets, create new ones); doing that inside the `QListView`'s own key/click
217/// dispatch reparents widgets mid-event and reads freed memory (`QWidget::setParent` SIGSEGV).
218/// Only `Send` data (id + event) is captured; the thread-local sink runs on the main thread.
219fn emit_deferred(id: NodeId, ev: Event) {
220    let boxed: Box<dyn FnOnce() + Send> = Box::new(move || emit(id, ev));
221    let data = Box::into_raw(Box::new(boxed)).cast::<c_void>();
222    unsafe { ffi::day_qt_post(run_posted, data) };
223}
224
225/// Pack a color as `0xAARRGGBB`, the form the shim reads.
226fn argb(c: day_spec::Color) -> u32 {
227    let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
228    (f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)
229}
230
231fn apply_button_content(
232    h: *mut c_void,
233    title: &str,
234    icon: Option<&day_spec::Icon>,
235    icon_only: bool,
236) {
237    let (name, fallback) = toolbar::icon_args(icon);
238    unsafe {
239        ffi::day_qt_button_set_content(
240            h,
241            cstr(title).as_ptr(),
242            cstr(&name).as_ptr(),
243            fallback,
244            c_int::from(icon_only),
245        );
246    };
247}
248
249/// Hand a [`day_spec::props::ButtonStyleSpec`] to the shim, which styles the `QPushButton` in
250/// place. The widget stays a `QPushButton`, so focus, Space/Enter activation and the a11y role
251/// are unaffected whatever the style is.
252fn apply_button_style(w: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
253    use day_spec::props::ButtonStyleSpec as S;
254    let (kind, fill) = match style {
255        // A QPushButton hugs a one-glyph title already, so Compact is the stock look.
256        S::Automatic | S::Compact | S::Plain => (0, day_spec::Color::CLEAR),
257        S::Bordered => (1, day_spec::Color::CLEAR),
258        S::Prominent => (2, day_spec::Color::CLEAR),
259        S::Tinted(c) => (3, c.resolved()),
260    };
261    // SAFETY: `w` is a live QPushButton created by `day_qt_button_new`; the shim only reads the
262    // packed colors.
263    unsafe { ffi::day_qt_button_set_style(w, kind, argb(fill), argb(S::on_tint(fill))) };
264}
265
266/// Re-encode a decoded bitmap through the shim (docs/images.md).
267///
268/// A free function rather than the duty's body so each refusal reads as an early return instead
269/// of another copy of the same emit. The pixels never cross the boundary: the shim encodes and
270/// hands back one heap buffer, which is copied out and released through its own free.
271fn encode_bitmap(
272    id: day_spec::BitmapId,
273    spec: &day_spec::EncodeSpec,
274) -> Result<Vec<u8>, day_spec::ImageError> {
275    use day_spec::ImageFormat as F;
276    let format = match spec.format {
277        F::Png => "png",
278        F::Jpeg => "jpeg",
279        F::Tiff => "tiff",
280        F::Bmp => "bmp",
281        // Qt reads more than it writes; `encode_formats` says which before an app gets here.
282        _ => return Err(day_spec::ImageError::Encode),
283    };
284    if !BITMAP_INFO.with(|m| m.borrow().contains_key(&id.0)) {
285        return Err(day_spec::ImageError::Gone);
286    }
287    // Qt takes quality as 0..=100, with -1 meaning the format's own default.
288    let quality = spec
289        .quality
290        .map_or(-1, |q| (q.clamp(0.0, 1.0) * 100.0).round() as c_int);
291    let (fit_w, fit_h) = spec.fit.map_or((0.0, 0.0), |f| (f.width, f.height));
292    let mut len: c_int = 0;
293    // SAFETY: the shim returns either null or a malloc'd buffer of `len` bytes; it is copied out
294    // and released through the shim's own free, and `len` is written before the pointer is used.
295    let bytes = unsafe {
296        let p = ffi::day_qt_image_encode(
297            id.0,
298            cstr(format).as_ptr(),
299            quality,
300            fit_w,
301            fit_h,
302            &raw mut len,
303        );
304        if p.is_null() || len <= 0 {
305            return Err(day_spec::ImageError::Encode);
306        }
307        let out = std::slice::from_raw_parts(p, len as usize).to_vec();
308        ffi::day_qt_bytes_free(p);
309        out
310    };
311    Ok(bytes)
312}
313
314/// Encode every page, hand the shim borrowed views of them, and copy the document out.
315fn render_pdf_document(
316    pages: &[day_spec::PdfPage],
317    info: &day_spec::PdfInfo,
318) -> Result<Vec<u8>, day_spec::ExportError> {
319    let encoded: Vec<(Vec<f64>, CString)> = pages
320        .iter()
321        .map(|page| {
322            let (nums, texts) = day_spec::encode_ops(&page.ops);
323            (nums, cstr(&texts.join("\u{1f}")))
324        })
325        .collect();
326    let views: Vec<ffi::DayQtPdfPage> = pages
327        .iter()
328        .zip(&encoded)
329        .map(|(page, (nums, texts))| ffi::DayQtPdfPage {
330            w: page.size.width,
331            h: page.size.height,
332            nums: nums.as_ptr(),
333            n: nums.len() as c_int,
334            texts: texts.as_ptr(),
335        })
336        .collect();
337    let title = info.title.as_deref().map(cstr);
338    let author = info.author.as_deref().map(cstr);
339    let mut len: c_int = 0;
340    let mut err: *mut c_char = std::ptr::null_mut();
341    // SAFETY: every page view borrows `encoded`, which outlives the call, and the strings are
342    // null or NUL-terminated. The shim returns null (with `err` a heap string or null) or a
343    // malloc'd buffer of `len` bytes; each is copied out and released through the shim's frees.
344    unsafe {
345        let p = ffi::day_qt_canvas_render_pdf(
346            views.as_ptr(),
347            views.len() as c_int,
348            title.as_ref().map_or(std::ptr::null(), |t| t.as_ptr()),
349            author.as_ref().map_or(std::ptr::null(), |a| a.as_ptr()),
350            &raw mut len,
351            &raw mut err,
352        );
353        if p.is_null() || len <= 0 {
354            let why = if err.is_null() {
355                "QPdfWriter failed".to_string()
356            } else {
357                let text = CStr::from_ptr(err).to_string_lossy().into_owned();
358                ffi::day_qt_string_free(err);
359                text
360            };
361            ffi::day_qt_bytes_free(p);
362            return Err(day_spec::ExportError::Failed(why));
363        }
364        let out = std::slice::from_raw_parts(p, len as usize).to_vec();
365        ffi::day_qt_bytes_free(p);
366        Ok(out)
367    }
368}
369
370pub(crate) fn cstr(s: &str) -> CString {
371    // An interior NUL must not blank the whole string — a label, a menu item, a window title
372    // would silently vanish. Strip the NULs and keep the visible text.
373    CString::new(s).unwrap_or_else(|_| CString::new(s.replace('\0', "")).unwrap_or_default())
374}
375
376// ---------------------------------------------------------------------------
377// The list (docs/list.md, §10): a QListView over a count-only model (day-toolkit-qt-sys's
378// `DayListView`). The view owns selection and its painting, the keyboard walker, focus and the
379// tab stop, accessibility, the scroll bar and drag-and-drop; Day owns the rows. A row's cell is
380// a plain QWidget placed over its item as a viewport child, and the cells live in a POOL
381// bounded by the viewport plus overscan: a row scrolling out gives its cell back, a row
382// scrolling in takes one and is rebound into it with a slot write, which is what
383// `Cap::ListRecycling => Native` promises. The bookkeeping is `CellPool`, Qt-free so the
384// tests at the end of this file exercise it without a display.
385//
386// Every entry into Day from a Qt callback is posted to the next loop turn: Qt delivers scroll,
387// resize and layout synchronously inside its own handlers, where `bind_row`'s re-entry into
388// `with_tree` cannot run (DESIGN.md §10). Deferred work looks the list up again, since it may
389// have been released meanwhile.
390// ---------------------------------------------------------------------------
391
392/// Rows built beyond each edge of the viewport, so a flick has something to show before the
393/// window callback lands. The pool holds at most a viewport of rows plus two of these.
394const LIST_OVERSCAN: usize = 8;
395
396/// Measured heights remembered per row token (`Automatic` lists). Past this many the cache
397/// starts over rather than growing with every row ever visited: a row outside the window is
398/// shown at the estimate until it is bound again, which is what happens to a row that was never
399/// visited anyway.
400const LIST_HEIGHT_CACHE: usize = 4096;
401
402/// The pooled cells of one list: which row each shows, and the spares. Cells are opaque keys
403/// (the native handle as `usize`), so none of this touches Qt.
404#[derive(Default)]
405struct CellPool {
406    /// row → the cell showing it.
407    bound: std::collections::BTreeMap<usize, usize>,
408    /// cell → the row it shows (the inverse of `bound`).
409    row_of: HashMap<usize, usize>,
410    /// Cells with no row, hidden, ready for the next row that scrolls in.
411    free: Vec<usize>,
412    /// A sectioned list's spare cells that last held a header (docs/list.md "Sections"), kept
413    /// apart from `free`: day-core rebuilds a cell that changes kind, so a header row only ever
414    /// takes a header's cell and an item row an item's, the per-kind reuse pools of
415    /// `UITableView` and `RecyclerView`. Each kind's spares stay as many as that kind ever had
416    /// bound at once, so the pool is a window of items plus the headers a window holds.
417    free_headers: Vec<usize>,
418    /// The cells holding a header now, bound or spare.
419    headers: std::collections::HashSet<usize>,
420}
421
422impl CellPool {
423    /// Retarget the pool at `band`, the rows that should have a cell. Returns the cells that
424    /// left a row (to park and recycle) and the rows that still need one, ascending.
425    fn retarget(&mut self, band: std::ops::Range<usize>) -> (Vec<usize>, Vec<usize>) {
426        let leaving: Vec<usize> = self
427            .bound
428            .range(..band.start)
429            .chain(self.bound.range(band.end..))
430            .map(|(row, _)| *row)
431            .collect();
432        let mut parked = Vec::with_capacity(leaving.len());
433        for row in leaving {
434            if let Some(cell) = self.bound.remove(&row) {
435                self.row_of.remove(&cell);
436                if self.headers.contains(&cell) {
437                    self.free_headers.push(cell);
438                } else {
439                    self.free.push(cell);
440                }
441                parked.push(cell);
442            }
443        }
444        let need: Vec<usize> = band.filter(|row| !self.bound.contains_key(row)).collect();
445        (parked, need)
446    }
447
448    /// Bind `cell` to `row`. The cell must be spare (taken through [`Self::take_free`] or new).
449    fn bind(&mut self, row: usize, cell: usize) {
450        self.bound.insert(row, cell);
451        self.row_of.insert(cell, row);
452    }
453
454    /// A spare cell that last held a row of the same kind (header or item), if any.
455    fn take_free(&mut self, header: bool) -> Option<usize> {
456        if header {
457            self.free_headers.pop()
458        } else {
459            self.free.pop()
460        }
461    }
462
463    /// `cell` now holds a header row (or an item row).
464    fn set_kind(&mut self, cell: usize, header: bool) {
465        if header {
466            self.headers.insert(cell);
467        } else {
468            self.headers.remove(&cell);
469        }
470    }
471
472    fn row_of(&self, cell: usize) -> Option<usize> {
473        self.row_of.get(&cell).copied()
474    }
475
476    /// Every cell the pool owns, bound or spare (the tests' bound on the pool).
477    #[cfg(test)]
478    fn len(&self) -> usize {
479        self.bound.len() + self.free.len() + self.free_headers.len()
480    }
481}
482
483/// Row changes waiting for the next loop turn (docs/list.md "Keyed updates"): the patches
484/// arrive inside a day-core borrow, and the model change that applies them re-enters Day
485/// through `bind_row`. Everything one turn sends goes to the view in one flush.
486#[derive(Debug, PartialEq)]
487enum RowWork {
488    /// Re-query the source: the count, and every bound row.
489    Reload,
490    /// Sequential deltas, in the order they arrived.
491    Splice(Vec<RowDelta>),
492}
493
494impl RowWork {
495    /// Fold `next` into the work already waiting: deltas after deltas stay sequential, and a
496    /// reload on either side makes the deltas moot (it re-queries the final rows anyway).
497    fn merge(waiting: Option<Self>, next: Self) -> Self {
498        match (waiting, next) {
499            (Some(Self::Splice(mut a)), Self::Splice(b)) => {
500                a.extend(b);
501                Self::Splice(a)
502            }
503            (None, next) => next,
504            (Some(_), _) => Self::Reload,
505        }
506    }
507
508    /// The deltas as the shim's `kind, a, b` triples (0 insert, 1 remove, 2 move).
509    fn triples(deltas: &[RowDelta]) -> Vec<c_int> {
510        let idx = |i: usize| c_int::try_from(i).unwrap_or(c_int::MAX);
511        deltas
512            .iter()
513            .flat_map(|d| match d {
514                RowDelta::Insert(i) => [0, idx(*i), 0],
515                RowDelta::Remove(i) => [1, idx(*i), 0],
516                RowDelta::Move(from, to) => [2, idx(*from), idx(*to)],
517            })
518            .collect()
519    }
520}
521
522/// The supplementary rows of a list of `n` rows (docs/list.md "Header, footer and empty
523/// state"). They only ever lead and trail the items (`[top padding] [header] ([empty state] |
524/// items) [footer] [bottom padding]`), so the walk asks about the runs at both ends and stops
525/// at the first item each way: a handful of calls however long the list.
526fn supplement_rows(n: usize, is_supplement: &dyn Fn(usize) -> bool) -> Vec<usize> {
527    let lead = (0..n).take_while(|i| is_supplement(*i)).count();
528    let trail = (lead..n).rev().take_while(|i| is_supplement(*i)).count();
529    (0..lead).chain(n - trail..n).collect()
530}
531
532/// `RowAlign` as the shim's number (0 Nearest, 1 Start, 2 Center, 3 End).
533fn row_align_code(align: day_spec::RowAlign) -> c_int {
534    match align {
535        day_spec::RowAlign::Nearest => 0,
536        day_spec::RowAlign::Start => 1,
537        day_spec::RowAlign::Center => 2,
538        day_spec::RowAlign::End => 3,
539    }
540}
541
542struct ListEntry {
543    host: *mut c_void,
544    /// The row pitch: every row's height for a `Uniform` list, and for an `Automatic` one the
545    /// first estimate for rows not measured yet.
546    row_height: f64,
547    /// `RowHeight::Automatic`: each built row is as tall as its content.
548    automatic: bool,
549    source: Rc<RefCell<Option<day_spec::ListSource>>>,
550    pool: CellPool,
551    /// `Automatic` lists: row token → the height Day laid that row at, so a row keeps its
552    /// height across a reload or a reorder and a row scrolling back in starts at it.
553    heights: HashMap<u64, f64>,
554    /// The sum of `heights`, for the estimate without a walk.
555    height_sum: f64,
556    /// The height the model gives rows not measured yet: the running average of `heights`.
557    estimate: c_int,
558    /// Every bound row rebinds on the next sync: the source changed under the cells.
559    rebind_all: bool,
560    /// The height day's layout last framed the host at, so the first fill — which runs before
561    /// Qt has laid the view out and it still reports no visible rows — has a window.
562    frame_height: c_int,
563    /// A window-driven sync is already posted: one flick emits a stream of window reports, and
564    /// they would each post a pass that does the same work.
565    fill_pending: bool,
566    /// Last host width a populate ran at — so `set_frame` only repopulates on a real width change
567    /// (a populate's own child `set_frame`s must not schedule another, or it loops forever).
568    last_width: c_int,
569    /// The width the cells were last laid out to: the VIEWPORT's, which a legacy scroll bar
570    /// makes narrower than the host. A viewport resize that changes it repopulates.
571    cell_width: c_int,
572    node: u64,
573    /// Whether several rows may be selected (`ListProps::multi_select`): decides which event
574    /// a native selection change reports (docs/list.md).
575    multi: bool,
576    /// A sectioned list's pinned header cell (docs/list.md "Sections"; `Cap::ListSections` =
577    /// Emulated), made on the first sync of a source with `is_header`.
578    pin: Option<usize>,
579    /// The header row the pinned cell was last bound to.
580    pin_row: Option<usize>,
581    /// The row count the view's header rows were last given for (`day_qt_list_set_headers`).
582    headers_for: Option<usize>,
583    /// The row count the view's supplementary rows were last given for
584    /// (`day_qt_list_set_supplements`).
585    supplements_for: Option<usize>,
586    /// Supplementary row token → the height Day laid it at, so a header, footer, empty state
587    /// or padding row keeps its height through a splice (which drops the view's per-row
588    /// heights) even while it is out of the window. A list has a handful of them.
589    supplement_heights: HashMap<u64, f64>,
590    /// Row changes waiting for this turn's flush (`queue_rows`).
591    pending: Option<RowWork>,
592}
593
594extern "C" fn on_list_activate(node: u64, row: c_int) {
595    ffi_guard::contain((), || {
596        if row >= 0 {
597            emit_deferred(NodeId(node), Event::ListActivated(row as usize));
598        }
599    });
600}
601
602/// The view's selection changed under the user (a click, the keyboard walker, a range): report
603/// it the way docs/list.md wants — the full set where several rows may be selected, the one
604/// row otherwise, and an emptied selection as an empty set either way, since only the set can
605/// say "nothing".
606extern "C" fn on_list_selection(node: u64, rows: *const c_int, count: c_int) {
607    // Every extern "C" trampoline in this backend runs its body through `ffi_guard::contain`:
608    // a panic unwinding into the C++ shim frame is undefined behavior (day-spec's ffi_guard).
609    ffi_guard::contain((), || {
610        let rows: Vec<i64> = if rows.is_null() || count <= 0 {
611            Vec::new()
612        } else {
613            // SAFETY: the shim hands a live array of `count` ints for the duration of the call.
614            unsafe { std::slice::from_raw_parts(rows, count as usize) }
615                .iter()
616                .map(|r| i64::from(*r))
617                .collect()
618        };
619        let multi = LIST_BY_NODE
620            .with(|m| m.borrow().get(&node).copied())
621            .and_then(|k| LIST_STATE.with(|m| m.borrow().get(&k).map(|st| st.multi)));
622        let Some(multi) = multi else { return };
623        let ev = match (multi, rows.as_slice()) {
624            (false, [row]) => Event::SelectionChanged(*row),
625            _ => Event::SelectionSet(rows),
626        };
627        emit(NodeId(node), ev);
628    });
629}
630
631/// The reorder guard's verdict for a hovered drop (docs/list.md), called synchronously from the
632/// view's drag-move handler: the accepted target index, or -1. The reorder Rc is cloned out of
633/// `LIST_STATE` before the app's guard runs, so no borrow is held.
634extern "C" fn on_list_can_move(node: u64, from: c_int, to: c_int) -> c_int {
635    // Runs the app's own guard closure — contained, with "reject the drop" as the default.
636    ffi_guard::contain(-1, || {
637        let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) else {
638            return -1;
639        };
640        let r = LIST_STATE.with(|m| {
641            m.borrow().get(&host_key).and_then(|st| {
642                let s = st.source.borrow().clone()?;
643                Some(((s.len)(), s.reorder))
644            })
645        });
646        let Some((len, Some(r))) = r else { return -1 };
647        let (from, to) = (from.max(0) as usize, to.max(0) as usize);
648        if from >= len {
649            return -1;
650        }
651        let to = to.min(len - 1);
652        ((r.can_move)(from, to) as c_int).min(len as c_int - 1)
653    })
654}
655
656/// Commit a drop the view accepted: rotate Day's snapshot through the sync seam (deferring the
657/// app callback) and re-bind the cells in the new order.
658extern "C" fn on_list_move(node: u64, from: c_int, to: c_int) {
659    ffi_guard::contain((), || {
660        let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) else {
661            return;
662        };
663        let r = LIST_STATE.with(|m| {
664            m.borrow()
665                .get(&host_key)
666                .and_then(|st| st.source.borrow().clone()?.reorder)
667        });
668        let Some(r) = r else { return };
669        let (from, to) = (from.max(0) as usize, to.max(0) as usize);
670        if from != to {
671            (r.move_row)(from, to);
672            schedule_list_populate(host_key);
673        }
674    });
675}
676
677/// A scroll piece with `track_offset` moved (docs/scroll.md "Offset and phase"): the shim
678/// coalesces to one call per frame plus the resting one, from its own timer, outside any Day
679/// borrow; the sink only enqueues.
680extern "C" fn on_scroll_offset(node: u64, x: c_double, y: c_double) {
681    ffi_guard::contain((), || {
682        emit(
683            NodeId(node),
684            Event::ScrollChanged(day_spec::Point::new(x, y)),
685        );
686    });
687}
688
689/// Rebind every bound row on the next event-loop turn — NOT inline: a reload runs inside a
690/// `with_tree` borrow, and `bind_row` re-enters `with_tree`, which would panic.
691fn schedule_list_populate(host_key: usize) {
692    Qt::post(Box::new(move || list_populate(host_key)));
693}
694
695/// The view's window moved (a scroll, a resize, a relayout): bring the pool to it. Deferred and
696/// coalesced — the report arrives from inside Qt's own scroll handling, where `bind_row`'s
697/// re-entry into `with_tree` cannot run.
698extern "C" fn on_list_window(node: u64) {
699    ffi_guard::contain((), || {
700        // Even a visible-row query can make Qt lay out the view and report inside a sync's
701        // LIST_STATE borrow. Defer the registry access too.
702        Qt::post(Box::new(move || {
703            if let Some(host_key) = LIST_BY_NODE.with(|m| m.borrow().get(&node).copied()) {
704                schedule_list_fill(host_key);
705            }
706        }));
707    });
708}
709
710/// Sync the pool to the window on the next loop turn, at most once per turn however many times
711/// it is asked.
712fn schedule_list_fill(host_key: usize) {
713    let post = LIST_STATE.with(|m| {
714        let mut m = m.borrow_mut();
715        let Some(st) = m.get_mut(&host_key) else {
716            return false;
717        };
718        let first = !st.fill_pending;
719        st.fill_pending = true;
720        first
721    });
722    if !post {
723        return;
724    }
725    Qt::post(Box::new(move || {
726        LIST_STATE.with(|m| {
727            if let Some(st) = m.borrow_mut().get_mut(&host_key) {
728                st.fill_pending = false;
729            }
730        });
731        list_sync(host_key);
732    }));
733}
734
735/// Scroll the list to its bottom on the next event-loop turn — deferred so any pending
736/// `list_populate` has sized the content first (posted callbacks run FIFO), matching Qt's
737/// scrollToBottom semantics.
738fn schedule_list_scroll_end(host_key: usize) {
739    Qt::post(Box::new(move || {
740        if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
741            unsafe { ffi::day_qt_list_scroll_to_end(host) };
742        }
743    }));
744}
745
746/// Scroll the list just far enough that `row` is in view (docs/list.md), on the next
747/// event-loop turn — the same deferral as `schedule_list_scroll_end`.
748fn schedule_list_scroll_row(host_key: usize, row: usize) {
749    Qt::post(Box::new(move || {
750        if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
751            unsafe { ffi::day_qt_list_scroll_to_row(host, row as c_int) };
752        }
753    }));
754}
755
756/// Queue a `ListPatch::Reload` or `ListPatch::Splice` for the flush on the next loop turn
757/// (one flush per turn, posted by the first patch of the turn). A row scroll asked for after
758/// the patch is posted after the flush, so it finds its row (docs/list.md "Programmatic
759/// scrolling").
760fn queue_rows(host_key: usize, work: RowWork) {
761    let post = LIST_STATE.with(|m| {
762        let mut m = m.borrow_mut();
763        let Some(st) = m.get_mut(&host_key) else {
764            return false;
765        };
766        let first = st.pending.is_none();
767        st.pending = Some(RowWork::merge(st.pending.take(), work));
768        first
769    });
770    if post {
771        Qt::post(Box::new(move || flush_rows(host_key)));
772    }
773}
774
775/// Apply the turn's row changes. A splice goes to the view as model deltas, so selection and
776/// the current row follow their rows (docs/list.md), but only when they fit what the view was
777/// told: every index valid against the rows the earlier deltas left, and the count at the end
778/// the source's. Anything else (a snapshot that drifted from the deltas) reloads with a model
779/// reset that keeps the scroll position, never a delta the view cannot take. Either way the
780/// bound rows rebind in place and the viewport is reported after.
781fn flush_rows(host_key: usize) {
782    let work = LIST_STATE.with(|m| {
783        let mut m = m.borrow_mut();
784        let st = m.get_mut(&host_key)?;
785        let work = st.pending.take()?;
786        st.rebind_all = true;
787        let len = st.source.borrow().as_ref().map(|s| (s.len)());
788        Some((st.host, work, len))
789    });
790    let Some((host, work, len)) = work else {
791        return;
792    };
793    if let (RowWork::Splice(deltas), Some(len)) = (work, len) {
794        let triples = RowWork::triples(&deltas);
795        let count = c_int::try_from(deltas.len()).unwrap_or(c_int::MAX);
796        let len = c_int::try_from(len).unwrap_or(c_int::MAX);
797        let applied = unsafe { ffi::day_qt_list_splice_all(host, triples.as_ptr(), count, len) };
798        if applied == 0 {
799            log::debug!("qt list: a splice did not fit the view's rows; reloaded instead");
800        }
801    }
802    list_sync(host_key);
803}
804
805/// The viewport under a list resized (a legacy scroll bar came or went): the rows are laid
806/// out to a width the viewport no longer has, so re-lay them. A viewport that still matches
807/// the cells — the usual overlay-bar case, where every host resize also lands here — is left
808/// alone, and so is a list that has not built a row yet.
809extern "C" fn on_list_viewport_resized(host: *mut c_void) {
810    ffi_guard::contain((), || {
811        // Qt can resize the viewport synchronously while we realize cells. Wait until
812        // that operation releases LIST_STATE; look up the host again in case it died.
813        let host_key = host as usize;
814        Qt::post(Box::new(move || {
815            let state =
816                LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| (st.host, st.cell_width)));
817            let Some((host, cell_width)) = state else {
818                return;
819            };
820            let vw = unsafe { ffi::day_qt_list_viewport_width(host) };
821            if cell_width > 0 && vw > 0.0 && (vw as c_int) != cell_width {
822                schedule_list_populate(host_key);
823            }
824        }));
825    });
826}
827
828/// The reader moved the list themselves (docs/list.md "Following the end"): the view saw a
829/// wheel step, a scroll bar action or a key move it (`DayListView::readerScrolled`). Reported
830/// on the next loop turn, as the window reports are, and so ahead of the viewport report the
831/// same movement brings (the view posts that one as the bar's value lands, after this).
832extern "C" fn on_list_reader_scroll(node: u64) {
833    ffi_guard::contain((), || {
834        Qt::post(Box::new(move || {
835            let report = LIST_BY_NODE
836                .with(|m| m.borrow().get(&node).copied())
837                .and_then(|host_key| {
838                    LIST_STATE.with(|m| {
839                        m.borrow()
840                            .get(&host_key)?
841                            .source
842                            .borrow()
843                            .as_ref()?
844                            .reader_scroll
845                            .clone()
846                    })
847                });
848            if let Some(report) = report {
849                report();
850            }
851        }));
852    });
853}
854
855/// A source change under the cells: every bound row is showing the wrong row's data, so
856/// rebind the window in place, top to bottom. Reload, reorder, and a width that re-lays every
857/// row all come through here. The pool is untouched: a cell keeps its row, the row gets its
858/// new content with one slot write.
859fn list_populate(host_key: usize) {
860    LIST_STATE.with(|m| {
861        if let Some(st) = m.borrow_mut().get_mut(&host_key) {
862            st.rebind_all = true;
863        }
864    });
865    list_sync(host_key);
866}
867
868/// What one sync pass carries out of the `LIST_STATE` borrow into the binding phase.
869struct SyncPass {
870    host: *mut c_void,
871    rowh: f64,
872    source: day_spec::ListSource,
873    /// `(row, cell)` to bind, ascending.
874    work: Vec<(usize, *mut c_void)>,
875    /// Cells that left their rows this pass.
876    parked: Vec<usize>,
877    width: c_int,
878    host_width: c_int,
879    first_visible: usize,
880    automatic: bool,
881    /// The header row to bind into the pinned cell, and the cell (sectioned lists).
882    pin_bind: Option<(usize, *mut c_void)>,
883}
884
885/// Bring the pool to the rows the viewport shows (plus the overscan) and bind whatever needs
886/// it. Idempotent and cheap when nothing moved, which is what lets every window report call it.
887fn list_sync(host_key: usize) {
888    // Phase 1 — under the LIST_STATE borrow: move the pool and snapshot what the binds need.
889    // Nothing here re-enters Day; the view's own callbacks post.
890    let Some(pass) = LIST_STATE.with(|m| {
891        let mut m = m.borrow_mut();
892        let st = m.get_mut(&host_key)?;
893        let source = st.source.borrow().clone()?;
894        let n = (source.len)();
895        let rowh = st.row_height.max(1.0);
896        // The model holds the whole count, built or not: the scroll bar is how the user
897        // reaches rows that do not exist yet. One delta, however many rows.
898        unsafe { ffi::day_qt_list_set_count(st.host, n as c_int) };
899        let rebind_all = std::mem::take(&mut st.rebind_all);
900        // A sectioned list's header rows (docs/list.md "Sections") move only with the source:
901        // a reload, or a count that changed before its reload arrived.
902        let is_header = source.is_header.clone();
903        if let Some(is_header) = &is_header
904            && (rebind_all || st.headers_for != Some(n))
905        {
906            let rows: Vec<c_int> = (0..n)
907                .filter(|i| is_header(*i))
908                .map(|i| i as c_int)
909                .collect();
910            unsafe { ffi::day_qt_list_set_headers(st.host, rows.as_ptr(), rows.len() as c_int) };
911            st.headers_for = Some(n);
912        }
913        // The list's own header, footer, empty state and padding rows (docs/list.md "Header,
914        // footer and empty state") move the same way, and take back the heights Day laid them
915        // at: a splice drops the view's per-row heights, and a padding row out of the window
916        // would otherwise count at the item pitch.
917        let is_supplement = source.is_supplement.clone();
918        let mut supplements = Vec::new();
919        if let Some(f) = &is_supplement
920            && (rebind_all || st.supplements_for != Some(n))
921        {
922            supplements = supplement_rows(n, f.as_ref());
923            let raw: Vec<c_int> = supplements.iter().map(|i| *i as c_int).collect();
924            unsafe { ffi::day_qt_list_set_supplements(st.host, raw.as_ptr(), raw.len() as c_int) };
925            st.supplements_for = Some(n);
926        }
927        let (mut w, mut h) = (0.0_f64, 0.0_f64);
928        unsafe { ffi::day_qt_widget_size(st.host, &raw mut w, &raw mut h) };
929        // Rows lay out to the VIEWPORT's width, not the host's: under a legacy scroll bar the
930        // two differ by the bar, and a row framed to the host slides its trailing column under
931        // it. The viewport reports nothing until Qt has laid the view out; the host stands in.
932        let vw = unsafe { ffi::day_qt_list_viewport_width(st.host) };
933        let width = if vw > 0.0 { vw } else { w }.max(1.0) as c_int;
934        // The rows on screen. The view reports none until Qt has laid it out — the framed
935        // height stands in until then.
936        let (mut first, mut last) = (0 as c_int, -1 as c_int);
937        unsafe { ffi::day_qt_list_visible_rows(st.host, &raw mut first, &raw mut last) };
938        let (first, last) = if last >= first {
939            (first.max(0) as usize, last.max(0) as usize + 1)
940        } else {
941            let vh = if st.frame_height > 0 {
942                f64::from(st.frame_height)
943            } else {
944                // Never framed and never laid out: build a screen's worth so the first paint is
945                // not blank, and let the frame that follows widen the window.
946                600.0
947            };
948            (0, (vh / rowh).ceil() as usize)
949        };
950        let first_visible = first.min(n.saturating_sub(1));
951        let band = first.saturating_sub(LIST_OVERSCAN)..(last + LIST_OVERSCAN).min(n);
952        let (parked, need) = st.pool.retarget(band);
953        for cell in &parked {
954            unsafe { ffi::day_qt_list_park_cell(st.host, *cell as *mut c_void) };
955        }
956        if rebind_all && (st.automatic || is_header.is_some() || is_supplement.is_some()) {
957            // The rows moved under the measured heights (a reload, a reorder): drop them and
958            // re-seed the window from the token cache below, before anything is laid out. A
959            // sectioned list's headers go too, and the supplementary rows: a reload can move
960            // them.
961            unsafe { ffi::day_qt_list_clear_heights(st.host) };
962        }
963        for row in supplements {
964            if let Some(h) = st.supplement_heights.get(&(source.token_at)(row)) {
965                unsafe {
966                    ffi::day_qt_list_set_row_height(st.host, row as c_int, h.ceil() as c_int);
967                };
968            }
969        }
970        let mut work: Vec<(usize, *mut c_void)> = Vec::with_capacity(need.len());
971        for row in need {
972            let header = is_header.as_ref().is_some_and(|f| f(row));
973            let cell = match st.pool.take_free(header) {
974                Some(spare) => spare as *mut c_void,
975                None => unsafe { ffi::day_qt_container_new() },
976            };
977            st.pool.bind(row, cell as usize);
978            // The view owns the cell's place from here: positioned over its row through every
979            // scroll and relayout, painted over the row's selection.
980            unsafe { ffi::day_qt_list_place_cell(st.host, row as c_int, cell) };
981            work.push((row, cell));
982        }
983        if rebind_all {
984            work = st
985                .pool
986                .bound
987                .iter()
988                .map(|(row, cell)| (*row, *cell as *mut c_void))
989                .collect();
990        }
991        work.sort_unstable_by_key(|(row, _)| *row);
992        if let Some(f) = &is_header {
993            for (row, cell) in &work {
994                st.pool.set_kind(*cell as usize, f(*row));
995            }
996        }
997        // The pinned header shows the header of the topmost row's section, rebound only when
998        // that section changes or the rows moved under it; with no header yet it hides.
999        let mut pin_bind = None;
1000        if is_header.is_some() {
1001            let host = st.host;
1002            let pin = *st
1003                .pin
1004                .get_or_insert_with(|| unsafe { ffi::day_qt_list_pin_cell(host) } as usize);
1005            let target = unsafe { ffi::day_qt_list_header_for(host, first_visible as c_int) };
1006            let target = usize::try_from(target).ok();
1007            if rebind_all || target != st.pin_row {
1008                st.pin_row = target;
1009                match target {
1010                    Some(row) => pin_bind = Some((row, pin as *mut c_void)),
1011                    None => unsafe { ffi::day_qt_list_pin_bound(host, -1, 0) },
1012                }
1013            }
1014        }
1015        if rebind_all && st.automatic {
1016            for (row, _) in &work {
1017                if let Some(h) = st.heights.get(&(source.token_at)(*row)) {
1018                    unsafe {
1019                        ffi::day_qt_list_set_row_height(st.host, *row as c_int, h.ceil() as c_int);
1020                    };
1021                }
1022            }
1023        }
1024        st.last_width = w.max(1.0) as c_int;
1025        st.cell_width = width;
1026        Some(SyncPass {
1027            host: st.host,
1028            rowh,
1029            source,
1030            work,
1031            parked,
1032            width,
1033            host_width: st.last_width,
1034            first_visible,
1035            automatic: st.automatic,
1036            pin_bind,
1037        })
1038    }) else {
1039        return;
1040    };
1041    let SyncPass {
1042        host,
1043        rowh,
1044        source,
1045        work,
1046        parked,
1047        width,
1048        host_width,
1049        first_visible,
1050        automatic,
1051        pin_bind,
1052    } = pass;
1053    // Phase 2 — no borrow held (bind_row re-enters with_tree, which may lay out + set_frame the
1054    // list host, taking LIST_STATE again).
1055    //
1056    // A parked cell's ids park with it (day-core's `recycle`), posted: the park arrived from a
1057    // pass that may sit inside a layout, and a cell this same turn binds again keeps its ids —
1058    // the re-check AppKit and UIKit both needed.
1059    for cell in parked {
1060        Qt::post(Box::new(move || {
1061            let recycle = LIST_STATE.with(|m| {
1062                let m = m.borrow();
1063                let st = m.get(&host_key)?;
1064                if st.pool.row_of(cell).is_some() {
1065                    return None; // bound again: its ids are the live row's
1066                }
1067                st.source.borrow().as_ref().map(|s| s.recycle.clone())
1068            });
1069            if let Some(recycle) = recycle {
1070                recycle(cell as *mut c_void);
1071            }
1072        }));
1073    }
1074    if source.viewport.is_some() {
1075        // What the list shows now (docs/list.md "Visible rows"), asked on the next turn: the
1076        // view lays out what this pass changed first, and a native layout may still hold the
1077        // core tree borrow. It supersedes `first_visible`, which is then never called.
1078        Qt::post(Box::new(move || list_report_viewport(host_key)));
1079    } else if source.first_visible.is_some() {
1080        // A viewport change can recompose and lay out a floating header. A
1081        // native layout may still hold the core tree borrow, so defer delivery.
1082        Qt::post(Box::new(move || {
1083            let source = LIST_STATE.with(|m| {
1084                m.borrow()
1085                    .get(&host_key)
1086                    .and_then(|st| st.source.borrow().clone())
1087            });
1088            if let Some(source) = source
1089                && let Some(report) = &source.first_visible
1090            {
1091                report(first_visible.min((source.len)().saturating_sub(1)));
1092            }
1093        }));
1094    }
1095    let mut measured = false;
1096    for (i, cell) in work {
1097        // The row's frame, so the bind lays the content out to the size it will be shown at.
1098        // The view places the cell itself; before its first layout pass the frame is empty and
1099        // the row pitch stands in.
1100        let (mut x, mut y, mut cw, mut ch) = (0 as c_int, 0 as c_int, 0 as c_int, 0 as c_int);
1101        unsafe {
1102            ffi::day_qt_list_cell_frame(
1103                host,
1104                i as c_int,
1105                &raw mut x,
1106                &raw mut y,
1107                &raw mut cw,
1108                &raw mut ch,
1109            );
1110        };
1111        if cw <= 0 || ch <= 0 {
1112            (x, y, cw, ch) = (0, (i as f64 * rowh) as c_int, width, rowh as c_int);
1113        }
1114        unsafe { ffi::day_qt_set_geometry(cell, x, y, cw, ch) };
1115        // First use builds the row; a pooled cell takes the new row with a slot write.
1116        (source.bind_row)(i, cell);
1117        // Day lays a bound row out at the list's own width — the host's, scroll bar included.
1118        // The cell is the viewport's width, so a legacy scroll bar covered the row's trailing
1119        // column (the sidebar's unread counts). Tell Day the cell's real width, the seam every
1120        // other backend uses (`ListSource::layout_cell`); it is remembered per cell, so later
1121        // binds start from it and this is a no-op once the widths agree.
1122        if cw != host_width {
1123            (source.layout_cell)(cell, f64::from(cw));
1124        }
1125        // A self-sizing row is as tall as Day laid it, padding included; the view re-lays its
1126        // items once per turn and moves the cells below. Later changes come as
1127        // `RowSizeInvalidated`. A section header sizes the same way in every list, `Uniform`
1128        // included (docs/list.md "Sections").
1129        // A supplementary row sizes to its content the same way (docs/list.md "Header, footer
1130        // and empty state").
1131        let header = source.is_header.as_ref().is_some_and(|f| f(i));
1132        let supplement = source.is_supplement.as_ref().is_some_and(|f| f(i));
1133        if automatic || header || supplement {
1134            let laid = (source.cell_height)(cell);
1135            if laid > 0.0 {
1136                let laid_px = laid.ceil() as c_int;
1137                unsafe {
1138                    ffi::day_qt_set_geometry(cell, x, y, cw, laid_px);
1139                    ffi::day_qt_list_set_row_height(host, i as c_int, laid_px);
1140                }
1141                // Headers and supplementary rows stay out of the items' estimate; the view
1142                // guesses headers apart, and a supplementary row keeps its own height.
1143                if supplement {
1144                    list_remember_supplement(host_key, (source.token_at)(i), laid);
1145                } else if !header {
1146                    list_remember_height(host_key, (source.token_at)(i), laid);
1147                    measured = true;
1148                }
1149            }
1150        }
1151    }
1152    if measured {
1153        list_update_estimate(host_key);
1154    }
1155    // The pinned copy of the current header: one more cell bound to that header's row, laid to
1156    // the viewport's width and placed by the view (`DayListView::placePin`).
1157    if let Some((row, pin)) = pin_bind {
1158        unsafe { ffi::day_qt_set_geometry(pin, 0, 0, width, rowh as c_int) };
1159        (source.bind_pinned)(row, pin);
1160        if width != host_width {
1161            (source.layout_cell)(pin, f64::from(width));
1162        }
1163        let laid = (source.cell_height)(pin);
1164        let height = if laid > 0.0 { laid.ceil() } else { rowh } as c_int;
1165        unsafe { ffi::day_qt_list_pin_bound(host, row as c_int, height) };
1166    }
1167}
1168
1169/// Report what the list shows (docs/list.md "Visible rows"): the first and last rows in view and
1170/// the distance to the end, read from the view as it is laid now. Nothing with no rows, and
1171/// nothing while row changes wait for their flush: the source already has its new rows and the
1172/// view not yet, so the old end would be reported against the new row count, and day-core takes
1173/// a new count with a small distance as a fresh arrival at the end (`on_end_reached` would fire
1174/// again for rows that were just appended). The flush reports after it.
1175fn list_report_viewport(host_key: usize) {
1176    let found = LIST_STATE.with(|m| {
1177        let m = m.borrow();
1178        let st = m.get(&host_key)?;
1179        if st.pending.is_some() {
1180            return None;
1181        }
1182        let report = st.source.borrow().as_ref()?.viewport.clone()?;
1183        Some((st.host, report))
1184    });
1185    let Some((host, report)) = found else {
1186        return;
1187    };
1188    let (mut first, mut last, mut end) = (0 as c_int, 0 as c_int, 0.0_f64);
1189    if unsafe { ffi::day_qt_list_viewport(host, &raw mut first, &raw mut last, &raw mut end) } == 0
1190    {
1191        return;
1192    }
1193    report(day_spec::ListViewport {
1194        first: first.max(0) as usize,
1195        last: last.max(first).max(0) as usize,
1196        end_distance: end.max(0.0),
1197    });
1198}
1199
1200/// Remember that the supplementary row with `token` was laid `height` tall.
1201fn list_remember_supplement(host_key: usize, token: u64, height: f64) {
1202    LIST_STATE.with(|m| {
1203        if let Some(st) = m.borrow_mut().get_mut(&host_key) {
1204            st.supplement_heights.insert(token, height);
1205        }
1206    });
1207}
1208
1209/// Remember that the row with `token` was laid `height` tall (`Automatic` lists), keeping the
1210/// running sum current for the estimate.
1211fn list_remember_height(host_key: usize, token: u64, height: f64) {
1212    LIST_STATE.with(|m| {
1213        let mut m = m.borrow_mut();
1214        let Some(st) = m.get_mut(&host_key) else {
1215            return;
1216        };
1217        if st.heights.len() >= LIST_HEIGHT_CACHE && !st.heights.contains_key(&token) {
1218            st.heights.clear();
1219            st.height_sum = 0.0;
1220        }
1221        if let Some(old) = st.heights.insert(token, height) {
1222            st.height_sum -= old;
1223        }
1224        st.height_sum += height;
1225    });
1226}
1227
1228/// Give the model the running average of the measured heights for the rows it has not
1229/// measured, when it moved by a point or more: every change is one relayout.
1230fn list_update_estimate(host_key: usize) {
1231    let update = LIST_STATE.with(|m| {
1232        let mut m = m.borrow_mut();
1233        let st = m.get_mut(&host_key)?;
1234        if st.heights.is_empty() {
1235            return None;
1236        }
1237        let avg = (st.height_sum / st.heights.len() as f64).round() as c_int;
1238        if avg <= 0 || avg == st.estimate {
1239            return None;
1240        }
1241        st.estimate = avg;
1242        Some((st.host, avg))
1243    });
1244    if let Some((host, avg)) = update {
1245        unsafe { ffi::day_qt_list_set_estimate(host, avg) };
1246    }
1247}
1248
1249/// A self-sizing row Day re-laid at a new height (`ListPatch::RowSizeInvalidated`), applied on
1250/// the next event-loop turn: it arrives inside a day-core layout pass, and the view's relayout
1251/// must not run under it. The pool says which row the cell shows now.
1252fn schedule_list_row_height(host_key: usize, cell: usize, height: f64) {
1253    Qt::post(Box::new(move || {
1254        let found = LIST_STATE.with(|m| {
1255            let m = m.borrow();
1256            let st = m.get(&host_key)?;
1257            // The pinned header re-laid: only the pin changes height (docs/list.md "Sections").
1258            if st.pin == Some(cell) {
1259                let row = st.pin_row?;
1260                unsafe {
1261                    ffi::day_qt_list_pin_bound(st.host, row as c_int, height.ceil() as c_int);
1262                };
1263                return None;
1264            }
1265            let row = st.pool.row_of(cell)?;
1266            // A header's height is not an item's: it stays out of the estimate. A supplementary
1267            // row's (the empty state re-laid to a new list height) is remembered on its own.
1268            let kind = st.source.borrow().as_ref().map(|s| {
1269                let token = (s.token_at)(row);
1270                if s.is_supplement.as_ref().is_some_and(|f| f(row)) {
1271                    (Some(token), true)
1272                } else if s.is_header.as_ref().is_some_and(|f| f(row)) {
1273                    (None, false)
1274                } else {
1275                    (Some(token), false)
1276                }
1277            });
1278            Some((st.host, row, kind))
1279        });
1280        let Some((host, row, kind)) = found else {
1281            return;
1282        };
1283        unsafe { ffi::day_qt_list_set_row_height(host, row as c_int, height.ceil() as c_int) };
1284        match kind {
1285            Some((Some(token), true)) => list_remember_supplement(host_key, token, height),
1286            Some((Some(token), false)) => {
1287                list_remember_height(host_key, token, height);
1288                list_update_estimate(host_key);
1289            }
1290            _ => {}
1291        }
1292    }));
1293}
1294
1295/// A right-click landed on a widget with a summon-time menu: ask the provider and hand Qt a
1296/// fresh `QMenu` (null when the provider answers empty). Runs synchronously inside Qt's
1297/// customContextMenuRequested — the provider must not re-enter the event loop.
1298extern "C" fn on_context_menu_summon(
1299    node: u64,
1300    x: std::os::raw::c_double,
1301    y: std::os::raw::c_double,
1302) -> *mut c_void {
1303    ffi_guard::contain(std::ptr::null_mut(), || {
1304        let Some(f) = CTX_MENU_FNS.with(|m| m.borrow().get(&node).cloned()) else {
1305            return std::ptr::null_mut();
1306        };
1307        let items = f(day_spec::Point::new(x, y));
1308        if items.is_empty() {
1309            return std::ptr::null_mut();
1310        }
1311        let menu = unsafe { ffi::day_qt_menu_new() };
1312        build_qt_menu(menu, &items);
1313        menu
1314    })
1315}
1316
1317/// A menu button was clicked (`day_qt_button_menu_fn`; `key` is its widget pointer): ask the
1318/// provider now and hand Qt a fresh `QMenu`, or null when it answers empty.
1319extern "C" fn on_button_menu(
1320    key: u64,
1321    _x: std::os::raw::c_double,
1322    _y: std::os::raw::c_double,
1323) -> *mut c_void {
1324    ffi_guard::contain(std::ptr::null_mut(), || {
1325        let Some(f) = BUTTON_MENUS.with(|t| t.get(key as usize)) else {
1326            return std::ptr::null_mut();
1327        };
1328        // The provider may remove this button; then no menu opens (docs/menus.md).
1329        let Some(items) = day_spec::resolve_button_menu(&f, || {
1330            BUTTON_MENUS.with(|t| t.get(key as usize)).is_some()
1331        }) else {
1332            return std::ptr::null_mut();
1333        };
1334        let menu = unsafe { ffi::day_qt_menu_new() };
1335        build_qt_menu(menu, &items);
1336        menu
1337    })
1338}
1339
1340extern "C" fn on_press(id: u64) {
1341    ffi_guard::contain((), || emit(NodeId(id), Event::Pressed));
1342}
1343extern "C" fn on_toggle(id: u64, on: c_int) {
1344    ffi_guard::contain((), || emit(NodeId(id), Event::ToggleChanged(on != 0)));
1345}
1346extern "C" fn on_text(id: u64, s: *const c_char) {
1347    ffi_guard::contain((), || {
1348        let text = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1349        emit(NodeId(id), Event::TextChanged(text));
1350    });
1351}
1352/// A styled run's link was clicked (docs/text-runs.md); the app's `.on_link()` decides what the
1353/// target does — Qt's own external opening is left off in the shim.
1354extern "C" fn on_text_selected(id: u64, start: c_int, end: c_int) {
1355    ffi_guard::contain((), || {
1356        let start = usize::try_from(start).unwrap_or(0);
1357        let end = usize::try_from(end).unwrap_or(0).max(start);
1358        emit(NodeId(id), Event::TextSelected { start, end });
1359    });
1360}
1361extern "C" fn on_text_scale() {
1362    ffi_guard::contain((), day_core::note_text_size_changed);
1363}
1364extern "C" fn on_link(id: u64, s: *const c_char) {
1365    ffi_guard::contain((), || {
1366        let url = unsafe { CStr::from_ptr(s) }.to_string_lossy().into_owned();
1367        emit(NodeId(id), Event::LinkActivated(url));
1368    });
1369}
1370extern "C" fn on_slider(id: u64, v: c_int, committed: c_int) {
1371    ffi_guard::contain((), || {
1372        let (min, max) = RANGES.with(|r| r.get(id as usize)).unwrap_or((0.0, 1.0));
1373        let value = min + (f64::from(v) / 1000.0) * (max - min);
1374        // The live value always; the settled one additionally, so a drag records once (the shim
1375        // decides which is which — see `day_qt_slider_new`).
1376        emit(NodeId(id), Event::ValueChanged(value));
1377        if committed != 0 {
1378            emit(NodeId(id), Event::ValueCommitted(value));
1379        }
1380    });
1381}
1382/// A key's phase from the shim's wire (docs/menus.md "Keys"): 0 down, 1 repeat (Qt's
1383/// `isAutoRepeat`), 2 up.
1384fn key_phase(phase: c_int) -> day_spec::KeyPhase {
1385    match phase {
1386        1 => day_spec::KeyPhase::Repeat,
1387        2 => day_spec::KeyPhase::Up,
1388        _ => day_spec::KeyPhase::Down,
1389    }
1390}
1391
1392/// Key callback from the C++ key filter (docs/menus.md): `code` 0–3 is an arrow, 10–19 a
1393/// digit, `phase` 0 down, 1 repeat, 2 up. Answers whether the app claimed it: a canvas nobody
1394/// hung `.on_key` on keeps none of them, so an enclosing scroll area still scrolls with the
1395/// keyboard. An up comes only for a down the node claimed, so it is always the node's.
1396extern "C" fn on_key(id: u64, code: c_int, modifiers: c_int, phase: c_int) -> c_int {
1397    ffi_guard::contain(0, || {
1398        let key = match code {
1399            0 => "ArrowLeft",
1400            1 => "ArrowRight",
1401            2 => "ArrowUp",
1402            3 => "ArrowDown",
1403            10..=19 => day_spec::KeyEvent::DIGITS[(code - 10) as usize],
1404            _ => return 0,
1405        };
1406        let node = NodeId(id);
1407        let phase = key_phase(phase);
1408        if phase != day_spec::KeyPhase::Up && !day_spec::keys::handled(node) {
1409            return 0;
1410        }
1411        emit(
1412            node,
1413            Event::Key(day_spec::KeyEvent::named(key, modifiers as u8).with_phase(phase)),
1414        );
1415        1
1416    })
1417}
1418
1419/// A line edit's Up, Down or Escape (docs/textfield.md "Keys"): claimed, and with `deliver`
1420/// reported, when the field has a key handler and no modifier is held. The release of a key
1421/// the field claimed comes as `phase` 2 and is the handler's whatever the modifiers.
1422extern "C" fn on_field_key(
1423    id: u64,
1424    name: *const c_char,
1425    modifiers: c_int,
1426    deliver: c_int,
1427    phase: c_int,
1428) -> c_int {
1429    ffi_guard::contain(0, || {
1430        // SAFETY: the shim passes one of its own NUL-terminated strings, valid for the call.
1431        let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
1432        let node = NodeId(id);
1433        let phase = key_phase(phase);
1434        if phase == day_spec::KeyPhase::Up {
1435            let up = day_spec::KeyEvent::named(name, modifiers as u8).with_phase(phase);
1436            emit(node, Event::Key(up));
1437            return 1;
1438        }
1439        if !day_spec::keys::field_claims(node, &name, modifiers as u8) {
1440            return 0;
1441        }
1442        if deliver != 0 {
1443            emit(
1444                node,
1445                Event::Key(day_spec::KeyEvent::named(name, 0).with_phase(phase)),
1446            );
1447        }
1448        1
1449    })
1450}
1451
1452/// Whether `id` took the whole keyboard (`Decorate::keyboard`, docs/menus.md): the C++ key
1453/// filter asks before it names a letter.
1454extern "C" fn on_text_key_query(id: u64) -> c_int {
1455    ffi_guard::contain(0, || c_int::from(day_spec::keys::text(NodeId(id))))
1456}
1457
1458/// A key on the full route (docs/menus.md "The full route"): `name` is the day name (empty
1459/// for text no single key is behind), `text` what it typed or null, both valid for the call,
1460/// `phase` 0 down, 1 repeat, 2 up (never with text). Answers whether the app claimed it.
1461extern "C" fn on_text_key(
1462    id: u64,
1463    name: *const c_char,
1464    text: *const c_char,
1465    modifiers: c_int,
1466    phase: c_int,
1467) -> c_int {
1468    ffi_guard::contain(0, || {
1469        // SAFETY: the shim passes NUL-terminated UTF-8 strings (or null) that outlive this call.
1470        let read = |p: *const c_char| {
1471            (!p.is_null()).then(|| {
1472                unsafe { std::ffi::CStr::from_ptr(p) }
1473                    .to_string_lossy()
1474                    .into_owned()
1475            })
1476        };
1477        let key = read(name).unwrap_or_default();
1478        let node = NodeId(id);
1479        let phase = key_phase(phase);
1480        if phase != day_spec::KeyPhase::Up && !day_spec::keys::handled(node) {
1481            return 0;
1482        }
1483        let modifiers = modifiers as u8;
1484        let event = match read(text) {
1485            Some(text) => day_spec::KeyEvent::typed_by(key, text, modifiers),
1486            None => day_spec::KeyEvent::named(key, modifiers),
1487        };
1488        emit(node, Event::Key(event.with_phase(phase)));
1489        1
1490    })
1491}
1492
1493/// Escape over a presented sheet cover (docs/cover.md "Modal sheet"): the topmost cover hears
1494/// it as its back request, whichever sheet's shortcut fired.
1495extern "C" fn on_cover_escape(id: u64) {
1496    ffi_guard::contain((), || {
1497        let node = COVERS
1498            .with(|c| c.borrow().last().map(|(_, node)| *node))
1499            .unwrap_or(NodeId(id));
1500        emit(
1501            node,
1502            Event::NavBack {
1503                already_popped: false,
1504            },
1505        );
1506    });
1507}
1508
1509/// Focus callback from the C++ event filter (docs/focus.md).
1510/// kind: 0 = lost, 1 = gained, 2 = submitted (line-edit return key).
1511extern "C" fn on_focus(id: u64, kind: c_int) {
1512    ffi_guard::contain((), || {
1513        let ev = match kind {
1514            2 => Event::Submitted,
1515            k => Event::FocusChanged(k != 0),
1516        };
1517        emit(NodeId(id), ev);
1518    });
1519}
1520
1521/// Gesture callback from the C++ event filter. phase: 0 tap; 1..=3 drag began/changed/ended;
1522/// 4..=6 pinch began/changed/ended (tx = cumulative scale); 7..=9 pan (tx/ty = delta);
1523/// 10..=12 hover; 13..=15 rotate began/changed/ended (tx = cumulative radians, clockwise);
1524/// 16 long press; 17 double tap; 18 press in; 19 press out.
1525extern "C" fn on_gesture(id: u64, phase: c_int, x: f64, y: f64, tx: f64, ty: f64) {
1526    use day_spec::{DragPhase, Point};
1527    ffi_guard::contain((), || {
1528        let at = Point::new(x, y);
1529        let seq_phase = |p: c_int| match p {
1530            0 => DragPhase::Began,
1531            2 => DragPhase::Ended,
1532            _ => DragPhase::Changed,
1533        };
1534        let ev = match phase {
1535            0 => Event::Tap(at),
1536            1 => Event::Drag {
1537                phase: DragPhase::Began,
1538                location: at,
1539                translation: Point::ZERO,
1540            },
1541            3 => Event::Drag {
1542                phase: DragPhase::Ended,
1543                location: at,
1544                translation: Point::new(tx, ty),
1545            },
1546            4..=6 => Event::Pinch {
1547                phase: seq_phase(phase - 4),
1548                scale: tx,
1549                location: at,
1550            },
1551            7..=9 => Event::Pan {
1552                phase: seq_phase(phase - 7),
1553                delta: Point::new(tx, ty),
1554                location: at,
1555            },
1556            10..=12 => Event::Hover {
1557                phase: seq_phase(phase - 10),
1558                location: at,
1559            },
1560            13..=15 => Event::Rotate {
1561                phase: seq_phase(phase - 13),
1562                rotation: tx,
1563                location: at,
1564            },
1565            16 => Event::LongPress(at),
1566            17 => Event::DoubleTap(at),
1567            18 | 19 => Event::Press {
1568                pressed: phase == 18,
1569                location: at,
1570            },
1571            _ => Event::Drag {
1572                phase: DragPhase::Changed,
1573                location: at,
1574                translation: Point::new(tx, ty),
1575            },
1576        };
1577        emit(NodeId(id), ev);
1578    });
1579}
1580
1581/// One contact list from a touches recognizer (docs/gestures.md "Touches"): six numbers per
1582/// contact, as `contacts` decodes them.
1583extern "C" fn on_touches(id: u64, data: *const c_double, count: c_int) {
1584    ffi_guard::contain((), || {
1585        let len = usize::try_from(count).unwrap_or(0) * 6;
1586        if data.is_null() || len == 0 {
1587            return;
1588        }
1589        // SAFETY: the shim passes `count` contacts of six doubles each, valid for the call.
1590        let numbers = unsafe { std::slice::from_raw_parts(data, len) };
1591        emit(NodeId(id), Event::Touches(contacts(numbers)));
1592    });
1593}
1594
1595/// Decode the shim's contact numbers: id, phase (0 began, 1 moved, 2 stationary, 3 ended,
1596/// 4 cancelled), x, y, pressure, kind (0 touch, 1 mouse, 2 stylus) per contact.
1597fn contacts(numbers: &[f64]) -> Vec<day_spec::Touch> {
1598    use day_spec::{Point, Touch, TouchPhase};
1599    numbers
1600        .as_chunks::<6>()
1601        .0
1602        .iter()
1603        .map(|c| {
1604            let phase = match c[1] as i32 {
1605                0 => TouchPhase::Began,
1606                2 => TouchPhase::Stationary,
1607                3 => TouchPhase::Ended,
1608                4 => TouchPhase::Cancelled,
1609                _ => TouchPhase::Moved,
1610            };
1611            Touch::new(c[0] as u64, phase, Point::new(c[2], c[3]))
1612                .with_pressure(c[4])
1613                .with_kind(pointer_kind(c[5] as c_int))
1614        })
1615        .collect()
1616}
1617
1618/// The shim's device code (0 touch, 1 mouse, 2 stylus) as a [`day_spec::PointerKind`].
1619fn pointer_kind(code: c_int) -> day_spec::PointerKind {
1620    match code {
1621        0 => day_spec::PointerKind::Touch,
1622        2 => day_spec::PointerKind::Stylus,
1623        _ => day_spec::PointerKind::Mouse,
1624    }
1625}
1626
1627/// The kind of device behind the latest pointer input changed (docs/gestures.md "Input
1628/// kind"); the shim reports only a change.
1629extern "C" fn on_pointer_kind(code: c_int) {
1630    ffi_guard::contain((), || {
1631        emit(
1632            day_spec::WINDOW_NODE,
1633            Event::PointerKindChanged(pointer_kind(code)),
1634        );
1635    });
1636}
1637
1638/// A realized container, label, canvas, image or divider: a view that takes no pointer input
1639/// until a recognizer, a menu, a drag, a drop or focus is attached, so a press on it reaches
1640/// whatever is behind it (docs/gestures.md "Pass-through").
1641fn passive(w: *mut c_void) -> QtHandle {
1642    // SAFETY: `w` is the widget the shim just made; the shim only sets a property on it.
1643    unsafe { ffi::day_qt_set_passive(w) };
1644    QtHandle(w)
1645}
1646
1647fn slider_ticks(value: f64, min: f64, max: f64) -> c_int {
1648    if max <= min {
1649        return 0;
1650    }
1651    (((value - min) / (max - min)) * 1000.0).round() as c_int
1652}
1653
1654/// A `0.0..=1.0` fraction as `QProgressBar` ticks (0..1000), clamped.
1655fn progress_ticks(fraction: f64) -> c_int {
1656    (fraction.clamp(0.0, 1.0) * 1000.0).round() as c_int
1657}
1658
1659/// Renderers registered by external Day Piece crates (§8.2).
1660#[distributed_slice]
1661pub static RENDERERS: [fn() -> Renderer<Qt>];
1662
1663/// A live secondary window (docs/windows.md): the day root node id, the `DayWindow`, and
1664/// its inner content widget (the adopted handle).
1665struct QtWin {
1666    #[cfg(target_os = "macos")]
1667    id: NodeId,
1668    #[cfg(target_os = "macos")]
1669    tab_group: Option<String>,
1670    win: *mut c_void,
1671    content: *mut c_void,
1672}
1673
1674pub struct Qt {
1675    registry: Registry<Qt>,
1676    window: *mut c_void,
1677    secondary: Vec<QtWin>,
1678    /// Each window's toolbar as the shim holds it (docs/toolbars.md), by window pointer.
1679    toolbars: std::collections::HashMap<usize, day_spec::ToolbarMirror>,
1680    /// The status items shown (docs/status-item.md): each spec and its `QSystemTrayIcon`.
1681    trays: Vec<(day_spec::StatusItemSpec, *mut c_void)>,
1682}
1683
1684impl Qt {
1685    #[must_use]
1686    pub fn new() -> Self {
1687        register_resources();
1688        let mut registry = Registry::default();
1689        for f in RENDERERS {
1690            registry.register(f());
1691        }
1692        Qt {
1693            registry,
1694            window: std::ptr::null_mut(),
1695            secondary: Vec::new(),
1696            toolbars: std::collections::HashMap::new(),
1697            trays: Vec::new(),
1698        }
1699    }
1700
1701    /// The `DayWindow` whose content container is `host`: a secondary window by its content, or
1702    /// the primary, which `ready` handed out as the `DayWindow` itself.
1703    fn qt_window_for(&self, host: &QtHandle) -> Option<*mut c_void> {
1704        match self.secondary.iter().find(|w| w.content == host.0) {
1705            Some(w) => Some(w.win),
1706            None if !self.window.is_null() && host.0 == self.window => Some(self.window),
1707            None => None,
1708        }
1709    }
1710
1711    /// The dialog parent (docs/windows.md): the ACTIVE Day window at present time,
1712    /// primary as the fallback.
1713    fn present_parent(&self) -> *mut c_void {
1714        self.secondary
1715            .iter()
1716            .find(|w| unsafe { ffi::day_qt_window_is_active(w.win) } != 0)
1717            .map_or(self.window, |w| w.win)
1718    }
1719}
1720
1721/// Register the app's native Qt resource blob (§18.3) if `day build` produced one. Once registered,
1722/// data reads go through `QResource::data` (zero-copy from the mmapped blob) via [`open_resource`],
1723/// and images load with `QPixmap(":/day/images/<name>")`.
1724fn register_resources() {
1725    let Ok(path) = std::env::var("DAY_QRESOURCE") else {
1726        return;
1727    };
1728    unsafe { ffi::day_qt_register_resource(cstr(&path).as_ptr()) };
1729    day_spec::resource::set_resource_opener(open_resource);
1730}
1731
1732/// `resource("name")` → the `:/day/assets/<name>` Qt resource, borrowed zero-copy from the
1733/// registered blob (valid for the app lifetime, so an empty guard suffices).
1734fn open_resource(name: &str) -> Option<day_spec::resource::Resource> {
1735    let respath = format!(":/day/assets/{name}");
1736    let mut len: usize = 0;
1737    let ptr = unsafe { ffi::day_qt_resource_data(cstr(&respath).as_ptr(), &raw mut len) };
1738    if ptr.is_null() {
1739        return None;
1740    }
1741    Some(unsafe { day_spec::resource::Resource::from_raw(ptr.cast::<u8>(), len, Box::new(())) })
1742}
1743
1744impl Default for Qt {
1745    fn default() -> Self {
1746        Self::new()
1747    }
1748}
1749
1750fn content_of(parent: &QtHandle) -> *mut c_void {
1751    // Scroll areas expose an inner content widget; the shim returns null for non-scrolls.
1752    let inner = unsafe { ffi::day_qt_scroll_content(parent.0) };
1753    if inner.is_null() { parent.0 } else { inner }
1754}
1755
1756/// Point size + the style's inherent weight for a logical [`Font`] (Qt has no semantic text styles;
1757/// we approximate the platform typographic scale, matching Apple's text-style sizes for consistency).
1758/// Public for standalone pieces (docs/extending.md), which have to resolve the same scale.
1759#[must_use]
1760#[expect(
1761    clippy::match_same_arms,
1762    reason = "one row per text style, in the order of the type scale it approximates"
1763)]
1764pub fn qt_style(f: Font) -> (f64, day_spec::FontWeight) {
1765    use day_spec::FontWeight::{Regular, Semibold};
1766    match f {
1767        Font::LargeTitle => (26.0, Regular),
1768        Font::Title => (22.0, Regular),
1769        Font::Title2 => (17.0, Regular),
1770        Font::Title3 => (15.0, Regular),
1771        Font::Headline => (13.0, Semibold),
1772        Font::Subheadline => (11.0, Regular),
1773        Font::Body => (13.0, Regular),
1774        Font::Callout => (12.0, Regular),
1775        Font::Footnote => (10.0, Regular),
1776        Font::Caption => (10.0, Regular),
1777        Font::Caption2 => (10.0, Regular),
1778        Font::System(pt) | Font::Custom(_, pt) => (pt, Regular),
1779    }
1780}
1781
1782/// Render a label's runs as Qt rich text (docs/text-runs.md).
1783///
1784/// Qt's rich text is an HTML subset, so this goes through the SHARED serializer — the escaping
1785/// is the risk, and it is the same risk GTK has, so it is written and tested once in day-spec.
1786fn set_label_runs(w: *mut c_void, text: &str, runs: &[day_spec::TextRun]) {
1787    if runs.is_empty() {
1788        // The plain setter also puts the format back to PlainText, so a label that loses its
1789        // runs stops parsing markup.
1790        unsafe { ffi::day_qt_label_set_text(w, cstr(text).as_ptr()) };
1791        return;
1792    }
1793    let base_pt = LABEL_PT
1794        .with(|t| t.get(w as usize))
1795        .unwrap_or_else(|| qt_style(Font::Body).0);
1796    let html = qt_label_markup(text, runs, base_pt);
1797    unsafe { ffi::day_qt_label_set_rich_text(w, cstr(&html).as_ptr()) };
1798}
1799
1800/// Qt's spelling of a decoration style in its rich-text CSS (`text-underline-style`). Qt has no
1801/// double rule, so `Double` draws a single one.
1802fn qt_underline_style(style: day_spec::DecorationStyle) -> &'static str {
1803    match style {
1804        day_spec::DecorationStyle::Single | day_spec::DecorationStyle::Double => "solid",
1805        day_spec::DecorationStyle::Dotted => "dotted",
1806        day_spec::DecorationStyle::Wavy => "wave",
1807    }
1808}
1809
1810/// A label's runs as Qt rich text: the shared serializer's markup, with what Qt's rich text
1811/// takes beyond it.
1812///
1813/// The shared markup underlines with `<u>`, which Qt reads as a single line and which overrides
1814/// any style around it. A run whose underline has a style of its own is therefore serialized
1815/// without the underline, inside a span carrying Qt's `text-underline-style` and
1816/// `text-decoration-color` (both parsed by Qt's rich text into the `QTextCharFormat` underline
1817/// style and color). Qt strikes through in one style and the text color, so a strikethrough is
1818/// written plain (`<s>`) rather than leaving its color to recolor an underline. A run's small
1819/// capitals are dropped (see below); the label's own `small_caps` is the face's `smcp`. Every other run is the shared markup verbatim:
1820/// serializing one run at a time writes exactly what one call over the whole text writes.
1821fn qt_label_markup(text: &str, runs: &[day_spec::TextRun], base_pt: f64) -> String {
1822    use std::fmt::Write as _;
1823    let dialect = day_spec::MarkupDialect::QtHtml;
1824    let mut out = String::with_capacity(text.len() + runs.len() * 32);
1825    let mut at = 0usize;
1826    for r in runs {
1827        let Some(styled) = text.get(r.range.clone()) else {
1828            continue;
1829        };
1830        if r.range.start > at
1831            && let Some(plain) = text.get(at..r.range.start)
1832        {
1833            out.push_str(&day_spec::runs_to_markup(plain, &[], dialect, base_pt));
1834        }
1835        let mut inner = r.clone();
1836        inner.range = 0..styled.len();
1837        // Qt strikes through in one style and the text color only.
1838        if inner.strikethrough.is_some() {
1839            inner.strikethrough = Some(day_spec::Decoration::SINGLE);
1840        }
1841        // Qt's rich text cannot ask a face for `smcp`: its `font-variant:small-caps` draws
1842        // scaled capitals, which Day never synthesizes, and measures them inconsistently (a
1843        // label laid out at its own natural width wrapped its last word on Linux). The run
1844        // keeps its ordinary lowercase.
1845        inner.font.small_caps = false;
1846        match r
1847            .underline
1848            .filter(|d| d.style != day_spec::DecorationStyle::Single)
1849        {
1850            Some(d) => {
1851                inner.underline = None;
1852                let _ = write!(
1853                    out,
1854                    "<span style=\"text-underline-style:{};",
1855                    qt_underline_style(d.style)
1856                );
1857                if let Some(c) = d.color {
1858                    let _ = write!(out, "text-decoration-color:{};", css_hex(c.resolved()));
1859                }
1860                out.push_str("\">");
1861                out.push_str(&day_spec::runs_to_markup(
1862                    styled,
1863                    &[inner],
1864                    dialect,
1865                    base_pt,
1866                ));
1867                out.push_str("</span>");
1868            }
1869            None => {
1870                out.push_str(&day_spec::runs_to_markup(
1871                    styled,
1872                    &[inner],
1873                    dialect,
1874                    base_pt,
1875                ));
1876            }
1877        }
1878        at = r.range.end;
1879    }
1880    if let Some(tail) = text.get(at..) {
1881        out.push_str(&day_spec::runs_to_markup(tail, &[], dialect, base_pt));
1882    }
1883    out
1884}
1885
1886/// `#rrggbb` for a color in Qt's rich-text CSS.
1887fn css_hex(c: day_spec::Color) -> String {
1888    let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u8;
1889    format!("#{:02x}{:02x}{:02x}", byte(c.r), byte(c.g), byte(c.b))
1890}
1891
1892/// Remember a label's resolved point size for [`set_label_runs`].
1893fn remember_label_pt(w: *mut c_void, f: day_spec::FontSpec) {
1894    LABEL_PT.with(|t| t.insert(w as usize, f.resolved_points(qt_style(f.style).0)));
1895}
1896
1897/// Apply a `Font::Custom` family on top of `day_qt_label_set_font` (which set size/weight/italic).
1898/// The family was registered with the `QFontDatabase` in `run()`; an unknown name falls back to the
1899/// default family inside Qt.
1900unsafe fn apply_custom_family(w: *mut c_void, spec: day_spec::FontSpec) {
1901    if let Font::Custom(family, _) = spec.style {
1902        unsafe { ffi::day_qt_label_set_font_family(w, cstr(family).as_ptr()) };
1903    }
1904}
1905
1906/// Day weight → `QFont::Weight` numeric value (Thin=100 … Black=900).
1907fn qt_weight(w: day_spec::FontWeight) -> c_int {
1908    use day_spec::FontWeight as W;
1909    match w {
1910        W::Thin => 100,
1911        W::UltraLight => 200,
1912        W::Light => 300,
1913        W::Regular => 400,
1914        W::Medium => 500,
1915        W::Semibold => 600,
1916        W::Bold => 700,
1917        W::Heavy => 800,
1918        W::Black => 900,
1919    }
1920}
1921
1922/// A label's base font as the C++ shim takes it.
1923struct FontParams {
1924    /// The resolved size: the style's (or the explicit) points times `FontSpec::scale`.
1925    pt: f64,
1926    weight: c_int,
1927    italic: c_int,
1928    tabular: c_int,
1929    small_caps: c_int,
1930    oldstyle: c_int,
1931}
1932
1933fn font_params(spec: day_spec::FontSpec) -> FontParams {
1934    let (pt, inherent) = qt_style(spec.style);
1935    FontParams {
1936        pt: spec.resolved_points(pt),
1937        weight: qt_weight(spec.weight.unwrap_or(inherent)),
1938        italic: c_int::from(spec.italic),
1939        tabular: c_int::from(spec.tabular),
1940        small_caps: c_int::from(spec.small_caps),
1941        oldstyle: c_int::from(spec.oldstyle_figures),
1942    }
1943}
1944
1945/// Set a label's base font (size, weight, italic and the font features).
1946fn apply_label_font(w: *mut c_void, spec: day_spec::FontSpec) {
1947    let f = font_params(spec);
1948    // SAFETY: `w` is a live label widget the caller holds; the shim only reads its font.
1949    unsafe {
1950        ffi::day_qt_label_set_font(
1951            w,
1952            f.pt,
1953            f.weight,
1954            f.italic,
1955            f.tabular,
1956            f.small_caps,
1957            f.oldstyle,
1958        );
1959    }
1960}
1961
1962/// Apply the paragraph attributes (docs/text.md) at realize and on `LabelPatch::Paragraph`.
1963fn apply_paragraph(w: *mut c_void, p: &day_spec::props::LabelParagraph) {
1964    let truncation = match p.truncation {
1965        day_spec::props::Truncation::Tail => 0,
1966        day_spec::props::Truncation::Head => 1,
1967        day_spec::props::Truncation::Middle => 2,
1968    };
1969    let max_lines = c_int::try_from(p.max_lines).unwrap_or(c_int::MAX);
1970    // SAFETY: `w` is a live label widget; the shim ignores any other widget.
1971    unsafe {
1972        ffi::day_qt_label_set_paragraph(w, max_lines, truncation, p.letter_spacing, p.line_height);
1973    };
1974}
1975
1976/// A label's `TextAlign` as the shim's code.
1977fn label_align(a: day_spec::props::TextAlign) -> c_int {
1978    match a {
1979        day_spec::props::TextAlign::Leading => 0,
1980        day_spec::props::TextAlign::Center => 1,
1981        day_spec::props::TextAlign::Trailing => 2,
1982        day_spec::props::TextAlign::Justified => 3,
1983    }
1984}
1985
1986// ---------------------------------------------------------------------------
1987// Navigation (docs/navigation.md): QSplitter host, sidebar + detail panes. Day sizes
1988// page content from the pane sizes reported here via FrameChanged.
1989// ---------------------------------------------------------------------------
1990
1991struct NavState {
1992    sidebar_pane: *mut std::os::raw::c_void,
1993    detail_pane: *mut std::os::raw::c_void,
1994    /// (page, node id) in insertion order. The sidebar page — when the host has one — is
1995    /// always first; what changes with the presentation is its PARENT, not its position.
1996    pages: Vec<(QtHandle, NodeId)>,
1997    /// The host's sidebar page, once it has one (docs/size-classes.md).
1998    sidebar_page: Option<QtHandle>,
1999    /// Sidebar+detail split (nav host Sidebar) vs. a pure push/pop stack (`nav_stack`).
2000    split: bool,
2001    /// Whether the sidebar pane is showing. Tracked rather than read back because the shim
2002    /// exposes `day_qt_set_visible` and no getter — what the sidebar toggle flips.
2003    sidebar_shown: bool,
2004    /// The content-list pane (docs/navigation.md), splitter pane 1. It exists on every host
2005    /// and is hidden on one that declared no content list; `list_width` is `Some` only where
2006    /// the app asked for the pane (`NavProps::list_width`). The pane PERSISTS through every
2007    /// presentation (`Cap::NavContentList` = Native): a narrow window collapses the sidebar
2008    /// into the stack and keeps the list beside the detail, as a narrow Mail.app does.
2009    list_pane: *mut std::os::raw::c_void,
2010    list_width: Option<f64>,
2011    /// The `Pane::List` page, once it has one — sized by its pane, never a member of the
2012    /// detail stack.
2013    list_page: Option<QtHandle>,
2014    /// Whether the pane is showing (`NavProps::list_visible`, then `NavPatch::ListVisible`).
2015    list_shown: bool,
2016    /// Whether the pane has been given the app's requested width yet. A pane hidden since
2017    /// construction keeps the constructor's placeholder size, so the first reveal places it.
2018    list_positioned: bool,
2019    /// Stack presentation: title per level (index 0 = root) for the back header — desktop has
2020    /// no system back affordance, so the header gives a pushed page its way out.
2021    titles: Vec<String>,
2022}
2023
2024/// Show/hide the sidebar of the navigation host `host` — what the sidebar affordance a
2025/// nav host contributes for itself drives (`day_spec::SIDEBAR_TOGGLE_ID`, docs/toolbars.md).
2026/// Per host, so a second window's button toggles that window's own pane. `false` when the
2027/// host is not split (nothing to toggle).
2028pub(crate) fn toggle_sidebar(host: *mut std::os::raw::c_void) -> bool {
2029    // The pane flips outside the borrow: the sibling panes' resize reports read `NAV_STATE`.
2030    let flip = NAV_STATE.with(|m| {
2031        let mut m = m.borrow_mut();
2032        let st = m.get_mut(&(host as usize))?;
2033        if !st.split {
2034            return None;
2035        }
2036        st.sidebar_shown = !st.sidebar_shown;
2037        Some((st.sidebar_pane, st.sidebar_shown))
2038    });
2039    match flip {
2040        Some((pane, shown)) => {
2041            unsafe { ffi::day_qt_set_visible(pane, i32::from(shown)) };
2042            true
2043        }
2044        None => false,
2045    }
2046}
2047
2048/// The stack-nav header's back button: a day-initiated pop — the host's handler writes it
2049/// into the path signal, which reconciles the pop.
2050extern "C" fn nav_back_clicked(id: u64) {
2051    ffi_guard::contain((), || {
2052        emit(
2053            NodeId(id),
2054            Event::NavBack {
2055                already_popped: false,
2056            },
2057        );
2058    });
2059}
2060
2061/// Sync the back header to the stack depth (visible while a pushed page shows), then
2062/// re-report page sizes — the pages host shrinks/grows by the header height.
2063fn nav_sync_header(host: *mut std::os::raw::c_void) {
2064    let (visible, title) = NAV_STATE.with(|m| {
2065        let m = m.borrow();
2066        let Some(state) = m.get(&(host as usize)) else {
2067            return (false, String::new());
2068        };
2069        (
2070            !state.split && state.pages.len() >= 2,
2071            state.titles.last().cloned().unwrap_or_default(),
2072        )
2073    });
2074    unsafe {
2075        ffi::day_qt_nav_header_update(host, c_int::from(visible), cstr(&title).as_ptr());
2076    }
2077    nav_sync_panes(host);
2078}
2079
2080/// Is this page the host's sidebar pane?
2081fn is_sidebar_page(page: *mut std::os::raw::c_void) -> bool {
2082    PAGE_PANE
2083        .with(|m| m.borrow().get(&(page as usize)).copied() == Some(day_spec::props::Pane::Sidebar))
2084}
2085
2086/// Is this page the host's content-list pane? Never part of the detail stack, at any
2087/// presentation (docs/navigation.md).
2088fn is_list_page(page: *mut std::os::raw::c_void) -> bool {
2089    PAGE_PANE
2090        .with(|m| m.borrow().get(&(page as usize)).copied() == Some(day_spec::props::Pane::List))
2091}
2092
2093/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
2094/// chrome changes but the pages do not.
2095///
2096/// Both presentations are the same `QSplitter` with the same back header already installed, so
2097/// the morph is: show or hide the sidebar pane, re-parent the sidebar PAGE between the two panes,
2098/// and let the header follow the new depth. `day_qt_add_child` re-parents a widget rather than
2099/// rebuilding it, so each page keeps its children and its scroll state.
2100fn nav_present(host: *mut std::os::raw::c_void, split: bool) {
2101    let Some((sidebar_page, sidebar_pane, detail_pane, was_split)) = NAV_STATE.with(|m| {
2102        let st = m.borrow();
2103        let s = st.get(&(host as usize))?;
2104        Some((s.sidebar_page, s.sidebar_pane, s.detail_pane, s.split))
2105    }) else {
2106        return;
2107    };
2108    if was_split == split {
2109        return;
2110    }
2111    unsafe {
2112        ffi::day_qt_set_visible(sidebar_pane, i32::from(split));
2113        if let Some(page) = sidebar_page {
2114            // Its own pane when split, the stack's root page when not.
2115            ffi::day_qt_add_child(if split { sidebar_pane } else { detail_pane }, page.0);
2116            ffi::day_qt_set_visible(page.0, 1);
2117        }
2118    }
2119    NAV_STATE.with(|m| {
2120        let mut m = m.borrow_mut();
2121        if let Some(s) = m.get_mut(&(host as usize)) {
2122            s.split = split;
2123            s.sidebar_shown = split;
2124            // Only the top detail page shows; the sidebar page, when split, sits outside that,
2125            // and the list page always does.
2126            let detail: Vec<QtHandle> = s
2127                .pages
2128                .iter()
2129                .filter(|(p, _)| !(split && is_sidebar_page(p.0) || is_list_page(p.0)))
2130                .map(|(p, _)| *p)
2131                .collect();
2132            let last = detail.len().saturating_sub(1);
2133            for (i, page) in detail.iter().enumerate() {
2134                unsafe { ffi::day_qt_set_visible(page.0, i32::from(i == last)) };
2135            }
2136        }
2137    });
2138    // Deferred one turn, like the pop path: hiding a QSplitter pane does not resize its sibling
2139    // until Qt runs its own layout pass, so reading the pane sizes now would report the old
2140    // detail width and leave the page laid out for a window that still had a sidebar.
2141    let host_addr = host as usize;
2142    <Qt as Platform>::post(Box::new(move || {
2143        nav_sync_header(host_addr as *mut std::os::raw::c_void);
2144    }));
2145}
2146
2147/// Report both pane sizes so `NavLayout` re-lays page content (enqueue-only, §8.3).
2148fn nav_sync_panes(host: *mut std::os::raw::c_void) {
2149    let reports: Vec<(NodeId, Size)> = NAV_STATE.with(|m| {
2150        let m = m.borrow();
2151        let Some(state) = m.get(&(host as usize)) else {
2152            return Vec::new();
2153        };
2154        let (mut sw, mut sh, mut lw, mut lh, mut dw, mut dh) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
2155        unsafe {
2156            ffi::day_qt_widget_size(state.sidebar_pane, &raw mut sw, &raw mut sh);
2157            ffi::day_qt_widget_size(state.list_pane, &raw mut lw, &raw mut lh);
2158            ffi::day_qt_widget_size(state.detail_pane, &raw mut dw, &raw mut dh);
2159        }
2160        if sh <= 0.0 && dh <= 0.0 {
2161            return Vec::new();
2162        }
2163        state
2164            .pages
2165            .iter()
2166            .map(|(page, id)| {
2167                // A page in the sidebar pane is sized by it, the list page by its pane;
2168                // everything else fills the detail.
2169                let size = if state.split && is_sidebar_page(page.0) {
2170                    Size::new(sw, sh)
2171                } else if is_list_page(page.0) {
2172                    Size::new(lw, lh)
2173                } else {
2174                    Size::new(dw, dh)
2175                };
2176                (*id, size)
2177            })
2178            .collect()
2179    });
2180    for (id, size) in reports {
2181        emit(id, Event::FrameChanged(size));
2182    }
2183}
2184
2185extern "C" fn nav_splitter_moved(host: *mut std::os::raw::c_void) {
2186    ffi_guard::contain((), || {
2187        nav_sync_panes(host);
2188        // The window toolbar's columns follow the panes (docs/toolbars.md).
2189        unsafe { ffi::day_qt_toolbar_sync_columns(host) };
2190    });
2191}
2192
2193// ---------------------------------------------------------------------------
2194// Inspector (docs/inspector.md): the nav QSplitter mirrored — content pane leading with the
2195// stretch, a show/hidable panel pane trailing at its preferred width, divider draggable.
2196// ---------------------------------------------------------------------------
2197
2198struct InspectorState {
2199    content_pane: *mut std::os::raw::c_void,
2200    panel_pane: *mut std::os::raw::c_void,
2201    /// `(pane NodeId, is-panel)` in attach order, for frame reports.
2202    panes: Vec<(NodeId, bool)>,
2203    width: f64,
2204    shown: bool,
2205}
2206
2207/// Report both pane sizes so `InspectorLayout` re-lays content (`nav_sync_panes`'s
2208/// counterpart). The panel reports its preferred width while hidden, so a reveal re-lays
2209/// nothing.
2210fn inspector_sync_panes(host: *mut std::os::raw::c_void) {
2211    let reports: Vec<(NodeId, Size)> = INSPECTOR_STATE.with(|m| {
2212        let m = m.borrow();
2213        let Some(state) = m.get(&(host as usize)) else {
2214            return Vec::new();
2215        };
2216        let (mut cw, mut ch, mut pw, mut ph) = (0.0, 0.0, 0.0, 0.0);
2217        unsafe {
2218            ffi::day_qt_widget_size(state.content_pane, &raw mut cw, &raw mut ch);
2219            ffi::day_qt_widget_size(state.panel_pane, &raw mut pw, &raw mut ph);
2220        }
2221        let _ = ph;
2222        if ch <= 0.0 {
2223            return Vec::new();
2224        }
2225        state
2226            .panes
2227            .iter()
2228            .map(|(id, panel)| {
2229                let size = if *panel {
2230                    let w = if state.shown && pw > 0.0 {
2231                        pw
2232                    } else {
2233                        state.width
2234                    };
2235                    Size::new(w, ch)
2236                } else {
2237                    Size::new(cw, ch)
2238                };
2239                (*id, size)
2240            })
2241            .collect()
2242    });
2243    for (id, size) in reports {
2244        emit(id, Event::FrameChanged(size));
2245    }
2246}
2247
2248extern "C" fn inspector_splitter_moved(host: *mut std::os::raw::c_void) {
2249    ffi_guard::contain((), || inspector_sync_panes(host));
2250}
2251
2252// ---------------------------------------------------------------------------
2253// Split (docs/split.md): a QSplitter of two plain panes, either orientation, the divider
2254// placed by the bound share and a drag reported back as the new share.
2255// ---------------------------------------------------------------------------
2256
2257struct SplitState {
2258    first_pane: *mut std::os::raw::c_void,
2259    second_pane: *mut std::os::raw::c_void,
2260    node: NodeId,
2261    /// `(pane NodeId, is-second)` in attach order, for frame reports.
2262    panes: Vec<(NodeId, bool)>,
2263    /// The first pane's share as last patched or reported.
2264    share: f64,
2265    min_pane: f64,
2266    /// The divider has been placed once; before that the splitter has no size to place it in.
2267    placed: bool,
2268    /// Day is moving the divider itself: the move that follows is not a report.
2269    suppress: bool,
2270}
2271
2272/// Report both pane sizes so `SplitLayout` re-lays content (`inspector_sync_panes`'s
2273/// counterpart).
2274fn split_sync_panes(host: *mut std::os::raw::c_void) {
2275    let reports: Vec<(NodeId, Size)> = SPLIT_STATE.with(|m| {
2276        let m = m.borrow();
2277        let Some(state) = m.get(&(host as usize)) else {
2278            return Vec::new();
2279        };
2280        let (mut aw, mut ah, mut bw, mut bh) = (0.0, 0.0, 0.0, 0.0);
2281        unsafe {
2282            ffi::day_qt_widget_size(state.first_pane, &raw mut aw, &raw mut ah);
2283            ffi::day_qt_widget_size(state.second_pane, &raw mut bw, &raw mut bh);
2284        }
2285        if aw <= 0.0 || ah <= 0.0 {
2286            return Vec::new();
2287        }
2288        state
2289            .panes
2290            .iter()
2291            .map(|(id, second)| {
2292                let size = if *second {
2293                    Size::new(bw, bh)
2294                } else {
2295                    Size::new(aw, ah)
2296                };
2297                (*id, size)
2298            })
2299            .collect()
2300    });
2301    for (id, size) in reports {
2302        emit(id, Event::FrameChanged(size));
2303    }
2304}
2305
2306/// A layout pass on the splitter: the first one with a size places the divider by the share;
2307/// every one re-lays the panes' content.
2308extern "C" fn split_resized(host: *mut std::os::raw::c_void) {
2309    ffi_guard::contain((), || {
2310        let place = SPLIT_STATE.with(|m| {
2311            let mut m = m.borrow_mut();
2312            let state = m.get_mut(&(host as usize))?;
2313            let (mut w, mut h) = (0.0, 0.0);
2314            unsafe { ffi::day_qt_widget_size(host, &raw mut w, &raw mut h) };
2315            if state.placed || w <= 0.0 || h <= 0.0 {
2316                return None;
2317            }
2318            state.placed = true;
2319            state.suppress = true;
2320            Some(state.share)
2321        });
2322        if let Some(share) = place {
2323            unsafe { ffi::day_qt_split_set_fraction(host, share) };
2324            SPLIT_STATE.with(|m| {
2325                if let Some(state) = m.borrow_mut().get_mut(&(host as usize)) {
2326                    state.suppress = false;
2327                }
2328            });
2329        }
2330        split_sync_panes(host);
2331    });
2332}
2333
2334/// The divider moved: a drag reports the new share; Day's own placement does not.
2335extern "C" fn split_moved(host: *mut std::os::raw::c_void) {
2336    ffi_guard::contain((), || {
2337        let share = unsafe { ffi::day_qt_split_fraction(host) }.clamp(0.0, 1.0);
2338        let report = SPLIT_STATE.with(|m| {
2339            let mut m = m.borrow_mut();
2340            let state = m.get_mut(&(host as usize))?;
2341            if state.suppress || !state.placed || (share - state.share).abs() <= 1e-4 {
2342                return None;
2343            }
2344            state.share = share;
2345            Some(state.node)
2346        });
2347        if let Some(node) = report {
2348            emit(node, Event::ValueChanged(share));
2349        }
2350        split_sync_panes(host);
2351    });
2352}
2353
2354// ---------------------------------------------------------------------------
2355// The navigation suite (docs/navigation.md): a QTabWidget host that owns its page widgets.
2356// ---------------------------------------------------------------------------
2357
2358/// The navigation suite (`NavPresentation::Tabs`): a `QTabWidget` whose bar IS the host's row list.
2359struct NavSuite {
2360    /// The host's own node — what the `QTabWidget`'s signal carries, so a click can find its suite
2361    /// even when a window holds more than one.
2362    host: NodeId,
2363    /// The nav menu's node. A tab click reports against it, exactly as a sidebar row click does,
2364    /// so the two are one event to everything above this backend. Zero until the menu arrives.
2365    menu_node: NodeId,
2366    /// Destination pages in bar order — index i IS the `Select(i)` index. The sidebar page is
2367    /// not in here; it is a hidden tab, because its rows became the bar.
2368    pages: Vec<(QtHandle, NodeId)>,
2369    /// The row labels and glyph names, once the menu has arrived.
2370    titles: Vec<String>,
2371    icons: Vec<Option<String>>,
2372    keys: Vec<String>,
2373}
2374
2375/// Put the rows on the bar, for as many tabs as currently exist.
2376///
2377/// Called from both sides, because either can arrive first: the pages are inserted as the tree is
2378/// built, and the rows come with the nav menu nested somewhere inside the sidebar page. Whichever
2379/// lands last completes the bar.
2380fn suite_apply_rows(host: *mut std::os::raw::c_void) {
2381    NAV_SUITES.with(|m| {
2382        let m = m.borrow();
2383        let Some(suite) = m.get(&(host as usize)) else {
2384            return;
2385        };
2386        for (i, title) in suite.titles.iter().enumerate() {
2387            // Row i is tab i: the sidebar page is parked under the widget, never a tab.
2388            if i >= suite.pages.len() {
2389                break;
2390            }
2391            let at = i as c_int;
2392            unsafe { ffi::day_qt_tabs_set_title(host, at, cstr(title).as_ptr()) };
2393            let icon = suite
2394                .icons
2395                .get(i)
2396                .and_then(|o| o.as_deref())
2397                .filter(|n| !n.is_empty())
2398                .map_or_default(icon_file_path);
2399            if !icon.is_empty() {
2400                unsafe { ffi::day_qt_tabs_set_icon(host, at, cstr(&icon).as_ptr()) };
2401            }
2402        }
2403    });
2404}
2405
2406/// Report each destination's content size so `NavLayout` re-lays it (enqueue-only, §8.3) — the
2407/// suite's counterpart of the list's own sizing, and for the same reason: `QTabWidget` owns page
2408/// geometry.
2409fn nav_suite_sync(host: *mut std::os::raw::c_void) {
2410    let reports: Vec<(NodeId, Size)> = NAV_SUITES.with(|m| {
2411        let m = m.borrow();
2412        let Some(suite) = m.get(&(host as usize)) else {
2413            return Vec::new();
2414        };
2415        let (mut w, mut h) = (0.0, 0.0);
2416        unsafe { ffi::day_qt_tabs_content_size(host, &raw mut w, &raw mut h) };
2417        if w <= 0.0 || h <= 0.0 {
2418            return Vec::new();
2419        }
2420        suite
2421            .pages
2422            .iter()
2423            .map(|(_, id)| (*id, Size::new(w, h)))
2424            .collect()
2425    });
2426    for (id, size) in reports {
2427        emit(id, Event::FrameChanged(size));
2428    }
2429}
2430
2431/// A realized nav menu's rows: `(node, titles, icon names)`.
2432type NavRow = (NodeId, Vec<String>, Vec<Option<String>>, Vec<String>);
2433
2434/// A tab click. Reported against the MENU, not the host, so one handler serves every presentation.
2435extern "C" fn nav_suite_changed(id: u64, index: c_int) {
2436    ffi_guard::contain((), || {
2437        let node = NAV_SUITES.with(|m| {
2438            m.borrow()
2439                .values()
2440                .find(|s| s.host.0 == id && s.menu_node.0 != 0)
2441                .map(|s| s.menu_node)
2442        });
2443        emit(
2444            node.unwrap_or(NodeId(id)),
2445            Event::SelectionChanged(i64::from(index)),
2446        );
2447    });
2448}
2449
2450extern "C" fn document_tab_event(id: u64, action: c_int, index: c_int, to: c_int) {
2451    ffi_guard::contain((), || {
2452        let key = NAV_SUITES
2453            .with(|m| {
2454                m.borrow()
2455                    .values()
2456                    .find(|s| s.host.0 == id)
2457                    .and_then(|s| s.keys.get(index.saturating_sub(1) as usize))
2458                    .cloned()
2459            })
2460            .unwrap_or_default();
2461        let tag = match action {
2462            0 => "day:tab-new",
2463            1 => "day:tab-close",
2464            _ => "day:tab-move",
2465        };
2466        emit(
2467            NodeId(id),
2468            Event::Custom {
2469                tag,
2470                num: f64::from((to - 1).max(0)),
2471                text: key,
2472            },
2473        );
2474    });
2475}
2476
2477/// Report each tab page's content size so `NavLayout` re-lays it (enqueue-only, §8.3).
2478extern "C" fn present_cb(req: u64, tag: c_int, index: i64, text: *const c_char) {
2479    ffi_guard::contain((), || {
2480        let text = if text.is_null() {
2481            String::new()
2482        } else {
2483            unsafe { CStr::from_ptr(text) }
2484                .to_string_lossy()
2485                .into_owned()
2486        };
2487        let result = day_spec::present::PresentResult::decode(tag, index, text);
2488        emit_window(Event::PresentResult { req, result });
2489    });
2490}
2491
2492fn emit_window(ev: Event) {
2493    let sink = SINK.with(|s| s.borrow().clone());
2494    if let Some(sink) = sink {
2495        sink(day_spec::WINDOW_NODE, ev);
2496    }
2497}
2498
2499// Secondary-window event trampolines (docs/windows.md): the shim keys them by day node id.
2500extern "C" fn win_resized(node: u64, w: c_int, h: c_int) {
2501    ffi_guard::contain((), || {
2502        emit(
2503            day_spec::NodeId(node),
2504            Event::WindowResized(Size::new(f64::from(w), f64::from(h))),
2505        );
2506    });
2507}
2508extern "C" fn win_closed(node: u64) {
2509    // Node 0 is the primary, which reports its close only while the app keeps running
2510    // (docs/windows.md "Keeping the app running").
2511    let target = if node == 0 {
2512        day_spec::WINDOW_NODE
2513    } else {
2514        day_spec::NodeId(node)
2515    };
2516    ffi_guard::contain((), || emit(target, Event::WindowClosed));
2517}
2518extern "C" fn win_focused(node: u64, active: c_int) {
2519    ffi_guard::contain((), || {
2520        emit(day_spec::NodeId(node), Event::WindowFocused(active != 0));
2521    });
2522}
2523
2524/// A window's display state changed (docs/windows.md "Window properties"). The shim dedupes
2525/// and keys it by node id, 0 standing for the primary window.
2526extern "C" fn win_state(node: u64, code: c_int) {
2527    ffi_guard::contain((), || {
2528        let state = day_spec::WindowState::from_code(code);
2529        log::debug!("qt: window state now {state:?}");
2530        let target = if node == 0 {
2531            day_spec::WINDOW_NODE
2532        } else {
2533            day_spec::NodeId(node)
2534        };
2535        emit(target, Event::WindowStateChanged(state));
2536    });
2537}
2538
2539extern "C" fn window_resized(w: c_int, h: c_int) {
2540    ffi_guard::contain((), || {
2541        let size = Size::new(f64::from(w), f64::from(h));
2542        LAST_WINDOW_SIZE.with(|c| c.set(size));
2543        emit(day_spec::WINDOW_NODE, Event::WindowResized(size));
2544        // Presented emulated covers track the content area (docs/cover.md: the frame is
2545        // native-owned while presented).
2546        COVERS.with(|c| {
2547            for (cover, node) in c.borrow().iter() {
2548                let (y, size) = cover_frame(*cover, size);
2549                unsafe {
2550                    ffi::day_qt_set_geometry(
2551                        *cover,
2552                        0,
2553                        y as c_int,
2554                        size.width as c_int,
2555                        size.height as c_int,
2556                    );
2557                };
2558                emit(*node, Event::FrameChanged(size));
2559            }
2560        });
2561    });
2562}
2563
2564/// A presented cover's place in a window content `area` large: the whole area, or the bottom
2565/// half for a half sheet (docs/cover.md). Answers the y offset and the cover's own size.
2566fn cover_frame(cover: *mut c_void, area: Size) -> (f64, Size) {
2567    if COVER_HALF.with(|s| s.borrow().contains(&(cover as usize))) {
2568        let h = (area.height * 0.5).floor();
2569        (area.height - h, Size::new(area.width, h))
2570    } else {
2571        (0.0, area)
2572    }
2573}
2574
2575extern "C" fn nav_menu_changed(id: u64, row: std::os::raw::c_int) {
2576    // -1 = cleared (programmatic unselect fires nothing thanks to blockSignals; a clear
2577    // reaching here means the widget emptied — ignore). Deferred: selecting a sidebar item
2578    // rebuilds the detail, which must not run inside the list's own event dispatch.
2579    ffi_guard::contain((), || {
2580        if row >= 0 {
2581            emit_deferred(NodeId(id), Event::SelectionChanged(i64::from(row)));
2582        }
2583    });
2584}
2585
2586extern "C" fn on_menu_action(id: u64) {
2587    ffi_guard::contain((), || emit_window(Event::MenuAction(id)));
2588}
2589
2590/// Resolve a bundled image NAME to a loadable file path (or "" if it doesn't resolve).
2591/// Used for per-row nav-menu icons, which the shim loads + tints to the palette text color.
2592fn icon_file_path(name: &str) -> String {
2593    // The staged glyph SVG first (docs/vectors.md): Qt's SVG icon engine renders it at the icon
2594    // size asked for, which keeps a nav row or tab glyph sharp at any scale. The raster cache is
2595    // the fallback for names that have no vector — ordinary bundled images.
2596    day_spec::resource::resolve_vector_svg(name)
2597        .or_else(|| day_spec::resource::resolve_image_file(name))
2598        .map_or_default(|p| p.to_string_lossy().into_owned())
2599}
2600
2601/// Build the nav list's per-row context menus (docs/menus.md) and hand them to the shim:
2602/// one `QMenu` per row with entries (null where a row has none), the same
2603/// [`build_qt_menu`] walk the piece decorator uses.
2604fn navlist_apply_row_menus(w: *mut c_void, menus: &[Vec<day_spec::MenuItem>]) {
2605    let ptrs: Vec<*mut c_void> = menus
2606        .iter()
2607        .map(|items| {
2608            if items.is_empty() {
2609                std::ptr::null_mut()
2610            } else {
2611                let m = unsafe { ffi::day_qt_menu_new() };
2612                build_qt_menu(m, items);
2613                m
2614            }
2615        })
2616        .collect();
2617    unsafe { ffi::day_qt_navlist_set_row_menus(w, ptrs.as_ptr(), ptrs.len() as i32) };
2618}
2619
2620/// The nav menu's section headings as a U+001F-joined list parallel to its rows (empty entry =
2621/// the row continues the current group), with how many headings there are.
2622fn nav_sections_joined(sections: &[Option<String>]) -> (String, usize) {
2623    let headings = sections.iter().filter(|s| s.is_some()).count();
2624    let joined = sections
2625        .iter()
2626        .map(|s| s.as_deref().unwrap_or_default())
2627        .collect::<Vec<_>>()
2628        .join("\u{1f}");
2629    (joined, headings)
2630}
2631
2632/// Per-row nav icon tints as a U+001F-joined list of "#rrggbb" entries (empty entry = no
2633/// row tint, the shim falls back to the palette text color), parallel to the icon list
2634/// (docs/vectors.md).
2635/// A color as the `"#aarrggbb"` the shim's `QColor` parses. The alpha is kept: the shim's
2636/// `SourceIn` fill multiplies it into the glyph's own coverage, as every other toolkit's tint does.
2637fn hex_argb(c: day_spec::Color) -> String {
2638    format!(
2639        "#{:02x}{:02x}{:02x}{:02x}",
2640        (c.a * 255.0).round() as u8,
2641        (c.r * 255.0) as u8,
2642        (c.g * 255.0) as u8,
2643        (c.b * 255.0) as u8
2644    )
2645}
2646
2647/// The image shim's tint channel (docs/vectors.md): a `#aarrggbb`, `currentColor` for a
2648/// template glyph that follows the palette, or empty for the authored colors.
2649fn image_tint(tint: Option<day_spec::Color>, template: bool) -> String {
2650    match tint {
2651        Some(c) => hex_argb(c),
2652        None if template => "currentColor".to_owned(),
2653        None => String::new(),
2654    }
2655}
2656
2657/// Whether a container asks for what only the painted surface gives (docs/surfaces.md): a
2658/// gradient, a border, a shadow, or rounding on some corners only. A plain color with all four
2659/// corners rounded stays on the stylesheet path it has always taken.
2660fn is_styled_surface(p: &ContainerProps) -> bool {
2661    matches!(
2662        p.fill,
2663        Some(day_spec::Paint::Linear(_) | day_spec::Paint::Radial(_) | day_spec::Paint::Conic(_))
2664    ) || p.border.is_some()
2665        || p.shadow.is_some()
2666        || (p.corner_radius > 0.0 && p.corners != day_spec::Corners::ALL)
2667}
2668
2669/// The color of a solid fill in the current appearance; `None` for no fill or a gradient.
2670fn solid_fill(fill: Option<&day_spec::Paint>) -> Option<day_spec::Color> {
2671    match fill {
2672        Some(day_spec::Paint::Solid(ink)) => Some(ink.resolved()),
2673        _ => None,
2674    }
2675}
2676
2677/// A styled surface as the shim's `day_qt_widget_set_styled_surface` takes it: the 24-number
2678/// spec, and the gradient's stops as (offset, r, g, b, a) groups, every ink resolved against
2679/// the current appearance. The gradient kinds are the shim's: 1 linear (start and end unit
2680/// points), 2 radial (center and radius, unit space), 3 conic (center and start angle in
2681/// degrees, clockwise from +x).
2682fn surface_spec(p: &ContainerProps) -> ([f64; 24], Vec<f64>) {
2683    use day_spec::Paint;
2684    let rgba = |c: day_spec::Color| [c.r, c.g, c.b, c.a];
2685    let mut spec = [0.0; 24];
2686    spec[0..4].copy_from_slice(&rgba(
2687        solid_fill(p.fill.as_ref()).unwrap_or(day_spec::Color::CLEAR),
2688    ));
2689    spec[4] = p.corner_radius;
2690    spec[5] = f64::from(p.corners.bits());
2691    spec[6] = f64::from(u8::from(p.clips));
2692    if let Some(border) = p.border {
2693        spec[7..11].copy_from_slice(&rgba(border.color.resolved()));
2694        spec[11] = border.width;
2695    }
2696    if let Some(shadow) = p.shadow {
2697        spec[12..16].copy_from_slice(&rgba(shadow.color.resolved()));
2698        spec[16] = shadow.blur;
2699        spec[17] = shadow.dx;
2700        spec[18] = shadow.dy;
2701    }
2702    let gradient = match &p.fill {
2703        Some(Paint::Linear(g)) => Some((1.0, [g.start.x, g.start.y, g.end.x, g.end.y], &g.stops)),
2704        Some(Paint::Radial(g)) => Some((2.0, [g.center.x, g.center.y, g.radius, 0.0], &g.stops)),
2705        Some(Paint::Conic(g)) => Some((
2706            3.0,
2707            [g.center.x, g.center.y, g.start.degrees(), 0.0],
2708            &g.stops,
2709        )),
2710        Some(Paint::Solid(_)) | None => None,
2711    };
2712    let mut stops = Vec::new();
2713    if let Some((kind, numbers, ink_stops)) = gradient {
2714        spec[19] = kind;
2715        spec[20..24].copy_from_slice(&numbers);
2716        for (offset, color) in day_spec::resolved_stops(ink_stops) {
2717            stops.push(offset);
2718            stops.extend_from_slice(&rgba(color));
2719        }
2720    }
2721    (spec, stops)
2722}
2723
2724/// Whether any ink of a container's surface depends on the appearance.
2725fn surface_is_dynamic(p: &ContainerProps) -> bool {
2726    p.fill.as_ref().is_some_and(day_spec::Paint::is_dynamic)
2727        || p.border.is_some_and(|b| b.color.is_dynamic())
2728        || p.shadow.is_some_and(|s| s.color.is_dynamic())
2729}
2730
2731/// Apply every styling field of a container (docs/surfaces.md), resolved against the current
2732/// appearance: at realize (`fresh`), for a reactive surface (`ContainerPatch::Surface`), and
2733/// again after an appearance switch. A role is the realize-time one; its surface follows the
2734/// palette by itself and only its radius changes later. A container that once painted its
2735/// surface keeps painting it, so a border going away leaves no stale stylesheet behind.
2736///
2737/// # Safety
2738/// `w` is a live container widget Day realized.
2739unsafe fn apply_surface(w: *mut c_void, p: &ContainerProps, fresh: bool) {
2740    // SAFETY: the caller's guarantee; every call reads or writes only `w` and the numbers
2741    // passed, which outlive the calls.
2742    unsafe {
2743        match p.role {
2744            Some(day_spec::SurfaceRole::SectionCard) => {
2745                // A translucent neutral over the window color: subtle in any palette, and it
2746                // follows the platform / forced (DAY_THEME) color scheme.
2747                ffi::day_qt_widget_set_section_card(w, p.corner_radius);
2748            }
2749            Some(day_spec::SurfaceRole::Window) => {
2750                ffi::day_qt_widget_set_window_surface(w, p.corner_radius, c_int::from(p.clips));
2751            }
2752            _ if is_styled_surface(p) || ffi::day_qt_widget_has_styled_surface(w) != 0 => {
2753                // A gradient, a border, a shadow or a choice of corners: the container paints
2754                // these itself, since a stylesheet cannot follow the frame or cast a shadow.
2755                let (spec, stops) = surface_spec(p);
2756                ffi::day_qt_widget_set_styled_surface(
2757                    w,
2758                    spec.as_ptr(),
2759                    stops.as_ptr(),
2760                    (stops.len() / 5) as c_int,
2761                );
2762            }
2763            _ if !fresh || p.fill.is_some() || p.corner_radius > 0.0 || p.clips => {
2764                let bg = solid_fill(p.fill.as_ref()).unwrap_or(day_spec::Color::CLEAR);
2765                ffi::day_qt_widget_set_surface(
2766                    w,
2767                    bg.r,
2768                    bg.g,
2769                    bg.b,
2770                    bg.a,
2771                    p.corner_radius,
2772                    c_int::from(p.clips),
2773                );
2774            }
2775            _ => {}
2776        }
2777    }
2778}
2779
2780// ---- inks that follow the appearance (docs/color.md "How a toolkit follows the appearance") ----
2781
2782/// The appearance-dependent inks one widget shows, kept so that an appearance switch can apply
2783/// each again, resolved against the new palette. Qt takes concrete colors only (a stylesheet, a
2784/// painter, rich text, a recolored glyph), and Day sends no patch on a switch: an adaptive ink is
2785/// the same value before and after it. Only dynamic inks are kept (`Ink::is_dynamic`); a
2786/// container's surface lives in `SURFACES` instead.
2787#[derive(Clone, Default)]
2788struct Inks {
2789    label_color: Option<day_spec::Ink>,
2790    label_runs: Option<(String, Vec<day_spec::TextRun>)>,
2791    button: Option<day_spec::props::ButtonStyleSpec>,
2792    image_tint: Option<day_spec::Ink>,
2793    nav: Option<NavRows>,
2794    cover: Option<day_spec::Ink>,
2795}
2796
2797impl Inks {
2798    fn is_empty(&self) -> bool {
2799        self.label_color.is_none()
2800            && self.label_runs.is_none()
2801            && self.button.is_none()
2802            && self.image_tint.is_none()
2803            && self.nav.is_none()
2804            && self.cover.is_none()
2805    }
2806}
2807
2808/// A sidebar's rows as the shim's row calls take them, kept while a row's tint depends on the
2809/// appearance.
2810#[derive(Clone, Default)]
2811struct NavRows {
2812    items: Vec<String>,
2813    icons: Vec<Option<String>>,
2814    tints: Vec<Option<day_spec::Ink>>,
2815    badge_icons: Vec<Option<String>>,
2816    badge_tints: Vec<Option<day_spec::Ink>>,
2817    badges: Vec<Option<String>>,
2818}
2819
2820impl NavRows {
2821    fn is_dynamic(&self) -> bool {
2822        self.tints
2823            .iter()
2824            .chain(&self.badge_tints)
2825            .any(|t| t.is_some_and(day_spec::Ink::is_dynamic))
2826    }
2827
2828    /// The unit-separator joined lists the shim's row calls take: titles, icon files, tints,
2829    /// badge icon files, badge tints, counts.
2830    fn joined(&self) -> [CString; 6] {
2831        let files = |icons: &[Option<String>]| {
2832            icons
2833                .iter()
2834                .map(|ic| ic.as_deref().map_or_default(icon_file_path))
2835                .collect::<Vec<_>>()
2836                .join("\u{1f}")
2837        };
2838        [
2839            cstr(&self.items.join("\u{1f}")),
2840            cstr(&files(&self.icons)),
2841            cstr(&nav_tints_joined(&self.tints)),
2842            cstr(&files(&self.badge_icons)),
2843            cstr(&nav_tints_joined(&self.badge_tints)),
2844            cstr(&nav_counts_joined(&self.badges)),
2845        ]
2846    }
2847}
2848
2849thread_local! {
2850    /// Appearance-dependent inks by widget pointer (`Inks`); swept with the widget.
2851    static INKS: SideTable<Inks> = SideTable::new();
2852    /// The surface each styled container shows now, by widget pointer: a fill patch changes
2853    /// one field of it, a surface patch replaces it, an appearance switch applies it again.
2854    static SURFACES: SideTable<ContainerProps> = SideTable::new();
2855}
2856
2857/// Change the inks kept for `w`; an entry left with nothing is dropped.
2858fn remember_inks(w: *mut c_void, f: impl FnOnce(&mut Inks)) {
2859    INKS.with(|t| {
2860        let mut inks = t.take(w as usize).unwrap_or_default();
2861        f(&mut inks);
2862        if !inks.is_empty() {
2863            t.insert(w as usize, inks);
2864        }
2865    });
2866}
2867
2868/// A dynamic ink, or `None` for a fixed one (which never needs applying again).
2869fn dynamic(ink: Option<day_spec::Ink>) -> Option<day_spec::Ink> {
2870    ink.filter(|i| i.is_dynamic())
2871}
2872
2873/// A label's text color in the current appearance (`None`: the palette's text color).
2874///
2875/// # Safety
2876/// `w` is a live label Day realized.
2877unsafe fn apply_label_color(w: *mut c_void, color: Option<day_spec::Ink>) {
2878    let c = color.map(day_spec::Ink::resolved);
2879    let (r, g, b, a) = c.map_or((0.0, 0.0, 0.0, 0.0), |c| (c.r, c.g, c.b, c.a));
2880    // SAFETY: the caller's guarantee; the shim reads only the numbers.
2881    unsafe { ffi::day_qt_label_set_color(w, r, g, b, a, c_int::from(c.is_some())) };
2882    remember_inks(w, |i| i.label_color = dynamic(color));
2883}
2884
2885/// A label's runs, kept for an appearance switch when one of their inks depends on it.
2886fn apply_label_runs(w: *mut c_void, text: &str, runs: &[day_spec::TextRun]) {
2887    set_label_runs(w, text, runs);
2888    let dynamic_runs = runs.iter().any(|r| {
2889        r.color.is_some_and(day_spec::Ink::is_dynamic)
2890            || r.background.is_some_and(day_spec::Ink::is_dynamic)
2891            || r.underline
2892                .and_then(|d| d.color)
2893                .is_some_and(day_spec::Ink::is_dynamic)
2894            || r.strikethrough
2895                .and_then(|d| d.color)
2896                .is_some_and(day_spec::Ink::is_dynamic)
2897    });
2898    remember_inks(w, |i| {
2899        i.label_runs = dynamic_runs.then(|| (text.to_owned(), runs.to_vec()));
2900    });
2901}
2902
2903/// A button's style, kept for an appearance switch when its tint depends on it.
2904fn apply_button_style_ink(w: *mut c_void, style: day_spec::props::ButtonStyleSpec) {
2905    apply_button_style(w, style);
2906    let tinted = matches!(style, day_spec::props::ButtonStyleSpec::Tinted(ink) if ink.is_dynamic());
2907    remember_inks(w, |i| i.button = tinted.then_some(style));
2908}
2909
2910/// A sidebar's rows set or updated in place: `rows` the Day rows to update, or `None` to replace
2911/// every row (the sections then come too).
2912///
2913/// # Safety
2914/// `w` is a live sidebar list Day realized.
2915unsafe fn apply_nav_rows(
2916    w: *mut c_void,
2917    rows: &NavRows,
2918    update: Option<&[usize]>,
2919    sections: &[Option<String>],
2920) -> usize {
2921    let [joined, icons, tints, badge_icons, badge_tints, counts] = rows.joined();
2922    let mut headings = 0;
2923    // SAFETY: the caller's guarantee; every string outlives the call.
2924    unsafe {
2925        if let Some(update) = update {
2926            let rows_joined = update
2927                .iter()
2928                .map(std::string::ToString::to_string)
2929                .collect::<Vec<_>>()
2930                .join(",");
2931            ffi::day_qt_navlist_update_rows(
2932                w,
2933                cstr(&rows_joined).as_ptr(),
2934                joined.as_ptr(),
2935                icons.as_ptr(),
2936                tints.as_ptr(),
2937                badge_icons.as_ptr(),
2938                badge_tints.as_ptr(),
2939                counts.as_ptr(),
2940            );
2941        } else {
2942            let (sections_joined, n) = nav_sections_joined(sections);
2943            headings = n;
2944            ffi::day_qt_navlist_set_items(
2945                w,
2946                joined.as_ptr(),
2947                icons.as_ptr(),
2948                tints.as_ptr(),
2949                badge_icons.as_ptr(),
2950                badge_tints.as_ptr(),
2951                counts.as_ptr(),
2952                cstr(&sections_joined).as_ptr(),
2953            );
2954        }
2955    }
2956    remember_inks(w, |i| i.nav = rows.is_dynamic().then(|| rows.clone()));
2957    headings
2958}
2959
2960/// The appearance changed: Day reads the new palette, then every ink Qt was handed as a
2961/// concrete color is applied again, resolved against it (docs/color.md "How a toolkit follows
2962/// the appearance"). Palette-driven parts (the stock controls, a template glyph, a section card)
2963/// have already followed. Canvases re-record on Day's side.
2964fn refresh_appearance() {
2965    day_core::note_appearance_changed();
2966    reapply_inks();
2967}
2968
2969/// Every kept ink applied again, resolved against `Palette::current()`.
2970fn reapply_inks() {
2971    let mut surfaces = Vec::new();
2972    SURFACES.with(|t| {
2973        t.for_each(|w, p| {
2974            if surface_is_dynamic(p) {
2975                surfaces.push((w, p.clone()));
2976            }
2977        });
2978    });
2979    for (w, p) in surfaces {
2980        // SAFETY: an entry lives exactly as long as its widget (swept on release).
2981        unsafe { apply_surface(w as *mut c_void, &p, false) };
2982    }
2983    let mut inks = Vec::new();
2984    INKS.with(|t| t.for_each(|w, i| inks.push((w, i.clone()))));
2985    for (w, i) in inks {
2986        let w = w as *mut c_void;
2987        // SAFETY: as above; each call re-applies to the widget the entry was made for.
2988        unsafe {
2989            if let Some(c) = i.label_color {
2990                apply_label_color(w, Some(c));
2991            }
2992            if let Some((text, runs)) = &i.label_runs {
2993                set_label_runs(w, text, runs);
2994            }
2995            if let Some(style) = i.button {
2996                apply_button_style(w, style);
2997            }
2998            if let Some(tint) = i.image_tint {
2999                let tint = image_tint(Some(tint.resolved()), false);
3000                ffi::day_qt_image_set_tint(w, cstr(&tint).as_ptr());
3001            }
3002            if let Some(rows) = &i.nav {
3003                let all: Vec<usize> = (0..rows.items.len()).collect();
3004                apply_nav_rows(w, rows, Some(&all), &[]);
3005            }
3006            if let Some(bg) = i.cover {
3007                let bg = bg.resolved();
3008                ffi::day_qt_widget_set_bg(w, bg.r, bg.g, bg.b, bg.a, std::ptr::null());
3009            }
3010        }
3011    }
3012}
3013
3014/// The shim's appearance callback (`day_qt_on_appearance`).
3015extern "C" fn on_appearance() {
3016    ffi_guard::contain((), refresh_appearance);
3017}
3018
3019/// Per-row counts for the shim, unit-separator joined (empty = no count).
3020fn nav_counts_joined(badges: &[Option<String>]) -> String {
3021    badges
3022        .iter()
3023        .map(|b| b.as_deref().unwrap_or(""))
3024        .collect::<Vec<_>>()
3025        .join("\u{1f}")
3026}
3027
3028/// Per-row tints for the shim, each resolved against the current appearance.
3029fn nav_tints_joined(tints: &[Option<day_spec::Ink>]) -> String {
3030    tints
3031        .iter()
3032        .map(|t| match t.map(day_spec::Ink::resolved) {
3033            Some(c) => format!(
3034                "#{:02x}{:02x}{:02x}",
3035                (c.r * 255.0) as u8,
3036                (c.g * 255.0) as u8,
3037                (c.b * 255.0) as u8
3038            ),
3039            None => String::new(),
3040        })
3041        .collect::<Vec<_>>()
3042        .join("\u{1f}")
3043}
3044
3045/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
3046/// `const` so `day::require_lifecycle!` can reject unsupported phases at compile time.
3047#[must_use]
3048pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
3049    phase.is_universal()
3050}
3051
3052/// Phase codes (from the Qt shim's `QApplication` signals) → day lifecycle events.
3053extern "C" fn on_lifecycle(code: c_int) {
3054    use day_spec::Lifecycle::{DidBecomeActive, WillResignActive, WillTerminate};
3055    ffi_guard::contain((), || {
3056        let phase = match code {
3057            2 => DidBecomeActive,
3058            3 => WillResignActive,
3059            7 => WillTerminate,
3060            _ => return,
3061        };
3062        emit_window(Event::Lifecycle(phase));
3063    });
3064}
3065
3066/// A QKeySequence-parseable string for a shortcut. Qt maps `Ctrl` to ⌘ on macOS, so `primary`
3067/// renders as the platform's command modifier everywhere.
3068fn qt_shortcut(sc: &day_spec::Shortcut) -> String {
3069    let mut parts: Vec<String> = Vec::new();
3070    if sc.primary {
3071        parts.push("Ctrl".into());
3072    }
3073    if sc.shift {
3074        parts.push("Shift".into());
3075    }
3076    if sc.alt {
3077        parts.push("Alt".into());
3078    }
3079    if sc.control {
3080        // The *physical* Control key: Qt::MetaModifier is Control on macOS, Control elsewhere.
3081        #[cfg(target_os = "macos")]
3082        parts.push("Meta".into());
3083        #[cfg(not(target_os = "macos"))]
3084        parts.push("Ctrl".into());
3085    }
3086    // Single letters are case-insensitive to Qt; named keys ("Delete", "Return", "F11") pass through.
3087    let key = if sc.key.chars().count() == 1 {
3088        sc.key.to_uppercase()
3089    } else {
3090        sc.key.clone()
3091    };
3092    parts.push(key);
3093    // Delete and Backspace end up bound together — the shim pairs them once the sequence is
3094    // parsed, where the key CODE is visible and no separator has to survive a shortcut string
3095    // that may itself contain a comma or semicolon (⌘, is Preferences).
3096    parts.join("+")
3097}
3098
3099/// Default label for a standard role when the app left the entry's label empty.
3100fn qt_role_label(role: day_spec::MenuRole) -> &'static str {
3101    use day_spec::MenuRole::{
3102        About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
3103        Paste, Preferences, Quit, Redo, SelectAll, Undo,
3104    };
3105    match role {
3106        Cut => "Cut",
3107        Copy => "Copy",
3108        Paste => "Paste",
3109        SelectAll => "Select All",
3110        Undo => "Undo",
3111        Redo => "Redo",
3112        Delete => "Delete",
3113        About => "About",
3114        Quit => "Quit",
3115        Preferences => "Preferences…",
3116        Minimize => "Minimize",
3117        CloseWindow => "Close",
3118        Fullscreen => "Enter Full Screen",
3119        NewWindow => "New Window",
3120        CheckForUpdates => "Check for Updates…",
3121    }
3122}
3123
3124/// Default portable shortcut for a role (Qt maps `Ctrl` → ⌘ on macOS).
3125fn qt_role_shortcut(role: day_spec::MenuRole) -> Option<&'static str> {
3126    use day_spec::MenuRole::{
3127        About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize, NewWindow,
3128        Paste, Preferences, Quit, Redo, SelectAll, Undo,
3129    };
3130    Some(match role {
3131        Cut => "Ctrl+X",
3132        Copy => "Ctrl+C",
3133        Paste => "Ctrl+V",
3134        SelectAll => "Ctrl+A",
3135        Undo => "Ctrl+Z",
3136        Redo => "Ctrl+Shift+Z",
3137        Quit => "Ctrl+Q",
3138        CloseWindow => "Ctrl+W",
3139        Minimize => "Ctrl+M",
3140        Preferences => "Ctrl+,",
3141        NewWindow => "Ctrl+N",
3142        Delete | About | Fullscreen | CheckForUpdates => return None,
3143    })
3144}
3145
3146/// Walk the day-neutral menu tree, issuing flat builder calls against a `QMenu` pointer.
3147pub(crate) fn build_qt_menu(menu: *mut c_void, items: &[day_spec::MenuItem]) {
3148    for item in items {
3149        match item {
3150            day_spec::MenuItem::Separator => unsafe { ffi::day_qt_menu_add_separator(menu) },
3151            day_spec::MenuItem::Submenu { label, items, .. } => {
3152                let sub = unsafe { ffi::day_qt_menu_add_submenu(menu, cstr(label).as_ptr()) };
3153                build_qt_menu(sub, items);
3154            }
3155            day_spec::MenuItem::Action {
3156                action,
3157                label,
3158                shortcut,
3159                enabled,
3160                checked,
3161                role,
3162                icon,
3163                ..
3164            } => {
3165                // A nonzero id always wins (the appkit precedence, docs/menus.md): the item
3166                // dispatches the day action, with the role only supplying label/shortcut
3167                // defaults — the auto Preferences item and `MenuRole::NewWindow` arrive
3168                // this way. Routing them through the role-only path dropped the dispatch
3169                // id, leaving visible-but-dead items (the macos-qt bug).
3170                if *action != 0 {
3171                    let text = match role {
3172                        Some(r) if label.is_empty() => qt_role_label(*r).to_string(),
3173                        _ => label.clone(),
3174                    };
3175                    let sc = shortcut
3176                        .as_ref()
3177                        .map(qt_shortcut)
3178                        .or_else(|| role.and_then(|r| qt_role_shortcut(r).map(str::to_string)))
3179                        .unwrap_or_default();
3180                    let (ic, ic_fallback) = crate::toolbar::icon_args(icon.as_ref());
3181                    unsafe {
3182                        ffi::day_qt_menu_add_action(
3183                            menu,
3184                            cstr(&text).as_ptr(),
3185                            *action,
3186                            cstr(&sc).as_ptr(),
3187                            c_int::from(*enabled),
3188                            cstr(&ic).as_ptr(),
3189                            ic_fallback,
3190                            checked.map_or(-1, c_int::from),
3191                        );
3192                    };
3193                } else if let Some(role) = role {
3194                    let text = if label.is_empty() {
3195                        qt_role_label(*role).to_string()
3196                    } else {
3197                        label.clone()
3198                    };
3199                    let sc = shortcut
3200                        .as_ref()
3201                        .map(qt_shortcut)
3202                        .or_else(|| qt_role_shortcut(*role).map(str::to_string))
3203                        .unwrap_or_default();
3204                    unsafe {
3205                        ffi::day_qt_menu_add_role(
3206                            menu,
3207                            cstr(&text).as_ptr(),
3208                            *role as c_int,
3209                            cstr(&sc).as_ptr(),
3210                        );
3211                    };
3212                }
3213            }
3214        }
3215    }
3216}
3217
3218/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
3219/// a visible placeholder. A missing renderer usually means the piece's `qt` feature wasn't enabled
3220/// (Tier A.2 derives it automatically under `day build`). Deduped per kind so a placeholder rendered
3221/// every frame doesn't spam the log.
3222fn warn_missing_renderer(kind: PieceKind) {
3223    day_spec::placeholder::report(kind, "qt");
3224}
3225
3226/// The visible placeholder a realize arm degrades to when its props payload has the wrong type
3227/// (`props_of` has already reported the mismatch) — the same label the missing-renderer arm shows.
3228pub(crate) fn placeholder_handle(kind: PieceKind) -> QtHandle {
3229    QtHandle(unsafe { ffi::day_qt_label_new(cstr(&format!("⟨{kind}⟩")).as_ptr(), 1) })
3230}
3231
3232/// `Qt::CursorShape` for a [`Cursor`], or -1 to unset (docs/cursor.md).
3233fn qt_cursor_shape(c: &Cursor) -> c_int {
3234    match c {
3235        Cursor::Default => -1,
3236        Cursor::Pointer => 13,                    // PointingHandCursor
3237        Cursor::Text | Cursor::VerticalText => 4, // IBeamCursor
3238        Cursor::Crosshair | Cursor::Cell => 2,    // CrossCursor
3239        Cursor::Move => 9,                        // SizeAllCursor
3240        Cursor::Grab => 17,                       // OpenHandCursor
3241        Cursor::Grabbing => 18,                   // ClosedHandCursor
3242        Cursor::NotAllowed => 14,                 // ForbiddenCursor
3243        Cursor::Wait => 3,                        // WaitCursor
3244        Cursor::Progress => 16,                   // BusyCursor
3245        Cursor::Help => 15,                       // WhatsThisCursor
3246        Cursor::ContextMenu | Cursor::ZoomIn | Cursor::ZoomOut => 0, // ArrowCursor
3247        Cursor::Copy => 19,                       // DragCopyCursor
3248        Cursor::Alias => 21,                      // DragLinkCursor
3249        Cursor::None => 10,                       // BlankCursor
3250        Cursor::NsResize => 5,                    // SizeVerCursor
3251        Cursor::EwResize => 6,                    // SizeHorCursor
3252        Cursor::NeswResize => 7,                  // SizeBDiagCursor
3253        Cursor::NwseResize => 8,                  // SizeFDiagCursor
3254        Cursor::ColResize => 12,                  // SplitHCursor
3255        Cursor::RowResize => 11,                  // SplitVCursor
3256        Cursor::Native(name) => match &**name {
3257            "UpArrowCursor" => 1,
3258            "BlankCursor" => 10,
3259            "SplitVCursor" => 11,
3260            "SplitHCursor" => 12,
3261            "WhatsThisCursor" => 15,
3262            "BusyCursor" => 16,
3263            "DragMoveCursor" => 20,
3264            _ => -1,
3265        },
3266    }
3267}
3268
3269impl Toolkit for Qt {
3270    type Handle = QtHandle;
3271
3272    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
3273        unsafe {
3274            day_toolkit_qt_sys::day_qt_set_visible(handle.0, i32::from(visible));
3275        }
3276    }
3277
3278    #[expect(
3279        clippy::match_same_arms,
3280        reason = "one arm per capability, each documented with the Qt mechanism behind it"
3281    )]
3282    fn capability(&self, cap: Cap) -> Support {
3283        match cap {
3284            // A reordering sidebar is Day's own list standing in for the native one: the rows
3285            // drag natively, the sidebar does not (docs/navigation.md).
3286            Cap::NavReorder => Support::Emulated,
3287            // `set_appearance` is `QStyleHints::setColorScheme`, which Qt has from 6.8. Every
3288            // ink follows a system switch on any version (`refresh_appearance`).
3289            Cap::Appearance => {
3290                // SAFETY: a compile-time answer from the shim; no arguments.
3291                if unsafe { ffi::day_qt_appearance_settable() } != 0 {
3292                    Support::Native
3293                } else {
3294                    Support::Unsupported
3295                }
3296            }
3297            Cap::SearchField => Support::Native,
3298            Cap::ComboBox => Support::Native,
3299            Cap::Stepper => Support::Native,
3300            Cap::DateTimePicker => Support::Native,
3301            Cap::ColorPicker => Support::Native,
3302            Cap::PullRefresh => Support::Emulated,
3303            Cap::Pager => Support::Emulated,
3304            Cap::PullRefreshGesture => Support::Unsupported,
3305            // `QWidget::setCursor` per widget; several CSS shapes take their nearest Qt shape
3306            // (docs/cursor.md).
3307            Cap::Cursor => Support::Emulated,
3308            // OS window tabs exist on macOS alone, through `day_platform_macos` (docs/windows.md).
3309            Cap::WindowTabbing if cfg!(target_os = "macos") => Support::Native,
3310            // `QFontDatabase::families()` + `styles()` (docs/fonts.md).
3311            Cap::FontList => Support::Native,
3312            // Qt's animation framework plays the whole AnimSpec contract on opacity, transform,
3313            // frame and a container's fill (a QSequentialAnimationGroup per widget and channel:
3314            // QPauseAnimation for the delay, looped QVariantAnimations keyed with the curve's
3315            // samples), and `read_displayed` reads the values in flight (docs/tween.md).
3316            Cap::Animation => Support::Native,
3317            // `QImage::loadFromData` reads every format Qt's image plugins handle, and
3318            // `QImage::save` writes back PNG/JPEG/TIFF/BMP (docs/images.md). `Cap::ImageProperties`
3319            // is deliberately NOT here: Qt exposes no metadata reader on this path, and an empty
3320            // struct would read as "this file records nothing" rather than "nobody looked".
3321            Cap::ImageDecode | Cap::ImageEncode => Support::Native,
3322            // The canvas widget's painter replays into a QImage and onto QPdfWriter pages
3323            // (QtGui, no extra module), so both exports are native (docs/canvas.md "Exporting").
3324            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
3325            // QListView has no sticky group rows: header rows are unselectable, disabled model
3326            // rows sized to their content, and the list pins a copy of the current section's
3327            // header over the top of its viewport (docs/list.md "Sections").
3328            Cap::ListSections => Support::Emulated,
3329            // `ScrollSnap` comes to rest by a glide to the nearest stop once the user's
3330            // scrolling has been quiet for 150 ms: Qt's scroll areas have resting points only
3331            // under a QScroller, which Day's do not grab (docs/scroll.md).
3332            Cap::ScrollSnap => Support::Emulated,
3333            // `Cap::ScrollPhases` stays Unsupported (the default arm): with no QScroller, Qt
3334            // tells no drag/coast/idle moments, so the scroll piece derives them from the
3335            // offset reports. `Cap::ScrollZoom` too (no zooming scroll area), and
3336            // `Cap::ScrollKeyboardDismiss` (a desktop toolkit with no software keyboard).
3337            // `Cap::PagerProgress` as well: the pager is the composed one (`Cap::Pager`
3338            // Emulated), whose progress the piece keeps at rest.
3339            //
3340            // The viewport report: the vertical bar's value and range and `indexAt` at the
3341            // viewport's edges, after every scroll, resize, splice and relayout (docs/list.md
3342            // "Visible rows"). Row scrolls aimed per pixel on the vertical bar, every
3343            // alignment, gliding with a QPropertyAnimation (`Toolkit::list_scroll`). The
3344            // offset: the bars' `valueChanged`, one report per frame plus the resting one.
3345            Cap::ListViewport | Cap::ListScrollAlign | Cap::ScrollOffset => Support::Native,
3346            // The scrolls the reader starts: the vertical bar's `actionTriggered` (only ever the
3347            // user's: a wheel step, which the view hands to the bar, a thumb drag, a page click)
3348            // when it moves the bar, and a key whose cursor move scrolled the list.
3349            Cap::ListReaderScroll => Support::Native,
3350            // QPlainTextEdit honors editable + selectable; Qt ships no built-in spell-check, so
3351            // Cap::TextSpellCheck stays Unsupported (the default arm).
3352            Cap::TextRuns
3353            | Cap::TextLinks
3354            | Cap::Snapshot
3355            | Cap::NavSplit
3356            // One QSplitter carries both presentations, with the back header installed either
3357            // way — so re-presenting is a pane visibility flip plus one re-parent of the
3358            // sidebar page (docs/size-classes.md).
3359            | Cap::NavRepresent
3360            // The same QSplitter's middle pane, with a real draggable divider on each side;
3361            // it persists through every presentation, the AppKit shape (docs/navigation.md).
3362            | Cap::NavContentList
3363            | Cap::Dialogs
3364            | Cap::FileDialogs
3365            // QFileDialog in `Directory` mode (docs/files.md).
3366            | Cap::FolderDialog
3367            | Cap::TextEditable
3368            | Cap::TextSelectable
3369            // Qt's own QDrag pipeline: grabbed-cell pixmap, insertion line, no-drop cursor.
3370            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::ListReorder
3371            // A QListView with Day's cells recycled through a bounded pool as rows scroll in
3372            // and out (docs/list.md): the view scrolls, Day fills the cell it is handed.
3373            | Cap::ListRecycling
3374            // Real DayWindows on the shared QApplication (docs/windows.md).
3375            | Cap::MultiWindow
3376            // showMinimized / showMaximized / showFullScreen / showNormal, reported back from
3377            // the DayWindow's WindowStateChange events (docs/windows.md "Window properties").
3378            // Wayland never reports minimized; the shim's `assumedMinimized` stands in for it.
3379            // `Cap::ContentProtection` stays Unsupported: no Linux display server lets a client
3380            // opt out of capture.
3381            | Cap::WindowStates
3382            | Cap::WindowFullscreen
3383            // `Qt::FramelessWindowHint`, resizable from its edges through
3384            // `QWindow::startSystemResize` (docs/window-chrome.md).
3385            | Cap::FramelessWindow
3386            // `QWindow::startSystemMove` on a press of the region's own background.
3387            | Cap::DragRegion
3388            // `resize`, `setMinimumSize`/`setMaximumSize`, `setFixedSize`.
3389            | Cap::WindowGeometry
3390            // `Qt::WindowStaysOnTopHint`, and `Qt::Tool` for no taskbar entry. Every workspace
3391            // has no Qt API and is ignored.
3392            | Cap::WindowLevel
3393            // `QApplication::alert`.
3394            | Cap::RequestAttention
3395            // `QGuiApplication::screens()`, with each screen's available geometry.
3396            | Cap::Monitors
3397            // A QTabWidget, which is Qt's own one-of-N container and already the shape Day
3398            // wants: it owns its pages and shows one at a time (docs/navigation.md).
3399            //
3400            // `Cap::NavTabsAdaptive` is deliberately not here: a Qt app may PIN a tab bar, but a
3401            // narrowing window hides its sidebar and pushes rather than growing one.
3402            | Cap::NavTabs
3403            // A real QToolBar under the menu bar (docs/toolbars.md).
3404            | Cap::AppMenu
3405            | Cap::Toolbar
3406            // The bar holds a native search field (docs/search.md).
3407            | Cap::ToolbarSearch
3408            // The nav QSplitter mirrored: panel pane trailing, divider draggable
3409            // (docs/inspector.md — not a QDockWidget; DayWindow is no QMainWindow).
3410            | Cap::Inspector
3411            // A QSplitter of two plain panes, either orientation (docs/split.md).
3412            | Cap::Split => Support::Native,
3413            // A focusable view joins Qt's tab chain (StrongFocus), focuses on a press before
3414            // its recognizers hear it, reports focus both ways, takes its keys with phases, and
3415            // shows the style's focus indicator when the keyboard brought focus
3416            // (docs/focus.md). Repeats are `QKeyEvent::isAutoRepeat`, releases `KeyRelease`
3417            // (docs/menus.md "Keys").
3418            Cap::Focusable | Cap::KeyPhases => Support::Native,
3419            // Day's own routing of the press, since Qt has no per-widget hit test to override
3420            // (docs/gestures.md "Hit slop").
3421            Cap::HitSlop => Support::Emulated,
3422            // QLabel has no selection signal; the label compares `selectionStart` and
3423            // `selectedText` after each mouse, key and focus event that can move it and reports
3424            // a change (docs/text.md "Hearing about the selection").
3425            Cap::LabelSelection => Support::Native,
3426            // A topmost child of the window content — not a system modal (docs/cover.md).
3427            Cap::Cover => Support::Emulated,
3428            // Native QTreeWidget disclosure and selection, with Day-owned row widgets.
3429            // Native tree drag-to-move is not wired yet.
3430            Cap::Tree | Cap::TreeSections => Support::Native,
3431            // Derived from QFontMetrics — Qt publishes no baseline of its own
3432            // (docs/baseline.md).
3433            Cap::BaselineAlignment => Support::Emulated,
3434            // `QAccessibleAnnouncementEvent` (docs/accessibility.md) is Qt 6.8; the shim
3435            // answers for the Qt it is built against.
3436            Cap::Announce => {
3437                // SAFETY: a constant read; no arguments and no pointers cross the boundary.
3438                if unsafe { ffi::day_qt_can_announce() } != 0 {
3439                    Support::Native
3440                } else {
3441                    Support::Unsupported
3442                }
3443            }
3444            // Qt publishes no system reduce-motion read (docs/accessibility.md): QStyleHints and
3445            // QGuiApplication carry nothing, `QStyle::SH_Widget_Animation_Duration` is the active
3446            // style's own constant rather than the user's setting, and
3447            // `QApplication::isEffectEnabled` answers the menu/tooltip effect switches. So
3448            // `Toolkit::reduce_motion` keeps its default, and `DAY_REDUCE_MOTION=1` is the one
3449            // way on.
3450            Cap::ReduceMotion => Support::Unsupported,
3451            // `move()` places a window on X11, Windows and macOS; Wayland lets no client place
3452            // its windows (docs/windows.md).
3453            Cap::WindowPosition => {
3454                // SAFETY: a read of the platform name.
3455                if unsafe { ffi::day_qt_is_wayland() } != 0 {
3456                    Support::Unsupported
3457                } else {
3458                    Support::Native
3459                }
3460            }
3461            // The Unity LauncherEntry signal, which docks may or may not read.
3462            // Written as a plain arm so the coverage matrix reads it as decided per platform (a
3463            // guard arm reads as unsupported).
3464            Cap::AppProgress | Cap::AppBadgeCount => {
3465                if cfg!(target_os = "linux") {
3466                    Support::Emulated
3467                } else {
3468                    Support::Unsupported
3469                }
3470            }
3471            // `WA_TranslucentBackground`. On X11 it needs a compositing window manager.
3472            Cap::TransparentWindow => Support::Native,
3473            // A QSystemTrayIcon host: a StatusNotifierWatcher or an XEmbed tray on Linux.
3474            Cap::StatusItem => {
3475                // SAFETY: a query of the running QApplication.
3476                if unsafe { ffi::day_qt_tray_available() } != 0 {
3477                    Support::Native
3478                } else {
3479                    Support::Unsupported
3480                }
3481            }
3482            // Deliberately Unsupported (the default arm): `OverlayTitleBar` (Qt draws no title
3483            // bar of its own to run content under; the window keeps its standard frame),
3484            // `WindowMaterial`, `WindowAppearance` (palette and scheme are app-wide),
3485            // `ContentProtection`, `DynamicShortcuts` (a .desktop file's actions are fixed).
3486            _ => Support::Unsupported,
3487        }
3488    }
3489
3490    fn realize(&mut self, kind: PieceKind, props: &dyn std::any::Any, id: NodeId) -> QtHandle {
3491        unsafe {
3492            match Builtin::from_key(kind) {
3493                Some(Builtin::Inspector) => {
3494                    let (visible, width, leading) =
3495                        props
3496                            .downcast_ref::<InspectorProps>()
3497                            .map_or((false, 280.0, false), |p| {
3498                                (
3499                                    p.visible,
3500                                    p.width,
3501                                    p.edge == day_spec::props::PaneEdge::Leading,
3502                                )
3503                            });
3504                    let host = ffi::day_qt_inspector_new(width, c_int::from(leading));
3505                    // Positional panes, role-mapped: the LEADING arrangement holds the panel
3506                    // first (docs/inspector.md `.edge`).
3507                    let (content_ix, panel_ix) = if leading { (1, 0) } else { (0, 1) };
3508                    let content_pane = ffi::day_qt_splitter_pane(host, content_ix);
3509                    let panel_pane = ffi::day_qt_splitter_pane(host, panel_ix);
3510                    ffi::day_qt_splitter_on_moved(host, inspector_splitter_moved);
3511                    // …and on every layout pass, so the panes stop reporting the placeholder
3512                    // geometry they have at insert time (before the window lays the splitter
3513                    // out at all).
3514                    ffi::day_qt_splitter_on_resized(host, inspector_splitter_moved);
3515                    ffi::day_qt_set_visible(panel_pane, c_int::from(visible));
3516                    INSPECTOR_STATE.with(|m| {
3517                        m.borrow_mut().insert(
3518                            host as usize,
3519                            InspectorState {
3520                                content_pane,
3521                                panel_pane,
3522                                panes: Vec::new(),
3523                                width,
3524                                shown: visible,
3525                            },
3526                        )
3527                    });
3528                    QtHandle(host)
3529                }
3530                Some(Builtin::Split) => {
3531                    let (axis, fraction, min_pane) = props
3532                        .downcast_ref::<SplitProps>()
3533                        .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
3534                            (p.axis, p.fraction, p.min_pane)
3535                        });
3536                    let vertical = axis == day_spec::props::SplitAxis::Vertical;
3537                    let host = ffi::day_qt_split_new(c_int::from(vertical), min_pane);
3538                    let first_pane = ffi::day_qt_splitter_pane(host, 0);
3539                    let second_pane = ffi::day_qt_splitter_pane(host, 1);
3540                    ffi::day_qt_splitter_on_moved(host, split_moved);
3541                    ffi::day_qt_splitter_on_resized(host, split_resized);
3542                    SPLIT_STATE.with(|m| {
3543                        m.borrow_mut().insert(
3544                            host as usize,
3545                            SplitState {
3546                                first_pane,
3547                                second_pane,
3548                                node: id,
3549                                panes: Vec::new(),
3550                                share: fraction.clamp(0.0, 1.0),
3551                                min_pane,
3552                                placed: false,
3553                                suppress: false,
3554                            },
3555                        )
3556                    });
3557                    QtHandle(host)
3558                }
3559                Some(Builtin::SplitPane) => {
3560                    let w = ffi::day_qt_container_new();
3561                    let second = props
3562                        .downcast_ref::<SplitPaneProps>()
3563                        .is_some_and(|p| p.second);
3564                    SPLIT_PANE_IDS.with(|m| m.borrow_mut().insert(w as usize, (id, second)));
3565                    QtHandle(w)
3566                }
3567                Some(Builtin::InspectorPane) => {
3568                    let w = ffi::day_qt_container_new();
3569                    let panel = props
3570                        .downcast_ref::<InspectorPaneProps>()
3571                        .is_some_and(|p| p.panel);
3572                    INSPECTOR_PANE_IDS.with(|m| m.borrow_mut().insert(w as usize, (id, panel)));
3573                    QtHandle(w)
3574                }
3575                Some(Builtin::Container) => {
3576                    let w = ffi::day_qt_container_new();
3577                    if let Some(p) = props.downcast_ref::<ContainerProps>() {
3578                        apply_surface(w, p, true);
3579                        if *p != ContainerProps::default() {
3580                            SURFACES.with(|t| t.insert(w as usize, p.clone()));
3581                        }
3582                    }
3583                    passive(w)
3584                }
3585                Some(Builtin::Nav) => {
3586                    let nav_props = props.downcast_ref::<NavProps>();
3587                    // Where the rows are the CHROME, the host is a QTabWidget — Qt's own
3588                    // one-of-N container, and already the shape Day wants here: it owns its page
3589                    // widgets and shows one at a time, so the pages stay resident and
3590                    // `NavPatch::Select` drives the bar instead of push/pop.
3591                    //
3592                    // A desktop only reaches this by PINNING `NavStyle::Tabs`;
3593                    // `Cap::NavTabsAdaptive` is off here, so a narrowing window hides the sidebar
3594                    // and pushes rather than growing a bar.
3595                    if nav_props.is_some_and(|p| p.presentation.rows_are_chrome()) {
3596                        let w = ffi::day_qt_tabs_new(id.0, nav_suite_changed);
3597                        NAV_SUITES.with(|m| {
3598                            m.borrow_mut().insert(
3599                                w as usize,
3600                                NavSuite {
3601                                    host: id,
3602                                    menu_node: NodeId(0),
3603                                    pages: Vec::new(),
3604                                    titles: Vec::new(),
3605                                    icons: Vec::new(),
3606                                    keys: Vec::new(),
3607                                },
3608                            )
3609                        });
3610                        if let Some(config) = nav_props.and_then(|p| p.documents.as_ref()) {
3611                            ffi::day_qt_tabs_documents(
3612                                w,
3613                                id.0,
3614                                cstr(&config.new_label).as_ptr(),
3615                                cstr(&config.close_label).as_ptr(),
3616                                c_int::from(config.can_add),
3617                                document_tab_event,
3618                            );
3619                        }
3620                        return QtHandle(w);
3621                    }
3622                    let is_split = nav_props.is_none_or(|p| p.presentation.is_split());
3623                    // The content-list pane (docs/navigation.md): pane 1 of the same splitter,
3624                    // hidden on a host that declared none — the same shape either way, so the
3625                    // header and the pane indices never move.
3626                    let list_width = nav_props.and_then(|p| p.list_width);
3627                    let list_visible = nav_props.is_none_or(|p| p.list_visible);
3628                    let host = ffi::day_qt_splitter_new(
3629                        list_width.unwrap_or(0.0),
3630                        day_spec::NAV_SIDEBAR_MIN_W,
3631                        day_spec::NAV_LIST_MIN_W,
3632                    );
3633                    let sidebar_pane = ffi::day_qt_splitter_pane(host, 0);
3634                    let list_pane = ffi::day_qt_splitter_pane(host, 1);
3635                    let mut detail_pane = ffi::day_qt_splitter_pane(host, 2);
3636                    // Collapsed for a destination that spans the whole detail area
3637                    // (`content_list_for`); `NavPatch::ListVisible` brings it back.
3638                    if list_width.is_some() && !list_visible {
3639                        ffi::day_qt_set_visible(list_pane, 0);
3640                    }
3641                    ffi::day_qt_splitter_on_moved(host, nav_splitter_moved);
3642                    ffi::day_qt_splitter_on_resized(host, nav_splitter_moved);
3643                    // The back header goes in for both presentations, hidden until a stack
3644                    // actually pushes. Installing it lazily would mean restructuring the detail
3645                    // pane's layout under live, absolutely-positioned pages the first time a
3646                    // window narrowed (docs/size-classes.md) — this way the widget tree is the
3647                    // same shape either way and a re-present only flips visibility.
3648                    let pages = ffi::day_qt_nav_header_install(host, id.0, nav_back_clicked);
3649                    if !pages.is_null() {
3650                        detail_pane = pages;
3651                    }
3652                    // Depth titles for the back header. Recorded in both presentations, so a
3653                    // window that narrows into a stack already knows what to put in the header
3654                    // (docs/size-classes.md); the header simply stays hidden while split.
3655                    let titles = vec![nav_props.map_or_default(|p| p.title.clone())];
3656                    if !is_split {
3657                        // A stack has no sidebar: hide the empty pane so the detail is full-width.
3658                        ffi::day_qt_set_visible(sidebar_pane, 0);
3659                    }
3660                    NAV_STATE.with(|m| {
3661                        m.borrow_mut().insert(
3662                            host as usize,
3663                            NavState {
3664                                sidebar_pane,
3665                                detail_pane,
3666                                pages: Vec::new(),
3667                                sidebar_page: None,
3668                                split: is_split,
3669                                sidebar_shown: is_split,
3670                                list_pane,
3671                                list_width,
3672                                list_page: None,
3673                                list_shown: list_visible,
3674                                // Sized at construction when it opened showing; a hidden
3675                                // pane is placed on its first reveal.
3676                                list_positioned: list_visible,
3677                                titles,
3678                            },
3679                        )
3680                    });
3681                    QtHandle(host)
3682                }
3683                Some(Builtin::NavPage) => {
3684                    let page = QtHandle(ffi::day_qt_container_new());
3685                    NAV_PAGE_IDS.with(|m| m.borrow_mut().insert(page.0 as usize, id));
3686                    if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
3687                        PAGE_PANE.with(|m| m.borrow_mut().insert(page.0 as usize, p.pane));
3688                    }
3689                    page
3690                }
3691                // Emulated fullscreen cover (docs/cover.md): parked hidden; Present re-homes
3692                // it onto the window content, topmost, at the content size.
3693                Some(Builtin::Cover) => {
3694                    let cover = QtHandle(ffi::day_qt_container_new());
3695                    ffi::day_qt_set_visible(cover.0, 0);
3696                    COVER_IDS.with(|m| m.borrow_mut().insert(cover.0 as usize, id));
3697                    let p = props_of::<CoverProps>(kind, "qt", props);
3698                    if p.is_some_and(|p| p.half) {
3699                        COVER_HALF.with(|s| s.borrow_mut().insert(cover.0 as usize));
3700                    }
3701                    if p.is_some_and(|p| (p.sheet || p.large) && !p.half) {
3702                        ffi::day_qt_cover_escape(cover.0, id.0, on_cover_escape);
3703                    }
3704                    cover
3705                }
3706                Some(Builtin::NavMenu) => {
3707                    let Some(p) = props_of::<NavMenuProps>(kind, "qt", props) else {
3708                        return placeholder_handle(kind);
3709                    };
3710                    let w = ffi::day_qt_navlist_new(id.0, nav_menu_changed);
3711                    // Keep the rows for `insert`, where a navigation suite above this menu can
3712                    // finally be found and handed them.
3713                    NAV_SUITE_ROWS.with(|m| {
3714                        m.borrow_mut().insert(
3715                            w as usize,
3716                            (
3717                                id,
3718                                p.items.clone(),
3719                                p.icons.clone(),
3720                                p.document_keys.clone(),
3721                            ),
3722                        )
3723                    });
3724                    // Parallel per-row icon file paths (empty entry = no icon): the bundled image
3725                    // NAME resolves to a loadable file path on the Rust side; the shim loads a
3726                    // QPixmap, tints it to the palette text color, and setIcon()s it. The
3727                    // trailing status glyph rides the same resolve-then-tint path as the leading
3728                    // icon; the shim's delegate paints it at the row's far edge.
3729                    let rows = NavRows {
3730                        items: p.items.clone(),
3731                        icons: p.icons.clone(),
3732                        tints: p.tints.clone(),
3733                        badge_icons: p.badge_icons.clone(),
3734                        badge_tints: p.badge_tints.clone(),
3735                        badges: p.badges.clone(),
3736                    };
3737                    let headings = apply_nav_rows(w, &rows, None, &p.sections);
3738                    navlist_apply_row_menus(w, &p.menus);
3739                    ffi::day_qt_navlist_set_selected(w, p.selected.map_or(-1, |i| i as c_int));
3740                    NAV_MENU_ROWS
3741                        .with(|m| m.borrow_mut().insert(w as usize, (p.items.len(), headings)));
3742                    QtHandle(w)
3743                }
3744                Some(Builtin::Scroll) => {
3745                    let p = props
3746                        .downcast_ref::<day_spec::props::ScrollProps>()
3747                        .cloned()
3748                        .unwrap_or_default();
3749                    let sa = ffi::day_qt_scroll_new(c_int::from(p.horizontal));
3750                    // The preferences (docs/scroll.md): hidden bars, and the emulated snap.
3751                    // `bounce` needs nothing: a Qt scroll area stops dead at its edges
3752                    // (`Some(false)` is how it always behaves) and has no overscroll effect to
3753                    // turn on. `zoom` and `keyboard_dismiss` are Unsupported; `track_phase` is
3754                    // left to the piece's emulation (no QScroller, so no native phases).
3755                    let (snap, interval) = match p.snap {
3756                        day_spec::props::ScrollSnap::None => (0, 0.0),
3757                        day_spec::props::ScrollSnap::Page => (1, 0.0),
3758                        day_spec::props::ScrollSnap::Interval(points) => (2, points),
3759                    };
3760                    let hidden = p.indicators == day_spec::props::ScrollIndicators::Hidden;
3761                    ffi::day_qt_scroll_configure(sa, c_int::from(hidden), snap, interval);
3762                    if p.track_offset {
3763                        ffi::day_qt_scroll_track_offset(sa, id.0, on_scroll_offset);
3764                    }
3765                    QtHandle(sa)
3766                }
3767                Some(Builtin::Label) => {
3768                    let Some(p) = props_of::<LabelProps>(kind, "qt", props) else {
3769                        return placeholder_handle(kind);
3770                    };
3771                    let w = ffi::day_qt_label_new(cstr(&p.text).as_ptr(), c_int::from(p.wraps));
3772                    ffi::day_qt_label_set_align(w, label_align(p.align));
3773                    apply_label_font(w, p.font);
3774                    apply_custom_family(w, p.font);
3775                    if p.font.monospace {
3776                        ffi::day_qt_label_set_monospace(w);
3777                    }
3778                    if p.color.is_some() {
3779                        apply_label_color(w, p.color);
3780                    }
3781                    remember_label_pt(w, p.font);
3782                    apply_paragraph(w, &p.paragraph());
3783                    apply_label_runs(w, &p.text, &p.runs);
3784                    if p.reports_selection {
3785                        ffi::day_qt_label_on_selection(w, id.0, on_text_selected);
3786                    }
3787                    // Wired unconditionally: runs can arrive later by patch, and connecting a
3788                    // signal on a label that never gets a link costs nothing.
3789                    ffi::day_qt_label_on_link(w, id.0, on_link);
3790                    passive(w)
3791                }
3792                Some(Builtin::Button) => {
3793                    let Some(p) = props_of::<ButtonProps>(kind, "qt", props) else {
3794                        return placeholder_handle(kind);
3795                    };
3796                    let w = ffi::day_qt_button_new(cstr(&p.title).as_ptr(), id.0, on_press);
3797                    ffi::day_qt_set_enabled(w, c_int::from(p.enabled));
3798                    ffi::day_qt_button_set_selected(w, c_int::from(p.selected));
3799                    apply_button_style_ink(w, p.style);
3800                    if p.icon.is_some() {
3801                        apply_button_content(w, &p.title, p.icon.as_ref(), p.icon_only);
3802                    }
3803                    ffi::day_qt_enable_focus(w, id.0, on_focus);
3804                    QtHandle(w)
3805                }
3806                Some(Builtin::Toggle) => {
3807                    let Some(p) = props_of::<ToggleProps>(kind, "qt", props) else {
3808                        return placeholder_handle(kind);
3809                    };
3810                    let w = ffi::day_qt_checkbox_new(c_int::from(p.on), id.0, on_toggle);
3811                    ffi::day_qt_set_enabled(w, c_int::from(p.enabled));
3812                    ffi::day_qt_enable_focus(w, id.0, on_focus);
3813                    QtHandle(w)
3814                }
3815                Some(Builtin::Slider) => {
3816                    let Some(p) = props_of::<SliderProps>(kind, "qt", props) else {
3817                        return placeholder_handle(kind);
3818                    };
3819                    RANGES.with(|r| r.insert(id.0 as usize, (p.min, p.max)));
3820                    let w = ffi::day_qt_slider_new(
3821                        slider_ticks(p.value, p.min, p.max),
3822                        id.0,
3823                        on_slider,
3824                    );
3825                    RANGES_BY_PTR.with(|r| r.insert(w as usize, (p.min, p.max)));
3826                    ffi::day_qt_enable_focus(w, id.0, on_focus);
3827                    QtHandle(w)
3828                }
3829                Some(Builtin::Picker) => picker::realize_any(self, props, id),
3830                Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
3831                Some(Builtin::TextField) => {
3832                    let Some(p) = props_of::<TextFieldProps>(kind, "qt", props) else {
3833                        return placeholder_handle(kind);
3834                    };
3835                    let w = ffi::day_qt_lineedit_new(
3836                        cstr(&p.text).as_ptr(),
3837                        cstr(&p.placeholder).as_ptr(),
3838                        id.0,
3839                        on_text,
3840                    );
3841                    ffi::day_qt_enable_focus(w, id.0, on_focus);
3842                    ffi::day_qt_lineedit_enable_field_keys(w, id.0, on_field_key);
3843                    QtHandle(w)
3844                }
3845                Some(Builtin::Divider) => {
3846                    let vertical = day_spec::props_of::<DividerProps>(kind, "qt", props)
3847                        .is_some_and(|p| p.vertical);
3848                    passive(ffi::day_qt_separator_new(c_int::from(vertical)))
3849                }
3850                Some(Builtin::Progress) => {
3851                    let Some(p) = props_of::<ProgressProps>(kind, "qt", props) else {
3852                        return placeholder_handle(kind);
3853                    };
3854                    if p.value.is_none() {
3855                        return crate::controls::spinner::make(self, p, id);
3856                    }
3857                    match p.value {
3858                        Some(v) => QtHandle(ffi::day_qt_progress_new(1, progress_ticks(v))),
3859                        None => QtHandle(ffi::day_qt_progress_new(0, 0)),
3860                    }
3861                }
3862                Some(Builtin::Canvas) => {
3863                    let w = ffi::day_qt_canvas_new();
3864                    // Focus, and with it the keyboard (docs/menus.md, docs/focus.md): a canvas
3865                    // is the one built-in piece with no native control under it, so nothing
3866                    // else would ever make it the focus widget.
3867                    ffi::day_qt_enable_keys(w, id.0, on_key);
3868                    ffi::day_qt_enable_focus(w, id.0, on_focus);
3869                    passive(w)
3870                }
3871                Some(Builtin::Image) => {
3872                    let Some(p) = props_of::<ImageProps>(kind, "qt", props) else {
3873                        return placeholder_handle(kind);
3874                    };
3875                    // Scaling: 0=fit, 1=fill (crop), 2=stretch.
3876                    let mode = match p.content_mode {
3877                        ContentMode::Fit => 0,
3878                        ContentMode::Fill => 1,
3879                        ContentMode::Stretch => 2,
3880                    };
3881                    let image = match &p.source {
3882                        // The staged-asset path: only a NAMED source resolves to a file, and only
3883                        // a file can be tinted — a recolor re-renders the glyph from its source.
3884                        day_spec::ImageSource::Named(named) => {
3885                            // Prefer vector geometry; ordinary images keep their native Qt resource path.
3886                            let res_path = format!(":/day/images/{named}");
3887                            let path = if let Some(svg) =
3888                                day_spec::resource::resolve_vector_svg(named)
3889                            {
3890                                svg.to_string_lossy().into_owned()
3891                            } else if ffi::day_qt_resource_exists(cstr(&res_path).as_ptr()) != 0 {
3892                                res_path
3893                            } else {
3894                                // The staged glyph SVG first (docs/vectors.md), the raster cache
3895                                // after — `icon_file_path`'s rule, so the piece and the icon
3896                                // channels agree.
3897                                icon_file_path(named)
3898                            };
3899                            // Vector-glyph tint (docs/vectors.md): the same SourceIn recolor the
3900                            // nav rows use, over a glyph the SVG engine renders at size. A
3901                            // template with no tint asks for the palette's text color
3902                            // (`currentColor`), which the shim re-applies on a palette change.
3903                            let tint = image_tint(p.tint.map(day_spec::Ink::resolved), p.template);
3904                            passive(ffi::day_qt_image_new(
3905                                cstr(&path).as_ptr(),
3906                                mode,
3907                                cstr(&tint).as_ptr(),
3908                            ))
3909                        }
3910                        // Bytes the app already holds — a download, a picked file, a paste — with
3911                        // no staged resource behind them (docs/images.md).
3912                        // An SVG among them takes the tint a staged glyph would (a template
3913                        // follows the palette); a raster is recolored by an explicit tint and
3914                        // otherwise draws as authored.
3915                        day_spec::ImageSource::Bytes(bytes) => {
3916                            let tint = image_tint(p.tint.map(day_spec::Ink::resolved), p.template);
3917                            passive(ffi::day_qt_image_new_bytes(
3918                                bytes.as_ptr(),
3919                                bytes.len() as c_int,
3920                                mode,
3921                                cstr(&tint).as_ptr(),
3922                            ))
3923                        }
3924                        // Already decoded: share the shim's one QImage rather than parsing twice.
3925                        day_spec::ImageSource::Decoded(id) => {
3926                            let tint = image_tint(p.tint.map(day_spec::Ink::resolved), false);
3927                            passive(ffi::day_qt_image_new_bitmap(
3928                                id.0,
3929                                mode,
3930                                cstr(&tint).as_ptr(),
3931                            ))
3932                        }
3933                    };
3934                    remember_inks(image.0, |i| i.image_tint = dynamic(p.tint));
3935                    image
3936                }
3937                Some(Builtin::Tree) => {
3938                    let Some(p) = props_of::<TreeProps>(kind, "qt", props) else {
3939                        return placeholder_handle(kind);
3940                    };
3941                    QtHandle(tree::new(id, p))
3942                }
3943                Some(Builtin::List) => {
3944                    let Some(p) = props_of::<ListProps>(kind, "qt", props) else {
3945                        return placeholder_handle(kind);
3946                    };
3947                    let (row_height, automatic) = match p.row_height {
3948                        RowHeight::Uniform(h) => (h, false),
3949                        RowHeight::Automatic => (44.0, true),
3950                    };
3951                    // A QListView over a count-only model (docs/list.md): selection, the
3952                    // keyboard walker and the drag-and-drop machinery are the view's; the
3953                    // guard and the commit of a reorder still run through Day's seam
3954                    // (`on_list_can_move`, `on_list_move`) so the app's own verdict decides
3955                    // every drop. Rows are bound as the window moves (`on_list_window`).
3956                    let separators = match p.separators {
3957                        None => -1,
3958                        Some(false) => 0,
3959                        Some(true) => 1,
3960                    };
3961                    let host = ffi::day_qt_list_new(
3962                        id.0,
3963                        row_height as c_int,
3964                        c_int::from(p.selectable),
3965                        c_int::from(p.multi_select),
3966                        c_int::from(p.reorderable),
3967                        separators,
3968                        on_list_selection,
3969                        on_list_activate,
3970                        on_list_can_move,
3971                        on_list_move,
3972                        on_list_window,
3973                    );
3974                    // A legacy scroll bar appearing or leaving resizes the viewport under
3975                    // the rows without the host moving: re-lay them to the width they have.
3976                    ffi::day_qt_list_on_viewport_resized(host, on_list_viewport_resized);
3977                    // The scrolls the reader starts (docs/list.md "Following the end").
3978                    ffi::day_qt_list_on_reader_scroll(host, on_list_reader_scroll);
3979                    // A sectioned list's headers size to their content even in a `Uniform`
3980                    // list (docs/list.md "Sections"), so its rows are not uniform either.
3981                    if automatic || p.sections {
3982                        ffi::day_qt_list_set_automatic(host);
3983                    }
3984                    LIST_STATE.with(|m| {
3985                        m.borrow_mut().insert(
3986                            host as usize,
3987                            ListEntry {
3988                                host,
3989                                row_height,
3990                                automatic,
3991                                source: Rc::new(RefCell::new(None)),
3992                                pool: CellPool::default(),
3993                                heights: HashMap::new(),
3994                                height_sum: 0.0,
3995                                estimate: row_height as c_int,
3996                                rebind_all: false,
3997                                frame_height: -1,
3998                                fill_pending: false,
3999                                last_width: -1,
4000                                cell_width: -1,
4001                                node: id.0,
4002                                multi: p.multi_select,
4003                                pin: None,
4004                                pin_row: None,
4005                                headers_for: None,
4006                                supplements_for: None,
4007                                supplement_heights: HashMap::new(),
4008                                pending: None,
4009                            },
4010                        )
4011                    });
4012                    LIST_BY_NODE.with(|m| m.borrow_mut().insert(id.0, host as usize));
4013                    QtHandle(host)
4014                }
4015                // A recycled list cell is ADOPTED from the native list, never realized
4016                // through this path; anything else is an extension piece.
4017                Some(Builtin::ListCell | Builtin::ListItem) | None => {
4018                    if let Some(make) = self.registry.get(kind).map(|r| r.make) {
4019                        return make(self, props, id);
4020                    }
4021                    warn_missing_renderer(kind);
4022                    placeholder_handle(kind)
4023                }
4024            }
4025        }
4026    }
4027
4028    fn update(
4029        &mut self,
4030        h: &QtHandle,
4031        kind: PieceKind,
4032        patch: &dyn std::any::Any,
4033        anim: Option<&AnimSpec>,
4034    ) {
4035        if let Some(patch) = patch.downcast_ref::<TreePatch>() {
4036            tree::patch(h.0 as usize, patch);
4037            return;
4038        }
4039        unsafe {
4040            match kind {
4041                kinds::IMAGE => {
4042                    if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
4043                        match p {
4044                            day_spec::props::ImagePatch::Tint(c) => {
4045                                // The shim remembers whether the glyph is a template, so a
4046                                // cleared tint lands back on the palette color rather than the
4047                                // authored art.
4048                                let tint = image_tint((*c).map(day_spec::Ink::resolved), false);
4049                                ffi::day_qt_image_set_tint(h.0, cstr(&tint).as_ptr());
4050                                remember_inks(h.0, |i| i.image_tint = dynamic(*c));
4051                            }
4052                            // A source swap repaints the same widget (docs/images.md), so an
4053                            // `image()` bound to a signal shows new pixels without rebuilding
4054                            // its subtree.
4055                            day_spec::props::ImagePatch::Source(source) => match source {
4056                                day_spec::ImageSource::Named(named) => {
4057                                    let res_path = format!(":/day/images/{named}");
4058                                    let path = if let Some(svg) =
4059                                        day_spec::resource::resolve_vector_svg(named)
4060                                    {
4061                                        svg.to_string_lossy().into_owned()
4062                                    } else if ffi::day_qt_resource_exists(cstr(&res_path).as_ptr())
4063                                        != 0
4064                                    {
4065                                        res_path
4066                                    } else {
4067                                        icon_file_path(named)
4068                                    };
4069                                    // The tint setter re-renders from the widget's recorded path,
4070                                    // so pointing it at the new file is the whole swap.
4071                                    ffi::day_qt_image_set_path(h.0, cstr(&path).as_ptr());
4072                                }
4073                                day_spec::ImageSource::Bytes(bytes) => {
4074                                    ffi::day_qt_image_set_bytes(
4075                                        h.0,
4076                                        bytes.as_ptr(),
4077                                        bytes.len() as c_int,
4078                                    );
4079                                }
4080                                day_spec::ImageSource::Decoded(id) => {
4081                                    ffi::day_qt_image_set_bitmap(h.0, id.0);
4082                                }
4083                            },
4084                        }
4085                    }
4086                }
4087                kinds::CONTAINER => {
4088                    let key = h.0 as usize;
4089                    match patch.downcast_ref::<ContainerPatch>() {
4090                        Some(ContainerPatch::Fill(fill)) => {
4091                            let mut p = SURFACES.with(|t| t.take(key)).unwrap_or_default();
4092                            p.fill.clone_from(fill);
4093                            match solid_fill(fill.as_ref()).filter(|_| p.role.is_none()) {
4094                                // Preserve the corner radius set at realize — a reactive
4095                                // `.background` must not square off a rounded surface.
4096                                // Animated from the fill shown when both ends are a fill
4097                                // (rule 8); a fill appearing or going away lands at once in
4098                                // the shim.
4099                                Some(bg) => with_qt_anim(anim, |anim| {
4100                                    ffi::day_qt_widget_set_bg(h.0, bg.r, bg.g, bg.b, bg.a, anim);
4101                                }),
4102                                // No fill, or a gradient: the whole surface, at once.
4103                                None => apply_surface(h.0, &p, false),
4104                            }
4105                            SURFACES.with(|t| t.insert(key, p));
4106                        }
4107                        // A reactive surface or a frame-relative radius (docs/surfaces.md
4108                        // "Reactive surfaces"): every field at once, applied at once; the
4109                        // role stays the realized one.
4110                        Some(ContainerPatch::Surface(next)) => {
4111                            let mut p = (**next).clone();
4112                            p.role = SURFACES.with(|t| t.get(key)).and_then(|old| old.role);
4113                            apply_surface(h.0, &p, false);
4114                            SURFACES.with(|t| t.insert(key, p));
4115                        }
4116                        None => {}
4117                    }
4118                }
4119                kinds::NAV_MENU => {
4120                    if let Some(NavMenuPatch::Items {
4121                        document_keys,
4122                        items,
4123                        icons,
4124                        tints,
4125                        menus,
4126                        badges,
4127                        badge_icons,
4128                        badge_tints,
4129                        sections,
4130                        selected,
4131                        rows_changed,
4132                        // `movable` is for toolkits whose own sidebar drags (Cap::NavReorder).
4133                        ..
4134                    }) = patch.downcast_ref::<NavMenuPatch>()
4135                    {
4136                        NAV_SUITE_ROWS.with(|m| {
4137                            if let Some(row) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4138                                row.1.clone_from(items);
4139                                row.2.clone_from(icons);
4140                                row.3 = document_keys.to_vec();
4141                            }
4142                        });
4143                        let host = ffi::day_qt_enclosing_tabs(h.0);
4144                        if !host.is_null() {
4145                            NAV_SUITES.with(|m| {
4146                                if let Some(s) = m.borrow_mut().get_mut(&(host as usize)) {
4147                                    s.titles.clone_from(items);
4148                                    s.icons.clone_from(icons);
4149                                    s.keys = document_keys.to_vec();
4150                                }
4151                            });
4152                            suite_apply_rows(host);
4153                        }
4154                        // Data-driven rows: rebuild the QListWidget from the new labels/icons
4155                        // (the same shim call realize uses), then apply the selection; the same
4156                        // rows with new words or counts update those rows in place.
4157                        let rows = NavRows {
4158                            items: items.clone(),
4159                            icons: icons.clone(),
4160                            tints: tints.clone(),
4161                            badge_icons: badge_icons.clone(),
4162                            badge_tints: badge_tints.clone(),
4163                            badges: badges.clone(),
4164                        };
4165                        if let Some(changed) = rows_changed {
4166                            apply_nav_rows(h.0, &rows, Some(changed), sections);
4167                            return;
4168                        }
4169                        let headings = apply_nav_rows(h.0, &rows, None, sections);
4170                        navlist_apply_row_menus(h.0, menus);
4171                        ffi::day_qt_navlist_set_selected(h.0, selected.map_or(-1, |i| i as c_int));
4172                        NAV_MENU_ROWS
4173                            .with(|m| m.borrow_mut().insert(h.0 as usize, (items.len(), headings)));
4174                    } else if let Some(NavMenuPatch::Selected(sel)) =
4175                        patch.downcast_ref::<NavMenuPatch>()
4176                    {
4177                        ffi::day_qt_navlist_set_selected(h.0, sel.map_or(-1, |i| i as c_int));
4178                    }
4179                }
4180                // Emulated cover (docs/cover.md): present = re-home + raise + opaque default
4181                // surface (palette Window color); dismiss = hide + report `CoverHidden` at
4182                // once. No interactive dismissal exists on this backend.
4183                kinds::COVER => {
4184                    if let Some(p) = patch.downcast_ref::<CoverPatch>() {
4185                        let node = COVER_IDS
4186                            .with(|m| m.borrow().get(&(h.0 as usize)).copied())
4187                            .unwrap_or(day_spec::WINDOW_NODE);
4188                        match p {
4189                            CoverPatch::Present { background, .. } => {
4190                                if let Some(bg) = background.map(day_spec::Ink::resolved) {
4191                                    ffi::day_qt_widget_set_bg(
4192                                        h.0,
4193                                        bg.r,
4194                                        bg.g,
4195                                        bg.b,
4196                                        bg.a,
4197                                        std::ptr::null(),
4198                                    );
4199                                }
4200                                remember_inks(h.0, |i| i.cover = dynamic(*background));
4201                                ffi::day_qt_add_child(self.window, h.0);
4202                                // A clear cover (a composed sheet's) lets the page show through.
4203                                let opaque = background.is_none_or(|bg| bg.resolved().a > 0.0);
4204                                ffi::day_qt_cover_top(h.0, c_int::from(opaque));
4205                                let (y, size) =
4206                                    cover_frame(h.0, LAST_WINDOW_SIZE.with(std::cell::Cell::get));
4207                                ffi::day_qt_set_geometry(
4208                                    h.0,
4209                                    0,
4210                                    y as c_int,
4211                                    size.width as c_int,
4212                                    size.height as c_int,
4213                                );
4214                                ffi::day_qt_set_visible(h.0, 1);
4215                                COVERS.with(|c| c.borrow_mut().push((h.0, node)));
4216                                emit(node, Event::FrameChanged(size));
4217                            }
4218                            CoverPatch::DismissDisabled(_) => {}
4219                            CoverPatch::Dismiss => {
4220                                ffi::day_qt_set_visible(h.0, 0);
4221                                COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
4222                                emit(node, Event::CoverHidden);
4223                            }
4224                        }
4225                    }
4226                }
4227                kinds::SPLIT => {
4228                    if let Some(p) = patch.downcast_ref::<SplitPatch>() {
4229                        let apply = SPLIT_STATE.with(|m| {
4230                            let mut m = m.borrow_mut();
4231                            let state = m.get_mut(&(h.0 as usize))?;
4232                            match p {
4233                                SplitPatch::Fraction(f) => state.share = f.clamp(0.0, 1.0),
4234                                SplitPatch::Axis(_) => {}
4235                            }
4236                            state.suppress = true;
4237                            Some((state.placed, state.share, state.min_pane))
4238                        });
4239                        if let Some((placed, share, min_pane)) = apply {
4240                            if let SplitPatch::Axis(axis) = p {
4241                                let vertical = *axis == day_spec::props::SplitAxis::Vertical;
4242                                ffi::day_qt_split_set_orientation(
4243                                    h.0,
4244                                    c_int::from(vertical),
4245                                    min_pane,
4246                                );
4247                            }
4248                            if placed {
4249                                ffi::day_qt_split_set_fraction(h.0, share);
4250                            }
4251                            SPLIT_STATE.with(|m| {
4252                                if let Some(state) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4253                                    state.suppress = false;
4254                                }
4255                            });
4256                            split_sync_panes(h.0);
4257                        }
4258                    }
4259                }
4260                kinds::INSPECTOR => {
4261                    if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>()
4262                    {
4263                        INSPECTOR_STATE.with(|m| {
4264                            if let Some(state) = m.borrow_mut().get_mut(&(h.0 as usize)) {
4265                                state.shown = *v;
4266                                ffi::day_qt_set_visible(state.panel_pane, c_int::from(*v));
4267                            }
4268                        });
4269                        // Deferred one turn, like the nav pop path: hiding a QSplitter pane
4270                        // does not resize its sibling until Qt runs its own layout pass.
4271                        let host_addr = h.0 as usize;
4272                        <Qt as Platform>::post(Box::new(move || {
4273                            inspector_sync_panes(host_addr as *mut std::os::raw::c_void);
4274                        }));
4275                    }
4276                }
4277                kinds::NAV => {
4278                    if let Some(p) = patch.downcast_ref::<day_spec::props::DocumentTabsPatch>() {
4279                        ffi::day_qt_tabs_chrome(h.0, c_int::from(p.native));
4280                        nav_suite_sync(h.0);
4281                        return;
4282                    }
4283                    if let Some(NavPatch::Reorder(order)) = patch.downcast_ref::<NavPatch>() {
4284                        NAV_SUITES.with(|m| {
4285                            let mut m = m.borrow_mut();
4286                            if let Some(s) = m.get_mut(&(h.0 as usize)) {
4287                                let old = s.pages.clone();
4288                                s.pages =
4289                                    order.iter().filter_map(|i| old.get(*i).copied()).collect();
4290                                for (i, (page, _)) in s.pages.iter().enumerate() {
4291                                    ffi::day_qt_tabs_move_page(h.0, page.0, i as c_int);
4292                                }
4293                            }
4294                        });
4295                        suite_apply_rows(h.0);
4296                        return;
4297                    }
4298                    if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
4299                        // A rail lands on the sidebar this backend does have: nothing in Qt is a
4300                        // vertical strip of icon-only destinations, and `NavPresentation::Rail` is
4301                        // ROUNDABLE for exactly that case (docs/size-classes.md) — the same call
4302                        // AppKit makes. What it shares with a split is the shape that matters
4303                        // here: rows beside the content.
4304                        let beside =
4305                            next.is_split() || *next == day_spec::props::NavPresentation::Rail;
4306                        nav_present(h.0, beside);
4307                        return;
4308                    }
4309                    // A navigation suite's resident-page switch (docs/navigation.md): the host
4310                    // is a QTabWidget with no `NAV_STATE` entry, so it is answered here, ahead
4311                    // of the split/stack block below — which returns early for it. (Until
4312                    // 2026-09-12 the suite branch sat inside that block and never ran, so a
4313                    // programmatic selection — a route, a deep link — left the bar on the
4314                    // first tab.) Destination i is tab i: the sidebar page is parked, never a
4315                    // tab. The newly shown page gets its size report at once.
4316                    if let Some(NavPatch::Select(i)) = patch.downcast_ref::<NavPatch>()
4317                        && NAV_SUITES.with(|m| m.borrow().contains_key(&(h.0 as usize)))
4318                    {
4319                        ffi::day_qt_tabs_set_current(h.0, *i as c_int);
4320                        nav_suite_sync(h.0);
4321                        return;
4322                    }
4323                    if let Some(p) = patch.downcast_ref::<NavPatch>() {
4324                        // A pane shown or hidden outside the borrow below: Qt resizes the
4325                        // sibling panes synchronously, the pane filter reports them, and
4326                        // that report reads `NAV_STATE` — a re-entrant borrow otherwise.
4327                        let mut list_apply: Option<(*mut c_void, bool, Option<f64>)> = None;
4328                        NAV_STATE.with(|m| {
4329                            let mut m = m.borrow_mut();
4330                            let Some(state) = m.get_mut(&(h.0 as usize)) else {
4331                                return;
4332                            };
4333                            // Split: the sidebar's page is not part of the detail stack.
4334                            // Stack: every page participates, its root included. The list
4335                            // page never is; its pane persists at every presentation.
4336                            let split_now = state.split;
4337                            let detail: Vec<(QtHandle, NodeId)> = state
4338                                .pages
4339                                .iter()
4340                                .filter(|(p, _)| {
4341                                    !(split_now && is_sidebar_page(p.0) || is_list_page(p.0))
4342                                })
4343                                .copied()
4344                                .collect();
4345                            let detail = &detail[..];
4346                            match p {
4347                                NavPatch::Pushed { title, .. } => {
4348                                    let last = detail.len().saturating_sub(1);
4349                                    for (i, (page, _)) in detail.iter().enumerate() {
4350                                        ffi::day_qt_set_visible(page.0, (i == last).into());
4351                                    }
4352                                    state.titles.push(title.clone());
4353                                }
4354                                NavPatch::Popped => {
4355                                    let n = detail.len();
4356                                    if let Some((top, _)) = detail.last() {
4357                                        ffi::day_qt_set_visible(top.0, 0);
4358                                    }
4359                                    if n >= 2 {
4360                                        ffi::day_qt_set_visible(detail[n - 2].0.0, 1);
4361                                    }
4362                                    if state.titles.len() > 1 {
4363                                        state.titles.pop();
4364                                    }
4365                                }
4366                                NavPatch::Title(t) => {
4367                                    if let Some(last) = state.titles.last_mut() {
4368                                        last.clone_from(t);
4369                                    }
4370                                }
4371                                // Custom back header → always NavBack{already_popped:false};
4372                                // no native auto-pop to suppress (docs/navigation.md).
4373                                #[expect(
4374                                    clippy::match_same_arms,
4375                                    reason = "each group of no-op patches keeps its own arm and the comment saying why"
4376                                )]
4377                                NavPatch::GuardTop(_) | NavPatch::Reorder(_) => {}
4378                                // Handled before this borrow (it re-parents widgets).
4379                                #[expect(
4380                                    clippy::match_same_arms,
4381                                    reason = "each group of no-op patches keeps its own arm and the comment saying why"
4382                                )]
4383                                NavPatch::Presentation(_) => {}
4384                                // The resident-page switch (docs/navigation.md): the app moved the
4385                                // selection, so the suite shows that destination.
4386                                NavPatch::Select(i) => {
4387                                    // The resident-page switch (docs/navigation.md) on a
4388                                    // split — which is also what a ROUNDED `Rail` lands on
4389                                    // here, Qt having no rail widget: show destination `i`
4390                                    // and hide its siblings. A suite's switch was answered
4391                                    // above, before this block.
4392                                    for (n, (page, _)) in detail.iter().enumerate() {
4393                                        ffi::day_qt_set_visible(page.0, c_int::from(n == *i));
4394                                    }
4395                                }
4396                                // Show or collapse the content-list pane (docs/navigation.md).
4397                                // The sibling panes take their new widths on Qt's next layout
4398                                // pass, so the frame report is deferred one turn below, like
4399                                // a pop's.
4400                                NavPatch::ListVisible(v) => {
4401                                    state.list_shown = *v;
4402                                    if state.list_width.is_some() {
4403                                        // First time on screen: the width the app asked for.
4404                                        // The constructor sized a pane that was showing; one
4405                                        // hidden since then still holds its placeholder.
4406                                        let place = if *v && !state.list_positioned {
4407                                            state.list_positioned = true;
4408                                            state.list_width
4409                                        } else {
4410                                            None
4411                                        };
4412                                        list_apply = Some((state.list_pane, *v, place));
4413                                    }
4414                                }
4415                                // Never arrives: the pane persists through every presentation
4416                                // (`Cap::NavContentList` = Native), so the pieces layer never
4417                                // asks for the merged-stack shape.
4418                                NavPatch::ListInStack(_) => {}
4419                            }
4420                        });
4421                        if let Some((pane, shown, place)) = list_apply {
4422                            ffi::day_qt_set_visible(pane, c_int::from(shown));
4423                            if let Some(w) = place {
4424                                ffi::day_qt_splitter_set_pane_width(h.0, 1, w);
4425                            }
4426                        }
4427                        // Header visibility follows the depth after the pop completes (the
4428                        // popped page leaves `pages` via remove()); defer one turn so the
4429                        // header + page sizes settle against the final stack. The raw QWidget
4430                        // pointer crosses the (main-thread-only) post as usize. The same
4431                        // deferral gives a shown or hidden list pane its settled sizes.
4432                        let host = h.0 as usize;
4433                        <Qt as Platform>::post(Box::new(move || {
4434                            nav_sync_header(host as *mut std::os::raw::c_void);
4435                        }));
4436                    }
4437                }
4438                kinds::LABEL => {
4439                    if let Some(p) = patch.downcast_ref::<LabelPatch>() {
4440                        match p {
4441                            LabelPatch::Paragraph(p) => apply_paragraph(h.0, p),
4442                            LabelPatch::Text(t) => {
4443                                ffi::day_qt_label_set_text(h.0, cstr(t).as_ptr());
4444                                remember_inks(h.0, |i| i.label_runs = None);
4445                            }
4446                            LabelPatch::Font(f) => {
4447                                apply_label_font(h.0, *f);
4448                                apply_custom_family(h.0, *f);
4449                                remember_label_pt(h.0, *f);
4450                            }
4451                            LabelPatch::Runs(text, runs) => apply_label_runs(h.0, text, runs),
4452                            LabelPatch::Color(c) => apply_label_color(h.0, *c),
4453                        }
4454                    }
4455                }
4456                kinds::BUTTON => {
4457                    if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
4458                        match p {
4459                            ButtonPatch::Content(c) => {
4460                                apply_button_content(h.0, &c.title, c.icon.as_ref(), c.icon_only);
4461                            }
4462                            ButtonPatch::Title(t) => {
4463                                ffi::day_qt_button_set_title(h.0, cstr(t).as_ptr());
4464                            }
4465                            ButtonPatch::Enabled(e) => {
4466                                ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4467                            }
4468                            ButtonPatch::Selected(on) => {
4469                                ffi::day_qt_button_set_selected(h.0, c_int::from(*on));
4470                            }
4471                            ButtonPatch::Style(s) => apply_button_style_ink(h.0, *s),
4472                        }
4473                    }
4474                }
4475                kinds::TOGGLE => {
4476                    if let Some(p) = patch.downcast_ref::<TogglePatch>() {
4477                        match p {
4478                            TogglePatch::On(on) => ffi::day_qt_checkbox_set(h.0, c_int::from(*on)),
4479                            TogglePatch::Enabled(e) => {
4480                                ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4481                            }
4482                        }
4483                    }
4484                }
4485                kinds::SLIDER => {
4486                    if let Some(p) = patch.downcast_ref::<SliderPatch>() {
4487                        match p {
4488                            SliderPatch::Value(v) => {
4489                                let (min, max) = RANGES_BY_PTR
4490                                    .with(|r| r.get(h.0 as usize))
4491                                    .unwrap_or((0.0, 1.0));
4492                                ffi::day_qt_slider_set(h.0, slider_ticks(*v, min, max));
4493                            }
4494                            SliderPatch::Enabled(e) => {
4495                                ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4496                            }
4497                        }
4498                    }
4499                }
4500                kinds::PROGRESS => {
4501                    if let Some(p @ ProgressPatch::Animating(_)) =
4502                        patch.downcast_ref::<ProgressPatch>()
4503                    {
4504                        crate::controls::spinner::update(self, h, p);
4505                        return;
4506                    }
4507
4508                    if let Some(ProgressPatch::Value(Some(v))) =
4509                        patch.downcast_ref::<ProgressPatch>()
4510                    {
4511                        ffi::day_qt_progress_set(h.0, progress_ticks(*v));
4512                    }
4513                }
4514                kinds::PICKER => picker::update_any(self, *h, patch),
4515                kinds::TEXT_AREA => textarea::update_any(self, *h, patch),
4516                kinds::TEXT_FIELD => {
4517                    if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
4518                        match p {
4519                            TextFieldPatch::Text { text, from_native } => {
4520                                if !*from_native {
4521                                    ffi::day_qt_lineedit_set_text(h.0, cstr(text).as_ptr());
4522                                }
4523                            }
4524                            TextFieldPatch::Placeholder(t) => {
4525                                ffi::day_qt_lineedit_set_placeholder(h.0, cstr(t).as_ptr());
4526                            }
4527                            TextFieldPatch::Enabled(e) => {
4528                                ffi::day_qt_set_enabled(h.0, c_int::from(*e));
4529                            }
4530                            TextFieldPatch::Select(sel) => {
4531                                let at = |n: usize| n.min(c_int::MAX as usize) as c_int;
4532                                ffi::day_qt_lineedit_select(h.0, at(sel.start), at(sel.end));
4533                            }
4534                        }
4535                    }
4536                }
4537                kinds::LIST => match patch.downcast_ref::<ListPatch>() {
4538                    Some(ListPatch::Reload) => queue_rows(h.0 as usize, RowWork::Reload),
4539                    // Row deltas as model deltas: selection and the current row follow.
4540                    Some(ListPatch::Splice(deltas)) => {
4541                        queue_rows(h.0 as usize, RowWork::Splice(deltas.clone()));
4542                    }
4543                    Some(ListPatch::ScrollToEnd) => schedule_list_scroll_end(h.0 as usize),
4544                    Some(ListPatch::ScrollToRow(row)) => {
4545                        schedule_list_scroll_row(h.0 as usize, *row);
4546                    }
4547                    Some(ListPatch::Selected(rows)) => {
4548                        // Programmatic selection sync (empty = clear): the view repaints and
4549                        // does not report it back.
4550                        let rows: Vec<c_int> = rows.iter().map(|r| *r as c_int).collect();
4551                        ffi::day_qt_list_set_selected(h.0, rows.as_ptr(), rows.len() as c_int);
4552                    }
4553                    Some(ListPatch::RowSizeInvalidated { cell, height }) => {
4554                        schedule_list_row_height(h.0 as usize, *cell, *height);
4555                    }
4556                    // No editing mode (Cap::ListEditing is Unsupported).
4557                    Some(ListPatch::Editing(_)) | None => {}
4558                },
4559                _ => {
4560                    if let Some(update) = self.registry.get(kind).map(|r| r.update) {
4561                        update(self, h, patch);
4562                    }
4563                }
4564            }
4565        }
4566    }
4567
4568    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
4569    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
4570        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
4571        // the hook needs it mutably.
4572        let f = self.registry.get(kind).and_then(|r| r.release);
4573        if let Some(f) = f {
4574            f(self, h);
4575        }
4576    }
4577    fn release(&mut self, h: QtHandle) {
4578        // A released window content = that window is gone (docs/windows.md teardown):
4579        // Now destroy the whole DayWindow (deleteLater — after this event dispatch), never
4580        // before, so day's child-widget releases can't touch freed memory.
4581        let toolbars = &mut self.toolbars;
4582        self.secondary.retain(|w| {
4583            if w.content == h.0 {
4584                #[cfg(target_os = "macos")]
4585                day_platform_macos::window_tabs::unregister(w.id);
4586                toolbars.remove(&(w.win as usize));
4587                unsafe { ffi::day_qt_window_destroy(w.win) };
4588                false
4589            } else {
4590                true
4591            }
4592        });
4593        let key = h.0 as usize;
4594        tree::release(key);
4595        if let Some(entry) = LIST_STATE.with(|m| m.borrow_mut().remove(&key)) {
4596            LIST_BY_NODE.with(|m| {
4597                m.borrow_mut().remove(&entry.node);
4598            });
4599            // The pinned header's cell is Day's row like any other (docs/list.md "Sections"):
4600            // give it back; its widget goes with the view.
4601            let source = entry.source.borrow().clone();
4602            if let (Some(pin), Some(source)) = (entry.pin, source) {
4603                (source.release)(pin as *mut c_void);
4604            }
4605        }
4606        // A disposed nav host / page must drop its NAV_STATE / NAV_PAGE_IDS entry — otherwise a
4607        // later widget that reuses the freed address is mistaken for a nav host in `set_frame`,
4608        // and `nav_sync_panes` reads its freed panes (a use-after-free SIGSEGV).
4609        NAV_STATE.with(|m| {
4610            m.borrow_mut().remove(&key);
4611        });
4612        NAV_PAGE_IDS.with(|m| {
4613            m.borrow_mut().remove(&key);
4614        });
4615        NAV_MENU_ROWS.with(|m| {
4616            m.borrow_mut().remove(&key);
4617        });
4618        SPLIT_STATE.with(|m| {
4619            m.borrow_mut().remove(&key);
4620        });
4621        SPLIT_PANE_IDS.with(|m| {
4622            m.borrow_mut().remove(&key);
4623        });
4624        // The same use-after-free rule for a disposed inspector split and its panes.
4625        INSPECTOR_STATE.with(|m| {
4626            m.borrow_mut().remove(&key);
4627        });
4628        INSPECTOR_PANE_IDS.with(|m| {
4629            m.borrow_mut().remove(&key);
4630        });
4631        // Same rule for the navigation suite's three tables: a freed QTabWidget whose address is
4632        // reused would otherwise inherit the old suite's destination pages, and report sizes to
4633        // node ids that no longer exist.
4634        NAV_SUITES.with(|m| {
4635            m.borrow_mut().remove(&key);
4636        });
4637        NAV_SUITE_ROWS.with(|m| {
4638            m.borrow_mut().remove(&key);
4639        });
4640        NAV_SUITE_PAGES.with(|m| {
4641            m.borrow_mut().remove(&key);
4642        });
4643        GESTURES.with(|g| {
4644            g.borrow_mut().retain(|(ptr, _)| *ptr != key);
4645        });
4646        // A cover torn down while presented (no Dismiss patch first) must leave the
4647        // presented set — `window_resized` writes through every entry's raw pointer, and a
4648        // stale one is a use-after-free once `day_qt_delete` runs below.
4649        COVERS.with(|c| c.borrow_mut().retain(|(w, _)| *w != h.0));
4650        COVER_HALF.with(|s| s.borrow_mut().remove(&(h.0 as usize)));
4651        COVER_IDS.with(|m| {
4652            m.borrow_mut().remove(&key);
4653        });
4654        // One sweep drops this handle from every SideTable registered on this thread — the
4655        // slider ranges, the tab icons, the textarea line bands, and any table added later —
4656        // so a widget recycling the freed address can't inherit the dead widget's entries.
4657        // (The explicit purges above stay: they key by node id / value pairs, not this address.)
4658        day_spec::sidetable::sweep(key);
4659        unsafe {
4660            ffi::day_qt_remove_child(h.0);
4661            ffi::day_qt_delete(h.0);
4662        }
4663    }
4664
4665    fn insert(&mut self, parent: &QtHandle, child: &QtHandle, index: usize) {
4666        // An emulated cover (docs/cover.md) is parked hidden at realize and surfaces only
4667        // through `CoverPatch::Present`, which re-homes it onto the window. `day_qt_add_child`
4668        // shows whatever it parents, so a cover inserted like any other child came back at
4669        // Qt's 640x480 default geometry over the page's top-left corner: nothing to see (no
4670        // fill), but in front of the sidebar, taking every click meant for it. Parent it for
4671        // ownership only, and leave it parked.
4672        if COVER_IDS.with(|m| m.borrow().contains_key(&(child.0 as usize))) {
4673            unsafe {
4674                ffi::day_qt_add_child(content_of(parent), child.0);
4675                ffi::day_qt_set_visible(child.0, 0);
4676            }
4677            return;
4678        }
4679        // Navigation suite: every destination becomes a tab. Day's nav host keeps its menu as
4680        // child 0, inside the SIDEBAR page whose rows became the bar; that page is parked under
4681        // the widget (so the menu keeps a parent chain up to the suite) and never a tab, because
4682        // drawing the rows again as a list would be the same navigation twice. So destination
4683        // i, Day's child i + 1, is tab i.
4684        let suite_handled = NAV_SUITES.with(|m| {
4685            let mut m = m.borrow_mut();
4686            let Some(suite) = m.get_mut(&(parent.0 as usize)) else {
4687                return false;
4688            };
4689            unsafe {
4690                if index == 0 {
4691                    ffi::day_qt_tabs_park(parent.0, child.0);
4692                } else {
4693                    ffi::day_qt_tabs_add_page(
4694                        parent.0,
4695                        child.0,
4696                        cstr("").as_ptr(),
4697                        (index - 1) as c_int,
4698                    );
4699                    let id = NAV_PAGE_IDS
4700                        .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4701                        .unwrap_or(NodeId(0));
4702                    suite.pages.push((*child, id));
4703                    // The first destination claims the content area (insertion is silent).
4704                    if suite.pages.len() == 1 {
4705                        ffi::day_qt_tabs_set_current(parent.0, 0);
4706                    }
4707                }
4708                NAV_SUITE_PAGES.with(|m| m.borrow_mut().insert(child.0 as usize));
4709            }
4710            true
4711        });
4712        if suite_handled {
4713            suite_apply_rows(parent.0);
4714            nav_suite_sync(parent.0);
4715            return;
4716        }
4717        // A nav menu that has just gained a parent chain: if a suite is above it, its rows are
4718        // that suite's bar. Labels and glyphs both, in row order.
4719        if let Some((node, titles, icons, keys)) =
4720            NAV_SUITE_ROWS.with(|m| m.borrow().get(&(child.0 as usize)).cloned())
4721        {
4722            let suite = unsafe { ffi::day_qt_enclosing_tabs(parent.0) };
4723            if !suite.is_null() {
4724                NAV_SUITES.with(|m| {
4725                    if let Some(s) = m.borrow_mut().get_mut(&(suite as usize)) {
4726                        s.menu_node = node;
4727                        s.titles = titles;
4728                        s.icons = icons;
4729                        s.keys = keys;
4730                    }
4731                });
4732                suite_apply_rows(suite);
4733            }
4734        }
4735        // Nav host: pages land by their PANE, not their position (docs/size-classes.md).
4736        let sidebar = is_sidebar_page(child.0);
4737        let list = is_list_page(child.0);
4738        let handled = NAV_STATE.with(|m| {
4739            let mut m = m.borrow_mut();
4740            let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4741                return false;
4742            };
4743            let id = NAV_PAGE_IDS
4744                .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4745                .unwrap_or(NodeId(0));
4746            if sidebar {
4747                state.sidebar_page = Some(*child);
4748            }
4749            if list {
4750                state.list_page = Some(*child);
4751            }
4752            // The content-list page fills its own pane at every presentation
4753            // (docs/navigation.md) — never a member of the detail stack.
4754            let pane = if list {
4755                state.list_pane
4756            } else if state.split && sidebar {
4757                state.sidebar_pane
4758            } else {
4759                state.detail_pane
4760            };
4761            unsafe { ffi::day_qt_add_child(pane, child.0) };
4762            state.pages.push((*child, id));
4763            true
4764        });
4765        if handled {
4766            nav_sync_panes(parent.0);
4767            return;
4768        }
4769        // Split host: the pane's own record says which pane it is (docs/split.md).
4770        let split_pane = SPLIT_STATE.with(|m| {
4771            let mut m = m.borrow_mut();
4772            let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4773                return false;
4774            };
4775            let (pane_id, second) = SPLIT_PANE_IDS
4776                .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4777                .unwrap_or((NodeId(0), index == 1));
4778            let pane = if second {
4779                state.second_pane
4780            } else {
4781                state.first_pane
4782            };
4783            unsafe { ffi::day_qt_add_child(pane, child.0) };
4784            state.panes.push((pane_id, second));
4785            true
4786        });
4787        if split_pane {
4788            split_sync_panes(parent.0);
4789            return;
4790        }
4791        // Inspector host: the pane's own record says which side it is (docs/inspector.md).
4792        let inspected = INSPECTOR_STATE.with(|m| {
4793            let mut m = m.borrow_mut();
4794            let Some(state) = m.get_mut(&(parent.0 as usize)) else {
4795                return false;
4796            };
4797            let (pane_id, panel) = INSPECTOR_PANE_IDS
4798                .with(|ids| ids.borrow().get(&(child.0 as usize)).copied())
4799                .unwrap_or((NodeId(0), index == 1));
4800            let pane = if panel {
4801                state.panel_pane
4802            } else {
4803                state.content_pane
4804            };
4805            unsafe { ffi::day_qt_add_child(pane, child.0) };
4806            state.panes.push((pane_id, panel));
4807            true
4808        });
4809        if inspected {
4810            inspector_sync_panes(parent.0);
4811        } else {
4812            unsafe { ffi::day_qt_add_child(content_of(parent), child.0) };
4813        }
4814    }
4815
4816    fn remove(&mut self, parent: &QtHandle, child: &QtHandle) {
4817        PAGE_PANE.with(|m| m.borrow_mut().remove(&(child.0 as usize)));
4818        NAV_STATE.with(|m| {
4819            if let Some(state) = m.borrow_mut().get_mut(&(parent.0 as usize)) {
4820                state.pages.retain(|(p, _)| p.0 != child.0);
4821                if state.sidebar_page.map(|p| p.0) == Some(child.0) {
4822                    state.sidebar_page = None;
4823                }
4824                if state.list_page.map(|p| p.0) == Some(child.0) {
4825                    state.list_page = None;
4826                }
4827            }
4828        });
4829        // A suite destination leaving: drop its tab too (removeTab keeps the widget, which
4830        // Day owns and disposes).
4831        let in_suite = NAV_SUITES.with(|m| {
4832            if let Some(suite) = m.borrow_mut().get_mut(&(parent.0 as usize)) {
4833                suite.pages.retain(|(p, _)| p.0 != child.0);
4834                true
4835            } else {
4836                false
4837            }
4838        });
4839        if in_suite {
4840            unsafe { ffi::day_qt_tabs_remove_page(parent.0, child.0) };
4841        }
4842        unsafe { ffi::day_qt_remove_child(child.0) };
4843    }
4844
4845    fn move_child(&mut self, _parent: &QtHandle, _child: &QtHandle, _to: usize) {}
4846
4847    fn measure(&mut self, h: &QtHandle, kind: PieceKind, p: Proposal) -> Size {
4848        let mut w = 0.0;
4849        let mut hh = 0.0;
4850        // A label's sizeHint() is a full rich-text layout at Qt's own wrap heuristic, and the
4851        // label arm below never uses it except as a last resort: ask only then.
4852        if kind != kinds::LABEL {
4853            unsafe { ffi::day_qt_size_hint(h.0, &raw mut w, &raw mut hh) };
4854        }
4855        match kind {
4856            kinds::NAV_MENU => {
4857                let (rows, headings) = NAV_MENU_ROWS
4858                    .with(|m| m.borrow().get(&(h.0 as usize)).copied().unwrap_or((0, 0)));
4859                // A heading band is its caption plus the gap above it (shim.cpp,
4860                // day_qt_navlist_set_items); left uncounted, a sectioned sidebar under-reports by
4861                // a band per group.
4862                Size::new(
4863                    p.width.unwrap_or(220.0),
4864                    p.height
4865                        .unwrap_or(rows as f64 * 34.0 + headings as f64 * 30.0 + 8.0),
4866                )
4867            }
4868            kinds::LABEL => {
4869                // Natural width from font metrics — QLabel::sizeHint() suggests a narrow
4870                // "readable column" for word-wrapped labels, which is not day's contract
4871                // (natural = unwrapped). Height always via heightForWidth at the width day
4872                // actually grants; sizeHint's heuristic height is never mixed in.
4873                let nat_w = f64::from(unsafe { ffi::day_qt_label_natural_width(h.0) });
4874                let width = match p.width {
4875                    Some(pw) => nat_w.min(pw),
4876                    None => nat_w,
4877                };
4878                let hfw = unsafe {
4879                    ffi::day_qt_label_height_for_width(h.0, width.round().max(1.0) as c_int)
4880                };
4881                if hfw > 0 {
4882                    Size::new(width.ceil(), f64::from(hfw))
4883                } else {
4884                    unsafe { ffi::day_qt_size_hint(h.0, &raw mut w, &raw mut hh) };
4885                    Size::new(width.ceil(), hh.ceil())
4886                }
4887            }
4888            // Buttons hug their text (sizeHint = content + chrome) like every other
4889            // toolkit: the generic arm would swallow a COLUMN's cross-axis width proposal
4890            // and stretch the button across the full content span.
4891            kinds::BUTTON => Size::new(w.ceil(), hh.ceil()),
4892            kinds::SLIDER => Size::new(p.width.unwrap_or(180.0), hh.max(20.0)),
4893            kinds::PICKER => picker::measure_any(self, *h, p),
4894            kinds::TEXT_AREA => textarea::measure_any(self, *h, p),
4895            kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(180.0), hh.max(24.0)),
4896            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 2.0),
4897            kinds::PROGRESS => Size::new(p.width.unwrap_or(180.0), hh.max(16.0)),
4898            kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
4899            _ => {
4900                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
4901                    measure(self, h, p)
4902                } else {
4903                    Size::new(p.width.unwrap_or(w), p.height.unwrap_or(hh))
4904                }
4905            }
4906        }
4907    }
4908
4909    fn set_opacity(&mut self, h: &QtHandle, opacity: f64, anim: Option<&AnimSpec>) {
4910        // Opacity + transform share one custom QGraphicsEffect per widget (see the shim); an
4911        // animated change plays as a run on Qt's animation framework (`QtAnim`).
4912        // SAFETY: `h` is a live widget Day realized; the run is alive for the call.
4913        with_qt_anim(anim, |anim| unsafe {
4914            ffi::day_qt_set_opacity(h.0, opacity, anim);
4915        });
4916    }
4917
4918    fn set_transform(&mut self, h: &QtHandle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
4919        // The effect re-draws the widget through a painter transformed about its center, spilling
4920        // beyond the widget's own frame (§8.4) so a moved/scaled/rotated box isn't clipped.
4921        // SAFETY: as in `set_opacity`.
4922        with_qt_anim(anim, |anim| unsafe {
4923            ffi::day_qt_set_transform(h.0, t.tx, t.ty, t.sx, t.sy, t.rotation.degrees(), anim);
4924        });
4925    }
4926
4927    /// What the widget shows now: the shim's runs write the `DayEffect`, the geometry and the
4928    /// fill on every tick, so these are the in-flight values; at rest, the model's.
4929    fn read_displayed(&self, h: &QtHandle) -> day_spec::Displayed {
4930        if h.0.is_null() {
4931            return day_spec::Displayed::default();
4932        }
4933        let mut d = ffi::DayQtDisplayed::default();
4934        // SAFETY: `h` is a live widget Day realized; the shim writes every field of `d`.
4935        unsafe { ffi::day_qt_read_displayed(h.0, &raw mut d) };
4936        day_spec::Displayed {
4937            opacity: Some(d.opacity),
4938            frame: (d.frame_ok != 0).then(|| Rect::new(d.x, d.y, d.w, d.h)),
4939            translation: Some(day_spec::Point::new(d.tx, d.ty)),
4940            background: (d.fill_ok != 0).then(|| day_spec::Color::rgba(d.r, d.g, d.b, d.a)),
4941        }
4942    }
4943
4944    fn set_cursor(&mut self, h: &QtHandle, cursor: Cursor) {
4945        // `QWidget::setCursor(Qt::CursorShape)`, or `unsetCursor` for Default (docs/cursor.md).
4946        // Qt has no zoom, cell, copy-drop, context-menu, or vertical-text shape; each takes its
4947        // nearest, which is why `Cap::Cursor` answers Emulated.
4948        unsafe { ffi::day_qt_widget_set_cursor(h.0, qt_cursor_shape(&cursor)) };
4949    }
4950
4951    fn set_input_traits(&mut self, h: &QtHandle, traits: &InputTraits) -> Option<QtHandle> {
4952        // One QLineEdit serves every trait as a property (docs/textfield.md), so the widget,
4953        // its signal wiring, its focus and its caret all stay. The shim qobject_casts to
4954        // QLineEdit, so a non-field handle is a safe no-op.
4955        //
4956        // Two members stay on the Rust side. `submit_label`: QLineEdit has no setter for the
4957        // enter-key type (only Qt Quick exposes one). `max_length`: `QLineEdit::setMaxLength`
4958        // counts UTF-16 code units where day-pieces counts characters, so a native limit would
4959        // refuse text the bound allows (five emoji are ten units); day-pieces holds it alone.
4960        unsafe {
4961            ffi::day_qt_lineedit_set_traits(
4962                h.0,
4963                c_int::from(traits.secure),
4964                c_int::from(traits.read_only),
4965                qt_input_purpose(traits.purpose),
4966            );
4967        };
4968        None
4969    }
4970
4971    fn set_selectable(&mut self, h: &QtHandle, selectable: bool) -> Option<QtHandle> {
4972        // The shim casts to Day's label, so a non-label handle is a safe no-op (docs/text.md).
4973        unsafe { ffi::day_qt_label_set_selectable(h.0, c_int::from(selectable)) };
4974        None
4975    }
4976
4977    /// The screen's logical DPI against the platform's reference: what the desktop's text-size
4978    /// setting (GNOME's text-scaling-factor, KDE's forced font DPI, both through `Xft.dpi`)
4979    /// does to Day's point-sized fonts. 1.0 on macOS, which has no such setting.
4980    fn text_scale(&mut self, _style: Font) -> f64 {
4981        // SAFETY: reads the primary screen's DPI; called on the UI thread after `run` built the
4982        // QApplication (and answers 1.0 when there is no screen).
4983        unsafe { ffi::day_qt_text_scale() }
4984    }
4985
4986    /// `QWidget::setLayoutDirection` on the widget itself. Day's containers have no Qt layout,
4987    /// so the direction never moves a child Day placed; hosts whose Qt widget mirrors its own
4988    /// coordinates (scroll areas, splitters, lists, trees) are skipped, and so is the canvas,
4989    /// which draws in its own coordinates.
4990    fn set_layout_direction(
4991        &mut self,
4992        h: &QtHandle,
4993        kind: PieceKind,
4994        direction: day_spec::LayoutDirection,
4995    ) {
4996        if matches!(
4997            kind,
4998            kinds::CONTAINER
4999                | kinds::SCROLL
5000                | kinds::CANVAS
5001                | kinds::IMAGE
5002                | kinds::NAV
5003                | kinds::NAV_PAGE
5004                | kinds::NAV_MENU
5005                | kinds::LIST
5006                | kinds::LIST_CELL
5007                | kinds::TREE
5008                | kinds::COVER
5009                | kinds::INSPECTOR
5010                | kinds::INSPECTOR_PANE
5011                | kinds::SPLIT
5012                | kinds::SPLIT_PANE
5013        ) || h.0.is_null()
5014        {
5015            return;
5016        }
5017        let rtl = c_int::from(direction == day_spec::LayoutDirection::Rtl);
5018        // SAFETY: `h` is a live widget Day realized.
5019        unsafe { ffi::day_qt_widget_set_direction(h.0, rtl) };
5020    }
5021
5022    /// Derived from the widget's own font metrics in the shim (docs/baseline.md): Qt has no
5023    /// baseline protocol to ask — `QFormLayout` aligns boxes, not text — so `Cap` reports this
5024    /// as `Emulated`.
5025    fn first_baseline(&mut self, h: &QtHandle, kind: PieceKind, size: Size) -> Option<f64> {
5026        if !day_spec::kind_has_baseline(kind) {
5027            return None;
5028        }
5029        let b = unsafe { ffi::day_qt_baseline(h.0, size.height) };
5030        (b >= 0.0).then_some(b)
5031    }
5032
5033    fn set_frame(&mut self, h: &QtHandle, frame: Rect, anim: Option<&AnimSpec>) {
5034        // A host whose panes or rows are laid out from its native size (nav, split, inspector,
5035        // list) re-reports them below from the size Qt gives it, so it takes its frame at once;
5036        // everything else animates its geometry under `anim` (a run in the shim).
5037        let key = h.0 as usize;
5038        let native_host = NAV_STATE.with(|m| m.borrow().contains_key(&key))
5039            || NAV_SUITES.with(|m| m.borrow().contains_key(&key))
5040            || SPLIT_STATE.with(|m| m.borrow().contains_key(&key))
5041            || INSPECTOR_STATE.with(|m| m.borrow().contains_key(&key))
5042            || LIST_STATE.with(|m| m.borrow().contains_key(&key));
5043        let anim = if native_host { None } else { anim };
5044        // SAFETY: `h` is a live widget Day realized; the run is alive for the call.
5045        with_qt_anim(anim, |anim| unsafe {
5046            ffi::day_qt_set_frame(
5047                h.0,
5048                frame.origin.x.round() as c_int,
5049                frame.origin.y.round() as c_int,
5050                frame.size.width.round() as c_int,
5051                frame.size.height.round() as c_int,
5052                anim,
5053            );
5054        });
5055        // Nav host resized (window resize): re-report page sizes for relayout.
5056        if NAV_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5057            nav_sync_panes(h.0);
5058        }
5059        if NAV_SUITES.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5060            nav_suite_sync(h.0);
5061        }
5062        // A split host framed: its pane frames are native-owned too (docs/split.md).
5063        if SPLIT_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5064            split_sync_panes(h.0);
5065        }
5066        // Same for an inspector split: its pane frames are native-owned too.
5067        if INSPECTOR_STATE.with(|m| m.borrow().contains_key(&(h.0 as usize))) {
5068            inspector_sync_panes(h.0);
5069        }
5070        // List host framed: (re)fill its cells — but only when the width actually changed, so the
5071        // set_frame calls a populate itself makes (on row content) don't schedule another forever.
5072        let width_changed = LIST_STATE.with(|m| {
5073            m.borrow()
5074                .get(&(h.0 as usize))
5075                .is_some_and(|st| st.last_width != frame.size.width.round() as c_int)
5076        });
5077        // A taller host shows more rows, and the ones it grew into are not built yet — so a
5078        // height change refills the window even though every built row is still valid. Width is
5079        // the one that invalidates content: each row is laid out to it.
5080        let framed_h = frame.size.height.round() as c_int;
5081        let height_changed = LIST_STATE.with(|m| {
5082            let mut m = m.borrow_mut();
5083            let Some(st) = m.get_mut(&(h.0 as usize)) else {
5084                return false;
5085            };
5086            let changed = st.frame_height != framed_h;
5087            st.frame_height = framed_h;
5088            changed
5089        });
5090        if width_changed {
5091            schedule_list_populate(h.0 as usize);
5092        } else if height_changed {
5093            schedule_list_fill(h.0 as usize);
5094        }
5095    }
5096
5097    fn scroll_bar_inset(&mut self, h: &QtHandle, vertical: bool) -> f64 {
5098        f64::from(unsafe { ffi::day_qt_scroll_bar_inset(h.0, c_int::from(vertical)) })
5099    }
5100
5101    fn set_scroll_content(&mut self, h: &QtHandle, content: Size) {
5102        unsafe {
5103            ffi::day_qt_scroll_set_content_size(
5104                h.0,
5105                content.width.round() as c_int,
5106                content.height.round() as c_int,
5107            );
5108        };
5109    }
5110
5111    /// A Qt item view row: compact, 8px sides and 28px tall.
5112    fn list_row_metrics(&mut self, _h: &QtHandle) -> day_spec::RowMetrics {
5113        day_spec::RowMetrics {
5114            insets: day_spec::Insets {
5115                top: 4.0,
5116                leading: 8.0,
5117                bottom: 4.0,
5118                trailing: 8.0,
5119            },
5120            min_height: 28.0,
5121        }
5122    }
5123
5124    fn scroll_to(&mut self, h: &QtHandle, target: Rect, animated: bool) {
5125        // Qt's scroll bars have no animation of their own: an animated scroll glides the bars'
5126        // values for 250 ms with an ease-out cubic, and lands where the jump would (docs/scroll.md).
5127        unsafe {
5128            ffi::day_qt_scroll_to_rect(
5129                h.0,
5130                target.origin.x.round() as c_int,
5131                target.origin.y.round() as c_int,
5132                target.size.width.round() as c_int,
5133                target.size.height.round() as c_int,
5134                c_int::from(animated),
5135            );
5136        };
5137    }
5138
5139    fn scroll_offset(&mut self, h: &QtHandle) -> day_spec::Point {
5140        let (mut x, mut y) = (0.0_f64, 0.0_f64);
5141        unsafe { ffi::day_qt_scroll_offset(h.0, &raw mut x, &raw mut y) };
5142        day_spec::Point::new(x, y)
5143    }
5144
5145    fn list_scroll(&mut self, h: &QtHandle, to: day_spec::ListScroll) -> bool {
5146        // QListView scrolls per pixel, so the shim aims the vertical bar itself: the row's
5147        // aligned position (`QAbstractItemView::scrollTo` has no "nearest" that keeps a fully
5148        // visible row still, nor a pinned-header inset), a jump or a 250 ms glide, re-aimed
5149        // while rows it reveals are measured. Posted: the request arrives in the same turn as
5150        // the splice that made its row, and the row flush posted first runs first.
5151        let host_key = h.0 as usize;
5152        let row = to
5153            .row
5154            .map_or(-1, |r| c_int::try_from(r).unwrap_or(c_int::MAX));
5155        let align = row_align_code(to.align);
5156        let animated = c_int::from(to.animated);
5157        Qt::post(Box::new(move || {
5158            if let Some(host) = LIST_STATE.with(|m| m.borrow().get(&host_key).map(|st| st.host)) {
5159                unsafe { ffi::day_qt_list_scroll(host, row, align, animated) };
5160            }
5161        }));
5162        true
5163    }
5164
5165    fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
5166        use day_spec::present::PresentSpec;
5167        let parent = self.present_parent();
5168        match spec {
5169            PresentSpec::Dialog { .. } => unsafe {
5170                ffi::day_qt_present_dialog(
5171                    req,
5172                    cstr(spec.title()).as_ptr(),
5173                    cstr(spec.message().unwrap_or("")).as_ptr(),
5174                    cstr(&spec.buttons_joined()).as_ptr(),
5175                    cstr(&spec.roles_joined()).as_ptr(),
5176                    parent,
5177                );
5178            },
5179            PresentSpec::Prompt {
5180                placeholder,
5181                initial,
5182                ok,
5183                cancel,
5184                ..
5185            } => unsafe {
5186                ffi::day_qt_present_prompt(
5187                    req,
5188                    cstr(spec.title()).as_ptr(),
5189                    cstr(spec.message().unwrap_or("")).as_ptr(),
5190                    cstr(placeholder).as_ptr(),
5191                    cstr(initial).as_ptr(),
5192                    cstr(ok).as_ptr(),
5193                    cstr(cancel).as_ptr(),
5194                    parent,
5195                );
5196            },
5197            PresentSpec::OpenFile { multiple, .. } => unsafe {
5198                ffi::day_qt_present_file_open(
5199                    req,
5200                    cstr(spec.title()).as_ptr(),
5201                    cstr(&spec.filters_joined()).as_ptr(),
5202                    c_int::from(*multiple),
5203                    parent,
5204                );
5205            },
5206            PresentSpec::OpenFolder { .. } => unsafe {
5207                ffi::day_qt_present_folder_open(req, cstr(spec.title()).as_ptr(), parent);
5208            },
5209            PresentSpec::SaveFile { suggested_name, .. } => unsafe {
5210                // The pieces layer copies the staged bytes to the chosen path.
5211                ffi::day_qt_present_file_save(
5212                    req,
5213                    cstr(spec.title()).as_ptr(),
5214                    cstr(suggested_name).as_ptr(),
5215                    cstr(&spec.filters_joined()).as_ptr(),
5216                    parent,
5217                );
5218            },
5219        }
5220    }
5221
5222    fn dismiss(&mut self, req: u64) {
5223        unsafe { ffi::day_qt_dismiss_present(req) };
5224    }
5225
5226    #[cfg(target_os = "macos")]
5227    fn share_support(&self) -> day_spec::Support {
5228        day_spec::Support::Native
5229    }
5230    #[cfg(target_os = "macos")]
5231    fn share(&mut self, spec: &day_spec::share::ShareSpec, _anchor: Option<&Self::Handle>) -> bool {
5232        unsafe { ffi::day_qt_share_url(cstr(&spec.url).as_ptr(), cstr(&spec.title).as_ptr()) }
5233    }
5234    fn open_url(&mut self, url: &str) {
5235        if let Ok(c) = std::ffi::CString::new(url) {
5236            unsafe { ffi::day_qt_open_url(c.as_ptr()) };
5237        }
5238    }
5239
5240    fn set_focusable(&mut self, h: &QtHandle, node: NodeId, focusable: bool) {
5241        if focusable {
5242            unsafe {
5243                ffi::day_qt_enable_keys(h.0, node.0, on_key);
5244                ffi::day_qt_enable_focus(h.0, node.0, on_focus);
5245                ffi::day_qt_set_focusable(h.0);
5246            }
5247        }
5248    }
5249
5250    fn focus(&mut self, h: &QtHandle, _node: NodeId, focused: bool) {
5251        // The shim clears only while this widget still owns focus, so a stale release
5252        // can't blur a sibling.
5253        unsafe { ffi::day_qt_widget_focus(h.0, c_int::from(focused)) };
5254    }
5255
5256    fn set_event_sink(&mut self, sink: EventSink) {
5257        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
5258    }
5259
5260    fn enable_gesture(&mut self, h: &QtHandle, node: NodeId, kind: day_spec::GestureKind) {
5261        use day_spec::GestureKind as K;
5262        let key = (h.0 as usize, kind);
5263        if !GESTURES.with(|g| g.borrow_mut().insert(key)) {
5264            return; // already wired
5265        }
5266        let code: c_int = match kind {
5267            K::Tap => 0,
5268            K::Drag => 1,
5269            K::Pinch => 2,
5270            K::Pan => 3,
5271            K::Hover => 4,
5272            K::Rotate => 5,
5273            K::Press => 6,
5274            K::LongPress => 7,
5275            K::DoubleTap => 8,
5276            K::Touches => 9,
5277        };
5278        unsafe { ffi::day_qt_enable_gesture(h.0, node.0, code, on_gesture) };
5279    }
5280
5281    // The shim's own recognizers (docs/gestures.md "Recognizers"): a press is the left
5282    // button's or the first finger's, a long press Qt's `mousePressAndHoldInterval` held within
5283    // its `startDragDistance`, a double tap Qt's `MouseButtonDblClick`. Touches need screen
5284    // contacts: Qt's touch events where the platform has a touch screen (X11's XInput 2,
5285    // Windows), with the mouse as one contact; a Mac's trackpad fingers are not screen
5286    // contacts, so there day-core derives the single contact.
5287    fn gesture_support(&self, kind: day_spec::GestureKind) -> Support {
5288        match kind {
5289            day_spec::GestureKind::Touches if cfg!(target_os = "macos") => Support::Unsupported,
5290            _ => Support::Native,
5291        }
5292    }
5293
5294    fn set_hit_slop(&mut self, h: &QtHandle, _node: NodeId, slop: day_spec::Insets) {
5295        unsafe {
5296            ffi::day_qt_set_hit_slop(h.0, slop.top, slop.leading, slop.bottom, slop.trailing);
5297        }
5298    }
5299
5300    fn set_drag_axis(&mut self, h: &QtHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
5301        let code = match axis {
5302            None => 0,
5303            Some(day_spec::DragAxis::Horizontal) => 1,
5304            Some(day_spec::DragAxis::Vertical) => 2,
5305        };
5306        unsafe { ffi::day_qt_set_drag_axis(h.0, code) };
5307    }
5308
5309    // `QWidget::setEnabled` cascades through the subtree: the controls dim, leave the focus
5310    // chain (focus inside moves on and reports its loss), take no input and read as disabled
5311    // to assistive technology; the shim counts nested calls (docs/forms.md).
5312    fn set_subtree_enabled(&mut self, h: &QtHandle, _node: NodeId, enabled: bool) {
5313        unsafe { ffi::day_qt_subtree_enabled(h.0, c_int::from(enabled)) };
5314    }
5315
5316    fn edit_toolbar(&mut self, h: &QtHandle, ops: &[day_spec::ToolbarOp]) -> bool {
5317        self.edit_toolbar(h, ops)
5318    }
5319
5320    fn update_toolbar(&mut self, h: &QtHandle, patch: &day_spec::ToolbarPatch) {
5321        self.patch_toolbar(h, patch);
5322    }
5323
5324    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
5325        if self.window.is_null() {
5326            return;
5327        }
5328        // KDE's bar: File, Edit, View, the app's own menus, then Settings and Help.
5329        let items = day_core::menu::standard_menu_bar_for(
5330            day_core::menu::MenuBarStyle::Kde,
5331            items.to_vec(),
5332        );
5333        let items = &items[..];
5334        let bar = unsafe { ffi::day_qt_window_menubar(self.window) };
5335        // Top level entries are the menu-bar menus; a bare action becomes a single-item menu.
5336        for item in items {
5337            match item {
5338                day_spec::MenuItem::Submenu { label, items, .. } => {
5339                    let menu = unsafe { ffi::day_qt_menubar_add_menu(bar, cstr(label).as_ptr()) };
5340                    build_qt_menu(menu, items);
5341                }
5342                other => {
5343                    let menu = unsafe { ffi::day_qt_menubar_add_menu(bar, cstr("").as_ptr()) };
5344                    build_qt_menu(menu, std::slice::from_ref(other));
5345                }
5346            }
5347        }
5348        // An in-window bar (Linux/Windows) now has its real height: reserve its strip so the
5349        // content area — and day's layout — sit below it instead of underneath it.
5350        unsafe { ffi::day_qt_window_menubar_done(self.window) };
5351    }
5352
5353    fn modifiers(&mut self) -> day_spec::Modifiers {
5354        let m = unsafe { ffi::day_qt_modifiers() };
5355        // The shim's mask uses the wire bits (`Modifiers::bits`).
5356        day_spec::Modifiers::from_bits((m & 7) as u8)
5357    }
5358
5359    fn set_drag_source(&mut self, h: &QtHandle, source: day_spec::transfer::Source) {
5360        transfer::source(h, source);
5361    }
5362    fn set_drop_target(&mut self, h: &QtHandle, target: day_spec::transfer::Target) {
5363        transfer::target(h, target);
5364    }
5365    fn set_context_menu_fn(&mut self, h: &QtHandle, node: NodeId, f: day_spec::ContextMenuFn) {
5366        CTX_MENU_FNS.with(|m| m.borrow_mut().insert(node.0, f));
5367        unsafe { ffi::day_qt_context_menu_fn(h.0, node.0, on_context_menu_summon) };
5368    }
5369
5370    fn set_button_menu(&mut self, h: &QtHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
5371        BUTTON_MENUS.with(|t| t.insert(h.0 as usize, f));
5372        // SAFETY: `h` is a live widget; the shim checks it is a QPushButton (qobject_cast)
5373        // before connecting to its click, and parents each menu to it.
5374        unsafe { ffi::day_qt_button_menu_fn(h.0, h.0 as u64, on_button_menu) };
5375    }
5376
5377    fn set_context_menu(&mut self, h: &QtHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
5378        if items.is_empty() {
5379            unsafe { ffi::day_qt_set_context_menu(h.0, std::ptr::null_mut()) };
5380            return;
5381        }
5382        let menu = unsafe { ffi::day_qt_menu_new() };
5383        build_qt_menu(menu, items);
5384        unsafe { ffi::day_qt_set_context_menu(h.0, menu) };
5385    }
5386
5387    fn attach_tree(&mut self, host: &QtHandle, source: day_spec::TreeSource) {
5388        tree::attach(host.0 as usize, source);
5389    }
5390
5391    fn attach_list(&mut self, host: &QtHandle, source: day_spec::ListSource) {
5392        LIST_STATE.with(|m| {
5393            if let Some(st) = m.borrow().get(&(host.0 as usize)) {
5394                *st.source.borrow_mut() = Some(source);
5395            }
5396        });
5397        // Deferred (see schedule_list_populate): populating re-enters with_tree via bind_row.
5398        schedule_list_populate(host.0 as usize);
5399    }
5400
5401    fn adopt(&mut self, raw: day_spec::RawHandle) -> QtHandle {
5402        // A recycling list cell (a plain QWidget) — Day fills/rebinds its row content in place.
5403        QtHandle(raw)
5404    }
5405
5406    fn set_a11y(&mut self, h: &QtHandle, a11y: &A11yProps) {
5407        unsafe {
5408            if let Some(id) = &a11y.identifier {
5409                ffi::day_qt_set_object_name(h.0, cstr(id).as_ptr());
5410            }
5411            if let Some(label) = &a11y.label {
5412                // Real QAccessible name (screen readers) + a visible tooltip.
5413                ffi::day_qt_set_accessible_name(h.0, cstr(label).as_ptr());
5414                ffi::day_qt_set_tooltip(h.0, cstr(label).as_ptr());
5415            }
5416            if let Some(hint) = &a11y.hint {
5417                ffi::day_qt_set_accessible_description(h.0, cstr(hint).as_ptr());
5418            }
5419            // Role, value and hidden go to the shim's own QAccessibleInterface, which Qt's
5420            // stock ones cannot carry for a widget they type themselves. The codes follow
5421            // `Role`'s declaration order (the table sits with the declaration in day-toolkit-qt-sys).
5422            let (role, level) = match a11y.role {
5423                Role::None => (0, 0),
5424                Role::Button => (1, 0),
5425                Role::Toggle => (2, 0),
5426                Role::Slider => (3, 0),
5427                Role::TextInput => (4, 0),
5428                Role::Heading(level) => (5, c_int::from(level.max(1))),
5429                Role::Image => (6, 0),
5430                Role::Meter => (7, 0),
5431                Role::Group => (8, 0),
5432                Role::Tree => (9, 0),
5433                Role::TreeItem => (10, 0),
5434                Role::Tab => (11, 0),
5435                Role::TabList => (12, 0),
5436            };
5437            let value = a11y.value.as_deref().map(cstr);
5438            if role != 0 || value.is_some() || a11y.hidden || a11y.selected.is_some() {
5439                ffi::day_qt_set_a11y_traits(
5440                    h.0,
5441                    role,
5442                    level,
5443                    value.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()),
5444                    c_int::from(a11y.hidden),
5445                    a11y.selected.map_or(-1, c_int::from),
5446                );
5447            }
5448        }
5449    }
5450
5451    /// The widget's own state (docs/testing.md), all of it read in the shim from the `QWidget` and
5452    /// its `QAccessibleInterface`. Slider and progress ticks go back through the range Day built
5453    /// them from; a slider whose range was never recorded reports no number.
5454    fn read_native(&self, h: &QtHandle) -> day_spec::NativeSnapshot {
5455        if h.0.is_null() {
5456            return day_spec::NativeSnapshot::default();
5457        }
5458        let mut n = std::mem::MaybeUninit::<ffi::DayQtNative>::zeroed();
5459        // SAFETY: the handle is a live QWidget Day realized, and the shim initializes every
5460        // field of `n` before returning.
5461        let mut n = unsafe {
5462            ffi::day_qt_read_native(h.0, n.as_mut_ptr());
5463            n.assume_init()
5464        };
5465        // SAFETY: each pointer is NULL or a NUL-terminated heap string the shim wrote, alive
5466        // until `day_qt_native_free` below.
5467        let string = |p: *mut c_char| {
5468            (!p.is_null()).then(|| unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned())
5469        };
5470        let role = match n.role {
5471            1 => Role::Button,
5472            2 => Role::Toggle,
5473            3 => Role::Slider,
5474            4 => Role::TextInput,
5475            5 => Role::Heading(u8::try_from(n.level).unwrap_or(1).max(1)),
5476            6 => Role::Image,
5477            7 => Role::Meter,
5478            8 => Role::Group,
5479            9 => Role::Tree,
5480            10 => Role::TreeItem,
5481            11 => Role::Tab,
5482            12 => Role::TabList,
5483            _ => Role::None,
5484        };
5485        let ticks = f64::from(n.number) / 1000.0;
5486        let number = match n.number_kind {
5487            1 => RANGES_BY_PTR
5488                .with(|r| r.get(h.0 as usize))
5489                .map(|(min, max)| {
5490                    // `slider_ticks` maps an empty range to tick 0, which is `min`.
5491                    if max <= min {
5492                        min
5493                    } else {
5494                        min + ticks * (max - min)
5495                    }
5496                }),
5497            2 => Some(ticks),
5498            _ => None,
5499        };
5500        let found = n.found != 0;
5501        let snapshot = day_spec::NativeSnapshot {
5502            found,
5503            role: if found { role } else { Role::None },
5504            label: string(n.label),
5505            value: string(n.value),
5506            identifier: string(n.identifier),
5507            // A picker's text comes from its own unit (see `picker::selected_text`).
5508            text: match crate::picker::selected_text(h.0) {
5509                Some(picked) => picked,
5510                None => string(n.text),
5511            },
5512            number,
5513            checked: (n.checked >= 0).then_some(n.checked != 0),
5514            enabled: Some(n.enabled != 0),
5515            visible: Some(n.visible != 0),
5516            frame: (n.frame_ok != 0).then(|| Rect::new(n.x, n.y, n.w, n.h)),
5517        };
5518        // SAFETY: `n` holds the strings the shim allocated above, released exactly once.
5519        unsafe { ffi::day_qt_native_free(&raw mut n) };
5520        snapshot
5521    }
5522
5523    fn announce(&mut self, text: &str, urgent: bool) {
5524        if self.window.is_null() {
5525            return;
5526        }
5527        // SAFETY: the primary DayWindow lives until the process exits; the text outlives the
5528        // call, and the shim copies it.
5529        unsafe { ffi::day_qt_announce(self.window, cstr(text).as_ptr(), c_int::from(urgent)) };
5530    }
5531
5532    fn request_frame(
5533        &mut self,
5534        host: &QtHandle,
5535        cb: day_spec::FrameCallback,
5536    ) -> day_spec::CancelFrame {
5537        let token = day_core::frame::native::register(cb);
5538        unsafe { ffi::day_qt_request_frame(host.0, token, run_frame) };
5539        Box::new(move || {
5540            day_core::frame::native::cancel(token);
5541            unsafe { ffi::day_qt_cancel_frame(token) };
5542        })
5543    }
5544
5545    fn replay(&mut self, h: &QtHandle, ops: &[DrawOp], _size: Size) {
5546        let (nums, texts) = day_spec::encode_ops(ops);
5547        let joined = cstr(&texts.join("\u{1f}"));
5548        unsafe {
5549            ffi::day_qt_canvas_set_ops(h.0, nums.as_ptr(), nums.len() as c_int, joined.as_ptr());
5550        };
5551    }
5552
5553    /// A role from the application palette (docs/color.md "Roles"): `QPalette::Accent` (6.6+,
5554    /// else `Highlight`), `WindowText` for text (at 0.6, 0.38 and 0.15 for secondary, tertiary
5555    /// and separators), `PlaceholderText`, `Link`, `Button`, `Window`, `Base` (also for an
5556    /// elevated surface) and `Highlight` at 0.35 for a selection. The palette has no
5557    /// destructive, success or warning color: Day's documented pairs answer those.
5558    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
5559        let mut rgba = [0.0f64; 4];
5560        // SAFETY: `rgba` has the four slots the shim writes; nothing else crosses.
5561        if unsafe { ffi::day_qt_system_color(c_int::from(role.wire()), rgba.as_mut_ptr()) } != 0 {
5562            day_spec::Color::rgba(rgba[0], rgba[1], rgba[2], rgba[3])
5563        } else {
5564            role.fallback(self.dark_mode())
5565        }
5566    }
5567
5568    /// `QStyleHints::setColorScheme` (Qt 6.8+), for this application only: Qt re-polishes
5569    /// every widget with the scheme's palette, and the palette change re-applies Day's inks.
5570    fn set_appearance(&mut self, dark: Option<bool>) {
5571        let mode = match dark {
5572            None => -1,
5573            Some(false) => 0,
5574            Some(true) => 1,
5575        };
5576        // SAFETY: a plain request on the application's style hints.
5577        if unsafe { ffi::day_qt_set_appearance(mode) } == 0 {
5578            return;
5579        }
5580        // Qt has re-polished by now: take its new palette and apply the inks again before
5581        // anything paints (day-core reads the same palette as soon as this returns). A palette
5582        // Qt delivers later still reaches `refresh_appearance`.
5583        day_spec::Palette::set_current(day_spec::Palette {
5584            dark: self.dark_mode(),
5585            colors: day_spec::SystemColor::ALL.map(|role| self.system_color(role)),
5586        });
5587        reapply_inks();
5588    }
5589
5590    fn dark_mode(&mut self) -> bool {
5591        // Ask Qt, not the `DAY_THEME` default: Qt Widgets follow the system scheme on their
5592        // own, so the default's "light unless DAY_THEME says otherwise" left app-painted
5593        // surfaces light while every native control around them rendered dark.
5594        // SAFETY: a plain palette read; no arguments and no pointers cross the boundary.
5595        unsafe { ffi::day_qt_dark_mode() != 0 }
5596    }
5597
5598    fn toggle_sidebar(&mut self, host: &QtHandle) -> bool {
5599        crate::toggle_sidebar(host.0)
5600    }
5601
5602    /// `QFontDatabase::families()` + `styles()`, decoded from the shim's list text
5603    /// (docs/fonts.md).
5604    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
5605        // SAFETY: the shim returns a NUL-terminated heap string (or null); it is read once and
5606        // released through the shim's own free.
5607        unsafe {
5608            let p = ffi::day_qt_font_families();
5609            if p.is_null() {
5610                return Vec::new();
5611            }
5612            let text = std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned();
5613            ffi::day_qt_string_free(p);
5614            day_spec::parse_font_list(&text)
5615        }
5616    }
5617
5618    /// `QFontMetricsF` of the font the canvas draws with (docs/fonts.md).
5619    fn measure_text(
5620        &mut self,
5621        text: &str,
5622        size: f64,
5623        font: &day_spec::CanvasFont,
5624    ) -> Option<day_spec::TextMetrics> {
5625        let text = cstr(text);
5626        let family = cstr(font.family_str());
5627        let mut out = [0.0f64; 8];
5628        // SAFETY: both strings outlive the call and `out` has the eight slots the shim fills.
5629        unsafe {
5630            ffi::day_qt_measure_text(
5631                text.as_ptr(),
5632                size,
5633                c_int::from(font.css_weight()),
5634                c_int::from(font.italic),
5635                family.as_ptr(),
5636                out.as_mut_ptr(),
5637            );
5638        };
5639        Some(day_spec::TextMetrics::from_slots(&out))
5640    }
5641
5642    /// Decode bytes with `QImage::loadFromData` (docs/images.md), which reads every format Qt's
5643    /// image plugins handle. The pixels stay in the shim; only what the decode reported is kept
5644    /// on this side.
5645    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
5646        let mut out = [0.0f64; 3];
5647        // SAFETY: the shim reads `len` bytes from the borrowed span and copies what it keeps,
5648        // and writes exactly three doubles into `out`.
5649        let ok = unsafe {
5650            ffi::day_qt_image_decode(id.0, bytes.as_ptr(), bytes.len() as c_int, out.as_mut_ptr())
5651        };
5652        let event = if ok != 0 {
5653            let info = day_spec::BitmapInfo {
5654                pixels: Size::new(out[0], out[1]),
5655                // Decoded bytes carry no density — a PNG is simply its pixels.
5656                scale: 1.0,
5657                format: day_spec::ImageFormat::sniff(bytes),
5658                has_alpha: out[2] > 0.5,
5659            };
5660            BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5661            Event::ImageDecoded {
5662                req,
5663                result: Ok(info),
5664            }
5665        } else {
5666            Event::ImageDecoded {
5667                req,
5668                result: Err(day_spec::ImageError::Decode),
5669            }
5670        };
5671        emit(day_spec::WINDOW_NODE, event);
5672    }
5673
5674    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
5675        BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
5676    }
5677
5678    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
5679        let result = encode_bitmap(id, spec);
5680        emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
5681    }
5682
5683    /// What `QImage::save` WRITES. Qt reads more than this — GIF and, with the right plugins,
5684    /// WebP — and the asymmetry is Qt's own, which is why this duty exists rather than letting
5685    /// `Cap::ImageEncode` imply that everything decodable is also encodable.
5686    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
5687        use day_spec::ImageFormat::{Bmp, Jpeg, Png, Tiff};
5688        vec![Png, Jpeg, Tiff, Bmp]
5689    }
5690
5691    fn release_image(&mut self, id: day_spec::BitmapId) {
5692        release_bitmap(id);
5693    }
5694
5695    /// The canvas widget's painter (`day_paint_ops`) replayed into a premultiplied ARGB32
5696    /// `QImage` whose device pixel ratio is `scale`, stored in the same registry
5697    /// `decode_image` fills (docs/canvas.md "Exporting").
5698    fn render_bitmap(
5699        &mut self,
5700        req: u64,
5701        id: day_spec::BitmapId,
5702        ops: &[DrawOp],
5703        size: Size,
5704        scale: f64,
5705    ) {
5706        let (pw, ph) = day_spec::export_pixels(size, scale);
5707        let (nums, texts) = day_spec::encode_ops(ops);
5708        let joined = cstr(&texts.join("\u{1f}"));
5709        let result = match (c_int::try_from(pw), c_int::try_from(ph)) {
5710            // SAFETY: both op channels outlive the call; the shim copies what it keeps.
5711            (Ok(w), Ok(h)) => {
5712                if unsafe {
5713                    ffi::day_qt_canvas_render_image(
5714                        id.0,
5715                        nums.as_ptr(),
5716                        nums.len() as c_int,
5717                        joined.as_ptr(),
5718                        w,
5719                        h,
5720                        scale,
5721                    )
5722                } == 0
5723                {
5724                    Err(day_spec::ExportError::Failed(format!(
5725                        "QImage could not allocate {pw} × {ph} pixels"
5726                    )))
5727                } else {
5728                    let info = day_spec::BitmapInfo {
5729                        pixels: Size::new(f64::from(pw), f64::from(ph)),
5730                        scale,
5731                        format: None,
5732                        has_alpha: true,
5733                    };
5734                    BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
5735                    Ok(info)
5736                }
5737            }
5738            _ => Err(day_spec::ExportError::TooLarge {
5739                width: pw,
5740                height: ph,
5741            }),
5742        };
5743        emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
5744    }
5745
5746    /// One `QPdfWriter` document, a page per `PdfPage`, each painted by `day_paint_ops` at
5747    /// resolution 72 so a unit is a PDF point (docs/canvas.md "Exporting").
5748    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
5749        let result = render_pdf_document(pages, info);
5750        emit(day_spec::WINDOW_NODE, Event::PdfRendered { req, result });
5751    }
5752
5753    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
5754        if self.window.is_null() {
5755            return Err("no window".into());
5756        }
5757        snapshot_qt_widget(self.window)
5758    }
5759
5760    fn snapshot_window_of(&mut self, host: &QtHandle) -> Result<Vec<u8>, String> {
5761        snapshot_qt_widget(host.0)
5762    }
5763
5764    fn native_window_tabs(&self) -> bool {
5765        cfg!(target_os = "macos")
5766    }
5767    #[cfg(target_os = "macos")]
5768    fn group_windows(&mut self, hosts: &[QtHandle]) {
5769        // Core applies window flags after open_window. Qt can recreate its NSWindow
5770        // while applying those flags, so obtain the native window only after that step.
5771        for host in hosts {
5772            if let Some(w) = self.secondary.iter().find(|w| w.content == host.0)
5773                && let Some(group) = &w.tab_group
5774            {
5775                unsafe {
5776                    ffi::day_qt_window_show(w.win);
5777                    let view = ffi::day_qt_window_nsview(w.win);
5778                    let raw = day_platform_macos::window_tabs::window_from_view(view);
5779                    day_platform_macos::window_tabs::register(raw, w.id, group);
5780                }
5781            }
5782        }
5783        let ids = hosts
5784            .iter()
5785            .filter_map(|h| {
5786                self.secondary
5787                    .iter()
5788                    .find(|w| w.content == h.0)
5789                    .map(|w| w.id)
5790            })
5791            .collect::<Vec<_>>();
5792        day_platform_macos::window_tabs::group(&ids);
5793    }
5794    #[cfg(target_os = "macos")]
5795    fn window_tab_order(&self, host: &QtHandle) -> Vec<NodeId> {
5796        self.secondary
5797            .iter()
5798            .find(|w| w.content == host.0)
5799            .map_or_default(|w| day_platform_macos::window_tabs::order(w.id))
5800    }
5801    fn native_document_tabs(&self) -> bool {
5802        true
5803    }
5804
5805    fn open_window(
5806        &mut self,
5807        id: NodeId,
5808        options: &WindowOptions,
5809        kind: day_spec::WindowKind,
5810    ) -> day_spec::WindowOpenReply<QtHandle> {
5811        let fixed = c_int::from(kind.is_panel());
5812        let win = unsafe {
5813            ffi::day_qt_window_new2(
5814                cstr(&options.title).as_ptr(),
5815                options.size.width as c_int,
5816                options.size.height as c_int,
5817                id.0,
5818                fixed,
5819            )
5820        };
5821        apply_open_options(win, options, fixed == 0);
5822        if !options.start_hidden {
5823            unsafe { ffi::day_qt_window_show(win) };
5824        }
5825        let content = unsafe { ffi::day_qt_window_content(win) };
5826        self.secondary.push(QtWin {
5827            #[cfg(target_os = "macos")]
5828            id,
5829            #[cfg(target_os = "macos")]
5830            tab_group: match &options.tabbing {
5831                day_spec::WindowTabbing::Group(g) | day_spec::WindowTabbing::Preferred(g) => {
5832                    Some(g.clone())
5833                }
5834                _ => None,
5835            },
5836            win,
5837            content,
5838        });
5839        day_spec::WindowOpenReply::Open(QtHandle(content))
5840    }
5841
5842    fn close_window(&mut self, host: &QtHandle) {
5843        if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
5844            // closeEvent confirms with WindowClosed; the window HIDES — destruction is
5845            // anchored to day-core releasing the content handle (`release`, below).
5846            #[cfg(target_os = "macos")]
5847            day_platform_macos::window_tabs::unregister(w.id);
5848            unsafe { ffi::day_qt_window_close(w.win) };
5849        }
5850    }
5851
5852    fn focus_window(&mut self, host: &QtHandle) {
5853        if let Some(w) = self.secondary.iter().find(|w| w.content == host.0) {
5854            unsafe { ffi::day_qt_window_raise(w.win) };
5855        }
5856    }
5857
5858    fn fit_window(&mut self, host: &QtHandle, size: Size) {
5859        // A panel that fits its content (docs/windows.md `size_to_fit`): the shim adds the
5860        // chrome strip back and moves a fixed-size window's pin; the resize event then reports
5861        // the new content area to day-core through `relayoutChrome`.
5862        if let Some(win) = self.qt_window_for(host) {
5863            // SAFETY: `win` is a live DayWindow (see `apply_window`).
5864            unsafe { ffi::day_qt_window_fit(win, size.width, size.height) };
5865        }
5866    }
5867
5868    fn set_window_title(&mut self, host: &QtHandle, title: &str) {
5869        // The primary is an ordinary window (docs/windows.md): `day::window_title` in the first
5870        // window's shell lands here with the primary's own root, and searching only the
5871        // secondary list would drop it.
5872        let win = match self.secondary.iter().find(|w| w.content == host.0) {
5873            Some(w) => w.win,
5874            None => self.window,
5875        };
5876        if !win.is_null() {
5877            unsafe { ffi::day_qt_window_set_title(win, cstr(title).as_ptr()) };
5878        }
5879    }
5880
5881    fn apply_window(&mut self, host: &QtHandle, change: &day_spec::WindowChange) {
5882        use day_spec::WindowChange as C;
5883        // A secondary window by its content, or the primary, which `ready` handed out as the
5884        // DayWindow itself.
5885        let Some(win) = self.qt_window_for(host) else {
5886            return;
5887        };
5888        match change {
5889            // SAFETY: `win` is a live DayWindow: the primary lives until the process exits, and
5890            // a secondary stays in `self.secondary` until day-core releases its content.
5891            C::State(state) => unsafe { ffi::day_qt_window_set_state(win, state.code()) },
5892            // No Linux display server (X11, Wayland) lets a client keep its surface out of
5893            // screenshots or screen sharing, so `Cap::ContentProtection` is Unsupported and the
5894            // request is ignored. (Qt has no portable switch for it on macOS or Windows either.)
5895            C::ContentProtected(_) => {}
5896            other => apply_property(win, other),
5897        }
5898    }
5899
5900    fn window_frame(&self, host: &QtHandle) -> Option<day_spec::Rect> {
5901        let win = self.qt_window_for(host)?;
5902        let mut out = [0.0f64; 4];
5903        // SAFETY: `win` is a live DayWindow (see `apply_window`); `out` holds the four doubles
5904        // the shim writes.
5905        let known = unsafe { ffi::day_qt_window_frame(win, out.as_mut_ptr()) } != 0;
5906        known.then(|| day_spec::Rect::new(out[0], out[1], out[2], out[3]))
5907    }
5908
5909    fn monitors(&self) -> Vec<day_spec::Monitor> {
5910        qt_monitors()
5911    }
5912
5913    fn set_drag_region(&mut self, h: &QtHandle, drag: bool) {
5914        // SAFETY: `h` is a live widget Day realized.
5915        unsafe { ffi::day_qt_set_drag_region(h.0, c_int::from(drag)) };
5916    }
5917
5918    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
5919        self.trays.retain(|(spec, tray)| {
5920            let keep = items.iter().any(|i| i.id == spec.id);
5921            if !keep {
5922                // SAFETY: a tray this backend made and has not deleted.
5923                unsafe { ffi::day_qt_tray_delete(*tray) };
5924            }
5925            keep
5926        });
5927        for spec in items {
5928            let tray = match self.trays.iter_mut().find(|(s, _)| s.id == spec.id) {
5929                Some((s, _)) if s == spec => continue,
5930                Some((s, tray)) => {
5931                    *s = spec.clone();
5932                    *tray
5933                }
5934                None => {
5935                    // SAFETY: a constructor; the QApplication exists by the time any duty runs.
5936                    let tray = unsafe { ffi::day_qt_tray_new() };
5937                    self.trays.push((spec.clone(), tray));
5938                    tray
5939                }
5940            };
5941            update_tray(tray, spec);
5942        }
5943    }
5944
5945    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
5946        #[cfg(target_os = "linux")]
5947        linux::set_progress(progress);
5948        #[cfg(not(target_os = "linux"))]
5949        let _ = progress;
5950    }
5951
5952    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
5953        #[cfg(target_os = "linux")]
5954        linux::set_badge(badge);
5955        #[cfg(not(target_os = "linux"))]
5956        let _ = badge;
5957    }
5958
5959    fn set_keep_running(&mut self, keep: bool) {
5960        // SAFETY: a flag write.
5961        unsafe { ffi::day_qt_set_keep_running(c_int::from(keep)) };
5962    }
5963
5964    fn quit_app(&mut self) {
5965        // SAFETY: called on the UI thread with the QApplication running.
5966        unsafe { ffi::day_qt_quit() };
5967    }
5968}
5969
5970/// The chrome, size limits and placement a window opens with, applied before it is first shown
5971/// (docs/window-chrome.md). `resizable` is false for a Preferences window, which keeps its
5972/// fixed size whatever the options say.
5973fn apply_open_options(win: *mut c_void, options: &WindowOptions, resizable: bool) {
5974    let frameless = options.chrome == day_spec::WindowChrome::Frameless;
5975    let transparent = options.background == day_spec::WindowBackground::Transparent;
5976    let resizable = resizable && options.resizable;
5977    // SAFETY (every call below): `win` is the DayWindow just created, not yet shown.
5978    unsafe {
5979        if options.min_size.is_some() || options.max_size.is_some() {
5980            let min = options.min_size.unwrap_or(Size::new(-1.0, -1.0));
5981            let max = options.max_size.unwrap_or(Size::new(-1.0, -1.0));
5982            ffi::day_qt_window_set_limits(win, min.width, min.height, max.width, max.height);
5983        }
5984        ffi::day_qt_window_set_chrome(
5985            win,
5986            c_int::from(frameless),
5987            c_int::from(transparent),
5988            c_int::from(options.shadow),
5989            c_int::from(resizable),
5990        );
5991        match options.placement {
5992            day_spec::WindowPlacement::Automatic => {}
5993            day_spec::WindowPlacement::Centered => ffi::day_qt_window_place(win, 1, 0.0, 0.0),
5994            day_spec::WindowPlacement::At(p) => ffi::day_qt_window_place(win, 2, p.x, p.y),
5995        }
5996    }
5997}
5998
5999/// Every [`day_spec::WindowChange`] but the display state and content protection
6000/// (docs/windows.md "Window properties"). Per-window appearance is not Qt's to give (its palette
6001/// and color scheme are app-wide), and every workspace has no Qt API; both are ignored.
6002fn apply_property(win: *mut c_void, change: &day_spec::WindowChange) {
6003    use day_spec::WindowChange as C;
6004    let switch = |which: c_int, on: bool| {
6005        // SAFETY: `win` is a live DayWindow (see `apply_window`).
6006        unsafe { ffi::day_qt_window_set_switch(win, which, c_int::from(on)) }
6007    };
6008    // SAFETY (the calls below): as above.
6009    match change {
6010        C::Frame { origin, size } => unsafe {
6011            ffi::day_qt_window_set_frame(
6012                win,
6013                c_int::from(origin.is_some()),
6014                origin.map_or(0.0, |p| p.x),
6015                origin.map_or(0.0, |p| p.y),
6016                c_int::from(size.is_some()),
6017                size.map_or(0.0, |s| s.width),
6018                size.map_or(0.0, |s| s.height),
6019            );
6020        },
6021        C::Limits { min, max } => unsafe {
6022            let min = min.unwrap_or(Size::new(-1.0, -1.0));
6023            let max = max.unwrap_or(Size::new(-1.0, -1.0));
6024            ffi::day_qt_window_set_limits(win, min.width, min.height, max.width, max.height);
6025        },
6026        C::Level(level) => switch(0, *level == day_spec::WindowLevel::Floating),
6027        C::SkipTaskbar(skip) => switch(1, *skip),
6028        C::Minimizable(on) => switch(2, *on),
6029        C::Maximizable(on) => switch(3, *on),
6030        C::Closable(on) => switch(4, *on),
6031        C::Resizable(on) => switch(5, *on),
6032        C::Visible(on) => switch(6, *on),
6033        C::RequestAttention(a) => unsafe {
6034            ffi::day_qt_window_alert(win, c_int::from(*a == day_spec::Attention::Critical));
6035        },
6036        _ => {}
6037    }
6038}
6039
6040/// Every attached display, from `QGuiApplication::screens()`: geometry and available geometry
6041/// in device-independent pixels (Day's points), the device pixel ratio, Qt's primary screen.
6042fn qt_monitors() -> Vec<day_spec::Monitor> {
6043    // SAFETY: a read of the QGuiApplication's screen list on the UI thread.
6044    let n = unsafe { ffi::day_qt_screen_count() };
6045    (0..n)
6046        .filter_map(|i| {
6047            let mut out = [0.0f64; 9];
6048            let mut name = [0 as std::os::raw::c_char; 256];
6049            let mut id = [0 as std::os::raw::c_char; 128];
6050            // SAFETY: the buffers are as long as the lengths passed, and the shim
6051            // NUL-terminates within them.
6052            let primary = unsafe {
6053                ffi::day_qt_screen_info(
6054                    i,
6055                    out.as_mut_ptr(),
6056                    name.as_mut_ptr(),
6057                    name.len() as c_int,
6058                    id.as_mut_ptr(),
6059                    id.len() as c_int,
6060                )
6061            };
6062            if primary < 0 {
6063                return None;
6064            }
6065            // SAFETY: NUL-terminated by the shim (above).
6066            let text = |b: &[std::os::raw::c_char]| unsafe {
6067                std::ffi::CStr::from_ptr(b.as_ptr())
6068                    .to_string_lossy()
6069                    .into_owned()
6070            };
6071            Some(day_spec::Monitor {
6072                id: text(&id),
6073                name: text(&name),
6074                frame: day_spec::Rect::new(out[0], out[1], out[2], out[3]),
6075                work_area: day_spec::Rect::new(out[4], out[5], out[6], out[7]),
6076                scale: out[8],
6077                primary: primary == 1,
6078            })
6079        })
6080        .collect()
6081}
6082
6083/// Apply a status item's spec to its `QSystemTrayIcon`: icon, hover text, menu, click action.
6084fn update_tray(tray: *mut c_void, spec: &day_spec::StatusItemSpec) {
6085    let (icon, fallback) = crate::toolbar::icon_args(spec.icon.as_ref());
6086    let tip = if spec.tooltip.is_empty() {
6087        spec.title.as_str()
6088    } else {
6089        spec.tooltip.as_str()
6090    };
6091    // SAFETY: a fresh QMenu, filled by the same builder the app menu uses; the tray takes it.
6092    let menu = unsafe { ffi::day_qt_menu_new() };
6093    build_qt_menu(menu, &spec.menu);
6094    let mask = spec.template || matches!(spec.icon, Some(day_spec::Icon::Symbol(_)));
6095    // SAFETY: `tray` is live (see `set_status_items`); the strings outlive the call.
6096    unsafe {
6097        ffi::day_qt_tray_update(
6098            tray,
6099            cstr(&icon).as_ptr(),
6100            fallback,
6101            c_int::from(mask),
6102            cstr(tip).as_ptr(),
6103            menu,
6104            spec.activate,
6105        );
6106    };
6107    log::debug!("qt: status item {} shown", spec.id);
6108}
6109
6110/// Grab any widget to PNG through the shim (the dayscript screenshot seam).
6111fn snapshot_qt_widget(widget: *mut c_void) -> Result<Vec<u8>, String> {
6112    let path = std::env::temp_dir().join(format!("day-qt-snap-{}.png", std::process::id()));
6113    let cpath = cstr(path.to_str().unwrap_or("/tmp/day-qt-snap.png"));
6114    // A scripted run's stated capture scale (Day.toml `[screenshots]`), else the widget's own.
6115    let scale = day_spec::capture_scale().unwrap_or(0.0);
6116    let rc = unsafe { ffi::day_qt_snapshot_png(widget, cpath.as_ptr(), scale) };
6117    if rc != 0 {
6118        return Err("grab failed".into());
6119    }
6120    let bytes = std::fs::read(&path).map_err(|e| e.to_string())?;
6121    let _ = std::fs::remove_file(&path);
6122    Ok(bytes)
6123}
6124
6125extern "C" fn run_posted(data: *mut c_void) {
6126    // The posted-closure trampoline runs arbitrary Rust (deferred emits, list populates) —
6127    // contained like every other FFI entry (day-spec's ffi_guard).
6128    let f: Box<Box<dyn FnOnce() + Send>> = unsafe { Box::from_raw(data.cast()) };
6129    ffi_guard::contain((), f);
6130}
6131
6132/// A window update opportunity delivered by Qt on the application thread.
6133extern "C" fn run_frame(token: u64, timestamp: f64) {
6134    day_core::frame::native::deliver(token, day_spec::FrameStamp::new(timestamp));
6135}
6136
6137impl Platform for Qt {
6138    const TARGET: &'static str = if cfg!(target_os = "macos") {
6139        "macos-qt"
6140    } else {
6141        "linux-qt"
6142    };
6143    const TOOLKIT: &'static str = "qt";
6144
6145    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, QtHandle, Size)>) {
6146        // One process per app id on Linux: a second launch forwards its arguments and exits
6147        // before it opens anything. Held until `run` returns, which is the app's end.
6148        #[cfg(target_os = "linux")]
6149        let _instance = linux::claim_instance();
6150        unsafe {
6151            // The macOS app menu (Quit/Hide) takes its name from argv[0] at QApplication
6152            // construction, so pass the app's display name ("Showcase", falling back to the window
6153            // title) into `day_qt_app_new` up front.
6154            let app_name = options.app_name.as_deref().unwrap_or(&options.title);
6155            let app = ffi::day_qt_app_new(cstr(app_name).as_ptr());
6156            // RTL locales (docs/localization): mirror native widget internals app-wide;
6157            // Day's own frames mirror in the layout engine.
6158            if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
6159                ffi::day_qt_app_set_rtl();
6160            }
6161            // The desktop's text size (docs/text.md "Text scale") follows the screen's DPI.
6162            ffi::day_qt_on_text_scale(on_text_scale);
6163            // Bundled custom fonts (§18.4): register with the QFontDatabase (needs the
6164            // QApplication above) before the first label realizes.
6165            for path in day_spec::fonts::bundled_fonts() {
6166                if ffi::day_qt_register_font(cstr(&path.to_string_lossy()).as_ptr()) < 0 {
6167                    log::warn!("could not register bundled font {}", path.display());
6168                }
6169            }
6170            // App icon (§18.2): Dock on macOS, taskbar on Linux/Windows (set by `day launch`).
6171            if let Ok(icon) = std::env::var("DAY_APP_ICON") {
6172                ffi::day_qt_set_app_icon(cstr(&icon).as_ptr());
6173            }
6174            let window = ffi::day_qt_window_new(
6175                cstr(&options.title).as_ptr(),
6176                options.size.width as c_int,
6177                options.size.height as c_int,
6178            );
6179            self.window = window;
6180            ffi::day_qt_set_present_cb(present_cb);
6181            ffi::day_qt_set_menu_cb(on_menu_action);
6182            ffi::day_qt_set_text_keys(on_text_key_query, on_text_key);
6183            ffi::day_qt_set_touches_cb(on_touches);
6184            ffi::day_qt_install_input_router(on_pointer_kind);
6185            ffi::day_qt_set_toolbar_cb(toolbar::on_toolbar_value);
6186            ffi::day_qt_set_lifecycle_cb(on_lifecycle);
6187            // A palette or color scheme change re-applies every appearance-dependent ink.
6188            ffi::day_qt_on_appearance(on_appearance);
6189            ready(self, QtHandle(window), options.size);
6190            ffi::day_qt_window_on_resize(window, window_resized);
6191            ffi::day_qt_set_window_events_cb(win_resized, win_closed, win_focused);
6192            ffi::day_qt_set_window_state_cb(win_state);
6193            apply_open_options(window, &options, true);
6194            ffi::day_qt_window_show(window);
6195            ffi::day_qt_app_run(app);
6196        }
6197    }
6198
6199    fn locale_hints(&self) -> Vec<String> {
6200        // No desktop-wide API here that beats the environment every session sets
6201        // (§12.2, docs/localization.md).
6202        day_spec::posix_locale_hints()
6203    }
6204
6205    fn post(f: Box<dyn FnOnce() + Send>) {
6206        let data = Box::into_raw(Box::new(f)).cast::<c_void>();
6207        unsafe { ffi::day_qt_post(run_posted, data) };
6208    }
6209
6210    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
6211        // The timer door behind `day::sleep` (docs/async.md): `QTimer::singleShot` on the
6212        // application object, which Qt runs in the application thread wherever it was armed.
6213        // No helper thread. Qt's delay is an `int`; a longer one runs as a chain of timers,
6214        // so the whole delay is honored.
6215        const STEP: u32 = c_int::MAX as u32;
6216        if ms > STEP {
6217            Self::post_delayed(STEP, Box::new(move || Self::post_delayed(ms - STEP, f)));
6218            return;
6219        }
6220        let data = Box::into_raw(Box::new(f)).cast::<c_void>();
6221        unsafe { ffi::day_qt_post_delayed(ms as c_int, run_posted, data) };
6222    }
6223}
6224
6225// Bitmap handles in reactive state can outlive the toolkit's thread-local registry at Quit.
6226// Keep normal releases strict about borrow conflicts, but tolerate a destroyed registry.
6227fn release_bitmap(id: day_spec::BitmapId) {
6228    let _ = BITMAP_INFO.try_with(|m| {
6229        m.borrow_mut().remove(&id.0);
6230        // SAFETY: release a known or already-absent id while toolkit TLS is still alive.
6231        // Do not call into the C++ registry once toolkit teardown has begun.
6232        unsafe { ffi::day_qt_image_release(id.0) };
6233    });
6234}
6235
6236/// Qt's macOS `QFileOpenEvent`; command-line activations on other OSes use day-core.
6237///
6238/// # Safety
6239/// `url` is null or a NUL-terminated C string that stays readable for the length of this call.
6240/// The shim passes the event's URL, which Qt owns and outlives the callback; nothing here keeps
6241/// the pointer past the copy.
6242#[unsafe(no_mangle)]
6243pub unsafe extern "C" fn day_qt_open_file(url: *const std::ffi::c_char) {
6244    day_spec::ffi_guard::contain((), || {
6245        if !url.is_null() {
6246            let file = unsafe { std::ffi::CStr::from_ptr(url) }
6247                .to_string_lossy()
6248                .into_owned();
6249            day_core::request_open_files(vec![file]);
6250        }
6251    });
6252}
6253
6254#[cfg(test)]
6255mod bitmap_teardown_tests {
6256    use super::*;
6257
6258    #[test]
6259    fn releasing_during_bitmap_registry_teardown_does_not_abort() {
6260        const CHILD: &str = "DAY_QT_BITMAP_TEARDOWN_CHILD";
6261        if std::env::var_os(CHILD).is_some() {
6262            struct LateRelease(std::sync::mpsc::Sender<()>);
6263            impl Drop for LateRelease {
6264                fn drop(&mut self) {
6265                    assert!(BITMAP_INFO.try_with(|_| ()).is_err());
6266                    release_bitmap(day_spec::BitmapId(1));
6267                    self.0.send(()).unwrap();
6268                }
6269            }
6270            let (sent, received) = std::sync::mpsc::channel();
6271            std::thread::spawn(move || {
6272                let held = LateRelease(sent);
6273                // The sink and bitmap registry share one TLS group. Dropping its captures
6274                // exercises unavailable TLS without relying on ordering of unrelated keys.
6275                SINK.with(|sink| {
6276                    *sink.borrow_mut() = Some(Rc::new(move |_, _| {
6277                        let _ = &held;
6278                    }));
6279                });
6280            })
6281            .join()
6282            .unwrap();
6283            received
6284                .recv_timeout(std::time::Duration::from_secs(5))
6285                .unwrap();
6286            return;
6287        }
6288        let output = std::process::Command::new(std::env::current_exe().unwrap())
6289            .args([
6290                "--exact",
6291                "bitmap_teardown_tests::releasing_during_bitmap_registry_teardown_does_not_abort",
6292                "--nocapture",
6293            ])
6294            .env(CHILD, "1")
6295            .output()
6296            .unwrap();
6297        assert!(
6298            output.status.success(),
6299            "{}",
6300            String::from_utf8_lossy(&output.stderr)
6301        );
6302    }
6303}
6304
6305#[cfg(test)]
6306mod input_tests {
6307    use super::{contacts, key_phase, pointer_kind};
6308    use day_spec::{KeyPhase, Point, PointerKind, TouchPhase};
6309
6310    #[test]
6311    fn contact_numbers_decode_in_order() {
6312        let numbers = [
6313            7.0, 0.0, 10.0, 20.0, 0.5, 0.0, // a finger going down at half force
6314            9.0, 2.0, 1.0, 2.0, 1.0, 2.0, // a pen held still
6315            0.0, 4.0, 3.0, 4.0, 1.0, 1.0, // the mouse, cancelled
6316            1.0, 3.0, // an incomplete trailing record is ignored
6317        ];
6318        let touches = contacts(&numbers);
6319        assert_eq!(touches.len(), 3);
6320        assert_eq!(touches[0].id, 7);
6321        assert_eq!(touches[0].phase, TouchPhase::Began);
6322        assert_eq!(touches[0].location, Point::new(10.0, 20.0));
6323        assert!((touches[0].pressure - 0.5).abs() < f64::EPSILON);
6324        assert_eq!(touches[0].kind, PointerKind::Touch);
6325        assert_eq!(touches[1].phase, TouchPhase::Stationary);
6326        assert_eq!(touches[1].kind, PointerKind::Stylus);
6327        assert_eq!(touches[2].phase, TouchPhase::Cancelled);
6328        assert_eq!(touches[2].kind, PointerKind::Mouse);
6329    }
6330
6331    #[test]
6332    fn wire_codes_name_phases_and_devices() {
6333        assert_eq!(key_phase(0), KeyPhase::Down);
6334        assert_eq!(key_phase(1), KeyPhase::Repeat);
6335        assert_eq!(key_phase(2), KeyPhase::Up);
6336        assert_eq!(pointer_kind(0), PointerKind::Touch);
6337        assert_eq!(pointer_kind(1), PointerKind::Mouse);
6338        assert_eq!(pointer_kind(2), PointerKind::Stylus);
6339    }
6340}
6341
6342#[cfg(test)]
6343mod surface_tests {
6344    use super::{dynamic, is_styled_surface, surface_is_dynamic, surface_spec};
6345    use day_spec::props::ContainerProps;
6346    use day_spec::{Border, Color, Corners, LinearGradient, Shadow, UnitPoint};
6347
6348    /// A plain colored, rounded surface keeps the stylesheet path; each new field leaves it.
6349    #[test]
6350    fn only_new_fields_take_the_painted_path() {
6351        let plain = ContainerProps {
6352            fill: Some(Color::rgb(1.0, 0.0, 0.0).into()),
6353            corner_radius: 8.0,
6354            clips: true,
6355            ..ContainerProps::default()
6356        };
6357        assert!(!is_styled_surface(&plain));
6358        // A corner choice without a radius rounds nothing, so it changes nothing.
6359        assert!(!is_styled_surface(&ContainerProps {
6360            corner_radius: 0.0,
6361            corners: Corners::TOP,
6362            ..plain.clone()
6363        }));
6364        assert!(is_styled_surface(&ContainerProps {
6365            corners: Corners::TOP,
6366            ..plain.clone()
6367        }));
6368        assert!(is_styled_surface(&ContainerProps {
6369            border: Some(Border::new(Color::WHITE, 1.0)),
6370            ..plain.clone()
6371        }));
6372        assert!(is_styled_surface(&ContainerProps {
6373            shadow: Some(Shadow::new(Color::WHITE, 4.0)),
6374            ..plain.clone()
6375        }));
6376        assert!(is_styled_surface(&ContainerProps {
6377            fill: Some(LinearGradient::vertical(Color::WHITE, Color::WHITE).into()),
6378            ..plain.clone()
6379        }));
6380        // Every gradient kind paints; a solid fill keeps the stylesheet.
6381        assert!(is_styled_surface(&ContainerProps {
6382            fill: Some(
6383                day_spec::RadialGradient::new(UnitPoint::CENTER, 0.5, [(0.0, Color::WHITE)]).into()
6384            ),
6385            ..plain.clone()
6386        }));
6387        assert!(is_styled_surface(&ContainerProps {
6388            fill: Some(
6389                day_spec::ConicGradient::centered(day_spec::Angle::ZERO, [(0.0, Color::WHITE)])
6390                    .into()
6391            ),
6392            ..plain
6393        }));
6394    }
6395
6396    /// A radial fill sends its center and radius, a conic one its center and start angle in
6397    /// degrees; stops go resolved, in order.
6398    #[test]
6399    fn radial_and_conic_fills_reach_the_shim() {
6400        let red = Color::rgb(1.0, 0.0, 0.0);
6401        let blue = Color::rgb(0.0, 0.0, 1.0);
6402        let radial = ContainerProps {
6403            fill: Some(
6404                day_spec::RadialGradient::new(
6405                    UnitPoint::new(0.25, 0.75),
6406                    0.4,
6407                    [(0.0, red), (1.0, blue)],
6408                )
6409                .into(),
6410            ),
6411            ..ContainerProps::default()
6412        };
6413        let (spec, stops) = surface_spec(&radial);
6414        assert_eq!(spec[19..24], [2.0, 0.25, 0.75, 0.4, 0.0]);
6415        assert_eq!(stops, [0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0]);
6416        let conic = ContainerProps {
6417            fill: Some(
6418                day_spec::ConicGradient::new(
6419                    UnitPoint::CENTER,
6420                    day_spec::Angle::rad(std::f64::consts::FRAC_PI_2),
6421                    [(0.0, red), (0.5, blue)],
6422                )
6423                .into(),
6424            ),
6425            ..ContainerProps::default()
6426        };
6427        let (spec, stops) = surface_spec(&conic);
6428        assert_eq!(spec[19..22], [3.0, 0.5, 0.5]);
6429        assert!((spec[22] - 90.0).abs() < 1e-9);
6430        assert_eq!(stops.len(), 10);
6431        assert_eq!(spec[0..4], [0.0, 0.0, 0.0, 0.0]);
6432    }
6433
6434    /// Only an ink that depends on the appearance is kept for a switch.
6435    #[test]
6436    fn a_surface_follows_the_appearance_only_with_a_dynamic_ink() {
6437        let fixed = ContainerProps {
6438            fill: Some(Color::WHITE.into()),
6439            border: Some(Border::new(Color::WHITE, 1.0)),
6440            ..ContainerProps::default()
6441        };
6442        assert!(!surface_is_dynamic(&fixed));
6443        let pair = day_spec::Ink::adaptive(Color::WHITE, Color::BLACK);
6444        assert!(surface_is_dynamic(&ContainerProps {
6445            fill: Some(pair.into()),
6446            ..fixed.clone()
6447        }));
6448        assert!(surface_is_dynamic(&ContainerProps {
6449            border: Some(Border::new(day_spec::SystemColor::Separator, 1.0)),
6450            ..fixed.clone()
6451        }));
6452        assert!(surface_is_dynamic(&ContainerProps {
6453            fill: Some(LinearGradient::vertical(Color::WHITE, pair).into()),
6454            ..fixed
6455        }));
6456        assert!(dynamic(Some(Color::WHITE.into())).is_none());
6457        assert_eq!(dynamic(Some(pair)), Some(pair));
6458    }
6459
6460    /// The spec's slots are the ones shim.cpp's `day_qt_widget_set_styled_surface` reads.
6461    #[test]
6462    fn spec_slots_match_the_shim() {
6463        // A fill is a color or a gradient, never both: the gradient leaves the color slots clear.
6464        let props = ContainerProps {
6465            fill: Some(
6466                LinearGradient::vertical(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0))
6467                    .into(),
6468            ),
6469            corner_radius: 12.0,
6470            corners: Corners::TOP_LEFT | Corners::BOTTOM_RIGHT,
6471            border: Some(Border::new(Color::rgba(0.5, 0.6, 0.7, 0.8), 2.0)),
6472            shadow: Some(Shadow::new(Color::rgba(0.0, 0.0, 0.0, 0.25), 16.0).offset(1.0, 6.0)),
6473            clips: false,
6474            role: None,
6475        };
6476        let (spec, stops) = surface_spec(&props);
6477        assert_eq!(spec[0..4], [0.0, 0.0, 0.0, 0.0]);
6478        assert_eq!(spec[4..7], [12.0, 5.0, 0.0]);
6479        assert_eq!(spec[7..12], [0.5, 0.6, 0.7, 0.8, 2.0]);
6480        assert_eq!(spec[12..19], [0.0, 0.0, 0.0, 0.25, 16.0, 1.0, 6.0]);
6481        let Some(day_spec::Paint::Linear(g)) = &props.fill else {
6482            unreachable!("the gradient set above")
6483        };
6484        assert_eq!(spec[19..24], [1.0, g.start.x, g.start.y, g.end.x, g.end.y]);
6485        assert_eq!(stops.len(), 10);
6486        assert_eq!(stops[0..5], [0.0, 1.0, 0.0, 0.0, 1.0]);
6487        assert_eq!(stops[5..10], [1.0, 0.0, 0.0, 1.0, 1.0]);
6488
6489        // Nothing set: every slot zero but the corner bits, and no stops.
6490        let (spec, stops) = surface_spec(&ContainerProps::default());
6491        assert_eq!(stops, [] as [f64; 0]);
6492        assert!(
6493            spec.iter()
6494                .enumerate()
6495                .all(|(i, v)| (i == 5) == (*v != 0.0))
6496        );
6497        assert_eq!(spec[5], 15.0);
6498    }
6499}
6500
6501#[cfg(test)]
6502mod list_rows_tests {
6503    use super::{RowWork, row_align_code, supplement_rows};
6504    use day_spec::props::RowDelta;
6505    use std::os::raw::c_int;
6506
6507    /// One turn's patches fold into one flush: deltas stay in order, and a reload on either
6508    /// side of them wins.
6509    #[test]
6510    fn row_work_merges_in_arrival_order() {
6511        let a = RowWork::Splice(vec![RowDelta::Insert(0)]);
6512        let b = RowWork::Splice(vec![RowDelta::Move(3, 0), RowDelta::Remove(2)]);
6513        assert_eq!(
6514            RowWork::merge(Some(a), b),
6515            RowWork::Splice(vec![
6516                RowDelta::Insert(0),
6517                RowDelta::Move(3, 0),
6518                RowDelta::Remove(2)
6519            ])
6520        );
6521        let splice = || RowWork::Splice(vec![RowDelta::Insert(1)]);
6522        assert_eq!(RowWork::merge(None, splice()), splice());
6523        assert_eq!(
6524            RowWork::merge(Some(RowWork::Reload), splice()),
6525            RowWork::Reload
6526        );
6527        assert_eq!(
6528            RowWork::merge(Some(splice()), RowWork::Reload),
6529            RowWork::Reload
6530        );
6531        assert_eq!(RowWork::merge(None, RowWork::Reload), RowWork::Reload);
6532    }
6533
6534    /// The shim's triples: kind 0 insert, 1 remove, 2 move, the move's target last.
6535    #[test]
6536    fn row_work_triples() {
6537        let deltas = [
6538            RowDelta::Insert(4),
6539            RowDelta::Remove(1),
6540            RowDelta::Move(5, 2),
6541        ];
6542        assert_eq!(RowWork::triples(&deltas), vec![0, 4, 0, 1, 1, 0, 2, 5, 2]);
6543        assert_eq!(RowWork::triples(&[]), Vec::<c_int>::new());
6544    }
6545
6546    /// The supplementary rows lead and trail the items; the walk finds both runs, an all-
6547    /// supplementary list (header, empty state, footer) whole, and none in a plain list.
6548    #[test]
6549    fn supplement_rows_at_both_ends() {
6550        // [top padding] [header] items 2..8 [footer] [bottom padding]
6551        let rows = supplement_rows(10, &|i| !(2..8).contains(&i));
6552        assert_eq!(rows, vec![0, 1, 8, 9]);
6553        assert_eq!(supplement_rows(3, &|_| true), vec![0, 1, 2]);
6554        assert_eq!(supplement_rows(5, &|_| false), Vec::<usize>::new());
6555        assert_eq!(supplement_rows(0, &|_| true), Vec::<usize>::new());
6556        // Only a trailing footer.
6557        assert_eq!(supplement_rows(4, &|i| i == 3), vec![3]);
6558        // The walk never asks about the items between the runs.
6559        let asked = std::cell::Cell::new(0);
6560        let rows = supplement_rows(1_000_000, &|i| {
6561            asked.set(asked.get() + 1);
6562            i == 0 || i == 999_999
6563        });
6564        assert_eq!(rows, vec![0, 999_999]);
6565        assert!(asked.get() <= 4);
6566    }
6567
6568    #[test]
6569    fn row_align_codes_match_the_shim() {
6570        use day_spec::RowAlign;
6571        assert_eq!(row_align_code(RowAlign::Nearest), 0);
6572        assert_eq!(row_align_code(RowAlign::Start), 1);
6573        assert_eq!(row_align_code(RowAlign::Center), 2);
6574        assert_eq!(row_align_code(RowAlign::End), 3);
6575    }
6576}
6577
6578#[cfg(test)]
6579mod cell_pool_tests {
6580    use super::{CellPool, LIST_OVERSCAN};
6581
6582    /// Drive the pool through a band the way `list_sync` does: park what left, bind what
6583    /// entered, spares first, new cells (fresh keys from `next`) only when none is spare.
6584    fn sync(pool: &mut CellPool, band: std::ops::Range<usize>, next: &mut usize) -> Vec<usize> {
6585        let (parked, need) = pool.retarget(band);
6586        for row in need {
6587            let cell = pool.take_free(false).unwrap_or_else(|| {
6588                *next += 1;
6589                *next
6590            });
6591            pool.bind(row, cell);
6592        }
6593        parked
6594    }
6595
6596    /// `sync` for a sectioned list whose header rows are the multiples of `every`.
6597    fn sync_sectioned(
6598        pool: &mut CellPool,
6599        band: std::ops::Range<usize>,
6600        every: usize,
6601        next: &mut usize,
6602    ) -> (Vec<usize>, usize) {
6603        let (parked, need) = pool.retarget(band);
6604        let mut flips = 0;
6605        for row in need {
6606            let header = row % every == 0;
6607            let cell = pool.take_free(header).unwrap_or_else(|| {
6608                *next += 1;
6609                *next
6610            });
6611            if *next != cell && pool.headers.contains(&cell) != header {
6612                flips += 1;
6613            }
6614            pool.bind(row, cell);
6615            pool.set_kind(cell, header);
6616        }
6617        (parked, flips)
6618    }
6619
6620    #[test]
6621    fn a_scroll_reuses_the_cells_that_left() {
6622        let mut pool = CellPool::default();
6623        let mut next = 0;
6624        assert_eq!(sync(&mut pool, 0..10, &mut next), [] as [usize; 0]);
6625        assert_eq!(pool.len(), 10);
6626        // Five rows scroll out at the top, five come in at the bottom: no new cell.
6627        let parked = sync(&mut pool, 5..15, &mut next);
6628        assert_eq!(parked.len(), 5);
6629        assert_eq!(pool.len(), 10);
6630        assert_eq!(next, 10);
6631        for row in 5..15 {
6632            assert!(pool.bound.contains_key(&row), "row {row} has a cell");
6633        }
6634        for cell in parked {
6635            assert!(
6636                pool.row_of(cell).is_some(),
6637                "the parked cell was re-bound to a new row"
6638            );
6639        }
6640    }
6641
6642    #[test]
6643    fn the_pool_stays_a_window_wide_across_a_long_scroll() {
6644        let mut pool = CellPool::default();
6645        let mut next = 0;
6646        let window = 12 + 2 * LIST_OVERSCAN;
6647        let mut top = 0usize;
6648        while top + window < 100_000 {
6649            sync(&mut pool, top..top + window, &mut next);
6650            assert!(pool.len() <= window, "pool grew to {} cells", pool.len());
6651            top += 7;
6652        }
6653        // A far jump reuses the same cells rather than allocating a second set.
6654        sync(&mut pool, 90_000..90_000 + window, &mut next);
6655        assert_eq!(pool.len(), window);
6656        assert_eq!(next, window);
6657    }
6658
6659    #[test]
6660    fn a_shrunk_band_parks_the_rest_and_keeps_them_spare() {
6661        let mut pool = CellPool::default();
6662        let mut next = 0;
6663        sync(&mut pool, 0..20, &mut next);
6664        let parked = sync(&mut pool, 0..5, &mut next);
6665        assert_eq!(parked.len(), 15);
6666        assert_eq!(pool.bound.len(), 5);
6667        assert_eq!(pool.free.len(), 15);
6668        for cell in &parked {
6669            assert_eq!(pool.row_of(*cell), None);
6670        }
6671        // Growing again takes the spares, newest first, and allocates nothing.
6672        sync(&mut pool, 0..20, &mut next);
6673        assert_eq!(pool.free.len(), 0);
6674        assert_eq!(next, 20);
6675    }
6676
6677    #[test]
6678    fn header_rows_take_header_cells_and_item_rows_item_cells() {
6679        let mut pool = CellPool::default();
6680        let mut next = 0;
6681        let every = 10;
6682        let window = 12 + 2 * LIST_OVERSCAN;
6683        // A window holds at most this many headers, and the pool at most that many more cells
6684        // than a window: each kind keeps its own spares.
6685        let headers = window.div_ceil(every) + 1;
6686        let mut top = 0usize;
6687        while top + window < 10_000 {
6688            let (_, flips) = sync_sectioned(&mut pool, top..top + window, every, &mut next);
6689            assert_eq!(flips, 0, "a cell changed kind at top {top}");
6690            assert!(
6691                pool.len() <= window + headers,
6692                "pool grew to {} cells",
6693                pool.len()
6694            );
6695            top += 3;
6696        }
6697        // A far jump reuses the same cells.
6698        let before = next;
6699        sync_sectioned(&mut pool, 9_000..9_000 + window, every, &mut next);
6700        assert_eq!(next, before);
6701    }
6702
6703    #[test]
6704    fn retarget_is_idempotent() {
6705        let mut pool = CellPool::default();
6706        let mut next = 0;
6707        sync(&mut pool, 3..9, &mut next);
6708        let before: Vec<(usize, usize)> = pool.bound.iter().map(|(r, c)| (*r, *c)).collect();
6709        let parked = sync(&mut pool, 3..9, &mut next);
6710        assert_eq!(parked, [] as [usize; 0]);
6711        let after: Vec<(usize, usize)> = pool.bound.iter().map(|(r, c)| (*r, *c)).collect();
6712        assert_eq!(before, after);
6713    }
6714}
6715
6716#[cfg(test)]
6717mod text_tests {
6718    use super::{css_hex, font_params, label_align, qt_label_markup};
6719    use day_spec::props::TextAlign;
6720    use day_spec::{Color, Decoration, DecorationStyle, Font, FontSpec, MarkupDialect, TextRun};
6721
6722    fn run(range: std::ops::Range<usize>) -> TextRun {
6723        TextRun {
6724            range,
6725            ..TextRun::default()
6726        }
6727    }
6728
6729    #[test]
6730    fn runs_without_a_styled_underline_are_the_shared_markup() {
6731        let text = "a < b and c & d\nnext";
6732        let mut bold = run(2..5);
6733        bold.font.weight = Some(day_spec::FontWeight::Bold);
6734        let mut under = run(10..11);
6735        under.underline = Some(Decoration::SINGLE.color(Color::rgb(1.0, 0.0, 0.0)));
6736        let runs = [bold, under];
6737        assert_eq!(
6738            qt_label_markup(text, &runs, 13.0),
6739            day_spec::runs_to_markup(text, &runs, MarkupDialect::QtHtml, 13.0)
6740        );
6741    }
6742
6743    #[test]
6744    fn a_styled_underline_travels_as_qt_css_around_the_run() {
6745        let text = "Check unknown now";
6746        let mut wavy = run(6..13);
6747        wavy.underline = Some(Decoration::wavy().color(Color::rgb(1.0, 0.0, 0.0)));
6748        let html = qt_label_markup(text, &[wavy], 13.0);
6749        assert_eq!(
6750            html,
6751            "Check <span style=\"text-underline-style:wave;text-decoration-color:#ff0000;\">\
6752             unknown</span> now"
6753        );
6754        let mut dotted = run(0..5);
6755        dotted.underline = Some(Decoration::dotted());
6756        let mut double = run(6..13);
6757        double.underline = Some(Decoration::double());
6758        let html = qt_label_markup(text, &[dotted, double], 13.0);
6759        assert!(html.starts_with("<span style=\"text-underline-style:dotted;\">Check</span> "));
6760        assert!(html.contains("<span style=\"text-underline-style:solid;\">unknown</span>"));
6761        assert!(!html.contains("<u>"));
6762    }
6763
6764    #[test]
6765    fn a_strikethrough_color_is_dropped_and_the_line_kept() {
6766        let mut struck = run(0..6);
6767        struck.strikethrough =
6768            Some(Decoration::new(DecorationStyle::Double).color(Color::rgb(1.0, 0.0, 0.0)));
6769        let html = qt_label_markup("Struck", &[struck], 13.0);
6770        assert_eq!(html, "<s>Struck</s>");
6771        assert_eq!(css_hex(Color::rgb(0.0, 0.5, 1.0)), "#007fff");
6772    }
6773
6774    #[test]
6775    fn a_run_asks_for_no_synthesized_small_caps() {
6776        let mut caps = run(0..4);
6777        caps.font.small_caps = true;
6778        assert_eq!(qt_label_markup("Caps", &[caps], 13.0), "Caps");
6779    }
6780
6781    #[test]
6782    fn a_run_that_misses_the_text_is_skipped() {
6783        let html = qt_label_markup("short", &[run(2..40)], 13.0);
6784        assert_eq!(html, "short");
6785    }
6786
6787    #[test]
6788    fn the_font_carries_scale_and_features() {
6789        let spec = FontSpec {
6790            style: Font::System(20.0),
6791            scale: 1.5,
6792            tabular: true,
6793            small_caps: true,
6794            oldstyle_figures: true,
6795            ..FontSpec::default()
6796        };
6797        let f = font_params(spec);
6798        assert!((f.pt - 30.0).abs() < 1e-9);
6799        assert_eq!((f.tabular, f.small_caps, f.oldstyle), (1, 1, 1));
6800        assert_eq!(label_align(TextAlign::Justified), 3);
6801        assert_eq!(label_align(TextAlign::Trailing), 2);
6802    }
6803}
6804
6805#[cfg(test)]
6806mod anim_tests {
6807    use super::*;
6808
6809    #[test]
6810    fn a_spec_lowers_to_its_delay_cycles_and_direction() {
6811        let run = QtAnim::new(&AnimSpec::linear(600).delay(900));
6812        assert_eq!((run.delay_ms, run.duration_ms, run.cycles), (900, 600, 1));
6813        assert!(!run.autoreverse);
6814        // A linear cycle needs only its two ends: Qt interpolates between key values linearly.
6815        assert_eq!(run.keys, vec![0.0, 1.0]);
6816        let run = QtAnim::new(&AnimSpec::linear(800).repeat(2, true));
6817        assert_eq!((run.cycles, run.autoreverse), (3, true));
6818        let run = QtAnim::new(&AnimSpec::linear(600).repeat_forever(true));
6819        assert_eq!(run.cycles, -1);
6820    }
6821
6822    #[test]
6823    fn a_spring_carries_its_overshooting_samples() {
6824        let spec = AnimSpec::spring(0.9, 0.25);
6825        let run = QtAnim::new(&spec);
6826        assert_eq!(run.keys.len(), spec.keyframes().len());
6827        assert_eq!(run.keys.first().copied(), Some(0.0));
6828        assert_eq!(run.keys.last().copied(), Some(1.0));
6829        // The loose spring passes its target by more than a third on the first swing.
6830        assert!(run.keys.iter().copied().fold(0.0, f64::max) > 1.35);
6831    }
6832
6833    #[test]
6834    fn an_easing_curve_is_sampled_exactly() {
6835        let spec = AnimSpec::ease_in_out(1000);
6836        let run = QtAnim::new(&spec);
6837        let n = run.keys.len() - 1;
6838        let mid = run.keys[n / 2];
6839        // Day's EaseInOut is smoothstep, which Qt's InOutQuad is not away from the middle.
6840        assert!((mid - spec.cycle_progress(0.5)).abs() < 1e-12);
6841        let quarter = run.keys[n / 4];
6842        let t = (n / 4) as f64 / n as f64;
6843        assert!((quarter - t * t * (3.0 - 2.0 * t)).abs() < 1e-12);
6844    }
6845
6846    #[test]
6847    fn the_shim_sees_the_samples_and_none_is_null() {
6848        let spec = AnimSpec::spring(0.4, 0.8).delay(50);
6849        let run = QtAnim::new(&spec);
6850        let raw = run.raw();
6851        assert_eq!(raw.n_keys as usize, run.keys.len());
6852        assert_eq!(raw.keys, run.keys.as_ptr());
6853        assert_eq!(raw.delay_ms, 50);
6854        assert!(with_qt_anim(None, <*const ffi::DayQtAnim>::is_null));
6855        assert!(!with_qt_anim(Some(&spec), <*const ffi::DayQtAnim>::is_null));
6856    }
6857}