Skip to main content

day_toolkit_uikit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-uikit — the ios-uikit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<UIView>`; UIKit is top-left/y-down so Day frames apply directly. The app
7//! boots via `UIApplicationMain` + a `define_class!` app delegate (pane's proven pattern: the
8//! delegate class is force-registered before `UIApplicationMain`, and exposes `window`/
9//! `setWindow:` for the no-scene-manifest compat path). iOS-only (`cfg(target_os = "ios")`);
10//! host builds see an empty crate.
11
12#![allow(unused_unsafe)]
13
14// `setBadgeCount:` lives in UserNotifications; the class lookup needs the framework linked.
15#[cfg(target_os = "ios")]
16#[link(name = "UserNotifications", kind = "framework")]
17unsafe extern "C" {}
18
19#[cfg(target_os = "ios")]
20pub use imp::*;
21
22#[cfg(target_os = "ios")]
23mod controls;
24
25#[cfg(target_os = "ios")]
26mod nav_progress;
27#[cfg(target_os = "ios")]
28mod picker;
29#[cfg(target_os = "ios")]
30mod textarea;
31#[cfg(any(target_os = "ios", test))]
32mod toolbar_policy;
33#[cfg(target_os = "ios")]
34mod transfer;
35
36/// The pure half of the canvas painter (docs/canvas.md "Shadows", "Blend modes", "Conic
37/// gradients"): the graphics state the replay tracks beside Core Graphics' own, and the
38/// arithmetic of the conic gradient. Kept free of UIKit so host tests cover it.
39#[cfg(any(target_os = "ios", test))]
40mod canvas_state {
41    use day_spec::{BlendMode, Color, DrawOp, Shadow};
42
43    /// How many wedges the conic fallback draws for a full turn: half a degree each, which is
44    /// under a pixel of arc out to a 340-point radius at 3x.
45    pub(super) const CONIC_WEDGES: u32 = 720;
46
47    #[derive(Clone, Copy, Default, PartialEq, Debug)]
48    struct Gstate {
49        shadow: bool,
50        blend: BlendMode,
51    }
52
53    /// The shadow and blend mode in force at each point of a replay.
54    ///
55    /// Core Graphics keeps both in its own graphics state and saves and restores them itself.
56    /// This mirror exists because the context has no getter for either, and two things need
57    /// the answer: a gradient is drawn through a clip, which would cut its own shadow off
58    /// unless the draw is grouped first, and `UIImage` drawing names its blend mode per call.
59    #[derive(Default, Debug)]
60    pub(super) struct CanvasState {
61        now: Gstate,
62        saved: Vec<Gstate>,
63    }
64
65    impl CanvasState {
66        /// Follow one op. Only the four state ops change anything.
67        pub(super) fn track(&mut self, op: &DrawOp) {
68            match op {
69                DrawOp::Save => self.saved.push(self.now),
70                // An unbalanced restore keeps the current state, as the context does.
71                DrawOp::Restore => {
72                    if let Some(prev) = self.saved.pop() {
73                        self.now = prev;
74                    }
75                }
76                DrawOp::Shadow(shadow) => self.now.shadow = visible_shadow(*shadow).is_some(),
77                DrawOp::Blend(mode) => self.now.blend = *mode,
78                _ => {}
79            }
80        }
81
82        /// The blend mode drawing combines with now.
83        pub(super) fn blend(&self) -> BlendMode {
84            self.now.blend
85        }
86
87        /// Whether a draw made of several context calls (a clip and a gradient) has to be
88        /// grouped into one transparency layer first, so the shadow and the blend mode apply
89        /// to its result as a whole.
90        pub(super) fn groups(&self) -> bool {
91            self.now.shadow || self.now.blend != BlendMode::Normal
92        }
93    }
94
95    /// The shadow to set, or `None` when the op clears it: an absent shadow, and one whose
96    /// color is fully transparent ([`day_spec::OpCode::SetShadow`]'s clearing form).
97    pub(super) fn visible_shadow(shadow: Option<Shadow>) -> Option<Shadow> {
98        shadow.filter(|s| s.color.resolved().a > 0.0)
99    }
100
101    /// A conic gradient's stops as a full turn: offsets clamped to `0..=1` and ascending, with
102    /// the first color held back to `0` and the last out to `1`, which is how
103    /// [`day_spec::ConicGradient::color_at`] reads stops that do not span the turn.
104    pub(super) fn conic_stops(stops: &[(f64, Color)]) -> Vec<(f64, Color)> {
105        let mut out: Vec<(f64, Color)> = Vec::with_capacity(stops.len() + 2);
106        let (Some(first), Some(last)) = (stops.first(), stops.last()) else {
107            return out;
108        };
109        if first.0 > 0.0 {
110            out.push((0.0, first.1));
111        }
112        let mut at = 0.0_f64;
113        for (offset, color) in stops {
114            at = offset.clamp(at, 1.0);
115            out.push((at, *color));
116        }
117        if last.0 < 1.0 {
118            out.push((1.0, last.1));
119        }
120        out
121    }
122
123    /// The edges of wedge `i` of `count` around a turn starting at `start_deg`, and the angle
124    /// its color is sampled at (the middle), all in canvas degrees. Wedge `i`'s end is wedge
125    /// `i + 1`'s start exactly, so neighbors share an edge and leave no seam.
126    pub(super) fn conic_wedge(start_deg: f64, i: u32, count: u32) -> (f64, f64, f64) {
127        let step = 360.0 / f64::from(count.max(1));
128        let from = start_deg + step * f64::from(i);
129        let to = start_deg + step * f64::from(i + 1);
130        (from, to, start_deg + step * (f64::from(i) + 0.5))
131    }
132
133    #[cfg(test)]
134    mod tests {
135        use super::*;
136        use day_spec::{ConicGradient, Rect, Shape};
137
138        fn shadow(alpha: f64) -> DrawOp {
139            DrawOp::Shadow(Some(Shadow::new(Color::rgba(0.0, 0.0, 0.0, alpha), 4.0)))
140        }
141
142        #[test]
143        fn shadow_and_blend_are_scoped_by_save_and_restore() {
144            let mut s = CanvasState::default();
145            assert!(!s.groups());
146            s.track(&DrawOp::Save);
147            s.track(&shadow(1.0));
148            assert!(s.groups());
149            s.track(&DrawOp::Save);
150            s.track(&DrawOp::Blend(BlendMode::Erase));
151            s.track(&DrawOp::Shadow(None));
152            assert_eq!(s.blend(), BlendMode::Erase);
153            assert!(s.groups());
154            s.track(&DrawOp::Restore);
155            assert_eq!(s.blend(), BlendMode::Normal);
156            assert!(s.groups(), "the outer shadow is back");
157            s.track(&DrawOp::Restore);
158            assert!(!s.groups());
159        }
160
161        #[test]
162        fn transparent_shadow_clears_and_extra_restore_is_ignored() {
163            let mut s = CanvasState::default();
164            s.track(&shadow(1.0));
165            s.track(&shadow(0.0));
166            assert!(!s.groups());
167            s.track(&DrawOp::Blend(BlendMode::Multiply));
168            s.track(&DrawOp::Restore);
169            assert_eq!(s.blend(), BlendMode::Multiply);
170            s.track(&DrawOp::Fill(
171                Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0)),
172                Color::WHITE.into(),
173            ));
174            assert_eq!(s.blend(), BlendMode::Multiply);
175        }
176
177        #[test]
178        fn conic_stops_span_the_turn() {
179            let red = Color::rgba(1.0, 0.0, 0.0, 1.0);
180            let blue = Color::rgba(0.0, 0.0, 1.0, 1.0);
181            assert!(conic_stops(&[]).is_empty());
182            assert_eq!(
183                conic_stops(&[(0.25, red), (0.75, blue)]),
184                vec![(0.0, red), (0.25, red), (0.75, blue), (1.0, blue)]
185            );
186            assert_eq!(
187                conic_stops(&[(0.0, red), (1.0, blue)]),
188                vec![(0.0, red), (1.0, blue)]
189            );
190            // Out-of-range and descending offsets are pulled into an ascending 0..=1 run.
191            assert_eq!(
192                conic_stops(&[(-0.5, red), (0.5, blue), (0.2, red), (1.5, blue)]),
193                vec![(0.0, red), (0.5, blue), (0.5, red), (1.0, blue)]
194            );
195        }
196
197        #[test]
198        fn wedges_tile_the_turn_without_gaps() {
199            let mut end = 30.0;
200            for i in 0..CONIC_WEDGES {
201                let (from, to, mid) = conic_wedge(30.0, i, CONIC_WEDGES);
202                assert!((from - end).abs() < 1e-9);
203                assert!(from < mid && mid < to);
204                end = to;
205            }
206            assert!((end - 390.0).abs() < 1e-9);
207        }
208
209        #[test]
210        fn wedge_colors_follow_the_gradient() {
211            let red = Color::rgba(1.0, 0.0, 0.0, 1.0);
212            let blue = Color::rgba(0.0, 0.0, 1.0, 1.0);
213            let g = ConicGradient::centered(
214                day_spec::Angle::ZERO,
215                vec![(0.0, red), (0.5, red), (0.5, blue)],
216            );
217            let (_, _, first) = conic_wedge(g.start.degrees(), 0, CONIC_WEDGES);
218            let (_, _, last) = conic_wedge(g.start.degrees(), CONIC_WEDGES - 1, CONIC_WEDGES);
219            assert_eq!(g.color_at(day_spec::Angle::deg(first)), red);
220            assert_eq!(g.color_at(day_spec::Angle::deg(last)), blue);
221        }
222    }
223}
224
225/// The pure half of a label's paragraph attributes and selection reports (docs/text.md): the
226/// point values the attributes resolve to, and the conversion from the UTF-16 offsets a
227/// `UITextView` reports to the byte offsets `Event::TextSelected` carries. Kept free of UIKit
228/// so host tests cover it.
229#[cfg(any(target_os = "ios", test))]
230mod label_text {
231    /// The byte offset in `text` of the UTF-16 offset `units`. An offset that falls inside a
232    /// surrogate pair rounds down to the character's start, or past its end with `up`; one
233    /// beyond the text (`NSNotFound` included) clamps to the end.
234    pub(super) fn byte_offset(text: &str, units: usize, up: bool) -> usize {
235        let mut seen = 0;
236        for (i, c) in text.char_indices() {
237            if seen >= units {
238                return i;
239            }
240            let next = seen + c.len_utf16();
241            if next > units {
242                return if up { i + c.len_utf8() } else { i };
243            }
244            seen = next;
245        }
246        text.len()
247    }
248
249    /// A text view's selected range (UTF-16 location and length) as byte offsets into `text`,
250    /// widened to whole characters, `start <= end`.
251    pub(super) fn byte_range(text: &str, location: usize, length: usize) -> (usize, usize) {
252        let start = byte_offset(text, location, false);
253        let end = byte_offset(text, location.saturating_add(length), true).max(start);
254        (start, end)
255    }
256
257    /// The line-height multiple in force, or `None` for the font's natural line height
258    /// (`LabelProps::line_height`: zero, negative and nonfinite all mean natural).
259    pub(super) fn line_height(multiple: f64) -> Option<f64> {
260        (multiple.is_finite() && multiple > 0.0).then_some(multiple)
261    }
262
263    /// The kern in points for `ems` of letter spacing at a font of `points`, or `None` when the
264    /// font's own spacing applies (`LabelProps::letter_spacing` of zero, or nonfinite).
265    pub(super) fn kern(ems: f64, points: f64) -> Option<f64> {
266        (ems.is_finite() && ems != 0.0).then_some(ems * points)
267    }
268
269    /// How far to raise the glyphs so a line box of `line` points centers them: `TextKit` puts a
270    /// fixed line height's extra space above the glyphs, and the CSS model Day follows splits
271    /// it evenly (docs/text.md "Line height").
272    pub(super) fn baseline_offset(line: f64, natural: f64) -> f64 {
273        (line - natural) / 2.0
274    }
275
276    #[cfg(test)]
277    mod tests {
278        use super::*;
279
280        #[test]
281        fn utf16_offsets_become_byte_offsets() {
282            let text = "a€😀b";
283            // a = 1 unit / 1 byte, € = 1 unit / 3 bytes, 😀 = 2 units / 4 bytes.
284            assert_eq!(byte_range(text, 0, 0), (0, 0));
285            assert_eq!(byte_range(text, 0, 1), (0, 1));
286            assert_eq!(byte_range(text, 1, 1), (1, 4));
287            assert_eq!(byte_range(text, 2, 2), (4, 8));
288            assert_eq!(byte_range(text, 4, 1), (8, 9));
289            assert_eq!(byte_range(text, 0, 5), (0, text.len()));
290        }
291
292        #[test]
293        fn a_half_surrogate_widens_to_the_character() {
294            let text = "x😀y";
295            assert_eq!(byte_range(text, 2, 0), (1, 5));
296            assert_eq!(byte_range(text, 1, 1), (1, 5));
297            assert_eq!(byte_range(text, 2, 1), (1, 5));
298        }
299
300        #[test]
301        fn offsets_past_the_end_clamp() {
302            assert_eq!(byte_range("abc", usize::MAX, 0), (3, 3));
303            assert_eq!(byte_range("abc", 1, usize::MAX), (1, 3));
304            assert_eq!(byte_range("", 0, 0), (0, 0));
305        }
306
307        #[test]
308        fn paragraph_values_resolve_to_points() {
309            assert_eq!(line_height(2.0), Some(2.0));
310            assert_eq!(line_height(0.0), None);
311            assert_eq!(line_height(-1.0), None);
312            assert_eq!(line_height(f64::NAN), None);
313            assert_eq!(kern(0.5, 20.0), Some(10.0));
314            assert_eq!(kern(-0.1, 10.0), Some(-1.0));
315            assert_eq!(kern(0.0, 20.0), None);
316            assert_eq!(kern(f64::INFINITY, 20.0), None);
317            assert!((baseline_offset(40.0, 24.0) - 8.0).abs() < 1e-9);
318            assert!((baseline_offset(20.0, 24.0) + 2.0).abs() < 1e-9);
319        }
320    }
321}
322
323/// The pure half of the animation contract on Core Animation (docs/tween.md). Kept free of
324/// UIKit so host tests cover it.
325#[cfg(any(target_os = "ios", test))]
326mod motion_curve {
327    use day_spec::Curve;
328
329    /// The control points `(x1, y1, x2, y2)` of the cubic Bézier that plays `curve` exactly.
330    /// Day's eases `t²`, `1-(1-t)²` and `t²(3-2t)` are each a Bézier whose x runs linearly
331    /// with its parameter (x controls at ⅓ and ⅔), so the y controls are the curve's own
332    /// Bernstein coefficients (linear: the straight line, ⅓ and ⅔ on both axes). A spring is
333    /// not a Bézier: it plays as a `CASpringAnimation` and gets the linear points.
334    pub(super) fn bezier_points(curve: Curve) -> (f64, f64, f64, f64) {
335        match curve {
336            Curve::EaseIn => (1.0 / 3.0, 0.0, 2.0 / 3.0, 1.0 / 3.0),
337            Curve::EaseOut => (1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0, 1.0),
338            Curve::EaseInOut => (1.0 / 3.0, 0.0, 2.0 / 3.0, 1.0),
339            Curve::Linear | Curve::Spring { .. } => (1.0 / 3.0, 1.0 / 3.0, 2.0 / 3.0, 2.0 / 3.0),
340        }
341    }
342
343    /// How many times Core Animation repeats a run of `cycles` cycles (`None` = forever): it
344    /// counts a forward and a backward pass as one repeat when the run autoreverses.
345    pub(super) fn repeat_count(cycles: Option<u32>, autoreverse: bool) -> f32 {
346        #[expect(
347            clippy::cast_precision_loss,
348            reason = "a cycle count past 2^24 plays the same as one a little off"
349        )]
350        let n = cycles.map_or(f32::INFINITY, |n| n as f32);
351        if autoreverse { n / 2.0 } else { n }
352    }
353
354    #[cfg(test)]
355    mod tests {
356        use super::*;
357
358        /// The point at parameter `s` of the cubic Bézier from (0, 0) to (1, 1).
359        fn bezier(p: (f64, f64, f64, f64), s: f64) -> (f64, f64) {
360            let (x1, y1, x2, y2) = p;
361            let u = 1.0 - s;
362            let at = |c1: f64, c2: f64| 3.0 * u * u * s * c1 + 3.0 * u * s * s * c2 + s * s * s;
363            (at(x1, x2), at(y1, y2))
364        }
365
366        #[test]
367        fn each_ease_is_its_bezier() {
368            for curve in [
369                Curve::Linear,
370                Curve::EaseIn,
371                Curve::EaseOut,
372                Curve::EaseInOut,
373            ] {
374                for i in 0..=20 {
375                    let s = f64::from(i) / 20.0;
376                    let (x, y) = bezier(bezier_points(curve), s);
377                    assert!(
378                        (x - s).abs() < 1e-12,
379                        "{curve:?}: x runs with its parameter"
380                    );
381                    let want = curve.fraction(x, 1.0);
382                    assert!((y - want).abs() < 1e-12, "{curve:?} at {x}: {y} vs {want}");
383                }
384            }
385        }
386
387        #[test]
388        fn autoreverse_counts_pairs() {
389            assert!((repeat_count(Some(3), false) - 3.0).abs() < f32::EPSILON);
390            assert!((repeat_count(Some(3), true) - 1.5).abs() < f32::EPSILON);
391            assert!((repeat_count(Some(1), true) - 0.5).abs() < f32::EPSILON);
392            assert!(repeat_count(None, true).is_infinite());
393        }
394    }
395}
396
397/// The pure half of a surface's gradient fill on a `CAGradientLayer` (docs/surfaces.md): the
398/// layer's kind, its unit-space points and its stops. Kept free of UIKit so host tests cover it.
399#[cfg(any(target_os = "ios", test))]
400mod surface_fill {
401    use day_spec::{Color, Ink, Paint};
402
403    /// The `CAGradientLayer` type a paint draws with.
404    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
405    pub(super) enum Kind {
406        Axial,
407        Radial,
408        Conic,
409    }
410
411    /// What a `CAGradientLayer` is set to for one gradient paint.
412    #[derive(Clone, Debug, PartialEq)]
413    pub(super) struct Layout {
414        pub(super) kind: Kind,
415        /// `startPoint`, in the layer's unit space (origin top left, like `UnitPoint`).
416        pub(super) start: (f64, f64),
417        /// `endPoint`, in the same space.
418        pub(super) end: (f64, f64),
419        /// `locations` and `colors`, offsets in `0..=1`.
420        pub(super) stops: Vec<(f64, Color)>,
421    }
422
423    /// `paint` as a `CAGradientLayer` in a frame of `size` points, each ink resolved by
424    /// `resolve`; `None` for a solid paint, which is a background color instead.
425    ///
426    /// - linear: an axial layer from `start` to `end`;
427    /// - radial: a radial layer, `startPoint` the center and `endPoint` the center plus the
428    ///   radius on both axes, so the ellipse is `radius` of the width across and `radius` of
429    ///   the height down, as the gradient's unit space defines it;
430    /// - conic: a conic layer around the center, `endPoint` in the start direction. Core
431    ///   Animation reads that direction in unit space, which a non-square frame stretches, so
432    ///   the point is placed where the on-screen angle is `start`. Stops span the full turn
433    ///   (`conic_stops`), as `ConicGradient::color_at` reads them.
434    pub(super) fn layout(
435        paint: &Paint,
436        size: (f64, f64),
437        resolve: impl Fn(Ink) -> Color,
438    ) -> Option<Layout> {
439        let clamped = |stops: &[(f64, Ink)]| -> Vec<(f64, Color)> {
440            stops
441                .iter()
442                .map(|&(at, ink)| (at.clamp(0.0, 1.0), resolve(ink)))
443                .collect()
444        };
445        match paint {
446            Paint::Solid(_) => None,
447            Paint::Linear(g) => Some(Layout {
448                kind: Kind::Axial,
449                start: (g.start.x, g.start.y),
450                end: (g.end.x, g.end.y),
451                stops: clamped(&g.stops),
452            }),
453            Paint::Radial(g) => Some(Layout {
454                kind: Kind::Radial,
455                start: (g.center.x, g.center.y),
456                end: (g.center.x + g.radius, g.center.y + g.radius),
457                stops: clamped(&g.stops),
458            }),
459            Paint::Conic(g) => {
460                let resolved: Vec<(f64, Color)> = g
461                    .stops
462                    .iter()
463                    .map(|&(at, ink)| (at, resolve(ink)))
464                    .collect();
465                let (sin, cos) = g.start.radians().sin_cos();
466                let (w, h) = size;
467                let (dx, dy) = if w > 0.0 && h > 0.0 {
468                    // A point `cos, sin` away on screen is `cos / w, sin / h` away in unit
469                    // space; scaled so the shorter side's half is the length.
470                    let k = w.min(h) / 2.0;
471                    (cos * k / w, sin * k / h)
472                } else {
473                    (cos / 2.0, sin / 2.0)
474                };
475                Some(Layout {
476                    kind: Kind::Conic,
477                    start: (g.center.x, g.center.y),
478                    end: (g.center.x + dx, g.center.y + dy),
479                    stops: crate::canvas_state::conic_stops(&resolved),
480                })
481            }
482        }
483    }
484
485    #[cfg(test)]
486    mod tests {
487        use super::*;
488        use day_spec::{Angle, ConicGradient, LinearGradient, RadialGradient, UnitPoint};
489
490        const RED: Color = Color::rgb(1.0, 0.0, 0.0);
491        const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
492
493        fn fixed(ink: Ink) -> Color {
494            ink.fixed().unwrap_or(Color::BLACK)
495        }
496
497        #[test]
498        fn a_solid_paint_is_no_gradient() {
499            assert_eq!(layout(&Paint::from(RED), (10.0, 10.0), fixed), None);
500        }
501
502        #[test]
503        fn linear_keeps_its_line_and_clamps_its_stops() {
504            let g = LinearGradient::new(
505                UnitPoint::new(0.0, 0.0),
506                UnitPoint::new(1.0, 1.0),
507                [(-0.5, RED), (1.5, BLUE)],
508            );
509            let l = layout(&Paint::from(g), (10.0, 20.0), fixed).expect("a gradient");
510            assert_eq!(l.kind, Kind::Axial);
511            assert_eq!((l.start, l.end), ((0.0, 0.0), (1.0, 1.0)));
512            assert_eq!(l.stops, vec![(0.0, RED), (1.0, BLUE)]);
513        }
514
515        #[test]
516        fn radial_reaches_the_radius_on_both_axes() {
517            let g = RadialGradient::new(UnitPoint::new(0.25, 0.5), 0.5, [(0.0, RED), (1.0, BLUE)]);
518            let l = layout(&Paint::from(g), (80.0, 40.0), fixed).expect("a gradient");
519            assert_eq!(l.kind, Kind::Radial);
520            assert_eq!((l.start, l.end), ((0.25, 0.5), (0.75, 1.0)));
521        }
522
523        #[test]
524        fn conic_points_at_its_start_angle_on_screen() {
525            for (w, h) in [(80.0, 80.0), (160.0, 40.0), (30.0, 90.0)] {
526                for deg in [0.0, 30.0, 90.0, 135.0, 250.0] {
527                    let g = ConicGradient::new(
528                        UnitPoint::CENTER,
529                        Angle::deg(deg),
530                        [(0.0, RED), (1.0, BLUE)],
531                    );
532                    let l = layout(&Paint::from(g), (w, h), fixed).expect("a gradient");
533                    assert_eq!(l.kind, Kind::Conic);
534                    let (dx, dy) = ((l.end.0 - l.start.0) * w, (l.end.1 - l.start.1) * h);
535                    let shown = dy.atan2(dx).to_degrees().rem_euclid(360.0);
536                    assert!((shown - deg).abs() < 1e-9, "{w}x{h} at {deg}: {shown}");
537                }
538            }
539        }
540
541        #[test]
542        fn conic_stops_span_the_turn() {
543            let g = ConicGradient::centered(Angle::ZERO, [(0.25, RED), (0.75, BLUE)]);
544            let l = layout(&Paint::from(g), (0.0, 0.0), fixed).expect("a gradient");
545            assert_eq!(
546                l.stops,
547                vec![(0.0, RED), (0.25, RED), (0.75, BLUE), (1.0, BLUE)]
548            );
549        }
550    }
551}
552
553/// The pure half of list splices, viewport reports, scroll snapping and pager progress
554/// (docs/list.md, docs/scroll.md, docs/pager.md). Kept free of UIKit so host tests cover it.
555#[cfg(any(target_os = "ios", test))]
556mod scrolling {
557    use day_spec::props::RowDelta;
558
559    /// A run of Day's sequential row deltas as the one batch `UITableView` takes: deletions
560    /// by the index a row had before the change, insertions by the index it has after, and
561    /// moves from one to the other.
562    #[derive(Debug, Default, PartialEq, Eq)]
563    pub(super) struct Batch {
564        pub deletes: Vec<usize>,
565        pub inserts: Vec<usize>,
566        pub moves: Vec<(usize, usize)>,
567    }
568
569    /// Folds `deltas`, each counted against the list the previous ones left (docs/list.md
570    /// "Splices"), over a table of `old` rows into one [`Batch`]. The deltas are replayed over
571    /// the old rows' identities; each final row is then an old row (moved, or carried along
572    /// in order) or a new one. Only rows a `Move` touched become batch moves: every other
573    /// surviving row keeps its order relative to the others, which is how `UITableView`
574    /// places the rows a batch does not name. `None` when a delta is out of range for the
575    /// list it applies to.
576    pub(super) fn fold(old: usize, deltas: &[RowDelta]) -> Option<Batch> {
577        // Per row: the old index and whether a move touched it; `None` for a new row.
578        let mut rows: Vec<Option<(usize, bool)>> = (0..old).map(|i| Some((i, false))).collect();
579        for delta in deltas {
580            match *delta {
581                RowDelta::Insert(at) => {
582                    if at > rows.len() {
583                        return None;
584                    }
585                    rows.insert(at, None);
586                }
587                RowDelta::Remove(at) => {
588                    if at >= rows.len() {
589                        return None;
590                    }
591                    rows.remove(at);
592                }
593                RowDelta::Move(from, to) => {
594                    if from >= rows.len() {
595                        return None;
596                    }
597                    let row = rows.remove(from);
598                    if to > rows.len() {
599                        return None;
600                    }
601                    rows.insert(to, row.map(|(was, _)| (was, true)));
602                }
603            }
604        }
605        let mut kept = vec![false; old];
606        let mut batch = Batch::default();
607        for (at, row) in rows.iter().enumerate() {
608            match *row {
609                None => batch.inserts.push(at),
610                Some((was, moved)) => {
611                    kept[was] = true;
612                    if moved {
613                        batch.moves.push((was, at));
614                    }
615                }
616            }
617        }
618        batch.deletes = (0..old).filter(|i| !kept[*i]).collect();
619        Some(batch)
620    }
621
622    /// Where each of a table's `old` rows ends once `deltas` land: its final index, `None`
623    /// for a row they remove. The table's rows mean the source's through this while a change
624    /// is on its way to it (`DayListData::hold`). `None` when a delta is out of range.
625    pub(super) fn final_rows(old: usize, deltas: &[RowDelta]) -> Option<Vec<Option<usize>>> {
626        let mut rows: Vec<Option<usize>> = (0..old).map(Some).collect();
627        for delta in deltas {
628            match *delta {
629                RowDelta::Insert(at) if at <= rows.len() => rows.insert(at, None),
630                RowDelta::Remove(at) if at < rows.len() => {
631                    rows.remove(at);
632                }
633                RowDelta::Move(from, to) if from < rows.len() && to < rows.len() => {
634                    let row = rows.remove(from);
635                    rows.insert(to, row);
636                }
637                _ => return None,
638            }
639        }
640        let mut finals = vec![None; old];
641        for (at, row) in rows.iter().enumerate() {
642            if let Some(was) = row {
643                finals[*was] = Some(at);
644            }
645        }
646        Some(finals)
647    }
648
649    /// How far the end of the content is below the end of the viewport, in points
650    /// (`ListViewport::end_distance`): the table's own bottom inset (a safe area, the
651    /// keyboard) is not content, and an overscroll past the end reports zero.
652    pub(super) fn end_distance(content: f64, offset: f64, viewport: f64, inset_end: f64) -> f64 {
653        (content - (offset + viewport - inset_end)).max(0.0)
654    }
655
656    /// Where a drag released toward `target` comes to rest on a grid of `interval` points
657    /// (`ScrollSnap::Interval`, docs/scroll.md "Snapping"): the stop nearest the target, never
658    /// one behind the release point against the direction of the fling, clamped to
659    /// `0..=max`. Offsets count from the start of the scroll range.
660    pub(super) fn snap_stop(
661        target: f64,
662        current: f64,
663        velocity: f64,
664        interval: f64,
665        max: f64,
666    ) -> f64 {
667        if !(interval.is_finite() && interval > 0.0 && target.is_finite()) {
668            return target;
669        }
670        let mut stop = (target / interval).round() * interval;
671        if velocity > 0.0 && stop < current {
672            stop = (current / interval).ceil() * interval;
673        } else if velocity < 0.0 && stop > current {
674            stop = (current / interval).floor() * interval;
675        }
676        stop.clamp(0.0, max.max(0.0))
677    }
678
679    /// A pager's position in reading-order pages (docs/pager.md "Progress"): the place of
680    /// the page the scroll view holds as current, plus how far the content has moved from
681    /// that page's origin toward the next, in page widths. `forward` is -1 where the next
682    /// page lies to the left (right-to-left).
683    pub(super) fn pager_position(
684        place: usize,
685        offset: f64,
686        origin: f64,
687        width: f64,
688        forward: f64,
689    ) -> f64 {
690        if !(width.is_finite() && width > 0.0) {
691            return place as f64;
692        }
693        place as f64 + forward * (offset - origin) / width
694    }
695
696    #[cfg(test)]
697    mod tests {
698        use super::*;
699        use day_spec::props::RowDelta::{Insert, Move, Remove};
700
701        /// Plays a batch the way `UITableView` does, over labeled rows: deletions and moved
702        /// rows leave, insertions and moved rows land at their final indices, and the rest
703        /// fill the remaining slots in their old order.
704        fn play(old: &[u32], batch: &Batch, new_rows: &mut dyn Iterator<Item = u32>) -> Vec<u32> {
705            let len = old.len() - batch.deletes.len() + batch.inserts.len();
706            let mut out: Vec<Option<u32>> = vec![None; len];
707            for &at in &batch.inserts {
708                out[at] = new_rows.next();
709            }
710            for &(from, to) in &batch.moves {
711                out[to] = Some(old[from]);
712            }
713            let mut rest = (0..old.len())
714                .filter(|i| !batch.deletes.contains(i) && !batch.moves.iter().any(|m| m.0 == *i))
715                .map(|i| old[i]);
716            out.into_iter()
717                .map(|slot| slot.or_else(|| rest.next()).unwrap_or(0))
718                .collect()
719        }
720
721        /// The same deltas applied one at a time.
722        fn sequential(
723            old: &[u32],
724            deltas: &[RowDelta],
725            new_rows: &mut dyn Iterator<Item = u32>,
726        ) -> Vec<u32> {
727            let mut rows = old.to_vec();
728            for delta in deltas {
729                match *delta {
730                    Insert(at) => rows.insert(at, new_rows.next().unwrap_or(0)),
731                    Remove(at) => {
732                        rows.remove(at);
733                    }
734                    Move(from, to) => {
735                        let row = rows.remove(from);
736                        rows.insert(to, row);
737                    }
738                }
739            }
740            rows
741        }
742
743        #[test]
744        fn the_conformance_edits_fold_into_batches() {
745            // Insert at the top, last to the top, remove from the middle.
746            for (old, deltas) in [
747                (vec![1, 2, 3], vec![Insert(0)]),
748                (vec![9, 1, 2, 3], vec![Move(3, 0)]),
749                (vec![3, 9, 1, 2], vec![Remove(2)]),
750                (vec![1, 2], vec![Insert(2)]),
751            ] {
752                let batch = fold(old.len(), &deltas).expect("in range");
753                let mut a = 100..;
754                let mut b = 100..;
755                // New rows are numbered in the order the batch inserts them, top down; the
756                // sequential replay numbers them as they arrive, so compare with one insert at
757                // most per case.
758                assert_eq!(
759                    play(&old, &batch, &mut a),
760                    sequential(&old, &deltas, &mut b)
761                );
762            }
763        }
764
765        #[test]
766        fn a_run_of_appends_is_one_insert_batch() {
767            // day-core appends bottom-up: each new row lands above the one placed before it.
768            let deltas: Vec<_> = (0..5).map(|_| Insert(3)).collect();
769            let batch = fold(3, &deltas).expect("in range");
770            assert_eq!(batch.inserts, vec![3, 4, 5, 6, 7]);
771            assert!(batch.deletes.is_empty() && batch.moves.is_empty());
772        }
773
774        #[test]
775        fn mixed_runs_keep_the_untouched_rows_in_order() {
776            let old: Vec<u32> = (0..8).collect();
777            let deltas = [Remove(6), Remove(2), Move(0, 4), Move(5, 1), Remove(0)];
778            let batch = fold(old.len(), &deltas).expect("in range");
779            let mut none = std::iter::empty();
780            let mut also_none = std::iter::empty();
781            assert_eq!(
782                play(&old, &batch, &mut none),
783                sequential(&old, &deltas, &mut also_none)
784            );
785            assert_eq!(batch.deletes, vec![1, 2, 6]);
786        }
787
788        #[test]
789        fn a_moved_then_removed_row_is_a_deletion_and_a_new_row_is_never_a_move() {
790            let batch = fold(3, &[Move(0, 2), Remove(2), Insert(0), Move(0, 2)]).expect("in range");
791            assert_eq!(batch.deletes, vec![0]);
792            assert_eq!(batch.inserts, vec![2]);
793            assert!(batch.moves.is_empty());
794        }
795
796        #[test]
797        fn a_table_row_means_where_its_row_ends() {
798            // The probe's change: two rows at the top, one removed below, two swapped.
799            let deltas = [Insert(0), Insert(0), Remove(40), Move(3, 4)];
800            let finals = final_rows(50, &deltas).expect("in range");
801            // Old row 0 ends at 2, old 1 at 4 and old 2 at 3 (the swap), old 38 is removed.
802            assert_eq!(&finals[..4], &[Some(2), Some(4), Some(3), Some(5)]);
803            assert_eq!(finals[38], None);
804            assert_eq!(finals[39], Some(40));
805            // The same rows the sequential replay leaves, row for row.
806            let old: Vec<u32> = (0..50).collect();
807            let mut fresh = 100..;
808            let after = sequential(&old, &deltas, &mut fresh);
809            for (was, end) in finals.iter().enumerate() {
810                if let Some(end) = end {
811                    assert_eq!(after[*end], old[was]);
812                }
813            }
814            assert_eq!(final_rows(2, &[Remove(2)]), None);
815        }
816
817        #[test]
818        fn out_of_range_deltas_do_not_fold() {
819            assert_eq!(fold(2, &[Remove(2)]), None);
820            assert_eq!(fold(2, &[Insert(3)]), None);
821            assert_eq!(fold(2, &[Move(2, 0)]), None);
822            assert_eq!(fold(2, &[Move(0, 2)]), None);
823        }
824
825        #[test]
826        fn the_end_distance_ignores_the_bottom_inset_and_overscroll() {
827            assert!((end_distance(1000.0, 0.0, 200.0, 0.0) - 800.0).abs() < 1e-9);
828            assert!(end_distance(1000.0, 834.0, 200.0, 34.0).abs() < 1e-9);
829            assert!(end_distance(1000.0, 900.0, 200.0, 0.0).abs() < 1e-9);
830            assert!(end_distance(100.0, 0.0, 200.0, 0.0).abs() < 1e-9);
831        }
832
833        #[test]
834        fn snapping_rounds_to_the_grid_with_the_fling() {
835            // Released at 130 with no fling: the nearest stop.
836            assert!((snap_stop(130.0, 130.0, 0.0, 100.0, 1000.0) - 100.0).abs() < 1e-9);
837            // A forward fling whose projected target rounds back still moves forward.
838            assert!((snap_stop(140.0, 130.0, 0.5, 100.0, 1000.0) - 200.0).abs() < 1e-9);
839            assert!((snap_stop(120.0, 130.0, -0.5, 100.0, 1000.0) - 100.0).abs() < 1e-9);
840            // Far flings keep their projected stop, clamped to the range.
841            assert!((snap_stop(640.0, 130.0, 3.0, 100.0, 1000.0) - 600.0).abs() < 1e-9);
842            assert!((snap_stop(1240.0, 900.0, 3.0, 100.0, 950.0) - 950.0).abs() < 1e-9);
843            assert!(snap_stop(-80.0, 30.0, -1.0, 100.0, 950.0).abs() < 1e-9);
844            // No grid: the target stands.
845            assert!((snap_stop(123.0, 0.0, 0.0, 0.0, 950.0) - 123.0).abs() < 1e-9);
846        }
847
848        #[test]
849        fn pager_position_follows_the_content_in_reading_order() {
850            assert!((pager_position(1, 390.0, 390.0, 390.0, 1.0) - 1.0).abs() < 1e-9);
851            assert!((pager_position(1, 585.0, 390.0, 390.0, 1.0) - 1.5).abs() < 1e-9);
852            // Right to left: the next page lies to the left.
853            assert!((pager_position(1, 195.0, 390.0, 390.0, -1.0) - 1.5).abs() < 1e-9);
854            assert!((pager_position(2, 10.0, 0.0, 0.0, 1.0) - 2.0).abs() < 1e-9);
855        }
856    }
857}
858
859/// Set a `UITextInputTraits` integer property on a `UITextView` (0 = on/default, 1 = off) —
860/// dispatched through the raw runtime, since objc2's checked send does not see these dynamically
861/// resolved setters. Public for standalone editor pieces (docs/extending.md).
862#[cfg(target_os = "ios")]
863pub use textarea::set_text_input_trait;
864
865#[cfg(target_os = "ios")]
866pub mod ext;
867#[cfg(target_os = "ios")]
868pub use ext::*;
869
870#[cfg(target_os = "ios")]
871mod imp {
872    use std::any::Any;
873    use std::cell::{Cell, RefCell};
874    use std::collections::HashMap;
875    use std::ffi::c_int;
876    use std::ptr::NonNull;
877    use std::rc::Rc;
878
879    use linkme::distributed_slice;
880    use objc2::rc::Retained;
881    use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
882    use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
883    use objc2_core_foundation::{CGAffineTransform, CGFloat, CGPoint, CGRect, CGSize};
884    use objc2_core_graphics::CGContext;
885    use objc2_foundation::{NSObject, NSRange, NSString};
886    use objc2_quartz_core::CADisplayLink;
887    use objc2_ui_kit::UIAdaptivePresentationControllerDelegate;
888    // UIApplicationMain is "deprecated" in objc2 only as a rename to the private
889    // `UIApplication::__main` binding; the classic entry point is what we want.
890    use objc2::Message as _;
891    use objc2_ui_kit::NSIndexPathUIKitAdditions as _;
892    use objc2_ui_kit::NSObjectUIAccessibility;
893    #[allow(deprecated)]
894    use objc2_ui_kit::UIApplicationMain;
895    use objc2_ui_kit::UINavigationControllerDelegate;
896    use objc2_ui_kit::UISearchBarDelegate;
897    use objc2_ui_kit::UISearchResultsUpdating;
898    use objc2_ui_kit::UISplitViewControllerDelegate;
899    use objc2_ui_kit::UITextViewDelegate;
900    use objc2_ui_kit::{
901        UIAction, UIAxis, UIContextMenuConfiguration, UIContextMenuInteraction,
902        UIContextMenuInteractionDelegate, UIInteraction, UIMenu, UIMenuElement,
903        UIMenuElementAttributes, UIMenuOptions, UIPointerEffect, UIPointerHighlightEffect,
904        UIPointerInteraction, UIPointerInteractionDelegate, UIPointerLiftEffect, UIPointerRegion,
905        UIPointerShape, UIPointerStyle, UITargetedPreview,
906    };
907    use objc2_ui_kit::{
908        UIActivityIndicatorView, UIApplication, UIApplicationDelegate, UIButton, UIButtonType,
909        UIColor, UIControl, UIControlEvents, UIControlState, UIEdgeInsets, UILabel,
910        UIModalPresentationStyle, UIProgressView, UIRectEdge, UIScrollView, UISlider, UISwitch,
911        UITextBorderStyle, UITextField, UITextView, UIView, UIViewController, UIWindow,
912    };
913    use objc2_ui_kit::{
914        UIBarButtonItem, UIBarButtonItemStyle, UIBarPositioningDelegate,
915        UIGestureRecognizerDelegate, UINavigationBar, UINavigationBarAppearance,
916        UINavigationBarDelegate, UINavigationController, UINavigationItem,
917    };
918    use objc2_ui_kit::{
919        UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate,
920        UITableViewDataSource, UITableViewDelegate, UITableViewDragDelegate,
921    };
922    use objc2_ui_kit::{
923        UIGestureRecognizer, UIGestureRecognizerState, UIPanGestureRecognizer,
924        UIPinchGestureRecognizer, UIRotationGestureRecognizer, UITapGestureRecognizer,
925    };
926    use objc2_ui_kit::{
927        UIKeyInput as _, UIKeyboardType, UIReturnKeyType, UITextAutocapitalizationType,
928        UITextContentTypeEmailAddress, UITextContentTypeName, UITextContentTypeNewPassword,
929        UITextContentTypeOneTimeCode, UITextContentTypePassword, UITextContentTypeTelephoneNumber,
930        UITextContentTypeURL, UITextContentTypeUsername, UITextFieldDelegate, UITextInput as _,
931        UITextInputTraits as _,
932    };
933    use objc2_ui_kit::{UITabBarController, UITabBarControllerDelegate};
934    // `.import`/`.exportToService` modes (deprecated in favor of `initFor…ContentTypes:`, which
935    // would pull in the UniformTypeIdentifiers crate) remain the simplest UTType-free path.
936    #[allow(deprecated)]
937    use objc2_ui_kit::UIDocumentPickerMode;
938    use objc2_ui_kit::{UIDocumentPickerDelegate, UIDocumentPickerViewController};
939
940    use day_spec::props::*;
941    use day_spec::{
942        A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Edges, Event, EventSink, Font,
943        InputPurpose, InputTraits, ListSource, NodeId, PieceKind, Platform, Proposal, RawHandle,
944        Rect, Registry, Renderer, Size, SubmitLabel, Support, Toolkit, Transform, TreeSource,
945        WINDOW_NODE, WindowOptions, kinds,
946    };
947
948    pub type Handle = Retained<UIView>;
949
950    /// The day-core event sink (node-id keyed).
951    type Sink = Rc<dyn Fn(NodeId, Event)>;
952
953    /// `DAY_DIAG_NAV` tracing, resolved once — the layout and nav-delegate hot paths run on
954    /// every pass and must not re-query the environment each time.
955    static DIAG_NAV: std::sync::LazyLock<bool> =
956        std::sync::LazyLock::new(|| std::env::var("DAY_DIAG_NAV").is_ok());
957
958    day_core::tls_group! {
959        static BUTTON_CONTENT: day_spec::sidetable::SideTable<day_spec::props::ButtonContent> = day_spec::sidetable::SideTable::new();
960        /// Views the app gave an accessibility label (`set_a11y`): a button's title change must
961        /// then leave the label alone (`apply_button_content`). Swept on release.
962        static APP_LABELED: day_spec::sidetable::SideTable<()> = day_spec::sidetable::SideTable::new();
963        /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether
964        /// it was realized as a template, and whether a tint is on it now. Rendering mode is a
965        /// property of the UIImage, so a source swap has to re-apply it, and a tint patch of
966        /// `None` keeps a template in the inherited tint rather than returning to the authored
967        /// art. Swept on release.
968        static IMAGE_MODES: day_spec::sidetable::SideTable<ImageMode> =
969            day_spec::sidetable::SideTable::new();
970        /// Surfaces whose layer holds a color from an ink that follows the appearance, or a
971        /// gradient (`apply_surface`): re-resolved on a trait change and re-fitted on layout.
972        /// Swept on release.
973        static SURFACES: day_spec::sidetable::SideTable<SurfaceState> =
974            day_spec::sidetable::SideTable::new();
975
976        static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
977        static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
978        static WINDOW: RefCell<Option<Retained<UIWindow>>> = const { RefCell::new(None) };
979        /// The Day content root + its keyboard-less frame (window coords) — keyboard avoidance
980        /// (docs/focus.md) shrinks the root to the keyboard top and restores this on dismiss.
981        static ROOT_VIEW: RefCell<Option<Retained<UIView>>> = const { RefCell::new(None) };
982        static ROOT_BASE_FRAME: Cell<CGRect> = const {
983            Cell::new(CGRect {
984                origin: CGPoint { x: 0.0, y: 0.0 },
985                size: CGSize {
986                    width: 0.0,
987                    height: 0.0,
988                },
989            })
990        };
991        /// The UITextField that currently owns the keyboard (editBegan/editEnded), so the
992        /// keyboard handler can reveal it inside its enclosing UIScrollView.
993        static FOCUSED_FIELD: RefCell<Option<Retained<UIView>>> = const { RefCell::new(None) };
994        /// Whether the software keyboard covers part of the key window, as its last
995        /// `keyboardWillChange:` said: what `KeyboardTaps::Dismiss` waits for (docs/scroll.md
996        /// "Keyboard").
997        static KEYBOARD_UP: Cell<bool> = const { Cell::new(false) };
998        #[allow(clippy::type_complexity)]
999        static PENDING: RefCell<Option<(Uikit, WindowOptions, Box<dyn FnOnce(Uikit, Handle, Size)>)>> =
1000            RefCell::new(None);
1001        static FRAMES: RefCell<HashMap<usize, FrameSource>> = RefCell::new(HashMap::new());
1002        /// Connected scenes' windowing state (docs/windows.md). The PRIMARY scene also
1003        /// mirrors into WINDOW/ROOT_VIEW/ROOT_BASE_FRAME above (every single-window code
1004        /// path keeps reading those); secondary day windows are registry-only.
1005        static SCENES: RefCell<Vec<SceneEntry>> = const { RefCell::new(Vec::new()) };
1006        /// Secondary opens in flight: the day root node ids handed to
1007        /// `requestSceneSessionActivation`, awaiting their scene's willConnect.
1008        static PENDING_WINDOWS: RefCell<Vec<(NodeId, String)>> = const { RefCell::new(Vec::new()) };
1009        /// A scene the PLATFORM opened (iPadOS Window ▸ New Window, an app icon dragged into
1010        /// Split View, a session restored from a previous run): set while the delegate asks
1011        /// day-core for content, so the `open_window` that call comes back through adopts this
1012        /// scene instead of requesting another one, and reports the node it was given.
1013        static ADOPTING_SCENE: Cell<Option<NodeId>> = const { Cell::new(None) };
1014        static ADOPTING: Cell<bool> = const { Cell::new(false) };
1015        /// Nonzero while a window is between size classes: `willTransitionToTraitCollection:`
1016        /// through the coordinator's completion. A `UISplitViewController` merges its columns
1017        /// when it collapses and takes them apart again when it expands, and the un-merge is a
1018        /// real pop on the primary's controller — the same call a user's back makes
1019        /// (docs/navigation.md).
1020        static CLASS_TRANSITIONS: Cell<usize> = const { Cell::new(0) };
1021        /// Bumped by each size-class transition, so a late ceiling releases only its own.
1022        static CLASS_TRANSITION_GEN: Cell<u64> = const { Cell::new(0) };
1023        /// App-level lifecycle debounce across scenes: whether any scene was
1024        /// foreground-active / any scene was foregrounded at the last recompute.
1025        static ANY_SCENE_ACTIVE: Cell<bool> = const { Cell::new(false) };
1026        static ANY_SCENE_FOREGROUND: Cell<bool> = const { Cell::new(false) };
1027
1028        /// Each link-carrying text view's delegate, kept alive for the view's lifetime (a
1029        /// `UITextView` holds its delegate weakly). Swept on release.
1030        /// The link a tap just reported, and when (`DayTextLink::tapped`), so the text view's own
1031        /// delegate call for the same tap, which arrives later, is not reported twice.
1032        static LAST_LINK_TAP: RefCell<Option<(String, std::time::Instant)>> =
1033            const { RefCell::new(None) };
1034        static TEXT_LINKS: day_spec::sidetable::SideTable<Retained<DayTextLink>> =
1035            day_spec::sidetable::SideTable::new();
1036        /// Each label's paragraph attributes, alignment, direction and selection reports
1037        /// (`LabelLook`), keyed by its backing view and moved along by the `.selectable()`
1038        /// swap. Swept on release.
1039        static LABEL_LOOKS: day_spec::sidetable::SideTable<LabelLook> =
1040            day_spec::sidetable::SideTable::new();
1041
1042        /// Keeps each view's gesture targets alive + records which are attached (idempotent).
1043        static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
1044            RefCell::new(HashMap::new());
1045        /// Each view's press and touches observers (docs/gestures.md "Press", "Touches"), kept
1046        /// alive beside the view's recognizers. Swept on release.
1047        static OBSERVERS: day_spec::sidetable::SideTable<Vec<Retained<DayObserver>>> =
1048            day_spec::sidetable::SideTable::new();
1049        /// The area a view takes pointer input in beyond its bounds (`set_hit_slop`,
1050        /// docs/gestures.md "Hit slop"). Read by the hit tests of Day's container and canvas
1051        /// views. Swept on release.
1052        static HIT_SLOP: day_spec::sidetable::SideTable<day_spec::Insets> =
1053            day_spec::sidetable::SideTable::new();
1054        /// The one axis a view's drag follows (`set_drag_axis`, docs/gestures.md "Gestures
1055        /// inside a scroll view"). Swept on release.
1056        static DRAG_AXIS: day_spec::sidetable::SideTable<day_spec::DragAxis> =
1057            day_spec::sidetable::SideTable::new();
1058        /// How many disabled groups a view roots (`set_subtree_enabled`, docs/forms.md
1059        /// "Disabling a group"). Swept on release.
1060        static GROUP_OFF: day_spec::sidetable::SideTable<GroupOff> =
1061            day_spec::sidetable::SideTable::new();
1062        /// A view inside one or more disabled groups that the walk changed: how many groups
1063        /// hold it, and what it had before the first. Swept on release.
1064        static HELD_OFF: day_spec::sidetable::SideTable<HeldOff> =
1065            day_spec::sidetable::SideTable::new();
1066        /// The hardware keys a focused view claimed the down of and has not seen come up yet
1067        /// (docs/menus.md "Keys"): the release goes to the same node. Swept on release.
1068        static KEYS_DOWN: day_spec::sidetable::SideTable<Vec<HeldKey>> =
1069            day_spec::sidetable::SideTable::new();
1070        /// The kind of device the last pointer down came from, as last reported
1071        /// (`Event::PointerKindChanged`, docs/gestures.md "Input kind").
1072        static POINTER_KIND: Cell<day_spec::PointerKind> =
1073            const { Cell::new(day_spec::PointerKind::Touch) };
1074        /// The window-level observers that report the input kind, one per window.
1075        static POINTER_WATCH: RefCell<Vec<Retained<DayObserver>>> = const { RefCell::new(Vec::new()) };
1076        /// Per-view context-menu interaction + its delegate (kept alive; replaced on
1077        /// reconfigure, swept on release via `day_spec::sidetable`). The teardown detaches
1078        /// the interaction from its view first, so a recycled address can never serve a dead
1079        /// view's menu, then drops both retains.
1080        /// The summon-time providers' interactions, same lifecycle rules as CTX_MENUS.
1081        static CTX_MENU_FNS: RefCell<HashMap<usize, (
1082            Retained<UIContextMenuInteraction>,
1083            Retained<DayContextMenuFn>,
1084        )>> = RefCell::new(HashMap::new());
1085        static CTX_MENUS: day_spec::sidetable::SideTable<(
1086            Retained<UIContextMenuInteraction>,
1087            Retained<DayContextMenu>,
1088        )> = day_spec::sidetable::SideTable::with_teardown(
1089            |(interaction, _delegate): (
1090                Retained<UIContextMenuInteraction>,
1091                Retained<DayContextMenu>,
1092            )| {
1093                // `view` is the interaction's weak back-pointer — present exactly while it
1094                // is still attached, which is when the detach matters.
1095                if let Some(v) = interaction.view() {
1096                    v.removeInteraction(ProtocolObject::from_ref(&*interaction));
1097                }
1098            },
1099        );
1100
1101        /// Keyed by the nav host view ptr (the UINavigationController's view).
1102        static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
1103        /// Page CONTENT view ptr → its UIViewController.
1104        static PAGE_VCS: RefCell<HashMap<usize, Retained<UIViewController>>> =
1105            RefCell::new(HashMap::new());
1106        /// Handles whose frames are native-owned (page content views).
1107        static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
1108            RefCell::new(std::collections::HashSet::new());
1109        /// Each nav page's pane, recorded at realize because `insert` sees only handles
1110        /// (docs/size-classes.md). The SIDEBAR page is the split host's primary column; every
1111        /// other page is a detail, pushed on the secondary's stack. Swept on release via
1112        /// `day_spec::sidetable`.
1113        static PAGE_PANE: day_spec::sidetable::SideTable<day_spec::props::Pane> =
1114            day_spec::sidetable::SideTable::new();
1115
1116
1117        /// Cover content view ptr → its presentation state.
1118        static COVER_STATE: RefCell<HashMap<usize, CoverState>> = RefCell::new(HashMap::new());
1119        /// The current `defers_system_gestures` union (day `Edges` bits) — read by the root
1120        /// and cover VCs' `preferredScreenEdgesDeferringSystemGestures` overrides.
1121        static DEFER_EDGES: Cell<u8> = const { Cell::new(0) };
1122        /// Whether a mounted `status_bar_hidden` asks for the bar hidden — read by the root
1123        /// and cover VCs' `prefersStatusBarHidden` overrides.
1124        static STATUS_BAR_HIDDEN: Cell<bool> = const { Cell::new(false) };
1125
1126        pub(super) static UNDO_FRONT: RefCell<Option<Retained<DayUndoManager>>> =
1127            const { RefCell::new(None) };
1128
1129        /// The app's edit-bridge state (`set_edit_state`) — what canPerformAction consults.
1130        static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
1131            const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
1132
1133        static DOCUMENT_HOSTS: RefCell<HashMap<usize, DocumentHost>> = RefCell::new(HashMap::new());
1134        static NAV_TABS: RefCell<HashMap<usize, NavTabsState>> = RefCell::new(HashMap::new());
1135        /// A realized NAV_MENU's rows, by its own view ptr. Recorded at realize because that is
1136        /// where the props are, and consumed at INSERT, which is the first moment the menu is in
1137        /// a view hierarchy and its enclosing host can be found.
1138        /// A tabs host's page content views → the host, so a nav menu inside a page that is not
1139        /// in the controller's hierarchy can still find it.
1140        static TABS_PAGE_HOST: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
1141        /// Icon NAMES, not resolved images: a tab resolves its own through the named-image path,
1142        /// so it gets the glyph's vector at the size the ASSET presents itself at.
1143        static NAV_MENU_ROWS: RefCell<HashMap<usize, (i64, NavTabRows)>> =
1144            RefCell::new(HashMap::new());
1145
1146        /// NAV_MENU table ptr → (data source, row count).
1147        static NAV_MENUS: RefCell<HashMap<usize, (Retained<DayNavTableData>, usize)>> =
1148            RefCell::new(HashMap::new());
1149
1150        /// LIST table ptr → (table, data source).
1151        static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
1152
1153        /// TREE collection-view ptr → its delegate/state object (docs/tree.md).
1154        static TREE_STATE: RefCell<HashMap<usize, Retained<DayTreeData>>> =
1155            RefCell::new(HashMap::new());
1156
1157        /// Canvas view ptr → its display list. Swept on release via `day_spec::sidetable` —
1158        /// a stale entry made a NEW DayCanvasView at a dead canvas's recycled address replay
1159        /// the old display list until its first `replay`.
1160        static OPS: day_spec::sidetable::SideTable<Vec<day_spec::DrawOp>> =
1161            day_spec::sidetable::SideTable::new();
1162        /// Canvas view ptr → its node, so the view's own key handling knows who to report to
1163        /// (docs/menus.md). Every canvas is registered at realize: focus, not a gesture, is
1164        /// what decides who hears a key.
1165        static KEY_NODES: day_spec::sidetable::SideTable<NodeId> =
1166            day_spec::sidetable::SideTable::new();
1167
1168        /// Live alert controllers keyed by request id (for programmatic dismissal).
1169        static PRESENT_VCS: RefCell<HashMap<u64, Retained<objc2_ui_kit::UIAlertController>>> =
1170            RefCell::new(HashMap::new());
1171        /// Live document pickers + their retained delegates, keyed by request id.
1172        #[allow(clippy::type_complexity)]
1173        static PRESENT_PICKERS: RefCell<
1174            HashMap<
1175                u64,
1176                (
1177                    Retained<UIDocumentPickerViewController>,
1178                    Retained<DayDocPicker>,
1179                ),
1180            >,
1181        > = RefCell::new(HashMap::new());
1182        /// FIFO of modal transitions (see [`ModalOp`]) — ops run one at a time, pumped from
1183        /// each transition's completion.
1184        static MODAL_QUEUE: RefCell<std::collections::VecDeque<ModalOp>> =
1185            const { RefCell::new(std::collections::VecDeque::new()) };
1186        /// Whether a present/dismiss transition is currently in flight.
1187        static MODAL_BUSY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1188        /// Transition generation — invalidates the watchdog of a normally-completed transition.
1189        static MODAL_GEN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
1190        /// When a transition was last seen in flight (`ui_idle`'s settle margin).
1191        static UI_LAST_ACTIVE: std::cell::Cell<Option<std::time::Instant>> =
1192            const { std::cell::Cell::new(None) };
1193
1194    }
1195
1196    /// One connected scene's windowing state.
1197    struct SceneEntry {
1198        window: Retained<UIWindow>,
1199        root_view: Retained<UIView>,
1200        base_frame: Cell<CGRect>,
1201        /// `None` = the primary scene; `Some` = a secondary day window's root node.
1202        node: Option<NodeId>,
1203        /// Whether the app asked for this window fullscreen (`WindowChange::State`): its root
1204        /// and cover VCs then hide the status bar and let the home indicator fade.
1205        fullscreen: Cell<bool>,
1206        /// The last `WindowStateChanged` code reported for this window, so a report fires once
1207        /// per real change.
1208        reported: Cell<i32>,
1209        /// Whether the app asked for this window's content to stay out of captures
1210        /// (`WindowChange::ContentProtected`).
1211        protected: Cell<bool>,
1212        /// The opaque window covering this scene while protected content is being recorded or
1213        /// mirrored; `None` the rest of the time.
1214        shield: RefCell<Option<Retained<UIWindow>>>,
1215        /// This window's own light/dark override (`WindowChange::Appearance`); `None` follows
1216        /// the app-wide choice.
1217        appearance: Cell<Option<bool>>,
1218    }
1219
1220    impl SceneEntry {
1221        fn new(
1222            window: Retained<UIWindow>,
1223            root_view: Retained<UIView>,
1224            base_frame: CGRect,
1225            node: Option<NodeId>,
1226        ) -> Self {
1227            SceneEntry {
1228                window,
1229                root_view,
1230                base_frame: Cell::new(base_frame),
1231                node,
1232                fullscreen: Cell::new(false),
1233                reported: Cell::new(day_spec::WindowState::Normal.code()),
1234                protected: Cell::new(false),
1235                shield: RefCell::new(None),
1236                appearance: Cell::new(None),
1237            }
1238        }
1239    }
1240
1241    thread_local! {
1242        /// The app-wide interface style `Toolkit::set_appearance` asked for; `None` until it
1243        /// is first called, when a `DAY_THEME` launch override stands in.
1244        static APP_STYLE: Cell<Option<objc2_ui_kit::UIUserInterfaceStyle>> =
1245            const { Cell::new(None) };
1246    }
1247
1248    fn interface_style(dark: Option<bool>) -> objc2_ui_kit::UIUserInterfaceStyle {
1249        use objc2_ui_kit::UIUserInterfaceStyle as Style;
1250        match dark {
1251            Some(true) => Style::Dark,
1252            Some(false) => Style::Light,
1253            None => Style::Unspecified,
1254        }
1255    }
1256
1257    /// The style every window wears unless it has its own: the app's `set_appearance`, else
1258    /// `DAY_THEME=light|dark` (themed CI runs), else the system's.
1259    fn app_style() -> objc2_ui_kit::UIUserInterfaceStyle {
1260        APP_STYLE.with(std::cell::Cell::get).unwrap_or_else(|| {
1261            interface_style(match std::env::var("DAY_THEME").ok().as_deref() {
1262                Some("dark") => Some(true),
1263                Some("light") => Some(false),
1264                _ => None,
1265            })
1266        })
1267    }
1268
1269    /// Put each scene window in the style it should wear: its own override, else the app's.
1270    /// Windows are collected first and styled outside the registry borrow, since a style
1271    /// change runs `traitCollectionDidChange` synchronously, which reads the registry again.
1272    fn refresh_scene_styles() {
1273        let windows: Vec<(Retained<UIWindow>, objc2_ui_kit::UIUserInterfaceStyle)> =
1274            SCENES.with(|s| {
1275                s.borrow()
1276                    .iter()
1277                    .map(|e| {
1278                        let style = match e.appearance.get() {
1279                            Some(dark) => interface_style(Some(dark)),
1280                            None => app_style(),
1281                        };
1282                        (e.window.clone(), style)
1283                    })
1284                    .collect()
1285            });
1286        for (window, style) in windows {
1287            if unsafe { window.overrideUserInterfaceStyle() } != style {
1288                unsafe { window.setOverrideUserInterfaceStyle(style) };
1289            }
1290        }
1291    }
1292
1293    /// The KEY window's scene entry applied to `f` — keyboard avoidance and modal
1294    /// presentation act on whichever Day window is key; primary statics are the fallback.
1295    fn with_key_scene<R>(f: impl FnOnce(&SceneEntry) -> R) -> Option<R> {
1296        SCENES.with(|s| {
1297            let scenes = s.borrow();
1298            let key = scenes
1299                .iter()
1300                .find(|e| e.window.isKeyWindow())
1301                .or_else(|| scenes.iter().find(|e| e.node.is_none()));
1302            key.map(f)
1303        })
1304    }
1305
1306    /// Is this device running at least `major`.0?
1307    ///
1308    /// day-toolkit-uikit deploys to iOS 15 and is built against a much newer SDK, so anything newer than
1309    /// the floor has to be asked for at runtime. objc2 compiles the call whatever the SDK
1310    /// version; the OS is what decides whether the nav host exists, and an unrecognized nav host
1311    /// is a crash, not a no-op.
1312    ///
1313    /// Cached: `NSProcessInfo` is a lookup per call otherwise, and the answer cannot change
1314    /// while the process runs.
1315    fn os_at_least(major: isize) -> bool {
1316        thread_local! {
1317            static VERSION: isize = objc2_foundation::NSProcessInfo::processInfo()
1318                .operatingSystemVersion()
1319                .majorVersion;
1320        }
1321        VERSION.with(|v| *v >= major)
1322    }
1323
1324    /// The scene entry a given view lives in, applied to `f` — matched by the view's WINDOW,
1325    /// which is the one identity every view in a scene shares all the way up the hierarchy.
1326    ///
1327    /// `with_key_scene` answers "whichever window the user is typing into"; this answers "the
1328    /// window this view is in", which is what a resize report needs — a background window being
1329    /// resized alongside the key one must still report against itself. `None` before the view
1330    /// has been added to a window.
1331    fn with_scene_of<R>(view: &UIView, f: impl FnOnce(&SceneEntry) -> R) -> Option<R> {
1332        let window = view.window()?;
1333        let wp = Retained::as_ptr(&window) as usize;
1334        SCENES.with(|s| {
1335            let scenes = s.borrow();
1336            scenes
1337                .iter()
1338                .find(|e| Retained::as_ptr(&e.window) as usize == wp)
1339                .map(f)
1340        })
1341    }
1342
1343    /// The scene entry whose Day root is `host` (a window's content container, as day-core
1344    /// addresses windows), applied to `f`.
1345    fn with_scene_of_host<R>(host: &UIView, f: impl FnOnce(&SceneEntry) -> R) -> Option<R> {
1346        let hp = std::ptr::from_ref::<UIView>(host) as usize;
1347        SCENES.with(|s| {
1348            s.borrow()
1349                .iter()
1350                .find(|e| Retained::as_ptr(&e.root_view) as usize == hp)
1351                .map(f)
1352        })
1353    }
1354
1355    /// The root node id the keyboard/resize rail should report against for the key window:
1356    /// a secondary's own root, or `WINDOW_NODE` for the primary.
1357    fn key_scene_target(entry: &SceneEntry) -> NodeId {
1358        entry.node.unwrap_or(WINDOW_NODE)
1359    }
1360
1361    /// The space this SCENE has, in points — never the screen's (docs/size-classes.md).
1362    ///
1363    /// `scene.screen().bounds()` is the display, and a scene has not filled the display since
1364    /// iPad multitasking; as of iPadOS 26 every iPad window is freely resizable, and an iPhone
1365    /// app on an iPad or mirrored to a Mac is a resizable window too. Measuring the screen made
1366    /// the LAUNCH snapshot wrong — the first size class was the display's, so a nav host resolved
1367    /// its presentation for a window that size and then visibly corrected itself once
1368    /// `DayHolderView` ran.
1369    ///
1370    /// The scene's own coordinate space is right on every version this backend supports; iOS 26
1371    /// moved it behind `effectiveGeometry` and deprecated the direct property, so both spellings
1372    /// are here — the same value, asked for the way the running OS wants it asked.
1373    fn scene_bounds(scene: &objc2_ui_kit::UIWindowScene) -> CGRect {
1374        use objc2_ui_kit::UICoordinateSpace;
1375        let space = if os_at_least(26) {
1376            scene.effectiveGeometry().coordinateSpace(mtm())
1377        } else {
1378            #[allow(deprecated)]
1379            scene.coordinateSpace()
1380        };
1381        let bounds = space.bounds();
1382        // A scene that has not been placed yet reports zero; the screen is the best guess left,
1383        // and the first layout pass corrects it either way.
1384        if bounds.size.width > 0.0 && bounds.size.height > 0.0 {
1385            bounds
1386        } else {
1387            scene.screen().bounds()
1388        }
1389    }
1390
1391    /// Ask the system not to shrink this window below what the app can draw
1392    /// (docs/size-classes.md). `sizeRestrictions` is `nil` wherever the platform does not let a
1393    /// window be resized at all (every iPhone), which is why this is a nil-check and not a
1394    /// version gate.
1395    ///
1396    /// Apple documents the minimum as a PREFERENCE satisfied on a best-effort basis, so this
1397    /// buys a floor the system usually honors, never one the app may rely on: laying out
1398    /// sensibly at whatever size arrives is still the app's job.
1399    fn apply_size_restrictions(scene: &objc2_ui_kit::UIWindowScene, min: Option<Size>) {
1400        let Some(min) = min.or_else(plist_min_window_size) else {
1401            return;
1402        };
1403        let Some(restrictions) = (unsafe { scene.sizeRestrictions() }) else {
1404            return;
1405        };
1406        unsafe { restrictions.setMinimumSize(CGSize::new(min.width, min.height)) };
1407    }
1408
1409    /// The URL scheme the app registered (`CFBundleURLTypes`), the first one as `day build`
1410    /// reads it for the Info.plist quick actions: dynamic shortcuts carry the same link form.
1411    fn bundle_url_scheme() -> Option<String> {
1412        let bundle = objc2_foundation::NSBundle::mainBundle();
1413        let types =
1414            unsafe { bundle.objectForInfoDictionaryKey(&NSString::from_str("CFBundleURLTypes")) }?;
1415        let types = types.downcast::<objc2_foundation::NSArray>().ok()?;
1416        types.iter().find_map(|t| {
1417            let dict = t.downcast::<objc2_foundation::NSDictionary>().ok()?;
1418            let schemes = dict.objectForKey(&*NSString::from_str("CFBundleURLSchemes"))?;
1419            let schemes = schemes.downcast::<objc2_foundation::NSArray>().ok()?;
1420            let first = schemes.firstObject()?.downcast::<NSString>().ok()?;
1421            Some(first.to_string()).filter(|s| !s.is_empty())
1422        })
1423    }
1424
1425    /// `Day.toml [window] min_width/min_height`, carried into the bundle's `Info.plist` by
1426    /// `day build` (`mobile::sync_window_keys`). The fallback when the app set no
1427    /// `WindowOptions.min_size` of its own, so one Day.toml declaration reaches both platforms.
1428    fn plist_min_window_size() -> Option<Size> {
1429        fn key(name: &str) -> Option<f64> {
1430            let bundle = objc2_foundation::NSBundle::mainBundle();
1431            let value = unsafe { bundle.objectForInfoDictionaryKey(&NSString::from_str(name)) }?;
1432            let s = value.downcast::<NSString>().ok()?;
1433            s.to_string().trim().parse::<f64>().ok()
1434        }
1435        let w = key("DayWindowMinWidth")?;
1436        let h = key("DayWindowMinHeight")?;
1437        (w > 0.0 && h > 0.0).then(|| Size::new(w, h))
1438    }
1439
1440    /// Build one Day window into `scene`: `UIWindow` + `DayRootVC` + `DayHolderView` + the
1441    /// safe-area-inset day root — the construction `didFinishLaunching` used to own,
1442    /// factored so every scene (primary and secondary) gets identical chrome.
1443    fn build_scene_window(
1444        mtm: MainThreadMarker,
1445        scene: &objc2_ui_kit::UIWindowScene,
1446        min_size: Option<Size>,
1447    ) -> (Retained<UIWindow>, Retained<UIView>, CGRect) {
1448        apply_size_restrictions(scene, min_size);
1449        let bounds = scene_bounds(scene);
1450        if *DIAG_NAV {
1451            let screen = scene.screen().bounds();
1452            // The scene's own size versus the display's — they are different on any iPad running
1453            // iPadOS 26, which opens apps windowed, and the gap is what makes measuring the
1454            // screen a bug rather than a shortcut (docs/size-classes.md). `min` echoes back the
1455            // `sizeRestrictions` the app just asked for, read back off the restrictions object
1456            // itself (iOS 13+) rather than off the geometry, whose `minimumSize` turns out not to
1457            // exist until iOS 27 — a reminder that an SDK header's availability annotation is a
1458            // compile-time promise, not a runtime one. 0x0 means no minimum took.
1459            log::debug!(
1460                "DAYDIAG scene {}x{} (screen {}x{})",
1461                bounds.size.width,
1462                bounds.size.height,
1463                screen.size.width,
1464                screen.size.height,
1465            );
1466        }
1467        let window = unsafe { UIWindow::initWithWindowScene(UIWindow::alloc(mtm), scene) };
1468        let vc: Retained<UIViewController> = DayRootVC::new(mtm).into_super();
1469        let holder = DayHolderView::new(mtm);
1470        unsafe { holder.setFrame(bounds) };
1471        // The holder tracks its window rather than keeping the frame it was built with: a scene
1472        // resized before its first layout pass (a restored window, a drag that starts during
1473        // launch) would otherwise hold the launch size until something else invalidated it.
1474        holder.setAutoresizingMask(
1475            objc2_ui_kit::UIViewAutoresizing::FlexibleWidth
1476                | objc2_ui_kit::UIViewAutoresizing::FlexibleHeight,
1477        );
1478        let root_view = unsafe { UIView::initWithFrame(UIView::alloc(mtm), bounds) };
1479        // RTL locales (docs/localization): force the semantic content attribute on the
1480        // window AND the day content roots — see the module docs.
1481        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
1482            let rtl = objc2_ui_kit::UISemanticContentAttribute::ForceRightToLeft;
1483            window.setSemanticContentAttribute(rtl);
1484            holder.setSemanticContentAttribute(rtl);
1485            root_view.setSemanticContentAttribute(rtl);
1486        }
1487        // Every window starts in the app's style: its `set_appearance`, or DAY_THEME=light|dark
1488        // (themed CI runs). A per-window override comes later, through `apply_window`.
1489        let style = app_style();
1490        if style != objc2_ui_kit::UIUserInterfaceStyle::Unspecified {
1491            unsafe { window.setOverrideUserInterfaceStyle(style) };
1492        }
1493        unsafe {
1494            holder.setBackgroundColor(Some(&UIColor::systemGroupedBackgroundColor()));
1495            holder.addSubview(&root_view);
1496            vc.setView(Some(&holder));
1497            window.setRootViewController(Some(&vc));
1498            window.makeKeyAndVisible();
1499        }
1500        watch_pointer(&window);
1501        // Safe area as root padding (§7.7): valid once the window is key. The window's OWN
1502        // bounds, not the ones the holder was built with — `makeKeyAndVisible` is where a scene
1503        // that is smaller than it first reported settles.
1504        let bounds = window.bounds();
1505        let insets = unsafe { window.safeAreaInsets() };
1506        // A hosted root takes the whole window (the holder's layout pass has the rule); the
1507        // tree usually mounts after this point, and the insert duty re-lays the holder then.
1508        let inner = content_frame(bounds, insets, scroll_leaf(&holder));
1509        unsafe { root_view.setFrame(inner) };
1510        if *DIAG_NAV {
1511            let min = unsafe { scene.sizeRestrictions() }
1512                .map_or(CGSize::new(0.0, 0.0), |r| unsafe { r.minimumSize() });
1513            log::debug!(
1514                "DAYDIAG launch window {}x{} safe(t{} b{} l{} r{}) -> root {}x{} min {}x{}",
1515                bounds.size.width,
1516                bounds.size.height,
1517                insets.top,
1518                insets.bottom,
1519                insets.left,
1520                insets.right,
1521                inner.size.width,
1522                inner.size.height,
1523                min.width,
1524                min.height,
1525            );
1526        }
1527        (window, root_view, inner)
1528    }
1529
1530    /// Recompute the app-level lifecycle from ALL scenes (docs/windows.md): scene phases
1531    /// replace the app-delegate callbacks under the scene lifecycle, and focus moving
1532    /// between two Day windows must not read as an app-level resign/become (the same
1533    /// debounce day-toolkit-gtk applies). Emits only on a real transition.
1534    fn note_scene_lifecycle_changed(mtm: MainThreadMarker) {
1535        use objc2_ui_kit::UISceneActivationState as S;
1536        let app = UIApplication::sharedApplication(mtm);
1537        let mut any_active = false;
1538        let mut any_foreground = false;
1539        for scene in unsafe { app.connectedScenes() } {
1540            match unsafe { scene.activationState() } {
1541                S::ForegroundActive => {
1542                    any_active = true;
1543                    any_foreground = true;
1544                }
1545                S::ForegroundInactive => any_foreground = true,
1546                _ => {}
1547            }
1548        }
1549        if ANY_SCENE_FOREGROUND.with(|c| c.replace(any_foreground)) != any_foreground {
1550            let phase = if any_foreground {
1551                day_spec::Lifecycle::WillEnterForeground
1552            } else {
1553                day_spec::Lifecycle::DidEnterBackground
1554            };
1555            emit(WINDOW_NODE, Event::Lifecycle(phase));
1556        }
1557        if ANY_SCENE_ACTIVE.with(|c| c.replace(any_active)) != any_active {
1558            let phase = if any_active {
1559                day_spec::Lifecycle::DidBecomeActive
1560            } else {
1561                day_spec::Lifecycle::WillResignActive
1562            };
1563            emit(WINDOW_NODE, Event::Lifecycle(phase));
1564        }
1565    }
1566
1567    /// The activity type a secondary-window scene request carries; its userInfo holds the
1568    /// day root node id under `day.node` (docs/windows.md).
1569    const DAY_WINDOW_ACTIVITY: &str = "dev.daybrite.day.window";
1570
1571    /// Scroll the focused field's nearest enclosing `UIScrollView` so the field is visible
1572    /// (keyboard avoidance, docs/focus.md). Runs a turn after the keyboard-driven root resize
1573    /// so Day's relayout has settled the frames it converts.
1574    fn reveal_focused_field() {
1575        // Next main-queue turn: Day's relayout for the resized root has run by then, so the
1576        // frames this converts are settled. (Same queue the backend's poster uses.)
1577        dispatch2::DispatchQueue::main().exec_async(|| {
1578            let Some(field) = FOCUSED_FIELD.with(|f| f.borrow().clone()) else {
1579                return;
1580            };
1581            let mut sup = field.superview();
1582            while let Some(v) = sup {
1583                sup = v.superview();
1584                if let Ok(sv) = v.downcast::<UIScrollView>() {
1585                    // Convert into the scroll's coordinate space (== content space for
1586                    // UIScrollView, whose bounds origin is the content offset), with a little
1587                    // breathing room below the field.
1588                    let mut r = field.convertRect_toView(field.bounds(), Some(&sv));
1589                    r.size.height += 12.0;
1590                    unsafe { sv.scrollRectToVisible_animated(r, true) };
1591                    return;
1592                }
1593            }
1594        });
1595    }
1596
1597    /// Keyboard avoidance for presented covers and sheets (docs/focus.md). A cover is a view
1598    /// controller of its own over the window, so the root clamp in `keyboardWillChange:` never
1599    /// reaches it. Its page view pins the content inside the safe area and reports the new size
1600    /// (`DayNavPageView::layoutSubviews`), so the part of the keyboard over the cover becomes
1601    /// its VC's `additionalSafeAreaInsets` bottom, net of the home-indicator inset it already
1602    /// has; a scroll-view content that fills the page gets the same inset as scroll insets.
1603    ///
1604    /// Measured a turn later, like `reveal_focused_field`: an iPad form sheet moves up out of
1605    /// the keyboard's way in the same notification, and its final frame is set by then.
1606    /// `kb` is the keyboard's end frame in screen coordinates; a hidden keyboard lies below
1607    /// every view, so its overlap is zero and the inset returns to nothing.
1608    fn avoid_keyboard_in_covers(kb: CGRect) {
1609        dispatch2::DispatchQueue::main().exec_async(move || {
1610            day_spec::ffi_guard::contain((), || {
1611                use objc2_ui_kit::UICoordinateSpace;
1612                let covers: Vec<Retained<DayCoverVC>> =
1613                    COVER_STATE.with(|m| m.borrow().values().map(|s| s.vc.clone()).collect());
1614                for vc in covers {
1615                    let Some(view) = vc.viewIfLoaded() else {
1616                        continue;
1617                    };
1618                    let mut extra = unsafe { vc.additionalSafeAreaInsets() };
1619                    let screen = view
1620                        .window()
1621                        .and_then(|w| w.windowScene())
1622                        .map(|s| s.screen());
1623                    let overlap = screen.map_or(0.0, |screen| {
1624                        let local =
1625                            view.convertRect_fromCoordinateSpace(kb, &screen.coordinateSpace());
1626                        let bounds = view.bounds();
1627                        let bottom = bounds.origin.y + bounds.size.height;
1628                        let beside = local.origin.x >= bounds.origin.x + bounds.size.width
1629                            || local.origin.x + local.size.width <= bounds.origin.x;
1630                        if beside || local.size.height <= 0.0 {
1631                            0.0
1632                        } else {
1633                            (bottom - local.origin.y).clamp(0.0, bounds.size.height)
1634                        }
1635                    });
1636                    // Out of a window the insets read stale, so no overlap means no inset
1637                    // rather than arithmetic on them.
1638                    let wanted = if overlap > 0.0 {
1639                        let own = view.safeAreaInsets().bottom - extra.bottom;
1640                        (overlap - own).max(0.0)
1641                    } else {
1642                        0.0
1643                    };
1644                    #[expect(
1645                        clippy::float_cmp,
1646                        reason = "unchanged-value check against the inset set last time"
1647                    )]
1648                    let changed = extra.bottom != wanted;
1649                    if changed {
1650                        extra.bottom = wanted;
1651                        unsafe { vc.setAdditionalSafeAreaInsets(extra) };
1652                    }
1653                }
1654            });
1655        });
1656    }
1657
1658    pub fn emit(id: NodeId, ev: Event) {
1659        let sink = SINK.with(|s| s.borrow().clone());
1660        if let Some(sink) = sink {
1661            sink(id, ev);
1662        }
1663    }
1664
1665    fn ptr_of(v: &UIView) -> usize {
1666        std::ptr::from_ref::<UIView>(v).cast::<()>() as usize
1667    }
1668
1669    /// An image view's rendering (`IMAGE_MODES`).
1670    #[derive(Clone, Copy)]
1671    struct ImageMode {
1672        template: bool,
1673        tinted: bool,
1674    }
1675
1676    impl ImageMode {
1677        /// `AlwaysTemplate`: the glyph's alpha as a mask, filled with the tint or the inherited
1678        /// one.
1679        fn renders_template(self) -> bool {
1680            self.template || self.tinted
1681        }
1682    }
1683
1684    /// The day name for a hardware-keyboard key, or `None` for every key the route does not
1685    /// carry — the [`day_spec::KeyEvent`] names (docs/menus.md).
1686    fn key_name(key: &objc2_ui_kit::UIKey) -> Option<&'static str> {
1687        use objc2_ui_kit::UIKeyModifierFlags as M;
1688        use objc2_ui_kit::UIKeyboardHIDUsage as U;
1689        match unsafe { key.keyCode() } {
1690            U::KeyboardLeftArrow => Some("ArrowLeft"),
1691            U::KeyboardRightArrow => Some("ArrowRight"),
1692            U::KeyboardUpArrow => Some("ArrowUp"),
1693            U::KeyboardDownArrow => Some("ArrowDown"),
1694            U::KeyboardDeleteForward => Some("Delete"),
1695            U::KeyboardDeleteOrBackspace => Some("Backspace"),
1696            // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃:
1697            // those combinations are key commands, and a canvas claiming one would starve them.
1698            _ if unsafe { key.modifierFlags() }
1699                .intersects(M::Command | M::Alternate | M::Control) =>
1700            {
1701                None
1702            }
1703            _ => {
1704                let typed = key.characters().to_string();
1705                let mut chars = typed.chars();
1706                match (chars.next(), chars.next()) {
1707                    (Some(c), None) => day_spec::KeyEvent::digit_name(c),
1708                    _ => None,
1709                }
1710            }
1711        }
1712    }
1713
1714    /// UIKit's modifier flags as day's mask.
1715    fn key_modifiers(f: objc2_ui_kit::UIKeyModifierFlags) -> u8 {
1716        let mut m = 0u8;
1717        if f.contains(objc2_ui_kit::UIKeyModifierFlags::Shift) {
1718            m |= day_spec::Modifiers::SHIFT.bits();
1719        }
1720        if f.contains(objc2_ui_kit::UIKeyModifierFlags::Command) {
1721            m |= day_spec::Modifiers::PRIMARY.bits();
1722        }
1723        if f.contains(objc2_ui_kit::UIKeyModifierFlags::Alternate) {
1724            m |= day_spec::Modifiers::ALT.bits();
1725        }
1726        if f.contains(objc2_ui_kit::UIKeyModifierFlags::Control) {
1727            m |= day_spec::Modifiers::CONTROL.bits();
1728        }
1729        m
1730    }
1731
1732    /// The web name for a hardware key that types nothing (docs/menus.md "The full route"),
1733    /// or `None` for a key that types.
1734    fn named_key(key: &objc2_ui_kit::UIKey) -> Option<&'static str> {
1735        use objc2_ui_kit::UIKeyboardHIDUsage as U;
1736        Some(match unsafe { key.keyCode() } {
1737            U::KeyboardLeftArrow => "ArrowLeft",
1738            U::KeyboardRightArrow => "ArrowRight",
1739            U::KeyboardUpArrow => "ArrowUp",
1740            U::KeyboardDownArrow => "ArrowDown",
1741            U::KeyboardReturnOrEnter | U::KeypadEnter | U::KeyboardReturn => "Enter",
1742            U::KeyboardTab => "Tab",
1743            U::KeyboardEscape => "Escape",
1744            U::KeyboardDeleteOrBackspace => "Backspace",
1745            U::KeyboardDeleteForward => "Delete",
1746            U::KeyboardHome => "Home",
1747            U::KeyboardEnd => "End",
1748            U::KeyboardPageUp => "PageUp",
1749            U::KeyboardPageDown => "PageDown",
1750            U::KeyboardInsert => "Insert",
1751            U::KeyboardF1 => "F1",
1752            U::KeyboardF2 => "F2",
1753            U::KeyboardF3 => "F3",
1754            U::KeyboardF4 => "F4",
1755            U::KeyboardF5 => "F5",
1756            U::KeyboardF6 => "F6",
1757            U::KeyboardF7 => "F7",
1758            U::KeyboardF8 => "F8",
1759            U::KeyboardF9 => "F9",
1760            U::KeyboardF10 => "F10",
1761            U::KeyboardF11 => "F11",
1762            U::KeyboardF12 => "F12",
1763            _ => return None,
1764        })
1765    }
1766
1767    /// A hardware key press on the full route (`Decorate::keyboard`, docs/menus.md "The full
1768    /// route") that `pressesBegan:` claims: a key that types nothing, by its web name, or a
1769    /// Control/Option chord, by its unmodified character. `None` for a press that is not the
1770    /// canvas's to claim here: a ⌘ chord is a key command's, and a press that types plain
1771    /// text goes to `super`, so the text input system delivers it through `insertText:` the
1772    /// same way the soft keyboard's text arrives, and a key is never heard twice.
1773    fn full_route_press(key: &objc2_ui_kit::UIKey) -> Option<day_spec::KeyEvent> {
1774        use objc2_ui_kit::UIKeyModifierFlags as M;
1775        let flags = unsafe { key.modifierFlags() };
1776        let mods = key_modifiers(flags);
1777        if flags.contains(M::Command) {
1778            return None;
1779        }
1780        if let Some(named) = named_key(key) {
1781            return Some(day_spec::KeyEvent::named(named, mods));
1782        }
1783        if !flags.intersects(M::Control | M::Alternate) {
1784            return None;
1785        }
1786        let typed = unsafe { key.charactersIgnoringModifiers() }.to_string();
1787        (!typed.is_empty() && !typed.chars().any(char::is_control))
1788            .then(|| day_spec::KeyEvent::named(typed, mods))
1789    }
1790
1791    /// Text the soft keyboard (or the text input system, for a hardware key `pressesBegan:`
1792    /// left to `super`) inserted into a canvas that took the whole keyboard: a newline is
1793    /// the Enter key and a tab the Tab key, anything else is text, named by itself when it
1794    /// is one character.
1795    fn emit_inserted_text(node: NodeId, text: &str, phase: day_spec::KeyPhase) {
1796        let event = match text {
1797            "\n" | "\r" => day_spec::KeyEvent::named("Enter", 0),
1798            "\t" => day_spec::KeyEvent::named("Tab", 0),
1799            "" => return,
1800            other => day_spec::KeyEvent::typed_text(other, 0),
1801        };
1802        emit(node, Event::Key(event.with_phase(phase)));
1803    }
1804
1805    /// Records a key whose down the view at `view` claimed, so its release reaches the same
1806    /// node (docs/menus.md "Keys").
1807    fn hold_key(view: usize, key: HeldKey) {
1808        KEYS_DOWN.with(|t| {
1809            let mut held = t.take(view).unwrap_or_default();
1810            held.retain(|k| k.code != key.code);
1811            held.push(key);
1812            t.insert(view, held);
1813        });
1814    }
1815
1816    /// The releases among `presses` whose downs `view` claimed: each is reported as
1817    /// `KeyPhase::Up` to the view's node, with the modifiers held now and no text. Returns the
1818    /// presses `super` must see: every one this view did not claim, and the typing keys, whose
1819    /// downs `super` saw.
1820    fn release_keys(
1821        view: &UIView,
1822        presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
1823    ) -> Vec<Retained<objc2_ui_kit::UIPress>> {
1824        let ptr = ptr_of(view);
1825        let node = KEY_NODES.with(|t| t.get(ptr));
1826        let mut rest = Vec::new();
1827        for press in presses {
1828            let Some(key) = (unsafe { press.key(view.mtm()) }) else {
1829                rest.push(press.retain());
1830                continue;
1831            };
1832            let code = unsafe { key.keyCode() }.0;
1833            let held = KEYS_DOWN
1834                .with(|t| {
1835                    t.with(ptr, |held| {
1836                        let i = held.iter().position(|k| k.code == code)?;
1837                        Some(held.remove(i))
1838                    })
1839                })
1840                .flatten();
1841            let Some(held) = held else {
1842                rest.push(press.retain());
1843                continue;
1844            };
1845            if let Some(node) = node
1846                && (!held.text || held.inserts > 0)
1847            {
1848                let mods = key_modifiers(unsafe { key.modifierFlags() });
1849                day_spec::ffi_guard::contain((), || {
1850                    emit(
1851                        node,
1852                        Event::Key(
1853                            day_spec::KeyEvent::named(held.name.as_str(), mods)
1854                                .with_phase(day_spec::KeyPhase::Up),
1855                        ),
1856                    );
1857                });
1858            }
1859            if held.text {
1860                rest.push(press.retain());
1861            }
1862        }
1863        rest
1864    }
1865    fn view_of<T: AsRef<UIView>>(x: &Retained<T>) -> Handle {
1866        Retained::from((**x).as_ref())
1867    }
1868
1869    /// The OUTERMOST view controller behind a host handle, or `None` for an ordinary view.
1870    ///
1871    /// Outermost matters: an adaptive nav host's handle is the split controller's view, and it is
1872    /// the split controller — not the secondary column's navigation controller inside it — that
1873    /// owns that view and must carry the containment. Used by `insert` to re-parent a host that
1874    /// lands inside a page (docs/navigation.md).
1875    /// The controller `view` belongs to, resolved the way UIKit resolves it.
1876    ///
1877    /// The registered-page lookup above matches only a page's OWN content view, and a nested host
1878    /// rarely lands there: it arrives inside whatever the page put between them — a `when` arm, a
1879    /// column, a `.grow(Dimension::Both)` wrapper — all of them plain views. The responder chain is the general
1880    /// answer, because `nextResponder` on a view yields its controller where it has one and its
1881    /// superview where it does not, so walking it stops at the nearest enclosing controller.
1882    ///
1883    /// Getting this wrong is not a layout glitch. UIKit raises the moment a controller's root view is
1884    /// added to a view owned by an unrelated controller:
1885    ///
1886    ///     A view can only be associated with at most one view controller at a time!
1887    fn enclosing_view_controller(view: &UIView) -> Option<Retained<UIViewController>> {
1888        let mut next = unsafe { view.nextResponder() };
1889        while let Some(responder) = next {
1890            if let Some(vc) = responder.downcast_ref::<UIViewController>() {
1891                return Some(vc.retain());
1892            }
1893            next = unsafe { responder.nextResponder() };
1894        }
1895        None
1896    }
1897
1898    /// The controller behind a nav host's handle — the split, the stack, or the `.tabSidebar`
1899    /// tab bar — for the containment fix-up `insert` performs when the host lands in a page.
1900    ///
1901    /// The tab bar counts. Left out, a tabs host nested in a page stayed a child of the WINDOW's
1902    /// root controller while its view sat under the page's navigation bar, and UIKit derives
1903    /// a controller's safe area from its PARENT controller: the tab pages were told the status
1904    /// bar was the only chrome above them, and a scroll-rooted tab page — which bleeds, and
1905    /// trusts that inset — laid its first row under the navigation bar and the top tab bar
1906    /// (the Showcase Tabs page on an iPad, 2026-09-10).
1907    fn host_controller(h: &Handle) -> Option<Retained<UIViewController>> {
1908        let key = ptr_of(h);
1909        // `as_ref` stops at the declared superclass, so these go up the chain by deref coercion.
1910        NAV_STATE
1911            .with(|m| {
1912                m.borrow().get(&key).map(|s| {
1913                    if let Some(parts) = s.split.as_ref() {
1914                        let vc: &UIViewController = &parts.split_vc;
1915                        Retained::from(vc)
1916                    } else {
1917                        let vc: &UIViewController = &s.nav;
1918                        Retained::from(vc)
1919                    }
1920                })
1921            })
1922            .or_else(|| {
1923                NAV_TABS.with(|m| {
1924                    m.borrow().get(&key).map(|t| {
1925                        let vc: &UIViewController = &t.tabbar;
1926                        Retained::from(vc)
1927                    })
1928                })
1929            })
1930    }
1931
1932    // -----------------------------------------------------------------------
1933    // DayShareActivity — one of the app's actions in the share sheet (docs/sharing.md)
1934    // -----------------------------------------------------------------------
1935
1936    struct ShareActivityIvars {
1937        /// The dispatch id a choice reports (`Event::MenuAction`).
1938        action: u64,
1939        title: Retained<NSString>,
1940        /// The SF Symbol drawn beside the title.
1941        symbol: Option<&'static str>,
1942    }
1943
1944    define_class!(
1945        // The default category is `UIActivityCategoryAction`: the sheet lists the action with
1946        // its title and glyph under the share targets, as Safari's Add Bookmark is listed.
1947        #[unsafe(super(objc2_ui_kit::UIActivity, NSObject))]
1948        #[thread_kind = MainThreadOnly]
1949        #[name = "DayUIKitShareActivity"]
1950        #[ivars = ShareActivityIvars]
1951        struct DayShareActivity;
1952
1953        unsafe impl NSObjectProtocol for DayShareActivity {}
1954
1955        impl DayShareActivity {
1956            #[unsafe(method_id(activityType))]
1957            fn activity_type(&self) -> Option<Retained<NSString>> {
1958                Some(NSString::from_str(&format!(
1959                    "{SHARE_ACTIVITY_PREFIX}{}",
1960                    self.ivars().action
1961                )))
1962            }
1963
1964            #[unsafe(method_id(activityTitle))]
1965            fn activity_title(&self) -> Option<Retained<NSString>> {
1966                Some(self.ivars().title.clone())
1967            }
1968
1969            #[unsafe(method_id(activityImage))]
1970            fn activity_image(&self) -> Option<Retained<objc2_ui_kit::UIImage>> {
1971                self.ivars()
1972                    .symbol
1973                    .and_then(|name| objc2_ui_kit::UIImage::systemImageNamed(&NSString::from_str(name)))
1974            }
1975
1976            #[unsafe(method(canPerformWithActivityItems:))]
1977            fn can_perform(&self, _items: &AnyObject) -> bool {
1978                true
1979            }
1980
1981            // Finish at once, so the sheet dismisses. The app's action does not run here: the
1982            // sheet's `completionWithItemsHandler` reports it once the sheet has closed
1983            // (`share`), so an action that presents a sheet of its own does not race the one
1984            // still on screen.
1985            #[unsafe(method(performActivity))]
1986            fn perform_activity(&self) {
1987                // SAFETY: UIKit's own completion call on the activity it is performing, on the
1988                // main thread the sheet calls this from.
1989                unsafe {
1990                    let _: () = msg_send![self, activityDidFinish: true];
1991                }
1992            }
1993        }
1994    );
1995
1996    /// The `activityType` prefix of a [`DayShareActivity`]; the action's dispatch id follows it.
1997    const SHARE_ACTIVITY_PREFIX: &str = "dev.daybrite.day.share.";
1998
1999    /// The dispatch id of the app action a share sheet reports as `activity_type`, if it is one
2000    /// of Day's.
2001    fn share_action_id(activity_type: &str) -> Option<u64> {
2002        activity_type
2003            .strip_prefix(SHARE_ACTIVITY_PREFIX)?
2004            .parse()
2005            .ok()
2006    }
2007
2008    impl DayShareActivity {
2009        fn new(action: &day_spec::share::ShareAction) -> Retained<Self> {
2010            let this = Self::alloc(mtm()).set_ivars(ShareActivityIvars {
2011                action: action.id,
2012                title: NSString::from_str(&action.title),
2013                symbol: action.symbol.map(day_spec::sf_symbol_name),
2014            });
2015            // SAFETY: `init` is UIActivity's designated initializer.
2016            unsafe { msg_send![super(this), init] }
2017        }
2018    }
2019
2020    // -----------------------------------------------------------------------
2021    // DayTarget — target/action trampoline, node-id keyed
2022    // -----------------------------------------------------------------------
2023
2024    struct TargetIvars {
2025        node: NodeId,
2026        /// A text field's input traits as last applied (`set_input_traits`): what the next
2027        /// call diffs against, and where the delegate reads `read_only`.
2028        traits: RefCell<InputTraits>,
2029        /// A text field's text is being re-entered by `set_input_traits`, not typed: the
2030        /// editing-changed action it provokes is not a `TextChanged`.
2031        muted: Cell<bool>,
2032    }
2033
2034    define_class!(
2035        #[unsafe(super(NSObject))]
2036        #[thread_kind = MainThreadOnly]
2037        #[name = "DayUIKitTarget"]
2038        #[ivars = TargetIvars]
2039        struct DayTarget;
2040
2041        unsafe impl NSObjectProtocol for DayTarget {}
2042
2043        /// A `text_field`'s delegate, for the one thing only a delegate can do: refuse edits.
2044        /// `UITextField` has no editable flag, so a read-only field stays an ordinary field
2045        /// (focusable, selectable, copyable) whose every change — typing, paste, cut, delete —
2046        /// is turned down here.
2047        unsafe impl UITextFieldDelegate for DayTarget {
2048            #[unsafe(method(textField:shouldChangeCharactersInRange:replacementString:))]
2049            fn text_field_should_change(
2050                &self,
2051                _field: &UITextField,
2052                _range: NSRange,
2053                _replacement: &NSString,
2054            ) -> bool {
2055                !self.ivars().traits.borrow().read_only
2056            }
2057        }
2058
2059        impl DayTarget {
2060            #[unsafe(method(fire:))]
2061            fn fire(&self, sender: &UIControl) {
2062                // Every trampoline body that dispatches into the sink runs under
2063                // ffi_guard::contain (§8.5): a panic unwinding out of this ObjC frame
2064                // would abort the process.
2065                day_spec::ffi_guard::contain((), || {
2066                    if self.ivars().muted.get() {
2067                        return;
2068                    }
2069                    let node = self.ivars().node;
2070                    let obj: &AnyObject = sender.as_ref();
2071                    if obj.downcast_ref::<objc2_ui_kit::UIRefreshControl>().is_some() {
2072                        emit(node, Event::RefreshRequested);
2073                    } else if let Some(sw) = obj.downcast_ref::<UISwitch>() {
2074                        emit(node, Event::ToggleChanged(unsafe { sw.isOn() }));
2075                    } else if let Some(sl) = obj.downcast_ref::<UISlider>() {
2076                        emit(node, Event::ValueChanged(f64::from(unsafe { sl.value() })));
2077                    } else if let Some(tf) = obj.downcast_ref::<UITextField>() {
2078                        let s = unsafe { tf.text() }.map_or_default(|s| s.to_string());
2079                        emit(node, Event::TextChanged(s));
2080                    } else {
2081                        emit(node, Event::Pressed);
2082                    }
2083                });
2084            }
2085
2086            /// A slider's interaction ENDED: the finger lifted (inside or outside the track), so
2087            /// the value under it is the one the user chose. `UIControlEvents::ValueChanged`
2088            /// fires continuously while dragging — bindings need that — so the settled value is a
2089            /// separate control event (day-spec `Event::ValueCommitted`).
2090            #[unsafe(method(commit:))]
2091            fn commit(&self, sender: &UIControl) {
2092                day_spec::ffi_guard::contain((), || {
2093                    let obj: &AnyObject = sender.as_ref();
2094                    if let Some(sl) = obj.downcast_ref::<UISlider>() {
2095                        emit(
2096                            self.ivars().node,
2097                            Event::ValueCommitted(f64::from(unsafe { sl.value() })),
2098                        );
2099                    }
2100                });
2101            }
2102
2103            /// EditingDidBegin — the keyboard is up and this field owns it (docs/focus.md).
2104            #[unsafe(method(editBegan:))]
2105            fn edit_began(&self, sender: &UIControl) {
2106                day_spec::ffi_guard::contain((), || {
2107                    FOCUSED_FIELD
2108                        .with(|f| *f.borrow_mut() = Some(Retained::from(sender as &UIView)));
2109                    // The keyboard may already be up (focus moved between fields): reveal now
2110                    // too, not only from the keyboard-frame notification.
2111                    reveal_focused_field();
2112                    emit(self.ivars().node, Event::FocusChanged(true));
2113                });
2114            }
2115
2116            /// EditingDidEnd — the field resigned (keyboard dismissed or focus moved on).
2117            #[unsafe(method(editEnded:))]
2118            fn edit_ended(&self, _sender: &UIControl) {
2119                day_spec::ffi_guard::contain((), || {
2120                    FOCUSED_FIELD.with(|f| *f.borrow_mut() = None);
2121                    emit(self.ivars().node, Event::FocusChanged(false));
2122                });
2123            }
2124
2125            /// EditingDidEndOnExit — the Return key. Registering this handler is also what
2126            /// makes Return dismiss the keyboard (the UIKit convention); an `on_submit` that
2127            /// moves focus re-raises it on the next field.
2128            #[unsafe(method(editExit:))]
2129            fn edit_exit(&self, _sender: &UIControl) {
2130                day_spec::ffi_guard::contain((), || {
2131                    emit(self.ivars().node, Event::Submitted);
2132                });
2133            }
2134        }
2135    );
2136
2137    impl DayTarget {
2138        fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2139            let this = Self::alloc(mtm).set_ivars(TargetIvars {
2140                node,
2141                traits: RefCell::default(),
2142                muted: Cell::new(false),
2143            });
2144            unsafe { msg_send![super(this), init] }
2145        }
2146    }
2147
2148    /// Send a one-argument `UITextInputTraits` setter to a `UITextField`. The field forwards
2149    /// most of the protocol (keyboard, capitalization, correction, content type, return key)
2150    /// to a private traits object rather than implementing it, so objc2's debug-only send
2151    /// verification (`class_getInstanceMethod`) reports the setter missing and a checked
2152    /// `msg_send!` panics, even though the send succeeds. The raw runtime entry point skips
2153    /// that check and resolves the setter exactly as UIKit itself does.
2154    ///
2155    /// # Safety
2156    /// `A` must be the setter's exact C argument type (`NSInteger` for the enum traits, an
2157    /// object pointer for `setTextContentType:`).
2158    unsafe fn send_input_trait<A>(tf: &UITextField, sel: Sel, arg: A) {
2159        let recv = std::ptr::from_ref::<UITextField>(tf)
2160            .cast::<AnyObject>()
2161            .cast_mut();
2162        // SAFETY: `recv` is a live main-thread `UITextField`; the caller vouches that `sel`
2163        // takes one `A` and returns `void`, matching this `(id, SEL, A) -> ()` retyping of
2164        // `objc_msgSend` (which is `extern "C-unwind"`).
2165        let send: unsafe extern "C-unwind" fn(*mut AnyObject, Sel, A) = unsafe {
2166            core::mem::transmute(objc2::ffi::objc_msgSend as unsafe extern "C-unwind" fn())
2167        };
2168        unsafe { send(recv, sel, arg) };
2169    }
2170
2171    /// Whether a `UITextField` masks its text. The getter is another forwarded
2172    /// `UITextInputTraits` member (see [`send_input_trait`]), so a checked `msg_send!` panics in
2173    /// a debug build even though the send succeeds; this takes the same raw path.
2174    ///
2175    /// # Safety
2176    /// `tf` must be a live `UITextField`, used on the main thread.
2177    unsafe fn is_secure_text_entry(tf: &UITextField) -> bool {
2178        let recv = std::ptr::from_ref::<UITextField>(tf)
2179            .cast::<AnyObject>()
2180            .cast_mut();
2181        // SAFETY: `recv` is a live main-thread `UITextField`; `isSecureTextEntry` takes no
2182        // argument and returns `BOOL`, matching this `(id, SEL) -> Bool` retyping of
2183        // `objc_msgSend` (which is `extern "C-unwind"`).
2184        let send: unsafe extern "C-unwind" fn(*mut AnyObject, Sel) -> objc2::runtime::Bool = unsafe {
2185            core::mem::transmute(objc2::ffi::objc_msgSend as unsafe extern "C-unwind" fn())
2186        };
2187        unsafe { send(recv, sel!(isSecureTextEntry)) }.as_bool()
2188    }
2189
2190    /// What a field's [`InputPurpose`] asks of UIKit: the keyboard, the AutoFill content
2191    /// type, capitalization, and whether the keyboard corrects and spell-checks. Everything
2192    /// but free text is typed exactly, so correction is off for all of them.
2193    fn purpose_traits(
2194        purpose: InputPurpose,
2195    ) -> (
2196        UIKeyboardType,
2197        Option<&'static NSString>,
2198        UITextAutocapitalizationType,
2199        bool,
2200    ) {
2201        use UIKeyboardType as K;
2202        use UITextAutocapitalizationType as C;
2203        // SAFETY (the statics below): UIKit string constants, present since iOS 12 at the
2204        // latest.
2205        unsafe {
2206            match purpose {
2207                InputPurpose::Text => (K::Default, None, C::Sentences, true),
2208                InputPurpose::Name => (K::Default, Some(UITextContentTypeName), C::Words, false),
2209                InputPurpose::Email => (
2210                    K::EmailAddress,
2211                    Some(UITextContentTypeEmailAddress),
2212                    C::None,
2213                    false,
2214                ),
2215                InputPurpose::Url => (K::URL, Some(UITextContentTypeURL), C::None, false),
2216                InputPurpose::Phone => (
2217                    K::PhonePad,
2218                    Some(UITextContentTypeTelephoneNumber),
2219                    C::None,
2220                    false,
2221                ),
2222                InputPurpose::Number => (K::NumberPad, None, C::None, false),
2223                InputPurpose::Decimal => (K::DecimalPad, None, C::None, false),
2224                InputPurpose::Username => {
2225                    (K::Default, Some(UITextContentTypeUsername), C::None, false)
2226                }
2227                InputPurpose::Password => {
2228                    (K::Default, Some(UITextContentTypePassword), C::None, false)
2229                }
2230                InputPurpose::NewPassword => (
2231                    K::Default,
2232                    Some(UITextContentTypeNewPassword),
2233                    C::None,
2234                    false,
2235                ),
2236                // The text keyboard: a code can carry letters, and the QuickType bar offers
2237                // the arriving one whatever the layout.
2238                InputPurpose::OneTimeCode => (
2239                    K::Default,
2240                    Some(UITextContentTypeOneTimeCode),
2241                    C::None,
2242                    false,
2243                ),
2244            }
2245        }
2246    }
2247
2248    // ── The window toolbar on a phone (docs/toolbars.md) ───────────────────────────────
2249    //
2250    // Day's window toolbar model is one item list per window root, and where it lands depends
2251    // on what the window holds. A window whose content is a navigation host puts the items on
2252    // the NAVIGATION BAR of the page showing, rebuilt for every page under that root so the
2253    // bar reads the same from page to page — the desktop toolbar's shape on the phone, with
2254    // the page's own `bar_action`s after it. A window with no navigation host anywhere in it
2255    // (a canvas, a form) has no page bar to use, so Day gives it one: a navigation bar across
2256    // the top of the window, carrying the same groups, and the day root gives up that strip.
2257    //
2258    // Search stays on the navigation surface and the sidebar toggle belongs to the split view,
2259    // so both item kinds are skipped either way.
2260
2261    const TB_BUTTON: u8 = 0;
2262    const TB_TOGGLE: u8 = 1;
2263
2264    struct ToolbarTargetIvars {
2265        action: u64,
2266        kind: u8,
2267        item: String,
2268        /// The window root the item's model lives under (`WINDOW_TOOLBARS` key).
2269        root: usize,
2270    }
2271
2272    define_class!(
2273        #[unsafe(super(NSObject))]
2274        #[thread_kind = MainThreadOnly]
2275        #[name = "DayUIKitToolbarTarget"]
2276        #[ivars = ToolbarTargetIvars]
2277        struct DayToolbarTarget;
2278
2279        unsafe impl NSObjectProtocol for DayToolbarTarget {}
2280
2281        impl DayToolbarTarget {
2282            #[unsafe(method(fire:))]
2283            fn fire(&self, _sender: &AnyObject) {
2284                day_spec::ffi_guard::contain((), || {
2285                    let iv = self.ivars();
2286                    fire_toolbar_item(iv.action, iv.kind, &iv.item, iv.root);
2287                });
2288            }
2289        }
2290    );
2291
2292    /// Run one toolbar item's command.
2293    ///
2294    /// Shared by the bar button's target/action and by the `menuRepresentation` the bar's
2295    /// overflow shows in its place, so an item folded into "More" does exactly what it did on
2296    /// the bar — including a toggle's model flip, which the overflow would otherwise skip.
2297    fn fire_toolbar_item(action: u64, kind: u8, item: &str, root: usize) {
2298        match kind {
2299            TB_TOGGLE => {
2300                // Flip the model first, so the re-applied bar shows the new state
2301                // before the app's own `ToolbarPatch::On` confirms it.
2302                let on = WINDOW_TOOLBARS.with(|t| {
2303                    let mut t = t.borrow_mut();
2304                    let bar = t.get_mut(&root)?;
2305                    let it = bar.items.iter_mut().find(|i| i.id == item)?;
2306                    match &mut it.kind {
2307                        day_spec::ToolbarItemKind::Toggle { on } => {
2308                            *on = !*on;
2309                            Some(*on)
2310                        }
2311                        _ => None,
2312                    }
2313                });
2314                if let Some(on) = on {
2315                    reapply_window_toolbar(root);
2316                    emit(
2317                        WINDOW_NODE,
2318                        Event::ToolbarChanged {
2319                            action,
2320                            value: day_spec::ToolbarValue::On(on),
2321                        },
2322                    );
2323                }
2324            }
2325            _ => emit(WINDOW_NODE, Event::MenuAction(action)),
2326        }
2327    }
2328
2329    impl DayToolbarTarget {
2330        fn new(
2331            mtm: MainThreadMarker,
2332            action: u64,
2333            kind: u8,
2334            item: String,
2335            root: usize,
2336        ) -> Retained<Self> {
2337            let this = Self::alloc(mtm).set_ivars(ToolbarTargetIvars {
2338                action,
2339                kind,
2340                item,
2341                root,
2342            });
2343            unsafe { msg_send![super(this), init] }
2344        }
2345    }
2346
2347    /// One window's toolbar: the model as the app last set it, and the targets its live
2348    /// items fire — kept alive here because `UIBarButtonItem` holds its target weakly.
2349    struct WindowToolbar {
2350        root: Retained<UIView>,
2351        items: Vec<day_spec::ToolbarItem>,
2352        targets: Vec<Retained<DayToolbarTarget>>,
2353        /// The bar a window with NO navigation host carries instead: a navigation bar of
2354        /// the window's own. `None` while the window's pages carry the items.
2355        docked: Option<Retained<UINavigationBar>>,
2356    }
2357
2358    thread_local! {
2359        /// Keyed by the window root view ptr (the handle `set_toolbar` receives).
2360        static WINDOW_TOOLBARS: RefCell<HashMap<usize, WindowToolbar>> = RefCell::new(HashMap::new());
2361    }
2362
2363    /// Apply a targeted patch to the stored model; `true` when something changed.
2364    fn patch_toolbar_model(
2365        items: &mut [day_spec::ToolbarItem],
2366        patch: &day_spec::ToolbarPatch,
2367    ) -> bool {
2368        use day_spec::{ToolbarItemKind as K, ToolbarPatch as P};
2369        match patch {
2370            P::On { item, on } => {
2371                if let Some(it) = items.iter_mut().find(|i| i.id == *item)
2372                    && let K::Toggle { on: o } = &mut it.kind
2373                    && *o != *on
2374                {
2375                    *o = *on;
2376                    return true;
2377                }
2378            }
2379            P::Selected { item, index } => {
2380                if let Some(it) = items.iter_mut().find(|i| i.id == *item)
2381                    && let K::Segmented { segments, selected } = &mut it.kind
2382                    && *index < segments.len()
2383                    && *selected != *index
2384                {
2385                    *selected = *index;
2386                    return true;
2387                }
2388            }
2389            P::Enabled { item, on } => {
2390                if let Some(it) = items.iter_mut().find(|i| i.id == *item)
2391                    && it.enabled != *on
2392                {
2393                    it.enabled = *on;
2394                    return true;
2395                }
2396            }
2397            // A search item's values are kept for the next page field built from the model,
2398            // and never re-apply the bar: the field takes them itself (`patch_page_search`).
2399            P::Text { .. } | P::Suggestions { .. } | P::Placeholder { .. } => {
2400                patch.apply_to(items);
2401            }
2402            // New words for a button: its title and accessibility label come from the model,
2403            // so the page bars take them on the re-apply.
2404            P::Label {
2405                item,
2406                label,
2407                tooltip,
2408            } => {
2409                if let Some(it) = items.iter_mut().find(|i| i.id == *item)
2410                    && (it.label != *label || it.tooltip != *tooltip)
2411                {
2412                    it.label.clone_from(label);
2413                    it.tooltip.clone_from(tooltip);
2414                    return true;
2415                }
2416            }
2417            P::Focus { .. } => {}
2418        }
2419        false
2420    }
2421
2422    /// Fresh `UIBarButtonItems` for one page. Built per page rather than shared: a bar button
2423    /// item belongs to one bar at a time, and every page under the navigation controller
2424    /// carries its own copy of the window's bar.
2425    fn build_toolbar_items(
2426        mtm: MainThreadMarker,
2427        root: usize,
2428        items: &[day_spec::ToolbarItem],
2429        targets: &mut Vec<Retained<DayToolbarTarget>>,
2430    ) -> Vec<Retained<UIBarButtonItem>> {
2431        use day_spec::ToolbarItemKind as K;
2432        let mut out: Vec<Retained<UIBarButtonItem>> = Vec::new();
2433        for item in items {
2434            let image = menu_image(item.icon.as_ref());
2435            let title = NSString::from_str(&item.label);
2436            let bar: Retained<UIBarButtonItem> = match &item.kind {
2437                K::Search { .. } => continue,
2438                K::Separator => unsafe { UIBarButtonItem::fixedSpaceItemOfWidth(16.0, mtm) },
2439                K::Label => {
2440                    let b = unsafe {
2441                        UIBarButtonItem::initWithTitle_style_target_action(
2442                            UIBarButtonItem::alloc(mtm),
2443                            Some(&title),
2444                            UIBarButtonItemStyle::Plain,
2445                            None,
2446                            None,
2447                        )
2448                    };
2449                    unsafe { b.setEnabled(false) };
2450                    out.push(b);
2451                    continue;
2452                }
2453                K::Menu { items: entries } => {
2454                    let menu = build_ui_menu(mtm, "", entries);
2455                    match image {
2456                        Some(img) => unsafe {
2457                            UIBarButtonItem::initWithImage_menu(
2458                                UIBarButtonItem::alloc(mtm),
2459                                Some(&img),
2460                                Some(&menu),
2461                            )
2462                        },
2463                        None => unsafe {
2464                            UIBarButtonItem::initWithTitle_menu(
2465                                UIBarButtonItem::alloc(mtm),
2466                                Some(&title),
2467                                Some(&menu),
2468                            )
2469                        },
2470                    }
2471                }
2472                K::Segmented { segments, selected } => {
2473                    // A menu of the segments with the chosen one checked: a segmented control
2474                    // has no room in a phone's bar, and a pull-down is what iOS does instead.
2475                    let mut els: Vec<Retained<UIMenuElement>> = Vec::new();
2476                    for (i, seg) in segments.iter().enumerate() {
2477                        let (action, id, enabled) = (item.action, item.id.clone(), item.enabled);
2478                        // The chosen segment is the checked row — the pull-down's way of showing
2479                        // which one is in force.
2480                        let el = ui_action(
2481                            mtm,
2482                            &seg.title,
2483                            enabled,
2484                            Some(i == *selected),
2485                            seg.icon.as_ref(),
2486                            move || {
2487                                let changed = WINDOW_TOOLBARS.with(|t| {
2488                                    let mut t = t.borrow_mut();
2489                                    let bar = t.get_mut(&root)?;
2490                                    let it = bar.items.iter_mut().find(|x| x.id == id)?;
2491                                    match &mut it.kind {
2492                                        K::Segmented { selected, .. } => {
2493                                            *selected = i;
2494                                            Some(())
2495                                        }
2496                                        _ => None,
2497                                    }
2498                                });
2499                                if changed.is_some() {
2500                                    reapply_window_toolbar(root);
2501                                }
2502                                emit(
2503                                    WINDOW_NODE,
2504                                    Event::ToolbarChanged {
2505                                        action,
2506                                        value: day_spec::ToolbarValue::Selected(i),
2507                                    },
2508                                );
2509                            },
2510                        );
2511                        els.push(el);
2512                    }
2513                    let menu = unsafe {
2514                        UIMenu::menuWithTitle_children(
2515                            &title,
2516                            &objc2_foundation::NSArray::from_retained_slice(&els),
2517                            mtm,
2518                        )
2519                    };
2520                    // The control's own icon if it declared one; failing that the SEGMENT in
2521                    // force, which is what a segmented control shows anyway. Only a set of
2522                    // segments with no icons at all falls back to the chosen segment's word: a
2523                    // bar button that reads "System" is as wide as its longest state and moves
2524                    // the items beside it every time the setting changes, where the glyph the
2525                    // segment already carries says the same thing in a bar button's width.
2526                    let current = image.or_else(|| {
2527                        segments
2528                            .get(*selected)
2529                            .and_then(|s| menu_image(s.icon.as_ref()))
2530                    });
2531                    if let Some(img) = current {
2532                        unsafe {
2533                            UIBarButtonItem::initWithImage_menu(
2534                                UIBarButtonItem::alloc(mtm),
2535                                Some(&img),
2536                                Some(&menu),
2537                            )
2538                        }
2539                    } else {
2540                        unsafe {
2541                            let word = segments
2542                                .get(*selected)
2543                                .map_or_else(|| title.clone(), |s| NSString::from_str(&s.title));
2544                            UIBarButtonItem::initWithTitle_menu(
2545                                UIBarButtonItem::alloc(mtm),
2546                                Some(&word),
2547                                Some(&menu),
2548                            )
2549                        }
2550                    }
2551                }
2552                K::Button | K::Toggle { .. } => {
2553                    let kind = if matches!(item.kind, K::Toggle { .. }) {
2554                        TB_TOGGLE
2555                    } else {
2556                        TB_BUTTON
2557                    };
2558                    let target =
2559                        DayToolbarTarget::new(mtm, item.action, kind, item.id.clone(), root);
2560                    let b = match image {
2561                        Some(img) => unsafe {
2562                            UIBarButtonItem::initWithImage_style_target_action(
2563                                UIBarButtonItem::alloc(mtm),
2564                                Some(&img),
2565                                UIBarButtonItemStyle::Plain,
2566                                Some(&target),
2567                                Some(sel!(fire:)),
2568                            )
2569                        },
2570                        None => unsafe {
2571                            UIBarButtonItem::initWithTitle_style_target_action(
2572                                UIBarButtonItem::alloc(mtm),
2573                                Some(&title),
2574                                UIBarButtonItemStyle::Plain,
2575                                Some(&target),
2576                                Some(sel!(fire:)),
2577                            )
2578                        },
2579                    };
2580                    if let K::Toggle { on } = item.kind {
2581                        // iOS 15's selected look for a bar button: the pressed-in tint.
2582                        unsafe { b.setSelected(on) };
2583                    }
2584                    targets.push(target);
2585                    b
2586                }
2587            };
2588            unsafe {
2589                bar.setEnabled(item.enabled);
2590                bar.setAccessibilityLabel(Some(&title), mtm);
2591                // `menuRepresentation` is iOS 16's, as is the overflow it feeds: iOS 15 has no
2592                // item groups to fold (see `apply_items_styled`).
2593                if os_at_least(16)
2594                    && let Some(rep) = menu_representation(mtm, item, root, &bar)
2595                {
2596                    bar.setMenuRepresentation(Some(&rep));
2597                }
2598            }
2599            out.push(bar);
2600        }
2601        out
2602    }
2603
2604    /// What the bar's overflow ("More") shows in an item's place once the width runs out.
2605    ///
2606    /// A bar button built from an image alone carries NO title, and UIKit's own substitution
2607    /// shows exactly what the item has: the recorder's Record and Play folded away to two bare
2608    /// glyphs with nothing to read. `menuRepresentation` is the documented override, and Day
2609    /// always gives one, so a folded item shows its localized label — with its icon beside it,
2610    /// which is what the item wears on the bar (docs/toolbars.md).
2611    fn menu_representation(
2612        mtm: MainThreadMarker,
2613        item: &day_spec::ToolbarItem,
2614        root: usize,
2615        bar: &UIBarButtonItem,
2616    ) -> Option<Retained<UIMenuElement>> {
2617        use day_spec::ToolbarItemKind as K;
2618        // A control that declared no name of its own is named by the choice in force, the way
2619        // its bar button already draws that choice's glyph — a nameless entry in the overflow
2620        // is the same blank row android-material grew before `nameSegmentHead`.
2621        let title = match (item.label.as_str(), &item.kind) {
2622            ("", K::Segmented { segments, selected }) => {
2623                segments.get(*selected).map_or_default(|s| s.title.clone())
2624            }
2625            (label, _) => label.to_string(),
2626        };
2627        if title.is_empty() {
2628            return None;
2629        }
2630        // A pull-down keeps its children and gains the title and icon it lacked; everything
2631        // else becomes one action that runs the same command the button runs.
2632        if let Some(menu) = unsafe { bar.menu() } {
2633            let image = menu_image(item.icon.as_ref());
2634            return Some(Retained::into_super(unsafe {
2635                UIMenu::menuWithTitle_image_identifier_options_children(
2636                    &NSString::from_str(&title),
2637                    image.as_deref(),
2638                    None,
2639                    UIMenuOptions::empty(),
2640                    &menu.children(),
2641                    mtm,
2642                )
2643            }));
2644        }
2645        let kind = if matches!(item.kind, K::Toggle { .. }) {
2646            TB_TOGGLE
2647        } else {
2648            TB_BUTTON
2649        };
2650        let (action, id) = (item.action, item.id.clone());
2651        // A toggle reads as a checked row in a menu, the way it reads as a pressed button on the bar.
2652        let checked = match item.kind {
2653            K::Toggle { on } => Some(on),
2654            _ => None,
2655        };
2656        let el = ui_action(
2657            mtm,
2658            &title,
2659            item.enabled,
2660            checked,
2661            item.icon.as_ref(),
2662            move || fire_toolbar_item(action, kind, &id, root),
2663        );
2664        Some(el)
2665    }
2666
2667    // ── Where a window's bar goes ──────────────────────────────────────────────────────
2668    //
2669    // Each expanded column receives its own commands; window commands ride the detail.
2670    // Collapsed stacks merge the visible contributions. iOS 16 item groups handle overflow
2671    // natively; older/plain bars use a bounded set of buttons and a native UIMenu.
2672
2673    /// Where one navigation controller shows its window's bar.
2674    #[derive(Clone, Copy, PartialEq, Eq)]
2675    enum BarPlacement {
2676        /// In the navigation bar: the stack that is showing pages.
2677        NavBar,
2678        /// One column of an expanded split.
2679        Column(day_spec::ToolbarColumn),
2680        /// Not this controller's concern: a stack nested inside another host's page. The
2681        /// window's bar rides the outer host, and a nested stack is left entirely alone — a
2682        /// toolbar-visibility call on it during its own push transition cancels the push on
2683        /// iOS 26 and later (the Showcase's Stack page popped straight back on CI's iPhone).
2684        Nested,
2685    }
2686
2687    fn same_nav(a: &DayNavController, b: &objc2_ui_kit::UINavigationController) -> bool {
2688        let a: &objc2_ui_kit::UINavigationController = a;
2689        std::ptr::eq(a, b)
2690    }
2691
2692    /// A page controller's identity, for the per-page records below.
2693    fn vc_key(vc: &UIViewController) -> usize {
2694        std::ptr::from_ref::<UIViewController>(vc).cast::<()>() as usize
2695    }
2696
2697    fn bar_placement(nav: &objc2_ui_kit::UINavigationController) -> BarPlacement {
2698        NAV_STATE.with(|m| {
2699            let m = m.borrow();
2700            for s in m.values() {
2701                let Some(parts) = &s.split else {
2702                    if same_nav(&s.nav, nav) {
2703                        // A plain stack is the window's host only when no other host's view
2704                        // contains it.
2705                        let nested = s.nav.view().is_some_and(|nv| {
2706                            m.values().any(|o| {
2707                                let host_view = match &o.split {
2708                                    Some(p) => p.split_vc.view(),
2709                                    None => o.nav.view(),
2710                                };
2711                                host_view.is_some_and(|hv| {
2712                                    !std::ptr::eq(&raw const *hv, &raw const *nv)
2713                                        && unsafe { nv.isDescendantOfView(&hv) }
2714                                })
2715                            })
2716                        });
2717                        return if nested {
2718                            BarPlacement::Nested
2719                        } else {
2720                            BarPlacement::NavBar
2721                        };
2722                    }
2723                    continue;
2724                };
2725                // Read UIKit directly: presentation notifications can trail the merge.
2726                let expanded = !unsafe { parts.split_vc.isCollapsed() };
2727                if same_nav(&parts.primary_nav, nav) {
2728                    return if expanded {
2729                        BarPlacement::Column(day_spec::ToolbarColumn::Sidebar)
2730                    } else {
2731                        BarPlacement::NavBar
2732                    };
2733                }
2734                if parts
2735                    .supplementary_nav
2736                    .as_ref()
2737                    .is_some_and(|n| same_nav(n, nav))
2738                {
2739                    return if expanded {
2740                        BarPlacement::Column(day_spec::ToolbarColumn::List)
2741                    } else {
2742                        BarPlacement::NavBar
2743                    };
2744                }
2745                if same_nav(&s.nav, nav) {
2746                    return if expanded {
2747                        BarPlacement::Column(day_spec::ToolbarColumn::Detail)
2748                    } else {
2749                        BarPlacement::NavBar
2750                    };
2751                }
2752            }
2753            BarPlacement::NavBar
2754        })
2755    }
2756
2757    /// Native search policy for the sidebar's own controller (docs/search.md).
2758    ///
2759    /// `Always` pins the field under the large title. `Scrolls` and `OnPull` hand it to UIKit's
2760    /// `hidesSearchBarWhenScrolling`, set once and left alone: the field shows with the list at
2761    /// its top, collapses with the large title as the list scrolls, and comes back at the top.
2762    /// UIKit has no "starts collapsed" state, and every attempt to manufacture one here (pin
2763    /// the bar, flip the flag later, scroll the list by the bar's height) left the bar in a
2764    /// state UIKit never shows on its own, so `OnPull` is `Scrolls` on this toolkit. Stacked
2765    /// placement at every width, so an iPad does not fold the field into the bar's trailing
2766    /// end, away from the list it searches.
2767    fn configure_sidebar_search(
2768        item: &objc2_ui_kit::UINavigationItem,
2769        nav: &DayNavController,
2770        hides: bool,
2771        initially_hidden: bool,
2772    ) {
2773        unsafe {
2774            item.setHidesSearchBarWhenScrolling(hides || initially_hidden);
2775            item.setLargeTitleDisplayMode(
2776                objc2_ui_kit::UINavigationItemLargeTitleDisplayMode::Always,
2777            );
2778            nav.navigationBar().setPrefersLargeTitles(true);
2779            if os_at_least(16) {
2780                item.setPreferredSearchBarPlacement(
2781                    objc2_ui_kit::UINavigationItemSearchBarPlacement::Stacked,
2782                );
2783            }
2784        }
2785    }
2786
2787    /// Every navigation controller of every host under a window root: the detail stack and
2788    /// the sidebar (and list) column stacks. Each is placed by `bar_placement`, so a collapse
2789    /// or expand MOVES the bar rather than leaving a copy behind.
2790    /// The adaptive tabs host under `root`, if the window has one. Its own bar carries the
2791    /// window's commands on iPadOS (docs/toolbars.md).
2792    fn tabs_host_under(root: &UIView) -> Option<Retained<UITabBarController>> {
2793        NAV_TABS.with(|m| {
2794            m.borrow()
2795                .values()
2796                .find(|t| {
2797                    unsafe { t.tabbar.view() }
2798                        .is_some_and(|v| unsafe { v.isDescendantOfView(root) })
2799                })
2800                .map(|t| t.tabbar.clone())
2801        })
2802    }
2803
2804    fn toolbar_navs_under(root: &UIView) -> Vec<Retained<DayNavController>> {
2805        NAV_STATE.with(|m| {
2806            m.borrow()
2807                .values()
2808                .filter(|s| {
2809                    // Test the split HOST's view where there is one: a collapsed split keeps
2810                    // its secondary column out of the hierarchy (the pages ride the primary's
2811                    // stack then), so asking that column would drop the whole window.
2812                    let view = match &s.split {
2813                        Some(parts) => parts.split_vc.view(),
2814                        None => s.nav.view(),
2815                    };
2816                    view.is_some_and(|v| unsafe { v.isDescendantOfView(root) })
2817                })
2818                .flat_map(|s| {
2819                    let mut navs = vec![s.nav.clone()];
2820                    if let Some(parts) = &s.split {
2821                        navs.push(parts.primary_nav.clone());
2822                        navs.extend(parts.supplementary_nav.clone());
2823                    }
2824                    navs
2825                })
2826                .collect()
2827        })
2828    }
2829
2830    thread_local! {
2831        /// Per view controller, the targets its bar items fire — kept alive here because a
2832        /// `UIBarButtonItem` holds its target weakly, and torn down with the page.
2833        static PAGE_TOOLBARS: RefCell<HashMap<usize, PageBar>> = RefCell::new(HashMap::new());
2834        /// Per NAVIGATION ITEM, the targets its bar buttons fire. A tabs host's shared bar has
2835        /// no view controller of its own to hang them on.
2836        static NAV_ITEM_TARGETS: RefCell<HashMap<usize, Vec<Retained<DayToolbarTarget>>>> =
2837            RefCell::new(HashMap::new());
2838    }
2839
2840    /// One page's bottom-bar targets, kept alive while that page is up: a `UIBarButtonItem`
2841    /// holds its target weakly.
2842    #[derive(Default)]
2843    struct PageBar {
2844        targets: Vec<Retained<DayToolbarTarget>>,
2845    }
2846
2847    /// The items a phone's bar can hold: spacers have no meaning on a bar that folds its
2848    /// overflow away, search rides the navigation surface, and the sidebar toggle is the
2849    /// split view's own.
2850    fn bar_controls(items: &[day_spec::ToolbarItem]) -> Vec<day_spec::ToolbarItem> {
2851        items
2852            .iter()
2853            .filter(|i| {
2854                // The sidebar affordance is UIKit's, not Day's: `UISplitViewController` shows
2855                // its own where a sidebar can be revealed, and `.tabSidebar` draws one in the
2856                // strip. Drawing Day's as well put a second, dead button on a phone — where
2857                // there is no sidebar to toggle at all — and duplicated the working one on an
2858                // iPad (docs/toolbars.md). Search rides the navigation surface, and a separator
2859                // means nothing on a bar that folds its overflow away.
2860                i.id != day_spec::SIDEBAR_TOGGLE_ID
2861                    && !matches!(
2862                        i.kind,
2863                        day_spec::ToolbarItemKind::Separator
2864                            | day_spec::ToolbarItemKind::Search { .. }
2865                    )
2866            })
2867            .cloned()
2868            .collect()
2869    }
2870
2871    /// One optional group per item, in declaration order, which is what lets a navigation bar
2872    /// fold the trailing ones into its overflow menu one at a time as the width runs out
2873    /// (docs/toolbars.md) — the reason a phone's bar takes groups rather than plain items.
2874    fn optional_item_groups(
2875        mtm: MainThreadMarker,
2876        controls: &[day_spec::ToolbarItem],
2877        bar_items: Vec<Retained<UIBarButtonItem>>,
2878    ) -> Vec<Retained<objc2_ui_kit::UIBarButtonItemGroup>> {
2879        controls
2880            .iter()
2881            .zip(bar_items)
2882            .map(|(item, bar)| unsafe {
2883                objc2_ui_kit::UIBarButtonItemGroup::optionalGroupWithCustomizationIdentifier_inDefaultCustomization_representativeItem_items(
2884                    &NSString::from_str(&item.id),
2885                    true,
2886                    None,
2887                    &objc2_foundation::NSArray::from_retained_slice(&[bar]),
2888                    mtm,
2889                )
2890            })
2891            .collect()
2892    }
2893
2894    /// Give `vc` the bar of the window it is in, if that window has one, where
2895    /// `bar_placement` says it goes. Called on every push, on the first page a navigation
2896    /// controller shows, and again on every model change and presentation change.
2897    fn apply_window_toolbar_to(nav: &objc2_ui_kit::UINavigationController, vc: &UIViewController) {
2898        let Some(mtm) = MainThreadMarker::new() else {
2899            return;
2900        };
2901        let Some(nav_view) = nav.view() else {
2902            return;
2903        };
2904        let found = WINDOW_TOOLBARS.with(|t| {
2905            t.borrow()
2906                .iter()
2907                .find(|(_, w)| unsafe { nav_view.isDescendantOfView(&w.root) })
2908                .map(|(root, w)| (*root, w.items.clone()))
2909        });
2910        let Some((root, items)) = found else {
2911            return;
2912        };
2913        let placement = bar_placement(nav);
2914        if placement == BarPlacement::Nested {
2915            return;
2916        }
2917        // A page bar is taking these, so the window's own bar comes down. It is here rather
2918        // than in `reapply_window_toolbar` alone because the app installs its toolbar while
2919        // it builds the window — before the navigation host it declares has any view — so the
2920        // first placement is the docked one, and this is where the host says otherwise.
2921        if let Some(root_view) =
2922            WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).map(|w| w.root.clone()))
2923        {
2924            undock_window_toolbar(root, &root_view);
2925        }
2926        // The window's items lead and the page's follow, so a page command sits next to the page
2927        // it acts on and the overflow eats from the trailing end (docs/toolbars.md). A column
2928        // that is not showing pages takes only its own page's items — the window's act on the
2929        // detail, which is one column over.
2930        let column = match placement {
2931            BarPlacement::Column(column) => Some(column),
2932            _ => None,
2933        };
2934        let window_items: Vec<_> = bar_controls(&items)
2935            .into_iter()
2936            .filter(|item| crate::toolbar_policy::belongs_to_column(item.column, column))
2937            .collect();
2938        // The expanded list already labels its content. Keep the controller title for
2939        // collapsed navigation/back history, but omit the duplicate root title in its bar.
2940        unsafe {
2941            let title = if column == Some(day_spec::ToolbarColumn::List) {
2942                Some(NSString::from_str(""))
2943            } else {
2944                vc.title()
2945            };
2946            vc.navigationItem().setTitle(title.as_deref());
2947        }
2948        apply_chrome(mtm, vc, root, &window_items);
2949        // The BOTTOM BAR is `UINavigationController`'s own, and it is hidden unless a page put
2950        // something on it (docs/toolbars.md). `apply_chrome` has just set this page's items, so
2951        // ask the page rather than clearing them and hiding unconditionally — which is what made
2952        // `Placement::Bottom` draw nothing on the one platform that has a bottom bar.
2953        let has_bottom = unsafe { vc.toolbarItems() }.is_some_and(|i| !i.is_empty());
2954        unsafe { nav.setToolbarHidden_animated(!has_bottom, false) };
2955    }
2956
2957    /// Lower one page's chrome: `window_items` first, then that page's own contributions, split
2958    /// by placement across the navigation item's leading, title and trailing slots.
2959    fn apply_chrome(
2960        mtm: MainThreadMarker,
2961        vc: &UIViewController,
2962        root: usize,
2963        window_items: &[day_spec::ToolbarItem],
2964    ) {
2965        let item = unsafe { vc.navigationItem() };
2966        apply_items_to(mtm, &item, root, window_items);
2967        // A bottom bar belongs to the view controller, not to its navigation item; the
2968        // navigation controller reveals it in `apply_window_toolbar_to` once it has items.
2969        let bottom: Vec<day_spec::ToolbarItem> = window_items
2970            .iter()
2971            .filter(|i| i.placement == day_spec::ToolbarPlacement::Bottom)
2972            .cloned()
2973            .collect();
2974        let mut targets = Vec::new();
2975        let bot = bottom_bar_items(mtm, root, &bottom, &mut targets, vc);
2976        unsafe {
2977            vc.setToolbarItems(
2978                (!bot.is_empty())
2979                    .then(|| objc2_foundation::NSArray::from_retained_slice(&bot))
2980                    .as_deref(),
2981            );
2982        }
2983        PAGE_TOOLBARS.with(|m| {
2984            m.borrow_mut().entry(vc_key(vc)).or_default().targets = targets;
2985        });
2986    }
2987
2988    /// A page's bottom bar, laid out the way Mail and Notes lay out theirs (docs/toolbars.md):
2989    /// the items before the first label at the leading edge, the label centered as the bar's
2990    /// status, the items after it at the trailing edge. A bar with no label spreads its items
2991    /// across the width with flexible spaces, as a stock `UIToolbar` of commands does.
2992    fn bottom_bar_items(
2993        mtm: MainThreadMarker,
2994        root: usize,
2995        items: &[day_spec::ToolbarItem],
2996        targets: &mut Vec<Retained<DayToolbarTarget>>,
2997        vc: &UIViewController,
2998    ) -> Vec<Retained<UIBarButtonItem>> {
2999        let flexible = || unsafe { UIBarButtonItem::flexibleSpaceItem(mtm) };
3000        let status = items
3001            .iter()
3002            .position(|i| matches!(i.kind, day_spec::ToolbarItemKind::Label));
3003        let mut out = Vec::new();
3004        for (index, item) in items.iter().enumerate() {
3005            if status == Some(index) {
3006                out.push(flexible());
3007                out.push(bottom_status_item(mtm, &item.id, &item.label, vc));
3008                out.push(flexible());
3009                continue;
3010            }
3011            let built = build_toolbar_items(mtm, root, std::slice::from_ref(item), targets);
3012            for bar in &built {
3013                remember_bottom(
3014                    &item.id,
3015                    BottomView::Button(objc2::rc::Weak::from_retained(bar)),
3016                );
3017            }
3018            if status.is_none() && !out.is_empty() && !built.is_empty() {
3019                out.push(flexible());
3020            }
3021            out.extend(built);
3022        }
3023        out
3024    }
3025
3026    /// A bottom bar's live views, by item id: what a patch changes in place.
3027    enum BottomView {
3028        /// A status item's outer view, and the page whose toolbar items carry it.
3029        Status(objc2::rc::Weak<UIView>, objc2::rc::Weak<UIViewController>),
3030        Button(objc2::rc::Weak<UIBarButtonItem>),
3031    }
3032
3033    thread_local! {
3034        /// Every page carries its own copy of the bottom bar, so an id can have several.
3035        static BOTTOM_VIEWS: RefCell<Vec<(String, BottomView)>> = const { RefCell::new(Vec::new()) };
3036    }
3037
3038    fn remember_bottom(id: &str, view: BottomView) {
3039        BOTTOM_VIEWS.with(|v| {
3040            let mut v = v.borrow_mut();
3041            v.retain(|(_, view)| match view {
3042                BottomView::Status(w, _) => w.load().is_some(),
3043                BottomView::Button(w) => w.load().is_some(),
3044            });
3045            v.push((id.to_owned(), view));
3046        });
3047    }
3048
3049    /// Apply `patch` to a bottom bar's live views without rebuilding the bar, where the patch
3050    /// is one a view can take in place: the status's words, a button's enabled state, a
3051    /// toggle's state. A status that changes a few times a second during a sync otherwise
3052    /// rebuilt every button on the bar each time, and a toggle on it flashed as it was made
3053    /// again. Answers whether the patch was the bottom bar's alone and is fully applied.
3054    fn patch_bottom_in_place(
3055        items: &[day_spec::ToolbarItem],
3056        patch: &day_spec::ToolbarPatch,
3057    ) -> bool {
3058        use day_spec::{ToolbarItemKind as K, ToolbarPatch as P};
3059        let Some(item) = items.iter().find(|i| i.id == patch.item()) else {
3060            return false;
3061        };
3062        if item.placement != day_spec::ToolbarPlacement::Bottom {
3063            return false;
3064        }
3065        let views: Vec<BottomView> = BOTTOM_VIEWS.with(|v| {
3066            v.borrow()
3067                .iter()
3068                .filter(|(id, _)| *id == item.id)
3069                .map(|(_, view)| match view {
3070                    BottomView::Status(w, vc) => BottomView::Status(w.clone(), vc.clone()),
3071                    BottomView::Button(w) => BottomView::Button(w.clone()),
3072                })
3073                .collect()
3074        });
3075        if views.is_empty() {
3076            return false;
3077        }
3078        match (patch, &item.kind) {
3079            (P::Label { label, .. }, K::Label) => {
3080                // A fresh status item in the old one's place, among the same button objects:
3081                // the toolbar fits a custom view to the room between its neighbors only when
3082                // its items are set, so new words in the old view could outgrow that room and
3083                // run over the buttons. The buttons themselves are not rebuilt, so nothing on
3084                // the bar redraws but the status.
3085                let Some(mtm) = MainThreadMarker::new() else {
3086                    return false;
3087                };
3088                for view in &views {
3089                    let BottomView::Status(row, vc) = view else {
3090                        continue;
3091                    };
3092                    let (Some(row), Some(vc)) = (row.load(), vc.load()) else {
3093                        continue;
3094                    };
3095                    let Some(bar) = (unsafe { vc.toolbarItems() }) else {
3096                        continue;
3097                    };
3098                    let mut list = bar.to_vec();
3099                    let Some(i) = list.iter().position(|b| {
3100                        unsafe { b.customView() }
3101                            .is_some_and(|v| std::ptr::eq(&raw const *v, &raw const *row))
3102                    }) else {
3103                        continue;
3104                    };
3105                    list[i] = bottom_status_item(mtm, &item.id, label, &vc);
3106                    unsafe {
3107                        vc.setToolbarItems_animated(
3108                            Some(&objc2_foundation::NSArray::from_retained_slice(&list)),
3109                            false,
3110                        );
3111                    }
3112                }
3113                true
3114            }
3115            (P::Enabled { on, .. }, _) => {
3116                for view in &views {
3117                    if let BottomView::Button(w) = view
3118                        && let Some(bar) = w.load()
3119                    {
3120                        unsafe { bar.setEnabled(*on) };
3121                    }
3122                }
3123                true
3124            }
3125            (P::On { on, .. }, K::Toggle { .. }) => {
3126                for view in &views {
3127                    if let BottomView::Button(w) = view
3128                        && let Some(bar) = w.load()
3129                    {
3130                        unsafe { bar.setSelected(*on) };
3131                    }
3132                }
3133                true
3134            }
3135            _ => false,
3136        }
3137    }
3138
3139    /// The bottom bar's status: Mail's "Updated Just Now" over its unread count. Each line of
3140    /// `text` is one line of the status, the first in the primary label color and the rest in
3141    /// the secondary, all in the footnote style so they follow the reader's text size. The
3142    /// toolbar gives the status the room between its buttons, with its own spacing beside them;
3143    /// the lines fill that width and truncate inside it, their text centered.
3144    fn bottom_status_item(
3145        mtm: MainThreadMarker,
3146        id: &str,
3147        text: &str,
3148        vc: &UIViewController,
3149    ) -> Retained<UIBarButtonItem> {
3150        let lines = unsafe { objc2_ui_kit::UIStackView::new(mtm) };
3151        unsafe {
3152            lines.setAxis(objc2_ui_kit::UILayoutConstraintAxis::Vertical);
3153            // Fill, with the text centered in each line: a centered stack lets a line grow past
3154            // its own width, so a long status ran under the buttons beside it.
3155            lines.setAlignment(objc2_ui_kit::UIStackViewAlignment::Fill);
3156        }
3157        fill_status(&lines, text);
3158        let outer: Retained<UIView> = Retained::into_super(lines.clone());
3159        remember_bottom(
3160            id,
3161            BottomView::Status(
3162                objc2::rc::Weak::from_retained(&outer),
3163                objc2::rc::Weak::from_retained(&vc.retain()),
3164            ),
3165        );
3166        unsafe { UIBarButtonItem::initWithCustomView(UIBarButtonItem::alloc(mtm), &lines) }
3167    }
3168
3169    /// Put `text` in a status view, one label a line, reusing the labels it already has.
3170    fn fill_status(stack: &objc2_ui_kit::UIStackView, text: &str) {
3171        let mtm = stack.mtm();
3172        let font = unsafe {
3173            objc2_ui_kit::UIFont::preferredFontForTextStyle(objc2_ui_kit::UIFontTextStyleFootnote)
3174        };
3175        let lines: Vec<&str> = text.lines().collect();
3176        let existing: Vec<Retained<UIView>> = unsafe { stack.arrangedSubviews() }.to_vec();
3177        for (index, line) in lines.iter().enumerate() {
3178            let label = if let Some(label) = existing
3179                .get(index)
3180                .and_then(|v| v.clone().downcast::<UILabel>().ok())
3181            {
3182                label
3183            } else {
3184                let label = UILabel::new(mtm);
3185                let color = if index == 0 {
3186                    UIColor::labelColor()
3187                } else {
3188                    UIColor::secondaryLabelColor()
3189                };
3190                unsafe {
3191                    label.setFont(Some(&font));
3192                    let _: () = msg_send![&*label, setAdjustsFontForContentSizeCategory: true];
3193                    label.setTextColor(Some(&color));
3194                    label.setTextAlignment(objc2_ui_kit::NSTextAlignment::Center);
3195                    // Just under the buttons' resistance, so a long status truncates before a
3196                    // button gives way, but well over the flexible spaces', which would
3197                    // otherwise squeeze the status to nothing.
3198                    label.setContentCompressionResistancePriority_forAxis(
3199                        objc2_ui_kit::UILayoutPriorityDefaultHigh - 1.0,
3200                        objc2_ui_kit::UILayoutConstraintAxis::Horizontal,
3201                    );
3202                    stack.addArrangedSubview(&label);
3203                }
3204                label
3205            };
3206            label.setText(Some(&NSString::from_str(line)));
3207        }
3208        for extra in existing.iter().skip(lines.len()) {
3209            extra.removeFromSuperview();
3210        }
3211        // One element for VoiceOver, read as the whole status rather than line by line.
3212        stack.setIsAccessibilityElement(true, mtm);
3213        stack.setAccessibilityLabel(Some(&NSString::from_str(&text.replace('\n', ", "))), mtm);
3214    }
3215
3216    /// Lower `all` onto one navigation item, split by placement across its leading, title and
3217    /// trailing slots (docs/toolbars.md).
3218    fn apply_items_to(
3219        mtm: MainThreadMarker,
3220        item: &objc2_ui_kit::UINavigationItem,
3221        root: usize,
3222        window_items: &[day_spec::ToolbarItem],
3223    ) {
3224        apply_items_styled(mtm, item, root, window_items, true);
3225    }
3226
3227    /// [`apply_items_to`], choosing how the trailing items are attached. Item GROUPS give a
3228    /// navigation bar its overflow behavior, but a tabs host's shared bar draws only plain
3229    /// trailing items — so that one asks for `rightBarButtonItems` instead.
3230    fn apply_items_styled(
3231        mtm: MainThreadMarker,
3232        item: &objc2_ui_kit::UINavigationItem,
3233        root: usize,
3234        window_items: &[day_spec::ToolbarItem],
3235        groups_ok: bool,
3236    ) {
3237        use day_spec::ToolbarPlacement as P;
3238        // Item groups, and the overflow they give a bar, are iOS 16's (`trailingItemGroups`,
3239        // `UIBarButtonItemGroup`'s fixed/optional constructors); iOS 15 takes plain items.
3240        let groups_ok = groups_ok && os_at_least(16);
3241        let (all, overflow): (Vec<_>, Vec<_>) = if groups_ok {
3242            (window_items.to_vec(), Vec::new())
3243        } else {
3244            let visible = crate::toolbar_policy::legacy_visible(window_items);
3245            let mut shown = Vec::new();
3246            let mut hidden = Vec::new();
3247            for (index, item) in window_items.iter().enumerate() {
3248                if visible.contains(&index) {
3249                    shown.push(item.clone());
3250                } else {
3251                    hidden.push(item.clone());
3252                }
3253            }
3254            (shown, hidden)
3255        };
3256
3257        let take = |ps: &[P], all: &[day_spec::ToolbarItem]| -> Vec<day_spec::ToolbarItem> {
3258            all.iter()
3259                .filter(|i| ps.contains(&i.placement))
3260                .cloned()
3261                .collect()
3262        };
3263        let leading = take(&[P::Navigation], &all);
3264        let principal = take(&[P::Principal], &all);
3265        let trailing = take(&[P::Automatic, P::Primary], &all);
3266        let secondary = take(&[P::Secondary], &all);
3267
3268        let mut targets = Vec::new();
3269        unsafe {
3270            let lead = build_toolbar_items(mtm, root, &leading, &mut targets);
3271            // SUPPLEMENT the back button, never replace it. `leftBarButtonItems` takes the back
3272            // button's place by default, so a leading item on a pushed page left the user with
3273            // no way back — this is the flag SwiftUI sets for exactly the same reason.
3274            item.setLeftItemsSupplementBackButton(true);
3275            item.setLeftBarButtonItems(
3276                (!lead.is_empty())
3277                    .then(|| objc2_foundation::NSArray::from_retained_slice(&lead))
3278                    .as_deref(),
3279            );
3280            // A centered item replaces the title view. Only the first is honored: the slot holds
3281            // one view, and stacking two there is how a title stops being readable.
3282            let mid = build_toolbar_items(mtm, root, &principal, &mut targets);
3283            if let Some(title) = principal
3284                .first()
3285                .filter(|i| matches!(i.kind, day_spec::ToolbarItemKind::Label))
3286            {
3287                // A label bar item has no customView. Build a native title label instead of
3288                // passing None and silently dropping a Principal label from the bar.
3289                let label = UILabel::new(mtm);
3290                label.setText(Some(&NSString::from_str(&title.label)));
3291                label.setFont(Some(&objc2_ui_kit::UIFont::preferredFontForTextStyle(
3292                    objc2_ui_kit::UIFontTextStyleHeadline,
3293                )));
3294                label.setTextColor(Some(&UIColor::labelColor()));
3295                label.setNumberOfLines(1);
3296                label.sizeToFit();
3297                item.setTitleView(Some(&label));
3298            } else {
3299                // Removing a principal item must restore the ordinary native page title.
3300                item.setTitleView(mid.first().and_then(|i| i.customView()).as_deref());
3301            }
3302            // Primary items ride the pinned trailing group so a crowded bar never folds them;
3303            // everything else rides one optional group apiece, which is what lets UIKit take
3304            // them into the overflow one at a time from the trailing end (docs/toolbars.md).
3305            if groups_ok {
3306                let mut groups: Vec<Retained<objc2_ui_kit::UIBarButtonItemGroup>> = Vec::new();
3307                let auto: Vec<_> = trailing
3308                    .iter()
3309                    .filter(|i| i.placement != P::Primary)
3310                    .cloned()
3311                    .collect();
3312                let prime: Vec<_> = trailing
3313                    .iter()
3314                    .filter(|i| i.placement == P::Primary)
3315                    .cloned()
3316                    .collect();
3317                groups.extend(optional_item_groups(
3318                    mtm,
3319                    &auto,
3320                    build_toolbar_items(mtm, root, &auto, &mut targets),
3321                ));
3322                // Primary items ride the PINNED trailing group (iOS 16's
3323                // `pinnedTrailingGroup`): beside the overflow button, and never folded into
3324                // it, which is "folds last" on a phone's bar. A fixed group placed among the
3325                // optional ones in `trailingItemGroups` went missing with the folded ones once
3326                // the bar ran out of room (iOS 26, Day Sketch's Inspector).
3327                if prime.is_empty() {
3328                    item.setPinnedTrailingGroup(None);
3329                } else {
3330                    let built = build_toolbar_items(mtm, root, &prime, &mut targets);
3331                    let pinned =
3332                        objc2_ui_kit::UIBarButtonItemGroup::fixedGroupWithRepresentativeItem_items(
3333                            None,
3334                            &objc2_foundation::NSArray::from_retained_slice(&built),
3335                            mtm,
3336                        );
3337                    item.setPinnedTrailingGroup(Some(&pinned));
3338                }
3339                groups.extend(optional_item_groups(
3340                    mtm,
3341                    &secondary,
3342                    build_toolbar_items(mtm, root, &secondary, &mut targets),
3343                ));
3344                item.setTrailingItemGroups(&objc2_foundation::NSArray::from_retained_slice(
3345                    &groups,
3346                ));
3347            } else {
3348                // Rightmost first, which is `setRightBarButtonItems`' own order — reversing puts
3349                // the app's first-declared item leftmost, the order every other backend draws.
3350                let mut flat: Vec<day_spec::ToolbarItem> = trailing.clone();
3351                flat.extend(secondary.clone());
3352                let mut built = build_toolbar_items(mtm, root, &flat, &mut targets);
3353                if !overflow.is_empty() {
3354                    let bars = build_toolbar_items(mtm, root, &overflow, &mut targets);
3355                    let children: Vec<_> = overflow
3356                        .iter()
3357                        .zip(&bars)
3358                        .filter_map(|(control, bar)| menu_representation(mtm, control, root, bar))
3359                        .collect();
3360                    let menu = UIMenu::menuWithChildren(
3361                        &objc2_foundation::NSArray::from_retained_slice(&children),
3362                        mtm,
3363                    );
3364                    // UIKit has a localized system More tab item, but no More bar-item
3365                    // constant. Reuse its localized name with Day's More symbol.
3366                    let system_more = objc2_ui_kit::UITabBarItem::initWithTabBarSystemItem_tag(
3367                        objc2_ui_kit::UITabBarItem::alloc(mtm),
3368                        objc2_ui_kit::UITabBarSystemItem::More,
3369                        0,
3370                    );
3371                    let more = UIBarButtonItem::initWithImage_menu(
3372                        UIBarButtonItem::alloc(mtm),
3373                        menu_image(Some(&day_spec::Icon::Symbol(day_spec::Symbol::More)))
3374                            .as_deref(),
3375                        Some(&menu),
3376                    );
3377                    more.setAccessibilityLabel(system_more.title().as_deref(), mtm);
3378                    let _: () = msg_send![&*more, setAccessibilityIdentifier: &*NSString::from_str("day-toolbar-overflow")];
3379                    built.insert(0, more);
3380                }
3381                let ordered: Vec<_> = built.into_iter().rev().collect();
3382                item.setRightBarButtonItems(Some(&objc2_foundation::NSArray::from_retained_slice(
3383                    &ordered,
3384                )));
3385            }
3386        }
3387        // The targets outlive the bar buttons, which hold theirs weakly. Keyed by the navigation
3388        // item, so a tabs host's shared bar and a page's own each keep their own.
3389        NAV_ITEM_TARGETS.with(|m| {
3390            m.borrow_mut()
3391                .insert(std::ptr::from_ref(item) as usize, targets);
3392        });
3393    }
3394
3395    /// Re-place a window's bar on every page of every navigation controller under it — after
3396    /// a model change, and after a collapse or expand — and its search field on the page
3397    /// showing.
3398    fn reapply_window_toolbar(root: usize) {
3399        reapply_window_bar_items(root);
3400        if let Some(root_view) =
3401            WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).map(|w| w.root.clone()))
3402        {
3403            sync_page_search(root, &root_view);
3404        }
3405    }
3406
3407    /// The buttons half of [`reapply_window_toolbar`].
3408    fn reapply_window_bar_items(root: usize) {
3409        let Some(root_view) =
3410            WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).map(|w| w.root.clone()))
3411        else {
3412            return;
3413        };
3414        WINDOW_TOOLBARS.with(|t| {
3415            if let Some(w) = t.borrow_mut().get_mut(&root) {
3416                w.targets.clear();
3417            }
3418        });
3419        // An ADAPTIVE TABS host draws its own chrome — the strip of destinations across the top
3420        // in `.tabSidebar`, a tab bar below in compact — and iPadOS puts a tabbed app's commands
3421        // on that same bar through the controller's `navigationItem`. Day used to dock a
3422        // navigation bar of its own above it, which is what stacked two bars on an iPad and
3423        // clipped the content between them (docs/toolbars.md).
3424        if let Some(tabbar) = tabs_host_under(&root_view) {
3425            undock_window_toolbar(root, &root_view);
3426            let items = WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).map(|w| w.items.clone()));
3427            if let Some(mtm) = MainThreadMarker::new() {
3428                let controls = bar_controls(&items.unwrap_or_default());
3429                // The tab in front owns the bar. Where the tab holds a navigation controller —
3430                // a wide window, where the page brings no host of its own — that controller's
3431                // top item IS the bar on screen; otherwise the page composed its own host and
3432                // its top item is (docs/toolbars.md).
3433                let shown = unsafe { tabbar.selectedViewController() };
3434                let item = shown.and_then(|vc| {
3435                    let inner = vc
3436                        .downcast_ref::<objc2_ui_kit::UINavigationController>()
3437                        .map(objc2::Message::retain)
3438                        .or_else(|| {
3439                            unsafe { vc.childViewControllers() }.iter().find_map(|c| {
3440                                c.downcast::<objc2_ui_kit::UINavigationController>().ok()
3441                            })
3442                        })?;
3443                    unsafe { inner.topViewController() }.map(|top| unsafe { top.navigationItem() })
3444                });
3445                if let Some(it) = item {
3446                    apply_items_to(mtm, &it, root, &controls);
3447                } else {
3448                    let nav_item = unsafe { tabbar.navigationItem() };
3449                    apply_items_styled(mtm, &nav_item, root, &controls, false);
3450                }
3451            }
3452            return;
3453        }
3454        let navs = toolbar_navs_under(&root_view);
3455        // A window whose content is not a navigation host has no page bar to put these on
3456        // (`toolbar_navs_under` finds nothing) — a canvas or a form filling the window, with
3457        // no `nav(…)` anywhere in it. `Cap::Toolbar` answered `Native` before the app built
3458        // that window, so dropping the items here would leave the app with neither a bar nor
3459        // the in-content strip it skipped on this backend's word. Dock one instead.
3460        if navs.is_empty() {
3461            dock_window_toolbar(root, &root_view);
3462            return;
3463        }
3464        undock_window_toolbar(root, &root_view);
3465        for nav in navs {
3466            for vc in &unsafe { nav.viewControllers() } {
3467                apply_window_toolbar_to(&nav, &vc);
3468            }
3469        }
3470    }
3471
3472    /// Keep navigation controls legible over nested scrolling content (including `WKWebView`
3473    /// inside a pager). UIKit's implicit scroll-edge appearance is transparent, and it may
3474    /// not track a nested scroll view's offset. Configure every height/edge state explicitly.
3475    fn configure_navigation_bar(bar: &UINavigationBar, mtm: MainThreadMarker) {
3476        let appearance = UINavigationBarAppearance::new(mtm);
3477        appearance.configureWithOpaqueBackground();
3478        // A dynamic system color follows both system appearance and a window theme override.
3479        appearance.setBackgroundColor(Some(&UIColor::systemBackgroundColor()));
3480        bar.setStandardAppearance(&appearance);
3481        bar.setCompactAppearance(Some(&appearance));
3482        // From iOS 26 UIKit draws the large title inside the scroll view, behind the bar, so an
3483        // opaque bar at the scroll edge paints over it and the list's top shows an empty band.
3484        // A transparent scroll-edge bar is the system's own look there.
3485        let edge = if os_at_least(26) {
3486            let edge = UINavigationBarAppearance::new(mtm);
3487            edge.configureWithTransparentBackground();
3488            edge
3489        } else {
3490            appearance.clone()
3491        };
3492        bar.setScrollEdgeAppearance(Some(&edge));
3493        bar.setCompactScrollEdgeAppearance(Some(&edge));
3494        unsafe { bar.setTranslucent(false) };
3495    }
3496
3497    /// The window's own bar, built or refreshed: a `UINavigationBar` across the top of the
3498    /// window, carrying the items exactly as a page's own bar carries them — as optional
3499    /// groups, so a phone that cannot fit twelve commands folds the trailing ones into the
3500    /// bar's overflow menu instead of clipping them. One iOS presentation for the window
3501    /// toolbar, whether the window's content brought a navigation host or not.
3502    ///
3503    /// The day root gives up the strip: `DayHolderView`'s layout pass measures the bar and
3504    /// re-pins the root below it, so the content the bar acts on is never underneath it.
3505    fn dock_window_toolbar(root: usize, root_view: &UIView) {
3506        let Some(mtm) = MainThreadMarker::new() else {
3507            return;
3508        };
3509        let Some(holder) = root_view.superview() else {
3510            return;
3511        };
3512        let items = WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).map(|w| w.items.clone()));
3513        let Some(items) = items else {
3514            return;
3515        };
3516        let controls = bar_controls(&items);
3517        let existing =
3518            WINDOW_TOOLBARS.with(|t| t.borrow().get(&root).and_then(|w| w.docked.clone()));
3519        let bar = existing.unwrap_or_else(|| {
3520            let bar = UINavigationBar::initWithFrame(UINavigationBar::alloc(mtm), CGRect::ZERO);
3521            configure_navigation_bar(&bar, mtm);
3522            let item = UINavigationItem::new(mtm);
3523            unsafe {
3524                bar.setItems(Some(&objc2_foundation::NSArray::from_retained_slice(&[
3525                    item,
3526                ])));
3527            };
3528            holder.addSubview(&bar);
3529            bar
3530        });
3531        // `topItem` is the one pushed above; a bar with no item would drop the groups. The
3532        // placements land as on a page's bar (docs/toolbars.md): leading items at the left,
3533        // a principal one as the title, `Primary` in a fixed group a narrow bar never folds,
3534        // the rest optional groups the overflow eats from the trailing end (plain items on
3535        // iOS 15). The item keeps the targets (`NAV_ITEM_TARGETS`), as a page's does.
3536        if let Some(item) = unsafe { bar.topItem() } {
3537            apply_items_to(mtm, &item, root, &controls);
3538        }
3539        WINDOW_TOOLBARS.with(|t| {
3540            if let Some(w) = t.borrow_mut().get_mut(&root) {
3541                w.docked = Some(bar);
3542            }
3543        });
3544        // The re-pin is the holder's, so it stays one computation for the safe area, the
3545        // keyboard rail and this bar — and so the `WindowResized` the shrink causes is
3546        // reported through the same path a rotation takes.
3547        holder.setNeedsLayout();
3548        holder.layoutIfNeeded();
3549    }
3550
3551    /// Take the window's own bar away and give the strip back to the day root — when the app
3552    /// clears its toolbar, and when a navigation host appears in the window to carry it.
3553    fn undock_window_toolbar(root: usize, root_view: &UIView) {
3554        let bar =
3555            WINDOW_TOOLBARS.with(|t| t.borrow_mut().get_mut(&root).and_then(|w| w.docked.take()));
3556        let Some(bar) = bar else {
3557            return;
3558        };
3559        bar.removeFromSuperview();
3560        // Marked, not forced: this runs inside a navigation push as often as not, and the
3561        // re-pin emits `WindowResized` back into day-core. The next pass is soon enough.
3562        if let Some(holder) = root_view.superview() {
3563            holder.setNeedsLayout();
3564        }
3565    }
3566
3567    /// The bar this window docks at its top, if it has one.
3568    fn docked_window_toolbar(root_view: &UIView) -> Option<Retained<UINavigationBar>> {
3569        let key = ptr_of(root_view);
3570        WINDOW_TOOLBARS.with(|t| t.borrow().get(&key).and_then(|w| w.docked.clone()))
3571    }
3572
3573    /// Take a window's bar off every page under it, leaving each page's own bar actions.
3574    fn clear_window_toolbar(root_view: &UIView) {
3575        for nav in toolbar_navs_under(root_view) {
3576            if bar_placement(&nav) == BarPlacement::Nested {
3577                continue;
3578            }
3579            for vc in &unsafe { nav.viewControllers() } {
3580                unsafe { vc.setToolbarItems(None) };
3581            }
3582            unsafe { nav.setToolbarHidden_animated(true, false) };
3583        }
3584    }
3585
3586    // ── A page's own search field (docs/search.md, "Page search") ─────────────────────
3587    //
3588    // A navigation page that declares `.searchable(…)` contributes the reserved `day::search`
3589    // item to its own chrome, and Day merges a page's chrome into its window's bar only while
3590    // that page is the one showing. So the item in the window's model always belongs to the
3591    // page on top, and that page's `navigationItem` takes a `UISearchController`: Mail's search
3592    // bar, under the title in the navigation bar. A bar button cannot be a field, so the item
3593    // never rides the bar's buttons (`bar_controls`).
3594    //
3595    // One controller per page, made the first time the page shows its field and kept for as
3596    // long as the page lives: a model re-apply never rebuilds it, so typing keeps the caret and
3597    // the keyboard. A page that a push covers keeps its field too, text and all, the way Mail's
3598    // list does under an open message, and the swipe back shows it in place. It comes off only
3599    // when the page on top stops offering it (`Search::available`, or the contribution leaving
3600    // with the page's scope), and with the page itself.
3601
3602    struct PageSearchIvars {
3603        /// The item's dispatch id: the slot Day keeps for `day::search` on this window.
3604        action: Cell<u64>,
3605        /// Suppresses the echo while Day writes the field's text into it.
3606        suppress: Cell<bool>,
3607        /// The text last reported, so activation and a submit do not report it twice.
3608        last: RefCell<String>,
3609    }
3610
3611    define_class!(
3612        #[unsafe(super(NSObject))]
3613        #[thread_kind = MainThreadOnly]
3614        #[name = "DayPageSearch"]
3615        #[ivars = PageSearchIvars]
3616        struct DayPageSearch;
3617
3618        unsafe impl NSObjectProtocol for DayPageSearch {}
3619
3620        unsafe impl UISearchResultsUpdating for DayPageSearch {
3621            #[unsafe(method(updateSearchResultsForSearchController:))]
3622            fn update(&self, sc: &objc2_ui_kit::UISearchController) {
3623                day_spec::ffi_guard::contain((), || {
3624                    if self.ivars().suppress.get() {
3625                        return;
3626                    }
3627                    let text = unsafe { sc.searchBar().text() }.map_or_default(|t| t.to_string());
3628                    self.report_text(text);
3629                });
3630            }
3631        }
3632
3633        unsafe impl UIBarPositioningDelegate for DayPageSearch {}
3634
3635        unsafe impl UISearchBarDelegate for DayPageSearch {
3636            /// The Search key: the text first if it has not gone out yet, then the submission
3637            /// (docs/search.md). The keyboard goes, as in Mail, so the results are not under it.
3638            #[unsafe(method(searchBarSearchButtonClicked:))]
3639            fn search_clicked(&self, bar: &objc2_ui_kit::UISearchBar) {
3640                day_spec::ffi_guard::contain((), || {
3641                    let text = unsafe { bar.text() }.map_or_default(|t| t.to_string());
3642                    self.report_text(text.clone());
3643                    self.send(day_spec::ToolbarValue::Submit(text));
3644                    let _ = bar.resignFirstResponder();
3645                });
3646            }
3647
3648            /// Cancel clears the field. UISearchController reports the empty text through the
3649            /// updater as well; whichever arrives first goes out, the other is the same text.
3650            #[unsafe(method(searchBarCancelButtonClicked:))]
3651            fn cancel_clicked(&self, _bar: &objc2_ui_kit::UISearchBar) {
3652                day_spec::ffi_guard::contain((), || self.report_text(String::new()));
3653            }
3654        }
3655    );
3656
3657    impl DayPageSearch {
3658        fn new(mtm: MainThreadMarker, action: u64, text: &str) -> Retained<Self> {
3659            let this = Self::alloc(mtm).set_ivars(PageSearchIvars {
3660                action: Cell::new(action),
3661                suppress: Cell::new(false),
3662                last: RefCell::new(text.to_string()),
3663            });
3664            unsafe { msg_send![super(this), init] }
3665        }
3666
3667        /// Send `text` as the field's new value, unless it is the value already sent.
3668        fn report_text(&self, text: String) {
3669            if *self.ivars().last.borrow() == text {
3670                return;
3671            }
3672            (*self.ivars().last.borrow_mut()).clone_from(&text);
3673            self.send(day_spec::ToolbarValue::Text(text));
3674        }
3675
3676        /// Through the item's action, the rail every toolbar value takes.
3677        fn send(&self, value: day_spec::ToolbarValue) {
3678            let action = self.ivars().action.get();
3679            if action != 0 {
3680                emit(WINDOW_NODE, Event::ToolbarChanged { action, value });
3681            }
3682        }
3683
3684        /// Show `text` without reporting it back: the app's own write (`ToolbarPatch::Text`).
3685        fn show_text(&self, sc: &objc2_ui_kit::UISearchController, text: &str) {
3686            *self.ivars().last.borrow_mut() = text.to_string();
3687            let bar = unsafe { sc.searchBar() };
3688            if unsafe { bar.text() }.is_some_and(|t| t.to_string() == text) {
3689                return;
3690            }
3691            self.ivars().suppress.set(true);
3692            unsafe { bar.setText(Some(&NSString::from_str(text))) };
3693            self.ivars().suppress.set(false);
3694        }
3695    }
3696
3697    /// One page's field: the controller on its navigation item and the object answering it.
3698    struct PageSearch {
3699        /// The window root (`WINDOW_TOOLBARS` key) whose bar carried the item.
3700        root: usize,
3701        vc: Retained<UIViewController>,
3702        sc: Retained<objc2_ui_kit::UISearchController>,
3703        handler: Retained<DayPageSearch>,
3704    }
3705
3706    thread_local! {
3707        /// Keyed by the page's view controller (`vc_key`). Retained here because the search
3708        /// controller does not own its updater or its bar's delegate.
3709        static PAGE_SEARCH: RefCell<HashMap<usize, PageSearch>> = RefCell::new(HashMap::new());
3710    }
3711
3712    /// The window's `day::search` item, if its bar has one.
3713    fn page_search_item(root: usize) -> Option<day_spec::ToolbarItem> {
3714        WINDOW_TOOLBARS.with(|t| {
3715            t.borrow().get(&root).and_then(|w| {
3716                w.items
3717                    .iter()
3718                    .find(|i| {
3719                        i.id == day_spec::SEARCH_ITEM_ID
3720                            && matches!(i.kind, day_spec::ToolbarItemKind::Search { .. })
3721                    })
3722                    .cloned()
3723            })
3724        })
3725    }
3726
3727    /// The page a page item of `column` belongs on right now: the top of the stack that carries
3728    /// the window's bar (the same choice `reapply_window_toolbar` makes for the buttons), as Day
3729    /// has asked for it — a push still queued or animating already counts, since the item
3730    /// arrives in the same turn as its page.
3731    fn page_search_target(
3732        root_view: &UIView,
3733        column: day_spec::ToolbarColumn,
3734    ) -> Option<Retained<UIViewController>> {
3735        // The top of `nav` as Day sees it, through its host's queue where it has one.
3736        let top_of = |nav: &objc2_ui_kit::UINavigationController| {
3737            let host = NAV_STATE.with(|m| {
3738                m.borrow()
3739                    .iter()
3740                    .find(|(_, s)| same_nav(&s.active_nav(), nav))
3741                    .map(|(k, s)| (*k, s.active_nav()))
3742            });
3743            match host {
3744                Some((host, active)) => current_top(host, &active),
3745                None => top_page(nav),
3746            }
3747        };
3748        if let Some(tabbar) = tabs_host_under(root_view) {
3749            let shown = unsafe { tabbar.selectedViewController() }?;
3750            let inner = shown
3751                .downcast_ref::<objc2_ui_kit::UINavigationController>()
3752                .map(objc2::Message::retain)
3753                .or_else(|| {
3754                    unsafe { shown.childViewControllers() }
3755                        .iter()
3756                        .find_map(|c| c.downcast::<objc2_ui_kit::UINavigationController>().ok())
3757                })?;
3758            return top_of(&inner);
3759        }
3760        // Each host's stack that is showing pages: the merged one while collapsed, otherwise the
3761        // column the item was declared in.
3762        let navs: Vec<Retained<objc2_ui_kit::UINavigationController>> = NAV_STATE.with(|m| {
3763            m.borrow()
3764                .values()
3765                .filter(|s| {
3766                    let view = match &s.split {
3767                        Some(parts) => parts.split_vc.view(),
3768                        None => s.nav.view(),
3769                    };
3770                    view.is_some_and(|v| unsafe { v.isDescendantOfView(root_view) })
3771                })
3772                .map(|s| {
3773                    let nav: Retained<DayNavController> = match &s.split {
3774                        Some(parts) if !s.is_collapsed() => match column {
3775                            day_spec::ToolbarColumn::Sidebar => parts.primary_nav.clone(),
3776                            day_spec::ToolbarColumn::List => parts
3777                                .supplementary_nav
3778                                .clone()
3779                                .unwrap_or_else(|| s.nav.clone()),
3780                            _ => s.nav.clone(),
3781                        },
3782                        _ => s.active_nav(),
3783                    };
3784                    Retained::into_super(nav)
3785                })
3786                .collect()
3787        });
3788        navs.into_iter()
3789            .find(|nav| bar_placement(nav) != BarPlacement::Nested)
3790            .and_then(|nav| top_of(&nav))
3791    }
3792
3793    /// Take a page's field off its navigation item, if it is still the one there.
3794    fn detach_page_search(entry: &PageSearch) {
3795        unsafe {
3796            if entry.sc.isActive() {
3797                entry.sc.setActive(false);
3798            }
3799            let item = entry.vc.navigationItem();
3800            if item
3801                .searchController()
3802                .is_some_and(|sc| std::ptr::eq(&raw const *sc, &raw const *entry.sc))
3803            {
3804                item.setSearchController(None);
3805            }
3806        }
3807    }
3808
3809    /// Put the window's `day::search` item on the page it belongs to, and take it off the page
3810    /// on top when that page stopped offering one. Run after every change to the bar's model,
3811    /// after a page shows, and before a value patch, so the field is in place to take it.
3812    /// Answers the page's controller and its handler, when the item is on one.
3813    fn sync_page_search(
3814        root: usize,
3815        root_view: &UIView,
3816    ) -> Option<(
3817        Retained<objc2_ui_kit::UISearchController>,
3818        Retained<DayPageSearch>,
3819    )> {
3820        let mtm = MainThreadMarker::new()?;
3821        let item = page_search_item(root);
3822        let column = item
3823            .as_ref()
3824            .map_or(day_spec::ToolbarColumn::Detail, |i| i.column);
3825        let target = page_search_target(root_view, column);
3826        if item.is_none() {
3827            // Only the page on top loses its field: a covered page keeps its own for when it
3828            // shows again, and a page that left the stack takes its field with it.
3829            let gone = target.and_then(|vc| {
3830                PAGE_SEARCH.with(|m| {
3831                    let mut m = m.borrow_mut();
3832                    m.get(&vc_key(&vc))
3833                        .is_some_and(|e| e.root == root)
3834                        .then(|| m.remove(&vc_key(&vc)))
3835                        .flatten()
3836                })
3837            });
3838            if let Some(entry) = gone {
3839                detach_page_search(&entry);
3840            }
3841            return None;
3842        }
3843        let (item, vc) = (item?, target?);
3844        let day_spec::ToolbarItemKind::Search {
3845            text, placeholder, ..
3846        } = &item.kind
3847        else {
3848            return None;
3849        };
3850        let nav_item = unsafe { vc.navigationItem() };
3851        let existing = PAGE_SEARCH.with(|m| {
3852            m.borrow()
3853                .get(&vc_key(&vc))
3854                .map(|e| (e.sc.clone(), e.handler.clone()))
3855        });
3856        let (sc, handler) = if let Some(found) = existing {
3857            found
3858        } else {
3859            // A sidebar root carries its navigation surface's own search; that one stays.
3860            if unsafe { nav_item.searchController() }.is_some() {
3861                return None;
3862            }
3863            let handler = DayPageSearch::new(mtm, item.action, text);
3864            let sc = unsafe {
3865                objc2_ui_kit::UISearchController::initWithSearchResultsController(
3866                    objc2_ui_kit::UISearchController::alloc(mtm),
3867                    None,
3868                )
3869            };
3870            unsafe {
3871                sc.setSearchResultsUpdater(Some(ProtocolObject::from_ref(&*handler)));
3872                // The results replace the page's own content, so nothing is dimmed.
3873                sc.setObscuresBackgroundDuringPresentation(false);
3874                let bar = sc.searchBar();
3875                bar.setDelegate(Some(ProtocolObject::from_ref(&*handler)));
3876                // Already UISearchBar's default; said here because Return means "search".
3877                if let Some(field) = search_text_field(&bar) {
3878                    send_input_trait(&field, sel!(setReturnKeyType:), UIReturnKeyType::Search.0);
3879                }
3880                if !text.is_empty() {
3881                    bar.setText(Some(&NSString::from_str(text)));
3882                }
3883                // Mail's: the bar slides away with the content and comes back on a pull.
3884                // Pinned for the turn it arrives in, though: a field that joins a page
3885                // already on screen (a feed that had to load first) would otherwise start
3886                // collapsed, behind a pull nobody knows to make. Showing first and turning
3887                // the hiding on once it has drawn is UIKit's own recipe for that.
3888                nav_item.setHidesSearchBarWhenScrolling(false);
3889                hide_page_search_when_drawn(vc.clone(), 0);
3890                // Under the title, at every width: an iPad would otherwise fold it into the
3891                // bar's trailing end, away from the page title it searches under.
3892                if os_at_least(16) {
3893                    nav_item.setPreferredSearchBarPlacement(
3894                        objc2_ui_kit::UINavigationItemSearchBarPlacement::Stacked,
3895                    );
3896                }
3897                // A push while the field is active must cover it, not run under it.
3898                vc.setDefinesPresentationContext(true);
3899            }
3900            PAGE_SEARCH.with(|m| {
3901                m.borrow_mut().insert(
3902                    vc_key(&vc),
3903                    PageSearch {
3904                        root,
3905                        vc: vc.clone(),
3906                        sc: sc.clone(),
3907                        handler: handler.clone(),
3908                    },
3909                )
3910            });
3911            (sc, handler)
3912        };
3913        handler.ivars().action.set(item.action);
3914        unsafe {
3915            if nav_item.searchController().is_none() {
3916                nav_item.setSearchController(Some(&sc));
3917            }
3918            let bar = sc.searchBar();
3919            let prompt = if placeholder.is_empty() {
3920                &item.label
3921            } else {
3922                placeholder
3923            };
3924            if bar.placeholder().is_none_or(|p| p.to_string() != *prompt) {
3925                bar.setPlaceholder(Some(&NSString::from_str(prompt)));
3926            }
3927            bar.setUserInteractionEnabled(item.enabled);
3928        }
3929        Some((sc, handler))
3930    }
3931
3932    /// Turn on a new page field's hide-on-scroll once its bar has drawn it open: before then
3933    /// the flag starts it collapsed. A page still on its way in (a queued push) is waited for,
3934    /// a turn at a time and boundedly, and one that never arrives keeps its field pinned.
3935    fn hide_page_search_when_drawn(vc: Retained<UIViewController>, attempt: u32) {
3936        let Some(mtm) = MainThreadMarker::new() else {
3937            return;
3938        };
3939        let vc = dispatch2::MainThreadBound::new(vc, mtm);
3940        let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
3941            .unwrap_or(dispatch2::DispatchTime::NOW);
3942        let _ = dispatch2::DispatchQueue::main().after(when, move || {
3943            day_spec::ffi_guard::contain((), || {
3944                let Some(mtm) = MainThreadMarker::new() else {
3945                    return;
3946                };
3947                let vc = vc.get(mtm);
3948                let nav = unsafe { vc.navigationController() };
3949                let shown = vc.viewIfLoaded().is_some_and(|v| v.window().is_some());
3950                match nav.and_then(|n| n.viewIfLoaded()) {
3951                    Some(nav_view) if shown => {
3952                        // The open bar is laid out first; the flag only governs what scrolling
3953                        // does from there.
3954                        nav_view.layoutIfNeeded();
3955                        unsafe { vc.navigationItem().setHidesSearchBarWhenScrolling(true) };
3956                    }
3957                    _ if attempt < 100 => hide_page_search_when_drawn(vc.retain(), attempt + 1),
3958                    _ => {}
3959                }
3960            });
3961        });
3962    }
3963
3964    /// `UISearchBar.searchTextField` (iOS 13), typed as the `UITextField` it is.
3965    fn search_text_field(bar: &objc2_ui_kit::UISearchBar) -> Option<Retained<UITextField>> {
3966        unsafe { msg_send![bar, searchTextField] }
3967    }
3968
3969    /// [`sync_page_search`] for the window `nav` is in.
3970    fn sync_page_search_near(nav: &objc2_ui_kit::UINavigationController) {
3971        let Some(nav_view) = nav.view() else {
3972            return;
3973        };
3974        let found = WINDOW_TOOLBARS.with(|t| {
3975            t.borrow()
3976                .iter()
3977                .find(|(_, w)| unsafe { nav_view.isDescendantOfView(&w.root) })
3978                .map(|(root, w)| (*root, w.root.clone()))
3979        });
3980        if let Some((root, root_view)) = found {
3981            sync_page_search(root, &root_view);
3982        }
3983    }
3984
3985    /// A search item's value patch on a phone (docs/toolbars.md): the field on the page showing
3986    /// takes it without a rebuild, and without reporting it back.
3987    fn patch_page_search(root: usize, root_view: &UIView, patch: &day_spec::ToolbarPatch) {
3988        let Some((sc, handler)) = sync_page_search(root, root_view) else {
3989            return;
3990        };
3991        match patch {
3992            day_spec::ToolbarPatch::Text { text, .. } => handler.show_text(&sc, text),
3993            day_spec::ToolbarPatch::Focus { .. } => unsafe {
3994                sc.setActive(true);
3995                sc.searchBar().becomeFirstResponder();
3996            },
3997            day_spec::ToolbarPatch::Placeholder { text, .. } => unsafe {
3998                sc.searchBar()
3999                    .setPlaceholder(Some(&NSString::from_str(text)));
4000            },
4001            // UIKit's completion surface is not wired yet (as for a surface's own search).
4002            _ => {}
4003        }
4004    }
4005
4006    struct FrameSource {
4007        link: Retained<CADisplayLink>,
4008        target: Retained<DayFrameTarget>,
4009    }
4010    impl Drop for FrameSource {
4011        fn drop(&mut self) {
4012            unsafe { self.link.invalidate() };
4013        }
4014    }
4015    struct FrameState {
4016        key: usize,
4017        token: Cell<u64>,
4018    }
4019    define_class!(
4020        #[unsafe(super(NSObject))]
4021        #[thread_kind = MainThreadOnly]
4022        #[name = "DayUIKitFrameTarget"]
4023        #[ivars = FrameState]
4024        struct DayFrameTarget;
4025        unsafe impl NSObjectProtocol for DayFrameTarget {}
4026        impl DayFrameTarget {
4027            #[unsafe(method(step:))]
4028            fn step(&self, link: &CADisplayLink) {
4029                day_spec::ffi_guard::contain((), || {
4030                    unsafe { link.setPaused(true) };
4031                    let token = self.ivars().token.replace(0);
4032                    day_core::frame::native::deliver(token, day_spec::FrameStamp {
4033                        timestamp: unsafe { link.timestamp() },
4034                        target_timestamp: Some(unsafe { link.targetTimestamp() }),
4035                    });
4036                    if self.ivars().token.get() == 0 {
4037                        FRAMES.with(|s| s.borrow_mut().remove(&self.ivars().key));
4038                    }
4039                });
4040            }
4041        }
4042    );
4043
4044    // -----------------------------------------------------------------------
4045    // DayTextLink — a text view's link delegate (docs/text-runs.md)
4046    // -----------------------------------------------------------------------
4047
4048    define_class!(
4049        #[unsafe(super(NSObject))]
4050        #[thread_kind = MainThreadOnly]
4051        #[name = "DayUIKitTextLink"]
4052        #[ivars = NodeId]
4053        struct DayTextLink;
4054
4055        unsafe impl NSObjectProtocol for DayTextLink {}
4056
4057        // UITextViewDelegate refines UIScrollViewDelegate; both are declared, and the scroll
4058        // half stays empty — a non-scrolling text view never calls it.
4059        unsafe impl UIScrollViewDelegate for DayTextLink {}
4060
4061        unsafe impl UITextViewDelegate for DayTextLink {
4062            /// Answer NO so UIKit does not open the URL itself: the target goes to day-core,
4063            /// and the label's `.on_link()` decides (its default opens it, which is the same
4064            /// destination by the route Day controls).
4065            #[unsafe(method(textView:shouldInteractWithURL:inRange:interaction:))]
4066            fn should_interact(
4067                &self,
4068                _tv: &UITextView,
4069                url: &objc2_foundation::NSURL,
4070                _range: objc2_foundation::NSRange,
4071                // `UITextItemInteraction`, taken as the NSInteger it wraps: objc2 deprecates
4072                // the newtype in favor of iOS 17 text-item methods that do not exist on the
4073                // versions Day targets. Unused either way.
4074                _interaction: isize,
4075            ) -> bool {
4076                day_spec::ffi_guard::contain((), || {
4077                    if let Some(s) = unsafe { url.absoluteString() } {
4078                        let s = s.to_string();
4079                        // Already reported by the tap recognizer, a beat earlier.
4080                        let echo = LAST_LINK_TAP.with(|l| {
4081                            l.borrow_mut().take_if(|(u, at)| {
4082                                *u == s && at.elapsed() < std::time::Duration::from_secs(2)
4083                            })
4084                        });
4085                        if echo.is_none() {
4086                            emit(*self.ivars(), Event::LinkActivated(s));
4087                        }
4088                    }
4089                });
4090                false
4091            }
4092
4093            /// The reader's selection moved: a label that asked for reports
4094            /// (`LabelProps::reports_selection`) hears it as `Event::TextSelected`.
4095            #[unsafe(method(textViewDidChangeSelection:))]
4096            fn selection_changed(&self, tv: &UITextView) {
4097                day_spec::ffi_guard::contain((), || report_selection(tv));
4098            }
4099        }
4100
4101        // The tap recognizer shares the touch with the text view's own recognizers.
4102        unsafe impl UIGestureRecognizerDelegate for DayTextLink {
4103            #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))]
4104            fn simultaneous(&self, _a: &UIGestureRecognizer, _b: &UIGestureRecognizer) -> bool {
4105                true
4106            }
4107        }
4108
4109        impl DayTextLink {
4110            /// A tap on a link, reported on touch-up. A selectable `UITextView` calls its
4111            /// delegate for a link only once its selection gestures (double tap, the long-press
4112            /// preview) have given up, which reads as a lag before every in-app link; the
4113            /// character under the finger answers at once. The delegate path stays for what only
4114            /// it sees (VoiceOver activation, the preview's open).
4115            #[unsafe(method(tapped:))]
4116            fn tapped(&self, recognizer: &UIGestureRecognizer) {
4117                day_spec::ffi_guard::contain((), || {
4118                    let Some(view) = (unsafe { recognizer.view() }) else {
4119                        return;
4120                    };
4121                    let point = unsafe { recognizer.locationInView(Some(&view)) };
4122                    let Some(url) = link_at(&view, point) else {
4123                        return;
4124                    };
4125                    LAST_LINK_TAP.with(|l| {
4126                        *l.borrow_mut() = Some((url.clone(), std::time::Instant::now()));
4127                    });
4128                    emit(*self.ivars(), Event::LinkActivated(url));
4129                });
4130            }
4131        }
4132    );
4133
4134    thread_local! {
4135        /// A stock cell's (vertical margin, one-line height), measured once (`native_row`).
4136        static NATIVE_ROW: std::cell::OnceCell<(f64, f64)> = const { std::cell::OnceCell::new() };
4137    }
4138
4139    /// A stock `UITableViewCell` with one line of its default content configuration: its top
4140    /// margin and the height UIKit fits it to, which is the row a native list shows.
4141    fn native_row() -> (f64, f64) {
4142        let Some(mtm) = MainThreadMarker::new() else {
4143            return (11.0, 44.0);
4144        };
4145        unsafe {
4146            let cell = objc2_ui_kit::UITableViewCell::initWithStyle_reuseIdentifier(
4147                objc2_ui_kit::UITableViewCell::alloc(mtm),
4148                objc2_ui_kit::UITableViewCellStyle::Default,
4149                None,
4150            );
4151            let config: Retained<AnyObject> = msg_send![&*cell, defaultContentConfiguration];
4152            let text = NSString::from_str("Hg");
4153            let _: () = msg_send![&*config, setText: &*text];
4154            let _: () = msg_send![&*cell, setContentConfiguration: &*config];
4155            let margins: objc2_ui_kit::NSDirectionalEdgeInsets =
4156                msg_send![&*config, directionalLayoutMargins];
4157            let size = cell
4158                .systemLayoutSizeFittingSize_withHorizontalFittingPriority_verticalFittingPriority(
4159                    CGSize::new(375.0, 0.0),
4160                    1000.0,
4161                    50.0,
4162                );
4163            (margins.top, size.height)
4164        }
4165    }
4166
4167    /// The link target of the character at `point` in text view `view`, if it carries one.
4168    fn link_at(view: &UIView, point: objc2_core_foundation::CGPoint) -> Option<String> {
4169        unsafe {
4170            let range: Option<Retained<AnyObject>> = msg_send![view, characterRangeAtPoint: point];
4171            let range = range?;
4172            let start: Retained<AnyObject> = msg_send![&*range, start];
4173            let begin: Retained<AnyObject> = msg_send![view, beginningOfDocument];
4174            let index: isize = msg_send![view, offsetFromPosition: &*begin, toPosition: &*start];
4175            let text: Option<Retained<objc2_foundation::NSAttributedString>> =
4176                msg_send![view, attributedText];
4177            let text = text?;
4178            if index < 0 || index as usize >= text.length() {
4179                return None;
4180            }
4181            let value = text.attribute_atIndex_effectiveRange(
4182                objc2_ui_kit::NSLinkAttributeName,
4183                index as usize,
4184                std::ptr::null_mut(),
4185            )?;
4186            if let Some(url) = value.downcast_ref::<objc2_foundation::NSURL>() {
4187                return url.absoluteString().map(|s| s.to_string());
4188            }
4189            value
4190                .downcast_ref::<NSString>()
4191                .map(std::string::ToString::to_string)
4192        }
4193    }
4194
4195    impl DayTextLink {
4196        /// Make `tv` report to `node` through this delegate, and keep the delegate alive with
4197        /// it: its link activations and its selection changes (`report_selection` decides
4198        /// whether the label wants those). `taps` adds the immediate link-tap recognizer, which
4199        /// only a text view that carries links needs. Idempotent: a view that already has one
4200        /// keeps it.
4201        fn attach(tv: &UITextView, node: NodeId, taps: bool, mtm: MainThreadMarker) {
4202            if TEXT_LINKS.with(|t| t.contains(ptr_of_view(tv))) {
4203                return;
4204            }
4205            let this = Self::alloc(mtm).set_ivars(node);
4206            let delegate: Retained<Self> = unsafe { msg_send![super(this), init] };
4207            unsafe { tv.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
4208            if !taps {
4209                TEXT_LINKS.with(|t| t.insert(ptr_of_view(tv), delegate));
4210                return;
4211            }
4212            let tap = unsafe {
4213                UITapGestureRecognizer::initWithTarget_action(
4214                    UITapGestureRecognizer::alloc(mtm),
4215                    Some(&delegate),
4216                    Some(sel!(tapped:)),
4217                )
4218            };
4219            unsafe {
4220                // The text view keeps the touch: its long-press preview and VoiceOver still work.
4221                tap.setCancelsTouchesInView(false);
4222                tap.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
4223                tv.addGestureRecognizer(&tap);
4224            }
4225            TEXT_LINKS.with(|t| t.insert(ptr_of_view(tv), delegate));
4226        }
4227    }
4228
4229    /// The side-table key for a view: its address, the same key `release` sweeps.
4230    fn ptr_of_view(v: &UITextView) -> usize {
4231        let v: &UIView = v.as_ref();
4232        std::ptr::from_ref::<UIView>(v) as usize
4233    }
4234
4235    // -----------------------------------------------------------------------
4236    // Label paragraph attributes (docs/text.md "Line limit", "Truncation", "Letter spacing",
4237    // "Line height", "Selection reports"; docs/localization.md "Direction of a subtree")
4238    // -----------------------------------------------------------------------
4239
4240    /// What a label keeps beside its backing view: the attributes `LabelPatch::Paragraph`
4241    /// replaces, the realize-only ones the paragraph is applied with, and the selection-report
4242    /// state. Moved to the replacement by the `.selectable()` swap (`set_selectable`), so the
4243    /// line limit, spacing and reports follow the label onto its `UITextView`.
4244    #[derive(Clone)]
4245    struct LabelLook {
4246        node: NodeId,
4247        wraps: bool,
4248        align: day_spec::props::TextAlign,
4249        para: day_spec::props::LabelParagraph,
4250        /// The direction `set_layout_direction` gave this label; `None` follows the app.
4251        rtl: Option<bool>,
4252        reports: bool,
4253        /// The last selection reported, in bytes; `start == end` is "nothing selected".
4254        selection: (usize, usize),
4255        /// Kern, a fixed line height or a base direction is on the attributed text, so a
4256        /// return to the natural values has to take them off again.
4257        styled: bool,
4258        /// The backing view, for the Dynamic Type refresh (`refresh_label_paragraphs`).
4259        view: objc2::rc::Weak<UIView>,
4260        /// The label's own color (`label_ink`), which a `LabelPatch::Runs` rebuild lays under
4261        /// the runs as a plain label shows it.
4262        color: Option<day_spec::Ink>,
4263    }
4264
4265    /// The color a label's text takes where no run says otherwise: its explicit color, else
4266    /// its role's (`None` is the label color).
4267    fn label_ink(p: &LabelProps) -> Option<day_spec::Ink> {
4268        p.color.or(match p.role {
4269            day_spec::props::TextRole::Secondary => {
4270                Some(day_spec::Ink::system(day_spec::SystemColor::SecondaryText))
4271            }
4272            day_spec::props::TextRole::Primary => None,
4273        })
4274    }
4275
4276    /// Record a freshly realized label's look and apply it: the line limit, truncation,
4277    /// spacing, line height and alignment all go through `apply_paragraph`, at realize and on
4278    /// every patch, so there is one place that decides them.
4279    fn track_label(view: &Handle, p: &LabelProps, node: NodeId) {
4280        let look = LabelLook {
4281            node,
4282            wraps: p.wraps,
4283            align: p.align,
4284            para: p.paragraph(),
4285            rtl: None,
4286            reports: p.reports_selection,
4287            selection: (0, 0),
4288            styled: false,
4289            view: objc2::rc::Weak::from_retained(view),
4290            color: label_ink(p),
4291        };
4292        LABEL_LOOKS.with(|t| t.insert(ptr_of(view), look));
4293        apply_paragraph(view);
4294    }
4295
4296    /// The color a label keeps under its runs (`LabelLook::color`).
4297    fn own_ink(view: &UIView) -> Option<day_spec::Ink> {
4298        LABEL_LOOKS
4299            .with(|t| t.with(ptr_of(view), |look| look.color))
4300            .flatten()
4301    }
4302
4303    /// Record a label's new color, for the next `LabelPatch::Runs` rebuild.
4304    fn set_own_ink(view: &UIView, color: Option<day_spec::Ink>) {
4305        LABEL_LOOKS.with(|t| t.with(ptr_of(view), |look| look.color = color));
4306    }
4307
4308    /// `Truncation` as the line-break mode that ends a limited label's last line.
4309    fn truncating(t: day_spec::props::Truncation) -> objc2_ui_kit::NSLineBreakMode {
4310        use day_spec::props::Truncation;
4311        use objc2_ui_kit::NSLineBreakMode;
4312        match t {
4313            Truncation::Tail => NSLineBreakMode::ByTruncatingTail,
4314            Truncation::Head => NSLineBreakMode::ByTruncatingHead,
4315            Truncation::Middle => NSLineBreakMode::ByTruncatingMiddle,
4316        }
4317    }
4318
4319    /// `TextAlign` as `NSTextAlignment`. Leading is `.natural` while the label follows the app,
4320    /// so an RTL locale aligns right without the app asking (docs/localization.md); under a
4321    /// subtree direction (`rtl`) both edges resolve against that direction, because a
4322    /// `UILabel` resolves `.natural` from the app's language, not from its own
4323    /// `semanticContentAttribute`.
4324    fn ns_alignment(
4325        align: day_spec::props::TextAlign,
4326        rtl: Option<bool>,
4327    ) -> objc2_ui_kit::NSTextAlignment {
4328        use day_spec::props::TextAlign;
4329        use objc2_ui_kit::NSTextAlignment;
4330        let edge = |right: bool| {
4331            if right {
4332                NSTextAlignment::Right
4333            } else {
4334                NSTextAlignment::Left
4335            }
4336        };
4337        match (align, rtl) {
4338            (TextAlign::Leading, None) => NSTextAlignment::Natural,
4339            (TextAlign::Leading, Some(rtl)) => edge(rtl),
4340            (TextAlign::Trailing, rtl) => edge(!rtl.unwrap_or_else(day_core::is_rtl)),
4341            (TextAlign::Center, _) => NSTextAlignment::Center,
4342            (TextAlign::Justified, _) => NSTextAlignment::Justified,
4343        }
4344    }
4345
4346    /// `text` with the look's paragraph attributes over its whole range: `NSKern` for letter
4347    /// spacing (ems times the label's point size), a paragraph style with the alignment, the
4348    /// line-break mode, a fixed line height (`minimumLineHeight` = `maximumLineHeight` =
4349    /// multiple times the point size, not `lineHeightMultiple`, which multiplies the natural
4350    /// height) and the base direction, and `NSBaselineOffset` to center the glyphs in that
4351    /// line box. Each attribute is set or removed, so applying it again is idempotent.
4352    fn restyled(
4353        text: &objc2_foundation::NSAttributedString,
4354        font: &objc2_ui_kit::UIFont,
4355        look: &LabelLook,
4356        align: objc2_ui_kit::NSTextAlignment,
4357        breaks: objc2_ui_kit::NSLineBreakMode,
4358    ) -> Retained<objc2_foundation::NSAttributedString> {
4359        use objc2::AllocAnyThread as _;
4360        use objc2_foundation::{NSMutableAttributedString, NSNumber};
4361        use objc2_ui_kit::{
4362            NSBaselineOffsetAttributeName, NSKernAttributeName, NSMutableParagraphStyle,
4363            NSParagraphStyleAttributeName, NSWritingDirection,
4364        };
4365        let s = unsafe {
4366            NSMutableAttributedString::initWithAttributedString(
4367                NSMutableAttributedString::alloc(),
4368                text,
4369            )
4370        };
4371        let whole = NSRange::new(0, s.length());
4372        let points = unsafe { font.pointSize() };
4373        let style = NSMutableParagraphStyle::new();
4374        unsafe {
4375            match crate::label_text::kern(look.para.letter_spacing, points) {
4376                Some(k) => {
4377                    s.addAttribute_value_range(NSKernAttributeName, &NSNumber::new_f64(k), whole);
4378                }
4379                None => s.removeAttribute_range(NSKernAttributeName, whole),
4380            }
4381            style.setAlignment(align);
4382            style.setLineBreakMode(breaks);
4383            if let Some(rtl) = look.rtl {
4384                style.setBaseWritingDirection(if rtl {
4385                    NSWritingDirection::RightToLeft
4386                } else {
4387                    NSWritingDirection::LeftToRight
4388                });
4389            }
4390            match crate::label_text::line_height(look.para.line_height) {
4391                Some(multiple) => {
4392                    let line = multiple * points;
4393                    style.setMinimumLineHeight(line);
4394                    style.setMaximumLineHeight(line);
4395                    let raise = crate::label_text::baseline_offset(line, font.lineHeight());
4396                    s.addAttribute_value_range(
4397                        NSBaselineOffsetAttributeName,
4398                        &NSNumber::new_f64(raise),
4399                        whole,
4400                    );
4401                }
4402                None => s.removeAttribute_range(NSBaselineOffsetAttributeName, whole),
4403            }
4404            s.addAttribute_value_range(NSParagraphStyleAttributeName, &style, whole);
4405        }
4406        s.into_super()
4407    }
4408
4409    /// Apply a label's look to its backing view (docs/text.md): idempotent, run at realize,
4410    /// after every `LabelPatch`, after the `.selectable()` swap, on a direction change and when
4411    /// Dynamic Type resizes the fonts (letter spacing and line height are in multiples of the
4412    /// point size).
4413    ///
4414    /// A `UILabel` takes the limit as `numberOfLines` and the truncation as its
4415    /// `lineBreakMode`, which UIKit applies to the last visible line; `sizeThatFits:` honors
4416    /// both, so `measure` needs nothing more. It stays a plain-text label until a paragraph
4417    /// attribute needs the attributed string. A `UITextView` takes them on its text
4418    /// container (`maximumNumberOfLines`, `lineBreakMode`), and its paragraph style always
4419    /// wraps by word: `TextKit` reads a truncating paragraph mode as "one line per paragraph",
4420    /// which the attributed text copied from a truncating `UILabel` would otherwise carry.
4421    fn apply_paragraph(view: &UIView) {
4422        use objc2_ui_kit::NSLineBreakMode;
4423        let key = ptr_of(view);
4424        let Some(look) = LABEL_LOOKS.with(|t| t.get(key)) else {
4425            return;
4426        };
4427        let lines = if look.wraps {
4428            look.para.max_lines as usize
4429        } else {
4430            1
4431        };
4432        let align = ns_alignment(look.align, look.rtl);
4433        let styled = crate::label_text::kern(look.para.letter_spacing, 1.0).is_some()
4434            || crate::label_text::line_height(look.para.line_height).is_some()
4435            || look.rtl.is_some();
4436        if let Some(label) = view.downcast_ref::<UILabel>() {
4437            // Unlimited keeps UIKit's default tail mode: the label still wraps, and ends in an
4438            // ellipsis only if its frame cuts it short.
4439            let mode = if lines > 0 {
4440                truncating(look.para.truncation)
4441            } else {
4442                NSLineBreakMode::ByTruncatingTail
4443            };
4444            unsafe {
4445                label.setNumberOfLines(lines.cast_signed());
4446                if (styled || look.styled)
4447                    && let (Some(text), Some(font)) = (label.attributedText(), label.font())
4448                {
4449                    label.setAttributedText(Some(&restyled(&text, &font, &look, align, mode)));
4450                }
4451                // After the attributed text, which brings its own alignment; either setter
4452                // restyles the whole string, so only when the value moved.
4453                if label.textAlignment() != align {
4454                    label.setTextAlignment(align);
4455                }
4456                if label.lineBreakMode() != mode {
4457                    label.setLineBreakMode(mode);
4458                }
4459            }
4460        } else if let Some(tv) = view.downcast_ref::<UITextView>() {
4461            let mode = if lines > 0 {
4462                truncating(look.para.truncation)
4463            } else {
4464                NSLineBreakMode::ByWordWrapping
4465            };
4466            unsafe {
4467                let container = tv.textContainer();
4468                container.setMaximumNumberOfLines(lines);
4469                container.setLineBreakMode(mode);
4470                if let Some(font) = tv.font() {
4471                    let text = tv.attributedText();
4472                    let wrap = NSLineBreakMode::ByWordWrapping;
4473                    tv.setAttributedText(Some(&restyled(&text, &font, &look, align, wrap)));
4474                }
4475                if tv.textAlignment() != align {
4476                    tv.setTextAlignment(align);
4477                }
4478            }
4479        }
4480        LABEL_LOOKS.with(|t| t.with(key, |l| l.styled = styled));
4481    }
4482
4483    /// Take a `LabelPatch::Paragraph` into the label's look; the patch arm applies it.
4484    fn set_label_paragraph(view: &UIView, para: day_spec::props::LabelParagraph) {
4485        LABEL_LOOKS.with(|t| t.with(ptr_of(view), |l| l.para = para));
4486    }
4487
4488    /// Re-apply every spaced or fixed-height label's look after a Dynamic Type change: the
4489    /// fonts took the new size by themselves, the kern and line height are in points.
4490    fn refresh_label_paragraphs() {
4491        let mut views = Vec::new();
4492        LABEL_LOOKS.with(|t| {
4493            t.for_each(|_, look| {
4494                if look.styled
4495                    && let Some(view) = look.view.load()
4496                {
4497                    views.push(view);
4498                }
4499            });
4500        });
4501        for view in views {
4502            apply_paragraph(&view);
4503        }
4504    }
4505
4506    /// Report a reporting label's selection when it changed (`Event::TextSelected`, byte
4507    /// offsets into the text the label shows). Called by the text view's delegate and after a
4508    /// text patch, which discards the selection without telling the delegate.
4509    fn report_selection(tv: &UITextView) {
4510        let key = ptr_of_view(tv);
4511        let Some(look) = LABEL_LOOKS.with(|t| t.get(key)) else {
4512            return;
4513        };
4514        if !look.reports {
4515            return;
4516        }
4517        // `selectedRange` is what iOS 15 has; the SDK deprecates it for iOS 26's
4518        // `selectedRanges`, whose union it still is.
4519        let range: NSRange = unsafe { msg_send![tv, selectedRange] };
4520        let text = unsafe { tv.text() }.to_string();
4521        let (start, end) = crate::label_text::byte_range(&text, range.location, range.length);
4522        let (was_start, was_end) = look.selection;
4523        // Once per change; a caret moving inside an empty selection is no change.
4524        if (start, end) == look.selection || (start == end && was_start == was_end) {
4525            return;
4526        }
4527        LABEL_LOOKS.with(|t| t.with(key, |l| l.selection = (start, end)));
4528        emit(look.node, Event::TextSelected { start, end });
4529    }
4530
4531    /// A `UITextView` for a label's text on `TextKit` 1, the layout a `UILabel` matches: under
4532    /// `TextKit` 2 a fixed line height with `NSBaselineOffset` measures short by half the
4533    /// offset (36 points for a 40-point line of 20-point text, measured on iOS 18.6), so the
4534    /// label would change height when it became selectable. iOS 16 made `TextKit` 2 the default
4535    /// and added `textViewUsingTextLayoutManager:` to opt out; iOS 15's text views are
4536    /// `TextKit` 1 already.
4537    fn label_text_view(mtm: MainThreadMarker) -> Retained<UITextView> {
4538        // A class method: the class object answers for it (`AnyClass::responds_to` would
4539        // look among the instance methods).
4540        let class = <UITextView as objc2::ClassType>::class();
4541        let opts_out: bool =
4542            unsafe { msg_send![class, respondsToSelector: sel!(textViewUsingTextLayoutManager:)] };
4543        if opts_out {
4544            UITextView::textViewUsingTextLayoutManager(false, mtm)
4545        } else {
4546            UITextView::new(mtm)
4547        }
4548    }
4549
4550    /// A label backing that can activate links: a read-only, non-scrolling `UITextView` laid out
4551    /// to measure like the `UILabel` it stands in for (zero inset, no line-fragment padding).
4552    fn link_text_view(p: &LabelProps, id: NodeId, mtm: MainThreadMarker) -> Retained<UITextView> {
4553        let tv = label_text_view(mtm);
4554        let font = resolve_font(p.font);
4555        unsafe {
4556            tv.setFont(Some(&font));
4557            let _: () = msg_send![&*tv, setAdjustsFontForContentSizeCategory: true];
4558            if let Some(c) = p.color {
4559                tv.setTextColor(Some(&uiink(c)));
4560            }
4561            tv.setAttributedText(Some(&attributed_label(
4562                &p.text,
4563                &font,
4564                label_ink(p),
4565                &p.runs,
4566            )));
4567            tv.setEditable(false);
4568            tv.setSelectable(true); // required for link interaction, not for selection alone
4569            tv.setScrollEnabled(false);
4570            tv.setBackgroundColor(None);
4571            tv.setTextContainerInset(UIEdgeInsets {
4572                top: 0.0,
4573                left: 0.0,
4574                bottom: 0.0,
4575                right: 0.0,
4576            });
4577            let container: *mut AnyObject = msg_send![&*tv, textContainer];
4578            let _: () = msg_send![container, setLineFragmentPadding: 0.0f64];
4579        }
4580        DayTextLink::attach(&tv, id, true, mtm);
4581        tv
4582    }
4583
4584    // -----------------------------------------------------------------------
4585    // DayGesture — tap/pan recognizer target, node-id keyed (docs/shapes.md)
4586    // -----------------------------------------------------------------------
4587
4588    struct GestureIvars {
4589        node: NodeId,
4590        kind: day_spec::GestureKind,
4591        /// The recognizer this object is the target of: a single tap waits for a double tap
4592        /// on the same view through it (`requireGestureRecognizerToFail:`).
4593        recognizer: RefCell<Option<Retained<UIGestureRecognizer>>>,
4594    }
4595
4596    /// Whether `view` has a context menu (`set_context_menu*`): its long press is the menu's.
4597    fn has_context_menu(view: &UIView) -> bool {
4598        let key = ptr_of(view);
4599        CTX_MENUS.with(|t| t.contains(key)) || CTX_MENU_FNS.with(|t| t.borrow().contains_key(&key))
4600    }
4601
4602    /// Whether `ancestor` is a strict ancestor of `view`.
4603    fn is_strict_ancestor(ancestor: &UIView, view: &UIView) -> bool {
4604        !std::ptr::eq(ancestor, view) && unsafe { view.isDescendantOfView(ancestor) }
4605    }
4606
4607    define_class!(
4608        #[unsafe(super(NSObject))]
4609        #[thread_kind = MainThreadOnly]
4610        #[name = "DayUIKitGesture"]
4611        #[ivars = GestureIvars]
4612        struct DayGesture;
4613
4614        unsafe impl NSObjectProtocol for DayGesture {}
4615
4616        // The delegate of the drag, pinch, rotation and long-press recognizers.
4617        unsafe impl UIGestureRecognizerDelegate for DayGesture {
4618            // A twist and a pinch (or a two-finger pan) are one hand movement, so the rotation
4619            // runs alongside Day's pinch and two-finger pan recognizers on the same view
4620            // instead of excluding them. A one-finger drag is left alone; a second finger still
4621            // ends it as it did. Every other kind keeps UIKit's exclusive arbitration: a long
4622            // press that fires makes the view's tap fail.
4623            #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))]
4624            fn simultaneous(&self, a: &UIGestureRecognizer, b: &UIGestureRecognizer) -> bool {
4625                day_spec::ffi_guard::contain(false, || {
4626                    if self.ivars().kind != day_spec::GestureKind::Rotate {
4627                        return false;
4628                    }
4629                    let same_view = match (unsafe { a.view() }, unsafe { b.view() }) {
4630                        (Some(x), Some(y)) => std::ptr::eq(&raw const *x, &raw const *y),
4631                        _ => false,
4632                    };
4633                    if !same_view {
4634                        return false;
4635                    }
4636                    let other: &AnyObject = b.as_ref();
4637                    other.downcast_ref::<UIPinchGestureRecognizer>().is_some()
4638                        || other
4639                            .downcast_ref::<UIPanGestureRecognizer>()
4640                            .is_some_and(|p| unsafe { p.minimumNumberOfTouches() } >= 2)
4641                })
4642            }
4643
4644            // The drag axis (docs/gestures.md "Gestures inside a scroll view"): a pan that
4645            // starts out across the axis is not the node's, so it fails and an enclosing
4646            // scroll view's pan, which waits for it, takes the sequence. A long press on a
4647            // view with a context menu is the menu's.
4648            #[unsafe(method(gestureRecognizerShouldBegin:))]
4649            fn should_begin(&self, g: &UIGestureRecognizer) -> bool {
4650                day_spec::ffi_guard::contain(true, || {
4651                    let Some(view) = (unsafe { g.view() }) else {
4652                        return true;
4653                    };
4654                    match self.ivars().kind {
4655                        day_spec::GestureKind::Drag => {
4656                            let Some(axis) = DRAG_AXIS.with(|t| t.get(ptr_of(&view))) else {
4657                                return true;
4658                            };
4659                            let obj: &AnyObject = g.as_ref();
4660                            let Some(pan) = obj.downcast_ref::<UIPanGestureRecognizer>() else {
4661                                return true;
4662                            };
4663                            let v = unsafe { pan.velocityInView(Some(&view)) };
4664                            let t = unsafe { pan.translationInView(Some(&view)) };
4665                            // The translation decides; the velocity breaks a tie at zero travel.
4666                            let probe = if t.x == 0.0 && t.y == 0.0 { v } else { t };
4667                            axis.leads(day_spec::Point::new(probe.x, probe.y))
4668                        }
4669                        day_spec::GestureKind::LongPress => !has_context_menu(&view),
4670                        _ => true,
4671                    }
4672                })
4673            }
4674
4675            // The claim rule (docs/gestures.md "Gestures inside a scroll view"): an enclosing
4676            // scroll view's pan, a navigation controller's back swipe or a pager's swipe waits
4677            // until the node's drag fails, so once the drag begins the sequence is the node's
4678            // until it ends. A pinch holds off an enclosing zoom the same way.
4679            #[unsafe(method(gestureRecognizer:shouldBeRequiredToFailByGestureRecognizer:))]
4680            fn required_to_fail_by(&self, a: &UIGestureRecognizer, b: &UIGestureRecognizer) -> bool {
4681                day_spec::ffi_guard::contain(false, || {
4682                    let (Some(mine), Some(theirs)) = (unsafe { a.view() }, unsafe { b.view() })
4683                    else {
4684                        return false;
4685                    };
4686                    if !is_strict_ancestor(&theirs, &mine) {
4687                        return false;
4688                    }
4689                    let other: &AnyObject = b.as_ref();
4690                    match self.ivars().kind {
4691                        day_spec::GestureKind::Drag => {
4692                            other.downcast_ref::<UIPanGestureRecognizer>().is_some()
4693                        }
4694                        day_spec::GestureKind::Pinch => {
4695                            other.downcast_ref::<UIPinchGestureRecognizer>().is_some()
4696                        }
4697                        _ => false,
4698                    }
4699                })
4700            }
4701        }
4702
4703        impl DayGesture {
4704            #[unsafe(method(fire:))]
4705            fn fire(&self, g: &UIGestureRecognizer) {
4706                day_spec::ffi_guard::contain((), || {
4707                    let node = self.ivars().node;
4708                    let view = unsafe { g.view() };
4709                    let loc = unsafe { g.locationInView(view.as_deref()) };
4710                    let at = day_spec::Point::new(loc.x, loc.y);
4711                    let state = unsafe { g.state() };
4712                    let phase = match state {
4713                        UIGestureRecognizerState::Began => day_spec::DragPhase::Began,
4714                        UIGestureRecognizerState::Ended
4715                        | UIGestureRecognizerState::Cancelled
4716                        | UIGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
4717                        _ => day_spec::DragPhase::Changed,
4718                    };
4719                    let obj: &AnyObject = g.as_ref();
4720                    // The recognizer's own release velocity (docs/gestures.md "Velocity"),
4721                    // sent just before a drag's or pan's `Ended`; a cancelled gesture has none.
4722                    let velocity = |kind: day_spec::GestureKind| {
4723                        if state != UIGestureRecognizerState::Ended {
4724                            return;
4725                        }
4726                        if let Some(pan) = obj.downcast_ref::<UIPanGestureRecognizer>() {
4727                            let v = unsafe { pan.velocityInView(view.as_deref()) };
4728                            emit(
4729                                node,
4730                                Event::GestureVelocity {
4731                                    kind,
4732                                    velocity: day_spec::Point::new(v.x, v.y),
4733                                },
4734                            );
4735                        }
4736                    };
4737                    match self.ivars().kind {
4738                        day_spec::GestureKind::Drag => {
4739                            let translation = if let Some(pan) =
4740                                obj.downcast_ref::<UIPanGestureRecognizer>()
4741                            {
4742                                let t = unsafe { pan.translationInView(view.as_deref()) };
4743                                day_spec::Point::new(t.x, t.y)
4744                            } else {
4745                                day_spec::Point::ZERO
4746                            };
4747                            velocity(day_spec::GestureKind::Drag);
4748                            emit(
4749                                node,
4750                                Event::Drag {
4751                                    phase,
4752                                    location: at,
4753                                    translation,
4754                                },
4755                            );
4756                        }
4757                        day_spec::GestureKind::Pinch => {
4758                            // UIPinchGestureRecognizer's scale is cumulative since Began —
4759                            // exactly Event::Pinch's contract.
4760                            let scale = obj
4761                                .downcast_ref::<UIPinchGestureRecognizer>()
4762                                .map_or(1.0, |p| unsafe { p.scale() });
4763                            emit(
4764                                node,
4765                                Event::Pinch {
4766                                    phase,
4767                                    scale,
4768                                    location: at,
4769                                },
4770                            );
4771                        }
4772                        day_spec::GestureKind::Rotate => {
4773                            // UIRotationGestureRecognizer's rotation is radians, cumulative
4774                            // since Began and clockwise positive in UIKit's y-down space:
4775                            // exactly Event::Rotate's contract.
4776                            let rotation = obj
4777                                .downcast_ref::<UIRotationGestureRecognizer>()
4778                                .map_or(0.0, |r| unsafe { r.rotation() });
4779                            emit(
4780                                node,
4781                                Event::Rotate {
4782                                    phase,
4783                                    rotation,
4784                                    location: at,
4785                                },
4786                            );
4787                        }
4788                        day_spec::GestureKind::Hover => {
4789                            emit(node, Event::Hover { phase, location: at });
4790                        }
4791                        day_spec::GestureKind::Pan => {
4792                            // Event::Pan's delta is INCREMENTAL: read the recognizer's
4793                            // cumulative translation, then zero it so the next fire reports
4794                            // only the movement since this one.
4795                            let delta = if let Some(pan) =
4796                                obj.downcast_ref::<UIPanGestureRecognizer>()
4797                            {
4798                                let t = unsafe { pan.translationInView(view.as_deref()) };
4799                                unsafe {
4800                                    pan.setTranslation_inView(
4801                                        CGPoint::new(0.0, 0.0),
4802                                        view.as_deref(),
4803                                    );
4804                                };
4805                                day_spec::Point::new(t.x, t.y)
4806                            } else {
4807                                day_spec::Point::ZERO
4808                            };
4809                            velocity(day_spec::GestureKind::Pan);
4810                            emit(
4811                                node,
4812                                Event::Pan {
4813                                    phase,
4814                                    delta,
4815                                    location: at,
4816                                },
4817                            );
4818                        }
4819                        // UILongPressGestureRecognizer is continuous: the press is reported
4820                        // once, when the platform's delay has passed.
4821                        day_spec::GestureKind::LongPress => {
4822                            if state == UIGestureRecognizerState::Began {
4823                                emit(node, Event::LongPress(at));
4824                            }
4825                        }
4826                        day_spec::GestureKind::DoubleTap => emit(node, Event::DoubleTap(at)),
4827                        _ => emit(node, Event::Tap(at)),
4828                    }
4829                });
4830            }
4831        }
4832    );
4833
4834    impl DayGesture {
4835        fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
4836            let this = Self::alloc(mtm).set_ivars(GestureIvars {
4837                node,
4838                kind,
4839                recognizer: RefCell::new(None),
4840            });
4841            unsafe { msg_send![super(this), init] }
4842        }
4843    }
4844
4845    /// What a [`DayObserver`] reports.
4846    #[derive(Clone, Copy, PartialEq, Eq)]
4847    enum Observe {
4848        /// `Event::Press` (docs/gestures.md "Press").
4849        Press,
4850        /// `Event::Touches` (docs/gestures.md "Touches").
4851        Touches,
4852        /// `Event::PointerKindChanged` for the whole window (docs/gestures.md "Input kind").
4853        Pointer,
4854    }
4855
4856    struct ObserverIvars {
4857        node: NodeId,
4858        what: Observe,
4859        /// A press is down (`Observe::Press`): its `false` is owed.
4860        pressed: Cell<bool>,
4861        /// The last point the press was at, in the view's coordinates.
4862        last: Cell<CGPoint>,
4863        /// The contacts on the view (`Observe::Touches`): each `UITouch`'s address and the id
4864        /// it is reported under.
4865        contacts: RefCell<Vec<(usize, u64)>>,
4866        next_id: Cell<u64>,
4867    }
4868
4869    /// The kind of device behind a touch.
4870    fn touch_kind(touch: &objc2_ui_kit::UITouch) -> day_spec::PointerKind {
4871        match unsafe { touch.r#type() } {
4872            objc2_ui_kit::UITouchType::Pencil => day_spec::PointerKind::Stylus,
4873            objc2_ui_kit::UITouchType::IndirectPointer => day_spec::PointerKind::Mouse,
4874            _ => day_spec::PointerKind::Touch,
4875        }
4876    }
4877
4878    /// Reports `kind` as the primary pointer when it differs from the last one reported.
4879    fn note_pointer_kind(kind: day_spec::PointerKind) {
4880        if POINTER_KIND.with(Cell::get) != kind {
4881            POINTER_KIND.with(|k| k.set(kind));
4882            emit(WINDOW_NODE, Event::PointerKindChanged(kind));
4883        }
4884    }
4885
4886    /// `bounds` grown by the view's hit slop, the leading and trailing edges following the
4887    /// view's layout direction (docs/gestures.md "Hit slop").
4888    fn hit_area(view: &UIView) -> CGRect {
4889        let b = view.bounds();
4890        let Some(slop) = HIT_SLOP.with(|t| t.get(ptr_of(view))) else {
4891            return b;
4892        };
4893        let rtl = view.effectiveUserInterfaceLayoutDirection()
4894            == objc2_ui_kit::UIUserInterfaceLayoutDirection::RightToLeft;
4895        let (left, right) = if rtl {
4896            (slop.trailing, slop.leading)
4897        } else {
4898            (slop.leading, slop.trailing)
4899        };
4900        CGRect::new(
4901            CGPoint::new(b.origin.x - left, b.origin.y - slop.top),
4902            CGSize::new(
4903                b.size.width + left + right,
4904                b.size.height + slop.top + slop.bottom,
4905            ),
4906        )
4907    }
4908
4909    fn rect_contains(r: CGRect, p: CGPoint) -> bool {
4910        p.x >= r.origin.x
4911            && p.y >= r.origin.y
4912            && p.x < r.origin.x + r.size.width
4913            && p.y < r.origin.y + r.size.height
4914    }
4915
4916    /// Whether any view has a hit slop now: the hit tests below walk subtrees only then.
4917    fn slop_in_use() -> bool {
4918        HIT_SLOP.with(|t| {
4919            let mut any = false;
4920            t.for_each(|_, _| any = true);
4921            any
4922        })
4923    }
4924
4925    /// Whether UIKit would hit-test into `view` at all.
4926    fn hit_testable(view: &UIView) -> bool {
4927        unsafe { !view.isHidden() && view.isUserInteractionEnabled() && view.alpha() >= 0.01 }
4928    }
4929
4930    /// Whether `p` (in `view`'s coordinates) lies in the slop of `view` or of a view under it.
4931    fn reaches_slop(view: &UIView, p: CGPoint) -> bool {
4932        if HIT_SLOP.with(|t| t.contains(ptr_of(view))) && rect_contains(hit_area(view), p) {
4933            return true;
4934        }
4935        unsafe { view.subviews() }.iter().any(|s| {
4936            hit_testable(&s) && reaches_slop(&s, unsafe { view.convertPoint_toView(p, Some(&s)) })
4937        })
4938    }
4939
4940    /// `pointInside:withEvent:` for Day's container and canvas views: the bounds grown by the
4941    /// view's own slop, and the slop of any view under it, which may reach past this one
4942    /// (docs/gestures.md "Hit slop").
4943    fn day_point_inside(view: &UIView, p: CGPoint) -> bool {
4944        rect_contains(hit_area(view), p)
4945            || (slop_in_use()
4946                && unsafe { view.subviews() }.iter().any(|s| {
4947                    hit_testable(&s)
4948                        && reaches_slop(&s, unsafe { view.convertPoint_toView(p, Some(&s)) })
4949                }))
4950    }
4951
4952    /// Whether a Day view takes pointer input itself (docs/gestures.md "Pass-through"): a
4953    /// recognizer or an interaction (context menu, drag source, drop target, pointer effect)
4954    /// is attached, or `keys` says it takes focus.
4955    fn takes_touches(view: &UIView, keys: bool) -> bool {
4956        keys || unsafe { view.gestureRecognizers() }.is_some_and(|g| g.count() > 0)
4957            || unsafe { view.interactions() }.count() > 0
4958    }
4959
4960    /// `hitTest:withEvent:` for Day's container and canvas views. The subviews front to back,
4961    /// each with its slop (a view UIKit draws, such as an image or a button, cannot grow its
4962    /// own hit area, so its parent answers for it); then the view itself, only when it takes
4963    /// touches: a view with nothing attached lets a press through to what is behind it.
4964    fn day_hit_test(
4965        view: &UIView,
4966        point: CGPoint,
4967        event: Option<&objc2_ui_kit::UIEvent>,
4968        own: bool,
4969    ) -> Option<Retained<UIView>> {
4970        if !hit_testable(view) || !day_point_inside(view, point) {
4971            return None;
4972        }
4973        let subviews = unsafe { view.subviews() }.to_vec();
4974        for sub in subviews.into_iter().rev() {
4975            let p = unsafe { view.convertPoint_toView(point, Some(&sub)) };
4976            if let Some(hit) = unsafe { sub.hitTest_withEvent(p, event) } {
4977                return Some(hit);
4978            }
4979            if hit_testable(&sub)
4980                && HIT_SLOP.with(|t| t.contains(ptr_of(&sub)))
4981                && rect_contains(hit_area(&sub), p)
4982            {
4983                let b = sub.bounds();
4984                let inside = CGPoint::new(
4985                    p.x.clamp(b.origin.x, b.origin.x + (b.size.width - 0.5).max(0.0)),
4986                    p.y.clamp(b.origin.y, b.origin.y + (b.size.height - 0.5).max(0.0)),
4987                );
4988                return unsafe { sub.hitTest_withEvent(inside, event) }.or(Some(sub));
4989            }
4990        }
4991        (own && rect_contains(hit_area(view), point)).then(|| view.retain())
4992    }
4993
4994    /// Whether a recognizer on one of `view`'s ancestors has taken the touches away: a scroll
4995    /// view's pan, a back swipe, a pager's swipe. Those cancel the view's touches; an observer
4996    /// that runs alongside them still sees the moves, so it asks.
4997    fn ancestor_took_over(view: &UIView) -> bool {
4998        let mut cur = unsafe { view.superview() };
4999        while let Some(v) = cur {
5000            if let Some(recognizers) = unsafe { v.gestureRecognizers() } {
5001                for r in &recognizers {
5002                    let state = unsafe { r.state() };
5003                    if unsafe { r.cancelsTouchesInView() }
5004                        && (state == UIGestureRecognizerState::Began
5005                            || state == UIGestureRecognizerState::Changed)
5006                    {
5007                        return true;
5008                    }
5009                }
5010            }
5011            cur = unsafe { v.superview() };
5012        }
5013        false
5014    }
5015
5016    define_class!(
5017        /// An observing recognizer (docs/gestures.md "Press", "Touches", "Input kind"). It
5018        /// never recognizes, so it never delays, cancels or excludes another recognizer, a
5019        /// control's own tracking or an enclosing scroll view: it stays possible while touches
5020        /// are down, reports what it sees, and fails when the last one lifts.
5021        #[unsafe(super(UIGestureRecognizer))]
5022        #[thread_kind = MainThreadOnly]
5023        #[name = "DayUIKitObserver"]
5024        #[ivars = ObserverIvars]
5025        struct DayObserver;
5026
5027        unsafe impl NSObjectProtocol for DayObserver {}
5028
5029        unsafe impl UIGestureRecognizerDelegate for DayObserver {
5030            #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))]
5031            fn simultaneous(&self, _a: &UIGestureRecognizer, _b: &UIGestureRecognizer) -> bool {
5032                true
5033            }
5034        }
5035
5036        impl DayObserver {
5037            #[unsafe(method(touchesBegan:withEvent:))]
5038            fn touches_began(
5039                &self,
5040                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5041                event: &objc2_ui_kit::UIEvent,
5042            ) {
5043                day_spec::ffi_guard::contain((), || self.observe(touches, event, 0));
5044            }
5045
5046            #[unsafe(method(touchesMoved:withEvent:))]
5047            fn touches_moved(
5048                &self,
5049                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5050                event: &objc2_ui_kit::UIEvent,
5051            ) {
5052                day_spec::ffi_guard::contain((), || self.observe(touches, event, 1));
5053            }
5054
5055            #[unsafe(method(touchesEnded:withEvent:))]
5056            fn touches_ended(
5057                &self,
5058                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5059                event: &objc2_ui_kit::UIEvent,
5060            ) {
5061                day_spec::ffi_guard::contain((), || self.observe(touches, event, 2));
5062            }
5063
5064            #[unsafe(method(touchesCancelled:withEvent:))]
5065            fn touches_cancelled(
5066                &self,
5067                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5068                event: &objc2_ui_kit::UIEvent,
5069            ) {
5070                day_spec::ffi_guard::contain((), || self.observe(touches, event, 3));
5071            }
5072
5073            #[unsafe(method(reset))]
5074            fn reset(&self) {
5075                let _: () = unsafe { msg_send![super(self), reset] };
5076                day_spec::ffi_guard::contain((), || self.finish(true));
5077            }
5078
5079            // A Mouse or trackpad pointer hovering over the window (`Observe::Pointer`).
5080            #[unsafe(method(hover:))]
5081            fn hover(&self, _g: &UIGestureRecognizer) {
5082                day_spec::ffi_guard::contain((), || {
5083                    note_pointer_kind(day_spec::PointerKind::Mouse);
5084                });
5085            }
5086        }
5087    );
5088
5089    impl DayObserver {
5090        fn new(mtm: MainThreadMarker, node: NodeId, what: Observe) -> Retained<Self> {
5091            let this = Self::alloc(mtm).set_ivars(ObserverIvars {
5092                node,
5093                what,
5094                pressed: Cell::new(false),
5095                last: Cell::new(CGPoint::new(0.0, 0.0)),
5096                contacts: RefCell::new(Vec::new()),
5097                next_id: Cell::new(0),
5098            });
5099            let this: Retained<Self> = unsafe {
5100                msg_send![super(this), initWithTarget: None::<&AnyObject>, action: None::<Sel>]
5101            };
5102            unsafe {
5103                this.setCancelsTouchesInView(false);
5104                this.setDelaysTouchesBegan(false);
5105                this.setDelaysTouchesEnded(false);
5106                this.setDelegate(Some(ProtocolObject::from_ref(&*this)));
5107            }
5108            this
5109        }
5110
5111        /// One touch callback: `step` 0 began, 1 moved, 2 ended, 3 cancelled.
5112        fn observe(
5113            &self,
5114            touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5115            event: &objc2_ui_kit::UIEvent,
5116            step: u8,
5117        ) {
5118            let view = unsafe { self.view() };
5119            match self.ivars().what {
5120                Observe::Pointer => {
5121                    if step == 0
5122                        && let Some(touch) = touches.iter().next()
5123                    {
5124                        note_pointer_kind(touch_kind(&touch));
5125                    }
5126                }
5127                Observe::Press => self.observe_press(touches, event, step, view.as_deref()),
5128                Observe::Touches => self.observe_touches(touches, event, step, view.as_deref()),
5129            }
5130            if step >= 2 {
5131                let all = unsafe { event.touchesForGestureRecognizer(self) };
5132                let done = all.is_none_or(|all| {
5133                    all.iter().all(|t| {
5134                        let p = unsafe { t.phase() };
5135                        p == objc2_ui_kit::UITouchPhase::Ended
5136                            || p == objc2_ui_kit::UITouchPhase::Cancelled
5137                    })
5138                });
5139                if done {
5140                    // Possible → Failed: UIKit resets the observer for the next sequence.
5141                    unsafe { self.setState(UIGestureRecognizerState::Failed) };
5142                }
5143            }
5144        }
5145
5146        fn observe_press(
5147            &self,
5148            touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5149            event: &objc2_ui_kit::UIEvent,
5150            step: u8,
5151            view: Option<&UIView>,
5152        ) {
5153            let Some(view) = view else { return };
5154            let iv = self.ivars();
5155            let Some(touch) = touches.iter().next() else {
5156                return;
5157            };
5158            let at = unsafe { touch.locationInView(Some(view)) };
5159            match step {
5160                0 => {
5161                    // The first contact only, and a pointer's primary button only.
5162                    let buttons = unsafe { event.buttonMask() };
5163                    let primary = buttons.0 == 0
5164                        || buttons.contains(objc2_ui_kit::UIEventButtonMask::Primary);
5165                    if iv.pressed.get() || !primary {
5166                        return;
5167                    }
5168                    iv.pressed.set(true);
5169                    iv.last.set(at);
5170                    emit(
5171                        iv.node,
5172                        Event::Press {
5173                            pressed: true,
5174                            location: day_spec::Point::new(at.x, at.y),
5175                        },
5176                    );
5177                }
5178                1 => {
5179                    if !iv.pressed.get() {
5180                        return;
5181                    }
5182                    iv.last.set(at);
5183                    // Leaving the hit area ends the press, and so does an enclosing scroll
5184                    // view starting to scroll.
5185                    if !rect_contains(hit_area(view), at) || ancestor_took_over(view) {
5186                        self.finish(false);
5187                    }
5188                }
5189                _ => {
5190                    iv.last.set(at);
5191                    self.finish(false);
5192                }
5193            }
5194        }
5195
5196        fn observe_touches(
5197            &self,
5198            touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
5199            event: &objc2_ui_kit::UIEvent,
5200            step: u8,
5201            view: Option<&UIView>,
5202        ) {
5203            let iv = self.ivars();
5204            let changed: Vec<usize> = touches
5205                .iter()
5206                .map(|t| Retained::as_ptr(&t) as usize)
5207                .collect();
5208            let Some(all) = (unsafe { event.touchesForGestureRecognizer(self) }) else {
5209                return;
5210            };
5211            let mut report = Vec::new();
5212            for touch in &all {
5213                let key = Retained::as_ptr(&touch) as usize;
5214                let id = {
5215                    let mut contacts = iv.contacts.borrow_mut();
5216                    if let Some(&(_, id)) = contacts.iter().find(|(k, _)| *k == key) {
5217                        id
5218                    } else {
5219                        let id = iv.next_id.get();
5220                        iv.next_id.set(id + 1);
5221                        contacts.push((key, id));
5222                        id
5223                    }
5224                };
5225                let phase = if changed.contains(&key) {
5226                    match step {
5227                        0 => day_spec::TouchPhase::Began,
5228                        1 => day_spec::TouchPhase::Moved,
5229                        2 => day_spec::TouchPhase::Ended,
5230                        _ => day_spec::TouchPhase::Cancelled,
5231                    }
5232                } else {
5233                    match unsafe { touch.phase() } {
5234                        objc2_ui_kit::UITouchPhase::Ended => day_spec::TouchPhase::Ended,
5235                        objc2_ui_kit::UITouchPhase::Cancelled => day_spec::TouchPhase::Cancelled,
5236                        _ => day_spec::TouchPhase::Stationary,
5237                    }
5238                };
5239                let at = unsafe { touch.locationInView(view) };
5240                let max = unsafe { touch.maximumPossibleForce() };
5241                let pressure = if max > 0.0 {
5242                    (unsafe { touch.force() }) / max
5243                } else {
5244                    1.0
5245                };
5246                report.push(
5247                    day_spec::Touch::new(id, phase, day_spec::Point::new(at.x, at.y))
5248                        .with_pressure(pressure)
5249                        .with_kind(touch_kind(&touch)),
5250                );
5251                if matches!(
5252                    phase,
5253                    day_spec::TouchPhase::Ended | day_spec::TouchPhase::Cancelled
5254                ) {
5255                    iv.contacts.borrow_mut().retain(|(k, _)| *k != key);
5256                }
5257            }
5258            if !report.is_empty() {
5259                emit(iv.node, Event::Touches(report));
5260            }
5261        }
5262
5263        /// Ends what is under way: the owed `pressed: false` at the last point, and with
5264        /// `cancel`, every contact still down as cancelled.
5265        fn finish(&self, cancel: bool) {
5266            let iv = self.ivars();
5267            if iv.pressed.replace(false) {
5268                let at = iv.last.get();
5269                emit(
5270                    iv.node,
5271                    Event::Press {
5272                        pressed: false,
5273                        location: day_spec::Point::new(at.x, at.y),
5274                    },
5275                );
5276            }
5277            let left: Vec<(usize, u64)> = std::mem::take(&mut *iv.contacts.borrow_mut());
5278            if cancel && !left.is_empty() && iv.what == Observe::Touches {
5279                let at = iv.last.get();
5280                let report = left
5281                    .into_iter()
5282                    .map(|(_, id)| {
5283                        day_spec::Touch::new(
5284                            id,
5285                            day_spec::TouchPhase::Cancelled,
5286                            day_spec::Point::new(at.x, at.y),
5287                        )
5288                    })
5289                    .collect();
5290                emit(iv.node, Event::Touches(report));
5291            }
5292        }
5293    }
5294
5295    /// Watches `window` for the kind of device behind each pointer down, and for a hovering
5296    /// pointer (docs/gestures.md "Input kind").
5297    fn watch_pointer(window: &UIWindow) {
5298        let mtm = window.mtm();
5299        let observer = DayObserver::new(mtm, WINDOW_NODE, Observe::Pointer);
5300        let hover = unsafe {
5301            objc2_ui_kit::UIHoverGestureRecognizer::initWithTarget_action(
5302                objc2_ui_kit::UIHoverGestureRecognizer::alloc(mtm),
5303                Some(&observer),
5304                Some(sel!(hover:)),
5305            )
5306        };
5307        unsafe {
5308            hover.setCancelsTouchesInView(false);
5309            hover.setDelegate(Some(ProtocolObject::from_ref(&*observer)));
5310            window.addGestureRecognizer(&observer);
5311            window.addGestureRecognizer(&hover);
5312        }
5313        POINTER_WATCH.with(|w| w.borrow_mut().push(observer));
5314    }
5315
5316    /// A disabled group's root (`GROUP_OFF`): how many groups it roots, and what it had before
5317    /// the first.
5318    #[derive(Clone, Copy)]
5319    struct GroupOff {
5320        groups: u32,
5321        interaction: bool,
5322        tint: objc2_ui_kit::UIViewTintAdjustmentMode,
5323    }
5324
5325    /// A view a disabled group changed (`HELD_OFF`).
5326    #[derive(Clone, Copy)]
5327    struct HeldOff {
5328        groups: u32,
5329        /// A control's own `isEnabled` before the first group.
5330        enabled: Option<bool>,
5331        /// An accessibility element's traits before the first group.
5332        traits: Option<objc2_ui_kit::UIAccessibilityTraits>,
5333    }
5334
5335    /// A hardware key a focused view claimed the down of (`KEYS_DOWN`).
5336    #[derive(Clone)]
5337    struct HeldKey {
5338        /// The key's HID usage, which its release carries too.
5339        code: isize,
5340        /// The key's name, as the down reported it.
5341        name: String,
5342        /// The key types: its downs and repeats arrive as text through `insertText:`, and
5343        /// `super` saw its press.
5344        text: bool,
5345        /// How many times its text was inserted so far: every one after the first is a repeat.
5346        inserts: u32,
5347    }
5348
5349    /// Lets `view` take touches, unless a disabled group roots at it: then the group's own
5350    /// restore turns them on (docs/forms.md "Disabling a group").
5351    fn allow_interaction(view: &UIView) {
5352        let key = ptr_of(view);
5353        if GROUP_OFF
5354            .with(|t| t.with(key, |g| g.interaction = true))
5355            .is_none()
5356        {
5357            unsafe { view.setUserInteractionEnabled(true) };
5358        }
5359    }
5360
5361    /// The controls day-core sends their own `Enabled` patch (docs/forms.md "Disabling a
5362    /// group"): the walk leaves their state to those patches.
5363    fn day_core_enables(view: &UIView) -> bool {
5364        let obj: &AnyObject = view.as_ref();
5365        obj.downcast_ref::<UIButton>().is_some()
5366            || obj.downcast_ref::<UISwitch>().is_some()
5367            || obj.downcast_ref::<UISlider>().is_some()
5368            || obj.downcast_ref::<UITextField>().is_some()
5369    }
5370
5371    fn for_each_descendant(view: &UIView, f: &mut impl FnMut(&UIView)) {
5372        for sub in unsafe { view.subviews() } {
5373            f(&sub);
5374            for_each_descendant(&sub, f);
5375        }
5376    }
5377
5378    /// `set_subtree_enabled` (docs/forms.md "Disabling a group"). Touches stop at the root
5379    /// (`isUserInteractionEnabled`, which also takes the subtree out of focus), its tint dims
5380    /// the UIKit way, focus inside resigns, every other control kind turns its own `isEnabled`
5381    /// off, and the composed accessibility elements read as not enabled. Counted per root and
5382    /// per view, so a view under two disabled groups stays disabled until both are enabled.
5383    fn set_group_enabled(root: &UIView, enabled: bool) {
5384        let mtm = root.mtm();
5385        let key = ptr_of(root);
5386        let current = GROUP_OFF.with(|t| t.get(key));
5387        if enabled {
5388            let Some(mut g) = current else { return };
5389            g.groups -= 1;
5390            if g.groups > 0 {
5391                GROUP_OFF.with(|t| t.insert(key, g));
5392                return;
5393            }
5394            GROUP_OFF.with(|t| t.remove(key));
5395            unsafe {
5396                root.setUserInteractionEnabled(g.interaction);
5397                root.setTintAdjustmentMode(g.tint);
5398            }
5399            for_each_descendant(root, &mut |v| {
5400                let vk = ptr_of(v);
5401                let Some(mut held) = HELD_OFF.with(|t| t.get(vk)) else {
5402                    return;
5403                };
5404                held.groups -= 1;
5405                if held.groups > 0 {
5406                    HELD_OFF.with(|t| t.insert(vk, held));
5407                    return;
5408                }
5409                HELD_OFF.with(|t| t.remove(vk));
5410                if let (Some(was), Some(control)) = (held.enabled, v.downcast_ref::<UIControl>()) {
5411                    unsafe { control.setEnabled(was) };
5412                }
5413                if let Some(traits) = held.traits {
5414                    v.setAccessibilityTraits(traits, mtm);
5415                }
5416            });
5417            return;
5418        }
5419        if let Some(mut g) = current {
5420            g.groups += 1;
5421            GROUP_OFF.with(|t| t.insert(key, g));
5422            return;
5423        }
5424        GROUP_OFF.with(|t| {
5425            t.insert(
5426                key,
5427                GroupOff {
5428                    groups: 1,
5429                    interaction: unsafe { root.isUserInteractionEnabled() },
5430                    tint: unsafe { root.tintAdjustmentMode() },
5431                },
5432            )
5433        });
5434        unsafe {
5435            root.setUserInteractionEnabled(false);
5436            root.setTintAdjustmentMode(objc2_ui_kit::UIViewTintAdjustmentMode::Dimmed);
5437        }
5438        let not_enabled = unsafe { objc2_ui_kit::UIAccessibilityTraitNotEnabled };
5439        let mut resign = Vec::new();
5440        if root.isFirstResponder() {
5441            resign.push(root.retain());
5442        }
5443        for_each_descendant(root, &mut |v| {
5444            let vk = ptr_of(v);
5445            if v.isFirstResponder() {
5446                resign.push(v.retain());
5447            }
5448            if let Some(mut held) = HELD_OFF.with(|t| t.get(vk)) {
5449                held.groups += 1;
5450                HELD_OFF.with(|t| t.insert(vk, held));
5451                return;
5452            }
5453            let mut held = HeldOff {
5454                groups: 1,
5455                enabled: None,
5456                traits: None,
5457            };
5458            if let Some(control) = v.downcast_ref::<UIControl>() {
5459                if !day_core_enables(v) {
5460                    held.enabled = Some(unsafe { control.isEnabled() });
5461                    unsafe { control.setEnabled(false) };
5462                }
5463            } else if v.isAccessibilityElement(mtm) {
5464                let traits = v.accessibilityTraits(mtm);
5465                held.traits = Some(traits);
5466                v.setAccessibilityTraits(traits | not_enabled, mtm);
5467            }
5468            HELD_OFF.with(|t| t.insert(vk, held));
5469        });
5470        for v in resign {
5471            let _ = unsafe { v.resignFirstResponder() };
5472        }
5473    }
5474
5475    // -----------------------------------------------------------------------
5476    // Menus (docs/menus.md): the day-neutral MenuItem tree becomes a UIMenu of UIActions, shown
5477    // by a UIContextMenuInteraction on long-press. Custom actions emit MenuAction(id); standard
5478    // roles route their selector up the responder chain so Cut/Copy/Paste hit the focused field.
5479    // -----------------------------------------------------------------------
5480
5481    struct CtxMenuIvars {
5482        menu: Retained<UIMenu>,
5483    }
5484
5485    define_class!(
5486        #[unsafe(super(NSObject))]
5487        #[thread_kind = MainThreadOnly]
5488        #[name = "DayUIKitContextMenu"]
5489        #[ivars = CtxMenuIvars]
5490        struct DayContextMenu;
5491
5492        unsafe impl NSObjectProtocol for DayContextMenu {}
5493
5494        unsafe impl UIContextMenuInteractionDelegate for DayContextMenu {
5495            #[unsafe(method_id(contextMenuInteraction:configurationForMenuAtLocation:))]
5496            fn configuration_for_menu(
5497                &self,
5498                _interaction: &UIContextMenuInteraction,
5499                _location: CGPoint,
5500            ) -> Option<Retained<UIContextMenuConfiguration>> {
5501                let menu = self.ivars().menu.clone();
5502                let provider = block2::RcBlock::new(
5503                    move |_suggested: NonNull<objc2_foundation::NSArray<UIMenuElement>>| -> *mut UIMenu {
5504                        // A block's object return is +0 by convention: hand back an
5505                        // autoreleased pointer. `into_raw` (+1) leaked one retain of the
5506                        // whole menu graph per summon.
5507                        Retained::autorelease_return(menu.clone())
5508                    },
5509                );
5510                Some(unsafe {
5511                    UIContextMenuConfiguration::configurationWithIdentifier_previewProvider_actionProvider(
5512                        None,
5513                        std::ptr::null_mut(),
5514                        block2::RcBlock::as_ptr(&provider),
5515                        mtm(),
5516                    )
5517                })
5518            }
5519        }
5520    );
5521
5522    impl DayContextMenu {
5523        fn new(mtm: MainThreadMarker, menu: Retained<UIMenu>) -> Retained<Self> {
5524            let this = Self::alloc(mtm).set_ivars(CtxMenuIvars { menu });
5525            unsafe { msg_send![super(this), init] }
5526        }
5527    }
5528
5529    // The summon-time variant (docs/menus.md "Dynamic context menus"): the menu is built
5530    // when the long-press lands, from the provider — UIContextMenuInteraction's
5531    // configuration callback is exactly that moment, and it hands over the location.
5532    struct CtxMenuFnIvars {
5533        f: day_spec::ContextMenuFn,
5534    }
5535
5536    define_class!(
5537        #[unsafe(super(NSObject))]
5538        #[thread_kind = MainThreadOnly]
5539        #[name = "DayUIKitContextMenuFn"]
5540        #[ivars = CtxMenuFnIvars]
5541        struct DayContextMenuFn;
5542
5543        unsafe impl NSObjectProtocol for DayContextMenuFn {}
5544
5545        unsafe impl UIContextMenuInteractionDelegate for DayContextMenuFn {
5546            #[unsafe(method_id(contextMenuInteraction:configurationForMenuAtLocation:))]
5547            fn configuration_for_menu(
5548                &self,
5549                _interaction: &UIContextMenuInteraction,
5550                location: CGPoint,
5551            ) -> Option<Retained<UIContextMenuConfiguration>> {
5552                // Guarded: the provider is app code (it usually re-selects, then builds).
5553                day_spec::ffi_guard::contain(None, || {
5554                    let items = (self.ivars().f)(day_spec::Point::new(location.x, location.y));
5555                    if items.is_empty() {
5556                        return None;
5557                    }
5558                    let mtm = self.mtm();
5559                    let menu = build_ui_menu(mtm, "", &items);
5560                    let provider = block2::RcBlock::new(
5561                        move |_suggested: NonNull<objc2_foundation::NSArray<UIMenuElement>>| -> *mut UIMenu {
5562                            Retained::autorelease_return(menu.clone())
5563                        },
5564                    );
5565                    Some(unsafe {
5566                        UIContextMenuConfiguration::configurationWithIdentifier_previewProvider_actionProvider(
5567                            None,
5568                            std::ptr::null_mut(),
5569                            block2::RcBlock::as_ptr(&provider),
5570                            mtm,
5571                        )
5572                    })
5573                })
5574            }
5575        }
5576    );
5577
5578    impl DayContextMenuFn {
5579        fn new(mtm: MainThreadMarker, f: day_spec::ContextMenuFn) -> Retained<Self> {
5580            let this = Self::alloc(mtm).set_ivars(CtxMenuFnIvars { f });
5581            unsafe { msg_send![super(this), init] }
5582        }
5583    }
5584
5585    /// Default label for a standard role left unlabeled by the app.
5586    fn ui_role_label(role: day_spec::MenuRole) -> &'static str {
5587        use day_spec::MenuRole::{
5588            About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize,
5589            NewWindow, Paste, Preferences, Quit, Redo, SelectAll, Undo,
5590        };
5591        match role {
5592            Cut => "Cut",
5593            Copy => "Copy",
5594            Paste => "Paste",
5595            SelectAll => "Select All",
5596            Undo => "Undo",
5597            Redo => "Redo",
5598            Delete => "Delete",
5599            About => "About",
5600            Quit => "Quit",
5601            Preferences => "Settings",
5602            Minimize => "Minimize",
5603            CloseWindow => "Close",
5604            Fullscreen => "Full Screen",
5605            NewWindow => "New Window",
5606            CheckForUpdates => "Check for Updates…",
5607        }
5608    }
5609
5610    /// The `UIResponder` standard-edit nav host a role routes to (None → a no-op labeled action, since
5611    /// iOS has no responder equivalent — e.g. Quit/About/window management).
5612    fn ui_role_selector(role: day_spec::MenuRole) -> Option<objc2::runtime::Sel> {
5613        use day_spec::MenuRole::{Copy, Cut, Delete, Paste, SelectAll};
5614        Some(match role {
5615            Cut => sel!(cut:),
5616            Copy => sel!(copy:),
5617            Paste => sel!(paste:),
5618            SelectAll => sel!(selectAll:),
5619            Delete => sel!(delete:),
5620            _ => return None,
5621        })
5622    }
5623
5624    thread_local! {
5625        /// Each realized list item's current props, by its view: a patch updates one part and
5626        /// the item is re-dressed from the whole (docs/list.md "List items").
5627        static LIST_ITEMS: RefCell<HashMap<usize, day_spec::props::ListItemProps>> =
5628            RefCell::new(HashMap::new());
5629    }
5630
5631    /// A list row's standard content (docs/list.md "List items"), the way UIKit draws its own
5632    /// rows: a `UIListContentView` showing the cell's default content configuration (its fonts,
5633    /// image size and spacing, the secondary color for the subtitle) beside a trailing value
5634    /// and the system checkmark, in a horizontal stack. The configuration keeps no margins of
5635    /// its own: the list gives the row the table's side margins, and the content view's own
5636    /// sizing gives it the cell's height (docs/list.md "Row metrics").
5637    fn make_list_item(
5638        p: &day_spec::props::ListItemProps,
5639        mtm: MainThreadMarker,
5640    ) -> Retained<UIView> {
5641        unsafe {
5642            let stack = objc2_ui_kit::UIStackView::new(mtm);
5643            stack.setAxis(objc2_ui_kit::UILayoutConstraintAxis::Horizontal);
5644            stack.setAlignment(objc2_ui_kit::UIStackViewAlignment::Center);
5645            stack.setSpacing(8.0);
5646            let config: Retained<AnyObject> =
5647                msg_send![objc2::class!(UIListContentConfiguration), cellConfiguration];
5648            let content: Retained<UIView> = msg_send![
5649                msg_send![objc2::class!(UIListContentView), alloc],
5650                initWithConfiguration: &*config
5651            ];
5652            // The content takes the width; the trailing parts keep their own.
5653            content.setContentHuggingPriority_forAxis(
5654                1.0,
5655                objc2_ui_kit::UILayoutConstraintAxis::Horizontal,
5656            );
5657            content.setContentCompressionResistancePriority_forAxis(
5658                250.0,
5659                objc2_ui_kit::UILayoutConstraintAxis::Horizontal,
5660            );
5661            stack.addArrangedSubview(&content);
5662            let detail = UILabel::new(mtm);
5663            detail.setFont(Some(&objc2_ui_kit::UIFont::preferredFontForTextStyle(
5664                objc2_ui_kit::UIFontTextStyleBody,
5665            )));
5666            let _: () = msg_send![&*detail, setAdjustsFontForContentSizeCategory: true];
5667            detail.setTextColor(Some(&objc2_ui_kit::UIColor::secondaryLabelColor()));
5668            detail.setContentHuggingPriority_forAxis(
5669                751.0,
5670                objc2_ui_kit::UILayoutConstraintAxis::Horizontal,
5671            );
5672            stack.addArrangedSubview(&detail);
5673            // The checkmark accessory's glyph: body size, semibold, in the tint color.
5674            let symbol: Retained<AnyObject> = msg_send![
5675                objc2::class!(UIImageSymbolConfiguration),
5676                configurationWithTextStyle: objc2_ui_kit::UIFontTextStyleBody,
5677                scale: 2isize
5678            ];
5679            let weight: Retained<AnyObject> = msg_send![
5680                objc2::class!(UIImageSymbolConfiguration),
5681                configurationWithWeight: 6isize
5682            ];
5683            let symbol: Retained<AnyObject> =
5684                msg_send![&*symbol, configurationByApplyingConfiguration: &*weight];
5685            let check: Option<Retained<objc2_ui_kit::UIImage>> = msg_send![
5686                objc2::class!(UIImage),
5687                systemImageNamed: &*NSString::from_str("checkmark"),
5688                withConfiguration: &*symbol
5689            ];
5690            let mark = objc2_ui_kit::UIImageView::initWithImage(
5691                objc2_ui_kit::UIImageView::alloc(mtm),
5692                check.as_deref(),
5693            );
5694            mark.setContentHuggingPriority_forAxis(
5695                751.0,
5696                objc2_ui_kit::UILayoutConstraintAxis::Horizontal,
5697            );
5698            stack.addArrangedSubview(&mark);
5699            let view: Retained<UIView> = Retained::into_super(stack);
5700            LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
5701            dress_list_item(&view, p);
5702            view
5703        }
5704    }
5705
5706    /// Show `p` on a list item's stack: its content configuration, value and check mark, and
5707    /// one accessibility element naming them all.
5708    fn dress_list_item(view: &UIView, p: &day_spec::props::ListItemProps) {
5709        let Some(stack) = view.downcast_ref::<objc2_ui_kit::UIStackView>() else {
5710            return;
5711        };
5712        let parts = unsafe { stack.arrangedSubviews() };
5713        if parts.len() < 3 {
5714            return;
5715        }
5716        let Some(mtm) = MainThreadMarker::new() else {
5717            return;
5718        };
5719        unsafe {
5720            let content = &parts.objectAtIndex(0);
5721            let config: Retained<AnyObject> =
5722                msg_send![objc2::class!(UIListContentConfiguration), cellConfiguration];
5723            let _: () = msg_send![&*config, setText: &*NSString::from_str(&p.title)];
5724            let subtitle = (!p.subtitle.is_empty()).then(|| NSString::from_str(&p.subtitle));
5725            let _: () = msg_send![&*config, setSecondaryText: subtitle.as_deref()];
5726            let image = menu_image(p.icon.as_ref()).map(|img| {
5727                img.imageWithRenderingMode(objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate)
5728            });
5729            let _: () = msg_send![&*config, setImage: image.as_deref()];
5730            let props: Retained<AnyObject> = msg_send![&*config, imageProperties];
5731            let tint = p.icon_tint.map(uiink);
5732            let _: () = msg_send![&*props, setTintColor: tint.as_deref()];
5733            let zero = objc2_ui_kit::NSDirectionalEdgeInsets {
5734                top: 0.0,
5735                leading: 0.0,
5736                bottom: 0.0,
5737                trailing: 0.0,
5738            };
5739            let _: () = msg_send![&*config, setDirectionalLayoutMargins: zero];
5740            // And none inherited: by default the content keeps its superview's margins too,
5741            // which would add the cell's margins a second time (`UIAxis` none).
5742            let _: () = msg_send![&*config, setAxesPreservingSuperviewLayoutMargins: 0usize];
5743            let _: () = msg_send![&**content, setConfiguration: &*config];
5744            let detail = &parts.objectAtIndex(1);
5745            if let Some(label) = detail.downcast_ref::<UILabel>() {
5746                label.setText(Some(&NSString::from_str(&p.detail)));
5747            }
5748            detail.setHidden(p.detail.is_empty());
5749            parts.objectAtIndex(2).setHidden(!p.checked);
5750            // One element for the row, as a standard cell is: its words, and selected while
5751            // the check mark shows.
5752            view.setIsAccessibilityElement(true, mtm);
5753            let words = [&p.title, &p.subtitle, &p.detail]
5754                .into_iter()
5755                .filter(|w| !w.is_empty())
5756                .map(String::as_str)
5757                .collect::<Vec<_>>()
5758                .join(", ");
5759            view.setAccessibilityLabel(Some(&NSString::from_str(&words)), mtm);
5760            view.setAccessibilityTraits(
5761                if p.checked {
5762                    objc2_ui_kit::UIAccessibilityTraitSelected
5763                } else {
5764                    0
5765                },
5766                mtm,
5767            );
5768        }
5769    }
5770
5771    /// Build a single `UIAction`; `handler` runs on the main thread when chosen.
5772    /// The item's glyph: an SF Symbol for a standard symbol (the shared Apple table), or a
5773    /// bundled image for an app's own vocabulary — the staged vector first, exactly as every
5774    /// other image channel resolves (docs/vectors.md).
5775    fn menu_image(icon: Option<&day_spec::Icon>) -> Option<Retained<objc2_ui_kit::UIImage>> {
5776        match icon? {
5777            day_spec::Icon::Symbol(s) => {
5778                let name = day_spec::sf_symbol_name(*s);
5779                (!name.is_empty())
5780                    .then(|| objc2_ui_kit::UIImage::systemImageNamed(&NSString::from_str(name)))
5781                    .flatten()
5782            }
5783            // The asset catalog first (an app's vectors and images are staged there, and a
5784            // file path only exists in a `day launch` tree), then the loose-file fallbacks.
5785            day_spec::Icon::Image(name) => load_bundled_uiimage(name).or_else(|| {
5786                let path = day_spec::resource::resolve_vector_svg(name)
5787                    .or_else(|| day_spec::resource::resolve_image_file(name))?;
5788                objc2_ui_kit::UIImage::imageWithContentsOfFile(&NSString::from_str(
5789                    &path.to_string_lossy(),
5790                ))
5791            }),
5792        }
5793    }
5794
5795    fn ui_action(
5796        mtm: MainThreadMarker,
5797        title: &str,
5798        enabled: bool,
5799        checked: Option<bool>,
5800        icon: Option<&day_spec::Icon>,
5801        handler: impl Fn() + 'static,
5802    ) -> Retained<UIMenuElement> {
5803        let block = block2::RcBlock::new(move |_a: NonNull<UIAction>| handler());
5804        let image = menu_image(icon);
5805        let action = unsafe {
5806            UIAction::actionWithTitle_image_identifier_handler(
5807                &NSString::from_str(title),
5808                image.as_deref(),
5809                None,
5810                block2::RcBlock::as_ptr(&block),
5811                mtm,
5812            )
5813        };
5814        if !enabled {
5815            unsafe { action.setAttributes(UIMenuElementAttributes::Disabled) };
5816        }
5817        // UIKit's own on/off state, so the item gets the system check mark and reserves its
5818        // column when off — the same look UIKit gives a picker's selected row (docs/menus.md).
5819        if let Some(on) = checked {
5820            action.setState(if on {
5821                objc2_ui_kit::UIMenuElementState::On
5822            } else {
5823                objc2_ui_kit::UIMenuElementState::Off
5824            });
5825        }
5826        Retained::into_super(action)
5827    }
5828
5829    /// Lower one run of items (already split on separators) into `UIMenuElements`.
5830    fn ui_menu_elements(
5831        mtm: MainThreadMarker,
5832        items: &[day_spec::MenuItem],
5833    ) -> Vec<Retained<UIMenuElement>> {
5834        let mut out: Vec<Retained<UIMenuElement>> = Vec::new();
5835        for item in items {
5836            match item {
5837                day_spec::MenuItem::Separator => {}
5838                day_spec::MenuItem::Submenu { label, items, .. } => {
5839                    out.push(Retained::into_super(build_ui_menu(mtm, label, items)));
5840                }
5841                day_spec::MenuItem::Action {
5842                    action: dispatch,
5843                    label,
5844                    shortcut: _,
5845                    enabled,
5846                    checked,
5847                    role,
5848                    icon,
5849                    ..
5850                } => {
5851                    if let Some(role) = role {
5852                        let title = if label.is_empty() {
5853                            ui_role_label(*role).to_string()
5854                        } else {
5855                            label.clone()
5856                        };
5857                        let sel = ui_role_selector(*role);
5858                        let id = *dispatch;
5859                        out.push(ui_action(
5860                            mtm,
5861                            &title,
5862                            *enabled,
5863                            *checked,
5864                            icon.as_ref(),
5865                            move || {
5866                                if let Some(sel) = sel {
5867                                    let app = UIApplication::sharedApplication(mtm);
5868                                    unsafe {
5869                                        app.sendAction_to_from_forEvent(sel, None, None, None);
5870                                    }
5871                                } else if id != 0 {
5872                                    // No UIKit nav host for this role (Undo/Redo): the item
5873                                    // carries the day dispatcher id instead — the same route a
5874                                    // labeled action takes, landing on the installed undo bridge.
5875                                    emit(WINDOW_NODE, Event::MenuAction(id));
5876                                }
5877                            },
5878                        ));
5879                    } else {
5880                        let id = *dispatch;
5881                        out.push(ui_action(
5882                            mtm,
5883                            label,
5884                            *enabled,
5885                            *checked,
5886                            icon.as_ref(),
5887                            move || {
5888                                emit(WINDOW_NODE, Event::MenuAction(id));
5889                            },
5890                        ));
5891                    }
5892                }
5893            }
5894        }
5895        out
5896    }
5897
5898    /// Build a `UIMenu` whose children preserve separators as inline sections (the native iOS look).
5899    fn build_ui_menu(
5900        mtm: MainThreadMarker,
5901        title: &str,
5902        items: &[day_spec::MenuItem],
5903    ) -> Retained<UIMenu> {
5904        // Split on separators; each run becomes an inline submenu so dividers render natively.
5905        let groups: Vec<&[day_spec::MenuItem]> = items
5906            .split(|i| matches!(i, day_spec::MenuItem::Separator))
5907            .filter(|g| !g.is_empty())
5908            .collect();
5909        let children: Vec<Retained<UIMenuElement>> = if groups.len() <= 1 {
5910            ui_menu_elements(mtm, items)
5911        } else {
5912            groups
5913                .into_iter()
5914                .map(|g| {
5915                    let elems = ui_menu_elements(mtm, g);
5916                    let arr = objc2_foundation::NSArray::from_retained_slice(&elems);
5917                    let inline = unsafe {
5918                        UIMenu::menuWithTitle_image_identifier_options_children(
5919                            &NSString::from_str(""),
5920                            None,
5921                            None,
5922                            UIMenuOptions::DisplayInline,
5923                            &arr,
5924                            mtm,
5925                        )
5926                    };
5927                    Retained::into_super(inline)
5928                })
5929                .collect()
5930        };
5931        let arr = objc2_foundation::NSArray::from_retained_slice(&children);
5932        unsafe { UIMenu::menuWithTitle_children(&NSString::from_str(title), &arr, mtm) }
5933    }
5934
5935    // -----------------------------------------------------------------------
5936    // Navigation (docs/navigation.md): UINavigationController child-contained in the
5937    // root VC. Each page = UIViewController whose view pins a content subview to the
5938    // safe area; the content view is Day's handle (its frame is native-owned).
5939    // -----------------------------------------------------------------------
5940
5941    /// The adaptive half of a nav host (docs/size-classes.md) — present only when the host was
5942    /// lowered as `Split`. A host lowered `Stack` is a stack at every size (a nested `nav_stack()`
5943    /// under a split host), and realizes as a plain navigation controller instead: a
5944    /// `UISplitViewController` assumes it owns the window, and nesting one inside a pane breaks
5945    /// its layout (the embedded-split trap).
5946    struct SplitParts {
5947        /// The adaptive host. `NavState::nav` is its SECONDARY column; the sidebar page's
5948        /// controller is its primary. Retained because a view holds no strong reference to its
5949        /// controller, and this one owns the columns and the collapse behavior.
5950        split_vc: Retained<objc2_ui_kit::UISplitViewController>,
5951        /// The PRIMARY column's navigation controller — the sidebar page's stack.
5952        ///
5953        /// It has to be a navigation controller, not a bare view controller: UIKit merges the
5954        /// secondary column into the primary's stack when it collapses, and with nothing to merge
5955        /// into it drops the navigation bar entirely — the collapsed list rendered with no title
5956        /// and no bar button. Which of the two is live therefore depends on the presentation,
5957        /// which is what `active_nav` answers (docs/size-classes.md).
5958        primary_nav: Retained<DayNavController>,
5959        /// The SUPPLEMENTARY column's controller (docs/navigation.md), `Some` only on a
5960        /// triple-column host (`NavProps::list_width`): the `Pane::List` page's stack. While
5961        /// collapsed, the pieces layer interposes its root between the sidebar root and the
5962        /// detail (`NavPatch::ListInStack`) and the `vcs` mirror carries it like any page.
5963        supplementary_nav: Option<Retained<DayNavController>>,
5964        /// The app's content-list width (`NavProps::list_width`), `Some` when the app declares
5965        /// a content-list pane: the supplementary column's width on a triple-column host.
5966        list_width: Option<f64>,
5967        /// Whether the destination in force shows the content list (the last
5968        /// `NavPatch::ListVisible`). A split's column count is fixed at creation, it never
5969        /// shows the primary without the supplementary, and a controller cannot be re-mounted
5970        /// in another of its columns (UIKit drops it) — so a list-backed destination gets a
5971        /// TRIPLE-column host and a list-less one a DOUBLE-column host, and a change between
5972        /// the two while expanded rebuilds the host (`rehost_split`, docs/navigation.md), the
5973        /// way SwiftUI rebuilds a `NavigationSplitView` whose column count changes.
5974        list_shown: std::cell::Cell<bool>,
5975        /// The host's own view (Day's handle for the node), a plain container the split's
5976        /// view fills. Stable across a rebuild, which is what keeps the handle valid.
5977        container: Retained<UIView>,
5978        /// The `Pane::List` page's controller, retained at `insert` — the RELIABLE identity
5979        /// for the collapse/expand bookkeeping. While merged, the supplementary column's own
5980        /// stack is empty (UIKit moved the controller into the primary's), so reading
5981        /// `supplementary_nav.viewControllers()` at a transition answers nothing; this
5982        /// reference is what the mirror rebase and the expand rebuild key on.
5983        list_vc: std::cell::RefCell<Option<Retained<UIViewController>>>,
5984        /// Triple-column only: a blank root the SECONDARY stack holds whenever Day has no
5985        /// detail page. Older runtimes (iOS 16) throw "Cannot display a nested
5986        /// `UINavigationController` with zero viewControllers" the moment a collapse nests an
5987        /// empty column; the placeholder keeps the nav non-empty and `apply_ops` swaps
5988        /// it for real pages. Never in the `vcs` mirror.
5989        secondary_placeholder: Option<Retained<UIViewController>>,
5990        split_delegate: Retained<DaySplitDelegate>,
5991    }
5992
5993    struct NavState {
5994        nav: Retained<DayNavController>,
5995        host_node: NodeId,
5996        /// `Some` for the adaptive (Split-lowered) host, `None` for a plain stack host.
5997        split: Option<SplitParts>,
5998        /// Set around Day's OWN calls to a pop method (the collapsed triple column's pops),
5999        /// so `DayNavController`'s pop overrides — the observation point for the user's back
6000        /// button, swipe and history menu — know those are not the user's. There is no mirror
6001        /// of the stack (docs/navigation.md): UIKit's `viewControllers` is read whenever a
6002        /// change is computed, and a page that has already left it is simply not there.
6003        day_pop: std::cell::Cell<bool>,
6004        /// Pending column request only; native viewControllers remains the stack authority.
6005        pending_list: std::cell::Cell<Option<(u64, bool)>>,
6006        column_request: std::cell::Cell<Option<std::time::Instant>>,
6007        delegate: Retained<DayNavDelegate>,
6008        /// Inline search (docs/search.md): the controller lives on the ROOT page's navigation
6009        /// item, so pulling the top-level list down reveals it. `None` when the surface is not
6010        /// searchable or its placement resolved elsewhere. Retained here because the navigation
6011        /// item does not own the updater.
6012        search_hides_on_scroll: bool,
6013        search_initially_hidden: bool,
6014        search: Option<(
6015            Retained<objc2_ui_kit::UISearchController>,
6016            Retained<DaySearchUpdater>,
6017        )>,
6018    }
6019
6020    impl NavState {
6021        /// Presentation callbacks can run before this state is registered. Read UIKit's
6022        /// settled answer when routing operations instead of caching that initial callback.
6023        fn is_collapsed(&self) -> bool {
6024            self.split
6025                .as_ref()
6026                .is_some_and(|parts| unsafe { parts.split_vc.isCollapsed() })
6027        }
6028
6029        /// The navigation controller that currently OWNS the stack (docs/size-classes.md).
6030        ///
6031        /// Collapsed, UIKit has merged the secondary's pages into the primary's, so a push has to
6032        /// land there; expanded, the two are separate and details belong to the secondary.
6033        /// Everything that pushes, pops, or inspects the stack goes through this rather than
6034        /// naming a column, so the same code is right in both presentations.
6035        fn active_nav(&self) -> Retained<DayNavController> {
6036            match &self.split {
6037                Some(parts) if self.is_collapsed() => parts.primary_nav.clone(),
6038                _ => self.nav.clone(),
6039            }
6040        }
6041    }
6042
6043    struct NavPageIvars {
6044        node: NodeId,
6045        immersive: bool,
6046    }
6047
6048    thread_local! {
6049        /// A re-measure for a text size change is posted and has not run yet.
6050        static TEXT_SIZE_PENDING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
6051        static APPEARANCE_PENDING: Cell<bool> = const { Cell::new(false) };
6052    }
6053
6054    /// Re-measure everything Day laid out (`day_core::note_text_size_changed`) on the next turn
6055    /// of the main queue, once: by then every label in the windows has taken the new size from
6056    /// its own trait change. Coalesced, since one change reaches many views.
6057    fn schedule_text_size_remeasure() {
6058        if TEXT_SIZE_PENDING.with(|p| p.replace(true)) {
6059            return;
6060        }
6061        dispatch2::DispatchQueue::main().exec_async(|| {
6062            TEXT_SIZE_PENDING.with(|p| p.set(false));
6063            day_spec::ffi_guard::contain((), refresh_label_paragraphs);
6064            day_spec::ffi_guard::contain((), day_core::note_text_size_changed);
6065        });
6066    }
6067
6068    /// Native system colors update themselves; app palette closures need Day's signal too.
6069    /// Defer and coalesce across pages/windows so UIKit can finish propagating traits and
6070    /// a synchronous setOverrideUserInterfaceStyle never re-enters the borrowed Day tree.
6071    fn schedule_appearance_refresh() {
6072        if APPEARANCE_PENDING.with(|p| p.replace(true)) {
6073            return;
6074        }
6075        dispatch2::DispatchQueue::main().exec_async(|| {
6076            APPEARANCE_PENDING.with(|p| p.set(false));
6077            day_spec::ffi_guard::contain((), day_core::note_appearance_changed);
6078        });
6079    }
6080
6081    /// A Day host view's traits changed: if the text size category is not the one it had, the
6082    /// labels under it have just taken a new size (docs/list.md "Row heights"). The app-wide
6083    /// notification covers the views in a window when the setting changes; this covers the
6084    /// rest, a tab or a page that was off screen then and only gets the new traits when it is
6085    /// shown, after the re-measure that notification ran.
6086    fn note_host_traits(view: &UIView, previous: Option<&objc2_ui_kit::UITraitCollection>) {
6087        use objc2_ui_kit::UITraitEnvironment as _;
6088        let traits = view.traitCollection();
6089        if previous
6090            .is_none_or(|old| unsafe { old.userInterfaceStyle() != traits.userInterfaceStyle() })
6091        {
6092            schedule_appearance_refresh();
6093        }
6094        let Some(previous) = previous else { return };
6095        let now = unsafe { traits.preferredContentSizeCategory() };
6096        let before = unsafe { previous.preferredContentSizeCategory() };
6097        if !now.isEqualToString(&before) {
6098            schedule_text_size_remeasure();
6099        }
6100    }
6101
6102    define_class!(
6103        #[unsafe(super(UIView))]
6104        #[thread_kind = MainThreadOnly]
6105        #[name = "DayNavPageView"]
6106        #[ivars = NavPageIvars]
6107        struct DayNavPageView;
6108
6109        impl DayNavPageView {
6110            /// Re-lay whenever the page joins (or rejoins) a window.
6111            ///
6112            /// `safeAreaInsets` is only meaningful for a view that is actually IN a window —
6113            /// UIKit does not recompute it for the off-screen members of a navigation stack. After
6114            /// a split collapse the sidebar page sits at the bottom of the merged stack, so it
6115            /// kept the insets it had in the other orientation (a landscape notch inset of 100pt
6116            /// applied in portrait). Reporting on entry is what makes the geometry right at the
6117            /// moment it starts to matter (docs/size-classes.md).
6118            #[unsafe(method(didMoveToWindow))]
6119            fn did_move_to_window(&self) {
6120                let _: () = unsafe { msg_send![super(self), didMoveToWindow] };
6121                if unsafe { self.window() }.is_some() {
6122                    self.setNeedsLayout();
6123                }
6124            }
6125
6126            /// The designated change hook for the insets themselves: a page can gain or lose
6127            /// bar height with its bounds unchanged (standard vs large-title bar as it moves
6128            /// between columns), and `layoutSubviews` alone never re-fires for that.
6129            #[unsafe(method(safeAreaInsetsDidChange))]
6130            fn safe_area_insets_did_change(&self) {
6131                let _: () = unsafe { msg_send![super(self), safeAreaInsetsDidChange] };
6132                self.setNeedsLayout();
6133            }
6134
6135            #[unsafe(method(traitCollectionDidChange:))]
6136            fn trait_collection_did_change(
6137                &self,
6138                previous: Option<&objc2_ui_kit::UITraitCollection>,
6139            ) {
6140                let _: () = unsafe { msg_send![super(self), traitCollectionDidChange: previous] };
6141                day_spec::ffi_guard::contain((), || note_host_traits(self, previous));
6142            }
6143
6144            #[unsafe(method(layoutSubviews))]
6145            fn layout_subviews(&self) {
6146                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
6147                // The FrameChanged report dispatches day-core's relayout — contained (§8.5).
6148                day_spec::ffi_guard::contain((), || {
6149                    // Out of any window the insets below are stale, and a report built from
6150                    // them would size the content for wherever this page last WAS.
6151                    if unsafe { self.window() }.is_none() {
6152                        return;
6153                    }
6154                    // Where the content goes depends on what it IS (§7.7). A page whose content
6155                    // resolves to one scroll view — the sidebar list, a `scroll`-rooted detail,
6156                    // a tree — fills the page's whole bounds, bars included, and UIKit's own
6157                    // inset adjustment starts its CONTENT below the bar and lets it run under
6158                    // the translucent chrome on the way past: Settings, Mail and every other
6159                    // list-shaped screen on the platform. Everything else is pinned inside the
6160                    // safe area, because a form or a canvas has no scroll insets to absorb a bar
6161                    // and would put its first row under it.
6162                    let bounds = self.bounds();
6163                    let insets = self.safeAreaInsets();
6164                    let subs = unsafe { self.subviews() };
6165                    let content = subs.firstObject();
6166                    let full_bleed = content.as_ref().is_some_and(|c| scroll_leaf(c));
6167                    // Immersive pages opt out of the TOP inset only. The bottom
6168                    // remains scrollable above the home indicator and keyboard.
6169                    let mut layout_insets = insets;
6170                    if self.ivars().immersive {
6171                        layout_insets.top = 0.0;
6172                        if full_bleed
6173                            && let Some(scroll) = content.as_ref().and_then(|c| first_content_scroll(c, 12))
6174                        {
6175                            unsafe {
6176                                scroll.setContentInsetAdjustmentBehavior(
6177                                    objc2_ui_kit::UIScrollViewContentInsetAdjustmentBehavior::Never,
6178                                );
6179                                let bottom = UIEdgeInsets { top: 0.0, left: 0.0, bottom: insets.bottom, right: 0.0 };
6180                                if scroll.contentInset() != bottom {
6181                                    scroll.setContentInset(bottom);
6182                                }
6183                                scroll.setVerticalScrollIndicatorInsets(insets);
6184                                // iOS 26 adds a frosted scroll-edge band independently of
6185                                // navigation-bar appearance. Immersive artwork stays clear.
6186                                if os_at_least(26) {
6187                                    scroll.topEdgeEffect().setHidden(true);
6188                                }
6189                            }
6190                        }
6191                    }
6192                    let frame = content_frame(bounds, layout_insets, full_bleed);
6193                    if let Some(content) = content {
6194                        unsafe { content.setFrame(frame) };
6195                        if *DIAG_NAV {
6196                            let a = content.frame();
6197                            log::debug!(
6198                                "DAYDIAG   applied node={} nsubs={} content=({},{} {}x{})",
6199                                self.ivars().node.0, subs.count(),
6200                                a.origin.x, a.origin.y, a.size.width, a.size.height,
6201                            );
6202                        }
6203                    }
6204                    if *DIAG_NAV {
6205                        let sup = unsafe { self.superview() }.map_or(bounds, |v| v.bounds());
6206                        let winf = unsafe { self.convertRect_toView(bounds, None) };
6207                        log::debug!(
6208                            "DAYDIAG page node={} bounds={}x{} win=({},{} {}x{}) safe(t{} b{} l{} r{}) bleed={} -> report {}x{} super={}x{} hidden={}",
6209                            self.ivars().node.0,
6210                            bounds.size.width, bounds.size.height,
6211                            winf.origin.x, winf.origin.y, winf.size.width, winf.size.height,
6212                            insets.top, insets.bottom, insets.left, insets.right,
6213                            full_bleed,
6214                            frame.size.width, frame.size.height,
6215                            sup.size.width, sup.size.height,
6216                            self.isHidden(),
6217                        );
6218                    }
6219                    emit(
6220                        self.ivars().node,
6221                        Event::FrameChanged(Size::new(frame.size.width, frame.size.height)),
6222                    );
6223                });
6224            }
6225        }
6226    );
6227
6228    impl DayNavPageView {
6229        fn new(mtm: MainThreadMarker, node: NodeId, immersive: bool) -> Retained<Self> {
6230            let this = Self::alloc(mtm).set_ivars(NavPageIvars { node, immersive });
6231            let v: Retained<Self> = unsafe { msg_send![super(this), init] };
6232            // GROUPED, not plain. iOS gives content two grounds and they are a matched pair:
6233            // `systemGroupedBackground` behind, `secondarySystemGroupedBackground` for the cards
6234            // that sit on it — the pairing every Settings-shaped screen and every inset-grouped
6235            // list uses, and the one that makes a split's two columns read as one surface rather
6236            // than two white sheets meeting at a seam. `SurfaceRole::SectionCard` takes the other
6237            // half; changing one without the other leaves grey on grey.
6238            unsafe { v.setBackgroundColor(Some(&UIColor::systemGroupedBackgroundColor())) };
6239            v
6240        }
6241    }
6242
6243    /// Whether a page's content is one thing that absorbs the bars itself — the shape that
6244    /// fills the page's bounds instead of the safe area (`DayNavPageView::layoutSubviews`).
6245    ///
6246    /// Walks the chain of single-child wrappers Day's layout leaves between the content view and
6247    /// its leaf (the sidebar is `column((menu,))`, a detail is often `scroll(column(…))`), and
6248    /// answers yes when the chain reaches either a `UIScrollView` — which is what a list, a
6249    /// tree, a text view and a `scroll` piece all are underneath — or a navigation host's view
6250    /// (a `UINavigationController`'s, or a split host's container), which passes the bars on to
6251    /// its own pages: a tab whose content is a nav host must reach under the tab bar, or the
6252    /// list inside it never can. A page with two children at any level is neither: a heading
6253    /// over a list has nowhere to absorb a bar, so that page keeps the safe-area pin.
6254    /// The frame a page or the window root gives its content inside `bounds`, given the safe
6255    /// area `insets` there. Pinned, all four insets pad it. Bleeding (`scroll_leaf`), only the
6256    /// SIDES still do: a bar is vertical chrome, and a scroll view absorbs it as a content
6257    /// inset on the way past — a side inset never is. iPadOS 26 floats the split view's
6258    /// sidebar over the secondary column and reports it as that column's left safe area
6259    /// (330pt on an iPad Pro), and a landscape iPhone reports its sensor housing the same way;
6260    /// a scroll view laid out across either puts its content under the sidebar, and the user
6261    /// sees a detail that runs on beneath the list. So the sides pad the frame in both modes,
6262    /// and the content moves aside when the sidebar is shown, which is what `FrameChanged`
6263    /// then reports (docs/size-classes.md).
6264    fn content_frame(bounds: CGRect, insets: UIEdgeInsets, bleed: bool) -> CGRect {
6265        let (top, bottom) = if bleed {
6266            (0.0, 0.0)
6267        } else {
6268            (insets.top, insets.bottom)
6269        };
6270        CGRect::new(
6271            CGPoint::new(insets.left, top),
6272            CGSize::new(
6273                (bounds.size.width - insets.left - insets.right).max(0.0),
6274                (bounds.size.height - top - bottom).max(0.0),
6275            ),
6276        )
6277    }
6278
6279    fn scroll_leaf(content: &UIView) -> bool {
6280        let mut view = content.retain();
6281        // Day's wrappers are shallow; a bound keeps a pathological tree from being walked twice
6282        // a frame during a resize.
6283        for _ in 0..6 {
6284            let subs = unsafe { view.subviews() };
6285            if subs.count() != 1 {
6286                return false;
6287            }
6288            let Some(child) = subs.firstObject() else {
6289                return false;
6290            };
6291            // A view controller's view answers to its controller: a nav or split host here
6292            // means the bars are that host's pages' business.
6293            let hosted = unsafe { child.nextResponder() }.is_some_and(|r| {
6294                r.downcast_ref::<objc2_ui_kit::UINavigationController>()
6295                    .is_some()
6296                    || r.downcast_ref::<objc2_ui_kit::UISplitViewController>()
6297                        .is_some()
6298                    || r.downcast_ref::<objc2_ui_kit::UITabBarController>()
6299                        .is_some()
6300            });
6301            if hosted {
6302                return true;
6303            }
6304            match child.downcast::<UIScrollView>() {
6305                Ok(_) => return true,
6306                Err(v) => view = v,
6307            }
6308        }
6309        false
6310    }
6311
6312    /// Schedule a re-pin of the page (or window holder) whose content chain `changed` sits in.
6313    ///
6314    /// Whether a page pins its content inside the safe area or runs it edge to edge depends on
6315    /// what the content IS (`scroll_leaf`), and that changes when a child joins or leaves the
6316    /// chain: a reader cover swapping its web view for a settings form kept the web view's
6317    /// edge-to-edge frame, and the form's header went under the status bar. `scroll_leaf`
6318    /// looks six single-child levels below a page's content view, so walking that far up
6319    /// finds every page whose answer the change can move. Only scheduled: the pass runs
6320    /// after the tree edit lands.
6321    fn reask_content_frame(changed: &UIView) {
6322        let mut view = Some(changed.retain());
6323        for _ in 0..8 {
6324            let Some(v) = view else {
6325                return;
6326            };
6327            if v.downcast_ref::<DayNavPageView>().is_some()
6328                || v.downcast_ref::<DayHolderView>().is_some()
6329            {
6330                v.setNeedsLayout();
6331                return;
6332            }
6333            view = unsafe { v.superview() };
6334        }
6335    }
6336
6337    struct NavControllerIvars {
6338        host: std::cell::Cell<usize>,
6339        guarded: std::cell::Cell<bool>,
6340    }
6341
6342    // A UINavigationController subclass that intercepts the BACK BUTTON via its own bar-delegate
6343    // `shouldPop` (docs/navigation.md). A nav controller IS its bar's delegate, so overriding
6344    // the method here is the sanctioned way to veto a back-button pop. While `guarded`, we veto
6345    // (return false) and emit `NavBack { already_popped: false }` so Rust's guard decides — the
6346    // sync/async mismatch resolves because the native pop simply never happens; Rust performs it
6347    // on `Proceed`. The swipe is a separate path (interactivePopGestureRecognizer), disabled in
6348    // the GuardTop patch.
6349    define_class!(
6350        #[unsafe(super(UINavigationController))]
6351        #[thread_kind = MainThreadOnly]
6352        #[name = "DayNavController"]
6353        #[ivars = NavControllerIvars]
6354        struct DayNavController;
6355
6356        unsafe impl NSObjectProtocol for DayNavController {}
6357        unsafe impl UIBarPositioningDelegate for DayNavController {}
6358
6359        unsafe impl UINavigationBarDelegate for DayNavController {
6360            #[unsafe(method(navigationBar:shouldPopItem:))]
6361            fn should_pop(&self, bar: &UINavigationBar, _item: &UINavigationItem) -> bool {
6362                // Contained (§8.5): a panic can only arise on the guarded branch, whose
6363                // intended answer is the veto — so the default is `false`.
6364                day_spec::ffi_guard::contain(false, || {
6365                    // The host's NODE, resolved through NAV_STATE — `ivars().host` is the host
6366                    // VIEW's pointer, which is the key of that map and not a `NodeId` at all.
6367                    // Casting it to one addressed a node that has never existed, so day-core
6368                    // never saw the event, the guard never ran, and the veto below stood
6369                    // forever: tapping back did nothing at all. Every other `NavBack` emit here
6370                    // already went through `state.host_node`; this was the one that did not, and
6371                    // it is invisible to the walkthrough because `nav_back:` drives day-core's
6372                    // rail directly and never reaches `shouldPopItem:`. Long-pressing the back
6373                    // button worked for the same reason — the history menu pops the controller
6374                    // itself, so the settle path reports it with the right node.
6375                    let node = NAV_STATE.with(|m| {
6376                        m.borrow()
6377                            .get(&self.ivars().host.get())
6378                            .map(|s| s.host_node)
6379                    });
6380                    match (self.ivars().guarded.get(), node) {
6381                        (true, Some(node)) => {
6382                            emit(
6383                                node,
6384                                Event::NavBack {
6385                                    already_popped: false,
6386                                },
6387                            );
6388                            // UIKit dims the back button after a vetoed pop; restore the bar's
6389                            // opacity on the next runloop turn (the documented shouldPop cosmetic
6390                            // fix).
6391                            let bar: Retained<UINavigationBar> = Retained::from(bar);
6392                            modal_after_idle(move || {
6393                                for v in &unsafe { bar.subviews() } {
6394                                    unsafe { v.setAlpha(1.0) };
6395                                }
6396                            });
6397                            false
6398                        }
6399                        // Not guarded, or a host this bar no longer belongs to: let UIKit pop.
6400                        // Vetoing with no one to answer is the one outcome that strands the
6401                        // user, so an unresolvable host fails OPEN.
6402                        _ => true,
6403                    }
6404                })
6405            }
6406        }
6407
6408        // The swipe's own gate, the counterpart of `shouldPopItem:` for the back button. The
6409        // recognizer takes one delegate, so this one also answers UIKit's two stock questions —
6410        // more than the root on the stack, and no transition already running — which the
6411        // default delegate answered before it was replaced. While guarded, the swipe asks Day's
6412        // guard exactly as the button does and starts nothing itself; the gesture stays
6413        // enabled, so a guard that says Proceed pops through Day's rail and the next swipe
6414        // works again without anyone re-enabling anything.
6415        unsafe impl UIGestureRecognizerDelegate for DayNavController {
6416            #[unsafe(method(gestureRecognizerShouldBegin:))]
6417            fn gesture_should_begin(&self, _g: &objc2_ui_kit::UIGestureRecognizer) -> bool {
6418                day_spec::ffi_guard::contain(false, || {
6419                    let count = unsafe { self.viewControllers() }.count();
6420                    if count < 2 || unsafe { self.transitionCoordinator() }.is_some() {
6421                        return false;
6422                    }
6423                    if self.ivars().guarded.get() {
6424                        let node = NAV_STATE.with(|m| {
6425                            m.borrow()
6426                                .get(&self.ivars().host.get())
6427                                .map(|s| s.host_node)
6428                        });
6429                        if let Some(node) = node {
6430                            emit(
6431                                node,
6432                                Event::NavBack {
6433                                    already_popped: false,
6434                                },
6435                            );
6436                            return false;
6437                        }
6438                        // Fail OPEN, as the button does.
6439                    }
6440                    true
6441                })
6442            }
6443        }
6444
6445        // The observation point for the user's back (docs/navigation.md): UIKit routes the
6446        // back button here once `shouldPopItem:` agrees, the swipe here under an interactive
6447        // transition, and the history menu to `popToViewController:`. Day's own stack changes
6448        // are `setViewControllers:` and never arrive here; its two pops on a collapsed triple
6449        // column announce themselves through `with_day_pop`. So a call that reaches super
6450        // with the flag clear IS the user's, and `observe_user_pop` reports it once its
6451        // transition has actually happened.
6452        impl DayNavController {
6453            #[unsafe(method_id(childViewControllerForStatusBarStyle))]
6454            fn status_bar_style_child(&self) -> Option<Retained<UIViewController>> {
6455                unsafe { self.topViewController() }
6456            }
6457
6458            #[unsafe(method_id(popViewControllerAnimated:))]
6459            fn pop_view_controller(&self, animated: bool) -> Option<Retained<UIViewController>> {
6460                let popped: Option<Retained<UIViewController>> =
6461                    unsafe { msg_send![super(self), popViewControllerAnimated: animated] };
6462                if let Some(p) = &popped {
6463                    self.note_pop(vec![p.clone()]);
6464                }
6465                popped
6466            }
6467
6468            #[unsafe(method_id(popToViewController:animated:))]
6469            fn pop_to_view_controller(
6470                &self,
6471                vc: &UIViewController,
6472                animated: bool,
6473            ) -> Option<Retained<objc2_foundation::NSArray<UIViewController>>> {
6474                let popped: Option<Retained<objc2_foundation::NSArray<UIViewController>>> = unsafe {
6475                    msg_send![super(self), popToViewController: vc, animated: animated]
6476                };
6477                if let Some(p) = popped.as_ref().filter(|p| p.count() > 0) {
6478                    self.note_pop(p.iter().collect());
6479                }
6480                popped
6481            }
6482
6483            #[unsafe(method_id(popToRootViewControllerAnimated:))]
6484            fn pop_to_root_view_controller(
6485                &self,
6486                animated: bool,
6487            ) -> Option<Retained<objc2_foundation::NSArray<UIViewController>>> {
6488                let popped: Option<Retained<objc2_foundation::NSArray<UIViewController>>> =
6489                    unsafe { msg_send![super(self), popToRootViewControllerAnimated: animated] };
6490                if let Some(p) = popped.as_ref().filter(|p| p.count() > 0) {
6491                    self.note_pop(p.iter().collect());
6492                }
6493                popped
6494            }
6495
6496            /// The swipe recognizer exists once the view does; give it this controller as its
6497            /// gate (`gestureRecognizerShouldBegin:` above).
6498            #[unsafe(method(viewDidLoad))]
6499            fn view_did_load(&self) {
6500                let _: () = unsafe { msg_send![super(self), viewDidLoad] };
6501                if let Some(g) = unsafe { self.interactivePopGestureRecognizer() } {
6502                    let delegate =
6503                        ProtocolObject::<dyn objc2_ui_kit::UIGestureRecognizerDelegate>::from_ref(
6504                            self,
6505                        );
6506                    unsafe { g.setDelegate(Some(delegate)) };
6507                }
6508            }
6509        }
6510    );
6511
6512    impl DayNavController {
6513        fn new(mtm: MainThreadMarker, host: usize) -> Retained<Self> {
6514            let this = Self::alloc(mtm).set_ivars(NavControllerIvars {
6515                host: std::cell::Cell::new(host),
6516                guarded: std::cell::Cell::new(false),
6517            });
6518            let this: Retained<Self> = unsafe { msg_send![super(this), init] };
6519            let bar = unsafe { this.navigationBar() };
6520            configure_navigation_bar(&bar, mtm);
6521            this
6522        }
6523
6524        /// A pop just went through one of the overrides above: the user's, unless Day
6525        /// announced its own (`with_day_pop`).
6526        fn note_pop(&self, popped: Vec<Retained<UIViewController>>) {
6527            let host = self.ivars().host.get();
6528            // A size-class transition is UIKit rearranging its own columns, not the user going
6529            // back: expanding a split view takes the detail back out of the merged stack with
6530            // this very call. Reported as a back it pops day's model, which deselects the row
6531            // the user was on, and the widened split then fills its empty detail with the first
6532            // row — the page they were reading replaced by the first one in the list.
6533            if CLASS_TRANSITIONS.with(std::cell::Cell::get) > 0 {
6534                if *DIAG_NAV {
6535                    log::debug!(
6536                        "DAYDIAG pop during a size-class transition: UIKit's own, not reported"
6537                    );
6538                }
6539                return;
6540            }
6541            let day = NAV_STATE.with(|m| m.borrow().get(&host).map(|s| s.day_pop.get()));
6542            // `Some(true)` is Day's own pop; `None` a controller no host owns any more.
6543            if day == Some(false) {
6544                observe_user_pop(host, self, popped);
6545            }
6546        }
6547
6548        /// The back button's own path, without the button: ask `shouldPopItem:` — where the
6549        /// guard's veto and its `NavBack` live — and pop when it agrees. `Toolkit::native_back`
6550        /// runs this, so dayscript's `nav_back: { native: true }` covers the code a tap runs.
6551        /// `true` when the affordance did something: popped, or handed a guarded back to Day.
6552        fn press_back(&self) -> bool {
6553            let bar = unsafe { self.navigationBar() };
6554            let Some(item) = (unsafe { bar.topItem() }) else {
6555                return false;
6556            };
6557            if unsafe { self.viewControllers() }.count() < 2 {
6558                return false;
6559            }
6560            // Asked the way the bar asks it — through the selector — so the guard's veto and
6561            // its `NavBack` run as they do for a tap.
6562            let agreed: bool =
6563                unsafe { msg_send![self, navigationBar: &*bar, shouldPopItem: &*item] };
6564            if !agreed {
6565                return true;
6566            }
6567            unsafe { self.popViewControllerAnimated(!day_core::testing::fast_animations()) }
6568                .is_some()
6569        }
6570    }
6571
6572    struct NavDelegateIvars {
6573        host: std::cell::Cell<usize>,
6574    }
6575
6576    /// Inline search on a `.searchable()` surface (docs/search.md).
6577    ///
6578    /// A `UISearchController` on the ROOT page's `navigationItem`. Search is pinned by
6579    /// default; opting into initially hidden search uses a compact title and native drawer.
6580    /// It is not a
6581    /// toolbar item — the phones have no toolbar — so the placement resolver hands it here
6582    /// instead, and the field belongs to the navigation surface it filters.
6583    struct SearchUpdaterIvars {
6584        /// The nav host's day node, so edits emit against the surface that declared the search.
6585        node: std::cell::Cell<u64>,
6586        /// Suppresses the echo while day writes the field's text back into it.
6587        suppress: std::cell::Cell<bool>,
6588    }
6589
6590    define_class!(
6591        #[unsafe(super(NSObject))]
6592        #[thread_kind = MainThreadOnly]
6593        #[name = "DaySearchUpdater"]
6594        #[ivars = SearchUpdaterIvars]
6595        struct DaySearchUpdater;
6596
6597        unsafe impl NSObjectProtocol for DaySearchUpdater {}
6598
6599        unsafe impl UISearchResultsUpdating for DaySearchUpdater {
6600            #[unsafe(method(updateSearchResultsForSearchController:))]
6601            fn update(&self, sc: &objc2_ui_kit::UISearchController) {
6602                day_spec::ffi_guard::contain((), || {
6603                    if self.ivars().suppress.get() {
6604                        return;
6605                    }
6606                    let text = unsafe { sc.searchBar().text() }.map_or_default(|t| t.to_string());
6607                    emit(NodeId(self.ivars().node.get()), Event::SearchChanged(text));
6608                });
6609            }
6610        }
6611
6612        unsafe impl UIBarPositioningDelegate for DaySearchUpdater {}
6613
6614        unsafe impl UISearchBarDelegate for DaySearchUpdater {
6615            /// The Search key (docs/search.md): every edit has already been reported by
6616            /// `updateSearchResultsForSearchController:`, so this only says "run it now". The
6617            /// keyboard goes, as in Settings and Mail, so the results are not under it.
6618            #[unsafe(method(searchBarSearchButtonClicked:))]
6619            fn search_clicked(&self, bar: &objc2_ui_kit::UISearchBar) {
6620                day_spec::ffi_guard::contain((), || {
6621                    let text = unsafe { bar.text() }.map_or_default(|t| t.to_string());
6622                    emit(
6623                        NodeId(self.ivars().node.get()),
6624                        Event::SearchSubmitted(text),
6625                    );
6626                    let _ = bar.resignFirstResponder();
6627                });
6628            }
6629        }
6630    );
6631
6632    impl DaySearchUpdater {
6633        fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
6634            let this = Self::alloc(mtm).set_ivars(SearchUpdaterIvars {
6635                node: std::cell::Cell::new(node.0),
6636                suppress: std::cell::Cell::new(false),
6637            });
6638            unsafe { msg_send![super(this), init] }
6639        }
6640    }
6641
6642    // The split host's own delegate (docs/size-classes.md). UIKit owns the decision here — a
6643    // `UISplitViewController` collapses and expands on its own as the horizontal size class
6644    // changes, which on a Plus/Pro Max iPhone happens on every rotation — so Day OBSERVES and
6645    // reports rather than driving. Pushing a presentation back at it would be a second source of
6646    // truth racing UIKit's own collapse animation.
6647    define_class!(
6648        #[unsafe(super(NSObject))]
6649        #[thread_kind = MainThreadOnly]
6650        #[name = "DaySplitDelegate"]
6651        #[ivars = NavDelegateIvars]
6652        struct DaySplitDelegate;
6653
6654        unsafe impl NSObjectProtocol for DaySplitDelegate {}
6655
6656        unsafe impl UISplitViewControllerDelegate for DaySplitDelegate {
6657            #[unsafe(method(splitViewControllerDidCollapse:))]
6658            fn did_collapse(&self, _svc: &objc2_ui_kit::UISplitViewController) {
6659                day_spec::ffi_guard::contain((), || {
6660                    split_presentation_changed(self.ivars().host.get(), false);
6661                });
6662            }
6663
6664            #[unsafe(method(splitViewControllerDidExpand:))]
6665            fn did_expand(&self, _svc: &objc2_ui_kit::UISplitViewController) {
6666                day_spec::ffi_guard::contain((), || {
6667                    split_presentation_changed(self.ivars().host.get(), true);
6668                });
6669            }
6670
6671            /// Which column tops the collapsed stack (docs/navigation.md, docs/size-classes.md):
6672            /// Day's MIRROR answers, for a double-column host as much as a triple. UIKit's own
6673            /// proposal is not the same on every release — at launch, with the detail column
6674            /// holding the first destination, iOS 26 proposes the secondary (the page shows)
6675            /// and iOS 18 the primary (the sidebar shows over a page the model says is open,
6676            /// with nothing to pop) — so leaving it to the proposal made the first screen
6677            /// depend on the OS. The detail tops while one is actually pushed; on a triple
6678            /// host the content list tops while it belongs to the destination; otherwise the
6679            /// sidebar.
6680            #[unsafe(method(splitViewController:topColumnForCollapsingToProposedTopColumn:))]
6681            fn top_column_for_collapsing(
6682                &self,
6683                _svc: &objc2_ui_kit::UISplitViewController,
6684                proposed: objc2_ui_kit::UISplitViewControllerColumn,
6685            ) -> objc2_ui_kit::UISplitViewControllerColumn {
6686                day_spec::ffi_guard::contain(proposed, || {
6687                    NAV_STATE.with(|m| {
6688                        let m = m.borrow();
6689                        let Some(state) = m.get(&self.ivars().host.get()) else {
6690                            return proposed;
6691                        };
6692                        let Some(parts) = state.split.as_ref() else {
6693                            return proposed;
6694                        };
6695                        // The mirror, not the native count — a triple host's secondary holds
6696                        // a placeholder while no real detail page exists, and the placeholder
6697                        // must never top the collapsed stack. The content list tops it only
6698                        // while it belongs to the destination (`NavPatch::ListInStack`);
6699                        // a destination without one leaves the sidebar root on top, which
6700                        // is what a phone opening on such a section must show.
6701                        let detail =
6702                            !day_pages(&state.nav, parts.secondary_placeholder.as_deref()).is_empty();
6703                        let column = if detail {
6704                            objc2_ui_kit::UISplitViewControllerColumn::Secondary
6705                        } else if parts.supplementary_nav.is_some() && parts.list_shown.get() {
6706                            objc2_ui_kit::UISplitViewControllerColumn::Supplementary
6707                        } else {
6708                            objc2_ui_kit::UISplitViewControllerColumn::Primary
6709                        };
6710                        if *DIAG_NAV {
6711                            log::debug!(
6712                                "DAYDIAG collapse top column proposed={} chosen={} detail={detail} list_shown={}",
6713                                proposed.0,
6714                                column.0,
6715                                parts.list_shown.get()
6716                            );
6717                        }
6718                        column
6719                    })
6720                })
6721            }
6722        }
6723    );
6724
6725    impl DaySplitDelegate {
6726        fn new(mtm: MainThreadMarker, host: usize) -> Retained<Self> {
6727            let this = Self::alloc(mtm).set_ivars(NavDelegateIvars {
6728                host: std::cell::Cell::new(host),
6729            });
6730            unsafe { msg_send![super(this), init] }
6731        }
6732    }
6733
6734    /// UIKit collapsed or expanded the split host: reconcile stranded double-column
6735    /// pages and report the new presentation. Operations read the native presentation
6736    /// directly, including when this callback preceded navigation state registration.
6737    fn split_presentation_changed(host: usize, expanded: bool) {
6738        let plan = NAV_STATE.with(|m| {
6739            let mut m = m.borrow_mut();
6740            let state = m.get_mut(&host)?;
6741            let parts = state.split.as_ref()?;
6742            if *DIAG_NAV {
6743                log::debug!(
6744                    "DAYDIAG split {} primary={} secondary={} supplementary={:?}",
6745                    if expanded { "EXPANDED" } else { "COLLAPSED" },
6746                    unsafe { parts.primary_nav.viewControllers() }.count(),
6747                    unsafe { state.nav.viewControllers() }.count(),
6748                    parts
6749                        .supplementary_nav
6750                        .as_ref()
6751                        .map(|n| unsafe { n.viewControllers() }.count()),
6752                );
6753            }
6754            // Nothing rebuilds columns here: the collapsed stack is only ever driven through
6755            // UIKit's own APIs (`Act::Triple*`), so its bookkeeping stays intact and its own
6756            // expand puts every column back where it belongs.
6757            //
6758            // A DOUBLE-column collapse can leave the detail STRANDED: UIKit decides the merge
6759            // before Day's launch sync has put the first destination in the secondary column
6760            // (iOS 18 asks for the top column that early; iOS 26 asks after), so the merge
6761            // carries nothing and the page the model says is open sits in a hidden column
6762            // with the sidebar on top and nothing to pop. Finish the merge UIKit started:
6763            // whatever the secondary still holds goes on top of the primary's stack, which is
6764            // the shape the mirror already has. Applied outside this borrow (a stack change
6765            // re-enters the delegates).
6766            // Stranded means the primary holds nothing but the sidebar root while the
6767            // secondary holds pages. Nothing subtler is safe to read: after an iOS 26 collapse
6768            // the primary carries the sidebar plus the NESTED secondary controller (its pages
6769            // inside it, and the secondary still reporting them), so a membership test by
6770            // identity would move a page UIKit had already merged and put it up twice.
6771            let strand = (!expanded && parts.supplementary_nav.is_none()).then(|| {
6772                let merged: Vec<Retained<UIViewController>> =
6773                    unsafe { parts.primary_nav.viewControllers() }
6774                        .iter()
6775                        .collect();
6776                let stranded: Vec<Retained<UIViewController>> = if merged.len() <= 1 {
6777                    unsafe { state.nav.viewControllers() }.iter().collect()
6778                } else {
6779                    Vec::new()
6780                };
6781                let kept: Vec<Retained<UIViewController>> = Vec::new();
6782                (
6783                    parts.primary_nav.clone(),
6784                    state.nav.clone(),
6785                    merged,
6786                    stranded,
6787                    kept,
6788                )
6789            });
6790            // A TRIPLE-column collapse strands the content list the same way: at launch on
6791            // iOS 18 the collapse takes the list as its top column (the delegate's answer
6792            // below) but merges before the list is there to carry, so a phone opens on the
6793            // sidebar while the model has the list open and nothing to pop. Put the list on
6794            // the stack through UIKit's own column API, as a tap on its row would, whenever
6795            // the delegate would have chosen it: no detail page, and a list that belongs to
6796            // the destination. Already on the stack (iOS 26), it is left alone.
6797            let list = !expanded
6798                && parts.supplementary_nav.is_some()
6799                && parts.list_shown.get()
6800                && day_pages(&state.nav, parts.secondary_placeholder.as_deref()).is_empty();
6801            Some((state.host_node, strand, list))
6802        });
6803        let Some((node, strand, list)) = plan else {
6804            return;
6805        };
6806        if let Some((primary, secondary, mut merged, stranded, kept)) = strand
6807            && !stranded.is_empty()
6808        {
6809            if *DIAG_NAV {
6810                log::debug!(
6811                    "DAYDIAG split COLLAPSED merging {} stranded page(s) onto primary={}",
6812                    stranded.len(),
6813                    merged.len()
6814                );
6815            }
6816            let rest = objc2_foundation::NSArray::from_retained_slice(&kept);
6817            unsafe { secondary.setViewControllers(&rest) };
6818            merged.extend(stranded);
6819            let arr = objc2_foundation::NSArray::from_retained_slice(&merged);
6820            unsafe { primary.setViewControllers_animated(&arr, false) };
6821        }
6822        // A turn later, once Day's launch sync has settled the chrome. The list's back button
6823        // takes its label from a bar still laid out at the expanded column's width, which
6824        // shortens "Day News" to UIKit's generic "Back" and keeps it; the push's own `didShow`
6825        // has the label measured again at the stack's width (`RELABEL_BACK`).
6826        if list {
6827            dispatch2::DispatchQueue::main().exec_async(move || {
6828                day_spec::ffi_guard::contain((), || {
6829                    RELABEL_BACK.with(|hosts| hosts.borrow_mut().insert(host));
6830                    request_compact_list(host, true);
6831                });
6832            });
6833        }
6834        emit(
6835            node,
6836            Event::NavPresentationChanged(if expanded {
6837                day_spec::props::NavPresentation::Split
6838            } else {
6839                day_spec::props::NavPresentation::Stack
6840            }),
6841        );
6842        // Re-lay every page against its NEW column, one runloop turn later.
6843        //
6844        // A merge REPARENTS the page views, and `layoutSubviews` only fires — and only reports
6845        // `FrameChanged` — when a view's own bounds change. Reparenting alone may not change
6846        // them in the same pass, so each page can keep the frame it had in the other
6847        // presentation: the list drawn at sidebar width on top of a detail still sized for the
6848        // split. Forcing the layout inline does not help either, because this callback runs
6849        // During the transition and the bounds are still mid-animation. Deferring is the same
6850        // shape as the Qt fix, where hiding a splitter pane does not resize its sibling until Qt
6851        // has run its own layout pass (docs/size-classes.md).
6852        dispatch2::DispatchQueue::main().exec_async(move || {
6853            // Expanded again: the host the destination in force calls for
6854            // (`SplitParts::list_shown`), before the columns below are laid out.
6855            if expanded {
6856                rehost_split(host);
6857            }
6858            split_settle(host);
6859        });
6860    }
6861
6862    /// Lay the split host's columns out for the presentation or host they now have, then
6863    /// re-place the window toolbar and the search field against them. Runs a turn after a
6864    /// collapse or expand, and after a rebuild.
6865    fn split_settle(host: usize) {
6866        // Copied out of NAV_STATE first, the file's re-entrancy rule: laying a column out
6867        // makes UIKit lay out what it shows, which binds list rows synchronously, and a row
6868        // built there inserts views through `Toolkit::insert`, which borrows NAV_STATE again.
6869        let settled = NAV_STATE.with(|m| {
6870            let m = m.borrow();
6871            let state = m.get(&host)?;
6872            let parts = state.split.as_ref()?;
6873            Some((
6874                parts.primary_nav.clone(),
6875                state.nav.clone(),
6876                parts.split_vc.clone(),
6877                state.search.is_some(),
6878                state.search_hides_on_scroll,
6879                state.search_initially_hidden,
6880            ))
6881        });
6882        let Some((primary_nav, nav, split_vc, search, hides_on_scroll, initially_hidden)) = settled
6883        else {
6884            return;
6885        };
6886        // RESIZE each page to the column that now owns it, then lay it out.
6887        //
6888        // Laying a view out does not change its own frame, which is why forcing
6889        // `layoutIfNeeded` alone never fixed this: UIKit does not resize the OFF-SCREEN
6890        // members of a navigation stack, and after a collapse the sidebar page sits at
6891        // the bottom of the merged stack. It kept the column bounds it had while
6892        // expanded — measured at 420x409 in landscape while the detail had correctly
6893        // re-laid to 430x839 — so its content stayed sized for the other presentation
6894        // (docs/size-classes.md).
6895        //
6896        // Every page is full-bleed within its own navigation controller, so that
6897        // controller's view bounds are the page's frame.
6898        // Ask each COLUMN to lay itself out, rather than resizing pages by hand.
6899        //
6900        // The navigation controller owns its pages' frames AND their safe-area insets, so
6901        // laying it out propagates both. Setting a page's frame directly does not: the
6902        // insets stay whatever they were where the page last lived, which is how a
6903        // landscape notch inset of 100pt survived into portrait.
6904        let relayout = |nav: &DayNavController| {
6905            if let Some(v) = unsafe { nav.viewIfLoaded() } {
6906                v.setNeedsLayout();
6907                v.layoutIfNeeded();
6908            }
6909        };
6910        relayout(&primary_nav);
6911        relayout(&nav);
6912        if let Some(v) = unsafe { split_vc.viewIfLoaded() } {
6913            v.setNeedsLayout();
6914            v.layoutIfNeeded();
6915        }
6916        // The window bar and the columns' bar actions follow the presentation
6917        // (docs/toolbars.md): the bar moves between the detail column's navigation
6918        // bar and the bottom of the merged stack, and the sidebar's every-page actions
6919        // leave it or rejoin it. `isCollapsed` has settled by now, one turn later.
6920        let roots: Vec<usize> = WINDOW_TOOLBARS.with(|t| t.borrow().keys().copied().collect());
6921        for root in roots {
6922            reapply_window_toolbar(root);
6923        }
6924        // The search policy follows its owning column (docs/search.md), including
6925        // the compact-title drawer opt-in. Both stacks are walked because the
6926        // sidebar page lives in the primary column expanded and in the merged one
6927        // collapsed, and only the page that has the controller is touched.
6928        if search {
6929            for nav in [&primary_nav, &nav] {
6930                for vc in &unsafe { nav.viewControllers() } {
6931                    let item = unsafe { vc.navigationItem() };
6932                    if unsafe { item.searchController() }.is_some() {
6933                        configure_sidebar_search(&item, nav, hides_on_scroll, initially_hidden);
6934                    }
6935                }
6936            }
6937        }
6938    }
6939
6940    /// The column controllers of a split host, built by `realize` and again by `rehost_split`.
6941    struct SplitBuild {
6942        split_vc: Retained<objc2_ui_kit::UISplitViewController>,
6943        primary_nav: Retained<DayNavController>,
6944        supplementary_nav: Option<Retained<DayNavController>>,
6945        secondary_placeholder: Option<Retained<UIViewController>>,
6946    }
6947
6948    /// A blank, grouped-background controller: the seed a column takes while it has no page.
6949    fn blank_vc(mtm: MainThreadMarker) -> Retained<UIViewController> {
6950        let vc = unsafe { UIViewController::new(mtm) };
6951        if let Some(v) = unsafe { vc.view() } {
6952            unsafe { v.setBackgroundColor(Some(&UIColor::systemGroupedBackgroundColor())) };
6953        }
6954        vc
6955    }
6956
6957    /// Build a split host of the style the destination calls for (docs/size-classes.md,
6958    /// docs/navigation.md): a double-column `UISplitViewController` whose SECONDARY column is
6959    /// Day's navigation stack (`secondary`) and whose PRIMARY is the sidebar page's own
6960    /// stack, with a SUPPLEMENTARY column for the content list when `triple`. UIKit
6961    /// collapses it to a single stack at compact width and expands it at regular — which is a
6962    /// rotation away on a Plus/Pro Max iPhone and the standing state on an iPad.
6963    ///
6964    /// Collapsing MERGES: UIKit inserts the primary's controller at the bottom of the
6965    /// secondary's navigation stack. That lands on exactly the shape Day's model already has
6966    /// in a stack presentation — the sidebar page as the stack's root — so the phone path is
6967    /// unchanged and only the mirror needs rebasing.
6968    ///
6969    /// The secondary column must never be an EMPTY navigation controller on the older
6970    /// runtimes (see `SplitParts::secondary_placeholder`): a triple-column host seeds it here
6971    /// when it holds nothing, and seeds the supplementary the same way, because the
6972    /// window-attach collapse can nest either before its page arrives.
6973    fn build_split(
6974        mtm: MainThreadMarker,
6975        secondary: &DayNavController,
6976        list_width: Option<f64>,
6977        triple: bool,
6978    ) -> SplitBuild {
6979        let split_vc = unsafe {
6980            objc2_ui_kit::UISplitViewController::initWithStyle(
6981                objc2_ui_kit::UISplitViewController::alloc(mtm),
6982                if triple {
6983                    objc2_ui_kit::UISplitViewControllerStyle::TripleColumn
6984                } else {
6985                    objc2_ui_kit::UISplitViewControllerStyle::DoubleColumn
6986                },
6987            )
6988        };
6989        let primary_nav = DayNavController::new(mtm, 0); // host ptr set by the caller
6990        let secondary_placeholder = triple.then(|| {
6991            let ph = blank_vc(mtm);
6992            if unsafe { secondary.viewControllers() }.count() == 0 {
6993                let arr = objc2_foundation::NSArray::from_retained_slice(std::slice::from_ref(&ph));
6994                unsafe { secondary.setViewControllers(&arr) };
6995            }
6996            ph
6997        });
6998        let supplementary_nav = triple.then(|| {
6999            let snav = DayNavController::new(mtm, 0);
7000            unsafe {
7001                let arr = objc2_foundation::NSArray::from_retained_slice(&[blank_vc(mtm)]);
7002                snav.setViewControllers(&arr);
7003                split_vc.setViewController_forColumn(
7004                    Some(&snav),
7005                    objc2_ui_kit::UISplitViewControllerColumn::Supplementary,
7006                );
7007                split_vc.setPreferredSupplementaryColumnWidth(
7008                    list_width.unwrap_or(day_spec::NAV_LIST_MIN_W),
7009                );
7010            }
7011            snav
7012        });
7013        unsafe {
7014            split_vc.setViewController_forColumn(
7015                Some(&primary_nav),
7016                objc2_ui_kit::UISplitViewControllerColumn::Primary,
7017            );
7018            split_vc.setViewController_forColumn(
7019                Some(secondary),
7020                objc2_ui_kit::UISplitViewControllerColumn::Secondary,
7021            );
7022            // Every column side by side when there is room; UIKit still collapses to one
7023            // stack at compact width. `oneBesideSecondary` is "primary beside secondary" on
7024            // a double-column host and "supplementary beside secondary" on a triple-column
7025            // one, which is why the list-less destination gets a host of its own.
7026            split_vc.setPreferredDisplayMode(if triple {
7027                objc2_ui_kit::UISplitViewControllerDisplayMode::TwoBesideSecondary
7028            } else {
7029                objc2_ui_kit::UISplitViewControllerDisplayMode::OneBesideSecondary
7030            });
7031            // TILE, explicitly. Left automatic, UIKit picks an OVERLAY on a portrait iPad:
7032            // the sidebar floats above a dimmed detail, and the detail keeps the full window
7033            // width — so Day lays its content out for a width the user cannot see the left
7034            // edge of. Tiling gives the detail column its own narrower bounds, which is what
7035            // the page then reports through `FrameChanged` (docs/size-classes.md).
7036            split_vc
7037                .setPreferredSplitBehavior(objc2_ui_kit::UISplitViewControllerSplitBehavior::Tile);
7038        }
7039        SplitBuild {
7040            split_vc,
7041            primary_nav,
7042            supplementary_nav,
7043            secondary_placeholder,
7044        }
7045    }
7046
7047    define_class!(
7048        #[unsafe(super(UIView))]
7049        #[thread_kind = MainThreadOnly]
7050        #[name = "DayNavContainer"]
7051        struct DayNavContainer;
7052
7053        /// The split host's container: Day's handle for the node, sized by Day's layout, and
7054        /// the one thing that sizes the split's view — to its own bounds, every pass.
7055        ///
7056        /// Explicit, not an autoresizing mask. A flexible child of a superview that grows FROM
7057        /// ZERO gets its own size plus the delta, so a split view that had already measured
7058        /// 420×810 came out 840×1620 the moment its container took that size — the list's
7059        /// trailing accessories and the bar title off the right edge of the phone. Which
7060        /// order the container and the split get their first size in depends on the page
7061        /// above (a tab page that bleeds under its bar reports before the tab settles), so
7062        /// the mask was never safe; a layout pass is.
7063        impl DayNavContainer {
7064            #[unsafe(method(layoutSubviews))]
7065            fn layout_subviews(&self) {
7066                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
7067                let bounds = self.bounds();
7068                for v in &unsafe { self.subviews() } {
7069                    unsafe { v.setFrame(bounds) };
7070                }
7071            }
7072        }
7073    );
7074
7075    impl DayNavContainer {
7076        fn new(mtm: MainThreadMarker) -> Retained<Self> {
7077            let this = Self::alloc(mtm).set_ivars(());
7078            unsafe { msg_send![super(this), init] }
7079        }
7080    }
7081
7082    /// Mount a split's view in the host's container under the window root's containment.
7083    fn mount_split(split_vc: &objc2_ui_kit::UISplitViewController, container: &UIView) {
7084        let root_vc = WINDOW
7085            .with(|w| w.borrow().clone())
7086            .and_then(|w| w.rootViewController());
7087        unsafe {
7088            if let Some(root_vc) = &root_vc {
7089                root_vc.addChildViewController(split_vc);
7090            }
7091            if let Some(v) = split_vc.view() {
7092                // No mask, for the reason the stack host gives: the container lays it out.
7093                v.setAutoresizingMask(objc2_ui_kit::UIViewAutoresizing::empty());
7094                v.setFrame(container.bounds());
7095                container.addSubview(&v);
7096                container.setNeedsLayout();
7097            }
7098            if let Some(root_vc) = &root_vc {
7099                split_vc.didMoveToParentViewController(Some(root_vc));
7100            }
7101        }
7102    }
7103
7104    /// Rebuild the split host for the destination in force (`SplitParts::list_shown`,
7105    /// docs/navigation.md): a fresh split of the other style with fresh column controllers,
7106    /// the pages moved across, swapped into the same container. Expanded only — collapsed,
7107    /// the columns are one stack and the list joins it through `NavPatch::ListInStack`. Every
7108    /// UIKit call runs outside the state borrow: each re-enters the navigation delegate.
7109    fn rehost_split(host: usize) {
7110        let Some(mtm) = MainThreadMarker::new() else {
7111            return;
7112        };
7113        let plan = NAV_STATE.with(|m| {
7114            let m = m.borrow();
7115            let state = m.get(&host)?;
7116            let parts = state.split.as_ref()?;
7117            let list_width = parts.list_width?;
7118            if state.is_collapsed() {
7119                return None;
7120            }
7121            let triple = parts.list_shown.get();
7122            if triple == parts.supplementary_nav.is_some() {
7123                return None;
7124            }
7125            Some((
7126                parts.split_vc.clone(),
7127                parts.primary_nav.clone(),
7128                parts.supplementary_nav.clone(),
7129                state.nav.clone(),
7130                day_pages(&state.nav, parts.secondary_placeholder.as_deref()),
7131                parts.list_vc.borrow().clone(),
7132                parts.container.clone(),
7133                parts.split_delegate.clone(),
7134                list_width,
7135                triple,
7136                state.delegate.clone(),
7137            ))
7138        });
7139        let Some((
7140            old_split,
7141            old_primary,
7142            old_snav,
7143            old_secondary,
7144            vcs,
7145            list_vc,
7146            container,
7147            split_delegate,
7148            list_width,
7149            triple,
7150            delegate,
7151        )) = plan
7152        else {
7153            return;
7154        };
7155        if *DIAG_NAV {
7156            log::debug!("DAYDIAG rehost triple={triple} details={}", vcs.len());
7157        }
7158        note_ui_transition();
7159        let empty = objc2_foundation::NSArray::<UIViewController>::new();
7160        let sidebar = unsafe { old_primary.viewControllers() }.firstObject();
7161        unsafe {
7162            // Pages out of the old columns — a page mounts in one stack at a time — then the
7163            // old host out of the window, then a fresh host with fresh column controllers.
7164            old_primary.setViewControllers(&empty);
7165            if let Some(snav) = &old_snav {
7166                snav.setViewControllers(&empty);
7167            }
7168            old_secondary.setViewControllers(&empty);
7169            old_split.willMoveToParentViewController(None);
7170            if let Some(v) = old_split.viewIfLoaded() {
7171                v.removeFromSuperview();
7172            }
7173            old_split.removeFromParentViewController();
7174        }
7175        let secondary = DayNavController::new(mtm, host);
7176        secondary
7177            .ivars()
7178            .guarded
7179            .set(old_secondary.ivars().guarded.get());
7180        let built = build_split(mtm, &secondary, Some(list_width), triple);
7181        built.primary_nav.ivars().host.set(host);
7182        unsafe {
7183            secondary.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7184            built
7185                .primary_nav
7186                .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7187            if let Some(snav) = &built.supplementary_nav {
7188                snav.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7189                snav.ivars().host.set(host);
7190                if let Some(lv) = &list_vc {
7191                    let arr =
7192                        objc2_foundation::NSArray::from_retained_slice(std::slice::from_ref(lv));
7193                    snav.setViewControllers(&arr);
7194                }
7195            }
7196            if let Some(sb) = &sidebar {
7197                let arr = objc2_foundation::NSArray::from_retained_slice(std::slice::from_ref(sb));
7198                built.primary_nav.setViewControllers(&arr);
7199            }
7200            if !vcs.is_empty() {
7201                let arr = objc2_foundation::NSArray::from_retained_slice(&vcs);
7202                secondary.setViewControllers(&arr);
7203            }
7204            built
7205                .split_vc
7206                .setDelegate(Some(ProtocolObject::from_ref(&*split_delegate)));
7207        }
7208        NAV_STATE.with(|m| {
7209            let mut m = m.borrow_mut();
7210            let Some(state) = m.get_mut(&host) else {
7211                return;
7212            };
7213            state.nav = secondary.clone();
7214            let Some(parts) = state.split.as_mut() else {
7215                return;
7216            };
7217            parts.split_vc = built.split_vc.clone();
7218            parts.primary_nav = built.primary_nav;
7219            parts.supplementary_nav = built.supplementary_nav;
7220            parts.secondary_placeholder = built.secondary_placeholder;
7221        });
7222        mount_split(&built.split_vc, &container);
7223    }
7224
7225    /// Apply Day's model of the stack to the ACTIVE navigation controller in one
7226    /// `setViewControllers:animated:` — UIKit's atomic stack primitive (docs/navigation.md).
7227    ///
7228    /// Incremental push/pop calls raced a fast driver: a selection change is a pop AND a
7229    /// push, and issuing the second while the first still animates leaves `viewControllers`
7230    /// reporting a transient state — one mid-flight read hit a 1-count and the detail-column
7231    /// wipe emptied the MERGED stack, sidebar included; the late didShow train then read as
7232    /// a user back and tore the route down. Deriving the whole array from the mirror at
7233    /// execution time is idempotent: however calls interleave, the last sync applies the
7234    /// final model and every intermediate state converges. A sync's settled count equals the
7235    /// mirror's by construction, so `didShow` can never mistake it for a user pop.
7236    /// The stack UIKit reports for `nav`, flattened: a merge on iOS 26 nests the secondary
7237    /// controller onto the primary as one entry, so a nested navigation controller reads as
7238    /// its own pages. `placeholder` — a triple host's blank secondary root — is left out.
7239    fn day_pages(
7240        nav: &objc2_ui_kit::UINavigationController,
7241        placeholder: Option<&UIViewController>,
7242    ) -> Vec<Retained<UIViewController>> {
7243        let mut out = Vec::new();
7244        for vc in &unsafe { nav.viewControllers() } {
7245            if let Some(nested) = vc.downcast_ref::<objc2_ui_kit::UINavigationController>() {
7246                out.extend(day_pages(nested, placeholder));
7247            } else if !placeholder.is_some_and(|p| std::ptr::eq(p, &raw const *vc)) {
7248                out.push(vc);
7249            }
7250        }
7251        out
7252    }
7253
7254    /// Whether `vc` is a Day page at all (a nav page's controller, `PAGE_VCS`), and which pane
7255    /// it was declared for.
7256    #[expect(
7257        clippy::option_option,
7258        reason = "outer `None` is a controller that is no Day page; the inner value is the page's optional pane"
7259    )]
7260    fn pane_of(vc: &UIViewController) -> Option<Option<day_spec::props::Pane>> {
7261        let handle = PAGE_VCS.with(|m| {
7262            m.borrow()
7263                .iter()
7264                .find(|(_, v)| std::ptr::eq(&raw const ***v, vc))
7265                .map(|(h, _)| *h)
7266        })?;
7267        Some(PAGE_PANE.with(|t| t.get(handle)))
7268    }
7269
7270    /// The detail pages on a host's active stack — everything that is a Day page and neither
7271    /// the sidebar nor the content list — in stack order.
7272    fn detail_pages(state: &NavState) -> Vec<Retained<UIViewController>> {
7273        let placeholder = state
7274            .split
7275            .as_ref()
7276            .and_then(|p| p.secondary_placeholder.clone());
7277        day_pages(&state.active_nav(), placeholder.as_deref())
7278            .into_iter()
7279            .filter(|vc| {
7280                // A Day page that is neither the sidebar nor the content list.
7281                matches!(
7282                    pane_of(vc),
7283                    Some(pane) if !matches!(
7284                        pane,
7285                        Some(day_spec::props::Pane::Sidebar | day_spec::props::Pane::List)
7286                    )
7287                )
7288            })
7289            .collect()
7290    }
7291
7292    /// The Day page on top of `nav`, through a nested merge.
7293    fn top_page(nav: &objc2_ui_kit::UINavigationController) -> Option<Retained<UIViewController>> {
7294        day_pages(nav, None).pop()
7295    }
7296
7297    /// Apply `target` to `nav` — one `setViewControllers:animated:` — and, if UIKit cancels
7298    /// the transition under it (a window capture mid-flight does that on iOS 26+), apply it
7299    /// once more. Callers compute `target` from what UIKit REPORTS at that moment
7300    /// (`day_pages`) plus their one change, never from a copy Day keeps: there is no mirror
7301    /// to fall out of step with (docs/navigation.md).
7302    fn set_stack(
7303        host: usize,
7304        generation: u64,
7305        nav: &DayNavController,
7306        target: Vec<Retained<UIViewController>>,
7307        retry: bool,
7308        quiet: bool,
7309    ) {
7310        use objc2_ui_kit::{
7311            UIViewControllerTransitionCoordinator, UIViewControllerTransitionCoordinatorContext,
7312        };
7313        let current = day_pages(nav, None);
7314        let unchanged = current.len() == target.len()
7315            && current
7316                .iter()
7317                .zip(&target)
7318                .all(|(a, b)| std::ptr::eq(&raw const **a, &raw const **b));
7319        if unchanged {
7320            settled(host, generation);
7321            return;
7322        }
7323        if *DIAG_NAV {
7324            log::debug!(
7325                "DAYDIAG exec SET native={} -> target={}",
7326                current.len(),
7327                target.len()
7328            );
7329        }
7330        let arr = objc2_foundation::NSArray::from_retained_slice(&target);
7331        // Re-stamp the transition clock at execution (docs: `ui_idle`), and never ANIMATE to
7332        // an empty stack — that transition never completes and holds `ui_idle` false.
7333        note_ui_transition();
7334        let animated = !target.is_empty() && !quiet && !day_core::testing::fast_animations();
7335        unsafe { nav.setViewControllers_animated(&arr, animated) };
7336        let Some(coordinator) = (unsafe { nav.transitionCoordinator() }) else {
7337            // No transition: the set applied on the spot.
7338            settled(host, generation);
7339            return;
7340        };
7341        {
7342            let mtm = MainThreadMarker::new().expect("nav changes run on main");
7343            let again = dispatch2::MainThreadBound::new((nav.retain(), target), mtm);
7344            let again = std::rc::Rc::new(std::cell::RefCell::new(Some(again)));
7345            let completion = block2::RcBlock::new(
7346                move |ctx: NonNull<
7347                    ProtocolObject<dyn objc2_ui_kit::UIViewControllerTransitionCoordinatorContext>,
7348                >| {
7349                    if !unsafe { ctx.as_ref().isCancelled() } || !retry {
7350                        settled(host, generation);
7351                        return;
7352                    }
7353                    if *DIAG_NAV {
7354                        log::debug!("DAYDIAG exec SET cancelled -> once more");
7355                    }
7356                    let Some(again) = again.borrow_mut().take() else {
7357                        settled(host, generation);
7358                        return;
7359                    };
7360                    dispatch2::DispatchQueue::main().exec_async(move || {
7361                        let mtm = MainThreadMarker::new().expect("dispatched to main");
7362                        let (nav, target) = again.into_inner(mtm);
7363                        day_spec::ffi_guard::contain((), || {
7364                            set_stack(host, generation, &nav, target, false, false);
7365                        });
7366                    });
7367                },
7368            );
7369            unsafe { coordinator.animateAlongsideTransition_completion(None, Some(&completion)) };
7370        }
7371    }
7372
7373    /// The stack changes a host has been asked for and not yet applied, and the target of the
7374    /// change last applied while its transition is still running.
7375    ///
7376    /// The only stack state Day keeps, and only while something is in flight. iOS 18 DEFERS a
7377    /// `setViewControllers:animated:` issued during another transition and keeps reporting
7378    /// the old stack until it lands, so a push computed from that read put the page the
7379    /// previous pop had just removed straight back — one leaked page per route change, and a
7380    /// twenty-deep stack by the end of a walkthrough (iOS 26 reports the new stack at once).
7381    /// So changes issued in one turn coalesce into one set, and a change issued while a set is
7382    /// in flight is based on that set's target rather than on the read. At rest, UIKit's
7383    /// `viewControllers` is the truth and this holds nothing.
7384    struct NavQueue {
7385        ops: Vec<NavOp>,
7386        scheduled: bool,
7387        in_flight: Option<Vec<Retained<UIViewController>>>,
7388        generation: u64,
7389        /// The next set is applied without animation: it was held back until the host first
7390        /// appeared, and what it restores was never on screen to animate away from.
7391        quiet: bool,
7392        /// How many turns `apply_ops` has waited for the host's first appearance.
7393        first_show_waits: u32,
7394    }
7395
7396    /// The most turns (50 ms each) a stack change waits for its host's first appearance.
7397    const FIRST_SHOW_MAX_WAITS: u32 = 20;
7398
7399    thread_local! {
7400        /// Hosts that have been in a window at least once: their changes never wait again.
7401        static NAV_SEEN: RefCell<std::collections::HashSet<usize>> =
7402            RefCell::new(std::collections::HashSet::new());
7403    }
7404
7405    enum NavOp {
7406        Push(Retained<UIViewController>),
7407        Pop(Retained<UIViewController>),
7408    }
7409
7410    thread_local! {
7411        static NAV_OPS: RefCell<HashMap<usize, NavQueue>> = RefCell::new(HashMap::new());
7412    }
7413
7414    /// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
7415    struct UikitBitmap {
7416        image: Retained<objc2_ui_kit::UIImage>,
7417        info: day_spec::BitmapInfo,
7418    }
7419
7420    thread_local! {
7421        /// `BitmapId` → the decoded image. Keyed by the id day-core minted rather than by a view
7422        /// pointer: one bitmap outlives any view and may be drawn by several at once. Entries
7423        /// leave only through `release_image`.
7424        static BITMAPS: RefCell<HashMap<u64, UikitBitmap>> = RefCell::new(HashMap::new());
7425        /// The fonts a painting thread's text ops resolve to, keyed by (size bits, font):
7426        /// filled by [`OffscreenResources`] for one export at a time (docs/canvas.md
7427        /// "Exporting"), so the painter asks UIKit's font machinery only from the UI thread.
7428        /// Empty on the UI thread itself.
7429        static OFFSCREEN_FONTS: RefCell<Vec<OffscreenFont>> = const { RefCell::new(Vec::new()) };
7430    }
7431
7432    /// One entry of `OFFSCREEN_FONTS`: the (size bits, canvas font) a text op asked for, and
7433    /// the `UIFont` the UI thread resolved it to.
7434    type OffscreenFont = ((u64, day_spec::CanvasFont), Retained<objc2_ui_kit::UIFont>);
7435
7436    /// A UIKit object on its way to or from a painting thread (docs/canvas.md "Exporting").
7437    struct Sendable<T>(T);
7438
7439    // SAFETY: wrapped only around objects UIKit documents as usable from any thread —
7440    // `UIImage` and `UIFont` are immutable, and `UIGraphicsImageRenderer` is thread-safe —
7441    // and each wrapped value is used by one thread at a time: the painter borrows it for one
7442    // export, then the UI thread owns the result.
7443    unsafe impl<T> Send for Sendable<T> {}
7444
7445    /// Everything the painter would read from the UI thread's tables, resolved there before an
7446    /// export leaves for a painting thread (docs/canvas.md "Exporting"): the decoded images its
7447    /// image ops draw, and the font each of its text runs needs.
7448    struct OffscreenResources {
7449        images: Vec<(u64, UikitBitmap)>,
7450        fonts: Vec<OffscreenFont>,
7451    }
7452
7453    impl OffscreenResources {
7454        /// Walk `ops` on the UI thread. An image whose handle was already released is simply
7455        /// absent, and the painter draws nothing for it, as it does on screen.
7456        fn collect(ops: &[DrawOp]) -> Self {
7457            let mut images: Vec<(u64, UikitBitmap)> = Vec::new();
7458            let mut fonts: Vec<OffscreenFont> = Vec::new();
7459            for op in ops {
7460                match op {
7461                    DrawOp::Image { image, .. } => {
7462                        if images.iter().any(|(id, _)| *id == image.0) {
7463                            continue;
7464                        }
7465                        let held = BITMAPS.with(|m| {
7466                            m.borrow().get(&image.0).map(|b| UikitBitmap {
7467                                image: b.image.clone(),
7468                                info: b.info,
7469                            })
7470                        });
7471                        if let Some(bitmap) = held {
7472                            images.push((image.0, bitmap));
7473                        }
7474                    }
7475                    DrawOp::Text { size, font, .. } => {
7476                        let key = (size.to_bits(), font.clone());
7477                        if fonts.iter().any(|(k, _)| *k == key) {
7478                            continue;
7479                        }
7480                        let resolved = canvas_uifont(*size, font);
7481                        fonts.push((key, resolved));
7482                    }
7483                    _ => {}
7484                }
7485            }
7486            Self { images, fonts }
7487        }
7488
7489        /// Run `paint` with these as the calling thread's own tables, then take them back out.
7490        /// Only entries this call added are removed afterwards, so a run on the UI thread
7491        /// itself (no painting thread could start) leaves its tables as they were.
7492        fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
7493            let mut added_images = Vec::with_capacity(self.images.len());
7494            BITMAPS.with(|m| {
7495                let mut m = m.borrow_mut();
7496                for (id, bitmap) in self.images {
7497                    if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
7498                        slot.insert(bitmap);
7499                        added_images.push(id);
7500                    }
7501                }
7502            });
7503            let added_fonts = self.fonts.len();
7504            OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
7505            let out = paint();
7506            OFFSCREEN_FONTS.with(|t| {
7507                let mut t = t.borrow_mut();
7508                let keep = t.len().saturating_sub(added_fonts);
7509                t.truncate(keep);
7510            });
7511            BITMAPS.with(|m| {
7512                let mut m = m.borrow_mut();
7513                for id in added_images {
7514                    m.remove(&id);
7515                }
7516            });
7517            out
7518        }
7519    }
7520
7521    /// A Day page joins a host's stack (the insert duty).
7522    fn push_page(host: usize, vc: Retained<UIViewController>) {
7523        queue_op(host, NavOp::Push(vc));
7524    }
7525
7526    /// A Day page leaves a host (the remove duty): off the active stack if it is still there.
7527    /// After a user's back it is not — the override reported that pop already — and the change
7528    /// is a no-op, which is the whole protocol between the two.
7529    fn pop_page(host: usize, vc: Retained<UIViewController>) {
7530        queue_op(host, NavOp::Pop(vc));
7531    }
7532
7533    fn queue_op(host: usize, op: NavOp) {
7534        let schedule = NAV_OPS.with(|q| {
7535            let mut q = q.borrow_mut();
7536            let entry = q.entry(host).or_insert_with(|| NavQueue {
7537                ops: Vec::new(),
7538                scheduled: false,
7539                in_flight: None,
7540                quiet: false,
7541                first_show_waits: 0,
7542                generation: 0,
7543            });
7544            entry.ops.push(op);
7545            let first = !entry.scheduled;
7546            entry.scheduled = true;
7547            first
7548        });
7549        if schedule {
7550            note_ui_transition();
7551            // Deferred past any in-flight modal transition, like every stack change: issued the
7552            // instant a scripted dialog dismissal starts, it races the dismissal and wedges the
7553            // controller.
7554            modal_after_idle(move || apply_ops(host));
7555        }
7556    }
7557
7558    /// Apply everything queued for `host` as one stack change — or, on a collapsed triple
7559    /// column, one UIKit column call per change, since that stack is driven only through
7560    /// UIKit's own APIs (docs/navigation.md).
7561    fn apply_ops(host: usize) {
7562        // A collapsed column presentation queues UIKit's push until after the next CA
7563        // commit. Serialize both detail changes and supplementary-column requests across
7564        // that blind interval, then across the actual transition coordinator's lifetime.
7565        if compact_column_transitioning(host)
7566            || NAV_STATE.with(|m| {
7567                m.borrow()
7568                    .get(&host)
7569                    .is_some_and(|s| s.pending_list.get().is_some())
7570            })
7571        {
7572            let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
7573                .unwrap_or(dispatch2::DispatchTime::NOW);
7574            let _ = dispatch2::DispatchQueue::main().after(when, move || {
7575                day_spec::ffi_guard::contain((), || apply_ops(host));
7576            });
7577            return;
7578        }
7579
7580        // The host's first appearance comes first. A stack set issued before the host is in a
7581        // window (a launch restoring the last section) would put the page over a root UIKit has
7582        // never laid out, and the root's navigation bar then keeps the state it was never given
7583        // — compact title, search field collapsed — for as long as the app runs. UIKit's own
7584        // apps push after the root appears; so does this, one turn later and without animation.
7585        //
7586        // Only before the host's FIRST appearance, and only for a moment: a host that has been
7587        // on screen once (a stack in a tab now in the background) applies at once, as before,
7588        // and one that never appears (built but never shown) stops waiting after a second
7589        // rather than retrying forever with its change unapplied.
7590        let in_window = NAV_STATE.with(|m| {
7591            m.borrow().get(&host).is_some_and(|s| {
7592                s.active_nav()
7593                    .viewIfLoaded()
7594                    .is_some_and(|v| v.window().is_some())
7595            })
7596        });
7597        if in_window {
7598            NAV_SEEN.with(|seen| {
7599                seen.borrow_mut().insert(host);
7600            });
7601        }
7602        let waited = NAV_OPS.with(|q| q.borrow().get(&host).map_or(0, |e| e.first_show_waits));
7603        let unseen = !in_window
7604            && !NAV_SEEN.with(|seen| seen.borrow().contains(&host))
7605            && waited < FIRST_SHOW_MAX_WAITS;
7606        if unseen {
7607            NAV_OPS.with(|q| {
7608                if let Some(entry) = q.borrow_mut().get_mut(&host) {
7609                    entry.quiet = true;
7610                    entry.first_show_waits += 1;
7611                }
7612            });
7613            let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
7614                .unwrap_or(dispatch2::DispatchTime::NOW);
7615            let _ = dispatch2::DispatchQueue::main().after(when, move || {
7616                day_spec::ffi_guard::contain((), || apply_ops(host));
7617            });
7618            return;
7619        }
7620
7621        let (ops, quiet) = NAV_OPS.with(|q| {
7622            let mut q = q.borrow_mut();
7623            let Some(entry) = q.get_mut(&host) else {
7624                return (Vec::new(), false);
7625            };
7626            // A set is still animating: leave everything queued (still scheduled) and let its
7627            // completion run this again. UIKit defers a `setViewControllers:animated:` issued
7628            // mid-transition and keeps reporting the old stack until it lands — the window in
7629            // which a scripted back found nothing to pop — and warns about the call besides.
7630            if entry.in_flight.is_some() {
7631                return (Vec::new(), false);
7632            }
7633            entry.scheduled = false;
7634            (
7635                std::mem::take(&mut entry.ops),
7636                std::mem::take(&mut entry.quiet),
7637            )
7638        });
7639        if ops.is_empty() {
7640            return;
7641        }
7642        let Some((active, placeholder, triple, secondary, svc)) = NAV_STATE.with(|m| {
7643            m.borrow().get(&host).map(|s| {
7644                let triple = s.is_collapsed()
7645                    && s.split
7646                        .as_ref()
7647                        .is_some_and(|p| p.supplementary_nav.is_some());
7648                (
7649                    s.active_nav(),
7650                    s.split
7651                        .as_ref()
7652                        .and_then(|p| p.secondary_placeholder.clone()),
7653                    triple,
7654                    s.nav.clone(),
7655                    s.split.as_ref().map(|p| p.split_vc.clone()),
7656                )
7657            })
7658        }) else {
7659            return;
7660        };
7661        if triple && let Some(svc) = svc {
7662            // Fold a route's pop+push (and any further route changes in this turn) into
7663            // ONE secondary-column update. Calling showColumn once per push can queue
7664            // duplicate pushes of the same secondary UINavigationController.
7665            let old = NAV_STATE
7666                .with(|m| m.borrow().get(&host).map(detail_pages))
7667                .unwrap_or_default();
7668            let mut details = old.clone();
7669            for op in ops {
7670                match op {
7671                    NavOp::Push(vc) => {
7672                        if !details
7673                            .iter()
7674                            .any(|v| std::ptr::eq(&raw const **v, &raw const *vc))
7675                        {
7676                            details.push(vc);
7677                        }
7678                    }
7679                    NavOp::Pop(vc) => {
7680                        details.retain(|v| !std::ptr::eq(&raw const **v, &raw const *vc));
7681                    }
7682                }
7683            }
7684            if details.is_empty() {
7685                if let Some(vc) = old.first()
7686                    && let Some((owner, below)) = owner_of(&active, vc)
7687                {
7688                    let pop = || unsafe {
7689                        match &below {
7690                            Some(b) => {
7691                                let _ = owner.popToViewController_animated(b, false);
7692                            }
7693                            None => {
7694                                let _ = owner.popToRootViewControllerAnimated(false);
7695                            }
7696                        }
7697                    };
7698                    match owner.downcast_ref::<DayNavController>() {
7699                        Some(d) => with_day_pop(d, pop),
7700                        None => pop(),
7701                    }
7702                    note_column_request(host);
7703                }
7704            } else {
7705                let already_visible = !old.is_empty();
7706                let arr = objc2_foundation::NSArray::from_retained_slice(&details);
7707                unsafe {
7708                    secondary.setViewControllers(&arr);
7709                }
7710                if !already_visible {
7711                    note_column_request(host);
7712                    unsafe {
7713                        svc.showColumn(objc2_ui_kit::UISplitViewControllerColumn::Secondary);
7714                    }
7715                }
7716            }
7717            return;
7718        }
7719        // Base the target on the change still in flight, if any, else on what UIKit reports.
7720        let base = NAV_OPS
7721            .with(|q| q.borrow().get(&host).and_then(|e| e.in_flight.clone()))
7722            .unwrap_or_else(|| day_pages(&active, placeholder.as_deref()));
7723        let mut target = base;
7724        for op in ops {
7725            match op {
7726                NavOp::Push(vc) => target.push(vc),
7727                NavOp::Pop(vc) => target.retain(|v| !std::ptr::eq(&raw const **v, &raw const *vc)),
7728            }
7729        }
7730        let generation = NAV_OPS.with(|q| {
7731            let mut q = q.borrow_mut();
7732            let Some(entry) = q.get_mut(&host) else {
7733                return 0;
7734            };
7735            entry.generation += 1;
7736            entry.in_flight = Some(target.clone());
7737            entry.generation
7738        });
7739        set_stack(host, generation, &active, target, true, quiet);
7740    }
7741
7742    /// The change `generation` on `host` has settled: the stack UIKit reports is the truth
7743    /// again, unless a newer change has been issued since.
7744    fn settled(host: usize, generation: u64) {
7745        let more = NAV_OPS.with(|q| {
7746            let mut q = q.borrow_mut();
7747            let Some(entry) = q.get_mut(&host) else {
7748                return false;
7749            };
7750            if entry.generation != generation {
7751                return false;
7752            }
7753            entry.in_flight = None;
7754            !entry.ops.is_empty()
7755        });
7756        if more {
7757            // Off the completion's stack: UIKit is still inside the transition there.
7758            dispatch2::DispatchQueue::main().exec_async(move || {
7759                day_spec::ffi_guard::contain((), || modal_after_idle(move || apply_ops(host)));
7760            });
7761        }
7762    }
7763
7764    /// The Day page on top of `host`'s active stack, as the app will see it: the top of the
7765    /// change in flight if there is one, else what UIKit reports.
7766    fn current_top(host: usize, active: &DayNavController) -> Option<Retained<UIViewController>> {
7767        // Changes still queued count too: a page's title arrives in the same turn as its push,
7768        // and while a modal transition holds the queue, UIKit's top is still the page below.
7769        NAV_OPS.with(|q| {
7770            let q = q.borrow();
7771            let entry = q.get(&host);
7772            if entry.is_none_or(|e| e.in_flight.is_none() && e.ops.is_empty()) {
7773                return top_page(active);
7774            }
7775            let mut stack = entry
7776                .and_then(|e| e.in_flight.clone())
7777                .unwrap_or_else(|| day_pages(active, None));
7778            for op in entry.map_or_default(|e| e.ops.as_slice()) {
7779                match op {
7780                    NavOp::Push(vc) => stack.push(vc.clone()),
7781                    NavOp::Pop(vc) => {
7782                        stack.retain(|v| !std::ptr::eq(&raw const **v, &raw const **vc));
7783                    }
7784                }
7785            }
7786            stack.last().cloned()
7787        })
7788    }
7789
7790    /// Which navigation controller directly holds `vc` — `nav` itself or a controller nested
7791    /// on its stack — and the entry below it there (`None` for a root). A nested controller
7792    /// whose root is `vc` is popped as a whole from `nav`, so that case answers `nav` and the
7793    /// entry below the nested controller.
7794    fn owner_of(
7795        nav: &objc2_ui_kit::UINavigationController,
7796        vc: &UIViewController,
7797    ) -> Option<(
7798        Retained<objc2_ui_kit::UINavigationController>,
7799        Option<Retained<UIViewController>>,
7800    )> {
7801        let stack: Vec<Retained<UIViewController>> =
7802            unsafe { nav.viewControllers() }.iter().collect();
7803        for (i, entry) in stack.iter().enumerate() {
7804            if std::ptr::eq(&raw const **entry, vc) {
7805                let below = (i > 0).then(|| stack[i - 1].clone());
7806                return Some((nav.retain(), below));
7807            }
7808            if let Some(nested) = entry.downcast_ref::<objc2_ui_kit::UINavigationController>() {
7809                let inner: Vec<Retained<UIViewController>> =
7810                    unsafe { nested.viewControllers() }.iter().collect();
7811                if inner
7812                    .first()
7813                    .is_some_and(|r| std::ptr::eq(&raw const **r, vc))
7814                {
7815                    let below = (i > 0).then(|| stack[i - 1].clone());
7816                    return Some((nav.retain(), below));
7817                }
7818                if let Some(j) = inner.iter().position(|v| std::ptr::eq(&raw const **v, vc)) {
7819                    return Some((nested.retain(), Some(inner[j - 1].clone())));
7820                }
7821            }
7822        }
7823        None
7824    }
7825
7826    /// Run one of Day's OWN pop calls on `nav` (the collapsed triple column's
7827    /// `popToViewController:` / `popToRootViewControllerAnimated:`) with the controller's pop
7828    /// overrides told it is not the user's — so a Day pop is never reported back to Day.
7829    fn with_day_pop(nav: &DayNavController, f: impl FnOnce()) {
7830        let host = nav.ivars().host.get();
7831        let set = |on: bool| {
7832            NAV_STATE.with(|m| {
7833                if let Some(s) = m.borrow().get(&host) {
7834                    s.day_pop.set(on);
7835                }
7836            });
7837        };
7838        set(true);
7839        f();
7840        set(false);
7841    }
7842
7843    /// Coalesce list presentation requests and wait for UIKit's current push/pop. Calling
7844    /// showColumn twice during a pop queues two pushes of the SAME supplementary controller.
7845    /// The ticket is pending work, not a stack mirror; presence is always read from UIKit.
7846    fn note_column_request(host: usize) {
7847        note_ui_transition();
7848        NAV_STATE.with(|m| {
7849            if let Some(state) = m.borrow().get(&host) {
7850                state.column_request.set(Some(std::time::Instant::now()));
7851            }
7852        });
7853    }
7854
7855    fn compact_column_transitioning(host: usize) -> bool {
7856        NAV_STATE.with(|m| {
7857            let m = m.borrow();
7858            let Some(state) = m.get(&host).filter(|s| s.is_collapsed()) else {
7859                return false;
7860            };
7861            let Some(parts) = state.split.as_ref() else {
7862                return false;
7863            };
7864            state
7865                .column_request
7866                .get()
7867                .is_some_and(|t| t.elapsed() < std::time::Duration::from_millis(250))
7868                || unsafe { parts.primary_nav.transitionCoordinator() }.is_some()
7869                || unsafe { state.nav.transitionCoordinator() }.is_some()
7870                || parts
7871                    .supplementary_nav
7872                    .as_ref()
7873                    .is_some_and(|n| unsafe { n.transitionCoordinator() }.is_some())
7874                || unsafe { parts.split_vc.transitionCoordinator() }.is_some()
7875        })
7876    }
7877
7878    thread_local! {
7879        /// Split hosts whose list went on the collapsed stack at launch, mid-collapse: the
7880        /// next `didShow` with a page under the top has that page's back label measured again.
7881        static RELABEL_BACK: std::cell::RefCell<std::collections::HashSet<usize>> =
7882            std::cell::RefCell::new(std::collections::HashSet::new());
7883    }
7884
7885    /// Re-set the title of the page under `nav`'s top, once, for a host in `RELABEL_BACK`.
7886    /// Assigning it again has UIKit lay the top page's back button out against the bar as it
7887    /// is now, so the label is the page's title rather than a "Back" chosen for a narrower bar.
7888    fn relabel_back(host: usize, nav: &objc2_ui_kit::UINavigationController) {
7889        let pages = unsafe { nav.viewControllers() };
7890        if pages.count() < 2 || !RELABEL_BACK.with(|hosts| hosts.borrow_mut().remove(&host)) {
7891            return;
7892        }
7893        let below = pages.objectAtIndex(pages.count() - 2);
7894        unsafe {
7895            let title = below.title();
7896            below.navigationItem().setTitle(None);
7897            below.navigationItem().setTitle(title.as_deref());
7898        }
7899    }
7900
7901    fn request_compact_list(host: usize, show: bool) {
7902        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
7903        let ticket = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7904        NAV_STATE.with(|m| {
7905            if let Some(state) = m.borrow().get(&host) {
7906                state.pending_list.set(Some((ticket, show)));
7907            }
7908        });
7909        apply_compact_list(host, ticket, show);
7910    }
7911
7912    fn apply_compact_list(host: usize, ticket: u64, show: bool) {
7913        let found = NAV_STATE.with(|m| {
7914            let m = m.borrow();
7915            let state = m.get(&host)?;
7916            if state.pending_list.get() != Some((ticket, show)) {
7917                return None;
7918            }
7919            if !state.is_collapsed() {
7920                state.pending_list.set(None);
7921                return None;
7922            }
7923            let parts = state.split.as_ref()?;
7924            Some((
7925                parts.split_vc.clone(),
7926                parts.primary_nav.clone(),
7927                parts.list_vc.borrow().clone()?,
7928            ))
7929        });
7930        let Some((split, primary, list)) = found else {
7931            return;
7932        };
7933        if compact_column_transitioning(host) {
7934            let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
7935                .unwrap_or(dispatch2::DispatchTime::NOW);
7936            let _ = dispatch2::DispatchQueue::main().after(when, move || {
7937                day_spec::ffi_guard::contain((), || apply_compact_list(host, ticket, show));
7938            });
7939            return;
7940        }
7941        NAV_STATE.with(|m| {
7942            if let Some(state) = m.borrow().get(&host) {
7943                state.pending_list.set(None);
7944            }
7945        });
7946        if show {
7947            if owner_of(&primary, &list).is_none() {
7948                note_column_request(host);
7949                unsafe {
7950                    split.showColumn(objc2_ui_kit::UISplitViewControllerColumn::Supplementary);
7951                }
7952            }
7953        } else {
7954            note_column_request(host);
7955            with_day_pop(&primary, || unsafe {
7956                let _ = primary.popToRootViewControllerAnimated(false);
7957            });
7958        }
7959    }
7960
7961    /// A pop the USER started on `nav` has been issued — the back button (UIKit calls
7962    /// `popViewControllerAnimated:` once `shouldPopItem:` agrees), the swipe (the same call,
7963    /// under an interactive transition), or the history menu (`popToViewController:`). Report
7964    /// it to Day once it has actually happened: unanimated it already has; animated, its own
7965    /// transition says when, and a swipe let go early is a cancelled pop that Day never hears
7966    /// of, because the page never left. Nothing is inferred from a `didShow` count any more
7967    /// (docs/navigation.md).
7968    fn observe_user_pop(
7969        host: usize,
7970        nav: &objc2_ui_kit::UINavigationController,
7971        popped: Vec<Retained<UIViewController>>,
7972    ) {
7973        use objc2_ui_kit::{
7974            UIViewControllerTransitionCoordinator, UIViewControllerTransitionCoordinatorContext,
7975        };
7976        let Some(coordinator) = (unsafe { nav.transitionCoordinator() }) else {
7977            confirm_user_pop(host, popped);
7978            return;
7979        };
7980        let mtm = MainThreadMarker::new().expect("nav pops run on main");
7981        // Only an interactive pop (the swipe) can be cancelled. A button or history-menu pop
7982        // has already left UIKit's stack, so tell Day now rather than when the slide ends:
7983        // the revealed page is live during that slide, and a row tapped there pushes onto a
7984        // model that still holds the outgoing page. The late report then popped the NEW page
7985        // instead, leaving Day's stack one page off UIKit's (the wrong title, and every later
7986        // push applied to the wrong depth).
7987        if !coordinator.isInteractive() {
7988            let popped = dispatch2::MainThreadBound::new(popped, mtm);
7989            // Off the override's stack: the report re-enters day-core, which pops the model
7990            // and patches this host, and UIKit is still inside `popViewController` here.
7991            dispatch2::DispatchQueue::main().exec_async(move || {
7992                let mtm = MainThreadMarker::new().expect("dispatched to main");
7993                let popped = popped.into_inner(mtm);
7994                day_spec::ffi_guard::contain((), || confirm_user_pop(host, popped));
7995            });
7996            return;
7997        }
7998        let popped = dispatch2::MainThreadBound::new(popped, mtm);
7999        let popped = std::rc::Rc::new(std::cell::RefCell::new(Some(popped)));
8000        let completion = block2::RcBlock::new(
8001            move |ctx: NonNull<
8002                ProtocolObject<dyn objc2_ui_kit::UIViewControllerTransitionCoordinatorContext>,
8003            >| {
8004                if unsafe { ctx.as_ref().isCancelled() } {
8005                    if *DIAG_NAV {
8006                        log::debug!("DAYDIAG user pop cancelled");
8007                    }
8008                    return;
8009                }
8010                let Some(popped) = popped.borrow_mut().take() else {
8011                    return;
8012                };
8013                // Off the callback's stack: the report re-enters day-core, which pops the
8014                // model and patches this host, and UIKit is still inside the transition here.
8015                dispatch2::DispatchQueue::main().exec_async(move || {
8016                    let mtm = MainThreadMarker::new().expect("dispatched to main");
8017                    let popped = popped.into_inner(mtm);
8018                    day_spec::ffi_guard::contain((), || confirm_user_pop(host, popped));
8019                });
8020            },
8021        );
8022        unsafe { coordinator.animateAlongsideTransition_completion(None, Some(&completion)) };
8023    }
8024
8025    /// The user's pop has happened. Tell Day, one `NavBack` per Day page that left the stack
8026    /// (a nested controller popped as a whole counts each page inside it). Day answers each
8027    /// with a `NavPatch::Popped` and a `remove` of the page, which finds it already gone.
8028    fn confirm_user_pop(host: usize, popped: Vec<Retained<UIViewController>>) {
8029        let Some(node) = NAV_STATE.with(|m| m.borrow().get(&host).map(|s| s.host_node)) else {
8030            return;
8031        };
8032        let mut pages = Vec::new();
8033        for vc in popped {
8034            match vc.downcast_ref::<objc2_ui_kit::UINavigationController>() {
8035                Some(nested) => pages.extend(day_pages(nested, None)),
8036                None => pages.push(vc),
8037            }
8038        }
8039        let levels = pages.iter().filter(|vc| pane_of(vc).is_some()).count();
8040        if *DIAG_NAV {
8041            log::debug!("DAYDIAG user pop levels={levels} of {} popped", pages.len());
8042        }
8043        for _ in 0..levels {
8044            emit(
8045                node,
8046                Event::NavBack {
8047                    already_popped: true,
8048                },
8049            );
8050        }
8051    }
8052
8053    define_class!(
8054        #[unsafe(super(NSObject))]
8055        #[thread_kind = MainThreadOnly]
8056        #[name = "DayNavDelegate"]
8057        #[ivars = NavDelegateIvars]
8058        struct DayNavDelegate;
8059
8060        unsafe impl NSObjectProtocol for DayNavDelegate {}
8061
8062        unsafe impl UINavigationControllerDelegate for DayNavDelegate {
8063            #[unsafe(method(navigationController:didShowViewController:animated:))]
8064            fn did_show(
8065                &self,
8066                nav: &objc2_ui_kit::UINavigationController,
8067                // Nullable in practice: the split view's detail stack reports a show with no
8068                // controller when its stack is swapped out under it (iPad), and messaging that
8069                // nil tripped objc2's check on every such call.
8070                vc: Option<&UIViewController>,
8071                _animated: bool,
8072            ) {
8073                // Nothing is inferred here (docs/navigation.md). A user's back is observed
8074                // where it starts — `DayNavController`'s pop overrides, for the button, the
8075                // swipe and the history menu alike — and confirmed by its own transition;
8076                // Day's changes are one `setViewControllers:` confirmed by theirs
8077                // (`apply_ops`). This callback is left with the window toolbar, which
8078                // rides every page and arrives on none of them, and a trace line.
8079                day_spec::ffi_guard::contain((), || {
8080                    if let Some(vc) = vc {
8081                        apply_window_toolbar_to(nav, vc);
8082                        sync_page_search_near(nav);
8083                    }
8084                    relabel_back(self.ivars().host.get(), nav);
8085                    if *DIAG_NAV {
8086                        let host = self.ivars().host.get();
8087                        let (mirror, active) = NAV_STATE.with(|m| {
8088                            m.borrow().get(&host).map_or((0, false), |s| {
8089                                let a = s.active_nav();
8090                                (
8091                                    day_pages(&a, None).len(),
8092                                    std::ptr::addr_eq(
8093                                        (&raw const *a).cast::<std::ffi::c_void>(),
8094                                        std::ptr::from_ref::<objc2_ui_kit::UINavigationController>(
8095                                            nav,
8096                                        )
8097                                        .cast::<std::ffi::c_void>(),
8098                                    ),
8099                                )
8100                            })
8101                        });
8102                        log::debug!(
8103                            "DAYDIAG didShow host={host:x} native={} mirror={mirror} active={active}",
8104                            unsafe { nav.viewControllers() }.count(),
8105                        );
8106                    }
8107                });
8108            }
8109        }
8110    );
8111
8112    impl DayNavDelegate {
8113        fn new(mtm: MainThreadMarker, host: usize) -> Retained<Self> {
8114            let this = Self::alloc(mtm).set_ivars(NavDelegateIvars {
8115                host: std::cell::Cell::new(host),
8116            });
8117            unsafe { msg_send![super(this), init] }
8118        }
8119    }
8120
8121    // -------------------------------------------------------------------
8122    // Cover (docs/cover.md): a fullscreen modal DayCoverVC whose view is a
8123    // DayNavPageView (safe-area pinning + FrameChanged reports), presented and
8124    // dismissed through the modal FIFO like every other VC transition.
8125    // -------------------------------------------------------------------
8126
8127    struct CoverState {
8128        vc: Retained<DayCoverVC>,
8129        node: NodeId,
8130    }
8131
8132    // -------------------------------------------------------------------
8133    // Window properties (docs/windows.md): fullscreen and content protection. iOS gives an
8134    // app neither switch, so both are emulated per scene — fullscreen as a hidden status bar
8135    // and an auto-hiding home indicator, protection as an opaque shield over the scene while
8136    // its screen is recorded or mirrored.
8137    // -------------------------------------------------------------------
8138
8139    /// Whether the window `vc`'s view is in has been asked for fullscreen. The root VC and the
8140    /// cover VCs answer the status-bar and home-indicator questions with it; a VC whose view is
8141    /// not in a Day window (a detached root under a cover) answers no.
8142    fn vc_window_fullscreen(vc: &UIViewController) -> bool {
8143        vc.viewIfLoaded()
8144            .and_then(|view| with_scene_of(&view, |e| e.fullscreen.get()))
8145            .unwrap_or(false)
8146    }
8147
8148    /// The display state a scene reports: `Fullscreen` while the app holds it fullscreen,
8149    /// `Normal` otherwise. An iOS window is never minimized or zoomed.
8150    fn scene_state(entry: &SceneEntry) -> day_spec::WindowState {
8151        if entry.fullscreen.get() {
8152            day_spec::WindowState::Fullscreen
8153        } else {
8154            day_spec::WindowState::Normal
8155        }
8156    }
8157
8158    /// The report a scene owes for its display state, to its root node (`WINDOW_NODE` for the
8159    /// primary): once per change, or every time with `always`, which a declined request uses
8160    /// so day-core's optimistic `state()` signal settles back on the state the window kept.
8161    /// Returned rather than emitted, so the caller emits with the registry released.
8162    fn scene_state_report(entry: &SceneEntry, always: bool) -> Option<(NodeId, Event)> {
8163        let state = scene_state(entry);
8164        (entry.reported.replace(state.code()) != state.code() || always).then(|| {
8165            log::debug!("uikit: window state now {state:?}");
8166            (
8167                entry.node.unwrap_or(WINDOW_NODE),
8168                Event::WindowStateChanged(state),
8169            )
8170        })
8171    }
8172
8173    /// Have every view controller in `window` that may own the status bar or the home
8174    /// indicator ask again: the root, and whatever is presented over it (a cover takes both
8175    /// over while it is up). In an animation block so the status bar fades.
8176    fn refresh_window_chrome(window: &UIWindow) {
8177        let mut vcs: Vec<Retained<UIViewController>> = Vec::new();
8178        let mut next = window.rootViewController();
8179        while let Some(vc) = next {
8180            next = vc.presentedViewController();
8181            vcs.push(vc);
8182        }
8183        let update = block2::RcBlock::new(move || {
8184            for vc in &vcs {
8185                vc.setNeedsStatusBarAppearanceUpdate();
8186                vc.setNeedsUpdateOfHomeIndicatorAutoHidden();
8187            }
8188        });
8189        unsafe { UIView::animateWithDuration_animations(0.25, &update, mtm()) };
8190    }
8191
8192    /// Whether the screen `window` shows on is being recorded, mirrored or `AirPlayed`. iOS 17
8193    /// moved the answer onto the scene's trait collection and deprecated the screen's flag; the
8194    /// older spelling stays for the earlier releases this backend supports.
8195    fn window_captured(window: &UIWindow) -> bool {
8196        if os_at_least(17) {
8197            window.windowScene().is_some_and(|scene| {
8198                let state = unsafe { scene.traitCollection().sceneCaptureState() };
8199                state == objc2_ui_kit::UISceneCaptureState::Active
8200            })
8201        } else {
8202            #[allow(deprecated)]
8203            window.screen().isCaptured()
8204        }
8205    }
8206
8207    /// Put up or take down each scene's content-protection shield for the current capture
8208    /// state. A shield is a window of its own above the alert level, so nothing the scene
8209    /// presents later (an alert, a cover) can land on top of it. It hides the content from a
8210    /// recording or a mirrored display; a screenshot still captures the app, because iOS tells
8211    /// an app about one only after it is taken.
8212    fn refresh_capture_shields() {
8213        let mtm = mtm();
8214        // Decide with the registry borrowed, act on UIKit without it: a new window joining the
8215        // scene can re-enter Day through the root VC's trait callback.
8216        let work: Vec<(Retained<UIWindow>, bool, Option<Retained<UIWindow>>)> = SCENES.with(|s| {
8217            s.borrow()
8218                .iter()
8219                .map(|e| {
8220                    let want = e.protected.get() && window_captured(&e.window);
8221                    (e.window.clone(), want, e.shield.borrow().clone())
8222                })
8223                .collect()
8224        });
8225        for (window, want, shield) in work {
8226            match (want, shield) {
8227                (true, None) => {
8228                    let Some(scene) = window.windowScene() else {
8229                        continue;
8230                    };
8231                    log::debug!("uikit: screen captured, shielding protected window");
8232                    let cover =
8233                        unsafe { UIWindow::initWithWindowScene(UIWindow::alloc(mtm), &scene) };
8234                    let vc = UIViewController::new(mtm);
8235                    unsafe {
8236                        if let Some(view) = vc.view() {
8237                            view.setBackgroundColor(Some(&UIColor::systemBackgroundColor()));
8238                        }
8239                        cover.setWindowLevel(objc2_ui_kit::UIWindowLevelAlert + 1.0);
8240                        cover.setRootViewController(Some(&vc));
8241                    }
8242                    cover.setHidden(false);
8243                    store_shield(&window, Some(cover));
8244                }
8245                (false, Some(cover)) => {
8246                    log::debug!("uikit: capture ended or protection off, removing shield");
8247                    cover.setHidden(true);
8248                    store_shield(&window, None);
8249                }
8250                _ => {}
8251            }
8252        }
8253    }
8254
8255    /// Record a scene's shield window (or its removal) against the scene that owns `window`.
8256    fn store_shield(window: &UIWindow, shield: Option<Retained<UIWindow>>) {
8257        let wp = std::ptr::from_ref::<UIWindow>(window) as usize;
8258        SCENES.with(|s| {
8259            if let Some(e) = s
8260                .borrow()
8261                .iter()
8262                .find(|e| Retained::as_ptr(&e.window) as usize == wp)
8263            {
8264                *e.shield.borrow_mut() = shield;
8265            }
8266        });
8267    }
8268
8269    /// Day `Edges` bits → `UIRectEdge` (leading/trailing map to left/right).
8270    fn rect_edges() -> UIRectEdge {
8271        let bits = DEFER_EDGES.with(std::cell::Cell::get);
8272        let mut edge = UIRectEdge::empty();
8273        if bits & Edges::TOP.0 != 0 {
8274            edge |= UIRectEdge::Top;
8275        }
8276        if bits & Edges::BOTTOM.0 != 0 {
8277            edge |= UIRectEdge::Bottom;
8278        }
8279        if bits & Edges::LEADING.0 != 0 {
8280            edge |= UIRectEdge::Left;
8281        }
8282        if bits & Edges::TRAILING.0 != 0 {
8283            edge |= UIRectEdge::Right;
8284        }
8285        edge
8286    }
8287
8288    fn first_content_scroll(view: &UIView, depth: usize) -> Option<Retained<UIScrollView>> {
8289        if let Some(scroll) = view.downcast_ref::<UIScrollView>() {
8290            return Some(scroll.retain());
8291        }
8292        if depth == 0 {
8293            return None;
8294        }
8295        for child in &unsafe { view.subviews() } {
8296            if let Some(scroll) = first_content_scroll(&child, depth - 1) {
8297                return Some(scroll);
8298            }
8299        }
8300        None
8301    }
8302
8303    thread_local! {
8304        /// Pages (`DayPageVC` pointers) whose list rested at its top when they last left the
8305        /// screen, to be put back there on the first layout after they reappear.
8306        static PAGE_RESTORE_TOP: RefCell<std::collections::HashSet<usize>> =
8307            RefCell::new(std::collections::HashSet::new());
8308    }
8309
8310    fn immersive_page(vc: &UIViewController) -> bool {
8311        vc.viewIfLoaded().is_some_and(|v| {
8312            v.downcast_ref::<DayNavPageView>()
8313                .is_some_and(|page| page.ivars().immersive)
8314        })
8315    }
8316
8317    // Navigation pages end editing on departure (push, pop and tab selection). Keep the
8318    // request scoped to the outgoing view, so an incoming page's first responder survives.
8319    define_class!(
8320        #[unsafe(super(UIViewController))]
8321        #[thread_kind = MainThreadOnly]
8322        #[name = "DayPageVC"]
8323        struct DayPageVC;
8324
8325        unsafe impl NSObjectProtocol for DayPageVC {}
8326
8327        impl DayPageVC {
8328            #[unsafe(method(preferredStatusBarStyle))]
8329            fn preferred_status_bar_style(&self) -> objc2_ui_kit::UIStatusBarStyle {
8330                if immersive_page(self) {
8331                    objc2_ui_kit::UIStatusBarStyle::LightContent
8332                } else {
8333                    objc2_ui_kit::UIStatusBarStyle::Default
8334                }
8335            }
8336
8337            /// What `UITableViewController` does for its table: a page whose list rested at its
8338            /// top when it left the screen comes back at its top, whatever the bar above it has
8339            /// grown or shrunk to meanwhile. A list left mid-inset reads to UIKit as scrolled,
8340            /// and the large title and search field it carries come back collapsed.
8341            #[unsafe(method(viewWillAppear:))]
8342            fn view_will_appear(&self, animated: bool) {
8343                unsafe {
8344                    let _: () = msg_send![super(self), viewWillAppear: animated];
8345                }
8346                if let Some(nav) = unsafe { self.navigationController() } {
8347                    let bar = unsafe { nav.navigationBar() };
8348                    if immersive_page(self) {
8349                        let appearance = UINavigationBarAppearance::new(self.mtm());
8350                        appearance.configureWithTransparentBackground();
8351                        bar.setStandardAppearance(&appearance);
8352                        bar.setCompactAppearance(Some(&appearance));
8353                        bar.setScrollEdgeAppearance(Some(&appearance));
8354                        bar.setCompactScrollEdgeAppearance(Some(&appearance));
8355                        unsafe {
8356                            bar.setTranslucent(true);
8357                            bar.setBarStyle(objc2_ui_kit::UIBarStyle::Black);
8358                            bar.setTintColor(Some(&UIColor::whiteColor()));
8359                        }
8360                    } else {
8361                        configure_navigation_bar(&bar, self.mtm());
8362                        unsafe {
8363                            bar.setBarStyle(objc2_ui_kit::UIBarStyle::Default);
8364                            bar.setTintColor(None);
8365                        }
8366                    }
8367                    unsafe { nav.setNeedsStatusBarAppearanceUpdate() };
8368                }
8369                // Name the list before UIKit decides the bar's state for this appearance
8370                // (`viewDidLayoutSubviews` is after that decision). Headers and a pinned
8371                // footer make this a multi-child page, so UIKit's own single-scroll-view
8372                // discovery through the wrapper hierarchy finds nothing.
8373                if unsafe { self.navigationItem().searchController() }.is_some()
8374                    && let Some(view) = self.viewIfLoaded()
8375                    && let Some(scroll) = first_content_scroll(&view, 12)
8376                {
8377                    let edge = objc2_ui_kit::NSDirectionalRectEdge::Top;
8378                    if unsafe { self.contentScrollViewForEdge(edge) }.as_deref() != Some(&*scroll) {
8379                        unsafe { self.setContentScrollView_forEdge(Some(&scroll), edge) };
8380                    }
8381                }
8382                let at_top = self
8383                    .viewIfLoaded()
8384                    .and_then(|v| first_content_scroll(&v, 12))
8385                    .is_some_and(|scroll| {
8386                        let y = scroll.contentOffset().y;
8387                        y <= 0.0 && y >= -scroll.adjustedContentInset().top - 1.0
8388                    });
8389                if at_top {
8390                    PAGE_RESTORE_TOP.with(|p| {
8391                        p.borrow_mut().insert(std::ptr::from_ref::<Self>(self) as usize);
8392                    });
8393                }
8394            }
8395
8396            #[unsafe(method(viewDidLayoutSubviews))]
8397            fn view_did_layout_subviews(&self) {
8398                unsafe {
8399                    let _: () = msg_send![super(self), viewDidLayoutSubviews];
8400                    let key = std::ptr::from_ref::<Self>(self) as usize;
8401                    if PAGE_RESTORE_TOP.with(|p| p.borrow_mut().remove(&key))
8402                        && let Some(view) = self.viewIfLoaded()
8403                        && let Some(scroll) = first_content_scroll(&view, 12)
8404                    {
8405                        let top = -scroll.adjustedContentInset().top;
8406                        if scroll.contentOffset().y > top {
8407                            scroll.setContentOffset(objc2_core_foundation::CGPoint::new(
8408                                scroll.contentOffset().x,
8409                                top,
8410                            ));
8411                        }
8412                    }
8413                    let item = self.navigationItem();
8414                    // Whenever the page carries a search controller, not only once its
8415                    // hide-on-scroll is on: the flag goes on a turn after the page first
8416                    // appears (`configure_sidebar_search`), and UIKit reads the scroll edge
8417                    // state from this association at that moment. Without it the bar reads as
8418                    // scrolled, and the title and search collapse the instant the flag lands.
8419                    if item.searchController().is_some() {
8420                        // Headers and a pinned sync footer make this a multi-child page.
8421                        // Explicitly identify its list instead of relying on UIKit's
8422                        // single-scroll-view discovery through the wrapper hierarchy.
8423                        if let Some(view) = self.viewIfLoaded()
8424                            && let Some(scroll) = first_content_scroll(&view, 12)
8425                        {
8426                            let edge = objc2_ui_kit::NSDirectionalRectEdge::Top;
8427                            if self.contentScrollViewForEdge(edge).as_deref() != Some(&*scroll) {
8428                                self.setContentScrollView_forEdge(Some(&scroll), edge);
8429                            }
8430                        }
8431                    }
8432                }
8433            }
8434
8435            #[unsafe(method(viewWillDisappear:))]
8436            fn view_will_disappear(&self, animated: bool) {
8437                unsafe {
8438                    let _: () = msg_send![super(self), viewWillDisappear: animated];
8439                    if let Some(view) = self.viewIfLoaded() {
8440                        view.endEditing(false);
8441                    }
8442                }
8443            }
8444        }
8445    );
8446
8447    /// The cover node a `DayCoverVC` presents, for the sheet's own dismissal report, and how
8448    /// it presents: UIKit makes a fresh presentation controller for every presentation, so the
8449    /// sheet's detents and delegate are applied each time the VC goes up (`configure_sheet`),
8450    /// never once at realize.
8451    struct CoverVcIvars {
8452        node: Cell<u64>,
8453        sheet: Cell<bool>,
8454        half: Cell<bool>,
8455    }
8456
8457    define_class!(
8458        #[unsafe(super(UIViewController))]
8459        #[thread_kind = MainThreadOnly]
8460        #[name = "DayCoverVC"]
8461        #[ivars = CoverVcIvars]
8462        struct DayCoverVC;
8463
8464        unsafe impl NSObjectProtocol for DayCoverVC {}
8465
8466        /// A sheet-style cover (`CoverProps::sheet`, the half sheet included) can be pulled
8467        /// down by the user. UIKit has already dismissed it when this arrives, so it is reported
8468        /// as the back request every cover answers (docs/cover.md): the piece writes `None`,
8469        /// the Dismiss patch finds no presentation left and confirms `CoverHidden` at once.
8470        /// `isModalInPresentation` (the dismissal shield) keeps the gesture from completing,
8471        /// so this never fires for a shielded cover.
8472        unsafe impl UIAdaptivePresentationControllerDelegate for DayCoverVC {
8473            #[unsafe(method(presentationControllerDidDismiss:))]
8474            fn presentation_controller_did_dismiss(
8475                &self,
8476                _controller: &objc2_ui_kit::UIPresentationController,
8477            ) {
8478                let node = self.ivars().node.get();
8479                if node != 0 {
8480                    emit(
8481                        NodeId(node),
8482                        Event::NavBack {
8483                            already_popped: false,
8484                        },
8485                    );
8486                }
8487            }
8488        }
8489
8490        /// The presented cover is the VC UIKit consults for system-gesture deferral, so the
8491        /// `defers_system_gestures` union applies while a game/cover is up.
8492        impl DayCoverVC {
8493            #[unsafe(method(viewWillDisappear:))]
8494            fn view_will_disappear(&self, animated: bool) {
8495                unsafe {
8496                    let _: () = msg_send![super(self), viewWillDisappear: animated];
8497                    if let Some(view) = self.viewIfLoaded() {
8498                        view.endEditing(false);
8499                    }
8500                }
8501            }
8502
8503            #[unsafe(method(preferredScreenEdgesDeferringSystemGestures))]
8504            fn preferred_edges(&self) -> UIRectEdge {
8505                rect_edges()
8506            }
8507
8508            /// A fullscreen presentation takes over the status bar's appearance, so the cover
8509            /// answers for it while it is up: hidden for a mounted `status_bar_hidden`, or
8510            /// while its window is fullscreen (docs/windows.md).
8511            #[unsafe(method(prefersStatusBarHidden))]
8512            fn prefers_status_bar_hidden(&self) -> bool {
8513                STATUS_BAR_HIDDEN.with(std::cell::Cell::get) || vc_window_fullscreen(self)
8514            }
8515
8516            /// And for the home indicator, which fades while the window is fullscreen.
8517            #[unsafe(method(prefersHomeIndicatorAutoHidden))]
8518            fn prefers_home_indicator_auto_hidden(&self) -> bool {
8519                vc_window_fullscreen(self)
8520            }
8521
8522            #[unsafe(method(preferredStatusBarUpdateAnimation))]
8523            fn status_bar_animation(&self) -> objc2_ui_kit::UIStatusBarAnimation {
8524                objc2_ui_kit::UIStatusBarAnimation::Fade
8525            }
8526        }
8527    );
8528
8529    impl DayCoverVC {
8530        fn new(mtm: MainThreadMarker, node: NodeId, sheet: bool, half: bool) -> Retained<Self> {
8531            let this = Self::alloc(mtm).set_ivars(CoverVcIvars {
8532                node: Cell::new(node.0),
8533                sheet: Cell::new(sheet),
8534                half: Cell::new(half),
8535            });
8536            unsafe { msg_send![super(this), init] }
8537        }
8538
8539        /// Dress the presentation this VC is about to get, every time it is presented (see
8540        /// `CoverVcIvars`). A sheet can be pulled down, so the VC hears about it as the
8541        /// presentation controller's delegate. The half sheet (docs/cover.md): the medium
8542        /// detent, with the large one a pull away, and nothing dimmed at medium so the content
8543        /// the sheet describes stays interactive underneath it, the way an iOS inspector sheet
8544        /// does; the grabber says it can be pulled.
8545        fn configure_sheet(&self, mtm: MainThreadMarker) {
8546            if !self.ivars().sheet.get() {
8547                return;
8548            }
8549            unsafe {
8550                if let Some(pc) = self.presentationController() {
8551                    pc.setDelegate(Some(ProtocolObject::from_ref(self)));
8552                }
8553                if self.ivars().half.get()
8554                    && let Some(sheet) = self.sheetPresentationController()
8555                {
8556                    use objc2_ui_kit::UISheetPresentationControllerDetent as Detent;
8557                    let medium = objc2_ui_kit::UISheetPresentationControllerDetentIdentifierMedium;
8558                    sheet.setDetents(&objc2_foundation::NSArray::from_retained_slice(&[
8559                        Detent::mediumDetent(mtm),
8560                        Detent::largeDetent(mtm),
8561                    ]));
8562                    sheet.setSelectedDetentIdentifier(Some(medium));
8563                    sheet.setLargestUndimmedDetentIdentifier(Some(medium));
8564                    sheet.setPrefersGrabberVisible(true);
8565                    sheet.setPrefersScrollingExpandsWhenScrolledToEdge(false);
8566                }
8567            }
8568        }
8569    }
8570
8571    /// The native FRONT of the app's one undo stack (docs/model.md): answers the questions
8572    /// UIKit's undo affordances ask (three-finger gestures, shake, hardware ⌘Z, the iPad menu
8573    /// bar) from mirrored state, and forwards invocations as `Event::Undo`. The stack lives
8574    /// in day-model; two histories can never fork.
8575    pub(super) struct UndoIvars {
8576        pub(super) state: RefCell<day_spec::UndoState>,
8577    }
8578
8579    define_class!(
8580        #[unsafe(super(objc2_foundation::NSUndoManager))]
8581        #[thread_kind = MainThreadOnly]
8582        #[name = "DayUndoManager"]
8583        #[ivars = UndoIvars]
8584        pub(super) struct DayUndoManager;
8585
8586        impl DayUndoManager {
8587            #[unsafe(method(canUndo))]
8588            fn can_undo(&self) -> bool {
8589                self.ivars().state.borrow().can_undo
8590            }
8591
8592            #[unsafe(method(canRedo))]
8593            fn can_redo(&self) -> bool {
8594                self.ivars().state.borrow().can_redo
8595            }
8596
8597            #[unsafe(method(undo))]
8598            fn do_undo(&self) {
8599                day_spec::ffi_guard::contain((), || {
8600                    emit(day_spec::WINDOW_NODE, Event::Undo { redo: false });
8601                });
8602            }
8603
8604            #[unsafe(method(redo))]
8605            fn do_redo(&self) {
8606                day_spec::ffi_guard::contain((), || {
8607                    emit(day_spec::WINDOW_NODE, Event::Undo { redo: true });
8608                });
8609            }
8610
8611            #[unsafe(method_id(undoMenuItemTitle))]
8612            fn undo_menu_item_title(&self) -> Retained<NSString> {
8613                let label = self.ivars().state.borrow().undo_label.clone();
8614                unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8615            }
8616
8617            #[unsafe(method_id(redoMenuItemTitle))]
8618            fn redo_menu_item_title(&self) -> Retained<NSString> {
8619                let label = self.ivars().state.borrow().redo_label.clone();
8620                unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8621            }
8622        }
8623    );
8624
8625    pub(super) fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
8626        UNDO_FRONT.with(|u| {
8627            u.borrow_mut()
8628                .get_or_insert_with(|| {
8629                    let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
8630                        state: RefCell::new(day_spec::UndoState::default()),
8631                    });
8632                    unsafe { msg_send![super(this), init] }
8633                })
8634                .clone()
8635        })
8636    }
8637
8638    define_class!(
8639        #[unsafe(super(UIViewController))]
8640        #[thread_kind = MainThreadOnly]
8641        #[name = "DayRootVC"]
8642        #[ivars = ()]
8643        struct DayRootVC;
8644
8645        /// Same override on the window root, so the modifier also works outside a cover.
8646        impl DayRootVC {
8647            /// Forward color to the visible content while keeping visibility window-owned.
8648            #[unsafe(method_id(childViewControllerForStatusBarStyle))]
8649            fn status_bar_style_child(&self) -> Option<Retained<UIViewController>> {
8650                unsafe { self.childViewControllers().lastObject() }
8651            }
8652
8653            #[unsafe(method(preferredScreenEdgesDeferringSystemGestures))]
8654            fn preferred_edges(&self) -> UIRectEdge {
8655                rect_edges()
8656            }
8657
8658            /// The window root answers for the status bar outside a cover. Its children (the
8659            /// tab and navigation hosts) are not asked: `childViewControllerForStatusBarHidden`
8660            /// stays nil, so one answer covers every page.
8661            #[unsafe(method(prefersStatusBarHidden))]
8662            fn prefers_status_bar_hidden(&self) -> bool {
8663                STATUS_BAR_HIDDEN.with(std::cell::Cell::get) || vc_window_fullscreen(self)
8664            }
8665
8666            #[unsafe(method(preferredStatusBarUpdateAnimation))]
8667            fn status_bar_animation(&self) -> objc2_ui_kit::UIStatusBarAnimation {
8668                objc2_ui_kit::UIStatusBarAnimation::Fade
8669            }
8670
8671            /// Fullscreen on iOS (docs/windows.md): the home indicator fades after a few
8672            /// seconds without a touch and returns on the next one, which is as far as an app
8673            /// can take it.
8674            #[unsafe(method(prefersHomeIndicatorAutoHidden))]
8675            fn prefers_home_indicator_auto_hidden(&self) -> bool {
8676                vc_window_fullscreen(self)
8677            }
8678
8679            /// The scene's capture state is a trait (iOS 17+): a recording or mirroring that
8680            /// starts or stops changes it, so the content-protection shield follows from here
8681            /// as well as from `UIScreenCapturedDidChangeNotification`.
8682            #[unsafe(method(traitCollectionDidChange:))]
8683            fn trait_collection_did_change(
8684                &self,
8685                previous: Option<&objc2_ui_kit::UITraitCollection>,
8686            ) {
8687                let _: () = unsafe { msg_send![super(self), traitCollectionDidChange: previous] };
8688                day_spec::ffi_guard::contain((), refresh_capture_shields);
8689            }
8690
8691            /// The window is crossing a size class — the whole reason a split view collapses or
8692            /// expands. Hold the flag from here until the transition's own completion, so the
8693            /// column restructuring UIKit performs in between is not read as the user
8694            /// navigating (`note_pop`). The window root sees this before any descendant does,
8695            /// which is what makes it early enough: UIKit un-merges the columns before it
8696            /// reports the expansion.
8697            #[unsafe(method(willTransitionToTraitCollection:withTransitionCoordinator:))]
8698            fn will_transition_to_traits(
8699                &self,
8700                traits: &objc2_ui_kit::UITraitCollection,
8701                coordinator: &ProtocolObject<
8702                    dyn objc2_ui_kit::UIViewControllerTransitionCoordinator,
8703                >,
8704            ) {
8705                // SAFETY: forwards the override's own arguments to the superclass implementation.
8706                unsafe {
8707                    let () = msg_send![
8708                        super(self),
8709                        willTransitionToTraitCollection: traits,
8710                        withTransitionCoordinator: coordinator,
8711                    ];
8712                }
8713                day_spec::ffi_guard::contain((), || begin_class_transition(coordinator));
8714            }
8715        }
8716    );
8717
8718    impl DayRootVC {
8719        fn new(mtm: MainThreadMarker) -> Retained<Self> {
8720            let this = Self::alloc(mtm).set_ivars(());
8721            unsafe { msg_send![super(this), init] }
8722        }
8723    }
8724
8725    define_class!(
8726        #[unsafe(super(UIView))]
8727        #[thread_kind = MainThreadOnly]
8728        #[name = "DayHolderView"]
8729        #[ivars = ()]
8730        struct DayHolderView;
8731
8732        /// The window root's content holder. UIKit resizes it on rotation, on iPad
8733        /// multitasking, and — since iPadOS 26 — on every drag of a resizable window's edge,
8734        /// then runs this layout pass. That is Day's size-change rail: re-pin the day root to
8735        /// the current safe area and emit `WindowResized`, the same shape as Android's
8736        /// configuration-change delivery (§9). It fires only when the BASE frame really
8737        /// changed, so the keyboard rail's shrunken root (which alters the frame but not the
8738        /// base) is never stomped.
8739        ///
8740        /// Everything here is resolved through this holder's own scene, never the primary's
8741        /// statics (docs/size-classes.md). One process can hold two windows at two sizes —
8742        /// Stage Manager, two side-by-side iPad windows — and reporting a secondary's geometry
8743        /// against `WINDOW_NODE` re-framed the primary's root view and re-bucketed the wrong
8744        /// window's size class.
8745        impl DayHolderView {
8746            #[unsafe(method(traitCollectionDidChange:))]
8747            fn trait_collection_did_change(
8748                &self,
8749                previous: Option<&objc2_ui_kit::UITraitCollection>,
8750            ) {
8751                let _: () = unsafe { msg_send![super(self), traitCollectionDidChange: previous] };
8752                day_spec::ffi_guard::contain((), || note_host_traits(self, previous));
8753            }
8754
8755            #[unsafe(method(layoutSubviews))]
8756            fn layout_subviews(&self) {
8757                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
8758                // The WindowResized report dispatches day-core's relayout — contained (§8.5).
8759                day_spec::ffi_guard::contain((), || {
8760                    // Before this holder's window is in a scene — or before launch published
8761                    // its root — the launch frame computation owns this; nothing to re-pin.
8762                    let Some((root, base, target)) = with_scene_of(self, |e| {
8763                        (e.root_view.clone(), e.base_frame.get(), key_scene_target(e))
8764                    }) else {
8765                        return;
8766                    };
8767                    let bounds = self.bounds();
8768                    let insets = self.safeAreaInsets();
8769                    // The same rule a page applies (§7.7, `scroll_leaf`): a root that is one
8770                    // navigation, split or tab host — or one scroll view — takes the WINDOW's
8771                    // bounds, bars and all, and the host hands the status bar and the home
8772                    // indicator to its pages as safe area. Padded, the host's bars stopped at
8773                    // the padding and the strip above the nav bar and below the tab bar was
8774                    // this holder's own ground. Anything else keeps the padding: a form has
8775                    // nothing to absorb a status bar with.
8776                    let full = scroll_leaf(self);
8777                    let mut inner = content_frame(bounds, insets, full);
8778                    // A window with no navigation host of its own carries the window toolbar
8779                    // here, across the top (docs/toolbars.md), where a page's bar would be.
8780                    // Framed on every pass rather than autoresized: its height is the bar's
8781                    // own answer for this width and it starts at the safe area's top edge,
8782                    // both of which a rotation changes — and the root's own frame is measured
8783                    // from them. A standalone bar lays its items out in the frame it is GIVEN
8784                    // (a navigation controller's insets itself), so a bar spanning the top
8785                    // inset would center its items over the status bar.
8786                    if let Some(bar) = docked_window_toolbar(&root) {
8787                        let h = bar.sizeThatFits(bounds.size).height;
8788                        unsafe {
8789                            bar.setFrame(CGRect::new(
8790                                CGPoint::new(0.0, insets.top),
8791                                CGSize::new(bounds.size.width, h),
8792                            ));
8793                        };
8794                        inner.origin.y += h;
8795                        inner.size.height = (inner.size.height - h).max(0.0);
8796                    }
8797                    #[expect(
8798                        clippy::float_cmp,
8799                        reason = "unchanged-frame check against the exact frame stored last time"
8800                    )]
8801                    let unchanged = inner.origin.x == base.origin.x
8802                        && inner.origin.y == base.origin.y
8803                        && inner.size.width == base.size.width
8804                        && inner.size.height == base.size.height;
8805                    if unchanged {
8806                        return;
8807                    }
8808                    // Stored before `emit`, and with the registry borrow already dropped: the
8809                    // report re-enters day-core, which reads scenes back.
8810                    with_scene_of(self, |e| e.base_frame.set(inner));
8811                    if target == WINDOW_NODE {
8812                        ROOT_BASE_FRAME.with(|f| f.set(inner));
8813                    }
8814                    unsafe { root.setFrame(inner) };
8815                    if *DIAG_NAV {
8816                        log::debug!(
8817                            "DAYDIAG holder node={:?} bounds={}x{} safe(t{} b{} l{} r{}) -> inner=({},{} {}x{})",
8818                            target,
8819                            bounds.size.width,
8820                            bounds.size.height,
8821                            insets.top,
8822                            insets.bottom,
8823                            insets.left,
8824                            insets.right,
8825                            inner.origin.x,
8826                            inner.origin.y,
8827                            inner.size.width,
8828                            inner.size.height,
8829                        );
8830                    }
8831                    emit(
8832                        target,
8833                        Event::WindowResized(Size::new(inner.size.width, inner.size.height)),
8834                    );
8835                });
8836            }
8837        }
8838    );
8839
8840    impl DayHolderView {
8841        fn new(mtm: MainThreadMarker) -> Retained<Self> {
8842            let this = Self::alloc(mtm).set_ivars(());
8843            unsafe { msg_send![super(this), init] }
8844        }
8845    }
8846
8847    /// Queue the cover's presentation behind any in-flight modal transition (§dialogs FIFO).
8848    fn cover_present(vc: Retained<DayCoverVC>) {
8849        modal_enqueue(ModalOp::Cover(vc, 0));
8850    }
8851
8852    /// Queue the cover's dismissal; the completion reports `CoverHidden` so the piece can
8853    /// dispose the content only after it left the screen.
8854    fn cover_dismiss(vc: Retained<DayCoverVC>, node: NodeId) {
8855        modal_enqueue(ModalOp::Run(Box::new(move || {
8856            let Some(presenting) = vc.presentingViewController() else {
8857                emit(node, Event::CoverHidden);
8858                return;
8859            };
8860            modal_begin_transition();
8861            // The completion is the normal `CoverHidden` source — but UIKit can drop a
8862            // transition completion outright (same failure the modal watchdog exists for),
8863            // and the piece would then never dispose the hidden content. The fallback
8864            // watchdog emits once the VC has actually left the hierarchy; the piece's
8865            // closing gate makes a duplicate report harmless.
8866            let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
8867            let completion = {
8868                let fired = fired.clone();
8869                block2::RcBlock::new(move || {
8870                    fired.store(true, std::sync::atomic::Ordering::Relaxed);
8871                    emit(node, Event::CoverHidden);
8872                    modal_end_transition();
8873                })
8874            };
8875            unsafe {
8876                presenting.dismissViewControllerAnimated_completion(true, Some(&completion));
8877            }
8878            let mtm = objc2::MainThreadMarker::new().expect("cover ops run on main");
8879            let vc_probe = dispatch2::MainThreadBound::new(vc.clone(), mtm);
8880            let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(1500))
8881                .unwrap_or(dispatch2::DispatchTime::NOW);
8882            let _ = dispatch2::DispatchQueue::main().after(when, move || {
8883                let mtm = objc2::MainThreadMarker::new().expect("dispatched to main");
8884                if !fired.load(std::sync::atomic::Ordering::Relaxed)
8885                    && vc_probe.get(mtm).presentingViewController().is_none()
8886                {
8887                    log::warn!("cover dismissal completion lost — reporting CoverHidden");
8888                    emit(node, Event::CoverHidden);
8889                }
8890            });
8891        })));
8892    }
8893
8894    // -------------------------------------------------------------------
8895    // Tabs (docs/navigation.md): UITabBarController child-contained in the root VC.
8896    // Each tab page is a UIViewController wrapping a DayNavPageView (safe-area
8897    // pinned content + FrameChanged), identical to a nav page.
8898    // -------------------------------------------------------------------
8899
8900    // -------------------------------------------------------------------
8901    // Adaptive tabs (docs/navigation.md): a NAV host lowered `Tabs` becomes a
8902    // `UITabBarController` in `.tabSidebar` mode — one controller that draws a tab bar when the
8903    // window is compact and a sidebar when it is not, with UIKit's own animation and the
8904    // iPadOS user-facing toggle. It is what SwiftUI's `.tabViewStyle(.sidebarAdaptable)`
8905    // compiles down to.
8906    //
8907    // Two consequences shape everything below. UIKit draws the SIDEBAR itself, from the same
8908    // tabs — so Day's `Pane::Sidebar` page has nothing to render and is left out of the
8909    // controller entirely. And every tab keeps its own view controller at every width, so the
8910    // host reports `Tabs` once and stays there: it never flips to push/pop as it widens, which
8911    // is why day-core keeps its pages resident and drives them with `NavPatch::Select`.
8912    // -------------------------------------------------------------------
8913
8914    // Browser documents are custom containers, never application-section tab controllers.
8915    struct DocumentHost {
8916        controller: Retained<UIViewController>,
8917        pages: Vec<(usize, Retained<UIViewController>)>,
8918        selected: usize,
8919    }
8920    fn document_frames(host: &UIView, state: &DocumentHost) {
8921        for (i, (_, vc)) in state.pages.iter().enumerate() {
8922            unsafe {
8923                if let Some(view) = vc.view() {
8924                    view.setFrame(host.bounds());
8925                    if i != state.selected && !view.isHidden() {
8926                        view.endEditing(false);
8927                    }
8928                    view.setHidden(i != state.selected);
8929                }
8930            }
8931        }
8932    }
8933
8934    /// A nav host's rows as a `.tabSidebar` host's tabs wear them: label, glyph and badge.
8935    #[derive(Clone, Default)]
8936    struct NavTabRows {
8937        titles: Vec<String>,
8938        icons: Vec<Option<String>>,
8939        badges: Vec<Option<String>>,
8940    }
8941
8942    struct NavTabsState {
8943        tabbar: Retained<UITabBarController>,
8944        /// Detail pages in insertion order — index i IS the `Select(i)` index.
8945        vcs: Vec<Retained<UIViewController>>,
8946        /// The `UITab` per page, parallel to `vcs`. Each carries its index as its IDENTIFIER,
8947        /// which is what turns a delegate callback back into a Day row and what `Select` looks up.
8948        tabs: Vec<Retained<objc2_ui_kit::UITab>>,
8949        /// Row labels, glyphs and badges from the host's `NAV_MENU`, which is where a nav host's
8950        /// rows live. Kept current by the menu's `NavMenuPatch::Items` (a language change, a
8951        /// badge count), which re-syncs the tabs.
8952        rows: NavTabRows,
8953        /// The `NAV_MENU`'s view, which is how that patch finds the host it feeds.
8954        menu_view: std::cell::Cell<usize>,
8955        /// The `NAV_MENU`'s node — a tab tap emits against it, exactly as a sidebar row click does,
8956        /// so the two are one event to everything above this backend.
8957        menu_node: std::cell::Cell<i64>,
8958        /// Suppresses the echo while Day drives the controller.
8959        ///
8960        /// `didSelectViewController:` fired for USER taps only, so the old delegate needed no
8961        /// guard. `didSelectTab:previousTab:` also fires for programmatic selection — including
8962        /// the one UIKit makes for itself inside `setTabs` — so installing the tabs reported a
8963        /// selection the user never made, and the app's bound signal followed it (the Showcase's
8964        /// tab demo came up on its third tab). This is the same origin guard every other
8965        /// two-way control in this backend carries.
8966        suppress: std::cell::Cell<bool>,
8967        /// Latest deferred selection; stale callbacks cannot override a newer selection.
8968        pending_selection: std::cell::Cell<Option<u64>>,
8969        _delegate: Retained<DayNavTabsDelegate>,
8970    }
8971
8972    /// Walk up from `v` for a `.tabSidebar` host — either the host's own view, or a PAGE known
8973    /// to belong to one.
8974    ///
8975    /// The page lookup is what makes the sidebar page reachable. Its view is deliberately never
8976    /// added to the controller (UIKit draws the sidebar itself), so it has no superview chain
8977    /// running to the host — but the rows Day needs for the tab labels live inside it. Recording
8978    /// the page → host edge at insert is what lets the menu find its way home anyway.
8979    fn enclosing_tabs_host(v: &UIView) -> Option<usize> {
8980        let mut cur = Some(v.retain());
8981        while let Some(view) = cur {
8982            let p = ptr_of(&view_of(&view));
8983            if NAV_TABS.with(|m| m.borrow().contains_key(&p)) {
8984                return Some(p);
8985            }
8986            if let Some(host) = TABS_PAGE_HOST.with(|m| m.borrow().get(&p).copied()) {
8987                return Some(host);
8988            }
8989            cur = unsafe { view.superview() };
8990        }
8991        None
8992    }
8993
8994    struct NavTabsDelegateIvars {
8995        host: std::cell::Cell<usize>,
8996    }
8997
8998    define_class!(
8999        #[unsafe(super(NSObject))]
9000        #[thread_kind = MainThreadOnly]
9001        #[name = "DayNavTabsDelegate"]
9002        #[ivars = NavTabsDelegateIvars]
9003        struct DayNavTabsDelegate;
9004
9005        unsafe impl NSObjectProtocol for DayNavTabsDelegate {}
9006
9007        unsafe impl UITabBarControllerDelegate for DayNavTabsDelegate {
9008            /// The pre-`UITab` callback (iOS 17 and older, where `setTabs:` does not exist and the
9009            /// host runs on `setViewControllers:`). The controller IS the identity there, so the
9010            /// row is its position in `vcs` — the same mirror `NavPatch::Select` indexes.
9011            #[unsafe(method(tabBarController:didSelectViewController:))]
9012            fn did_select_vc(&self, _tabbar: &UITabBarController, selected: &UIViewController) {
9013                day_spec::ffi_guard::contain((), || {
9014                    let sel = ptr_of(&view_of(
9015                        &unsafe { selected.view() }.expect("selected page view"),
9016                    ));
9017                    let found = NAV_TABS.with(|m| {
9018                        let m = m.borrow();
9019                        let t = m.get(&self.ivars().host.get())?;
9020                        if t.suppress.get() {
9021                            return None;
9022                        }
9023                        t.pending_selection.set(None);
9024                        let idx = t.vcs.iter().position(|vc| {
9025                            unsafe { vc.view() }.is_some_and(|v| ptr_of(&view_of(&v)) == sel)
9026                        })?;
9027                        Some((t.menu_node.get(), idx as i64))
9028                    });
9029                    if let Some((n, idx)) = found.filter(|(n, _)| *n != 0) {
9030                        emit(NodeId(n as u64), Event::SelectionChanged(idx));
9031                    }
9032                });
9033            }
9034        }
9035
9036        /// The tab-based callback, not `didSelectViewController:`. Both fire on iOS 18+, but only
9037        /// this one names the TAB — and a tab is the thing Day addresses there, so the row comes
9038        /// from its identifier rather than from `selectedIndex`, which cannot see into a group.
9039        ///
9040        /// Declared outside the protocol block on purpose. A protocol block asks the RUNTIME for
9041        /// the nav host's type encoding, and `tabBarController:didSelectTab:previousTab:` is iOS
9042        /// 18's — on an older runtime the class fails to register at all ("method not found"),
9043        /// which took the whole scene down the moment a tabs host was realized. As a plain method
9044        /// objc2 derives the encoding from these types instead, UIKit dispatches it by nav host
9045        /// where it exists, and nothing asks for it where it does not.
9046        impl DayNavTabsDelegate {
9047            #[unsafe(method(tabBarController:didSelectTab:previousTab:))]
9048            fn did_select(
9049                &self,
9050                _tabbar: &UITabBarController,
9051                selected: &objc2_ui_kit::UITab,
9052                _previous: Option<&objc2_ui_kit::UITab>,
9053            ) {
9054                // UIKit calls this only for user taps, not programmatic selection — no echo
9055                // guard needed; the panic containment is §8.5.
9056                day_spec::ffi_guard::contain((), || {
9057                    let id = unsafe { selected.identifier() }.to_string();
9058                    let found = NAV_TABS.with(|m| {
9059                        let m = m.borrow();
9060                        let t = m.get(&self.ivars().host.get())?;
9061                        if t.suppress.get() {
9062                            return None;
9063                        }
9064                        t.pending_selection.set(None);
9065                        let idx = t
9066                            .tabs
9067                            .iter()
9068                            .position(|tab| unsafe { tab.identifier() }.to_string() == id)?;
9069                        Some((t.menu_node.get(), idx as i64))
9070                    });
9071                    if let Some((n, idx)) = found.filter(|(n, _)| *n != 0) {
9072                        emit(NodeId(n as u64), Event::SelectionChanged(idx));
9073                    }
9074                });
9075            }
9076        }
9077    );
9078
9079    /// Rebuild the host's `UITab`s from its rows and hand them to the controller.
9080    /// Called whenever either side changes — a page joining, or the rows arriving/being re-derived.
9081    ///
9082    /// `UITab` rather than a `viewControllers` array of `UITabBarItem`s (2026-09). Apple's guidance
9083    /// since iOS 18 is that adopting `UITab` is what gives a tab bar its automatic adaptivity —
9084    /// the tab bar and the sidebar are then two renderings of one list of tabs, which is exactly
9085    /// Day's model, and it is what `.tabSidebar` mode is built to consume. The old array still
9086    /// works, but the controller has to infer everything from view controllers, and the
9087    /// sidebar-side affordances (reordering, customization, `sidebar.preferredPlacement`) have no
9088    /// tab to hang on.
9089    ///
9090    /// Each tab keeps its Day index as its IDENTIFIER, so a delegate callback resolves to a row
9091    /// without consulting `selectedIndex` — an index that stops meaning "the nth row" the moment
9092    /// tabs nest.
9093    ///
9094    /// The view-controller provider hands back the page Day already built. `vcs` owns it for the
9095    /// life of the host, so the block returns a borrow rather than transferring anything.
9096    impl DayNavTabsDelegate {
9097        fn new(mtm: MainThreadMarker, host: usize) -> Retained<Self> {
9098            let this = Self::alloc(mtm).set_ivars(NavTabsDelegateIvars {
9099                host: std::cell::Cell::new(host),
9100            });
9101            unsafe { msg_send![super(this), init] }
9102        }
9103    }
9104
9105    /// The host's tabs, rebuilt from its pages and its rows (docs/navigation.md).
9106    ///
9107    /// The glyph is handed over exactly as the app staged it: a tab bar draws the image at its own
9108    /// size, so a tab icon is a matter of AUTHORING the glyph at icon size (docs/vectors.md), not
9109    /// of resizing it here — thumbnailing downsamples the catalog's bitmap rendition and throws
9110    /// away the vector representation that put it there.
9111    /// Give a tab back its page alone once the page turns out to bring a navigation host of its
9112    /// own (a `nav_stack` at its root).
9113    ///
9114    /// `insert` wraps a tab's page in a navigation controller on a wide window, because that is
9115    /// the only thing that gives a tab a bar for its page's commands. A page that composes its
9116    /// own stack already has one, and the wrapper stacked a second bar over it with the same
9117    /// title and the same commands (Stanza's tabs on an iPad). The stack is inserted after its
9118    /// page, so the wrapper is undone here, when it arrives, which leaves the tab as a compact
9119    /// window has it: the page, whose stack owns the bar.
9120    fn unwrap_tab_page(page_vc: &Retained<UIViewController>) {
9121        let found =
9122            NAV_TABS.with(|m| {
9123                let mut m = m.borrow_mut();
9124                m.iter_mut().find_map(|(host, t)| {
9125                    let at =
9126                        t.vcs.iter().position(|vc| {
9127                            vc.downcast_ref::<objc2_ui_kit::UINavigationController>()
9128                                .is_some_and(|n| {
9129                                    unsafe { n.viewControllers() }.iter().next().is_some_and(
9130                                        |root| Retained::as_ptr(&root) == Retained::as_ptr(page_vc),
9131                                    )
9132                                })
9133                        })?;
9134                    Some((*host, std::mem::replace(&mut t.vcs[at], page_vc.clone())))
9135                })
9136            });
9137        let Some((host, wrapper)) = found else { return };
9138        // The page leaves the wrapper before it becomes the tab's own controller: UIKit takes a
9139        // controller with a parent as a tab only after asserting.
9140        if let Some(n) = wrapper.downcast_ref::<objc2_ui_kit::UINavigationController>() {
9141            unsafe { n.setViewControllers(&objc2_foundation::NSArray::new()) };
9142        }
9143        nav_tabs_sync(host);
9144    }
9145
9146    fn nav_tabs_sync(host: usize) {
9147        let Some(mtm) = MainThreadMarker::new() else {
9148            return;
9149        };
9150        // `UITab` and `setTabs:` are iOS 18's. Asked of the CONTROLLER rather than of a version
9151        // number, the way `setMode:` is asked above: it is the fact the call depends on, and an
9152        // older runtime then takes the `setViewControllers:` shape an iOS 17 app always had
9153        // instead of dying on a class that is not there (docs/navigation.md).
9154        let modern = NAV_TABS.with(|m| {
9155            m.borrow()
9156                .get(&host)
9157                .map(|t| t.tabbar.respondsToSelector(objc2::sel!(setTabs:)))
9158        });
9159        match modern {
9160            None => return,
9161            Some(false) => {
9162                nav_tabs_sync_classic(host);
9163                return;
9164            }
9165            Some(true) => {}
9166        }
9167        // Build outside the borrow: creating a tab retains a provider block, and `setTabs` can
9168        // call back into UIKit while the map is held.
9169        let built: Option<(
9170            Retained<UITabBarController>,
9171            Vec<Retained<objc2_ui_kit::UITab>>,
9172        )> = NAV_TABS.with(|m| {
9173            let m = m.borrow();
9174            let t = m.get(&host)?;
9175            let tabs: Vec<Retained<objc2_ui_kit::UITab>> = t
9176                .vcs
9177                .iter()
9178                .enumerate()
9179                .map(|(i, vc)| {
9180                    let title = t.rows.titles.get(i).cloned().unwrap_or_default();
9181                    let badge = t.rows.badges.get(i).cloned().flatten();
9182                    let badge = badge
9183                        .as_deref()
9184                        .filter(|b| !b.is_empty())
9185                        .map(NSString::from_str);
9186                    let image = t
9187                        .rows
9188                        .icons
9189                        .get(i)
9190                        .and_then(|o| o.as_deref())
9191                        .and_then(load_bundled_uiimage);
9192                    unsafe { vc.setTitle(Some(&NSString::from_str(&title))) };
9193                    // REUSE the tab that already stands for this page. A `UITab` is a model
9194                    // object with an identity, not a per-render descriptor: its provider
9195                    // hands UIKit a view controller and UIKit then owns that controller as
9196                    // the tab's. Minting a second tab for the same page — which rebuilding
9197                    // on every sync did, and this host syncs on every page insert and every
9198                    // rows change — leaves two tabs claiming one controller, and UIKit
9199                    // asserts in `-[UITab viewController]` the moment it resolves the
9200                    // second. Only the title and the glyph are re-applied.
9201                    let key = ptr_of(&view_of(&unsafe { vc.view() }.expect("page view")));
9202                    if let Some(existing) = t
9203                        .tabs
9204                        .iter()
9205                        .find(|tab| unsafe { tab.identifier() }.to_string() == key.to_string())
9206                    {
9207                        unsafe {
9208                            existing.setTitle(&NSString::from_str(&title));
9209                            existing.setImage(image.as_deref());
9210                            existing.setBadgeValue(badge.as_deref());
9211                        }
9212                        return existing.clone();
9213                    }
9214                    let page = vc.clone();
9215                    let provider = block2::RcBlock::new(
9216                        move |_tab: NonNull<objc2_ui_kit::UITab>| -> NonNull<UIViewController> {
9217                            NonNull::from(&*page)
9218                        },
9219                    );
9220                    let tab = unsafe {
9221                        objc2_ui_kit::UITab::initWithTitle_image_identifier_viewControllerProvider(
9222                            objc2_ui_kit::UITab::alloc(mtm),
9223                            &NSString::from_str(&title),
9224                            image.as_deref(),
9225                            // The PAGE is the identity, not its position: `insert` can put a
9226                            // page in the middle, and a tab's identifier is fixed at
9227                            // construction. Day's index is then the tab's position in `tabs`.
9228                            &NSString::from_str(&key.to_string()),
9229                            Some(&provider),
9230                        )
9231                    };
9232                    unsafe { tab.setBadgeValue(badge.as_deref()) };
9233                    tab
9234                })
9235                .collect();
9236            Some((t.tabbar.clone(), tabs))
9237        });
9238        let Some((tabbar, tabs)) = built else { return };
9239        NAV_TABS.with(|m| {
9240            if let Some(t) = m.borrow_mut().get_mut(&host) {
9241                t.tabs.clone_from(&tabs);
9242                t.suppress.set(true);
9243            }
9244        });
9245        unsafe { tabbar.setTabs(&objc2_foundation::NSArray::from_retained_slice(&tabs)) };
9246        NAV_TABS.with(|m| {
9247            if let Some(t) = m.borrow().get(&host) {
9248                t.suppress.set(false);
9249            }
9250        });
9251    }
9252
9253    /// New words or counts on the same tabs: set on the `UITab`s (or, before iOS 18, the
9254    /// controllers' tab bar items) already installed, without handing UIKit the tab array again.
9255    fn nav_tabs_refresh(host: usize) {
9256        let modern = NAV_TABS.with(|m| {
9257            m.borrow()
9258                .get(&host)
9259                .map(|t| t.tabbar.respondsToSelector(objc2::sel!(setTabs:)))
9260        });
9261        if modern != Some(true) {
9262            // The classic sync already re-sets nothing when the controllers are unchanged.
9263            nav_tabs_sync_classic(host);
9264            return;
9265        }
9266        NAV_TABS.with(|m| {
9267            let m = m.borrow();
9268            let Some(t) = m.get(&host) else { return };
9269            for (i, tab) in t.tabs.iter().enumerate() {
9270                let title = t.rows.titles.get(i).cloned().unwrap_or_default();
9271                let badge = t
9272                    .rows
9273                    .badges
9274                    .get(i)
9275                    .cloned()
9276                    .flatten()
9277                    .filter(|b| !b.is_empty());
9278                let image = t
9279                    .rows
9280                    .icons
9281                    .get(i)
9282                    .and_then(|o| o.as_deref())
9283                    .and_then(load_bundled_uiimage);
9284                unsafe {
9285                    tab.setTitle(&NSString::from_str(&title));
9286                    tab.setImage(image.as_deref());
9287                    tab.setBadgeValue(badge.as_deref().map(NSString::from_str).as_deref());
9288                    if let Some(vc) = t.vcs.get(i) {
9289                        vc.setTitle(Some(&NSString::from_str(&title)));
9290                    }
9291                }
9292            }
9293        });
9294    }
9295
9296    /// The same sync on a runtime without `UITab` (iOS 17 and older): the controller's own
9297    /// `viewControllers`, each page carrying its title and glyph on the `UITabBarItem` UIKit
9298    /// makes for it. `NavTabsState::tabs` stays empty there, which is what tells `Select` and
9299    /// the delegate to address a page by its INDEX — the position in `vcs` — rather than by a
9300    /// tab identity that does not exist.
9301    ///
9302    /// The roster is only re-set when it really changed: `setViewControllers:` rebuilds the bar
9303    /// and can drop the selection, and this host syncs on every page insert and every rows
9304    /// change. The showing page is restored either way, since a rebuild that keeps the same
9305    /// pages must not send the user back to the first one.
9306    fn nav_tabs_sync_classic(host: usize) {
9307        let built = NAV_TABS.with(|m| {
9308            let m = m.borrow();
9309            let t = m.get(&host)?;
9310            for (i, vc) in t.vcs.iter().enumerate() {
9311                let title = t.rows.titles.get(i).cloned().unwrap_or_default();
9312                let badge = t
9313                    .rows
9314                    .badges
9315                    .get(i)
9316                    .cloned()
9317                    .flatten()
9318                    .filter(|b| !b.is_empty());
9319                let image = t
9320                    .rows
9321                    .icons
9322                    .get(i)
9323                    .and_then(|o| o.as_deref())
9324                    .and_then(load_bundled_uiimage);
9325                unsafe {
9326                    vc.setTitle(Some(&NSString::from_str(&title)));
9327                    // UIKit makes the item on first access; `None` only before the controller
9328                    // has one at all, which a page that is already in `vcs` always does.
9329                    if let Some(item) = vc.tabBarItem() {
9330                        item.setTitle(Some(&NSString::from_str(&title)));
9331                        item.setImage(image.as_deref());
9332                        item.setBadgeValue(badge.as_deref().map(NSString::from_str).as_deref());
9333                    }
9334                }
9335            }
9336            Some((t.tabbar.clone(), t.vcs.clone()))
9337        });
9338        let Some((tabbar, vcs)) = built else { return };
9339        let current = unsafe { tabbar.viewControllers() };
9340        let unchanged = current.is_some_and(|cur| {
9341            cur.len() == vcs.len()
9342                && cur
9343                    .iter()
9344                    .zip(vcs.iter())
9345                    .all(|(a, b)| Retained::as_ptr(&a) == Retained::as_ptr(b))
9346        });
9347        if unchanged {
9348            return;
9349        }
9350        let showing = unsafe { tabbar.selectedIndex() };
9351        NAV_TABS.with(|m| {
9352            if let Some(t) = m.borrow().get(&host) {
9353                t.suppress.set(true);
9354            }
9355        });
9356        unsafe {
9357            tabbar.setViewControllers(Some(&objc2_foundation::NSArray::from_retained_slice(&vcs)));
9358            if showing < vcs.len() {
9359                tabbar.setSelectedIndex(showing);
9360            }
9361        }
9362        NAV_TABS.with(|m| {
9363            if let Some(t) = m.borrow().get(&host) {
9364                t.suppress.set(false);
9365            }
9366        });
9367    }
9368
9369    // -------------------------------------------------------------------
9370    // DayNavTableData — nav_menu() as a SIDEBAR list: `UICollectionViewListCell` rows whose
9371    // content and background configurations are the adaptive ones, so UIKit draws the glyph, the
9372    // label, the chevron and the selection pill from the list's own appearance (docs/navigation.md)
9373    // -------------------------------------------------------------------
9374
9375    struct NavTableIvars {
9376        node: NodeId,
9377        items: RefCell<Vec<Retained<NSString>>>,
9378        /// Per-row icon tint (docs/vectors.md); `None` keeps the neutral template look.
9379        tints: RefCell<Vec<Option<day_spec::Ink>>>,
9380        /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has none.
9381        /// Template mode tints them with the cell's tint color (the iOS list idiom).
9382        icons: RefCell<Vec<Option<Retained<objc2_ui_kit::UIImage>>>>,
9383        /// Trailing status glyphs per row, resolved the same way as `icons`.
9384        icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
9385        badges: RefCell<Vec<Option<String>>>,
9386        badge_icons: RefCell<Vec<Option<Retained<objc2_ui_kit::UIImage>>>>,
9387        /// Tint for `badge_icons`; `None` keeps the neutral template look.
9388        badge_tints: RefCell<Vec<Option<day_spec::Ink>>>,
9389        /// Per-row context menu (docs/menus.md), empty = none — served through the table
9390        /// delegate's row-context hook, the standard iOS long-press row menu.
9391        menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
9392        /// A heading introducing the row at the same index (`NavMenuProps::sections`): `Some`
9393        /// opens a group before that row, `None` continues the current one. Parallel to `items`,
9394        /// which is what keeps a heading from shifting the indices rows are addressed by.
9395        sections: RefCell<Vec<Option<String>>>,
9396        /// Whether the LAYOUT currently draws headings — it is baked in at construction, so a
9397        /// data-driven set that changes the answer has to install a new one.
9398        headers: std::cell::Cell<bool>,
9399    }
9400
9401    define_class!(
9402        #[unsafe(super(NSObject))]
9403        #[thread_kind = MainThreadOnly]
9404        #[name = "DayNavTableData"]
9405        #[ivars = NavTableIvars]
9406        struct DayNavTableData;
9407
9408        unsafe impl NSObjectProtocol for DayNavTableData {}
9409        unsafe impl UIScrollViewDelegate for DayNavTableData {}
9410
9411        unsafe impl UICollectionViewDataSource for DayNavTableData {
9412            /// One section per heading (`NavMenuProps::sections`). A list with no headings is one
9413            /// section, which is the flat list this always drew.
9414            #[unsafe(method(numberOfSectionsInCollectionView:))]
9415            fn number_of_sections(&self, _cv: &objc2_ui_kit::UICollectionView) -> isize {
9416                self.groups().len().max(1) as isize
9417            }
9418
9419            #[unsafe(method(collectionView:numberOfItemsInSection:))]
9420            fn rows_in_section(
9421                &self,
9422                _cv: &objc2_ui_kit::UICollectionView,
9423                section: isize,
9424            ) -> isize {
9425                self.groups()
9426                    .get(section as usize)
9427                    .map_or(0, |(_, _, len)| *len as isize)
9428            }
9429
9430            /// The section's heading, as a list HEADER supplementary (docs/navigation.md).
9431            ///
9432            /// `headerConfiguration` is the adaptive one, like the cells': it reads the
9433            /// `listEnvironment` trait the sidebar appearance publishes and resolves itself to
9434            /// that appearance's header — the small, uppercase-ish group label a source list uses
9435            /// — so nothing here names a font or an inset.
9436            #[unsafe(method_id(collectionView:viewForSupplementaryElementOfKind:atIndexPath:))]
9437            fn header_for_section(
9438                &self,
9439                cv: &objc2_ui_kit::UICollectionView,
9440                kind: &NSString,
9441                index_path: &objc2_foundation::NSIndexPath,
9442            ) -> Retained<objc2_ui_kit::UICollectionReusableView> {
9443                let view: Retained<objc2_ui_kit::UICollectionViewListCell> = unsafe {
9444                    cv.dequeueReusableSupplementaryViewOfKind_withReuseIdentifier_forIndexPath(
9445                        kind,
9446                        &NSString::from_str(NAV_HEADER_ID),
9447                        index_path,
9448                    )
9449                }
9450                .downcast()
9451                .expect("the registered header class IS UICollectionViewListCell");
9452                let title = self
9453                    .groups()
9454                    .get(unsafe { index_path.section() } as usize)
9455                    .and_then(|(t, _, _)| t.clone());
9456                // The view's OWN default, which UIKit resolves for a header in this list's
9457                // style. The adaptive class method `+headerConfiguration` would say the same
9458                // thing, but it is iOS 18+, and on anything older the message is not ignored —
9459                // it is `method not found` and an abort before the first frame.
9460                let content = unsafe { view.defaultContentConfiguration() };
9461                unsafe {
9462                    // A leading run of rows before the first heading has none to draw. The
9463                    // configuration still applies, so the header collapses to nothing rather than
9464                    // reserving a blank band.
9465                    content.setText(title.as_deref().map(NSString::from_str).as_deref());
9466                    view.setContentConfiguration(Some(ProtocolObject::from_ref(&*content)));
9467                }
9468                // ListCell -> Cell -> ReusableView: the supplementary method answers in the base.
9469                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(view))
9470            }
9471
9472            #[unsafe(method_id(collectionView:cellForItemAtIndexPath:))]
9473            fn cell_for_row(
9474                &self,
9475                cv: &objc2_ui_kit::UICollectionView,
9476                index_path: &objc2_foundation::NSIndexPath,
9477            ) -> Retained<objc2_ui_kit::UICollectionViewCell> {
9478                let mtm = self.mtm();
9479                let cell: Retained<objc2_ui_kit::UICollectionViewListCell> = unsafe {
9480                    cv.dequeueReusableCellWithReuseIdentifier_forIndexPath(
9481                        &NSString::from_str(NAV_CELL_ID),
9482                        index_path,
9483                    )
9484                }
9485                .downcast()
9486                .expect("the registered class IS UICollectionViewListCell");
9487                let row = self
9488                    .row_of(
9489                        unsafe { index_path.section() } as usize,
9490                        unsafe { index_path.item() } as usize,
9491                    )
9492                    .unwrap_or(0);
9493                let title = self
9494                    .ivars()
9495                    .items
9496                    .borrow()
9497                    .get(row)
9498                    .cloned()
9499                    .unwrap_or_else(|| NSString::from_str(""));
9500                let img = self
9501                    .ivars()
9502                    .icons
9503                    .borrow()
9504                    .get(row)
9505                    .and_then(std::clone::Clone::clone);
9506                let tint = self.ivars().tints.borrow().get(row).copied().flatten();
9507                let badge_text = self.ivars().badges.borrow().get(row).cloned().flatten();
9508                let bimg = self
9509                    .ivars()
9510                    .badge_icons
9511                    .borrow()
9512                    .get(row)
9513                    .and_then(std::clone::Clone::clone);
9514                let btint = self
9515                    .ivars()
9516                    .badge_tints
9517                    .borrow()
9518                    .get(row)
9519                    .copied()
9520                    .flatten();
9521                // Both configurations are the ADAPTIVE ones: each reads the `listEnvironment`
9522                // trait the list publishes and resolves itself to that appearance. In a sidebar
9523                // list that means the inset rounded pill, the tinted label while selected and no
9524                // separators — the Settings look, from UIKit, with nothing here naming a radius
9525                // or an inset. (The per-appearance spellings, `sidebarCellConfiguration` and
9526                // friends, are deprecated precisely because these adapt; they also draw nothing
9527                // useful outside a list that publishes the trait, which is why this had to stop
9528                // being a UITableView to work at all.)
9529                // `defaultContentConfiguration` rather than the class method: it comes back
9530                // already resolved against this cell's list environment and its current state,
9531                // which is where the selected row's tinted label comes from. The class method
9532                // resolves the environment but not the state, so the pill drew and the label
9533                // stayed the resting color.
9534                let content = unsafe { cell.defaultContentConfiguration() };
9535                unsafe {
9536                    content.setText(Some(&title));
9537                    content.setImage(img.as_deref());
9538                    // A glyph needs a SIZE. An SF Symbol scales itself to the row's text style,
9539                    // but Day's are staged rasters (docs/vectors.md) whose intrinsic size is the
9540                    // 48pt canvas they were authored on — so left alone they draw at 48pt and
9541                    // drag the row's height up with them. This is the size an iOS list icon is,
9542                    // and it is the one thing here that has to be said rather than inherited.
9543                    content
9544                        .imageProperties()
9545                        .setMaximumSize(CGSize::new(28.0, 28.0));
9546                    if let Some(c) = tint {
9547                        content.imageProperties().setTintColor(Some(&uiink(c)));
9548                    }
9549                    cell.setContentConfiguration(Some(ProtocolObject::from_ref(&*content)));
9550                    // The cell's OWN default, for the same reason the content configuration is
9551                    // taken from the cell above: it is resolved against this cell's list
9552                    // environment. The class method `listCellConfiguration:` would do as well,
9553                    // but it is iOS 18+, and calling it on anything older is not a missing
9554                    // background — it is `+[UIBackgroundConfiguration listCellConfiguration]:
9555                    // method not found` and an abort before the first frame. The instance method is
9556                    // itself iOS 16's; on iOS 15 a list cell already takes its background from the
9557                    // list environment, so there is nothing to set.
9558                    if os_at_least(16) {
9559                        cell.setBackgroundConfiguration(Some(
9560                            &cell.defaultBackgroundConfiguration(),
9561                        ));
9562                    }
9563                    cell.setAccessories(&nav_accessories(
9564                        mtm,
9565                        badge_text.as_deref(),
9566                        bimg.as_deref(),
9567                        btint,
9568                    ));
9569                    let progress = self
9570                        .ivars()
9571                        .icon_progress
9572                        .borrow()
9573                        .iter()
9574                        .find(|(i, _)| *i == row)
9575                        .map(|(_, v)| *v);
9576                    crate::nav_progress::update(&cell, progress, mtm);
9577                }
9578                objc2::rc::Retained::into_super(cell)
9579            }
9580        }
9581
9582        unsafe impl UICollectionViewDelegate for DayNavTableData {
9583            #[unsafe(method(collectionView:didSelectItemAtIndexPath:))]
9584            fn did_select(
9585                &self,
9586                cv: &objc2_ui_kit::UICollectionView,
9587                index_path: &objc2_foundation::NSIndexPath,
9588            ) {
9589                day_spec::ffi_guard::contain((), || {
9590                    let _ = cv;
9591                    let Some(row) = self.row_of(unsafe { index_path.section() } as usize, unsafe {
9592                        index_path.item()
9593                    }
9594                        as usize)
9595                    else {
9596                        return;
9597                    };
9598                    // The row STAYS selected. A sidebar beside its detail is the one place a
9599                    // list's selection means "you are here" rather than "you just tapped", and
9600                    // UIKit draws that as the rounded pill Settings shows. Clearing it here left
9601                    // the split with nothing marking the page on screen. The model answers this
9602                    // event with `NavMenuPatch::Selected`, which is what actually settles the
9603                    // highlight — including back to `None` where a presentation has no selection.
9604                    // Keyboard focus also selects rows inside UIKit's focus-update transaction.
9605                    // Deliver after that transaction returns: synchronously rebuilding navigation
9606                    // or reloading the selected collection here invalidates UIKit's focus context
9607                    // and can throw an Objective-C exception through Rust's event pump.
9608                    let node = self.ivars().node;
9609                    dispatch2::DispatchQueue::main().exec_async(move || {
9610                        emit(node, Event::SelectionChanged(row as i64));
9611                    });
9612                });
9613            }
9614
9615            /// The row's context menu (docs/menus.md): the same UIMenu the piece decorator
9616            /// builds, served through the table's own long-press affordance.
9617            #[unsafe(method_id(collectionView:contextMenuConfigurationForItemAtIndexPath:point:))]
9618            fn context_menu_for_row(
9619                &self,
9620                _cv: &objc2_ui_kit::UICollectionView,
9621                index_path: &objc2_foundation::NSIndexPath,
9622                _point: CGPoint,
9623            ) -> Option<Retained<UIContextMenuConfiguration>> {
9624                let row = self
9625                    .row_of(
9626                        unsafe { index_path.section() } as usize,
9627                        unsafe { index_path.item() } as usize,
9628                    )
9629                    .unwrap_or(usize::MAX);
9630                let items = self
9631                    .ivars()
9632                    .menus
9633                    .borrow()
9634                    .get(row)
9635                    .cloned()
9636                    .unwrap_or_default();
9637                if items.is_empty() {
9638                    // `define_class!` rewrites the return, so no early `return` — one expression.
9639                    None
9640                } else {
9641                    let menu = build_ui_menu(self.mtm(), "", &items);
9642                    let provider = block2::RcBlock::new(
9643                        move |_suggested: NonNull<objc2_foundation::NSArray<UIMenuElement>>| -> *mut UIMenu {
9644                            // +0 block return: autorelease, don't leak a retain per summon
9645                            // (see DayContextMenu::configuration_for_menu).
9646                            Retained::autorelease_return(menu.clone())
9647                        },
9648                    );
9649                    Some(unsafe {
9650                        UIContextMenuConfiguration::configurationWithIdentifier_previewProvider_actionProvider(
9651                            None,
9652                            std::ptr::null_mut(),
9653                            block2::RcBlock::as_ptr(&provider),
9654                            self.mtm(),
9655                        )
9656                    })
9657                }
9658            }
9659        }
9660    );
9661
9662    /// Load a bundled image by NAME for a nav/tab icon (docs/navigation.md): by-name from the
9663    /// `DayPieces` asset catalog first — the reliable iOS path, same as the `image()` piece — then a
9664    /// loose staged file (dev / assets). Callers apply `.alwaysTemplate` so it tints with the
9665    /// control's color.
9666    /// The bundle Day's staged glyphs live in — the SwiftPM resource bundle the Apple stager
9667    /// writes its asset catalog into (`resources/apple.rs`).
9668    fn day_pieces_bundle() -> Option<Retained<objc2_foundation::NSBundle>> {
9669        let main = unsafe { objc2_foundation::NSBundle::mainBundle() };
9670        let bname = NSString::from_str("DayPieces_DayPieces");
9671        let bext = NSString::from_str("bundle");
9672        let url = unsafe { main.URLForResource_withExtension(Some(&bname), Some(&bext)) }?;
9673        unsafe { objc2_foundation::NSBundle::bundleWithURL(&url) }
9674    }
9675
9676    fn load_bundled_uiimage(name: &str) -> Option<Retained<objc2_ui_kit::UIImage>> {
9677        let nsname = NSString::from_str(name);
9678        if let Some(day_bundle) = day_pieces_bundle()
9679            && let Some(img) = unsafe {
9680                objc2_ui_kit::UIImage::imageNamed_inBundle_compatibleWithTraitCollection(
9681                    &nsname,
9682                    Some(&day_bundle),
9683                    None,
9684                )
9685            }
9686        {
9687            return Some(img);
9688        }
9689        if let Some(path) = day_spec::resource::resolve_image_file(name)
9690            && let Some(img) = unsafe {
9691                objc2_ui_kit::UIImage::imageWithContentsOfFile(&NSString::from_str(
9692                    &path.to_string_lossy(),
9693                ))
9694            }
9695        {
9696            return Some(img);
9697        }
9698        None
9699    }
9700
9701    /// Resolve nav glyph names to template images once per rebuild (docs/navigation.md).
9702    fn resolve_nav_images(
9703        names: &[Option<String>],
9704    ) -> Vec<Option<Retained<objc2_ui_kit::UIImage>>> {
9705        names
9706            .iter()
9707            .map(|ic| {
9708                let name = ic.as_deref()?;
9709                let img = load_bundled_uiimage(name)?;
9710                Some(unsafe {
9711                    img.imageWithRenderingMode(if std::path::Path::new(name).is_absolute() {
9712                        objc2_ui_kit::UIImageRenderingMode::AlwaysOriginal
9713                    } else {
9714                        objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate
9715                    })
9716                })
9717            })
9718            .collect()
9719    }
9720
9721    /// The reuse identifier for a sidebar row.
9722    const NAV_CELL_ID: &str = "day.nav.cell";
9723    /// The reuse identifier for a sidebar section heading.
9724    const NAV_HEADER_ID: &str = "day.nav.header";
9725
9726    /// The sidebar list's layout. `headers` turns section headings on: left off for a list that
9727    /// declares none, so a flat list reserves no band where a heading would go.
9728    ///
9729    /// The list's appearance follows the width the layout is asked for, the way UIKit's own
9730    /// apps do it: at a regular width the SIDEBAR appearance, the Settings sidebar's rounded
9731    /// selection pill and group labels; at a compact width an INSET GROUPED list, the phone's
9732    /// grouped table with its section headings over each group. Both come from the
9733    /// configuration itself (`listEnvironment` is what the cells' and headers' adaptive
9734    /// configurations read), so nothing here names a font, an inset or a background, and a
9735    /// heading scrolls as the platform scrolls it.
9736    fn nav_list_layout(
9737        mtm: MainThreadMarker,
9738        headers: bool,
9739    ) -> Retained<objc2_ui_kit::UICollectionViewLayout> {
9740        unsafe {
9741            let provider = block2::RcBlock::new(
9742                move |_: isize,
9743                      environment: NonNull<
9744                    ProtocolObject<dyn objc2_ui_kit::NSCollectionLayoutEnvironment>,
9745                >|
9746                      -> *mut objc2_ui_kit::NSCollectionLayoutSection {
9747                    let environment = environment.as_ref();
9748                    let compact =
9749                        objc2_ui_kit::NSCollectionLayoutEnvironment::traitCollection(environment)
9750                            .horizontalSizeClass()
9751                            == objc2_ui_kit::UIUserInterfaceSizeClass::Compact;
9752                    let config =
9753                        objc2_ui_kit::UICollectionLayoutListConfiguration::initWithAppearance(
9754                            objc2_ui_kit::UICollectionLayoutListConfiguration::alloc(mtm),
9755                            if compact {
9756                                objc2_ui_kit::UICollectionLayoutListAppearance::InsetGrouped
9757                            } else {
9758                                objc2_ui_kit::UICollectionLayoutListAppearance::Sidebar
9759                            },
9760                        );
9761                    config.setHeaderMode(if headers {
9762                        objc2_ui_kit::UICollectionLayoutListHeaderMode::Supplementary
9763                    } else {
9764                        objc2_ui_kit::UICollectionLayoutListHeaderMode::None
9765                    });
9766                    let section = objc2_ui_kit::NSCollectionLayoutSection::
9767                        sectionWithListConfiguration_layoutEnvironment(&config, environment);
9768                    Retained::autorelease_return(section)
9769                },
9770            );
9771            Retained::into_super(
9772                objc2_ui_kit::UICollectionViewCompositionalLayout::initWithSectionProvider(
9773                    objc2_ui_kit::UICollectionViewCompositionalLayout::alloc(mtm),
9774                    block2::RcBlock::as_ptr(&provider),
9775                ),
9776            )
9777        }
9778    }
9779
9780    /// A row's trailing accessories: the status glyph an app asked for, then the chevron.
9781    ///
9782    /// `UICellAccessory` rather than subviews placed by hand — the list positions them, sizes them
9783    /// and keeps them clear of a label that has to truncate, which the cell this replaced did in
9784    /// its own `layoutSubviews`.
9785    fn nav_accessories(
9786        mtm: MainThreadMarker,
9787        text: Option<&str>,
9788        badge: Option<&objc2_ui_kit::UIImage>,
9789        badge_tint: Option<day_spec::Ink>,
9790    ) -> Retained<objc2_foundation::NSArray<objc2_ui_kit::UICellAccessory>> {
9791        let mut items: Vec<Retained<objc2_ui_kit::UICellAccessory>> = Vec::new();
9792        if let Some(text) = text.filter(|s| !s.is_empty()) {
9793            let label = unsafe {
9794                objc2_ui_kit::UICellAccessoryLabel::initWithText(
9795                    objc2_ui_kit::UICellAccessoryLabel::alloc(mtm),
9796                    &NSString::from_str(text),
9797                )
9798            };
9799            items.push(objc2::rc::Retained::into_super(label));
9800        }
9801        if let Some(img) = badge {
9802            let iv = unsafe {
9803                objc2_ui_kit::UIImageView::initWithImage(
9804                    objc2_ui_kit::UIImageView::alloc(mtm),
9805                    Some(img),
9806                )
9807            };
9808            if let Some(c) = badge_tint {
9809                unsafe { iv.setTintColor(Some(&uiink(c))) };
9810            }
9811            unsafe { iv.sizeToFit() };
9812            let acc = unsafe {
9813                objc2_ui_kit::UICellAccessoryCustomView::initWithCustomView_placement(
9814                    objc2_ui_kit::UICellAccessoryCustomView::alloc(mtm),
9815                    &iv,
9816                    objc2_ui_kit::UICellAccessoryPlacement::Trailing,
9817                )
9818            };
9819            items.push(objc2::rc::Retained::into_super(acc));
9820        }
9821        let chevron = unsafe {
9822            objc2_ui_kit::UICellAccessoryDisclosureIndicator::init(
9823                objc2_ui_kit::UICellAccessoryDisclosureIndicator::alloc(mtm),
9824            )
9825        };
9826        items.push(objc2::rc::Retained::into_super(chevron));
9827        objc2_foundation::NSArray::from_retained_slice(&items)
9828    }
9829
9830    /// Move a sidebar list's highlight to `row`, or clear it (`NavMenuProps::selected`), looking
9831    /// the row's index path up through the list's registered data source.
9832    ///
9833    /// Only for callers that hold NO borrow of `NAV_MENUS` and no `DayNavTableData` of their own.
9834    /// The ones that do call [`select_nav_path`] with `path_of` applied to the data they already
9835    /// have: this lookup borrows the map, and doing that from inside a `borrow_mut` panicked the
9836    /// whole nav build ("`RefCell` already mutably borrowed", contained at the FFI boundary, so the
9837    /// app came up with no navigation host at all).
9838    fn select_nav_row(cv: &objc2_ui_kit::UICollectionView, row: Option<usize>) {
9839        let path = row.and_then(|r| {
9840            NAV_MENUS.with(|m| {
9841                m.borrow()
9842                    .get(&ptr_of(&view_of(&cv.retain())))?
9843                    .0
9844                    .path_of(r)
9845            })
9846        });
9847        select_nav_path(cv, path);
9848    }
9849
9850    /// Move a sidebar list's highlight to `path` — a (section, item) pair, because a row's flat
9851    /// index is not its index PATH once the list has headings and the grouping is private to the
9852    /// list (`DayNavTableData::path_of`).
9853    ///
9854    /// Not animated and not scrolled to: this runs while the model syncs the selection, and both
9855    /// would read as the list moving under a tap the user already made.
9856    fn select_nav_path(cv: &objc2_ui_kit::UICollectionView, path: Option<(usize, usize)>) {
9857        unsafe {
9858            let ip = path.map(|(section, item)| {
9859                objc2_foundation::NSIndexPath::indexPathForItem_inSection(
9860                    item as isize,
9861                    section as isize,
9862                )
9863            });
9864            cv.selectItemAtIndexPath_animated_scrollPosition(
9865                ip.as_deref(),
9866                false,
9867                objc2_ui_kit::UICollectionViewScrollPosition::empty(),
9868            );
9869        }
9870    }
9871
9872    impl DayNavTableData {
9873        // The parameters are `NavMenuProps`, minus `selected`: index-aligned per-row
9874        // decoration arrays. Taking the props struct instead would tie this to one caller —
9875        // `NavMenuPatch::Items` carries the same arrays without a props value to hand over.
9876        #[allow(clippy::too_many_arguments)]
9877        fn new(
9878            mtm: MainThreadMarker,
9879            node: NodeId,
9880            items: &[String],
9881            icons: &[Option<String>],
9882            tints: &[Option<day_spec::Ink>],
9883            menus: &[Vec<day_spec::MenuItem>],
9884            badges: &[Option<String>],
9885            badge_icons: &[Option<String>],
9886            badge_tints: &[Option<day_spec::Ink>],
9887            sections: &[Option<String>],
9888        ) -> Retained<Self> {
9889            let resolved = resolve_nav_images(icons);
9890            let this = Self::alloc(mtm).set_ivars(NavTableIvars {
9891                node,
9892                items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
9893                icons: RefCell::new(resolved),
9894                icon_progress: RefCell::new(Vec::new()),
9895                badges: RefCell::new(badges.to_vec()),
9896                badge_icons: RefCell::new(resolve_nav_images(badge_icons)),
9897                badge_tints: RefCell::new(badge_tints.to_vec()),
9898                tints: RefCell::new(tints.to_vec()),
9899                menus: RefCell::new(menus.to_vec()),
9900                sections: RefCell::new(sections.to_vec()),
9901                headers: std::cell::Cell::new(sections.iter().any(std::option::Option::is_some)),
9902            });
9903            unsafe { msg_send![super(this), init] }
9904        }
9905
9906        /// The row groups this menu draws, as `(heading, first row, row count)`.
9907        ///
9908        /// `NavMenuProps::sections` is parallel to the rows — a heading INTRODUCES the row at its
9909        /// own index — so the groups are runs, and a row's flat index is `first + item`. Rows
9910        /// before the first heading form a leading group with none, which is what lets a list open
9911        /// with ungrouped rows.
9912        fn groups(&self) -> Vec<(Option<String>, usize, usize)> {
9913            let rows = self.ivars().items.borrow().len();
9914            let sections = self.ivars().sections.borrow();
9915            let mut out: Vec<(Option<String>, usize, usize)> = Vec::new();
9916            for row in 0..rows {
9917                match sections.get(row).cloned().flatten() {
9918                    Some(title) => out.push((Some(title), row, 1)),
9919                    None if out.is_empty() => out.push((None, row, 1)),
9920                    None => {
9921                        let last = out.last_mut().expect("non-empty");
9922                        last.2 += 1;
9923                    }
9924                }
9925            }
9926            out
9927        }
9928
9929        /// The flat row an index path addresses, and the reverse — everything above this backend
9930        /// speaks in flat row indices (`SelectionChanged`, `NavMenuProps::selected`, the tint and
9931        /// badge arrays), so the grouping stays private to the list.
9932        fn row_of(&self, section: usize, item: usize) -> Option<usize> {
9933            let g = self.groups();
9934            let (_, first, len) = g.get(section)?;
9935            (item < *len).then_some(first + item)
9936        }
9937
9938        fn path_of(&self, row: usize) -> Option<(usize, usize)> {
9939            self.groups()
9940                .iter()
9941                .enumerate()
9942                .find_map(|(s, (_, first, len))| {
9943                    (row >= *first && row < first + len).then_some((s, row - first))
9944                })
9945        }
9946
9947        /// Data-driven rows changed (`NavMenuPatch::Items`): swap labels/icons in place.
9948        // One parallel array per row attribute, which is the shape `NavMenuPatch::Items`
9949        // arrives in; bundling them into a struct here would only unpack it again.
9950        #[allow(clippy::too_many_arguments)]
9951        fn set_items(
9952            &self,
9953            items: &[String],
9954            icons: &[Option<String>],
9955            tints: &[Option<day_spec::Ink>],
9956            menus: &[Vec<day_spec::MenuItem>],
9957            badges: &[Option<String>],
9958            badge_icons: &[Option<String>],
9959            badge_tints: &[Option<day_spec::Ink>],
9960            sections: &[Option<String>],
9961        ) {
9962            *self.ivars().items.borrow_mut() =
9963                items.iter().map(|s| NSString::from_str(s)).collect();
9964            *self.ivars().sections.borrow_mut() = sections.to_vec();
9965            *self.ivars().tints.borrow_mut() = tints.to_vec();
9966            *self.ivars().menus.borrow_mut() = menus.to_vec();
9967            *self.ivars().icons.borrow_mut() = resolve_nav_images(icons);
9968            self.ivars().icon_progress.borrow_mut().clear();
9969            *self.ivars().badges.borrow_mut() = badges.to_vec();
9970            *self.ivars().badge_icons.borrow_mut() = resolve_nav_images(badge_icons);
9971            *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
9972        }
9973    }
9974
9975    // -----------------------------------------------------------------------
9976    // The hierarchical tree (docs/tree.md): a list-layout UICollectionView, its rows driven
9977    // by a diffable data source over one section's snapshot — the token tree itself. Day owns
9978    // disclosure end to end: the cell's outline-disclosure accessory carries a custom action
9979    // handler that only EMITS `Event::TreeExpanded`; the piece answers with
9980    // `TreePatch::Expand`, which re-applies the section snapshot — so a native tap and the
9981    // dayscript `expand:` step share one path, and nothing auto-toggles behind day's back.
9982    // -----------------------------------------------------------------------
9983
9984    struct TreeIvars {
9985        node: NodeId,
9986        source: RefCell<Option<TreeSource>>,
9987        ds: RefCell<
9988            Option<Retained<objc2_ui_kit::UICollectionViewDiffableDataSource<NSObject, NSObject>>>,
9989        >,
9990        /// token → its interned `NSNumber`: the diffable identifiers compare by isEqual, and
9991        /// One object per token also keeps snapshot identity stable across reloads.
9992        items: RefCell<HashMap<u64, Retained<objc2_foundation::NSNumber>>>,
9993        /// Disclosure by token, as last patched — what a rebuilt snapshot restores.
9994        expanded: RefCell<std::collections::HashSet<u64>>,
9995        row_height: std::cell::Cell<f64>,
9996        selectable: std::cell::Cell<bool>,
9997    }
9998
9999    define_class!(
10000        #[unsafe(super(NSObject))]
10001        #[thread_kind = MainThreadOnly]
10002        #[name = "DayTreeData"]
10003        #[ivars = TreeIvars]
10004        struct DayTreeData;
10005
10006        unsafe impl NSObjectProtocol for DayTreeData {}
10007
10008        unsafe impl UIScrollViewDelegate for DayTreeData {}
10009
10010        unsafe impl UICollectionViewDelegate for DayTreeData {
10011            #[unsafe(method(collectionView:shouldSelectItemAtIndexPath:))]
10012            fn should_select_item(
10013                &self,
10014                _cv: &objc2_ui_kit::UICollectionView,
10015                ip: &objc2_foundation::NSIndexPath,
10016            ) -> bool {
10017                let ds = self.ivars().ds.borrow();
10018                ds.as_ref()
10019                    .and_then(|ds| ds.itemIdentifierForIndexPath(ip))
10020                    .and_then(|it| Self::token_of_item(&it))
10021                    .is_some_and(|t| {
10022                        self.ivars()
10023                            .source
10024                            .borrow()
10025                            .as_ref()
10026                            .is_some_and(|s| !(s.section_header)(t))
10027                    })
10028            }
10029
10030            #[unsafe(method(collectionView:didSelectItemAtIndexPath:))]
10031            fn did_select(
10032                &self,
10033                cv: &objc2_ui_kit::UICollectionView,
10034                _ip: &objc2_foundation::NSIndexPath,
10035            ) {
10036                day_spec::ffi_guard::contain((), || self.report_selection(cv));
10037            }
10038
10039            #[unsafe(method(collectionView:didDeselectItemAtIndexPath:))]
10040            fn did_deselect(
10041                &self,
10042                cv: &objc2_ui_kit::UICollectionView,
10043                _ip: &objc2_foundation::NSIndexPath,
10044            ) {
10045                day_spec::ffi_guard::contain((), || self.report_selection(cv));
10046            }
10047
10048            #[unsafe(method_id(collectionView:contextMenuConfigurationForItemAtIndexPath:point:))]
10049            fn context_menu_for_item(
10050                &self,
10051                _cv: &objc2_ui_kit::UICollectionView,
10052                index_path: &objc2_foundation::NSIndexPath,
10053                _point: CGPoint,
10054            ) -> Option<Retained<objc2_ui_kit::UIContextMenuConfiguration>> {
10055                // A summon-time ROW menu (docs/menus.md, docs/tree.md): long-press asks the
10056                // tree's `row_menu` provider for this row.
10057                day_spec::ffi_guard::contain(None, || {
10058                    let row_menu = self
10059                        .ivars()
10060                        .source
10061                        .borrow()
10062                        .as_ref()
10063                        .and_then(|s| s.row_menu.clone())?;
10064                    let ds = self.ivars().ds.borrow().clone()?;
10065                    let token = ds
10066                        .itemIdentifierForIndexPath(index_path)
10067                        .and_then(|it| Self::token_of_item(&it))?;
10068                    let items = row_menu(token);
10069                    if items.is_empty() {
10070                        return None;
10071                    }
10072                    let mtm = self.mtm();
10073                    let menu = build_ui_menu(mtm, "", &items);
10074                    let provider = block2::RcBlock::new(
10075                        move |_suggested: NonNull<objc2_foundation::NSArray<UIMenuElement>>| -> *mut UIMenu {
10076                            Retained::autorelease_return(menu.clone())
10077                        },
10078                    );
10079                    Some(unsafe {
10080                        UIContextMenuConfiguration::configurationWithIdentifier_previewProvider_actionProvider(
10081                            None,
10082                            std::ptr::null_mut(),
10083                            block2::RcBlock::as_ptr(&provider),
10084                            mtm,
10085                        )
10086                    })
10087                })
10088            }
10089
10090            #[unsafe(method(collectionView:didEndDisplayingCell:forItemAtIndexPath:))]
10091            fn did_end_displaying(
10092                &self,
10093                _cv: &objc2_ui_kit::UICollectionView,
10094                cell: &objc2_ui_kit::UICollectionViewCell,
10095                _ip: &objc2_foundation::NSIndexPath,
10096            ) {
10097                // The row left the screen (a collapse, a scroll): clear its day element ids
10098                // so a hidden row stops answering `find_by_id` — the next bind re-sets the
10099                // live row's (docs/tree.md; the rule every tree backend wires).
10100                day_spec::ffi_guard::contain((), || {
10101                    let content = cell.contentView();
10102                    let recycle = self
10103                        .ivars()
10104                        .source
10105                        .borrow()
10106                        .as_ref()
10107                        .map(|s| s.recycle.clone());
10108                    if let Some(recycle) = recycle {
10109                        recycle(Retained::as_ptr(&content) as RawHandle);
10110                    }
10111                });
10112            }
10113        }
10114    );
10115
10116    impl DayTreeData {
10117        fn new(
10118            mtm: MainThreadMarker,
10119            node: NodeId,
10120            selectable: bool,
10121            row_height: f64,
10122        ) -> Retained<Self> {
10123            let this = Self::alloc(mtm).set_ivars(TreeIvars {
10124                node,
10125                source: RefCell::new(None),
10126                ds: RefCell::new(None),
10127                items: RefCell::new(HashMap::new()),
10128                expanded: RefCell::new(std::collections::HashSet::new()),
10129                row_height: std::cell::Cell::new(row_height),
10130                selectable: std::cell::Cell::new(selectable),
10131            });
10132            unsafe { msg_send![super(this), init] }
10133        }
10134
10135        /// The same `NSNumber` for a token, every time (see `TreeIvars::items`).
10136        fn intern(&self, token: u64) -> Retained<objc2_foundation::NSNumber> {
10137            self.ivars()
10138                .items
10139                .borrow_mut()
10140                .entry(token)
10141                .or_insert_with(|| objc2_foundation::NSNumber::new_u64(token))
10142                .clone()
10143        }
10144
10145        fn token_of_item(item: &AnyObject) -> Option<u64> {
10146            item.downcast_ref::<objc2_foundation::NSNumber>()
10147                .map(objc2_foundation::NSNumber::as_u64)
10148        }
10149
10150        /// The one section's identifier (a lone list has exactly one).
10151        fn section() -> Retained<objc2_foundation::NSNumber> {
10152            objc2_foundation::NSNumber::new_u64(0)
10153        }
10154
10155        /// Report the FULL selected token set (docs/tree.md).
10156        fn report_selection(&self, cv: &objc2_ui_kit::UICollectionView) {
10157            if !self.ivars().selectable.get() {
10158                return;
10159            }
10160            let ds = self.ivars().ds.borrow().clone();
10161            let Some(ds) = ds else { return };
10162            let mut tokens = Vec::new();
10163            if let Some(paths) = cv.indexPathsForSelectedItems() {
10164                for ip in &paths {
10165                    if let Some(tok) = ds
10166                        .itemIdentifierForIndexPath(&ip)
10167                        .and_then(|it| Self::token_of_item(&it))
10168                    {
10169                        tokens.push(tok);
10170                    }
10171                }
10172            }
10173            emit(self.ivars().node, Event::TreeSelection(tokens));
10174        }
10175
10176        /// Rebuild the section snapshot from the source's current hierarchy and re-apply the
10177        /// recorded disclosure. Call outside any day-core borrow (deferred by the patches).
10178        fn apply_snapshot(&self, animated: bool) {
10179            let Some(ds) = self.ivars().ds.borrow().clone() else {
10180                return;
10181            };
10182            let src = self.ivars().source.borrow().clone();
10183            let Some(src) = src else { return };
10184            let snap: Retained<objc2_ui_kit::NSDiffableDataSourceSectionSnapshot<NSObject>> = unsafe {
10185                msg_send![
10186                    <objc2_ui_kit::NSDiffableDataSourceSectionSnapshot<NSObject> as objc2::AnyThread>::alloc(),
10187                    init
10188                ]
10189            };
10190            // Parents-first DFS: append each level under its parent item.
10191            let mut present: Vec<u64> = Vec::new();
10192            let mut stack: Vec<Option<u64>> = vec![None];
10193            while let Some(parent) = stack.pop() {
10194                let n = (src.children_len)(parent);
10195                if n == 0 {
10196                    continue;
10197                }
10198                let kids: Vec<u64> = (0..n).map(|i| (src.child_token)(parent, i)).collect();
10199                let arr = objc2_foundation::NSArray::from_retained_slice(
10200                    &kids
10201                        .iter()
10202                        .map(|t| unsafe { Retained::cast_unchecked::<NSObject>(self.intern(*t)) })
10203                        .collect::<Vec<_>>(),
10204                );
10205                match parent {
10206                    None => snap.appendItems(&arr),
10207                    Some(p) => {
10208                        let item = unsafe { Retained::cast_unchecked::<NSObject>(self.intern(p)) };
10209                        snap.appendItems_intoParentItem(&arr, Some(&item));
10210                    }
10211                }
10212                for k in kids {
10213                    present.push(k);
10214                    if (src.expandable)(k) {
10215                        stack.push(Some(k));
10216                    }
10217                }
10218            }
10219            let open: Vec<Retained<NSObject>> = present
10220                .iter()
10221                .filter(|t| self.ivars().expanded.borrow().contains(t))
10222                .map(|t| unsafe { Retained::cast_unchecked::<NSObject>(self.intern(*t)) })
10223                .collect();
10224            if !open.is_empty() {
10225                snap.expandItems(&objc2_foundation::NSArray::from_retained_slice(&open));
10226            }
10227            let section = unsafe { Retained::cast_unchecked::<NSObject>(Self::section()) };
10228            ds.applySnapshot_toSection_animatingDifferences(&snap, &section, animated);
10229        }
10230    }
10231
10232    // A tree row: a UICollectionViewListCell that (a) sizes itself to the tree's UNIFORM row
10233    // height — day content is frame-laid, so auto-layout self-sizing would collapse it — and
10234    // (b) re-lays its day row at the content view's OWN width on every layout pass, because
10235    // indentation and accessories make that width per-row (docs/tree.md `layout_cell`).
10236    struct TreeCellIvars {
10237        row_height: std::cell::Cell<f64>,
10238    }
10239
10240    define_class!(
10241        #[unsafe(super(objc2_ui_kit::UICollectionViewListCell))]
10242        #[thread_kind = MainThreadOnly]
10243        #[name = "DayTreeListCell"]
10244        #[ivars = TreeCellIvars]
10245        struct DayTreeListCell;
10246
10247        impl DayTreeListCell {
10248            #[unsafe(method(layoutSubviews))]
10249            fn layout_subviews(&self) {
10250                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
10251                day_spec::ffi_guard::contain((), || {
10252                    let content = self.contentView();
10253                    let width = content.bounds().size.width;
10254                    if width <= 0.0 {
10255                        return;
10256                    }
10257                    // This cell's tree: walk up to the collection view, which keys TREE_STATE.
10258                    let mut cur = self.superview();
10259                    while let Some(v) = cur {
10260                        cur = v.superview();
10261                        if let Ok(cv) = v.downcast::<objc2_ui_kit::UICollectionView>() {
10262                            let layout = TREE_STATE.with(|m| {
10263                                m.borrow().get(&(Retained::as_ptr(&cv) as usize)).and_then(
10264                                    |d| {
10265                                        d.ivars()
10266                                            .source
10267                                            .borrow()
10268                                            .as_ref()
10269                                            .map(|s| s.layout_cell.clone())
10270                                    },
10271                                )
10272                            });
10273                            if let Some(f) = layout {
10274                                f(Retained::as_ptr(&content) as RawHandle, width);
10275                            }
10276                            break;
10277                        }
10278                    }
10279                });
10280            }
10281
10282            #[unsafe(method_id(preferredLayoutAttributesFittingAttributes:))]
10283            fn preferred_layout_attributes(
10284                &self,
10285                attrs: &objc2_ui_kit::UICollectionViewLayoutAttributes,
10286            ) -> Retained<objc2_ui_kit::UICollectionViewLayoutAttributes> {
10287                let mut frame = attrs.frame();
10288                frame.size.height = self.ivars().row_height.get();
10289                attrs.setFrame(frame);
10290                unsafe {
10291                    Retained::retain(
10292                        std::ptr::from_ref::<objc2_ui_kit::UICollectionViewLayoutAttributes>(attrs).cast_mut(),
10293                    )
10294                }
10295                .expect("attributes retained")
10296            }
10297        }
10298    );
10299
10300    fn tree_entry_u(key: usize) -> Option<Retained<DayTreeData>> {
10301        TREE_STATE.with(|m| m.borrow().get(&key).cloned())
10302    }
10303
10304    // A list row: a UITableViewCell that re-lays its day row at the content view's OWN width
10305    // whenever that differs from the width the row was laid at. In editing mode the table
10306    // narrows the content view for the delete control and the reorder grip (docs/list.md
10307    // "Editing mode"), and a row laid at the table's width would run underneath them.
10308    struct ListCellIvars {
10309        /// The content width last reported through `ListSource::layout_cell` (0 = none yet).
10310        reported: std::cell::Cell<f64>,
10311        /// The table this cell was made for (its `LIST_STATE` key) and that list's node: a
10312        /// deallocating cell has no superview left to find them by, and the node tells a
10313        /// later table at the same address apart from this one.
10314        table: usize,
10315        node: NodeId,
10316        /// The content view's address, the key `bind_row` used: recorded at creation so
10317        /// `dealloc` has nothing to ask the cell for.
10318        content: std::cell::Cell<usize>,
10319    }
10320
10321    define_class!(
10322        #[unsafe(super(objc2_ui_kit::UITableViewCell))]
10323        #[thread_kind = MainThreadOnly]
10324        #[name = "DayListCell"]
10325        #[ivars = ListCellIvars]
10326        struct DayListCell;
10327
10328        impl DayListCell {
10329            #[unsafe(method(layoutSubviews))]
10330            fn layout_subviews(&self) {
10331                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
10332                day_spec::ffi_guard::contain((), || {
10333                    let content = self.contentView();
10334                    let width = content.bounds().size.width;
10335                    if width <= 0.0 {
10336                        return;
10337                    }
10338                    let mut cur = self.superview();
10339                    while let Some(v) = cur {
10340                        cur = v.superview();
10341                        let Ok(table) = v.downcast::<objc2_ui_kit::UITableView>() else {
10342                            continue;
10343                        };
10344                        // Outside editing the content view spans the table and the row was
10345                        // laid at that width already; report only a width that differs from
10346                        // it, and the table's width again once editing ends.
10347                        let full = table.bounds().size.width;
10348                        let reported = self.ivars().reported.get();
10349                        #[expect(
10350                            clippy::float_cmp,
10351                            reason = "0.0 is the never-reported sentinel and `reported` holds the exact width sent last"
10352                        )]
10353                        let settled = reported == 0.0 || reported == width;
10354                        if (width - full).abs() < 0.5 && settled {
10355                            break;
10356                        }
10357                        let entry = LIST_STATE.with(|m| {
10358                            m.borrow().get(&(Retained::as_ptr(&table) as usize)).cloned()
10359                        });
10360                        let layout = entry.and_then(|(_, data)| {
10361                            data.ivars().source.borrow().as_ref().map(|s| s.layout_cell.clone())
10362                        });
10363                        if let Some(f) = layout {
10364                            self.ivars().reported.set(width);
10365                            f(Retained::as_ptr(&content) as RawHandle, width);
10366                        }
10367                        break;
10368                    }
10369                });
10370            }
10371
10372            /// A self-sizing row's height (`RowHeight::Automatic`, docs/list.md "Row
10373            /// heights"): UIKit asks the cell after `cellForRowAtIndexPath:` bound it, and the
10374            /// answer is the height Day laid the row at, re-laid first at the width the content
10375            /// view has (narrower than the table in editing mode) once the cell has reported
10376            /// one. A uniform list never asks: its table has a fixed `rowHeight`.
10377            #[unsafe(method(systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority:))]
10378            fn size_fitting(
10379                &self,
10380                target: CGSize,
10381                horizontal: objc2_ui_kit::UILayoutPriority,
10382                vertical: objc2_ui_kit::UILayoutPriority,
10383            ) -> CGSize {
10384                let measured = day_spec::ffi_guard::contain(None, || {
10385                    let data = self.list_data()?;
10386                    // A supplementary row sizes to its content in a uniform list too
10387                    // (docs/list.md "Header, footer and empty state").
10388                    if !data.ivars().automatic && !self.is_supplement() {
10389                        return None;
10390                    }
10391                    let source = data.ivars().source.borrow().clone()?;
10392                    let content = self.contentView();
10393                    let cell = Retained::as_ptr(&content) as RawHandle;
10394                    let reported = self.ivars().reported.get();
10395                    let width = if reported > 0.0 { reported } else { target.width };
10396                    if width > 0.0 {
10397                        (source.layout_cell)(cell, width);
10398                    }
10399                    let height = (source.cell_height)(cell);
10400                    (height > 0.0).then_some(CGSize::new(target.width, height))
10401                });
10402                match measured {
10403                    Some(size) => size,
10404                    None => unsafe {
10405                        msg_send![
10406                            super(self),
10407                            systemLayoutSizeFittingSize: target,
10408                            withHorizontalFittingPriority: horizontal,
10409                            verticalFittingPriority: vertical
10410                        ]
10411                    },
10412                }
10413            }
10414        }
10415    );
10416
10417    impl DayListCell {
10418        /// The list data a cell's table answers to, found by walking up to the table.
10419        fn list_data(&self) -> Option<Retained<DayListData>> {
10420            let mut cur = self.superview();
10421            while let Some(v) = cur {
10422                cur = v.superview();
10423                if let Ok(table) = v.downcast::<objc2_ui_kit::UITableView>() {
10424                    return LIST_STATE
10425                        .with(|m| {
10426                            m.borrow()
10427                                .get(&(Retained::as_ptr(&table) as usize))
10428                                .cloned()
10429                        })
10430                        .map(|(_, data)| data);
10431                }
10432            }
10433            None
10434        }
10435
10436        /// Whether this cell holds a supplementary row: those cells are queued under their own
10437        /// reuse identifier, so a cell never changes kind.
10438        fn is_supplement(&self) -> bool {
10439            self.reuseIdentifier()
10440                .is_some_and(|ident| ident.to_string() == LIST_SUPPLEMENT_CELL)
10441        }
10442
10443        fn new(
10444            mtm: MainThreadMarker,
10445            ident: &NSString,
10446            table: usize,
10447            node: NodeId,
10448        ) -> Retained<Self> {
10449            let this = Self::alloc(mtm).set_ivars(ListCellIvars {
10450                reported: std::cell::Cell::new(0.0),
10451                table,
10452                node,
10453                content: std::cell::Cell::new(0),
10454            });
10455            let this: Retained<Self> = unsafe {
10456                msg_send![
10457                    super(this),
10458                    initWithStyle: objc2_ui_kit::UITableViewCellStyle::Default,
10459                    reuseIdentifier: ident
10460                ]
10461            };
10462            if this.is_supplement() {
10463                // Plain content (docs/list.md "Header, footer and empty state"): no selection
10464                // highlight, and the separator below it pushed past the trailing edge, the
10465                // way UIKit hides a single row's separator. The separator above belongs to the
10466                // row before and stays.
10467                this.setSelectionStyle(objc2_ui_kit::UITableViewCellSelectionStyle::None);
10468                this.setSeparatorInset(UIEdgeInsets {
10469                    top: 0.0,
10470                    left: SEPARATOR_OFF,
10471                    bottom: 0.0,
10472                    right: 0.0,
10473                });
10474            }
10475            this.ivars()
10476                .content
10477                .set(Retained::as_ptr(&this.contentView()) as usize);
10478            this
10479        }
10480    }
10481
10482    /// `dealloc` (the macro routes `Drop` there): `UITableView` is done with this cell for good.
10483    /// It reuses queued cells but also discards surplus ones, and every discarded cell used to
10484    /// leave the row Day built in its content view behind in day-core. Release that row
10485    /// (docs/list.md). Posted, because a cell can deallocate inside a reload Day is applying.
10486    /// Nothing is retained here: a first version took the content view and the list entry
10487    /// along on the post, and `UITableView` then died on its own "dataSource is not set"
10488    /// assertion mid-layout on iOS 18; copying the addresses recorded at creation does not.
10489    /// The content key stays this cell's until the release runs, because day-core holds the
10490    /// content view until then; the node id keeps a later table at the same address from
10491    /// being mistaken for this one.
10492    impl Drop for DayListCell {
10493        fn drop(&mut self) {
10494            let (table, node) = (self.ivars().table, self.ivars().node);
10495            let content = self.ivars().content.get();
10496            if content == 0 {
10497                return;
10498            }
10499            <Uikit as Platform>::post(Box::new(move || {
10500                let release = LIST_STATE.with(|m| {
10501                    let m = m.borrow();
10502                    let (_, data) = m.get(&table)?;
10503                    if data.ivars().node != node {
10504                        return None;
10505                    }
10506                    let source = data.ivars().source.borrow();
10507                    source.as_ref().map(|s| s.release.clone())
10508                });
10509                if let Some(release) = release {
10510                    release(content as RawHandle);
10511                }
10512            }));
10513        }
10514    }
10515
10516    // A sectioned list's header (docs/list.md "Sections"): a plain table's section header view,
10517    // which UIKit pins to the top while its section scrolls under it. Day builds the header
10518    // row in its content view, as it builds a row in a cell's.
10519    define_class!(
10520        #[unsafe(super(objc2_ui_kit::UITableViewHeaderFooterView))]
10521        #[thread_kind = MainThreadOnly]
10522        #[name = "DayListHeader"]
10523        #[ivars = ListCellIvars]
10524        struct DayListHeader;
10525
10526        impl DayListHeader {
10527            /// A header sizes to its content in every list: lay it at the offered width and
10528            /// answer the height Day laid it at.
10529            #[unsafe(method(systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority:))]
10530            fn size_fitting(
10531                &self,
10532                target: CGSize,
10533                horizontal: objc2_ui_kit::UILayoutPriority,
10534                vertical: objc2_ui_kit::UILayoutPriority,
10535            ) -> CGSize {
10536                let measured = day_spec::ffi_guard::contain(None, || {
10537                    let (table, node) = (self.ivars().table, self.ivars().node);
10538                    let source = LIST_STATE.with(|m| {
10539                        let m = m.borrow();
10540                        let (_, data) = m.get(&table)?;
10541                        if data.ivars().node != node {
10542                            return None;
10543                        }
10544                        data.ivars().source.borrow().clone()
10545                    })?;
10546                    let cell = self.ivars().content.get() as RawHandle;
10547                    if target.width > 0.0 {
10548                        (source.layout_cell)(cell, target.width);
10549                    }
10550                    let height = (source.cell_height)(cell);
10551                    (height > 0.0).then_some(CGSize::new(target.width, height))
10552                });
10553                match measured {
10554                    Some(size) => size,
10555                    None => unsafe {
10556                        msg_send![
10557                            super(self),
10558                            systemLayoutSizeFittingSize: target,
10559                            withHorizontalFittingPriority: horizontal,
10560                            verticalFittingPriority: vertical
10561                        ]
10562                    },
10563                }
10564            }
10565        }
10566    );
10567
10568    impl DayListHeader {
10569        fn new(
10570            mtm: MainThreadMarker,
10571            ident: &NSString,
10572            table: usize,
10573            node: NodeId,
10574        ) -> Retained<Self> {
10575            let this = Self::alloc(mtm).set_ivars(ListCellIvars {
10576                reported: std::cell::Cell::new(0.0),
10577                table,
10578                node,
10579                content: std::cell::Cell::new(0),
10580            });
10581            let this: Retained<Self> =
10582                unsafe { msg_send![super(this), initWithReuseIdentifier: ident] };
10583            this.ivars()
10584                .content
10585                .set(Retained::as_ptr(&this.contentView()) as usize);
10586            this
10587        }
10588    }
10589
10590    /// The header's goodbye, exactly as `DayListCell`'s: release the row Day built in it.
10591    impl Drop for DayListHeader {
10592        fn drop(&mut self) {
10593            let (table, node) = (self.ivars().table, self.ivars().node);
10594            let content = self.ivars().content.get();
10595            if content == 0 {
10596                return;
10597            }
10598            <Uikit as Platform>::post(Box::new(move || {
10599                let release = LIST_STATE.with(|m| {
10600                    let m = m.borrow();
10601                    let (_, data) = m.get(&table)?;
10602                    if data.ivars().node != node {
10603                        return None;
10604                    }
10605                    let source = data.ivars().source.borrow();
10606                    source.as_ref().map(|s| s.release.clone())
10607                });
10608                if let Some(release) = release {
10609                    release(content as RawHandle);
10610                }
10611            }));
10612        }
10613    }
10614
10615    // -----------------------------------------------------------------------
10616    // DayListData — UITableView data source + delegate for the recycling list (docs/list.md, §10)
10617    // -----------------------------------------------------------------------
10618
10619    /// The association key under which a list's table retains its `DayListData`.
10620    static LIST_DATA_SOURCE_KEY: u8 = 0;
10621
10622    /// The reuse identifier of an item row's cell.
10623    const LIST_ITEM_CELL: &str = "day.cell";
10624    /// The reuse identifier of a supplementary row's cell (docs/list.md "Header, footer and
10625    /// empty state"): its own queue, so a cell's chrome is set once, at creation.
10626    const LIST_SUPPLEMENT_CELL: &str = "day.supplement";
10627    /// A separator inset wider than any screen, which hides one cell's separator.
10628    const SEPARATOR_OFF: CGFloat = 100_000.0;
10629    /// The most sequential deltas a splice folds into one animated batch; past it the table
10630    /// reloads and keeps its offset (docs/list.md "Splices"). A batch costs a replay over the
10631    /// rows per delta, and a run this long is a bulk change no row animation helps.
10632    const SPLICE_BATCH_LIMIT: usize = 64;
10633
10634    // A list's table (docs/list.md "Visible rows"). It reports the viewport after each of its
10635    // layout passes, which is when a resize, a reload or a splice has landed, and when a
10636    // scroll has realized the rows it brought into view.
10637    define_class!(
10638        #[unsafe(super(objc2_ui_kit::UITableView))]
10639        #[thread_kind = MainThreadOnly]
10640        #[name = "DayListTable"]
10641        #[ivars = ()]
10642        struct DayListTable;
10643
10644        impl DayListTable {
10645            #[unsafe(method(layoutSubviews))]
10646            fn layout_subviews(&self) {
10647                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
10648                day_spec::ffi_guard::contain((), || {
10649                    let key = std::ptr::from_ref(self) as usize;
10650                    let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
10651                    if let Some((table, data)) = entry {
10652                        data.report_viewport(&table);
10653                    }
10654                });
10655            }
10656        }
10657    );
10658
10659    impl DayListTable {
10660        /// A list table of `style`, handed back as the plain table the list code speaks.
10661        fn make(
10662            mtm: MainThreadMarker,
10663            style: objc2_ui_kit::UITableViewStyle,
10664        ) -> Retained<objc2_ui_kit::UITableView> {
10665            let this = Self::alloc(mtm).set_ivars(());
10666            let this: Retained<Self> = unsafe {
10667                msg_send![
10668                    super(this),
10669                    initWithFrame: CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(0.0, 0.0)),
10670                    style: style
10671                ]
10672            };
10673            Retained::into_super(this)
10674        }
10675    }
10676
10677    struct ListIvars {
10678        node: NodeId,
10679        source: RefCell<Option<ListSource>>,
10680        row_height: std::cell::Cell<f64>,
10681        /// `RowHeight::Automatic`: the table self-sizes its cells through `DayListCell`'s
10682        /// `systemLayoutSizeFittingSize:…`, and `row_height` is only the estimate.
10683        automatic: bool,
10684        /// A height pass is posted and not yet run (`post_row_heights` coalesces).
10685        heights_pending: std::cell::Cell<bool>,
10686        selectable: std::cell::Cell<bool>,
10687        /// The app's localized word for the swipe action (docs/list.md); empty ⇒ trash glyph.
10688        delete_label: RefCell<String>,
10689        /// The list has section headers (docs/list.md "Sections"). Day's display rows count
10690        /// headers; the table gets a section per header, and the header row becomes the
10691        /// section's header view, which a plain table pins while the section scrolls.
10692        sections: bool,
10693        /// The display row of each section's header, ascending: recomputed whenever the table
10694        /// asks for its section count (a reload), so the index-path mapping always matches
10695        /// the rows the table believes it has.
10696        headers: RefCell<Vec<usize>>,
10697        /// A change of rows on its way to the table ([`HeldRows`], `DayListData::hold`).
10698        held: RefCell<Option<HeldRows>>,
10699        /// The row count a change being applied ends on, while `apply_held` runs.
10700        applying: std::cell::Cell<Option<usize>>,
10701    }
10702
10703    /// The changes of a list's rows the table has not taken yet: every `ListPatch` arrives
10704    /// inside day-core's borrow, often from a row bind's flush in the middle of the table's
10705    /// own layout pass, and the table takes them together on the next main-queue turn. Until
10706    /// then the table still shows the rows it had, while the source already answers in the
10707    /// final state, so a row the table binds meanwhile is the source row its row ends at
10708    /// (`finals`), as `NSTableView`'s held splice maps them in day-toolkit-appkit. Bound by the
10709    /// source's index instead, a cell showed the row of the old index and the batch then moved
10710    /// it, leaving it on a row whose item it does not show.
10711    struct HeldRows {
10712        /// The sequential deltas of every splice held, in order; `None` once a reload is held,
10713        /// which covers every change before and after it.
10714        deltas: Option<Vec<day_spec::props::RowDelta>>,
10715        /// The display rows the table shows, which the deltas start from.
10716        shown: usize,
10717        /// The source's row count when the last splice was sent ([`DayListData::apply_splice`]).
10718        after: Option<usize>,
10719        /// The source row each of the table's rows ends at (`scrolling::final_rows`); `None`
10720        /// once a reload is held, when each row is read at its own index.
10721        finals: Option<Vec<Option<usize>>>,
10722    }
10723
10724    define_class!(
10725        #[unsafe(super(NSObject))]
10726        #[thread_kind = MainThreadOnly]
10727        #[name = "DayListData"]
10728        #[ivars = ListIvars]
10729        struct DayListData;
10730
10731        unsafe impl NSObjectProtocol for DayListData {}
10732
10733        impl DayListData {
10734            /// Only a sectioned list answers the section-header selectors: a plain list keeps
10735            /// UIKit's own section metrics exactly as before. UITableView reads this once, when
10736            /// the delegate and data source are set, after `sections` is.
10737            #[unsafe(method(respondsToSelector:))]
10738            fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
10739                let header_selector = selector == objc2::sel!(numberOfSectionsInTableView:)
10740                    || selector == objc2::sel!(tableView:viewForHeaderInSection:)
10741                    || selector == objc2::sel!(tableView:heightForHeaderInSection:)
10742                    || selector == objc2::sel!(tableView:didEndDisplayingHeaderView:forSection:);
10743                if header_selector && !self.ivars().sections {
10744                    false
10745                } else {
10746                    unsafe { msg_send![super(self), respondsToSelector: selector] }
10747                }
10748            }
10749
10750            #[unsafe(method(numberOfSectionsInTableView:))]
10751            fn number_of_sections(&self, _tv: &objc2_ui_kit::UITableView) -> isize {
10752                day_spec::ffi_guard::contain(0, || {
10753                    self.refresh_headers();
10754                    self.ivars().headers.borrow().len() as isize
10755                })
10756            }
10757
10758            #[unsafe(method_id(tableView:viewForHeaderInSection:))]
10759            fn view_for_header(
10760                &self,
10761                tv: &objc2_ui_kit::UITableView,
10762                section: isize,
10763            ) -> Option<Retained<UIView>> {
10764                // (Closure body: define_class converts only the tail expression.)
10765                let make = || {
10766                let display =
10767                    self.ivars().headers.borrow().get(section.max(0) as usize).copied()?;
10768                let mtm = self.mtm();
10769                let ident = NSString::from_str("day.header");
10770                let table = std::ptr::from_ref(tv) as usize;
10771                let node = self.ivars().node;
10772                let header: Retained<objc2_ui_kit::UITableViewHeaderFooterView> =
10773                    unsafe { tv.dequeueReusableHeaderFooterViewWithIdentifier(&ident) }
10774                        .unwrap_or_else(|| {
10775                            Retained::into_super(DayListHeader::new(mtm, &ident, table, node))
10776                        });
10777                let content = header.contentView();
10778                let source = self.ivars().source.borrow().clone();
10779                if let Some(source) = source {
10780                    let raw = Retained::as_ptr(&content) as RawHandle;
10781                    day_spec::ffi_guard::contain((), || (source.bind_row)(display, raw));
10782                }
10783                Some(Retained::into_super(header))
10784                };
10785                make()
10786            }
10787
10788            #[unsafe(method(tableView:heightForHeaderInSection:))]
10789            fn height_for_header(&self, _tv: &objc2_ui_kit::UITableView, _section: isize) -> CGFloat {
10790                unsafe { objc2_ui_kit::UITableViewAutomaticDimension }
10791            }
10792
10793            /// The header left the screen: park its ids, as a row's cell does.
10794            #[unsafe(method(tableView:didEndDisplayingHeaderView:forSection:))]
10795            fn did_end_displaying_header(
10796                &self,
10797                _tv: &objc2_ui_kit::UITableView,
10798                view: &UIView,
10799                _section: isize,
10800            ) {
10801                day_spec::ffi_guard::contain((), || {
10802                    let Some(header) = view.downcast_ref::<objc2_ui_kit::UITableViewHeaderFooterView>()
10803                    else {
10804                        return;
10805                    };
10806                    let content = Retained::as_ptr(&header.contentView()) as usize;
10807                    let view = Retained::into_raw(view.retain()) as usize;
10808                    let data = Retained::into_raw(self.retain()) as usize;
10809                    <Uikit as Platform>::post(Box::new(move || {
10810                        // Reclaim both +1s first, so every early return balances them.
10811                        let view = unsafe { Retained::from_raw(view as *mut UIView) };
10812                        let data = unsafe { Retained::from_raw(data as *mut DayListData) };
10813                        let (Some(view), Some(data)) = (view, data) else { return };
10814                        if view.window().is_some() {
10815                            return; // displayed again: its ids are the live header's
10816                        }
10817                        let recycle =
10818                            data.ivars().source.borrow().as_ref().map(|s| s.recycle.clone());
10819                        if let Some(recycle) = recycle {
10820                            recycle(content as RawHandle);
10821                        }
10822                    }));
10823                });
10824            }
10825        }
10826
10827        unsafe impl UIScrollViewDelegate for DayListData {
10828            #[unsafe(method(scrollViewDidScroll:))]
10829            /// Every step of a scroll, the user's or a programmatic one, animated or not
10830            /// (docs/list.md "Visible rows"). The full report supersedes `first_visible`,
10831            /// which this host no longer calls. A step of the reader's drag is reported as
10832            /// theirs first (docs/list.md "Following the end").
10833            fn list_did_scroll(&self, view: &objc2_ui_kit::UIScrollView) {
10834                day_spec::ffi_guard::contain((), || {
10835                    if let Some(table) = view.downcast_ref::<objc2_ui_kit::UITableView>() {
10836                        if view.isDragging() {
10837                            self.note_reader_scroll(table);
10838                        }
10839                        self.report_viewport(table);
10840                    }
10841                });
10842            }
10843
10844            /// The reader started dragging the list: a scroll the app asked for that is still
10845            /// on its way stops where it is (UIKit would run it on against the finger), and
10846            /// the scroll is theirs (docs/list.md "Following the end").
10847            #[unsafe(method(scrollViewWillBeginDragging:))]
10848            fn list_will_begin_dragging(&self, view: &objc2_ui_kit::UIScrollView) {
10849                day_spec::ffi_guard::contain((), || {
10850                    if let Some(table) = view.downcast_ref::<objc2_ui_kit::UITableView>() {
10851                        view.setContentOffset_animated(view.contentOffset(), false);
10852                        self.note_reader_scroll(table);
10853                    }
10854                });
10855            }
10856
10857            /// A tap on the status bar scrolls the list to its top: the reader's scroll
10858            /// (docs/list.md "Following the end"). The list scrolls, as without a delegate.
10859            #[unsafe(method(scrollViewShouldScrollToTop:))]
10860            fn list_should_scroll_to_top(&self, view: &objc2_ui_kit::UIScrollView) -> bool {
10861                day_spec::ffi_guard::contain((), || {
10862                    if let Some(table) = view.downcast_ref::<objc2_ui_kit::UITableView>() {
10863                        self.note_reader_scroll(table);
10864                    }
10865                });
10866                true
10867            }
10868
10869            /// An animated programmatic scroll came to rest: report where.
10870            #[unsafe(method(scrollViewDidEndScrollingAnimation:))]
10871            fn list_did_end_scrolling_animation(&self, view: &objc2_ui_kit::UIScrollView) {
10872                day_spec::ffi_guard::contain((), || {
10873                    if let Some(table) = view.downcast_ref::<objc2_ui_kit::UITableView>() {
10874                        self.report_viewport(table);
10875                    }
10876                });
10877            }
10878        }
10879
10880        unsafe impl UITableViewDataSource for DayListData {
10881            #[unsafe(method(tableView:numberOfRowsInSection:))]
10882            fn rows_in_section(&self, _tv: &objc2_ui_kit::UITableView, section: isize) -> isize {
10883                // Snapshot-only read (no tree) — safe during reloadData inside a with_tree
10884                // borrow. `len` is an app closure, so the body is contained (§8.5).
10885                day_spec::ffi_guard::contain(0, || {
10886                    let len = self
10887                        .ivars()
10888                        .source
10889                        .borrow()
10890                        .as_ref()
10891                        .map_or(0, |s| (s.len)());
10892                    if !self.ivars().sections {
10893                        return len as isize;
10894                    }
10895                    // A section's rows run from after its header to the next header.
10896                    let headers = self.ivars().headers.borrow();
10897                    let section = section.max(0) as usize;
10898                    let Some(&start) = headers.get(section) else {
10899                        return 0;
10900                    };
10901                    let end = headers.get(section + 1).copied().unwrap_or(len).max(start + 1);
10902                    (end - start - 1) as isize
10903                })
10904            }
10905
10906            #[unsafe(method_id(tableView:cellForRowAtIndexPath:))]
10907            fn cell_for_row(
10908                &self,
10909                tv: &objc2_ui_kit::UITableView,
10910                index_path: &objc2_foundation::NSIndexPath,
10911            ) -> Retained<objc2_ui_kit::UITableViewCell> {
10912                let mtm = self.mtm();
10913                // The source row this table row shows: through a change still on its way to
10914                // the table (`HeldRows`), which a bind's own flush can send mid-pass.
10915                let source_row = self.source_row(index_path);
10916                let row = source_row.unwrap_or_else(|| self.display_of(index_path));
10917                let ident = NSString::from_str(if self.is_supplement(row) {
10918                    LIST_SUPPLEMENT_CELL
10919                } else {
10920                    LIST_ITEM_CELL
10921                });
10922                let table = std::ptr::from_ref(tv) as usize;
10923                let node = self.ivars().node;
10924                let cell =
10925                    unsafe { tv.dequeueReusableCellWithIdentifier(&ident) }.unwrap_or_else(|| {
10926                        Retained::into_super(DayListCell::new(mtm, &ident, table, node))
10927                    });
10928                // Day builds/rebinds its row content inside the cell's contentView. The bind
10929                // runs day-core's row builder — contained (§8.5); a panicking row leaves the
10930                // recycled cell blank rather than aborting.
10931                let content = cell.contentView();
10932                // A row the held change removes keeps the cell it has until the change lands.
10933                let source = self.ivars().source.borrow().clone();
10934                if let (Some(source), Some(row)) = (source, source_row) {
10935                    let raw = Retained::as_ptr(&content) as RawHandle;
10936                    day_spec::ffi_guard::contain((), || (source.bind_row)(row, raw));
10937                }
10938                cell
10939            }
10940
10941            // --- drag-to-reorder (docs/list.md): the data-source half. With a drag delegate and
10942            // `dragInteractionEnabled`, UITableView runs its whole native reorder UX — long-press
10943            // lift, the gap under the finger, haptics — and commits through `moveRow`.
10944
10945            #[unsafe(method(tableView:canMoveRowAtIndexPath:))]
10946            fn can_move_row(
10947                &self,
10948                _tv: &objc2_ui_kit::UITableView,
10949                index_path: &objc2_foundation::NSIndexPath,
10950            ) -> objc2::runtime::Bool {
10951                // A row the guard won't move anywhere (a pinned row) refuses the lift itself:
10952                // probing (row -> row) is the cheapest "may this row drag at all" question.
10953                // The verdict runs the app's guard closure — contained (§8.5), refusing on panic.
10954                let row = self.display_of(index_path);
10955                objc2::runtime::Bool::new(day_spec::ffi_guard::contain(false, || {
10956                    self.reorder_verdict(row, row) >= 0
10957                }))
10958            }
10959
10960            #[unsafe(method(tableView:moveRowAtIndexPath:toIndexPath:))]
10961            fn move_row(
10962                &self,
10963                _tv: &objc2_ui_kit::UITableView,
10964                from_path: &objc2_foundation::NSIndexPath,
10965                to_path: &objc2_foundation::NSIndexPath,
10966            ) {
10967                // UIKit hands FINAL indices (post-removal semantics — the seam's own contract).
10968                // The table has already animated the move; commit rotates Day's snapshot and
10969                // defers the app callback — contained (§8.5).
10970                day_spec::ffi_guard::contain((), || {
10971                    let (from, to) = (self.display_of(from_path), self.display_of(to_path));
10972                    if from == to {
10973                        return;
10974                    }
10975                    let mv = self
10976                        .ivars()
10977                        .source
10978                        .borrow()
10979                        .as_ref()
10980                        .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
10981                    if let Some(mv) = mv {
10982                        mv(from, to);
10983                    }
10984                });
10985            }
10986
10987            // --- editing mode (docs/list.md "Editing mode"): the delete control's commit. A
10988            // swipe never lands here — the trailing swipe configuration carries its own
10989            // handler — only the Delete button the red control reveals while editing.
10990            #[unsafe(method(tableView:commitEditingStyle:forRowAtIndexPath:))]
10991            fn commit_editing_style(
10992                &self,
10993                tv: &objc2_ui_kit::UITableView,
10994                style: objc2_ui_kit::UITableViewCellEditingStyle,
10995                index_path: &objc2_foundation::NSIndexPath,
10996            ) {
10997                day_spec::ffi_guard::contain((), || {
10998                    if style != objc2_ui_kit::UITableViewCellEditingStyle::Delete {
10999                        return;
11000                    }
11001                    let row = self.display_of(index_path);
11002                    let del = self
11003                        .ivars()
11004                        .source
11005                        .borrow()
11006                        .as_ref()
11007                        .and_then(|s| s.delete.clone())
11008                        .filter(|d| (d.can_delete)(row));
11009                    if let Some(del) = del {
11010                        // The seam shortens Day's snapshot first, so the native removal
11011                        // animates against the count the data source now reports.
11012                        (del.delete_row)(row);
11013                        let paths =
11014                            objc2_foundation::NSArray::from_retained_slice(&[index_path.retain()]);
11015                        unsafe {
11016                            tv.deleteRowsAtIndexPaths_withRowAnimation(
11017                                &paths,
11018                                objc2_ui_kit::UITableViewRowAnimation::Automatic,
11019                            );
11020                        };
11021                    }
11022                });
11023            }
11024        }
11025
11026        unsafe impl UITableViewDelegate for DayListData {
11027            // Editing mode's per-row control: the red delete control on a row `deletable`
11028            // offers, none otherwise. Outside editing this answers the same, and the swipe
11029            // configuration below supplies the actions; `None` there keeps a row the guard
11030            // protects from falling back to UIKit's stock Delete swipe.
11031            #[unsafe(method(tableView:editingStyleForRowAtIndexPath:))]
11032            fn editing_style(
11033                &self,
11034                _tv: &objc2_ui_kit::UITableView,
11035                index_path: &objc2_foundation::NSIndexPath,
11036            ) -> objc2_ui_kit::UITableViewCellEditingStyle {
11037                self.row_editing_style(self.display_of(index_path))
11038            }
11039
11040            // A row without a delete control keeps its leading edge while editing, rather than
11041            // indenting for a control it does not have.
11042            #[unsafe(method(tableView:shouldIndentWhileEditingRowAtIndexPath:))]
11043            fn should_indent_while_editing(
11044                &self,
11045                _tv: &objc2_ui_kit::UITableView,
11046                index_path: &objc2_foundation::NSIndexPath,
11047            ) -> objc2::runtime::Bool {
11048                objc2::runtime::Bool::new(
11049                    self.row_editing_style(self.display_of(index_path))
11050                        != objc2_ui_kit::UITableViewCellEditingStyle::None,
11051                )
11052            }
11053
11054            /// The cell left the screen: park its row's dayscript ids. Deferred and re-checked,
11055            /// as AppKit's `didRemoveRowView` is: a reload or batch update can dequeue the very
11056            /// cell it is ending, bind it to a row, and only then report the old display ended.
11057            /// Recycled there, a row on screen lost its ids, and `wait_for` on it failed (an iPad
11058            /// catalog manager opened just as a catalog was added).
11059            #[unsafe(method(tableView:didEndDisplayingCell:forRowAtIndexPath:))]
11060            fn did_end_displaying(
11061                &self,
11062                tv: &objc2_ui_kit::UITableView,
11063                cell: &objc2_ui_kit::UITableViewCell,
11064                _ip: &objc2_foundation::NSIndexPath,
11065            ) {
11066                day_spec::ffi_guard::contain((), || {
11067                    let key = std::ptr::from_ref(tv) as usize;
11068                    // A +1 across the post (the closure must be Send, which Retained is not;
11069                    // everything stays on the main thread). UIKit may free an ended cell.
11070                    let cell = Retained::into_raw(cell.retain()) as usize;
11071                    <Uikit as Platform>::post(Box::new(move || {
11072                        // Reclaim the +1 first, so every early return balances it.
11073                        let cell = unsafe {
11074                            Retained::from_raw(cell as *mut objc2_ui_kit::UITableViewCell)
11075                        };
11076                        let Some(cell) = cell else { return };
11077                        let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
11078                        let Some((table, data)) = entry else { return };
11079                        if unsafe { table.indexPathForCell(&cell) }.is_some() {
11080                            return; // displayed again: its ids are the live row's
11081                        }
11082                        let recycle = data
11083                            .ivars()
11084                            .source
11085                            .borrow()
11086                            .as_ref()
11087                            .map(|s| s.recycle.clone());
11088                        if let Some(recycle) = recycle {
11089                            let content = cell.contentView();
11090                            recycle(Retained::as_ptr(&content) as RawHandle);
11091                        }
11092                    }));
11093                });
11094            }
11095
11096            #[unsafe(method(tableView:willDisplayCell:forRowAtIndexPath:))]
11097            fn will_display(
11098                &self,
11099                _tv: &objc2_ui_kit::UITableView,
11100                cell: &objc2_ui_kit::UITableViewCell,
11101                ip: &objc2_foundation::NSIndexPath,
11102            ) {
11103                day_spec::ffi_guard::contain((), || {
11104                    let source = self.ivars().source.borrow().clone();
11105                    // Through a change still on its way to the table (`HeldRows`).
11106                    if let Some(source) = source
11107                        && let Some(row) = self.source_row(ip)
11108                        && row < (source.len)()
11109                    {
11110                        let content = cell.contentView();
11111                        (source.bind_row)(row, Retained::as_ptr(&content) as RawHandle);
11112                    }
11113                });
11114            }
11115
11116            #[unsafe(method(tableView:heightForRowAtIndexPath:))]
11117            fn height_for_row(
11118                &self,
11119                _tv: &objc2_ui_kit::UITableView,
11120                index_path: &objc2_foundation::NSIndexPath,
11121            ) -> CGFloat {
11122                // A supplementary row is as tall as Day laid it, even in a uniform list
11123                // (docs/list.md "Header, footer and empty state"): the cell answers.
11124                let row = self.source_row(index_path).unwrap_or_else(|| self.display_of(index_path));
11125                if self.ivars().automatic || self.is_supplement(row) {
11126                    unsafe { objc2_ui_kit::UITableViewAutomaticDimension }
11127                } else {
11128                    self.ivars().row_height.get()
11129                }
11130            }
11131
11132            /// A supplementary row never shows the selection highlight.
11133            #[unsafe(method(tableView:shouldHighlightRowAtIndexPath:))]
11134            fn should_highlight(
11135                &self,
11136                _tv: &objc2_ui_kit::UITableView,
11137                index_path: &objc2_foundation::NSIndexPath,
11138            ) -> bool {
11139                !self.is_supplement(self.display_of(index_path))
11140            }
11141
11142            /// Nor is it ever selected.
11143            #[unsafe(method_id(tableView:willSelectRowAtIndexPath:))]
11144            fn will_select(
11145                &self,
11146                _tv: &objc2_ui_kit::UITableView,
11147                index_path: &objc2_foundation::NSIndexPath,
11148            ) -> Option<Retained<objc2_foundation::NSIndexPath>> {
11149                (!self.is_supplement(self.display_of(index_path))).then(|| index_path.retain())
11150            }
11151
11152            /// Nor does focus (a hardware keyboard's row navigation) stop on it.
11153            #[unsafe(method(tableView:canFocusRowAtIndexPath:))]
11154            fn can_focus(
11155                &self,
11156                _tv: &objc2_ui_kit::UITableView,
11157                index_path: &objc2_foundation::NSIndexPath,
11158            ) -> bool {
11159                !self.is_supplement(self.display_of(index_path))
11160            }
11161
11162            #[unsafe(method(tableView:didSelectRowAtIndexPath:))]
11163            fn did_select(
11164                &self,
11165                tv: &objc2_ui_kit::UITableView,
11166                index_path: &objc2_foundation::NSIndexPath,
11167            ) {
11168                day_spec::ffi_guard::contain((), || {
11169                    let row = self.display_of(index_path);
11170                    unsafe { tv.deselectRowAtIndexPath_animated(index_path, true) };
11171                    if self.ivars().selectable.get() {
11172                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
11173                        emit(self.ivars().node, Event::ListActivated(row));
11174                    }
11175                });
11176            }
11177
11178            // --- swipe actions (docs/list.md). `UISwipeActionsConfiguration` is the modern
11179            // spelling: it gives the full native UX — the row tracking the finger, the actions
11180            // revealing behind it, the full-swipe shortcut for the first action — where the
11181            // older `commitEditingStyle` pair only offered a fixed Delete button. The trailing
11182            // edge carries the delete affordance first (full swipe deletes, the Mail idiom),
11183            // then the row's own trailing offer; the leading edge is the offer alone.
11184            // Returning `None` means this row has no swipe action, which is exactly how a
11185            // guarded row declines.
11186            #[unsafe(method_id(tableView:trailingSwipeActionsConfigurationForRowAtIndexPath:))]
11187            fn trailing_swipe_actions(
11188                &self,
11189                tv: &objc2_ui_kit::UITableView,
11190                index_path: &objc2_foundation::NSIndexPath,
11191            ) -> Option<Retained<objc2_ui_kit::UISwipeActionsConfiguration>> {
11192                // The whole body runs inside a closure: `define_class!`'s `method_id` return
11193                // shim leaves no room for an early `return None`, but a closure gives `?` back.
11194                // `contain` doubles as the invoker (§8.5) — the guard seam runs app closures,
11195                // and a panic degrades to "no swipe action".
11196                let body = || -> Option<Retained<objc2_ui_kit::UISwipeActionsConfiguration>> {
11197                    let row = self.display_of(index_path);
11198                    let (del, sw) = {
11199                        let src = self.ivars().source.borrow();
11200                        let s = src.as_ref()?;
11201                        (s.delete.clone(), s.swipe.clone())
11202                    };
11203                    let mtm = MainThreadMarker::new()?;
11204                    let mut actions: Vec<Retained<objc2_ui_kit::UIContextualAction>> = Vec::new();
11205                    // A guarded row offers NO delete rather than one that fails on use.
11206                    if let Some(del) = del.filter(|d| (d.can_delete)(row)) {
11207                        let label = self.ivars().delete_label.borrow().clone();
11208                        let title = (!label.is_empty()).then(|| NSString::from_str(&label));
11209                        let tv: Retained<objc2_ui_kit::UITableView> = Retained::from(tv);
11210                        let path: Retained<objc2_foundation::NSIndexPath> =
11211                            Retained::from(index_path);
11212                        let handler =
11213                            block2::RcBlock::new(
11214                                move |_a: NonNull<objc2_ui_kit::UIContextualAction>,
11215                                      _v: NonNull<UIView>,
11216                                      done: NonNull<
11217                                    block2::DynBlock<dyn Fn(objc2::runtime::Bool)>,
11218                                >| {
11219                                    // Commit through the seam first — it shortens Day's snapshot
11220                                    // synchronously — then let the table animate the row away.
11221                                    // Deleting the row natively (rather than reloading) keeps the
11222                                    // swipe's own animation continuous into the removal.
11223                                    (del.delete_row)(row);
11224                                    let paths = objc2_foundation::NSArray::from_retained_slice(
11225                                        std::slice::from_ref(&path),
11226                                    );
11227                                    unsafe {
11228                                        tv.deleteRowsAtIndexPaths_withRowAnimation(
11229                                            &paths,
11230                                            objc2_ui_kit::UITableViewRowAnimation::Automatic,
11231                                        );
11232                                        // Report the action finished; the row is gone, so the swipe
11233                                        // must not spring back.
11234                                        done.as_ref().call((objc2::runtime::Bool::YES,));
11235                                    }
11236                                },
11237                            );
11238                        let action = unsafe {
11239                            objc2_ui_kit::UIContextualAction::contextualActionWithStyle_title_handler(
11240                                objc2_ui_kit::UIContextualActionStyle::Destructive,
11241                                title.as_deref(),
11242                                block2::RcBlock::as_ptr(&handler),
11243                                mtm,
11244                            )
11245                        };
11246                        // No app label ⇒ the wordless idiom: a trash glyph, legible in every
11247                        // locale.
11248                        if title.is_none()
11249                            && let Some(img) = objc2_ui_kit::UIImage::systemImageNamed(
11250                                &NSString::from_str("trash"),
11251                            )
11252                        {
11253                            unsafe { action.setImage(Some(&img)) };
11254                        }
11255                        actions.push(action);
11256                    }
11257                    if let Some(sw) = sw {
11258                        let offer = (sw.actions_at)(row, day_spec::SwipeEdge::Trailing);
11259                        for (i, a) in offer.iter().enumerate() {
11260                            actions.push(Self::contextual_action(
11261                                a,
11262                                row,
11263                                day_spec::SwipeEdge::Trailing,
11264                                i,
11265                                sw.perform.clone(),
11266                                mtm,
11267                            ));
11268                        }
11269                    }
11270                    if actions.is_empty() {
11271                        return None;
11272                    }
11273                    Some(
11274                        objc2_ui_kit::UISwipeActionsConfiguration::configurationWithActions(
11275                            &objc2_foundation::NSArray::from_retained_slice(&actions),
11276                            mtm,
11277                        ),
11278                    )
11279                };
11280                day_spec::ffi_guard::contain(None, body)
11281            }
11282
11283            #[unsafe(method_id(tableView:leadingSwipeActionsConfigurationForRowAtIndexPath:))]
11284            fn leading_swipe_actions(
11285                &self,
11286                _tv: &objc2_ui_kit::UITableView,
11287                index_path: &objc2_foundation::NSIndexPath,
11288            ) -> Option<Retained<objc2_ui_kit::UISwipeActionsConfiguration>> {
11289                // Guarded as the trailing edge is: the offer runs the app's provider closure.
11290                let body = || -> Option<Retained<objc2_ui_kit::UISwipeActionsConfiguration>> {
11291                    let row = self.display_of(index_path);
11292                    let sw = self
11293                        .ivars()
11294                        .source
11295                        .borrow()
11296                        .as_ref()
11297                        .and_then(|s| s.swipe.clone())?;
11298                    let mtm = MainThreadMarker::new()?;
11299                    let offer = (sw.actions_at)(row, day_spec::SwipeEdge::Leading);
11300                    if offer.is_empty() {
11301                        return None;
11302                    }
11303                    let actions: Vec<Retained<objc2_ui_kit::UIContextualAction>> = offer
11304                        .iter()
11305                        .enumerate()
11306                        .map(|(i, a)| {
11307                            Self::contextual_action(
11308                                a,
11309                                row,
11310                                day_spec::SwipeEdge::Leading,
11311                                i,
11312                                sw.perform.clone(),
11313                                mtm,
11314                            )
11315                        })
11316                        .collect();
11317                    Some(
11318                        objc2_ui_kit::UISwipeActionsConfiguration::configurationWithActions(
11319                            &objc2_foundation::NSArray::from_retained_slice(&actions),
11320                            mtm,
11321                        ),
11322                    )
11323                };
11324                day_spec::ffi_guard::contain(None, body)
11325            }
11326
11327            // The guard's live veto/override: UIKit proposes a landing slot while the finger
11328            // moves; returning the source path refuses it (the gap stays home), another path
11329            // retargets it — the affordance mirrors the app's answer before the drop.
11330            #[unsafe(method_id(tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:))]
11331            fn target_for_move(
11332                &self,
11333                _tv: &objc2_ui_kit::UITableView,
11334                from_path: &objc2_foundation::NSIndexPath,
11335                proposed: &objc2_foundation::NSIndexPath,
11336            ) -> Retained<objc2_foundation::NSIndexPath> {
11337                // (Closure body: define_class converts only the tail expression.)
11338                let target = || {
11339                    let (from, to) = (self.display_of(from_path), self.display_of(proposed));
11340                    let accepted = self.reorder_verdict(from, to);
11341                    if accepted < 0 {
11342                        return from_path.retain();
11343                    }
11344                    if accepted as usize == to {
11345                        return proposed.retain();
11346                    }
11347                    // A retarget names a display row: in a sectioned table, the end of the
11348                    // row's own section when the finger strays past it (docs/list.md
11349                    // "Sections").
11350                    self.path_of(accepted as usize)
11351                        .unwrap_or_else(|| from_path.retain())
11352                };
11353                // Contained (§8.5): the verdict runs the app's guard closure; a panic refuses
11354                // the move (the source path keeps the gap home).
11355                day_spec::ffi_guard::contain(from_path.retain(), target)
11356            }
11357        }
11358
11359        // The drag delegate that lets rows lift without editing mode (docs/list.md): one drag
11360        // item with an empty provider — nothing leaves the table; UIKit treats it as a local
11361        // reorder and drives the data-source move above.
11362        unsafe impl UITableViewDragDelegate for DayListData {
11363            #[unsafe(method_id(tableView:itemsForBeginningDragSession:atIndexPath:))]
11364            fn items_for_drag(
11365                &self,
11366                _tv: &objc2_ui_kit::UITableView,
11367                _session: &ProtocolObject<dyn objc2_ui_kit::UIDragSession>,
11368                index_path: &objc2_foundation::NSIndexPath,
11369            ) -> Retained<objc2_foundation::NSArray<objc2_ui_kit::UIDragItem>> {
11370                // (Closure body: define_class converts only the tail expression.)
11371                let items = || {
11372                    let row = self.display_of(index_path);
11373                    if self.reorder_verdict(row, row) < 0 {
11374                        return objc2_foundation::NSArray::new();
11375                    }
11376                    let provider = objc2_foundation::NSItemProvider::new();
11377                    let item = unsafe {
11378                        objc2_ui_kit::UIDragItem::initWithItemProvider(
11379                            objc2_ui_kit::UIDragItem::alloc(self.mtm()),
11380                            &provider,
11381                        )
11382                    };
11383                    objc2_foundation::NSArray::from_retained_slice(&[item])
11384                };
11385                // Contained (§8.5): the verdict runs the app's guard closure; a panic refuses
11386                // the lift (no drag items).
11387                day_spec::ffi_guard::contain(objc2_foundation::NSArray::new(), items)
11388            }
11389        }
11390    );
11391
11392    impl DayListData {
11393        fn new(
11394            mtm: MainThreadMarker,
11395            node: NodeId,
11396            selectable: bool,
11397            row_height: f64,
11398            automatic: bool,
11399            delete_label: String,
11400            sections: bool,
11401        ) -> Retained<Self> {
11402            let this = Self::alloc(mtm).set_ivars(ListIvars {
11403                node,
11404                source: RefCell::new(None),
11405                row_height: std::cell::Cell::new(row_height),
11406                automatic,
11407                heights_pending: std::cell::Cell::new(false),
11408                selectable: std::cell::Cell::new(selectable),
11409                delete_label: RefCell::new(delete_label),
11410                sections,
11411                headers: RefCell::new(Vec::new()),
11412                held: RefCell::new(None),
11413                applying: std::cell::Cell::new(None),
11414            });
11415            unsafe { msg_send![super(this), init] }
11416        }
11417
11418        /// Re-read which display rows are headers (docs/list.md "Sections").
11419        fn refresh_headers(&self) {
11420            let source = self.ivars().source.borrow().clone();
11421            let headers = source
11422                .and_then(|s| {
11423                    let is_header = s.is_header.clone()?;
11424                    Some((0..(s.len)()).filter(|i| is_header(*i)).collect())
11425                })
11426                .unwrap_or_default();
11427            *self.ivars().headers.borrow_mut() = headers;
11428        }
11429
11430        /// The display row (the index Day's source speaks) at a table index path.
11431        fn display_of(&self, ip: &objc2_foundation::NSIndexPath) -> usize {
11432            let row = unsafe { ip.row() }.max(0) as usize;
11433            if !self.ivars().sections {
11434                return row;
11435            }
11436            let section = unsafe { ip.section() }.max(0) as usize;
11437            self.ivars()
11438                .headers
11439                .borrow()
11440                .get(section)
11441                .map_or(row, |header| header + 1 + row)
11442        }
11443
11444        /// The source row a table row at `ip` shows: its display row, or, while a change is
11445        /// on its way to the table ([`HeldRows`]), the row it ends at; `None` for a row that
11446        /// change removes, which keeps the cell it has.
11447        fn source_row(&self, ip: &objc2_foundation::NSIndexPath) -> Option<usize> {
11448            let row = self.display_of(ip);
11449            match self
11450                .ivars()
11451                .held
11452                .borrow()
11453                .as_ref()
11454                .and_then(|held| held.finals.as_ref())
11455            {
11456                // A row past the rows held means the table already counts the source's rows,
11457                // and the held change reloads it once it lands.
11458                Some(finals) if row < finals.len() => finals[row],
11459                _ => Some(row),
11460            }
11461        }
11462
11463        /// Hold a change of the source's rows for the table: `deltas` for a
11464        /// `ListPatch::Splice` (`after` is the source's row count then), `None` for a
11465        /// `Reload`. The table takes every change held on the next main-queue turn, together
11466        /// ([`HeldRows`]); `key` is the list's handle.
11467        fn hold(
11468            &self,
11469            key: usize,
11470            table: &objc2_ui_kit::UITableView,
11471            deltas: Option<&[day_spec::props::RowDelta]>,
11472            after: Option<usize>,
11473        ) {
11474            let first = self.ivars().held.borrow().is_none();
11475            // The rows the table shows: the ones a change being applied ends on, if any.
11476            let shown = if first {
11477                self.ivars()
11478                    .applying
11479                    .get()
11480                    .unwrap_or_else(|| self.table_len(table))
11481            } else {
11482                0
11483            };
11484            {
11485                let mut held = self.ivars().held.borrow_mut();
11486                let held = held.get_or_insert_with(|| HeldRows {
11487                    deltas: Some(Vec::new()),
11488                    shown,
11489                    after: None,
11490                    finals: None,
11491                });
11492                // Sequential deltas compose by concatenation; a reload covers everything.
11493                match (deltas, held.deltas.as_mut()) {
11494                    (Some(deltas), Some(all)) => all.extend_from_slice(deltas),
11495                    _ => held.deltas = None,
11496                }
11497                if after.is_some() {
11498                    held.after = after;
11499                }
11500                held.finals = held
11501                    .deltas
11502                    .as_deref()
11503                    .and_then(|deltas| crate::scrolling::final_rows(held.shown, deltas));
11504            }
11505            if !first {
11506                return;
11507            }
11508            // Outside the tree borrow the patch arrived in: the table's update realizes and
11509            // binds cells synchronously.
11510            <Uikit as Platform>::post(Box::new(move || {
11511                let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
11512                if let Some((table, data)) = entry {
11513                    data.apply_held(&table);
11514                }
11515            }));
11516        }
11517
11518        /// Give the table the change held for it ([`HeldRows`]) and lay it out, so the
11519        /// viewport report counts the new rows. A change arriving meanwhile, from a bind the
11520        /// update runs, is held for the next turn against the rows this one ends on.
11521        fn apply_held(&self, table: &objc2_ui_kit::UITableView) {
11522            let Some(held) = self.ivars().held.borrow_mut().take() else {
11523                return;
11524            };
11525            let len = self
11526                .ivars()
11527                .source
11528                .borrow()
11529                .as_ref()
11530                .map(|s| day_spec::ffi_guard::contain(0, || (s.len)()));
11531            self.ivars().applying.set(len);
11532            match &held.deltas {
11533                Some(deltas) => self.apply_splice(table, deltas, held.after),
11534                // reloadData can retire cells synchronously, whose recycle needs the tree.
11535                None => unsafe { table.reloadData() },
11536            }
11537            table.layoutIfNeeded();
11538            self.ivars().applying.set(None);
11539            self.report_viewport(table);
11540        }
11541
11542        /// The index path of a display row; `None` for a header, which is no row of the table.
11543        fn path_of(&self, display: usize) -> Option<Retained<objc2_foundation::NSIndexPath>> {
11544            if !self.ivars().sections {
11545                return Some(objc2_foundation::NSIndexPath::indexPathForRow_inSection(
11546                    display as isize,
11547                    0,
11548                ));
11549            }
11550            let headers = self.ivars().headers.borrow();
11551            let section = headers.partition_point(|h| *h <= display).checked_sub(1)?;
11552            let row = display.checked_sub(headers[section] + 1)?;
11553            Some(objc2_foundation::NSIndexPath::indexPathForRow_inSection(
11554                row as isize,
11555                section as isize,
11556            ))
11557        }
11558
11559        /// The display rows the table currently holds: its rows, plus one header per section
11560        /// in a sectioned list.
11561        fn table_len(&self, table: &objc2_ui_kit::UITableView) -> usize {
11562            let sections = unsafe { table.numberOfSections() }.max(0);
11563            let rows: isize = (0..sections)
11564                .map(|s| unsafe { table.numberOfRowsInSection(s) }.max(0))
11565                .sum();
11566            let headers = if self.ivars().sections { sections } else { 0 };
11567            (rows + headers) as usize
11568        }
11569
11570        /// Whether display row `row` is a supplementary row: the list's header, footer, empty
11571        /// state or content padding (docs/list.md "Header, footer and empty state"). Asks the
11572        /// source, which answers from its snapshot without the tree.
11573        fn is_supplement(&self, row: usize) -> bool {
11574            let check = self
11575                .ivars()
11576                .source
11577                .borrow()
11578                .as_ref()
11579                .and_then(|s| s.is_supplement.clone());
11580            check.is_some_and(|f| day_spec::ffi_guard::contain(false, || f(row)))
11581        }
11582
11583        /// Reports what the table shows (docs/list.md "Visible rows"): the first and last
11584        /// rows with any part inside the area between its insets, and how far the content's
11585        /// end lies below the viewport's. Nothing while the table holds another row count than
11586        /// the source: a splice or reload is still on its way, and numbers from the old rows
11587        /// under the new count would read as the new end and fire `on_end_reached` again.
11588        fn report_viewport(&self, table: &objc2_ui_kit::UITableView) {
11589            let source = self.ivars().source.borrow().clone();
11590            let Some(source) = source else { return };
11591            let Some(report) = source.viewport.clone() else {
11592                return;
11593            };
11594            let len = day_spec::ffi_guard::contain(0, || (source.len)());
11595            if len == 0 || self.table_len(table) != len {
11596                return;
11597            }
11598            let bounds = table.bounds();
11599            let inset = table.adjustedContentInset();
11600            let height = bounds.size.height - inset.top - inset.bottom;
11601            if height < 1.0 || bounds.size.width <= 0.0 {
11602                return;
11603            }
11604            // Half a point in from each edge: a row that only touches an edge is not in view.
11605            let area = CGRect::new(
11606                CGPoint::new(0.0, bounds.origin.y + inset.top + 0.5),
11607                CGSize::new(bounds.size.width, height - 1.0),
11608            );
11609            let paths = unsafe { table.indexPathsForRowsInRect(area) };
11610            let mut span: Option<(usize, usize)> = None;
11611            let mut sections = (isize::MAX, isize::MIN);
11612            let mut note = |row: usize| {
11613                span = Some(span.map_or((row, row), |(a, b)| (a.min(row), b.max(row))));
11614            };
11615            if let Some(paths) = paths {
11616                for ip in &paths {
11617                    note(self.display_of(&ip));
11618                    let s = unsafe { ip.section() };
11619                    sections = (sections.0.min(s), sections.1.max(s));
11620                }
11621            }
11622            if self.ivars().sections {
11623                // A section header in view is a row of Day's too.
11624                let headers = self.ivars().headers.borrow().clone();
11625                let count = unsafe { table.numberOfSections() };
11626                let from = sections.0.min(count).saturating_sub(1).max(0);
11627                let to = sections.1.max(from).min(count - 1);
11628                for s in from..=to {
11629                    let rect = unsafe { table.rectForHeaderInSection(s) };
11630                    let shows = rect.size.height > 0.0
11631                        && rect.origin.y < area.origin.y + area.size.height
11632                        && rect.origin.y + rect.size.height > area.origin.y;
11633                    if shows && let Some(&row) = headers.get(s.max(0) as usize) {
11634                        note(row);
11635                    }
11636                }
11637            }
11638            let Some((first, last)) = span else { return };
11639            let end_distance = crate::scrolling::end_distance(
11640                table.contentSize().height,
11641                table.contentOffset().y,
11642                bounds.size.height,
11643                inset.bottom,
11644            );
11645            day_spec::ffi_guard::contain((), || {
11646                report(day_spec::ListViewport {
11647                    first,
11648                    last,
11649                    end_distance,
11650                });
11651            });
11652        }
11653
11654        /// The reader is moving the list (a finger or a trackpad drags it, or the status bar
11655        /// sends it to the top): tell the source the scroll is theirs (docs/list.md
11656        /// "Following the end"), before the viewport report that says where it went. Not
11657        /// while the list is at or past its end (the rubber band of a reader pulling at the
11658        /// end): the reader is still at the end, and the report that would say so is the one
11659        /// already sent.
11660        fn note_reader_scroll(&self, table: &objc2_ui_kit::UITableView) {
11661            let reader = self
11662                .ivars()
11663                .source
11664                .borrow()
11665                .as_ref()
11666                .and_then(|s| s.reader_scroll.clone());
11667            let Some(reader) = reader else { return };
11668            let end_distance = crate::scrolling::end_distance(
11669                table.contentSize().height,
11670                table.contentOffset().y,
11671                table.bounds().size.height,
11672                table.adjustedContentInset().bottom,
11673            );
11674            if end_distance > 0.0 {
11675                day_spec::ffi_guard::contain((), || reader());
11676            }
11677        }
11678
11679        /// `ListPatch::Splice` (docs/list.md "Splices"), run a turn after the patch, outside
11680        /// the tree. Day's deltas are sequential; `UITableView` takes one batch counted
11681        /// against the rows it holds, so the deltas are folded into that batch. The table
11682        /// reloads instead, keeping its offset, wherever a batch would not agree with what it
11683        /// holds and what the source answers: a sectioned table (deltas there count headers,
11684        /// which are sections to UIKit), a long run, a later change already in the source
11685        /// (`after` is the row count the source had when the patch was sent), or a table whose
11686        /// own count is not the one the deltas start from (one that never loaded counts the
11687        /// source's new rows as its old ones, which is the "invalid batch updates" exception).
11688        fn apply_splice(
11689            &self,
11690            table: &objc2_ui_kit::UITableView,
11691            deltas: &[day_spec::props::RowDelta],
11692            after: Option<usize>,
11693        ) {
11694            if deltas.is_empty() {
11695                return;
11696            }
11697            let now = self
11698                .ivars()
11699                .source
11700                .borrow()
11701                .as_ref()
11702                .map(|s| day_spec::ffi_guard::contain(0, || (s.len)()));
11703            let batch = (|| {
11704                let after = after?;
11705                if self.ivars().sections || deltas.len() > SPLICE_BATCH_LIMIT || now != Some(after)
11706                {
11707                    return None;
11708                }
11709                let old = self.table_len(table);
11710                let batch = crate::scrolling::fold(old, deltas)?;
11711                (old + batch.inserts.len() == after + batch.deletes.len()).then_some(batch)
11712            })();
11713            let Some(batch) = batch else {
11714                Self::reload_keeping_offset(table);
11715                return;
11716            };
11717            let paths = |rows: &[usize]| {
11718                let paths: Vec<_> = rows
11719                    .iter()
11720                    .map(|row| {
11721                        objc2_foundation::NSIndexPath::indexPathForRow_inSection(*row as isize, 0)
11722                    })
11723                    .collect();
11724                objc2_foundation::NSArray::from_retained_slice(&paths)
11725            };
11726            // Rows that only arrive below the viewport go in without an animation: nobody sees
11727            // them arrive, and `endUpdates` animates the table's own bounds, which turns away
11728            // every touch on the table until it ends. Rows that keep arriving (a feed, a chat
11729            // that follows its end) would otherwise keep the reader from taking the list
11730            // (docs/list.md "Following the end").
11731            if batch.deletes.is_empty()
11732                && batch.moves.is_empty()
11733                && Self::all_below_viewport(table, &batch.inserts)
11734                && let Some(mtm) = MainThreadMarker::new()
11735            {
11736                let update = block2::RcBlock::new(|| unsafe {
11737                    table.beginUpdates();
11738                    table.insertRowsAtIndexPaths_withRowAnimation(
11739                        &paths(&batch.inserts),
11740                        objc2_ui_kit::UITableViewRowAnimation::None,
11741                    );
11742                    table.endUpdates();
11743                });
11744                UIView::performWithoutAnimation(&update, mtm);
11745                return;
11746            }
11747            let animation = objc2_ui_kit::UITableViewRowAnimation::Automatic;
11748            unsafe {
11749                table.beginUpdates();
11750                if !batch.deletes.is_empty() {
11751                    table
11752                        .deleteRowsAtIndexPaths_withRowAnimation(&paths(&batch.deletes), animation);
11753                }
11754                if !batch.inserts.is_empty() {
11755                    table
11756                        .insertRowsAtIndexPaths_withRowAnimation(&paths(&batch.inserts), animation);
11757                }
11758                for (from, to) in &batch.moves {
11759                    table.moveRowAtIndexPath_toIndexPath(
11760                        &objc2_foundation::NSIndexPath::indexPathForRow_inSection(
11761                            *from as isize,
11762                            0,
11763                        ),
11764                        &objc2_foundation::NSIndexPath::indexPathForRow_inSection(*to as isize, 0),
11765                    );
11766                }
11767                table.endUpdates();
11768            }
11769        }
11770
11771        /// Whether rows inserted at `inserts` (final rows of an insert-only batch) all land
11772        /// below the viewport: after every row the table shows, which reach its bottom edge.
11773        fn all_below_viewport(table: &objc2_ui_kit::UITableView, inserts: &[usize]) -> bool {
11774            let Some(last) = table
11775                .indexPathsForVisibleRows()
11776                .and_then(|paths| paths.iter().map(|ip| unsafe { ip.row() }).max())
11777            else {
11778                return false;
11779            };
11780            let Some(first_insert) = inserts.iter().min() else {
11781                return false;
11782            };
11783            let last_path = objc2_foundation::NSIndexPath::indexPathForRow_inSection(last, 0);
11784            let shown = unsafe { table.rectForRowAtIndexPath(&last_path) };
11785            let bottom = table.contentOffset().y + table.bounds().size.height
11786                - table.adjustedContentInset().bottom;
11787            *first_insert as isize > last && shown.origin.y + shown.size.height >= bottom - 0.5
11788        }
11789
11790        /// Reloads a table where it stands: the offset it had, clamped to the new content.
11791        fn reload_keeping_offset(table: &objc2_ui_kit::UITableView) {
11792            let offset = table.contentOffset();
11793            unsafe { table.reloadData() };
11794            table.layoutIfNeeded();
11795            let inset = table.adjustedContentInset();
11796            let lowest = -inset.top;
11797            let highest = (table.contentSize().height + inset.bottom - table.bounds().size.height)
11798                .max(lowest);
11799            let y = offset.y.clamp(lowest, highest);
11800            if (table.contentOffset().y - y).abs() > 0.25 {
11801                table.setContentOffset(CGPoint::new(offset.x, y));
11802            }
11803        }
11804
11805        /// `Toolkit::list_scroll` (docs/list.md "Programmatic scrolling"), run a turn after the
11806        /// call so it lands behind the splice or reload that made its row. `UITableView`
11807        /// aligns and animates natively; a row whose bottom it cannot know yet (a self-sizing
11808        /// list's estimate) is corrected after an instant jump, once the jump realized it.
11809        fn scroll(&self, table: &objc2_ui_kit::UITableView, to: day_spec::ListScroll) {
11810            use objc2_ui_kit::UITableViewScrollPosition as At;
11811            // The reader's finger holds the list (docs/list.md "Following the end"): UIKit
11812            // would run the app's scroll against it.
11813            if table.isTracking() {
11814                return;
11815            }
11816            let count = self.table_len(table);
11817            if count == 0 {
11818                return;
11819            }
11820            table.layoutIfNeeded();
11821            let target = match to.row {
11822                Some(row) => {
11823                    let position = match to.align {
11824                        day_spec::RowAlign::Nearest => At::None,
11825                        day_spec::RowAlign::Start => At::Top,
11826                        day_spec::RowAlign::Center => At::Middle,
11827                        day_spec::RowAlign::End => At::Bottom,
11828                    };
11829                    self.scroll_path(table, row.min(count - 1))
11830                        .map(|ip| (ip, position))
11831                }
11832                None => Self::last_path(table).map(|ip| (ip, At::Bottom)),
11833            };
11834            match target {
11835                Some((ip, position)) => unsafe {
11836                    table.scrollToRowAtIndexPath_atScrollPosition_animated(
11837                        &ip,
11838                        position,
11839                        to.animated,
11840                    );
11841                },
11842                // A header-only section: its header's rect.
11843                None => {
11844                    if let Some(row) = to.row {
11845                        let section = self.ivars().headers.borrow().iter().position(|h| *h == row);
11846                        if let Some(s) = section {
11847                            let rect = unsafe { table.rectForHeaderInSection(s as isize) };
11848                            table.scrollRectToVisible_animated(rect, to.animated);
11849                        }
11850                    } else {
11851                        let inset = table.adjustedContentInset();
11852                        let end = (table.contentSize().height + inset.bottom
11853                            - table.bounds().size.height)
11854                            .max(-inset.top);
11855                        table.setContentOffset_animated(
11856                            CGPoint::new(table.contentOffset().x, end),
11857                            to.animated,
11858                        );
11859                    }
11860                }
11861            }
11862            if to.row.is_none() && !to.animated {
11863                // The very end of the content, past any inset, now that the jump has laid
11864                // out the rows there at their real heights.
11865                table.layoutIfNeeded();
11866                let inset = table.adjustedContentInset();
11867                let end = (table.contentSize().height + inset.bottom - table.bounds().size.height)
11868                    .max(-inset.top);
11869                table.setContentOffset(CGPoint::new(table.contentOffset().x, end));
11870            }
11871            if !to.animated {
11872                self.report_viewport(table);
11873            }
11874        }
11875
11876        /// The index path a scroll to display row `row` aims at: the row's own, or for a
11877        /// section header the first row under it (the header rides above it).
11878        fn scroll_path(
11879            &self,
11880            table: &objc2_ui_kit::UITableView,
11881            row: usize,
11882        ) -> Option<Retained<objc2_foundation::NSIndexPath>> {
11883            if let Some(ip) = self.path_of(row) {
11884                return Some(ip);
11885            }
11886            let section = self
11887                .ivars()
11888                .headers
11889                .borrow()
11890                .iter()
11891                .position(|h| *h == row)?;
11892            (unsafe { table.numberOfRowsInSection(section as isize) } > 0).then(|| {
11893                objc2_foundation::NSIndexPath::indexPathForRow_inSection(0, section as isize)
11894            })
11895        }
11896
11897        /// The table's last row, in the last section that has one.
11898        fn last_path(
11899            table: &objc2_ui_kit::UITableView,
11900        ) -> Option<Retained<objc2_foundation::NSIndexPath>> {
11901            let sections = unsafe { table.numberOfSections() };
11902            (0..sections).rev().find_map(|s| {
11903                let rows = unsafe { table.numberOfRowsInSection(s) };
11904                (rows > 0)
11905                    .then(|| objc2_foundation::NSIndexPath::indexPathForRow_inSection(rows - 1, s))
11906            })
11907        }
11908
11909        /// `ListPatch::RowSizeInvalidated`: a self-sizing row was re-laid at a new height.
11910        /// The patch arrives under the day-core borrow, and re-sizing asks the cells, which ask
11911        /// the source; so the table re-sizes its rows on the next turn, once for every row a
11912        /// pass changed, and without animation: the row takes its content's height.
11913        fn post_row_heights(key: usize) {
11914            let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
11915            let Some((_, data)) = entry else { return };
11916            if data.ivars().heights_pending.replace(true) {
11917                return;
11918            }
11919            <Uikit as Platform>::post(Box::new(move || {
11920                let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
11921                let Some((table, data)) = entry else { return };
11922                data.ivars().heights_pending.set(false);
11923                // Only while the table shows the source's row count. A splice or reload that
11924                // changed the count is still on its way (both are posted too), and an empty
11925                // batch would make the table adopt the new count early; that change's own
11926                // batch then failed UITableView's row-count check and threw ("Invalid batch
11927                // updates"), aborting the app. The pending change re-sizes the rows itself.
11928                let len = data.ivars().source.borrow().as_ref().map(|s| (s.len)());
11929                if len != Some(data.table_len(&table)) {
11930                    return;
11931                }
11932                let cls = <objc2_ui_kit::UIView as objc2::ClassType>::class();
11933                unsafe {
11934                    let was: bool = msg_send![cls, areAnimationsEnabled];
11935                    let _: () = msg_send![cls, setAnimationsEnabled: false];
11936                    table.beginUpdates();
11937                    table.endUpdates();
11938                    let _: () = msg_send![cls, setAnimationsEnabled: was];
11939                }
11940            }));
11941        }
11942
11943        /// A row's editing control: Delete where the delete seam offers one, none otherwise.
11944        /// It runs the app's guard closure, so it is contained (§8.5), answering none on panic.
11945        fn row_editing_style(&self, row: usize) -> objc2_ui_kit::UITableViewCellEditingStyle {
11946            day_spec::ffi_guard::contain(objc2_ui_kit::UITableViewCellEditingStyle::None, || {
11947                let deletable = self
11948                    .ivars()
11949                    .source
11950                    .borrow()
11951                    .as_ref()
11952                    .and_then(|s| s.delete.clone())
11953                    .is_some_and(|d| (d.can_delete)(row));
11954                if deletable {
11955                    objc2_ui_kit::UITableViewCellEditingStyle::Delete
11956                } else {
11957                    objc2_ui_kit::UITableViewCellEditingStyle::None
11958                }
11959            })
11960        }
11961
11962        /// The guard's verdict for `from -> to` through the sync seam (accepted index, or -1 —
11963        /// also -1 when the list has no reorder seam at all).
11964        fn reorder_verdict(&self, from: usize, to: usize) -> i64 {
11965            self.ivars()
11966                .source
11967                .borrow()
11968                .as_ref()
11969                .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
11970                .unwrap_or(-1)
11971        }
11972
11973        /// One offered swipe action as a `UIContextualAction` (docs/list.md). The handler
11974        /// commits through the seam — which defers the app's callback to the event drain —
11975        /// and reports done; the row springs back on its own (an action that removes its row
11976        /// does so through the app's data refresh).
11977        fn contextual_action(
11978            a: &day_spec::ListSwipeAction,
11979            row: usize,
11980            edge: day_spec::SwipeEdge,
11981            index: usize,
11982            perform: std::rc::Rc<dyn Fn(usize, day_spec::SwipeEdge, usize)>,
11983            mtm: MainThreadMarker,
11984        ) -> Retained<objc2_ui_kit::UIContextualAction> {
11985            let handler = block2::RcBlock::new(
11986                move |_a: NonNull<objc2_ui_kit::UIContextualAction>,
11987                      _v: NonNull<UIView>,
11988                      done: NonNull<block2::DynBlock<dyn Fn(objc2::runtime::Bool)>>| {
11989                    day_spec::ffi_guard::contain((), || {
11990                        perform(row, edge, index);
11991                        unsafe { done.as_ref().call((objc2::runtime::Bool::YES,)) };
11992                    });
11993                },
11994            );
11995            let style = if a.destructive {
11996                objc2_ui_kit::UIContextualActionStyle::Destructive
11997            } else {
11998                objc2_ui_kit::UIContextualActionStyle::Normal
11999            };
12000            let action = unsafe {
12001                objc2_ui_kit::UIContextualAction::contextualActionWithStyle_title_handler(
12002                    style,
12003                    Some(&NSString::from_str(&a.label)),
12004                    block2::RcBlock::as_ptr(&handler),
12005                    mtm,
12006                )
12007            };
12008            if let Some(t) = a.tint {
12009                unsafe { action.setBackgroundColor(Some(&uiink(t))) };
12010            }
12011            // The glyph, where one is declared — UIKit shows it in place of the title on
12012            // standard-height rows (the title stays the accessibility name), the same
12013            // wordless idiom the delete affordance uses.
12014            if let Some(sym) = a.symbol
12015                && let Some(img) = objc2_ui_kit::UIImage::systemImageNamed(&NSString::from_str(
12016                    day_spec::sf_symbol_name(sym),
12017                ))
12018            {
12019                unsafe { action.setImage(Some(&img)) };
12020            }
12021            action
12022        }
12023    }
12024
12025    /// A realized LIST's (table view, its data source), keyed by table ptr.
12026    type ListEntry = (Retained<objc2_ui_kit::UITableView>, Retained<DayListData>);
12027
12028    // -----------------------------------------------------------------------
12029    // DayScrollDelegate — a `scroll` piece's offset, phase, snap and zoom (docs/scroll.md)
12030    // -----------------------------------------------------------------------
12031
12032    /// The association key under which a scroll view retains its `DayScrollDelegate`.
12033    static SCROLL_DELEGATE_KEY: u8 = 0;
12034
12035    /// A scroll view's offset from the content's top-leading corner: `contentOffset` less
12036    /// the insets UIKit puts around the content, so the top at rest is zero.
12037    fn content_offset(sv: &UIScrollView) -> day_spec::Point {
12038        let at = sv.contentOffset();
12039        let inset = sv.adjustedContentInset();
12040        day_spec::Point::new(at.x + inset.left, at.y + inset.top)
12041    }
12042
12043    struct ScrollIvars {
12044        node: NodeId,
12045        horizontal: bool,
12046        /// `ScrollProps::track_offset`: send `Event::ScrollChanged`.
12047        track_offset: bool,
12048        /// `ScrollProps::track_phase`: send `Event::ScrollPhase`.
12049        track_phase: bool,
12050        /// `ScrollSnap::Interval`'s grid, in points; `None` otherwise (`Page` is UIKit's own
12051        /// paging and needs no delegate).
12052        interval: Option<f64>,
12053        /// The zooming content (`ScrollProps::zoom`): one plain view, the scroll view's only
12054        /// Day subview, that Day's children are inserted into and UIKit scales.
12055        zoom_content: Option<Retained<UIView>>,
12056        /// The last offset and scale sent, so a callback that moved nothing sends nothing.
12057        last_offset: Cell<Option<day_spec::Point>>,
12058        last_scale: Cell<Option<f64>>,
12059        phase: Cell<day_spec::ScrollPhase>,
12060    }
12061
12062    define_class!(
12063        // The scroll view's delegate, installed only when the props ask for something it
12064        // reports or decides; retained by the scroll view itself (an associated object), since
12065        // `UIScrollView.delegate` is weak.
12066        #[unsafe(super(NSObject))]
12067        #[thread_kind = MainThreadOnly]
12068        #[name = "DayScrollDelegate"]
12069        #[ivars = ScrollIvars]
12070        struct DayScrollDelegate;
12071
12072        unsafe impl NSObjectProtocol for DayScrollDelegate {}
12073
12074        unsafe impl UIScrollViewDelegate for DayScrollDelegate {
12075            /// Whatever moved the content: a finger, momentum, a bounce, a programmatic
12076            /// scroll's every frame, a zoom (docs/scroll.md "Offset and phase"). UIKit calls
12077            /// this once per frame of a scroll, and its last call has the offset at rest.
12078            #[unsafe(method(scrollViewDidScroll:))]
12079            fn did_scroll(&self, sv: &UIScrollView) {
12080                day_spec::ffi_guard::contain((), || self.report_offset(sv));
12081            }
12082
12083            #[unsafe(method(scrollViewWillBeginDragging:))]
12084            fn will_begin_dragging(&self, _sv: &UIScrollView) {
12085                day_spec::ffi_guard::contain((), || {
12086                    self.enter(day_spec::ScrollPhase::Dragging);
12087                });
12088            }
12089
12090            /// `ScrollSnap::Interval`: the target UIKit projected for the release, moved to
12091            /// the grid; UIKit then decelerates onto it (docs/scroll.md "Snapping").
12092            #[unsafe(method(scrollViewWillEndDragging:withVelocity:targetContentOffset:))]
12093            unsafe fn will_end_dragging(
12094                &self,
12095                sv: &UIScrollView,
12096                velocity: CGPoint,
12097                target: NonNull<CGPoint>,
12098            ) {
12099                day_spec::ffi_guard::contain((), || {
12100                    let Some(interval) = self.ivars().interval else {
12101                        return;
12102                    };
12103                    let at = sv.contentOffset();
12104                    let size = sv.bounds().size;
12105                    let content = sv.contentSize();
12106                    let inset = sv.adjustedContentInset();
12107                    // SAFETY: UIKit hands a valid, writable pointer for the duration of the
12108                    // call (the documented in-out parameter).
12109                    let goal = unsafe { target.read() };
12110                    let snapped = if self.ivars().horizontal {
12111                        let range = content.width + inset.left + inset.right - size.width;
12112                        let x = crate::scrolling::snap_stop(
12113                            goal.x + inset.left,
12114                            at.x + inset.left,
12115                            velocity.x,
12116                            interval,
12117                            range,
12118                        );
12119                        CGPoint::new(x - inset.left, goal.y)
12120                    } else {
12121                        let range = content.height + inset.top + inset.bottom - size.height;
12122                        let y = crate::scrolling::snap_stop(
12123                            goal.y + inset.top,
12124                            at.y + inset.top,
12125                            velocity.y,
12126                            interval,
12127                            range,
12128                        );
12129                        CGPoint::new(goal.x, y - inset.top)
12130                    };
12131                    // SAFETY: as above.
12132                    unsafe { target.write(snapped) };
12133                });
12134            }
12135
12136            #[unsafe(method(scrollViewDidEndDragging:willDecelerate:))]
12137            fn did_end_dragging(&self, _sv: &UIScrollView, decelerate: bool) {
12138                day_spec::ffi_guard::contain((), || {
12139                    self.enter(if decelerate {
12140                        day_spec::ScrollPhase::Coasting
12141                    } else {
12142                        day_spec::ScrollPhase::Idle
12143                    });
12144                });
12145            }
12146
12147            #[unsafe(method(scrollViewDidEndDecelerating:))]
12148            fn did_end_decelerating(&self, sv: &UIScrollView) {
12149                day_spec::ffi_guard::contain((), || {
12150                    self.report_offset(sv);
12151                    self.enter(day_spec::ScrollPhase::Idle);
12152                });
12153            }
12154
12155            /// A programmatic animated scroll ended: no phase (the user did not scroll), but
12156            /// the offset it rests at is reported if the last frame did not already.
12157            #[unsafe(method(scrollViewDidEndScrollingAnimation:))]
12158            fn did_end_scrolling_animation(&self, sv: &UIScrollView) {
12159                day_spec::ffi_guard::contain((), || self.report_offset(sv));
12160            }
12161
12162            #[unsafe(method_id(viewForZoomingInScrollView:))]
12163            fn view_for_zooming(&self, _sv: &UIScrollView) -> Option<Retained<UIView>> {
12164                self.ivars().zoom_content.clone()
12165            }
12166
12167            #[unsafe(method(scrollViewDidZoom:))]
12168            fn did_zoom(&self, sv: &UIScrollView) {
12169                day_spec::ffi_guard::contain((), || self.report_scale(sv));
12170            }
12171
12172            #[unsafe(method(scrollViewDidEndZooming:withView:atScale:))]
12173            fn did_end_zooming(&self, sv: &UIScrollView, _view: Option<&UIView>, _scale: CGFloat) {
12174                day_spec::ffi_guard::contain((), || {
12175                    self.report_scale(sv);
12176                    self.report_offset(sv);
12177                });
12178            }
12179        }
12180    );
12181
12182    impl DayScrollDelegate {
12183        /// The delegate a `scroll` piece's view was realized with, if it got one.
12184        fn of(sv: &UIScrollView) -> Option<Retained<Self>> {
12185            let delegate: Option<Retained<AnyObject>> = unsafe { msg_send![sv, delegate] };
12186            delegate?.downcast::<Self>().ok()
12187        }
12188
12189        /// `Event::ScrollChanged`, when tracked and when the offset moved.
12190        fn report_offset(&self, sv: &UIScrollView) {
12191            let iv = self.ivars();
12192            if !iv.track_offset {
12193                return;
12194            }
12195            let at = content_offset(sv);
12196            if iv.last_offset.replace(Some(at)) != Some(at) {
12197                emit(iv.node, Event::ScrollChanged(at));
12198            }
12199        }
12200
12201        /// `Event::ScrollZoomed`, when the view zooms and the scale moved; `force` sends the
12202        /// scale at rest even when it did not move (a patch that asked for the scale it has).
12203        fn report_scale_with(&self, sv: &UIScrollView, force: bool) {
12204            let iv = self.ivars();
12205            if iv.zoom_content.is_none() {
12206                return;
12207            }
12208            let scale = sv.zoomScale();
12209            if iv.last_scale.replace(Some(scale)) != Some(scale) || force {
12210                emit(iv.node, Event::ScrollZoomed(scale));
12211            }
12212        }
12213
12214        fn report_scale(&self, sv: &UIScrollView) {
12215            self.report_scale_with(sv, false);
12216        }
12217
12218        /// `Event::ScrollPhase` on a change, when tracked.
12219        fn enter(&self, phase: day_spec::ScrollPhase) {
12220            let iv = self.ivars();
12221            if iv.track_phase && iv.phase.replace(phase) != phase {
12222                emit(iv.node, Event::ScrollPhase(phase));
12223            }
12224        }
12225
12226        /// `ScrollPatch::Zoom` (docs/scroll.md "Zoom"): to `scale`, clamped to the range,
12227        /// around the point at the viewport's center. `zoomToRect:animated:` is UIKit's own
12228        /// zoom, animation included, and it clamps the offset to the new content.
12229        fn zoom(&self, sv: &UIScrollView, scale: f64, animated: bool) {
12230            if self.ivars().zoom_content.is_none() || !scale.is_finite() {
12231                return;
12232            }
12233            let scale = scale.clamp(sv.minimumZoomScale(), sv.maximumZoomScale());
12234            let now = sv.zoomScale();
12235            if (now - scale).abs() < 1e-6 {
12236                self.report_scale_with(sv, true);
12237                return;
12238            }
12239            let at = sv.contentOffset();
12240            let size = sv.bounds().size;
12241            // The viewport's center in the content view's own (unscaled) coordinates.
12242            let center = CGPoint::new(
12243                (at.x + size.width / 2.0) / now,
12244                (at.y + size.height / 2.0) / now,
12245            );
12246            let span = CGSize::new(size.width / scale, size.height / scale);
12247            let rect = CGRect::new(
12248                CGPoint::new(center.x - span.width / 2.0, center.y - span.height / 2.0),
12249                span,
12250            );
12251            sv.zoomToRect_animated(rect, animated);
12252            if !animated {
12253                self.report_scale(sv);
12254            }
12255        }
12256    }
12257
12258    /// The zooming content view of a `scroll` realized with `ScrollProps::zoom`: Day's
12259    /// children go in it, and Day's content size is its unscaled size.
12260    fn zoom_content(parent: &UIView) -> Option<Retained<UIView>> {
12261        let sv = parent.downcast_ref::<UIScrollView>()?;
12262        DayScrollDelegate::of(sv)?.ivars().zoom_content.clone()
12263    }
12264
12265    /// The `scroll` piece's native view (docs/scroll.md): every preference UIKit's scroll
12266    /// view has a property for, and the delegate for what it reports or decides.
12267    fn make_scroll(p: &ScrollProps, id: NodeId, mtm: MainThreadMarker) -> Retained<UIScrollView> {
12268        use day_spec::props::{KeyboardDismiss, KeyboardTaps, ScrollIndicators, ScrollSnap};
12269        let sv = unsafe { UIScrollView::new(mtm) };
12270        if p.indicators == ScrollIndicators::Hidden {
12271            sv.setShowsVerticalScrollIndicator(false);
12272            sv.setShowsHorizontalScrollIndicator(false);
12273        }
12274        match p.bounce {
12275            Some(false) => sv.setBounces(false),
12276            Some(true) => {
12277                sv.setBounces(true);
12278                if p.horizontal {
12279                    sv.setAlwaysBounceHorizontal(true);
12280                } else {
12281                    sv.setAlwaysBounceVertical(true);
12282                }
12283            }
12284            None => {}
12285        }
12286        let interval = match p.snap {
12287            ScrollSnap::None => None,
12288            // Pages of the viewport's extent, one per swipe: UIKit's paging is exactly that.
12289            ScrollSnap::Page => {
12290                sv.setPagingEnabled(true);
12291                None
12292            }
12293            ScrollSnap::Interval(points) => {
12294                // The fast rate is what a grid-snapping view decelerates with (Photos' strip).
12295                sv.setDecelerationRate(unsafe { objc2_ui_kit::UIScrollViewDecelerationRateFast });
12296                (points.is_finite() && points > 0.0).then_some(points)
12297            }
12298        };
12299        match p.keyboard_dismiss {
12300            KeyboardDismiss::Never => {}
12301            KeyboardDismiss::OnDrag => {
12302                sv.setKeyboardDismissMode(objc2_ui_kit::UIScrollViewKeyboardDismissMode::OnDrag);
12303            }
12304            KeyboardDismiss::Interactive => sv
12305                .setKeyboardDismissMode(objc2_ui_kit::UIScrollViewKeyboardDismissMode::Interactive),
12306        }
12307        if p.keyboard_taps == KeyboardTaps::Dismiss {
12308            let tap = DayKeyboardTap::new(mtm);
12309            unsafe { sv.addGestureRecognizer(&tap) };
12310        }
12311        let zoom_content = p.zoom.map(|range| {
12312            sv.setMinimumZoomScale(range.min.min(range.max));
12313            sv.setMaximumZoomScale(range.max.max(range.min));
12314            let content = UIView::new(mtm);
12315            unsafe { sv.addSubview(&content) };
12316            content
12317        });
12318        if p.track_offset || p.track_phase || interval.is_some() || zoom_content.is_some() {
12319            let delegate = DayScrollDelegate::alloc(mtm).set_ivars(ScrollIvars {
12320                node: id,
12321                horizontal: p.horizontal,
12322                track_offset: p.track_offset,
12323                track_phase: p.track_phase,
12324                interval,
12325                zoom_content,
12326                last_offset: Cell::new(None),
12327                last_scale: Cell::new(None),
12328                phase: Cell::new(day_spec::ScrollPhase::Idle),
12329            });
12330            let delegate: Retained<DayScrollDelegate> = unsafe { msg_send![super(delegate), init] };
12331            unsafe {
12332                sv.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
12333                // SAFETY: both are live objects; the association retains the delegate for
12334                // the scroll view's lifetime, which is what a weak `delegate` needs.
12335                objc2::ffi::objc_setAssociatedObject(
12336                    std::ptr::from_ref::<objc2::runtime::AnyObject>(&sv).cast_mut(),
12337                    std::ptr::addr_of!(SCROLL_DELEGATE_KEY).cast(),
12338                    std::ptr::from_ref::<objc2::runtime::AnyObject>(&delegate).cast_mut(),
12339                    objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
12340                );
12341            }
12342        }
12343        sv
12344    }
12345
12346    struct KeyboardTapIvars {
12347        /// Where the touch went down, in the window.
12348        start: Cell<CGPoint>,
12349    }
12350
12351    define_class!(
12352        // `KeyboardTaps::Dismiss` (docs/scroll.md "Keyboard"): while the software keyboard is
12353        // up, a tap in the scroll view that is not on a text input dismisses it and goes no
12354        // further. A recognizer of Day's own rather than a `UITapGestureRecognizer`, because
12355        // UIKit lets a button's own tap win over an ancestor's single-tap recognizer, and the
12356        // tap must not reach the button. It holds the touches back from the views under it
12357        // (`delaysTouchesBegan`) only while the keyboard is up: it fails at once otherwise, so
12358        // taps are delivered undelayed, and it fails as soon as the touch moves, so a drag
12359        // still scrolls.
12360        #[unsafe(super(objc2_ui_kit::UIGestureRecognizer))]
12361        #[thread_kind = MainThreadOnly]
12362        #[name = "DayKeyboardTap"]
12363        #[ivars = KeyboardTapIvars]
12364        struct DayKeyboardTap;
12365
12366        impl DayKeyboardTap {
12367            #[unsafe(method(touchesBegan:withEvent:))]
12368            fn touches_began(
12369                &self,
12370                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12371                event: &objc2_ui_kit::UIEvent,
12372            ) {
12373                day_spec::ffi_guard::contain((), || {
12374                    let all = unsafe { event.touchesForGestureRecognizer(self) };
12375                    let touch = touches.iter().next();
12376                    let several = all.is_some_and(|all| all.count() > 1);
12377                    let on_input = touch
12378                        .as_ref()
12379                        .and_then(|t| unsafe { t.view() })
12380                        .is_some_and(|v| is_text_input(&v));
12381                    match touch {
12382                        Some(t) if KEYBOARD_UP.with(Cell::get) && !several && !on_input => {
12383                            let at = unsafe { t.locationInView(None) };
12384                            self.ivars().start.set(at);
12385                        }
12386                        _ => unsafe {
12387                            self.setState(objc2_ui_kit::UIGestureRecognizerState::Failed);
12388                        },
12389                    }
12390                });
12391            }
12392
12393            #[unsafe(method(touchesMoved:withEvent:))]
12394            fn touches_moved(
12395                &self,
12396                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12397                _event: &objc2_ui_kit::UIEvent,
12398            ) {
12399                day_spec::ffi_guard::contain((), || {
12400                    let Some(touch) = touches.iter().next() else {
12401                        return;
12402                    };
12403                    let at = unsafe { touch.locationInView(None) };
12404                    let start = self.ivars().start.get();
12405                    if (at.x - start.x).hypot(at.y - start.y) > 10.0 {
12406                        unsafe { self.setState(objc2_ui_kit::UIGestureRecognizerState::Failed) };
12407                    }
12408                });
12409            }
12410
12411            #[unsafe(method(touchesEnded:withEvent:))]
12412            fn touches_ended(
12413                &self,
12414                _touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12415                _event: &objc2_ui_kit::UIEvent,
12416            ) {
12417                // Recognized: end editing in the window, which resigns the text input and
12418                // takes the keyboard down. Done here rather than through a target, which would
12419                // have the recognizer hold itself.
12420                day_spec::ffi_guard::contain((), || {
12421                    unsafe { self.setState(objc2_ui_kit::UIGestureRecognizerState::Ended) };
12422                    if let Some(window) = unsafe { self.view() }.and_then(|v| v.window()) {
12423                        let _ = window.endEditing(true);
12424                    }
12425                });
12426            }
12427
12428            #[unsafe(method(touchesCancelled:withEvent:))]
12429            fn touches_cancelled(
12430                &self,
12431                _touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12432                _event: &objc2_ui_kit::UIEvent,
12433            ) {
12434                day_spec::ffi_guard::contain((), || unsafe {
12435                    self.setState(objc2_ui_kit::UIGestureRecognizerState::Failed);
12436                });
12437            }
12438        }
12439    );
12440
12441    impl DayKeyboardTap {
12442        fn new(mtm: MainThreadMarker) -> Retained<Self> {
12443            let this = Self::alloc(mtm).set_ivars(KeyboardTapIvars {
12444                start: Cell::new(CGPoint::new(0.0, 0.0)),
12445            });
12446            let this: Retained<Self> = unsafe {
12447                msg_send![super(this), initWithTarget: None::<&AnyObject>, action: None::<Sel>]
12448            };
12449            unsafe {
12450                this.setCancelsTouchesInView(true);
12451                this.setDelaysTouchesBegan(true);
12452            }
12453            this
12454        }
12455    }
12456
12457    /// Whether a touch on `view` lands on a text input: the view or one of its ancestors is a
12458    /// text field or a text view.
12459    fn is_text_input(view: &UIView) -> bool {
12460        let mut cur = Some(view.retain());
12461        while let Some(v) = cur {
12462            if v.downcast_ref::<UITextField>().is_some() || v.downcast_ref::<UITextView>().is_some()
12463            {
12464                return true;
12465            }
12466            cur = v.superview();
12467        }
12468        false
12469    }
12470
12471    // -----------------------------------------------------------------------
12472    // DayCanvasView — replay in drawRect (§11)
12473    // -----------------------------------------------------------------------
12474
12475    define_class!(
12476        #[unsafe(super(UIView))]
12477        #[thread_kind = MainThreadOnly]
12478        #[name = "DayFocusableContainer"]
12479        #[ivars = ()]
12480        struct DayFocusableContainer;
12481        impl DayFocusableContainer {
12482            // A surface's shadow is cast from a path, which the layer does not resize with its
12483            // bounds (docs/surfaces.md): a frame change re-lays the view out, and the path is
12484            // rebuilt here.
12485            #[unsafe(method(layoutSubviews))]
12486            fn layout_subviews(&self) {
12487                let _: () = unsafe { msg_send![super(self), layoutSubviews] };
12488                day_spec::ffi_guard::contain((), || {
12489                    relayout_surface(self);
12490                    sync_surface_shadow_path(self);
12491                });
12492            }
12493
12494            // Layer colors are `CGColor`s, which do not follow the appearance: set them again
12495            // from the surface's inks when the traits change (color brief §1.5). Still called
12496            // on iOS 17+, where it is deprecated in favor of trait registration.
12497            #[unsafe(method(traitCollectionDidChange:))]
12498            fn trait_collection_did_change(
12499                &self,
12500                previous: Option<&objc2_ui_kit::UITraitCollection>,
12501            ) {
12502                let _: () = unsafe { msg_send![super(self), traitCollectionDidChange: previous] };
12503                day_spec::ffi_guard::contain((), || refresh_surface_inks(self, previous));
12504            }
12505
12506            #[unsafe(method(canBecomeFirstResponder))]
12507            fn can_become_first_responder(&self) -> bool {
12508                KEY_NODES.with(|t| t.get(std::ptr::from_ref::<Self>(self).cast::<UIView>() as usize)).is_some()
12509            }
12510
12511            #[unsafe(method(becomeFirstResponder))]
12512            fn become_first_responder(&self) -> bool {
12513                let became: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
12514                if became {
12515                    let ptr = std::ptr::from_ref::<DayFocusableContainer>(self).cast::<UIView>() as usize;
12516                    if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12517                        day_spec::ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
12518                    }
12519                }
12520                became
12521            }
12522
12523            #[unsafe(method(resignFirstResponder))]
12524            fn resign_first_responder(&self) -> bool {
12525                let resigned: bool = unsafe { msg_send![super(self), resignFirstResponder] };
12526                if resigned {
12527                    let ptr = std::ptr::from_ref::<DayFocusableContainer>(self).cast::<UIView>() as usize;
12528                    // A key held across the focus change sends no release (docs/menus.md "Keys").
12529                    KEYS_DOWN.with(|t| t.remove(ptr));
12530                    if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12531                        day_spec::ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
12532                    }
12533                }
12534                resigned
12535            }
12536
12537            // Pass-through and hit slop (docs/gestures.md): a container takes a touch only
12538            // when something is attached to it or it takes focus.
12539            #[unsafe(method_id(hitTest:withEvent:))]
12540            fn hit_test(
12541                &self,
12542                point: CGPoint,
12543                event: Option<&objc2_ui_kit::UIEvent>,
12544            ) -> Option<Retained<UIView>> {
12545                let view: &UIView = self;
12546                let keys = KEY_NODES.with(|t| t.contains(ptr_of(view)));
12547                day_hit_test(view, point, event, takes_touches(view, keys))
12548            }
12549
12550            #[unsafe(method(pointInside:withEvent:))]
12551            fn point_inside(&self, point: CGPoint, _event: Option<&objc2_ui_kit::UIEvent>) -> bool {
12552                day_point_inside(self, point)
12553            }
12554
12555            // The focus system an iPad's hardware keyboard drives (Tab, arrows with Full
12556            // Keyboard Access): a `.focusable()` view joins it and draws its focus effect, and
12557            // being focused there makes it the first responder its keys arrive at.
12558            #[unsafe(method(canBecomeFocused))]
12559            fn can_become_focused(&self) -> bool {
12560                KEY_NODES.with(|t| t.contains(ptr_of(self)))
12561            }
12562
12563            #[unsafe(method(didUpdateFocusInContext:withAnimationCoordinator:))]
12564            fn did_update_focus(&self, context: &AnyObject, coordinator: &AnyObject) {
12565                unsafe {
12566                    let _: () = msg_send![super(self), didUpdateFocusInContext: context, withAnimationCoordinator: coordinator];
12567                }
12568                let next: Option<Retained<AnyObject>> = unsafe { msg_send![context, nextFocusedItem] };
12569                let this: &AnyObject = self.as_ref();
12570                if next.is_some_and(|n| std::ptr::eq(&raw const *n, this)) && !self.isFirstResponder() {
12571                    let _ = self.becomeFirstResponder();
12572                }
12573            }
12574
12575            #[unsafe(method(pressesEnded:withEvent:))]
12576            fn presses_ended(
12577                &self,
12578                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12579                event: Option<&objc2_ui_kit::UIPressesEvent>,
12580            ) {
12581                let rest = release_keys(self, presses);
12582                if rest.len() == presses.len() {
12583                    let _: () = unsafe { msg_send![super(self), pressesEnded: presses, withEvent: event] };
12584                } else if !rest.is_empty() {
12585                    let rest = objc2_foundation::NSSet::from_retained_slice(&rest);
12586                    let _: () = unsafe { msg_send![super(self), pressesEnded: &*rest, withEvent: event] };
12587                }
12588            }
12589
12590            #[unsafe(method(pressesCancelled:withEvent:))]
12591            fn presses_cancelled(
12592                &self,
12593                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12594                event: Option<&objc2_ui_kit::UIPressesEvent>,
12595            ) {
12596                let rest = release_keys(self, presses);
12597                if rest.len() == presses.len() {
12598                    let _: () = unsafe { msg_send![super(self), pressesCancelled: presses, withEvent: event] };
12599                } else if !rest.is_empty() {
12600                    let rest = objc2_foundation::NSSet::from_retained_slice(&rest);
12601                    let _: () = unsafe { msg_send![super(self), pressesCancelled: &*rest, withEvent: event] };
12602                }
12603            }
12604
12605            // A touch focuses the canvas, the way a press does on the desktops. The gesture
12606            // recognizers still see it: this runs before `super`, which forwards to them.
12607            #[unsafe(method(touchesBegan:withEvent:))]
12608            fn touches_began(
12609                &self,
12610                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12611                event: Option<&objc2_ui_kit::UIEvent>,
12612            ) {
12613                if self.canBecomeFirstResponder() && !self.isFirstResponder() {
12614                    let _ = self.becomeFirstResponder();
12615                }
12616                let _: () = unsafe { msg_send![super(self), touchesBegan: touches, withEvent: event] };
12617            }
12618
12619            /// Hardware-keyboard presses while this canvas is first responder. Anything that is
12620            /// not a claimed arrow goes to `super`, which walks the responder chain exactly as
12621            /// it would have — so a key nobody wanted still reaches whatever else wants it.
12622            #[unsafe(method(pressesBegan:withEvent:))]
12623            fn presses_began(
12624                &self,
12625                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12626                event: Option<&objc2_ui_kit::UIPressesEvent>,
12627            ) {
12628                let ptr = std::ptr::from_ref::<DayFocusableContainer>(self).cast::<UIView>() as usize;
12629                let handled = day_spec::ffi_guard::contain(false, || {
12630                    let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
12631                        return false;
12632                    };
12633                    if !day_spec::keys::handled(node) {
12634                        return false;
12635                    }
12636                    let mut any = false;
12637                    for press in presses {
12638                        let Some(key) = (unsafe { press.key(self.mtm()) }) else {
12639                            continue;
12640                        };
12641                        let Some(name) = key_name(&key) else {
12642                            continue;
12643                        };
12644                        emit(
12645                            node,
12646                            Event::Key(day_spec::KeyEvent::named(
12647                                name,
12648                                key_modifiers(unsafe { key.modifierFlags() }),
12649                            )),
12650                        );
12651                        hold_key(ptr, HeldKey {
12652                            code: unsafe { key.keyCode() }.0,
12653                            name: name.to_owned(),
12654                            text: false,
12655                            inserts: 0,
12656                        });
12657                        any = true;
12658                    }
12659                    any
12660                });
12661                if !handled {
12662                    let _: () =
12663                        unsafe { msg_send![super(self), pressesBegan: presses, withEvent: event] };
12664                }
12665            }
12666        }
12667    );
12668    impl DayFocusableContainer {
12669        fn new(mtm: MainThreadMarker) -> Retained<Self> {
12670            let this = Self::alloc(mtm).set_ivars(());
12671            unsafe { msg_send![super(this), init] }
12672        }
12673    }
12674
12675    define_class!(
12676        /// A container whose fill is a gradient (docs/surfaces.md): the same view, backed
12677        /// by a `CAGradientLayer` instead of a plain layer. The gradient being the view's OWN
12678        /// layer is what keeps it the size of the view through every frame change and
12679        /// animation, under the subviews, and shaped by the layer's corners and border.
12680        #[unsafe(super(DayFocusableContainer))]
12681        #[thread_kind = MainThreadOnly]
12682        #[name = "DayGradientContainer"]
12683        #[ivars = ()]
12684        struct DayGradientContainer;
12685        impl DayGradientContainer {
12686            #[unsafe(method(layerClass))]
12687            fn layer_class() -> &'static objc2::runtime::AnyClass {
12688                <objc2_quartz_core::CAGradientLayer as objc2::ClassType>::class()
12689            }
12690        }
12691    );
12692    impl DayGradientContainer {
12693        fn new(mtm: MainThreadMarker) -> Retained<Self> {
12694            let this = Self::alloc(mtm).set_ivars(());
12695            unsafe { msg_send![super(this), init] }
12696        }
12697    }
12698
12699    struct CanvasIvars;
12700
12701    define_class!(
12702        #[unsafe(super(UIView))]
12703        #[thread_kind = MainThreadOnly]
12704        #[name = "DayCanvasView"]
12705        #[ivars = CanvasIvars]
12706        struct DayCanvasView;
12707
12708        impl DayCanvasView {
12709            #[unsafe(method(drawRect:))]
12710            fn draw_rect(&self, _dirty: CGRect) {
12711                let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12712                let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
12713                paint_ops(&ops);
12714            }
12715
12716            // Focus, and with it a hardware keyboard's arrows (docs/menus.md, docs/focus.md).
12717            // A plain UIView is never first responder, so nothing an app DRAWS could hear a
12718            // key. Focus on iOS is also the software keyboard — but a canvas has no text input
12719            // to raise one, so becoming first responder here costs nothing on a touch-only
12720            // device and buys the arrows on iPad with a keyboard attached.
12721            #[unsafe(method(canBecomeFirstResponder))]
12722            fn can_become_first_responder(&self) -> bool {
12723                true
12724            }
12725
12726            // The soft keyboard (docs/menus.md "The full route"). UIKit raises it for a first
12727            // responder that adopts `UIKeyInput`, and asks the responder itself whether it
12728            // does: a canvas that took the whole keyboard answers yes, every other canvas
12729            // answers as a plain view, so a drawing app's canvas never raises a keyboard it
12730            // cannot use. The traits say "raw text": no autocorrection, no capitalization,
12731            // no smart punctuation — a terminal gets exactly what was typed. `UIKeyInput`
12732            // alone has no marked text, so the keyboard type is ASCII-capable: the keyboards
12733            // that type a character per key. A multistage input method (Chinese, Japanese)
12734            // needs the full `UITextInput` contract, which a canvas does not offer yet; the
12735            // docs say so.
12736            #[unsafe(method(conformsToProtocol:))]
12737            fn conforms_to_protocol(&self, protocol: &objc2::runtime::AnyProtocol) -> bool {
12738                let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12739                let takes_keyboard = KEY_NODES
12740                    .with(|t| t.get(ptr))
12741                    .is_some_and(|node| day_spec::ffi_guard::contain(false, || day_spec::keys::text(node)));
12742                let adopted = matches!(
12743                    protocol.name().to_bytes(),
12744                    b"UIKeyInput" | b"UITextInputTraits"
12745                );
12746                // No early `return`: the method body is wrapped, and a `return` would hand
12747                // the wrapper a `bool` where it expects an ObjC `Bool`.
12748                if takes_keyboard && adopted {
12749                    true
12750                } else {
12751                    unsafe { msg_send![super(self), conformsToProtocol: protocol] }
12752                }
12753            }
12754
12755            #[unsafe(method(hasText))]
12756            fn has_text(&self) -> bool {
12757                true
12758            }
12759
12760            #[unsafe(method(insertText:))]
12761            fn insert_text(&self, text: &NSString) {
12762                let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12763                let text = text.to_string();
12764                if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12765                    day_spec::ffi_guard::contain((), || {
12766                        // The text of a held hardware key: the first insert is its down, every
12767                        // later one before the release a repeat (docs/menus.md "Keys").
12768                        let phase = KEYS_DOWN
12769                            .with(|t| {
12770                                t.with(ptr, |held| {
12771                                    held.iter_mut().rev().find(|k| k.text).map(|k| {
12772                                        k.inserts += 1;
12773                                        k.inserts > 1
12774                                    })
12775                                })
12776                            })
12777                            .flatten()
12778                            .map_or(day_spec::KeyPhase::Down, |repeat| {
12779                                if repeat {
12780                                    day_spec::KeyPhase::Repeat
12781                                } else {
12782                                    day_spec::KeyPhase::Down
12783                                }
12784                            });
12785                        emit_inserted_text(node, &text, phase);
12786                    });
12787                }
12788            }
12789
12790            #[unsafe(method(deleteBackward))]
12791            fn delete_backward(&self) {
12792                let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12793                if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12794                    day_spec::ffi_guard::contain((), || {
12795                        emit(node, Event::Key(day_spec::KeyEvent::named("Backspace", 0)));
12796                    });
12797                }
12798            }
12799
12800            #[unsafe(method(autocorrectionType))]
12801            fn autocorrection_type(&self) -> objc2_ui_kit::UITextAutocorrectionType {
12802                objc2_ui_kit::UITextAutocorrectionType::No
12803            }
12804
12805            #[unsafe(method(autocapitalizationType))]
12806            fn autocapitalization_type(&self) -> UITextAutocapitalizationType {
12807                UITextAutocapitalizationType::None
12808            }
12809
12810            #[unsafe(method(spellCheckingType))]
12811            fn spell_checking_type(&self) -> objc2_ui_kit::UITextSpellCheckingType {
12812                objc2_ui_kit::UITextSpellCheckingType::No
12813            }
12814
12815            #[unsafe(method(smartQuotesType))]
12816            fn smart_quotes_type(&self) -> objc2_ui_kit::UITextSmartQuotesType {
12817                objc2_ui_kit::UITextSmartQuotesType::No
12818            }
12819
12820            #[unsafe(method(smartDashesType))]
12821            fn smart_dashes_type(&self) -> objc2_ui_kit::UITextSmartDashesType {
12822                objc2_ui_kit::UITextSmartDashesType::No
12823            }
12824
12825            #[unsafe(method(smartInsertDeleteType))]
12826            fn smart_insert_delete_type(&self) -> objc2_ui_kit::UITextSmartInsertDeleteType {
12827                objc2_ui_kit::UITextSmartInsertDeleteType::No
12828            }
12829
12830            #[unsafe(method(keyboardType))]
12831            fn keyboard_type(&self) -> UIKeyboardType {
12832                UIKeyboardType::ASCIICapable
12833            }
12834
12835            #[unsafe(method(returnKeyType))]
12836            fn return_key_type(&self) -> UIReturnKeyType {
12837                UIReturnKeyType::Default
12838            }
12839
12840            #[unsafe(method(becomeFirstResponder))]
12841            fn become_first_responder(&self) -> bool {
12842                let became: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
12843                if became {
12844                    let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12845                    if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12846                        day_spec::ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
12847                    }
12848                }
12849                became
12850            }
12851
12852            #[unsafe(method(resignFirstResponder))]
12853            fn resign_first_responder(&self) -> bool {
12854                let resigned: bool = unsafe { msg_send![super(self), resignFirstResponder] };
12855                if resigned {
12856                    let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12857                    // A key held across the focus change sends no release (docs/menus.md "Keys").
12858                    KEYS_DOWN.with(|t| t.remove(ptr));
12859                    if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
12860                        day_spec::ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
12861                    }
12862                }
12863                resigned
12864            }
12865
12866            // A canvas that does nothing with a touch lets it through to the views beneath,
12867            // as a view with no touch handling does on Android and on the desktops. UIKit would
12868            // otherwise hand every touch inside the canvas to it: a shape drawn over controls,
12869            // such as a border stroked over an address bar, left the bar unable to take a tap.
12870            // A canvas keeps its touches when it has a gesture recognizer or an interaction
12871            // (Day's taps, drags, hovers and context menus) or a key handler, which a touch
12872            // focuses.
12873            #[unsafe(method_id(hitTest:withEvent:))]
12874            fn hit_test(
12875                &self,
12876                point: CGPoint,
12877                event: Option<&objc2_ui_kit::UIEvent>,
12878            ) -> Option<Retained<UIView>> {
12879                let view: &UIView = self;
12880                let keys = KEY_NODES.with(|t| t.get(ptr_of(view))).is_some_and(|node| {
12881                    day_spec::ffi_guard::contain(false, || day_spec::keys::handled(node))
12882                });
12883                day_hit_test(view, point, event, takes_touches(view, keys))
12884            }
12885
12886            #[unsafe(method(pointInside:withEvent:))]
12887            fn point_inside(&self, point: CGPoint, _event: Option<&objc2_ui_kit::UIEvent>) -> bool {
12888                day_point_inside(self, point)
12889            }
12890
12891            #[unsafe(method(pressesEnded:withEvent:))]
12892            fn presses_ended(
12893                &self,
12894                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12895                event: Option<&objc2_ui_kit::UIPressesEvent>,
12896            ) {
12897                let rest = release_keys(self, presses);
12898                if rest.len() == presses.len() {
12899                    let _: () = unsafe { msg_send![super(self), pressesEnded: presses, withEvent: event] };
12900                } else if !rest.is_empty() {
12901                    let rest = objc2_foundation::NSSet::from_retained_slice(&rest);
12902                    let _: () = unsafe { msg_send![super(self), pressesEnded: &*rest, withEvent: event] };
12903                }
12904            }
12905
12906            #[unsafe(method(pressesCancelled:withEvent:))]
12907            fn presses_cancelled(
12908                &self,
12909                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12910                event: Option<&objc2_ui_kit::UIPressesEvent>,
12911            ) {
12912                let rest = release_keys(self, presses);
12913                if rest.len() == presses.len() {
12914                    let _: () = unsafe { msg_send![super(self), pressesCancelled: presses, withEvent: event] };
12915                } else if !rest.is_empty() {
12916                    let rest = objc2_foundation::NSSet::from_retained_slice(&rest);
12917                    let _: () = unsafe { msg_send![super(self), pressesCancelled: &*rest, withEvent: event] };
12918                }
12919            }
12920
12921            // A touch focuses the canvas, the way a press does on the desktops. The gesture
12922            // recognizers still see it: this runs before `super`, which forwards to them.
12923            #[unsafe(method(touchesBegan:withEvent:))]
12924            fn touches_began(
12925                &self,
12926                touches: &objc2_foundation::NSSet<objc2_ui_kit::UITouch>,
12927                event: Option<&objc2_ui_kit::UIEvent>,
12928            ) {
12929                if !self.isFirstResponder() {
12930                    let _ = self.becomeFirstResponder();
12931                }
12932                let _: () = unsafe { msg_send![super(self), touchesBegan: touches, withEvent: event] };
12933            }
12934
12935            /// Hardware-keyboard presses while this canvas is first responder. Anything that is
12936            /// not a claimed arrow goes to `super`, which walks the responder chain exactly as
12937            /// it would have — so a key nobody wanted still reaches whatever else wants it.
12938            #[unsafe(method(pressesBegan:withEvent:))]
12939            fn presses_began(
12940                &self,
12941                presses: &objc2_foundation::NSSet<objc2_ui_kit::UIPress>,
12942                event: Option<&objc2_ui_kit::UIPressesEvent>,
12943            ) {
12944                let ptr = std::ptr::from_ref::<DayCanvasView>(self).cast::<UIView>() as usize;
12945                // The presses this canvas did not claim go to `super` together, so a text
12946                // press in the same set as a claimed arrow still reaches the text input
12947                // system, and a set nobody wanted walks the responder chain as before.
12948                let unclaimed: Vec<Retained<objc2_ui_kit::UIPress>> =
12949                    day_spec::ffi_guard::contain(Vec::new(), || {
12950                        let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
12951                            return presses.iter().map(|p| p.retain()).collect();
12952                        };
12953                        if !day_spec::keys::handled(node) {
12954                            return presses.iter().map(|p| p.retain()).collect();
12955                        }
12956                        let full = day_spec::keys::text(node);
12957                        let mut rest = Vec::new();
12958                        for press in presses {
12959                            let key = unsafe { press.key(self.mtm()) };
12960                            let claimed = match &key {
12961                                Some(key) if full => full_route_press(key),
12962                                Some(key) => key_name(key).map(|name| {
12963                                    day_spec::KeyEvent::named(
12964                                        name,
12965                                        key_modifiers(unsafe { key.modifierFlags() }),
12966                                    )
12967                                }),
12968                                None => None,
12969                            };
12970                            let Some(key) = key else {
12971                                rest.push(press.retain());
12972                                continue;
12973                            };
12974                            let code = unsafe { key.keyCode() }.0;
12975                            if let Some(event) = claimed {
12976                                hold_key(ptr, HeldKey {
12977                                    code,
12978                                    name: event.key.to_string(),
12979                                    text: false,
12980                                    inserts: 0,
12981                                });
12982                                emit(node, Event::Key(event));
12983                            } else {
12984                                // A key that types, on the full route: its text arrives
12985                                // through `insertText:`, its release here.
12986                                let typed = unsafe { key.charactersIgnoringModifiers() }.to_string();
12987                                if full && !typed.is_empty() && !typed.chars().any(char::is_control) {
12988                                    hold_key(ptr, HeldKey {
12989                                        code,
12990                                        name: typed,
12991                                        text: true,
12992                                        inserts: 0,
12993                                    });
12994                                }
12995                                rest.push(press.retain());
12996                            }
12997                        }
12998                        rest
12999                    });
13000                if unclaimed.len() == presses.len() {
13001                    let _: () =
13002                        unsafe { msg_send![super(self), pressesBegan: presses, withEvent: event] };
13003                } else if !unclaimed.is_empty() {
13004                    let rest = objc2_foundation::NSSet::from_retained_slice(&unclaimed);
13005                    let _: () =
13006                        unsafe { msg_send![super(self), pressesBegan: &*rest, withEvent: event] };
13007                }
13008            }
13009        }
13010    );
13011
13012    impl DayCanvasView {
13013        fn new(mtm: MainThreadMarker) -> Retained<Self> {
13014            let this = Self::alloc(mtm).set_ivars(CanvasIvars);
13015            let v: Retained<Self> = unsafe { msg_send![super(this), init] };
13016            unsafe {
13017                v.setBackgroundColor(Some(&UIColor::clearColor()));
13018                v.setOpaque(false);
13019            }
13020            v
13021        }
13022    }
13023
13024    /// The text a widget displays, for `read_native`: a label's or text field's string, a
13025    /// button's title, a text area's contents. `None` for a secure field (it masks its text),
13026    /// an icon-only button (its title is empty, the name rides the accessibility label), and
13027    /// every other view.
13028    fn native_text(h: &UIView) -> Option<String> {
13029        if let Some(label) = h.downcast_ref::<UILabel>() {
13030            return Some(unsafe { label.text() }.map_or_default(|s| s.to_string()));
13031        }
13032        if let Some(tf) = h.downcast_ref::<UITextField>() {
13033            if unsafe { is_secure_text_entry(tf) } {
13034                return None;
13035            }
13036            return Some(unsafe { tf.text() }.map_or_default(|s| s.to_string()));
13037        }
13038        // A text area, or a label with links or `.selectable()` (both read-only text views).
13039        if let Some(tv) = h.downcast_ref::<UITextView>() {
13040            return Some(unsafe { tv.text() }.to_string());
13041        }
13042        let btn = h.downcast_ref::<UIButton>()?;
13043        // A configured button titles through its configuration (`apply_button_style`), and
13044        // falls back to the state title when that is empty, as UIKit draws it.
13045        let title = unsafe {
13046            btn.configuration()
13047                .and_then(|config| config.title())
13048                .filter(|t| !t.is_empty())
13049                .or_else(|| btn.currentTitle())
13050        }
13051        .map_or_default(|s| s.to_string());
13052        (!title.is_empty()).then_some(title)
13053    }
13054
13055    /// A slider's value or a progress bar's fraction, for `read_native`. The slider is built
13056    /// with Day's min and max and the bar runs 0–1, so both are already in Day's range; the
13057    /// `f32` goes through its shortest decimal so 0.1 reads back as 0.1, not 0.10000000149.
13058    fn native_number(h: &UIView) -> Option<f64> {
13059        let v = if let Some(sl) = h.downcast_ref::<UISlider>() {
13060            unsafe { sl.value() }
13061        } else {
13062            unsafe { h.downcast_ref::<UIProgressView>()?.progress() }
13063        };
13064        v.to_string().parse().ok()
13065    }
13066
13067    /// Shown: in a window, and neither the view nor any superview hidden.
13068    fn native_visible(h: &UIView) -> bool {
13069        if h.window().is_none() {
13070            return false;
13071        }
13072        let mut view: Option<Retained<UIView>> = Some(Retained::from(h));
13073        while let Some(v) = view {
13074            if v.isHidden() {
13075                return false;
13076            }
13077            view = v.superview();
13078        }
13079        true
13080    }
13081
13082    /// The view's frame in its window's coordinates (origin top left, points), for
13083    /// `read_native`.
13084    fn native_frame(h: &UIView) -> Option<Rect> {
13085        h.window()?;
13086        let r = h.convertRect_toView(h.bounds(), None);
13087        Some(Rect::new(
13088            r.origin.x,
13089            r.origin.y,
13090            r.size.width,
13091            r.size.height,
13092        ))
13093    }
13094
13095    fn apply_button_content(
13096        btn: &UIButton,
13097        title: &str,
13098        icon: Option<&day_spec::Icon>,
13099        icon_only: bool,
13100    ) {
13101        let image = menu_image(icon).map(|image| {
13102            let image = if matches!(icon, Some(day_spec::Icon::Image(_))) {
13103                image
13104                    .imageByPreparingThumbnailOfSize(CGSize::new(20.0, 20.0))
13105                    .unwrap_or(image)
13106            } else {
13107                image
13108            };
13109            image.imageWithRenderingMode(objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate)
13110        });
13111        let visible_title = if icon_only && image.is_some() {
13112            ""
13113        } else {
13114            title
13115        };
13116        unsafe {
13117            // A configuration with an empty title can fall back to the legacy state title.
13118            // Clear that title before installing content, particularly for icon-only controls.
13119            btn.setTitle_forState(None, UIControlState::Normal);
13120            {
13121                let config = btn.configuration().unwrap_or_else(|| {
13122                    objc2_ui_kit::UIButtonConfiguration::plainButtonConfiguration(btn.mtm())
13123                });
13124                config.setTitle(Some(&NSString::from_str(visible_title)));
13125                config.setImage(image.as_deref());
13126                config.setImagePadding(if icon_only { 0.0 } else { 6.0 });
13127                btn.setConfiguration(Some(&config));
13128            }
13129            // The title is the spoken name, unless the app named the button itself; overwriting
13130            // that here replaced app labels on every title change.
13131            if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
13132                btn.setAccessibilityLabel(Some(&NSString::from_str(title)), btn.mtm());
13133            }
13134        }
13135        BUTTON_CONTENT.with(|m| {
13136            m.insert(
13137                ptr_of(btn),
13138                day_spec::props::ButtonContent {
13139                    title: title.into(),
13140                    icon: icon.cloned(),
13141                    icon_only,
13142                },
13143            );
13144        });
13145    }
13146
13147    thread_local! {
13148        /// Each button's style, keyed by its view pointer, so deselecting a button
13149        /// (`set_button_selected`) can give it its own look back.
13150        static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
13151            RefCell::new(HashMap::new());
13152    }
13153
13154    /// Put `ButtonProps::selected` on a `UIButton`. `isSelected` is the control's own state, from
13155    /// which VoiceOver adds the selected trait; the look is the system's tinted configuration,
13156    /// the treatment iOS gives a chosen filter chip, and deselecting restores the button's own
13157    /// style. A touch never toggles `isSelected`, so nothing has to be put back after a press.
13158    fn set_button_selected(btn: &UIButton, on: bool, mtm: MainThreadMarker) {
13159        unsafe {
13160            btn.setSelected(on);
13161            let title = btn
13162                .configuration()
13163                .and_then(|c| c.title())
13164                .or_else(|| btn.titleForState(UIControlState::Normal))
13165                .map_or_default(|s| s.to_string());
13166            if on {
13167                let config = objc2_ui_kit::UIButtonConfiguration::tintedButtonConfiguration(mtm);
13168                config.setTitle(Some(&NSString::from_str(&title)));
13169                btn.setConfiguration(Some(&config));
13170            } else {
13171                let style = BUTTON_STYLES
13172                    .with(|m| m.borrow().get(&ptr_of(btn)).copied())
13173                    .unwrap_or_default();
13174                apply_button_style(btn, &title, style, mtm);
13175            }
13176        }
13177    }
13178
13179    /// Put a [`day_spec::props::ButtonStyleSpec`] on a `UIButton`, keeping it a `UIButton`.
13180    ///
13181    /// Bordered / Prominent map to `UIButtonConfiguration` tiers (iOS 15+) — the plain system
13182    /// button reads as a LINK, not a button. A tint is the FILLED configuration with
13183    /// `baseBackgroundColor`, so UIKit still draws the press dimming, the disabled state and the
13184    /// focus/pointer effects itself.
13185    ///
13186    /// A configured button takes its title from the configuration, so the title is set on
13187    /// whichever path this takes.
13188    fn apply_button_style(
13189        btn: &UIButton,
13190        title: &str,
13191        style: day_spec::props::ButtonStyleSpec,
13192        mtm: MainThreadMarker,
13193    ) {
13194        use day_spec::props::ButtonStyleSpec as S;
13195        use objc2_ui_kit::UIButtonConfiguration;
13196        BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
13197        unsafe {
13198            let config = match style {
13199                // The plain system button hugs its title already, so Compact is Automatic.
13200                S::Automatic | S::Compact | S::Plain => {
13201                    btn.setConfiguration(None);
13202                    btn.setTitle_forState(Some(&NSString::from_str(title)), UIControlState::Normal);
13203                    return;
13204                }
13205                S::Prominent => UIButtonConfiguration::borderedProminentButtonConfiguration(mtm),
13206                S::Bordered => UIButtonConfiguration::borderedButtonConfiguration(mtm),
13207                S::Tinted(c) => {
13208                    let config = UIButtonConfiguration::filledButtonConfiguration(mtm);
13209                    config.setBaseBackgroundColor(Some(&uiink(c)));
13210                    config.setBaseForegroundColor(Some(&uiink_mapped(c, S::on_tint)));
13211                    config
13212                }
13213            };
13214            config.setTitle(Some(&NSString::from_str(title)));
13215            btn.setConfiguration(Some(&config));
13216        }
13217    }
13218
13219    fn uicolor(c: day_spec::Color) -> Retained<UIColor> {
13220        unsafe { UIColor::colorWithRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
13221    }
13222
13223    /// A `CGColor` for the layer properties and context calls that take one.
13224    fn cgcolor(c: day_spec::Color) -> Retained<objc2_core_graphics::CGColor> {
13225        // SAFETY: reading the color of a `UIColor` made from plain components.
13226        unsafe { uicolor(c).CGColor() }
13227    }
13228
13229    /// The `UIColor` an ink is drawn in (docs/color.md): a fixed ink is a plain color; a
13230    /// light/dark pair and a role are dynamic colors, which UIKit resolves against the trait
13231    /// collection of wherever they are shown. A view given one recolors on an appearance switch
13232    /// by itself, with no patch: a background, a text color, a tint, an attributed-string
13233    /// color and a button configuration's colors all re-resolve. A layer color (`CGColor`)
13234    /// does not, so those are re-resolved on a trait change (`refresh_surface_inks`).
13235    ///
13236    /// A role's alpha override replaces the alpha, as `withAlphaComponent` does.
13237    ///
13238    /// Public for pieces with a native view of their own (an attributed string's colors, a
13239    /// text view's): a color from here follows a light/dark switch with nothing re-applied.
13240    #[must_use]
13241    pub fn uiink(ink: day_spec::Ink) -> Retained<UIColor> {
13242        use day_spec::Ink;
13243        match ink {
13244            Ink::Fixed(c) => uicolor(c),
13245            Ink::Adaptive { light, dark } => dynamic_uicolor(move |traits| {
13246                uicolor(if traits_dark(traits) { dark } else { light })
13247            }),
13248            Ink::System { role, alpha: None } => role_uicolor(role),
13249            Ink::System {
13250                role,
13251                alpha: Some(alpha),
13252            } => {
13253                let base = role_uicolor(role);
13254                dynamic_uicolor(move |traits| {
13255                    base.resolvedColorWithTraitCollection(traits)
13256                        .colorWithAlphaComponent(alpha.clamp(0.0, 1.0))
13257                })
13258            }
13259        }
13260    }
13261
13262    /// A dynamic color: `provider` picks the color for each trait collection UIKit resolves
13263    /// it against (iOS 13+).
13264    fn dynamic_uicolor(
13265        provider: impl Fn(&objc2_ui_kit::UITraitCollection) -> Retained<UIColor> + 'static,
13266    ) -> Retained<UIColor> {
13267        let block = block2::RcBlock::new(
13268            move |traits: NonNull<objc2_ui_kit::UITraitCollection>| -> NonNull<UIColor> {
13269                // SAFETY: UIKit passes a live trait collection for the duration of the call.
13270                let color = provider(unsafe { traits.as_ref() });
13271                // A block's object return is +0 by convention: hand back an autoreleased
13272                // pointer, which a `Retained` never makes null.
13273                let ptr = Retained::autorelease_ptr(color);
13274                // SAFETY: `autorelease_ptr` returns the retained object's own, non-null pointer.
13275                unsafe { NonNull::new_unchecked(ptr) }
13276            },
13277        );
13278        // SAFETY: the provider returns a valid, autoreleased color for every call.
13279        unsafe { UIColor::colorWithDynamicProvider(&block) }
13280    }
13281
13282    /// Whether `traits` describe the dark appearance. High contrast keeps its light or dark
13283    /// side, as the system's own colors do.
13284    fn traits_dark(traits: &objc2_ui_kit::UITraitCollection) -> bool {
13285        // SAFETY: reading a property of a live trait collection.
13286        let style = unsafe { traits.userInterfaceStyle() };
13287        style == objc2_ui_kit::UIUserInterfaceStyle::Dark
13288    }
13289
13290    /// The platform color for a role (color brief §1.4), dynamic as UIKit's own system
13291    /// colors are. What `Toolkit::system_color` answers too, resolved, so a role shows exactly
13292    /// what `day::resolve` returns for it.
13293    fn role_uicolor(role: day_spec::SystemColor) -> Retained<UIColor> {
13294        use day_spec::SystemColor as R;
13295        match role {
13296            R::Accent => UIColor::systemBlueColor(),
13297            R::Text => UIColor::labelColor(),
13298            R::SecondaryText => UIColor::secondaryLabelColor(),
13299            R::TertiaryText => UIColor::tertiaryLabelColor(),
13300            R::Placeholder => UIColor::placeholderTextColor(),
13301            R::Link => UIColor::linkColor(),
13302            R::Separator => UIColor::separatorColor(),
13303            R::ControlFill => UIColor::tertiarySystemFillColor(),
13304            R::Background => UIColor::systemBackgroundColor(),
13305            R::Surface => UIColor::secondarySystemBackgroundColor(),
13306            R::GroupedBackground => UIColor::systemGroupedBackgroundColor(),
13307            // The background a raised surface takes (a sheet, a popover): the system
13308            // background in the ELEVATED interface level, which is lighter in the dark
13309            // appearance and the same white in the light one.
13310            R::ElevatedSurface => dynamic_uicolor(|traits| {
13311                let elevated =
13312                    objc2_ui_kit::UITraitCollection::traitCollectionWithUserInterfaceLevel(
13313                        objc2_ui_kit::UIUserInterfaceLevel::Elevated,
13314                    );
13315                #[expect(
13316                    deprecated,
13317                    reason = "its iOS 17 replacement, traitCollectionByModifyingTraits, is not on the iOS 15 floor"
13318                )]
13319                let merged =
13320                    objc2_ui_kit::UITraitCollection::traitCollectionWithTraitsFromCollections(
13321                        &objc2_foundation::NSArray::from_slice(&[traits, &*elevated]),
13322                    );
13323                UIColor::systemBackgroundColor().resolvedColorWithTraitCollection(&merged)
13324            }),
13325            // The accent at a fifth: what UIKit's own text selection highlight is.
13326            R::Selection => dynamic_uicolor(|traits| {
13327                UIColor::systemBlueColor()
13328                    .resolvedColorWithTraitCollection(traits)
13329                    .colorWithAlphaComponent(0.2)
13330            }),
13331            R::Destructive => UIColor::systemRedColor(),
13332            R::Success => UIColor::systemGreenColor(),
13333            R::Warning => UIColor::systemOrangeColor(),
13334        }
13335    }
13336
13337    /// The sRGB components of a color that is already resolved (not dynamic).
13338    fn uicolor_components(color: &UIColor) -> Option<day_spec::Color> {
13339        let (mut r, mut g, mut b, mut a) = (0.0, 0.0, 0.0, 0.0);
13340        // SAFETY: each out pointer refers to a live CGFloat on this stack.
13341        unsafe { color.getRed_green_blue_alpha(&raw mut r, &raw mut g, &raw mut b, &raw mut a) }
13342            .then(|| day_spec::Color::rgba(r, g, b, a))
13343    }
13344
13345    /// `ink` resolved for the appearance `view` is shown in: its own trait collection, which
13346    /// carries a per-window override.
13347    fn ink_in(view: &UIView, ink: day_spec::Ink) -> Retained<UIColor> {
13348        use objc2_ui_kit::UITraitEnvironment as _;
13349        uiink(ink).resolvedColorWithTraitCollection(&view.traitCollection())
13350    }
13351
13352    /// `ink` resolved for `view` as a `CGColor`, for a layer property: Core Animation keeps the
13353    /// value, so a trait change has to set it again (`refresh_surface_inks`).
13354    pub(crate) fn ink_cg(
13355        view: &UIView,
13356        ink: day_spec::Ink,
13357    ) -> Retained<objc2_core_graphics::CGColor> {
13358        // SAFETY: reading the CGColor of a resolved (non-dynamic) color.
13359        unsafe { ink_in(view, ink).CGColor() }
13360    }
13361
13362    /// A dynamic color `f` derives from `ink` in each appearance: the readable title on a
13363    /// tinted fill (`ButtonStyleSpec::on_tint`).
13364    fn uiink_mapped(
13365        ink: day_spec::Ink,
13366        f: fn(day_spec::Color) -> day_spec::Color,
13367    ) -> Retained<UIColor> {
13368        if let Some(c) = ink.fixed() {
13369            return uicolor(f(c));
13370        }
13371        let base = uiink(ink);
13372        dynamic_uicolor(move |traits| {
13373            let shown = base.resolvedColorWithTraitCollection(traits);
13374            uicolor(f(
13375                uicolor_components(&shown).unwrap_or(day_spec::Color::BLACK)
13376            ))
13377        })
13378    }
13379
13380    /// What a surface keeps after `apply_surface` (`SURFACES`): its props, for the layer
13381    /// colors a trait change re-resolves and the conic direction a resize re-places, and the
13382    /// gradient sublayer of a plain container whose fill became a gradient after realize.
13383    struct SurfaceState {
13384        props: ContainerProps,
13385        fill_layer: Option<Retained<objc2_quartz_core::CAGradientLayer>>,
13386    }
13387
13388    /// Apply a container's surface (docs/surfaces.md) to its view, all of it on the view's own
13389    /// `CALayer`: the fill is `backgroundColor` (a dynamic color for an ink that follows the
13390    /// appearance), or a gradient: the view's own layer when it is a `CAGradientLayer`
13391    /// (`DayGradientContainer`, chosen at realize), else a gradient sublayer under the
13392    /// subviews for a container whose fill became a gradient later. The rounding is
13393    /// `cornerRadius` on the `maskedCorners` selection; the border is the layer's, which Core
13394    /// Animation draws inside the bounds along those corners and OVER the sublayers, so over
13395    /// the content; the shadow is the layer's, cast from a path of the same rounded rectangle
13396    /// (`sync_surface_shadow_path`).
13397    ///
13398    /// Idempotent: realize runs it, and so does every `ContainerPatch::Surface`, so a radius
13399    /// going from 0 to 12 starts clipping and a border or shadow that goes away is cleared.
13400    fn apply_surface(v: &UIView, p: &ContainerProps) {
13401        let layer = v.layer();
13402        let key = ptr_of(v);
13403        let mut fill_layer = SURFACES.with(|t| t.take(key)).and_then(|s| s.fill_layer);
13404        set_fill(v, p.fill.as_ref(), &mut fill_layer);
13405        let radius = p.corner_radius.max(0.0);
13406        layer.setCornerRadius(radius);
13407        layer.setMaskedCorners(corner_mask(p.corners));
13408        layer.setBorderWidth(p.border.map_or(0.0, |b| b.width.max(0.0)));
13409        if let Some(shadow) = p.shadow {
13410            // `shadowRadius` is the Gaussian's standard deviation, half of the CSS blur radius
13411            // `Shadow::blur` is. The color and its alpha (`shadowOpacity`) are set with the
13412            // other layer colors below.
13413            layer.setShadowRadius((shadow.blur / 2.0).max(0.0));
13414            layer.setShadowOffset(CGSize::new(shadow.dx, shadow.dy));
13415            // A mask would cut the shadow off with everything else outside the bounds. The
13416            // fill, the gradient and the border follow the corners without one.
13417            layer.setMasksToBounds(false);
13418        } else {
13419            layer.setShadowOpacity(0.0);
13420            layer.setShadowPath(None);
13421            layer.setMasksToBounds(p.clips || radius > 0.0);
13422        }
13423        let state = SurfaceState {
13424            props: p.clone(),
13425            fill_layer,
13426        };
13427        apply_surface_inks(v, &state);
13428        sync_fill_layer(v, &state);
13429        sync_surface_shadow_path(v);
13430        if state.fill_layer.is_some() || surface_tracked(p) {
13431            SURFACES.with(|t| t.insert(key, state));
13432        }
13433    }
13434
13435    /// Whether a surface keeps its props after `apply_surface`: it holds a layer color from an
13436    /// ink that follows the appearance (re-resolved on a trait change), or a gradient (its
13437    /// colors re-resolved, a conic one's direction re-placed on a resize).
13438    fn surface_tracked(p: &ContainerProps) -> bool {
13439        p.fill
13440            .as_ref()
13441            .is_some_and(|f| !matches!(f, day_spec::Paint::Solid(_)))
13442            || p.border.is_some_and(|b| b.color.is_dynamic())
13443            || p.shadow.is_some_and(|s| s.color.is_dynamic())
13444    }
13445
13446    /// The layer's corner selection for Day's.
13447    fn corner_mask(corners: day_spec::Corners) -> objc2_quartz_core::CACornerMask {
13448        use day_spec::Corners as C;
13449        use objc2_quartz_core::CACornerMask;
13450        let mut mask = CACornerMask::empty();
13451        for (corner, bit) in [
13452            (C::TOP_LEFT, CACornerMask::LayerMinXMinYCorner),
13453            (C::TOP_RIGHT, CACornerMask::LayerMaxXMinYCorner),
13454            (C::BOTTOM_LEFT, CACornerMask::LayerMinXMaxYCorner),
13455            (C::BOTTOM_RIGHT, CACornerMask::LayerMaxXMaxYCorner),
13456        ] {
13457            if corners.contains(corner) {
13458                mask |= bit;
13459            }
13460        }
13461        mask
13462    }
13463
13464    /// Put a container's fill on its view: a solid ink as the background color (dynamic for an
13465    /// ink that follows the appearance), nothing as no background, a gradient on the view's
13466    /// own `CAGradientLayer` or on a gradient sublayer made for it. Whichever is not in use is
13467    /// cleared, so a color never shows through a gradient's translucent stops. The gradient's
13468    /// geometry and colors are `apply_surface_inks`'s.
13469    fn set_fill(
13470        v: &UIView,
13471        fill: Option<&day_spec::Paint>,
13472        fill_layer: &mut Option<Retained<objc2_quartz_core::CAGradientLayer>>,
13473    ) {
13474        use objc2_quartz_core::CAGradientLayer;
13475        let layer = v.layer();
13476        let own = layer.downcast_ref::<CAGradientLayer>();
13477        match fill {
13478            Some(day_spec::Paint::Solid(_)) | None => {
13479                if let Some(own) = own {
13480                    // SAFETY: nil is a valid value for `colors`, and draws no gradient.
13481                    unsafe { own.setColors(None) };
13482                }
13483                if let Some(old) = fill_layer.take() {
13484                    old.removeFromSuperlayer();
13485                }
13486                let color = match fill {
13487                    Some(day_spec::Paint::Solid(ink)) => Some(uiink(*ink)),
13488                    _ => None,
13489                };
13490                // SAFETY: setting a view property on the main thread.
13491                unsafe { v.setBackgroundColor(color.as_deref()) };
13492            }
13493            Some(_) => {
13494                // SAFETY: setting a view property on the main thread.
13495                unsafe { v.setBackgroundColor(None) };
13496                if own.is_none() && fill_layer.is_none() {
13497                    let sub = CAGradientLayer::new();
13498                    sub.setName(Some(&NSString::from_str("day.fill")));
13499                    without_actions(|| layer.insertSublayer_atIndex(&sub, 0));
13500                    *fill_layer = Some(sub);
13501                }
13502            }
13503        }
13504    }
13505
13506    /// `ContainerPatch::Fill`: change the fill alone, keeping the rest of the surface as it is.
13507    fn patch_fill(v: &UIView, fill: Option<&day_spec::Paint>) {
13508        let key = ptr_of(v);
13509        let (props, mut fill_layer) = SURFACES.with(|t| t.take(key)).map_or_else(
13510            || (ContainerProps::default(), None),
13511            |s| (s.props, s.fill_layer),
13512        );
13513        set_fill(v, fill, &mut fill_layer);
13514        let state = SurfaceState {
13515            props: ContainerProps {
13516                fill: fill.cloned(),
13517                ..props
13518            },
13519            fill_layer,
13520        };
13521        apply_surface_inks(v, &state);
13522        sync_fill_layer(v, &state);
13523        if state.fill_layer.is_some() || surface_tracked(&state.props) {
13524            SURFACES.with(|t| t.insert(key, state));
13525        }
13526    }
13527
13528    /// Run `f` with Core Animation's implicit actions off: a standalone sublayer animates every
13529    /// property change for a quarter second otherwise.
13530    fn without_actions(f: impl FnOnce()) {
13531        objc2_quartz_core::CATransaction::begin();
13532        objc2_quartz_core::CATransaction::setDisableActions(true);
13533        f();
13534        objc2_quartz_core::CATransaction::commit();
13535    }
13536
13537    /// Set the surface's layer colors from its inks, resolved for the appearance the view is
13538    /// shown in: the border color, the shadow's color and opacity, and the gradient (its
13539    /// colors, and the geometry with them). Core Animation keeps a `CGColor`, which does not
13540    /// follow the appearance, so `refresh_surface_inks` runs this again on a trait change.
13541    fn apply_surface_inks(v: &UIView, state: &SurfaceState) {
13542        use objc2_quartz_core::CAGradientLayer;
13543        let layer = v.layer();
13544        let p = &state.props;
13545        if let Some(border) = p.border {
13546            layer.setBorderColor(Some(&ink_cg(v, border.color)));
13547        }
13548        if let Some(shadow) = p.shadow {
13549            // The color's alpha rides `shadowOpacity`.
13550            let c = uicolor_components(&ink_in(v, shadow.color)).unwrap_or(day_spec::Color::BLACK);
13551            layer.setShadowColor(Some(&cgcolor(day_spec::Color::rgba(c.r, c.g, c.b, 1.0))));
13552            #[expect(
13553                clippy::cast_possible_truncation,
13554                reason = "an opacity in 0..=1 narrows to the f32 Core Animation takes"
13555            )]
13556            layer.setShadowOpacity(c.a.clamp(0.0, 1.0) as f32);
13557        }
13558        let Some(paint) = p.fill.as_ref() else {
13559            return;
13560        };
13561        if let Some(own) = layer.downcast_ref::<CAGradientLayer>() {
13562            set_gradient(v, own, paint);
13563        } else if let Some(sub) = &state.fill_layer {
13564            without_actions(|| set_gradient(v, sub, paint));
13565        }
13566    }
13567
13568    /// Put a gradient paint on a `CAGradientLayer` (`surface_fill::layout`), its stops resolved
13569    /// for `v`'s appearance and its geometry for `v`'s size. A solid paint clears it.
13570    fn set_gradient(v: &UIView, gl: &objc2_quartz_core::CAGradientLayer, paint: &day_spec::Paint) {
13571        use crate::surface_fill::{Kind, layout};
13572        let size = v.bounds().size;
13573        let Some(l) = layout(paint, (size.width, size.height), |ink| {
13574            uicolor_components(&ink_in(v, ink)).unwrap_or(day_spec::Color::CLEAR)
13575        }) else {
13576            // SAFETY: nil is a valid value for `colors`, and draws no gradient.
13577            unsafe { gl.setColors(None) };
13578            return;
13579        };
13580        // SAFETY: the type constants are framework statics, valid for the process lifetime.
13581        let kind = unsafe {
13582            match l.kind {
13583                Kind::Axial => objc2_quartz_core::kCAGradientLayerAxial,
13584                Kind::Radial => objc2_quartz_core::kCAGradientLayerRadial,
13585                Kind::Conic => objc2_quartz_core::kCAGradientLayerConic,
13586            }
13587        };
13588        gl.setType(kind);
13589        let colors: Vec<_> = l.stops.iter().map(|&(_, c)| cgcolor(c)).collect();
13590        // SAFETY: `CGColor` is a Core Foundation type that is toll-free usable as an
13591        // Objective-C object, which is how `CAGradientLayer.colors` is documented to take it;
13592        // the array retains each one.
13593        let objects: Vec<&AnyObject> = colors
13594            .iter()
13595            .map(|c| unsafe {
13596                &*std::ptr::from_ref::<objc2_core_graphics::CGColor>(c).cast::<AnyObject>()
13597            })
13598            .collect();
13599        let locations: Vec<_> = l
13600            .stops
13601            .iter()
13602            .map(|&(at, _)| objc2_foundation::NSNumber::new_f64(at))
13603            .collect();
13604        // SAFETY: the array holds CGColors, the element type the property expects.
13605        unsafe { gl.setColors(Some(&objc2_foundation::NSArray::from_slice(&objects))) };
13606        gl.setLocations(Some(&objc2_foundation::NSArray::from_retained_slice(
13607            &locations,
13608        )));
13609        // Layer unit space has its origin at the top left on iOS, like `UnitPoint`.
13610        gl.setStartPoint(CGPoint::new(l.start.0, l.start.1));
13611        gl.setEndPoint(CGPoint::new(l.end.0, l.end.1));
13612    }
13613
13614    /// Keep a gradient sublayer the size and shape of its view, and a conic gradient's start
13615    /// direction right for the view's proportions: run from `layoutSubviews`.
13616    fn sync_fill_layer(v: &UIView, state: &SurfaceState) {
13617        let layer = v.layer();
13618        if let Some(sub) = &state.fill_layer {
13619            without_actions(|| {
13620                sub.setFrame(layer.bounds());
13621                sub.setCornerRadius(layer.cornerRadius());
13622                sub.setMaskedCorners(layer.maskedCorners());
13623            });
13624        }
13625        if matches!(state.props.fill, Some(day_spec::Paint::Conic(_))) {
13626            apply_surface_inks(v, state);
13627        }
13628    }
13629
13630    /// A container laid out again: re-fit its gradient sublayer and conic direction.
13631    fn relayout_surface(v: &UIView) {
13632        let key = ptr_of(v);
13633        let Some(state) = SURFACES.with(|t| t.take(key)) else {
13634            return;
13635        };
13636        sync_fill_layer(v, &state);
13637        SURFACES.with(|t| t.insert(key, state));
13638    }
13639
13640    /// A container's traits changed: when the change can change a color (the appearance,
13641    /// the contrast, the interface level), set its layer colors again from its inks
13642    /// (color brief §1.5). Background, text and tint colors follow by themselves.
13643    fn refresh_surface_inks(v: &UIView, previous: Option<&objc2_ui_kit::UITraitCollection>) {
13644        use objc2_ui_kit::UITraitEnvironment as _;
13645        let key = ptr_of(v);
13646        if !SURFACES.with(|t| t.contains(key)) {
13647            return;
13648        }
13649        if previous.is_some_and(|old| {
13650            !v.traitCollection()
13651                .hasDifferentColorAppearanceComparedToTraitCollection(Some(old))
13652        }) {
13653            return;
13654        }
13655        let Some(state) = SURFACES.with(|t| t.take(key)) else {
13656            return;
13657        };
13658        apply_surface_inks(v, &state);
13659        SURFACES.with(|t| t.insert(key, state));
13660    }
13661
13662    /// Keep a surface's shadow path on its layer's rounded rectangle: the bounds, the corner
13663    /// radius and the corner selection the layer holds now. A layer without a shadow is left
13664    /// alone, which is every container that is not a shadowed surface.
13665    fn sync_surface_shadow_path(v: &UIView) {
13666        use objc2_quartz_core::CACornerMask;
13667        use objc2_ui_kit::UIRectCorner;
13668        let layer = v.layer();
13669        if layer.shadowOpacity() <= 0.0 {
13670            return;
13671        }
13672        let bounds = v.bounds();
13673        let radius = layer
13674            .cornerRadius()
13675            .min(bounds.size.width / 2.0)
13676            .min(bounds.size.height / 2.0)
13677            .max(0.0);
13678        let masked = layer.maskedCorners();
13679        let mut corners = UIRectCorner::empty();
13680        for (bit, corner) in [
13681            (CACornerMask::LayerMinXMinYCorner, UIRectCorner::TopLeft),
13682            (CACornerMask::LayerMaxXMinYCorner, UIRectCorner::TopRight),
13683            (CACornerMask::LayerMinXMaxYCorner, UIRectCorner::BottomLeft),
13684            (CACornerMask::LayerMaxXMaxYCorner, UIRectCorner::BottomRight),
13685        ] {
13686            if masked.contains(bit) {
13687                corners |= corner;
13688            }
13689        }
13690        let path =
13691            objc2_ui_kit::UIBezierPath::bezierPathWithRoundedRect_byRoundingCorners_cornerRadii(
13692                bounds,
13693                corners,
13694                CGSize::new(radius, radius),
13695            );
13696        layer.setShadowPath(Some(&path.CGPath()));
13697    }
13698
13699    fn cg(r: day_spec::Rect) -> CGRect {
13700        CGRect::new(
13701            CGPoint::new(r.origin.x, r.origin.y),
13702            CGSize::new(r.size.width, r.size.height),
13703        )
13704    }
13705
13706    /// Put a [`day_spec::StrokeStyle`] onto a path: width always, and dash/cap/join/miter only
13707    /// when they differ from the defaults, so a plain stroke costs no extra messages.
13708    fn apply_stroke_style(p: &objc2_ui_kit::UIBezierPath, style: &day_spec::StrokeStyle) {
13709        use day_spec::{LineCap, LineJoin};
13710        unsafe {
13711            p.setLineWidth(style.width);
13712            if style.is_plain() {
13713                return;
13714            }
13715            p.setLineCapStyle(match style.cap {
13716                LineCap::Butt => objc2_core_graphics::CGLineCap::Butt,
13717                LineCap::Round => objc2_core_graphics::CGLineCap::Round,
13718                LineCap::Square => objc2_core_graphics::CGLineCap::Square,
13719            });
13720            p.setLineJoinStyle(match style.join {
13721                LineJoin::Miter => objc2_core_graphics::CGLineJoin::Miter,
13722                LineJoin::Round => objc2_core_graphics::CGLineJoin::Round,
13723                LineJoin::Bevel => objc2_core_graphics::CGLineJoin::Bevel,
13724            });
13725            p.setMiterLimit(style.miter_limit);
13726            if !style.dash.is_empty() {
13727                let pattern: Vec<CGFloat> = style.dash.iter().map(|d| *d as CGFloat).collect();
13728                p.setLineDash_count_phase(
13729                    pattern.as_ptr(),
13730                    pattern.len() as isize,
13731                    style.dash_phase,
13732                );
13733            }
13734        }
13735    }
13736
13737    /// Draw a gradient through whatever clip is currently installed. Shared by the gradient
13738    /// FILL arms and the gradient STROKE arm, which differ only in what they clip to first.
13739    fn draw_gradient_in(ctx: &CGContext, paint: &day_spec::Paint, bounds: day_spec::Rect) {
13740        let opts = objc2_core_graphics::CGGradientDrawingOptions::DrawsBeforeStartLocation
13741            | objc2_core_graphics::CGGradientDrawingOptions::DrawsAfterEndLocation;
13742        unsafe {
13743            match paint {
13744                day_spec::Paint::Linear(g) => {
13745                    let Some(grad) = cggradient(&day_spec::resolved_stops(&g.stops)) else {
13746                        return;
13747                    };
13748                    let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
13749                    CGContext::draw_linear_gradient(
13750                        Some(ctx),
13751                        Some(&grad),
13752                        CGPoint::new(s.x, s.y),
13753                        CGPoint::new(e.x, e.y),
13754                        opts,
13755                    );
13756                }
13757                day_spec::Paint::Radial(g) => {
13758                    let Some(grad) = cggradient(&day_spec::resolved_stops(&g.stops)) else {
13759                        return;
13760                    };
13761                    CGContext::save_g_state(Some(ctx));
13762                    CGContext::translate_ctm(Some(ctx), bounds.origin.x, bounds.origin.y);
13763                    CGContext::scale_ctm(Some(ctx), bounds.size.width, bounds.size.height);
13764                    let c = CGPoint::new(g.center.x, g.center.y);
13765                    CGContext::draw_radial_gradient(
13766                        Some(ctx),
13767                        Some(&grad),
13768                        c,
13769                        0.0,
13770                        c,
13771                        g.radius,
13772                        opts,
13773                    );
13774                    CGContext::restore_g_state(Some(ctx));
13775                }
13776                day_spec::Paint::Conic(g) => {
13777                    let c = g.center.resolve(bounds);
13778                    draw_conic(ctx, g, CGPoint::new(c.x, c.y));
13779                }
13780                day_spec::Paint::Solid(_) => {}
13781            }
13782        }
13783    }
13784
13785    /// `CGContextDrawConicGradient`, where the running OS has it (iOS 17). Day deploys to
13786    /// iOS 15, and a direct reference to the symbol would stop the app loading there, so it is
13787    /// looked up at runtime instead; `None` sends the caller to the wedge painter.
13788    fn native_conic() -> Option<
13789        unsafe extern "C-unwind" fn(
13790            &CGContext,
13791            Option<&objc2_core_graphics::CGGradient>,
13792            CGPoint,
13793            CGFloat,
13794        ),
13795    > {
13796        unsafe extern "C" {
13797            fn dlsym(
13798                handle: *mut std::ffi::c_void,
13799                symbol: *const std::ffi::c_char,
13800            ) -> *mut std::ffi::c_void;
13801        }
13802        /// `RTLD_DEFAULT` on Apple platforms: search every loaded image.
13803        const RTLD_DEFAULT: isize = -2;
13804        static SYMBOL: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
13805            // `DAY_UIKIT_CONIC_WEDGES` runs the iOS 15 and 16 painter on a newer system, the
13806            // only way to look at it where those runtimes cannot be installed.
13807            if std::env::var_os("DAY_UIKIT_CONIC_WEDGES").is_some() {
13808                return 0;
13809            }
13810            // SAFETY: `dlsym` with the default handle and a NUL-terminated name only reads the
13811            // loaded images' symbol tables.
13812            unsafe {
13813                dlsym(
13814                    RTLD_DEFAULT as *mut std::ffi::c_void,
13815                    c"CGContextDrawConicGradient".as_ptr(),
13816                ) as usize
13817            }
13818        });
13819        if *SYMBOL == 0 {
13820            return None;
13821        }
13822        // SAFETY: a non-null result is the address of `CGContextDrawConicGradient`, whose C
13823        // signature (context, gradient, center, angle) is the one named here.
13824        Some(unsafe {
13825            std::mem::transmute::<
13826                usize,
13827                unsafe extern "C-unwind" fn(
13828                    &CGContext,
13829                    Option<&objc2_core_graphics::CGGradient>,
13830                    CGPoint,
13831                    CGFloat,
13832                ),
13833            >(*SYMBOL)
13834        })
13835    }
13836
13837    /// Draw a conic gradient about `center` through the clip currently installed
13838    /// (docs/canvas.md "Conic gradients"). Core Graphics measures the angle from +x toward +y,
13839    /// which in UIKit's y-down space is the clockwise turn Day's angles take.
13840    fn draw_conic(ctx: &CGContext, g: &day_spec::ConicGradient, center: CGPoint) {
13841        use crate::canvas_state::{CONIC_WEDGES, conic_stops, conic_wedge};
13842        if let Some(native) = native_conic() {
13843            if let Some(grad) = cggradient(&conic_stops(&day_spec::resolved_stops(&g.stops))) {
13844                // SAFETY: a live context and gradient, on the thread drawing into the context.
13845                unsafe { native(ctx, Some(&grad), center, g.start.radians()) };
13846            }
13847            return;
13848        }
13849        // Before iOS 17: thin wedges from the center out past the clip, each one flat color.
13850        // They are painted without antialiasing, so there is no seam between two of them, and
13851        // into a layer of their own in COPY mode, because without antialiasing Core Graphics
13852        // paints every pixel a wedge touches and neighbors overlap by a pixel: copying makes
13853        // the later wedge replace the earlier one there, where compositing would count a
13854        // translucent color twice. The clip, installed with antialiasing on, still gives the
13855        // shape a soft edge when the layer is composited.
13856        let clip = CGContext::clip_bounding_box(Some(ctx));
13857        if g.stops.is_empty() || !(clip.size.width > 0.0 && clip.size.height > 0.0) {
13858            return;
13859        }
13860        let reach = [
13861            (clip.origin.x, clip.origin.y),
13862            (clip.origin.x + clip.size.width, clip.origin.y),
13863            (clip.origin.x, clip.origin.y + clip.size.height),
13864            (clip.origin.x + clip.size.width, clip.origin.y + clip.size.height),
13865        ]
13866        .iter()
13867        .map(|(x, y)| (x - center.x).hypot(y - center.y))
13868        .fold(0.0_f64, f64::max)
13869            // A chord between two edge points sits inside the circle; go a little further out.
13870            * 1.01
13871            + 1.0;
13872        if !reach.is_finite() {
13873            return;
13874        }
13875        let edge = |deg: f64| {
13876            let (sin, cos) = deg.to_radians().sin_cos();
13877            (center.x + reach * cos, center.y + reach * sin)
13878        };
13879        CGContext::save_g_state(Some(ctx));
13880        // SAFETY: no auxiliary dictionary; the layer is ended below on the same context.
13881        unsafe { CGContext::begin_transparency_layer(Some(ctx), None) };
13882        CGContext::set_blend_mode(Some(ctx), objc2_core_graphics::CGBlendMode::Copy);
13883        CGContext::set_should_antialias(Some(ctx), false);
13884        for i in 0..CONIC_WEDGES {
13885            let (from, to, mid) = conic_wedge(g.start.degrees(), i, CONIC_WEDGES);
13886            let color = g.color_at(day_spec::Angle::deg(mid));
13887            let (a, b) = (edge(from), edge(to));
13888            CGContext::set_rgb_fill_color(Some(ctx), color.r, color.g, color.b, color.a);
13889            CGContext::begin_path(Some(ctx));
13890            CGContext::move_to_point(Some(ctx), center.x, center.y);
13891            CGContext::add_line_to_point(Some(ctx), a.0, a.1);
13892            CGContext::add_line_to_point(Some(ctx), b.0, b.1);
13893            CGContext::close_path(Some(ctx));
13894            CGContext::fill_path(Some(ctx));
13895        }
13896        CGContext::end_transparency_layer(Some(ctx));
13897        CGContext::restore_g_state(Some(ctx));
13898    }
13899
13900    /// Core Graphics' name for a Day blend mode (docs/canvas.md "Blend modes"): the separable
13901    /// modes one for one, `Add` as Porter-Duff plus, `Erase` as destination-out.
13902    fn cg_blend(mode: day_spec::BlendMode) -> objc2_core_graphics::CGBlendMode {
13903        use day_spec::BlendMode as B;
13904        use objc2_core_graphics::CGBlendMode as M;
13905        match mode {
13906            B::Normal => M::Normal,
13907            B::Multiply => M::Multiply,
13908            B::Screen => M::Screen,
13909            B::Overlay => M::Overlay,
13910            B::Darken => M::Darken,
13911            B::Lighten => M::Lighten,
13912            B::Add => M::PlusLighter,
13913            B::Erase => M::DestinationOut,
13914        }
13915    }
13916
13917    /// Clip to whatever `clip` installs and draw the gradient `paint` through it, as ONE
13918    /// drawing: under a shadow or a blend mode the pair is grouped into a transparency layer
13919    /// first, so the shadow is cast by the gradient-filled shape (a bare clip would cut the
13920    /// shadow off with everything else outside the shape) and the blend applies once.
13921    fn gradient_through(
13922        ctx: &CGContext,
13923        state: &crate::canvas_state::CanvasState,
13924        paint: &day_spec::Paint,
13925        bounds: day_spec::Rect,
13926        clip: impl FnOnce(),
13927    ) {
13928        let grouped = state.groups();
13929        CGContext::save_g_state(Some(ctx));
13930        if grouped {
13931            // SAFETY: no auxiliary dictionary; the layer is ended below on the same context.
13932            unsafe { CGContext::begin_transparency_layer(Some(ctx), None) };
13933            CGContext::save_g_state(Some(ctx));
13934        }
13935        clip();
13936        draw_gradient_in(ctx, paint, bounds);
13937        if grouped {
13938            CGContext::restore_g_state(Some(ctx));
13939            CGContext::end_transparency_layer(Some(ctx));
13940        }
13941        CGContext::restore_g_state(Some(ctx));
13942    }
13943
13944    fn draw_op(op: &day_spec::DrawOp, state: &crate::canvas_state::CanvasState) {
13945        use day_spec::DrawOp;
13946        unsafe {
13947            match op {
13948                // One path for the whole batch, then one fill or stroke — the AppKit twin
13949                // (docs/canvas.md "Stamping"). `apply` is UIBezierPath's own transform, so each
13950                // copy is the template translated without touching the graphics state.
13951                // A gradient resolves against each copy's own bounding box, so a gradient
13952                // stamp is its copies drawn one at a time.
13953                DrawOp::Stamp(st) if !matches!(st.paint, day_spec::Paint::Solid(_)) => {
13954                    for p in &st.at {
13955                        let shape = st.shape.translated(p.x, p.y);
13956                        let copy = match &st.stroke {
13957                            None => DrawOp::Fill(shape, st.paint.clone()),
13958                            Some(style) => DrawOp::Stroke(shape, st.paint.clone(), style.clone()),
13959                        };
13960                        draw_op(&copy, state);
13961                    }
13962                }
13963                DrawOp::Stamp(st) => {
13964                    let batch = unsafe { objc2_ui_kit::UIBezierPath::bezierPath() };
13965                    for p in &st.at {
13966                        if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
13967                            unsafe { batch.appendPath(&copy) };
13968                        }
13969                    }
13970                    let color = match &st.paint {
13971                        day_spec::Paint::Solid(c) => c.resolved(),
13972                        _ => day_spec::Color::WHITE,
13973                    };
13974                    match &st.stroke {
13975                        None => {
13976                            uicolor(color).setFill();
13977                            unsafe { batch.fill() };
13978                        }
13979                        Some(style) => {
13980                            uicolor(color).setStroke();
13981                            apply_stroke_style(&batch, style);
13982                            unsafe { batch.stroke() };
13983                        }
13984                    }
13985                }
13986                DrawOp::Fill(shape, paint) => match paint {
13987                    day_spec::Paint::Solid(color) => {
13988                        uicolor((*color).resolved()).setFill();
13989                        if let Some(p) = bezier(shape) {
13990                            p.fill();
13991                        }
13992                    }
13993                    // Native gradients: clip to the shape's path and draw the CGGradient
13994                    // through it, resolved from the unit points in the shape's bounds.
13995                    day_spec::Paint::Linear(_)
13996                    | day_spec::Paint::Radial(_)
13997                    | day_spec::Paint::Conic(_) => {
13998                        let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
13999                        if let (Some(p), Some(ctx)) = (bezier(shape), ctx) {
14000                            gradient_through(&ctx, state, paint, shape.bounds(), || p.addClip());
14001                        }
14002                    }
14003                },
14004                DrawOp::Stroke(shape, paint, style) => {
14005                    let Some(p) = bezier(shape) else { return };
14006                    apply_stroke_style(&p, style);
14007                    match paint {
14008                        day_spec::Paint::Solid(color) => {
14009                            uicolor((*color).resolved()).setStroke();
14010                            p.stroke();
14011                        }
14012                        // A gradient stroke has no CoreGraphics primitive: convert the stroke
14013                        // to the region it covers (`CGPathCreateCopyByStrokingPath` via
14014                        // `bezierPathByStrokingPath` is unavailable here), clip to it, and draw
14015                        // the gradient through. `replacePathWithStrokedPath` on the context is
14016                        // the documented way to get exactly that region.
14017                        day_spec::Paint::Linear(_)
14018                        | day_spec::Paint::Radial(_)
14019                        | day_spec::Paint::Conic(_) => {
14020                            let Some(ctx) = objc2_ui_kit::UIGraphicsGetCurrentContext() else {
14021                                return;
14022                            };
14023                            gradient_through(&ctx, state, paint, shape.bounds(), || {
14024                                // The stroked region is cut with the CONTEXT's line width,
14025                                // cap, join and dash, not the path object's.
14026                                cg_stroke_style(&ctx, style);
14027                                CGContext::add_path(Some(&ctx), Some(&p.CGPath()));
14028                                CGContext::replace_path_with_stroked_path(Some(&ctx));
14029                                CGContext::clip(Some(&ctx));
14030                            });
14031                        }
14032                    }
14033                }
14034                DrawOp::Clip(shape) => {
14035                    // `addClip` INTERSECTS with the context's current clip and reads the
14036                    // path's own even-odd flag, which is exactly Day's contract.
14037                    if let Some(p) = bezier(shape) {
14038                        p.addClip();
14039                    }
14040                }
14041                DrawOp::Text {
14042                    text,
14043                    at,
14044                    size,
14045                    color,
14046                    anchor,
14047                    font,
14048                } => {
14049                    let font = canvas_uifont(*size, font);
14050                    let attrs = canvas_text_attrs(&font, *color);
14051                    let ns = NSString::from_str(text);
14052                    let mut origin = CGPoint::new(at.x, at.y);
14053                    // `drawAtPoint:` takes the line box's top-leading corner; every other anchor
14054                    // is an offset from it, computed from the metrics this draw already holds.
14055                    if *anchor != day_spec::TextAnchor::LEADING {
14056                        let sz: CGSize = msg_send![&ns, sizeWithAttributes: &*attrs];
14057                        let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
14058                        origin.x += dx;
14059                        origin.y += dy;
14060                    }
14061                    let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
14062                }
14063                // A released bitmap draws nothing rather than a placeholder: a canvas re-records
14064                // on every tracked read, so a handle can be dropped between the record and this
14065                // replay, and a frame that flashes a grey box is worse than one that omits it.
14066                DrawOp::Image {
14067                    image,
14068                    rect,
14069                    opacity,
14070                    source,
14071                } => {
14072                    let held = BITMAPS.with(|m| {
14073                        m.borrow()
14074                            .get(&image.0)
14075                            .map(|b| (b.image.clone(), b.info.pixels))
14076                    });
14077                    if let Some((img, pixels)) = held {
14078                        let dest = CGRect::new(
14079                            CGPoint::new(rect.origin.x, rect.origin.y),
14080                            CGSize::new(rect.size.width, rect.size.height),
14081                        );
14082                        // UIImage's plain drawInRect always draws at full opacity, even if
14083                        // CGContext's alpha was set. Use its explicit compositing overload,
14084                        // which also names the blend mode: the one the replay is in.
14085                        match source {
14086                            None => img.drawInRect_blendMode_alpha(
14087                                dest,
14088                                cg_blend(state.blend()),
14089                                *opacity,
14090                            ),
14091                            // A region (in the bitmap's pixels): clip to the rect and draw the
14092                            // whole image scaled so the region lands in it. `UIImage` has no
14093                            // sub-rect draw that keeps its orientation, and this is exact for
14094                            // any image at any scale, because `drawInRect` scales the whole
14095                            // image into the rect whatever its point size. The shared clamp
14096                            // decides only whether anything is inside the bitmap at all; the
14097                            // clip does the rest.
14098                            Some(src) => {
14099                                if day_spec::clamp_image_source(*src, *rect, pixels).is_some() {
14100                                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14101                                    CGContext::save_g_state(ctx.as_deref());
14102                                    CGContext::clip_to_rect(ctx.as_deref(), dest);
14103                                    let kx = rect.size.width / src.size.width;
14104                                    let ky = rect.size.height / src.size.height;
14105                                    let full = CGRect::new(
14106                                        CGPoint::new(
14107                                            rect.origin.x - src.origin.x * kx,
14108                                            rect.origin.y - src.origin.y * ky,
14109                                        ),
14110                                        CGSize::new(pixels.width * kx, pixels.height * ky),
14111                                    );
14112                                    img.drawInRect_blendMode_alpha(
14113                                        full,
14114                                        cg_blend(state.blend()),
14115                                        *opacity,
14116                                    );
14117                                    CGContext::restore_g_state(ctx.as_deref());
14118                                }
14119                            }
14120                        }
14121                    }
14122                }
14123                // The shadow and the blend mode are Core Graphics graphics state: `Save` and
14124                // `Restore` below scope them with the clip and the transform, and every fill,
14125                // stroke, text and image drawn while a shadow is set casts its own. The
14126                // offset and the blur are in the context's base space (points here, y down
14127                // in a UIKit context), which the current transform does not touch: Day's
14128                // contract exactly. Core Graphics' blur is the CSS blur radius.
14129                DrawOp::Shadow(shadow) => {
14130                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14131                    match crate::canvas_state::visible_shadow(*shadow) {
14132                        Some(s) => CGContext::set_shadow_with_color(
14133                            ctx.as_deref(),
14134                            CGSize::new(s.dx, s.dy),
14135                            s.blur.max(0.0),
14136                            Some(&cgcolor(s.color.resolved())),
14137                        ),
14138                        // No color is Core Graphics' "shadowing off".
14139                        None => CGContext::set_shadow_with_color(
14140                            ctx.as_deref(),
14141                            CGSize::new(0.0, 0.0),
14142                            0.0,
14143                            None,
14144                        ),
14145                    }
14146                }
14147                // The backdrop is this canvas's own bitmap: the view's layer on screen (never
14148                // opaque, so `Erase` leaves real transparency and the view behind shows), the
14149                // renderer's image in an export.
14150                DrawOp::Blend(mode) => {
14151                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14152                    CGContext::set_blend_mode(ctx.as_deref(), cg_blend(*mode));
14153                }
14154                DrawOp::Save => {
14155                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14156                    CGContext::save_g_state(ctx.as_deref());
14157                }
14158                DrawOp::Restore => {
14159                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14160                    CGContext::restore_g_state(ctx.as_deref());
14161                }
14162                DrawOp::Concat(m) => {
14163                    let ctx = objc2_ui_kit::UIGraphicsGetCurrentContext();
14164                    // CGAffineTransform shares day_geometry::Affine's row-vector convention.
14165                    let t = CGAffineTransform {
14166                        a: m.a,
14167                        b: m.b,
14168                        c: m.c,
14169                        d: m.d,
14170                        tx: m.tx,
14171                        ty: m.ty,
14172                    };
14173                    CGContext::concat_ctm(ctx.as_deref(), t);
14174                }
14175            }
14176        }
14177    }
14178
14179    /// A `CGGradient` from a display-list gradient's stops (device RGB, like every canvas color).
14180    fn cggradient(
14181        stops: &[(f64, day_spec::Color)],
14182    ) -> Option<objc2_core_foundation::CFRetained<objc2_core_graphics::CGGradient>> {
14183        if stops.is_empty() {
14184            return None;
14185        }
14186        let components: Vec<f64> = stops
14187            .iter()
14188            .flat_map(|(_, c)| [c.r, c.g, c.b, c.a])
14189            .collect();
14190        let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
14191        let space = objc2_core_graphics::CGColorSpace::new_device_rgb();
14192        unsafe {
14193            objc2_core_graphics::CGGradient::with_color_components(
14194                space.as_deref(),
14195                components.as_ptr(),
14196                locations.as_ptr(),
14197                stops.len(),
14198            )
14199        }
14200    }
14201
14202    fn bezier(shape: &day_spec::Shape) -> Option<Retained<objc2_ui_kit::UIBezierPath>> {
14203        use day_spec::Shape;
14204        use objc2_ui_kit::UIBezierPath;
14205        unsafe {
14206            Some(match shape {
14207                Shape::Rect(r) => UIBezierPath::bezierPathWithRect(cg(*r)),
14208                Shape::RoundedRect(r, rad) => {
14209                    UIBezierPath::bezierPathWithRoundedRect_cornerRadius(cg(*r), *rad)
14210                }
14211                Shape::Ellipse(r) => UIBezierPath::bezierPathWithOvalInRect(cg(*r)),
14212                Shape::Arc { rect, start, sweep } => {
14213                    let (start_deg, sweep_deg) = (start.degrees(), sweep.degrees());
14214                    let center = CGPoint::new(
14215                        rect.origin.x + rect.size.width / 2.0,
14216                        rect.origin.y + rect.size.height / 2.0,
14217                    );
14218                    let radius = rect.size.width.min(rect.size.height) / 2.0;
14219                    UIBezierPath::bezierPathWithArcCenter_radius_startAngle_endAngle_clockwise(
14220                        center,
14221                        radius,
14222                        start_deg.to_radians(),
14223                        (start_deg + sweep_deg).to_radians(),
14224                        true,
14225                    )
14226                }
14227                Shape::Line(a, b) => {
14228                    let p = UIBezierPath::bezierPath();
14229                    p.moveToPoint(CGPoint::new(a.x, a.y));
14230                    p.addLineToPoint(CGPoint::new(b.x, b.y));
14231                    p
14232                }
14233                Shape::Path(path) => {
14234                    use day_spec::PathSeg;
14235                    if path.segs.is_empty() {
14236                        return None;
14237                    }
14238                    let p = UIBezierPath::bezierPath();
14239                    for seg in &path.segs {
14240                        match seg {
14241                            PathSeg::Move(a) => p.moveToPoint(CGPoint::new(a.x, a.y)),
14242                            PathSeg::Line(a) => p.addLineToPoint(CGPoint::new(a.x, a.y)),
14243                            PathSeg::Quad(c, a) => p.addQuadCurveToPoint_controlPoint(
14244                                CGPoint::new(a.x, a.y),
14245                                CGPoint::new(c.x, c.y),
14246                            ),
14247                            PathSeg::Cubic(c1, c2, a) => p
14248                                .addCurveToPoint_controlPoint1_controlPoint2(
14249                                    CGPoint::new(a.x, a.y),
14250                                    CGPoint::new(c1.x, c1.y),
14251                                    CGPoint::new(c2.x, c2.y),
14252                                ),
14253                            PathSeg::Close => p.closePath(),
14254                        }
14255                    }
14256                    // The fill rule travels ON the path, which is also how `addClip` reads it.
14257                    p.setUsesEvenOddFillRule(path.rule == day_spec::FillRule::EvenOdd);
14258                    p
14259                }
14260                Shape::Polygon(pts) => {
14261                    if pts.len() < 2 {
14262                        return None;
14263                    }
14264                    let p = UIBezierPath::bezierPath();
14265                    p.moveToPoint(CGPoint::new(pts[0].x, pts[0].y));
14266                    for pt in &pts[1..] {
14267                        p.addLineToPoint(CGPoint::new(pt.x, pt.y));
14268                    }
14269                    p.closePath();
14270                    p
14271                }
14272            })
14273        }
14274    }
14275
14276    // -----------------------------------------------------------------------
14277    // The backend
14278    // -----------------------------------------------------------------------
14279
14280    #[distributed_slice]
14281    pub static RENDERERS: [fn() -> Renderer<Uikit>];
14282
14283    /// Rasterize this app's own window to PNG (docs/window-image.md).
14284    ///
14285    /// `UIGraphicsImageRenderer` + `drawViewHierarchyInRect:afterScreenUpdates:` — the standard iOS
14286    /// way, and SYNCHRONOUS, which is what lets `day::window_image()` stay a plain call on every
14287    /// backend. `afterScreenUpdates: true` so a capture taken right after a state change shows the
14288    /// change rather than the frame before it.
14289    ///
14290    /// `chrome` picks the whole window over Day's content view; both are views in the same tree.
14291    /// The `UIImage` behind an [`day_spec::ImageSource`] (docs/images.md).
14292    ///
14293    /// Shared by realize and the `Source` patch on purpose: a swapped source must load exactly
14294    /// what a fresh realize would have, or a piece shows different pixels depending on whether it
14295    /// was built or updated.
14296    pub(crate) fn uikit_image_for(
14297        source: &day_spec::ImageSource,
14298    ) -> Option<Retained<objc2_ui_kit::UIImage>> {
14299        match source {
14300            day_spec::ImageSource::Named(named) => {
14301                let name = NSString::from_str(named);
14302                // Processed image (§18.3): load by name from the DayPieces `Assets.car` — the
14303                // SwiftPM `.process` catalog compiled by actool into DayPieces_DayPieces.bundle.
14304                let main = unsafe { objc2_foundation::NSBundle::mainBundle() };
14305                let bname = NSString::from_str("DayPieces_DayPieces");
14306                let bext = NSString::from_str("bundle");
14307                if let Some(url) =
14308                    unsafe { main.URLForResource_withExtension(Some(&bname), Some(&bext)) }
14309                    && let Some(day_bundle) =
14310                        unsafe { objc2_foundation::NSBundle::bundleWithURL(&url) }
14311                    && let Some(img) = unsafe {
14312                        objc2_ui_kit::UIImage::imageNamed_inBundle_compatibleWithTraitCollection(
14313                            &name,
14314                            Some(&day_bundle),
14315                            None,
14316                        )
14317                    }
14318                {
14319                    return Some(img);
14320                }
14321                // Fallback: a loose file staged in the bundle (assets/ or images/), or dev.
14322                let path = day_spec::resource::resolve_image_file(named)?;
14323                unsafe {
14324                    objc2_ui_kit::UIImage::imageWithContentsOfFile(&NSString::from_str(
14325                        &path.to_string_lossy(),
14326                    ))
14327                }
14328            }
14329            // Bytes the app already holds — a download, a picked file, a paste — with no staged
14330            // resource behind them.
14331            day_spec::ImageSource::Bytes(bytes) => {
14332                let data = objc2_foundation::NSData::with_bytes(bytes);
14333                unsafe { objc2_ui_kit::UIImage::imageWithData(&data) }
14334            }
14335            // Already decoded: share the one UIImage rather than parsing the same bytes twice.
14336            day_spec::ImageSource::Decoded(id) => {
14337                BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
14338            }
14339        }
14340    }
14341
14342    /// Redraw `image` at `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s `fit`.
14343    fn scaled_image(
14344        image: &objc2_ui_kit::UIImage,
14345        pixels: Size,
14346        scale: f64,
14347    ) -> Retained<objc2_ui_kit::UIImage> {
14348        use objc2::AllocAnyThread as _;
14349        let w = (pixels.width * scale).round().max(1.0);
14350        let h = (pixels.height * scale).round().max(1.0);
14351        let bounds = CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(w, h));
14352        // The format's scale is pinned to 1: the renderer would otherwise multiply by the
14353        // screen's scale and hand back an image twice the size that was asked for.
14354        let format = unsafe { objc2_ui_kit::UIGraphicsImageRendererFormat::preferredFormat() };
14355        unsafe { format.setScale(1.0) };
14356        let renderer = unsafe {
14357            objc2_ui_kit::UIGraphicsImageRenderer::initWithBounds_format(
14358                objc2_ui_kit::UIGraphicsImageRenderer::alloc(),
14359                bounds,
14360                &format,
14361            )
14362        };
14363        let src: Retained<objc2_ui_kit::UIImage> = Retained::from(image);
14364        // SAFETY: the renderer runs the block synchronously, inside this call.
14365        unsafe {
14366            let block = block2::RcBlock::new(
14367                move |_ctx: core::ptr::NonNull<objc2_ui_kit::UIGraphicsImageRendererContext>| {
14368                    src.drawInRect(bounds);
14369                },
14370            );
14371            renderer.imageWithActions(&raw const *block as *mut _)
14372        }
14373    }
14374
14375    /// Re-encode a decoded bitmap (docs/images.md).
14376    ///
14377    /// A free function rather than the duty's body so each refusal reads as an early return
14378    /// instead of another copy of the same emit.
14379    fn encode_bitmap(
14380        id: day_spec::BitmapId,
14381        spec: &day_spec::EncodeSpec,
14382    ) -> Result<Vec<u8>, day_spec::ImageError> {
14383        use day_spec::ImageFormat as F;
14384        let held = BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| (b.image.clone(), b.info)));
14385        let (image, info) = held.ok_or(day_spec::ImageError::Gone)?;
14386        // `fit` scales the longest side down first. A box LARGER than the original is ignored:
14387        // upscaling on an export path inflates the bytes without adding any detail.
14388        let image = match spec.fit {
14389            Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
14390                let s = (fit.width / info.pixels.width)
14391                    .min(fit.height / info.pixels.height)
14392                    .min(1.0);
14393                if s < 1.0 {
14394                    scaled_image(&image, info.pixels, s)
14395                } else {
14396                    image
14397                }
14398            }
14399            _ => image,
14400        };
14401        let data = match spec.format {
14402            F::Png => image.png_representation(),
14403            // UIKit's compression runs 0 (most) … 1 (least), which is `EncodeSpec::quality`'s
14404            // scale exactly.
14405            F::Jpeg => image.jpeg_representation(spec.quality.unwrap_or(0.9).clamp(0.0, 1.0)),
14406            // UIKit ships no other writer; `encode_formats` says so before an app asks.
14407            _ => return Err(day_spec::ImageError::Encode),
14408        };
14409        Ok(data.ok_or(day_spec::ImageError::Encode)?.to_vec())
14410    }
14411
14412    /// Replay a canvas's ops into the current UIKit graphics context: the one painter the
14413    /// on-screen `drawRect:` and both exports share (docs/canvas.md "Exporting").
14414    fn paint_ops(ops: &[day_spec::DrawOp]) {
14415        // SAFETY: reading the current graphics context on the thread that set it.
14416        let mut state = crate::canvas_state::CanvasState::default();
14417        let Some(cg) = (unsafe { objc2_ui_kit::UIGraphicsGetCurrentContext() }) else {
14418            for op in ops {
14419                state.track(op);
14420                draw_op(op, &state);
14421            }
14422            return;
14423        };
14424        cg_begin_replay(&cg);
14425        for op in ops {
14426            state.track(op);
14427            if !cg_fast_op(&cg, op) {
14428                draw_op(op, &state);
14429            }
14430        }
14431    }
14432
14433    /// Paint one op straight into the Core Graphics context when it is a solid fill, a solid
14434    /// stroke or a clip of a shape the context can take as path calls, and say whether it did.
14435    /// This is the hot path of a dense drawing (a map tile is a few thousand of these), and the
14436    /// path object route below it costs an order of magnitude more: every `UIBezierPath` is an
14437    /// allocation and a message per segment, and its fill or stroke re-derives the graphics state
14438    /// the context already holds. Everything else (text, images, gradients, stamps, rounded rects
14439    /// and arcs) keeps the full painter. The fill and stroke color spaces are set to sRGB once per
14440    /// replay by `cg_begin_replay`, so the components here read as the ones `uicolor` would make.
14441    fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
14442        use objc2_core_graphics::{CGContext, CGImage};
14443        match op {
14444            DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
14445                let Some(even_odd) = cg_add_shape(cg, shape) else {
14446                    return false;
14447                };
14448                let c = [
14449                    color.resolved().r,
14450                    color.resolved().g,
14451                    color.resolved().b,
14452                    color.resolved().a,
14453                ];
14454                // SAFETY: four components for the sRGB fill space set at the start of the replay.
14455                unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
14456                if even_odd {
14457                    CGContext::eo_fill_path(Some(cg));
14458                } else {
14459                    CGContext::fill_path(Some(cg));
14460                }
14461                true
14462            }
14463            DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
14464                if cg_add_shape(cg, shape).is_none() {
14465                    return false;
14466                }
14467                let c = [
14468                    color.resolved().r,
14469                    color.resolved().g,
14470                    color.resolved().b,
14471                    color.resolved().a,
14472                ];
14473                // SAFETY: four components for the sRGB stroke space set at the start of the replay.
14474                unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
14475                cg_stroke_style(cg, style);
14476                CGContext::stroke_path(Some(cg));
14477                true
14478            }
14479            DrawOp::Clip(shape) => {
14480                let Some(even_odd) = cg_add_shape(cg, shape) else {
14481                    return false;
14482                };
14483                if even_odd {
14484                    CGContext::eo_clip(Some(cg));
14485                } else {
14486                    CGContext::clip(Some(cg));
14487                }
14488                true
14489            }
14490            DrawOp::Image {
14491                image,
14492                rect,
14493                opacity,
14494                source,
14495            } => {
14496                // The bitmap's pixels straight to the context (`drawInRect:` on the image object
14497                // costs tens of microseconds per call, and a pattern fill is hundreds of copies).
14498                let Some((cg_image, pixels)) = BITMAPS.with(|m| {
14499                    m.borrow().get(&image.0).and_then(|b| {
14500                        // SAFETY: reading the immutable image's CGImage on the thread holding it.
14501                        let cg = unsafe { b.image.CGImage() }?;
14502                        Some((cg, b.info.pixels))
14503                    })
14504                }) else {
14505                    return false;
14506                };
14507                // A region is in the bitmap's pixels with a top-left origin, which is also how
14508                // `CGImageCreateWithImageInRect` counts; the shared clamp keeps its mapping into
14509                // `rect` when it overhangs the bitmap.
14510                let (cropped, dest) = match source {
14511                    None => (None, *rect),
14512                    Some(src) => {
14513                        let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
14514                        else {
14515                            return true;
14516                        };
14517                        let crop = CGImage::with_image_in_rect(
14518                            Some(&cg_image),
14519                            CGRect::new(
14520                                CGPoint::new(src.origin.x, src.origin.y),
14521                                CGSize::new(src.size.width, src.size.height),
14522                            ),
14523                        );
14524                        let Some(crop) = crop else {
14525                            return true;
14526                        };
14527                        (Some(crop), dest)
14528                    }
14529                };
14530                if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
14531                    return true;
14532                }
14533                // The canvas is y-down and `CGContextDrawImage` puts the image's first row at the
14534                // TOP of `rect` only in a y-up space, so the image is drawn through a local flip.
14535                CGContext::save_g_state(Some(cg));
14536                CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
14537                CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
14538                CGContext::scale_ctm(Some(cg), 1.0, -1.0);
14539                CGContext::draw_image(
14540                    Some(cg),
14541                    CGRect::new(
14542                        CGPoint::new(0.0, 0.0),
14543                        CGSize::new(dest.size.width, dest.size.height),
14544                    ),
14545                    Some(cropped.as_deref().unwrap_or(&cg_image)),
14546                );
14547                CGContext::restore_g_state(Some(cg));
14548                true
14549            }
14550            _ => false,
14551        }
14552    }
14553
14554    /// Begin a replay on `cg`: fill and stroke colors are given as sRGB components from here on.
14555    fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
14556        use objc2_core_graphics::{CGColorSpace, CGContext};
14557        // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
14558        let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
14559        CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
14560        CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
14561    }
14562
14563    /// Add `shape` as the context's current path and say whether it fills even-odd, or `None` for
14564    /// a shape that takes the path object route (a rounded rect or an arc).
14565    fn cg_add_shape(ctx: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
14566        use day_spec::{PathSeg, Shape};
14567        use objc2_core_graphics::CGContext;
14568        CGContext::begin_path(Some(ctx));
14569        match shape {
14570            Shape::Rect(r) => CGContext::add_rect(Some(ctx), cg(*r)),
14571            Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(ctx), cg(*r)),
14572            Shape::Line(a, b) => {
14573                CGContext::move_to_point(Some(ctx), a.x, a.y);
14574                CGContext::add_line_to_point(Some(ctx), b.x, b.y);
14575            }
14576            Shape::Polygon(pts) => {
14577                let (first, rest) = pts.split_first()?;
14578                if rest.is_empty() {
14579                    return None;
14580                }
14581                CGContext::move_to_point(Some(ctx), first.x, first.y);
14582                for p in rest {
14583                    CGContext::add_line_to_point(Some(ctx), p.x, p.y);
14584                }
14585                CGContext::close_path(Some(ctx));
14586            }
14587            Shape::Path(path) => {
14588                if path.segs.is_empty() {
14589                    return None;
14590                }
14591                for seg in &path.segs {
14592                    match seg {
14593                        PathSeg::Move(a) => CGContext::move_to_point(Some(ctx), a.x, a.y),
14594                        PathSeg::Line(a) => CGContext::add_line_to_point(Some(ctx), a.x, a.y),
14595                        PathSeg::Quad(c, a) => {
14596                            CGContext::add_quad_curve_to_point(Some(ctx), c.x, c.y, a.x, a.y);
14597                        }
14598                        PathSeg::Cubic(c1, c2, a) => CGContext::add_curve_to_point(
14599                            Some(ctx),
14600                            c1.x,
14601                            c1.y,
14602                            c2.x,
14603                            c2.y,
14604                            a.x,
14605                            a.y,
14606                        ),
14607                        PathSeg::Close => CGContext::close_path(Some(ctx)),
14608                    }
14609                }
14610                return Some(path.rule == day_spec::FillRule::EvenOdd);
14611            }
14612            Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
14613        }
14614        Some(false)
14615    }
14616
14617    /// Put a [`day_spec::StrokeStyle`] on the context. Every field is set, because the graphics
14618    /// state keeps the previous stroke's cap, join and dash and a plain stroke must not inherit
14619    /// them.
14620    fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
14621        use day_spec::{LineCap, LineJoin};
14622        use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
14623        CGContext::set_line_width(Some(cg), style.width);
14624        CGContext::set_line_cap(
14625            Some(cg),
14626            match style.cap {
14627                LineCap::Butt => CGLineCap::Butt,
14628                LineCap::Round => CGLineCap::Round,
14629                LineCap::Square => CGLineCap::Square,
14630            },
14631        );
14632        CGContext::set_line_join(
14633            Some(cg),
14634            match style.join {
14635                LineJoin::Miter => CGLineJoin::Miter,
14636                LineJoin::Round => CGLineJoin::Round,
14637                LineJoin::Bevel => CGLineJoin::Bevel,
14638            },
14639        );
14640        CGContext::set_miter_limit(Some(cg), style.miter_limit);
14641        if style.dash.is_empty() {
14642            // SAFETY: a null pattern with a zero count clears the dash, per the CGContext docs.
14643            unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
14644        } else {
14645            let pattern: Vec<CGFloat> = style.dash.iter().map(|d| *d as CGFloat).collect();
14646            // SAFETY: `pattern` outlives the call, and `count` is its length.
14647            unsafe {
14648                CGContext::set_line_dash(
14649                    Some(cg),
14650                    style.dash_phase,
14651                    pattern.as_ptr(),
14652                    pattern.len(),
14653                );
14654            };
14655        }
14656    }
14657
14658    /// The renderer for one offscreen export, made on the UI thread: `preferredFormat` reads
14659    /// the main screen's traits. The format is pinned to the standard (sRGB) range, the space
14660    /// canvas colors are written in, so an encode of the export carries the bytes the drawing
14661    /// named rather than their Display P3 conversion.
14662    fn offscreen_renderer(
14663        size: Size,
14664        scale: f64,
14665    ) -> Retained<objc2_ui_kit::UIGraphicsImageRenderer> {
14666        use objc2::AllocAnyThread as _;
14667        // SAFETY: plain UIKit object construction on the UI thread.
14668        unsafe {
14669            let format = objc2_ui_kit::UIGraphicsImageRendererFormat::preferredFormat();
14670            format.setScale(scale);
14671            format.setOpaque(false);
14672            format.setPreferredRange(objc2_ui_kit::UIGraphicsImageRendererFormatRange::Standard);
14673            objc2_ui_kit::UIGraphicsImageRenderer::initWithSize_format(
14674                objc2_ui_kit::UIGraphicsImageRenderer::alloc(),
14675                CGSize::new(size.width, size.height),
14676                &format,
14677            )
14678        }
14679    }
14680
14681    /// Render `ops` offscreen at `scale` pixels per point through `renderer` (docs/canvas.md
14682    /// "Exporting"), on a painting thread: `UIGraphicsImageRenderer` is thread-safe, and it
14683    /// hands its block a UIKit context with the top-left origin a canvas view draws in, so the
14684    /// painter runs unchanged. The images and fonts the ops need are already this thread's
14685    /// (`OffscreenResources`).
14686    fn render_bitmap_image(
14687        renderer: &objc2_ui_kit::UIGraphicsImageRenderer,
14688        ops: Vec<day_spec::DrawOp>,
14689        size: Size,
14690        scale: f64,
14691    ) -> Result<(Retained<objc2_ui_kit::UIImage>, day_spec::BitmapInfo), day_spec::ExportError>
14692    {
14693        let (pw, ph) = day_spec::export_pixels(size, scale);
14694        // SAFETY: the renderer runs the block synchronously, inside `imageWithActions`, so the
14695        // ops it owns outlive every use.
14696        let image = unsafe {
14697            let block = block2::RcBlock::new(
14698                move |_ctx: core::ptr::NonNull<objc2_ui_kit::UIGraphicsImageRendererContext>| {
14699                    day_spec::ffi_guard::contain((), || paint_ops(&ops));
14700                },
14701            );
14702            renderer.imageWithActions(&raw const *block as *mut _)
14703        };
14704        // A renderer that could not allocate its backing store hands back an empty image
14705        // rather than an error; that is the only refusal UIKit reports here.
14706        // SAFETY: reading the immutable image's backing CGImage, on the thread that made it.
14707        if unsafe { image.CGImage() }.is_none() {
14708            return Err(day_spec::ExportError::Failed(format!(
14709                "UIGraphicsImageRenderer produced no image for {pw}x{ph} pixels"
14710            )));
14711        }
14712        let info = day_spec::BitmapInfo {
14713            pixels: Size::new(f64::from(pw), f64::from(ph)),
14714            scale,
14715            format: None,
14716            has_alpha: true,
14717        };
14718        Ok((image, info))
14719    }
14720
14721    /// Write `pages` into one PDF with `UIGraphicsPDFRenderer` (docs/canvas.md "Exporting").
14722    ///
14723    /// Each page opens with `beginPageWithBounds:pageInfo:` at its own size, and UIKit flips
14724    /// every page to the top-left origin, so the painter runs unchanged and stays vector: paths
14725    /// become PDF paths and text is set from embedded font subsets. Title and author go in the
14726    /// format's `documentInfo` under the Core Graphics keys, which land in the file's Info
14727    /// dictionary.
14728    fn render_pdf_data(
14729        pages: &[day_spec::PdfPage],
14730        info: &day_spec::PdfInfo,
14731    ) -> Result<Vec<u8>, day_spec::ExportError> {
14732        use objc2::AllocAnyThread as _;
14733        let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
14734        let rect = |s: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(s.width, s.height));
14735        let mut keys: Vec<&NSString> = Vec::new();
14736        let mut values: Vec<Retained<AnyObject>> = Vec::new();
14737        // SAFETY: `kCGPDFContextTitle`/`kCGPDFContextAuthor` are immutable CFString constants,
14738        // and CFString is toll-free bridged with NSString, so the pointer reads as one.
14739        let (title_key, author_key) = unsafe {
14740            (
14741                &*std::ptr::from_ref::<objc2_core_foundation::CFString>(
14742                    objc2_core_graphics::kCGPDFContextTitle,
14743                )
14744                .cast::<NSString>(),
14745                &*std::ptr::from_ref::<objc2_core_foundation::CFString>(
14746                    objc2_core_graphics::kCGPDFContextAuthor,
14747                )
14748                .cast::<NSString>(),
14749            )
14750        };
14751        for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
14752            if let Some(v) = value {
14753                keys.push(key);
14754                values.push(Retained::into_super(Retained::into_super(
14755                    NSString::from_str(v),
14756                )));
14757            }
14758        }
14759        let document_info = objc2_foundation::NSDictionary::from_retained_objects(&keys, &values);
14760        let page_info = objc2_foundation::NSDictionary::<NSString, AnyObject>::new();
14761        // SAFETY: main thread (a Toolkit duty). The dictionaries hold NSString keys and NSString
14762        // values, the types `documentInfo` and `pageInfo` declare. The renderer runs the block
14763        // synchronously, inside `PDFDataWithActions`.
14764        let data = unsafe {
14765            let format = objc2_ui_kit::UIGraphicsPDFRendererFormat::new();
14766            format.setDocumentInfo(&document_info);
14767            let renderer = objc2_ui_kit::UIGraphicsPDFRenderer::initWithBounds_format(
14768                objc2_ui_kit::UIGraphicsPDFRenderer::alloc(),
14769                rect(first.size),
14770                &format,
14771            );
14772            let pages = pages.to_vec();
14773            let block = block2::RcBlock::new(
14774                move |ctx: core::ptr::NonNull<objc2_ui_kit::UIGraphicsPDFRendererContext>| {
14775                    day_spec::ffi_guard::contain((), || {
14776                        let ctx = ctx.as_ref();
14777                        for page in &pages {
14778                            ctx.beginPageWithBounds_pageInfo(rect(page.size), &page_info);
14779                            paint_ops(&page.ops);
14780                        }
14781                    });
14782                },
14783            );
14784            renderer.PDFDataWithActions(&raw const *block as *mut _)
14785        };
14786        if data.is_empty() {
14787            return Err(day_spec::ExportError::Failed(
14788                "UIGraphicsPDFRenderer wrote no data".into(),
14789            ));
14790        }
14791        Ok(data.to_vec())
14792    }
14793
14794    fn snapshot_uikit(chrome: bool) -> Result<Vec<u8>, String> {
14795        let view: Retained<UIView> = with_key_scene(|e| {
14796            if chrome {
14797                Retained::from(&*e.window as &UIView)
14798            } else {
14799                e.root_view.clone()
14800            }
14801        })
14802        .ok_or("no window to capture")?;
14803        snapshot_view(&view)
14804    }
14805
14806    /// Rasterize one view (a window's content container — the primary root, or a secondary
14807    /// "window"'s host view, which on iOS is a fullscreen cover's content).
14808    fn snapshot_view(view: &UIView) -> Result<Vec<u8>, String> {
14809        // A view outside any window cannot be drawn with `afterScreenUpdates: true`: UIKit
14810        // moves it into a temporary window to force the commit, and when the view is
14811        // controller-backed its hierarchy check raises an NSException — which is foreign to
14812        // Rust and aborts the process. This happens to the PRIMARY root while a fullscreen
14813        // cover is presented (UIKit detaches the underlay), so refuse rather than raise.
14814        if unsafe { view.window() }.is_none() {
14815            return Err("view is not in a window".into());
14816        }
14817        let bounds = view.bounds();
14818        if bounds.size.width <= 0.0 || bounds.size.height <= 0.0 {
14819            return Err("zero-size window".into());
14820        }
14821        // SAFETY: main thread (a Toolkit duty); the renderer draws synchronously inside the block.
14822        let image: Retained<objc2_ui_kit::UIImage> = unsafe {
14823            use objc2::AllocAnyThread as _;
14824            // Captures are consumed as sRGB pixels by dayscript and image clients. The
14825            // display's preferred format can be Display P3, whose green bytes differ even
14826            // for an sRGB source image. Render into sRGB rather than merely retagging it.
14827            let traits = objc2_ui_kit::UITraitCollection::traitCollectionWithDisplayGamut(
14828                objc2_ui_kit::UIDisplayGamut::SRGB,
14829            );
14830            let format =
14831                objc2_ui_kit::UIGraphicsImageRendererFormat::formatForTraitCollection(&traits);
14832            format.setPreferredRange(objc2_ui_kit::UIGraphicsImageRendererFormatRange::Standard);
14833            let renderer = objc2_ui_kit::UIGraphicsImageRenderer::initWithBounds_format(
14834                objc2_ui_kit::UIGraphicsImageRenderer::alloc(),
14835                bounds,
14836                &format,
14837            );
14838            let v: Retained<UIView> = Retained::from(view);
14839            let block = block2::RcBlock::new(
14840                move |_ctx: core::ptr::NonNull<objc2_ui_kit::UIGraphicsImageRendererContext>| {
14841                    v.drawViewHierarchyInRect_afterScreenUpdates(v.bounds(), true);
14842                },
14843            );
14844            renderer.imageWithActions(&raw const *block as *mut _)
14845        };
14846        let data = image.png_representation().ok_or("png encode failed")?;
14847        Ok(data.to_vec())
14848    }
14849
14850    pub struct Uikit {
14851        registry: Registry<Uikit>,
14852        /// One pointer interaction per view carrying a `.cursor()` (docs/cursor.md), keyed by
14853        /// the view pointer. Removed when the cursor goes back to `Default`.
14854        pointers: HashMap<usize, (Retained<DayPointerDelegate>, Retained<UIPointerInteraction>)>,
14855    }
14856
14857    // ---------------------------------------------------------------------------
14858    // DayPointerDelegate — the `.cursor()` decorator on iPadOS (docs/cursor.md)
14859    // ---------------------------------------------------------------------------
14860
14861    struct PointerIvars {
14862        cursor: RefCell<Cursor>,
14863    }
14864
14865    // iPadOS draws pointer EFFECTS, not arrow shapes: a beam over text, a highlight or lift
14866    // over a target, or nothing. The delegate answers `styleForRegion:` with the nearest of
14867    // those for the requested shape, which is why `Cap::Cursor` answers Emulated.
14868    define_class!(
14869        #[unsafe(super(NSObject))]
14870        #[thread_kind = MainThreadOnly]
14871        #[name = "DayPointerDelegate"]
14872        #[ivars = PointerIvars]
14873        struct DayPointerDelegate;
14874
14875        unsafe impl NSObjectProtocol for DayPointerDelegate {}
14876
14877        unsafe impl UIPointerInteractionDelegate for DayPointerDelegate {
14878            #[unsafe(method_id(pointerInteraction:styleForRegion:))]
14879            fn style_for_region(
14880                &self,
14881                interaction: &UIPointerInteraction,
14882                region: &UIPointerRegion,
14883            ) -> Option<Retained<UIPointerStyle>> {
14884                self.style_for(interaction, region)
14885            }
14886        }
14887    );
14888
14889    impl DayPointerDelegate {
14890        /// The pointer style for the current cursor (the method above cannot return early
14891        /// inside `define_class!`, so the logic lives here).
14892        fn style_for(
14893            &self,
14894            interaction: &UIPointerInteraction,
14895            region: &UIPointerRegion,
14896        ) -> Option<Retained<UIPointerStyle>> {
14897            let mtm = MainThreadMarker::from(self);
14898            let cursor = self.ivars().cursor.borrow().clone();
14899            let rect = unsafe { region.rect() };
14900            let view = unsafe { interaction.view() };
14901            let preview = || {
14902                view.as_deref().map(|v| unsafe {
14903                    UITargetedPreview::initWithView(UITargetedPreview::alloc(mtm), v)
14904                })
14905            };
14906            Some(match cursor {
14907                Cursor::None => UIPointerStyle::hiddenPointerStyle(mtm),
14908                // An I-beam is a vertical beam as tall as the line; vertical text turns it.
14909                Cursor::Text => UIPointerStyle::styleWithShape_constrainedAxes(
14910                    &UIPointerShape::beamWithPreferredLength_axis(
14911                        rect.size.height,
14912                        UIAxis::Vertical,
14913                        mtm,
14914                    ),
14915                    UIAxis::Neither,
14916                ),
14917                Cursor::VerticalText => UIPointerStyle::styleWithShape_constrainedAxes(
14918                    &UIPointerShape::beamWithPreferredLength_axis(
14919                        rect.size.width,
14920                        UIAxis::Horizontal,
14921                        mtm,
14922                    ),
14923                    UIAxis::Neither,
14924                ),
14925                // Tap-to-activate and drag targets: the pointer morphs onto the view.
14926                Cursor::Pointer
14927                | Cursor::ContextMenu
14928                | Cursor::Copy
14929                | Cursor::Alias
14930                | Cursor::Grab
14931                | Cursor::Grabbing => {
14932                    let p = preview()?;
14933                    let effect: Retained<UIPointerEffect> =
14934                        Retained::into_super(UIPointerHighlightEffect::effectWithPreview(&p));
14935                    unsafe { UIPointerStyle::styleWithEffect_shape(&effect, None) }
14936                }
14937                Cursor::Move => {
14938                    let p = preview()?;
14939                    let effect: Retained<UIPointerEffect> =
14940                        Retained::into_super(UIPointerLiftEffect::effectWithPreview(&p));
14941                    unsafe { UIPointerStyle::styleWithEffect_shape(&effect, None) }
14942                }
14943                // Everything else keeps the system pointer; iPadOS has no such shapes.
14944                _ => return None,
14945            })
14946        }
14947    }
14948
14949    impl DayPointerDelegate {
14950        fn new(mtm: MainThreadMarker, cursor: Cursor) -> Retained<Self> {
14951            let this = Self::alloc(mtm).set_ivars(PointerIvars {
14952                cursor: RefCell::new(cursor),
14953            });
14954            unsafe { msg_send![super(this), init] }
14955        }
14956    }
14957
14958    impl Uikit {
14959        #[must_use]
14960        pub fn new() -> Self {
14961            let mut registry = Registry::default();
14962            for f in RENDERERS {
14963                registry.register(f());
14964            }
14965            Uikit {
14966                registry,
14967                pointers: HashMap::new(),
14968            }
14969        }
14970    }
14971
14972    impl Default for Uikit {
14973        fn default() -> Self {
14974            Self::new()
14975        }
14976    }
14977
14978    // The expect is an invariant, not a runtime failure mode: every Toolkit duty runs on the
14979    // main thread by contract (§8.1).
14980    pub(crate) fn mtm() -> MainThreadMarker {
14981        MainThreadMarker::new().expect("day-toolkit-uikit: not on the main thread")
14982    }
14983
14984    impl Uikit {
14985        /// The main-thread marker every UIKit call needs, for a standalone piece's renderer
14986        /// (docs/extending.md) — the same accessor day-toolkit-appkit offers. Sound for the same reason
14987        /// the free function above is: holding `&mut Uikit` means a Toolkit duty is running.
14988        #[must_use]
14989        pub fn mtm(&self) -> MainThreadMarker {
14990            mtm()
14991        }
14992    }
14993
14994    /// One animatable channel of a view as the duties set it (docs/tween.md "The animation
14995    /// contract"): the `CALayer` key paths UIKit's own setter writes.
14996    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
14997    enum Channel {
14998        /// `alpha`: the layer's `opacity`.
14999        Opacity,
15000        /// `transform`: the layer's 3D `transform`.
15001        Transform,
15002        /// The view's frame: the layer's `position` and `bounds`.
15003        Frame,
15004        /// A container's fill: the layer's `backgroundColor`.
15005        Background,
15006        /// A whole surface (`ContainerPatch::Surface`): the fill, the corner radius, the
15007        /// border's width and color, and the shadow's color and opacity.
15008        Surface,
15009    }
15010
15011    impl Channel {
15012        /// The layer key paths this channel animates.
15013        fn key_paths(self) -> &'static [&'static str] {
15014            match self {
15015                Channel::Opacity => &["opacity"],
15016                Channel::Transform => &["transform"],
15017                Channel::Frame => &["position", "bounds"],
15018                Channel::Background => &["backgroundColor"],
15019                Channel::Surface => &[
15020                    "backgroundColor",
15021                    "cornerRadius",
15022                    "borderWidth",
15023                    "borderColor",
15024                    "shadowColor",
15025                    "shadowOpacity",
15026                ],
15027            }
15028        }
15029    }
15030
15031    /// The name Day's run on `path` is added under. Its own, so a run UIKit adds for the same
15032    /// property (a `UIView` animation block keys by the bare path) is never replaced by it, and
15033    /// a new set replaces Day's run in flight.
15034    fn anim_key(path: &str) -> Retained<NSString> {
15035        NSString::from_str(&format!("day.{path}"))
15036    }
15037
15038    /// Whether a run on `channel` is in flight on `layer`: Day's own (`anim_key`) or one a
15039    /// `UIView` animation block added under the bare key path.
15040    fn channel_running(layer: &objc2_quartz_core::CALayer, channel: Channel) -> bool {
15041        channel.key_paths().iter().any(|path| {
15042            // SAFETY: looking up an animation by name only reads the layer's animation list.
15043            unsafe {
15044                layer.animationForKey(&anim_key(path)).is_some()
15045                    || layer.animationForKey(&NSString::from_str(path)).is_some()
15046            }
15047        })
15048    }
15049
15050    /// The value `layer` holds for `path`, boxed the way Core Animation boxes it (`NSNumber`,
15051    /// `NSValue`, `CGColorRef`); `None` for a nil color.
15052    fn layer_value(layer: &objc2_quartz_core::CALayer, path: &str) -> Option<Retained<AnyObject>> {
15053        let key = NSString::from_str(path);
15054        // SAFETY: every path here names an animatable `CALayer` property, which key-value
15055        // coding answers with an object, or nil for a missing color.
15056        unsafe { msg_send![layer, valueForKey: &*key] }
15057    }
15058
15059    /// The exact Bézier for a Day easing curve (`motion_curve::bezier_points`).
15060    fn timing_function(curve: Curve) -> Retained<objc2_quartz_core::CAMediaTimingFunction> {
15061        let (x1, y1, x2, y2) = crate::motion_curve::bezier_points(curve);
15062        #[expect(
15063            clippy::cast_possible_truncation,
15064            reason = "Core Animation takes the control points as floats"
15065        )]
15066        objc2_quartz_core::CAMediaTimingFunction::functionWithControlPoints(
15067            x1 as f32, y1 as f32, x2 as f32, y2 as f32,
15068        )
15069    }
15070
15071    /// Set one channel of `view` (docs/tween.md "The animation contract"). `apply` runs UIKit's
15072    /// own setters, which write the layer's model values at once; with `anim`, an explicit Core
15073    /// Animation run then plays from the value displayed now to the new model value:
15074    ///
15075    /// - delay: `beginTime` in the future with a backwards fill, so the start shows through it;
15076    /// - repeat and autoreverse: `repeatCount` and `autoreverses` (Core Animation counts a
15077    ///   forward and a backward pass as one repeat, so an autoreversing run counts halves);
15078    /// - a spring: `CASpringAnimation` with mass 1 and `Curve::spring_constants`, released at
15079    ///   rest, over the spec's duration (its settle time); an easing curve: its exact Bézier;
15080    /// - retarget: the start is read from the presentation layer before the run in flight is
15081    ///   removed; a plain set removes Day's run, one that repeats forever included;
15082    /// - rest: the model value is the target from the start, so once a finite run ends (and is
15083    ///   removed) the target shows, after a backward last cycle too.
15084    fn animate_channel(
15085        view: &UIView,
15086        channel: Channel,
15087        anim: Option<&AnimSpec>,
15088        apply: impl FnOnce(),
15089    ) {
15090        use objc2_quartz_core::CAMediaTiming as _;
15091        let layer = view.layer();
15092        let paths = channel.key_paths();
15093        let shown: Vec<Option<Retained<AnyObject>>> = if anim.is_some() {
15094            // SAFETY: the presentation layer is a read-only copy of what is on screen.
15095            let presentation = unsafe { layer.presentationLayer() };
15096            let source = presentation.as_deref().unwrap_or(&layer);
15097            paths.iter().map(|p| layer_value(source, p)).collect()
15098        } else {
15099            Vec::new()
15100        };
15101        for path in paths {
15102            layer.removeAnimationForKey(&anim_key(path));
15103        }
15104        apply();
15105        let Some(spec) = anim else {
15106            return;
15107        };
15108        if spec.duration_ms == 0 && spec.delay_ms == 0 {
15109            return;
15110        }
15111        let now = layer.convertTime_fromLayer(objc2_quartz_core::CACurrentMediaTime(), None);
15112        for (path, from) in paths.iter().zip(shown) {
15113            // A fill appearing or going away (nil on either side) applies at once.
15114            let (Some(from), Some(to)) = (from, layer_value(&layer, path)) else {
15115                continue;
15116            };
15117            let run = channel_run(path, &from, &to, spec);
15118            run.setBeginTime(
15119                now + if spec.duration_ms == 0 {
15120                    0.0
15121                } else {
15122                    spec.delay_secs()
15123                },
15124            );
15125            // SAFETY: a framework constant.
15126            run.setFillMode(unsafe { objc2_quartz_core::kCAFillModeBackwards });
15127            run.setRemovedOnCompletion(true);
15128            layer.addAnimation_forKey(&run, Some(&anim_key(path)));
15129        }
15130    }
15131
15132    /// The run for `path` from `from` to `to`: one cycle's animation with the repeat applied.
15133    fn channel_run(
15134        path: &str,
15135        from: &AnyObject,
15136        to: &AnyObject,
15137        spec: &AnimSpec,
15138    ) -> Retained<objc2_quartz_core::CAAnimation> {
15139        use objc2_quartz_core::{CABasicAnimation, CAMediaTiming as _, CASpringAnimation};
15140        let key = NSString::from_str(path);
15141        if spec.duration_ms == 0 {
15142            // No cycle, only a delay: hold the start for it, then the model value shows.
15143            let hold = CABasicAnimation::animationWithKeyPath(Some(&key));
15144            // SAFETY: the start is the layer's own boxed value for `path`.
15145            unsafe {
15146                hold.setFromValue(Some(from));
15147                hold.setToValue(Some(from));
15148            }
15149            hold.setDuration(spec.delay_secs());
15150            return Retained::into_super(Retained::into_super(hold));
15151        }
15152        let run: Retained<objc2_quartz_core::CAAnimation> = match spec.curve.spring_constants() {
15153            // A spring on a color is sampled with its progress held to 0..=1, so every
15154            // color shown lies between the two ends (docs/tween.md rule 8).
15155            Some(_) if path.ends_with("Color") => color_keyframes(&key, from, to, spec),
15156            Some((stiffness, damping)) => {
15157                let spring = CASpringAnimation::animationWithKeyPath(Some(&key));
15158                spring.setMass(1.0);
15159                spring.setStiffness(stiffness);
15160                spring.setDamping(damping);
15161                spring.setInitialVelocity(0.0);
15162                // Over-damped (ratio above 1) needs iOS 17's switch; below it Core
15163                // Animation plays such a spring critically damped.
15164                if spring.respondsToSelector(sel!(setAllowsOverdamping:)) {
15165                    spring.setAllowsOverdamping(true);
15166                }
15167                // SAFETY: both ends are the layer's own boxed values for `path`.
15168                unsafe {
15169                    spring.setFromValue(Some(from));
15170                    spring.setToValue(Some(to));
15171                }
15172                Retained::into_super(Retained::into_super(Retained::into_super(spring)))
15173            }
15174            None => {
15175                let basic = CABasicAnimation::animationWithKeyPath(Some(&key));
15176                // SAFETY: both ends are the layer's own boxed values for `path`.
15177                unsafe {
15178                    basic.setFromValue(Some(from));
15179                    basic.setToValue(Some(to));
15180                }
15181                basic.setTimingFunction(Some(&timing_function(spec.curve)));
15182                Retained::into_super(Retained::into_super(basic))
15183            }
15184        };
15185        run.setDuration(spec.duration_secs());
15186        run.setAutoreverses(spec.autoreverse);
15187        run.setRepeatCount(crate::motion_curve::repeat_count(
15188            spec.cycles(),
15189            spec.autoreverse,
15190        ));
15191        run
15192    }
15193
15194    /// The sRGB components of a boxed `CGColorRef`, as UIKit reads any color.
15195    fn boxed_color(value: &AnyObject) -> Option<day_spec::Color> {
15196        // SAFETY: the value came from a `backgroundColor` key, which Core Animation boxes as a
15197        // `CGColorRef`, a CF object bridged to `id`.
15198        let cg = unsafe { &*std::ptr::from_ref(value).cast::<objc2_core_graphics::CGColor>() };
15199        cgcolor_components(cg)
15200    }
15201
15202    /// The sRGB components of `cg`, as UIKit reads any color.
15203    fn cgcolor_components(cg: &objc2_core_graphics::CGColor) -> Option<day_spec::Color> {
15204        uicolor_components(&UIColor::colorWithCGColor(cg))
15205    }
15206
15207    /// A sampled color run: one keyframe per [`AnimSpec::keyframes`] entry, blended in sRGB
15208    /// with the progress held to `0..=1`.
15209    fn color_keyframes(
15210        key: &NSString,
15211        from: &AnyObject,
15212        to: &AnyObject,
15213        spec: &AnimSpec,
15214    ) -> Retained<objc2_quartz_core::CAAnimation> {
15215        let frames = objc2_quartz_core::CAKeyframeAnimation::animationWithKeyPath(Some(key));
15216        let samples = spec.keyframes();
15217        let ends = boxed_color(from).zip(boxed_color(to));
15218        let colors: Vec<_> = samples
15219            .iter()
15220            .map(|k| {
15221                let p = k.progress.clamp(0.0, 1.0);
15222                let c = ends.map_or(day_spec::Color::rgba(0.0, 0.0, 0.0, 0.0), |(a, b)| {
15223                    day_spec::Color::rgba(
15224                        a.r + (b.r - a.r) * p,
15225                        a.g + (b.g - a.g) * p,
15226                        a.b + (b.b - a.b) * p,
15227                        a.a + (b.a - a.a) * p,
15228                    )
15229                });
15230                cgcolor(c)
15231            })
15232            .collect();
15233        let values: Vec<&AnyObject> = colors
15234            .iter()
15235            // SAFETY: a CGColor is a CF object, bridged to `id`.
15236            .map(|c| unsafe {
15237                &*std::ptr::from_ref::<objc2_core_graphics::CGColor>(c).cast::<AnyObject>()
15238            })
15239            .collect();
15240        let times: Vec<Retained<objc2_foundation::NSNumber>> = samples
15241            .iter()
15242            .map(|k| objc2_foundation::NSNumber::new_f64(k.offset))
15243            .collect();
15244        if ends.is_some() {
15245            // SAFETY: the values are colors for a `backgroundColor` run.
15246            unsafe { frames.setValues(Some(&objc2_foundation::NSArray::from_slice(&values))) };
15247            frames.setKeyTimes(Some(&objc2_foundation::NSArray::from_retained_slice(
15248                &times,
15249            )));
15250        }
15251        // SAFETY: a framework constant.
15252        frames.setCalculationMode(unsafe { objc2_quartz_core::kCAAnimationLinear });
15253        Retained::into_super(Retained::into_super(frames))
15254    }
15255
15256    /// Build UIKit's `CGAffineTransform` for a Day [`Transform`], composed scale → rotate →
15257    /// translate about the view's layer anchor (default center, matching `Transform`'s default
15258    /// anchor). Non-center anchors approximate: translation is exact, scale/rotation stay about
15259    /// center (§8.4 — arbitrary-anchor transforms need a layer anchorPoint change, a later refinement).
15260    fn cgaffine(t: Transform) -> CGAffineTransform {
15261        let th = t.rotation.radians();
15262        let (s, c) = th.sin_cos();
15263        CGAffineTransform {
15264            a: t.sx * c,
15265            b: t.sx * s,
15266            c: -t.sy * s,
15267            d: t.sy * c,
15268            tx: t.tx,
15269            ty: t.ty,
15270        }
15271    }
15272
15273    /// Day `Role` → the `UIAccessibility` trait bit to add (explicit canvas/custom roles only —
15274    /// native controls self-describe, §13). UIKit has no toggle/meter trait, so those are `None`.
15275    fn ui_traits(role: day_spec::Role) -> Option<objc2_ui_kit::UIAccessibilityTraits> {
15276        use day_spec::Role;
15277        use objc2_ui_kit::{
15278            UIAccessibilityTraitAdjustable, UIAccessibilityTraitButton, UIAccessibilityTraitHeader,
15279            UIAccessibilityTraitImage, UIAccessibilityTraitTabBar,
15280        };
15281        unsafe {
15282            Some(match role {
15283                // UIKit has no trait for one tab: it is a button, and the selected trait
15284                // (`set_a11y`'s `selected`) says which one is current. The strip is a tab bar.
15285                Role::Button | Role::Toggle | Role::Tab => UIAccessibilityTraitButton,
15286                Role::TabList => UIAccessibilityTraitTabBar,
15287                Role::Slider => UIAccessibilityTraitAdjustable,
15288                Role::Heading(_) => UIAccessibilityTraitHeader,
15289                Role::Image => UIAccessibilityTraitImage,
15290                _ => return None,
15291            })
15292        }
15293    }
15294
15295    /// Native `UIAccessibility` traits → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
15296    fn day_role_from_traits(t: objc2_ui_kit::UIAccessibilityTraits) -> day_spec::Role {
15297        use day_spec::Role;
15298        use objc2_ui_kit::{
15299            UIAccessibilityTraitAdjustable, UIAccessibilityTraitButton, UIAccessibilityTraitHeader,
15300            UIAccessibilityTraitImage, UIAccessibilityTraitTabBar,
15301        };
15302        unsafe {
15303            if t & UIAccessibilityTraitAdjustable != 0 {
15304                Role::Slider
15305            } else if t & UIAccessibilityTraitTabBar != 0 {
15306                Role::TabList
15307            } else if t & UIAccessibilityTraitHeader != 0 {
15308                Role::Heading(0)
15309            } else if t & UIAccessibilityTraitImage != 0 {
15310                Role::Image
15311            } else if t & UIAccessibilityTraitButton != 0 {
15312                Role::Button
15313            } else {
15314                Role::None
15315            }
15316        }
15317    }
15318
15319    /// The iOS native semantic text style for a logical [`Font`] (`None` for a custom size).
15320    /// `UIFont.preferredFont(forTextStyle:)` IS Dynamic Type — it scales with the user's chosen text
15321    /// size in Settings ▸ Accessibility ▸ Display & Text Size ▸ Larger Text.
15322    fn ui_text_style(f: Font) -> Option<&'static objc2_ui_kit::UIFontTextStyle> {
15323        use objc2_ui_kit::*;
15324        unsafe {
15325            Some(match f {
15326                Font::LargeTitle => UIFontTextStyleLargeTitle,
15327                Font::Title => UIFontTextStyleTitle1,
15328                Font::Title2 => UIFontTextStyleTitle2,
15329                Font::Title3 => UIFontTextStyleTitle3,
15330                Font::Headline => UIFontTextStyleHeadline,
15331                Font::Subheadline => UIFontTextStyleSubheadline,
15332                Font::Body => UIFontTextStyleBody,
15333                Font::Callout => UIFontTextStyleCallout,
15334                Font::Footnote => UIFontTextStyleFootnote,
15335                Font::Caption => UIFontTextStyleCaption1,
15336                Font::Caption2 => UIFontTextStyleCaption2,
15337                Font::System(_) | Font::Custom(..) => return None,
15338            })
15339        }
15340    }
15341
15342    /// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
15343    /// else a descriptor for the family with the bold/italic symbolic traits the weight and
15344    /// slant ask for (UIKit picks the family's nearest face, or synthesizes), falling back to a
15345    /// PostScript/full-name lookup (a bundled font registered in `run`) and then to the system
15346    /// font with one warning.
15347    fn canvas_uifont(size: f64, font: &day_spec::CanvasFont) -> Retained<objc2_ui_kit::UIFont> {
15348        use objc2_ui_kit::*;
15349        // A painting thread draws with the fonts the UI thread resolved for this export
15350        // (`OffscreenResources`); on the UI thread the table is empty and the lookup falls
15351        // through to UIKit.
15352        let prepared = OFFSCREEN_FONTS.with(|t| {
15353            t.borrow()
15354                .iter()
15355                .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
15356                .map(|(_, f)| f.clone())
15357        });
15358        if let Some(f) = prepared {
15359            return f;
15360        }
15361        let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
15362        let mut traits = UIFontDescriptorSymbolicTraits::empty();
15363        if weight >= day_spec::FontWeight::Semibold {
15364            traits |= UIFontDescriptorSymbolicTraits::TraitBold;
15365        }
15366        if font.italic {
15367            traits |= UIFontDescriptorSymbolicTraits::TraitItalic;
15368        }
15369        let with_traits = |base: Retained<UIFont>| -> Retained<UIFont> {
15370            if traits.is_empty() {
15371                return base;
15372            }
15373            unsafe {
15374                let desc = base.fontDescriptor();
15375                match desc.fontDescriptorWithSymbolicTraits(desc.symbolicTraits() | traits) {
15376                    Some(d2) => UIFont::fontWithDescriptor_size(&d2, size),
15377                    None => base,
15378                }
15379            }
15380        };
15381        let Some(family) = font.family.as_deref() else {
15382            let base = unsafe { UIFont::systemFontOfSize_weight(size, ui_weight(weight)) };
15383            // The weight is already exact; only the slant is left to the descriptor.
15384            return if font.italic {
15385                unsafe {
15386                    let desc = base.fontDescriptor();
15387                    match desc.fontDescriptorWithSymbolicTraits(
15388                        desc.symbolicTraits() | UIFontDescriptorSymbolicTraits::TraitItalic,
15389                    ) {
15390                        Some(d2) => UIFont::fontWithDescriptor_size(&d2, size),
15391                        None => base,
15392                    }
15393                }
15394            } else {
15395                base
15396            };
15397        };
15398        let ns_family = NSString::from_str(family);
15399        let known = unsafe { UIFont::fontNamesForFamilyName(&ns_family) }.count() > 0;
15400        if known {
15401            let keys: [&NSString; 1] = [unsafe { UIFontDescriptorFamilyAttribute }];
15402            let objs: [&AnyObject; 1] = [ns_family.as_ref() as &AnyObject];
15403            let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
15404            let desc = unsafe { UIFontDescriptor::fontDescriptorWithFontAttributes(&attrs) };
15405            let desc = if traits.is_empty() {
15406                desc
15407            } else {
15408                unsafe { desc.fontDescriptorWithSymbolicTraits(traits) }.unwrap_or(desc)
15409            };
15410            return unsafe { UIFont::fontWithDescriptor_size(&desc, size) };
15411        }
15412        if let Some(f) = unsafe { UIFont::fontWithName_size(&ns_family, size) } {
15413            return with_traits(f);
15414        }
15415        log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
15416        unsafe { UIFont::systemFontOfSize_weight(size, ui_weight(weight)) }
15417    }
15418
15419    /// The attribute dictionary canvas text draws and measures with (the same one, so
15420    /// `measure_text` and `replay` agree on the line box).
15421    fn canvas_text_attrs(
15422        font: &objc2_ui_kit::UIFont,
15423        color: day_spec::Color,
15424    ) -> Retained<objc2_foundation::NSDictionary<NSString, AnyObject>> {
15425        let col = uicolor(color);
15426        // SAFETY: both are UIKit's own attribute-name constants, valid for the process lifetime.
15427        let keys: [&NSString; 2] = unsafe {
15428            [
15429                objc2_ui_kit::NSFontAttributeName,
15430                objc2_ui_kit::NSForegroundColorAttributeName,
15431            ]
15432        };
15433        let objs: [&AnyObject; 2] = [font as &AnyObject, col.as_ref() as &AnyObject];
15434        objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
15435    }
15436
15437    /// The Day rung nearest a `UIFontWeightTrait` value (−1 … 1; the constants UIKit documents
15438    /// for its own weights: ultraLight −0.8, thin −0.6, light −0.4, regular 0, medium 0.23,
15439    /// semibold 0.3, bold 0.4, heavy 0.56, black 0.62).
15440    fn weight_from_trait(t: f64) -> day_spec::FontWeight {
15441        use day_spec::FontWeight as W;
15442        match t {
15443            t if t <= -0.7 => W::UltraLight,
15444            t if t <= -0.5 => W::Thin,
15445            t if t <= -0.2 => W::Light,
15446            t if t < 0.15 => W::Regular,
15447            t if t < 0.27 => W::Medium,
15448            t if t < 0.35 => W::Semibold,
15449            t if t < 0.5 => W::Bold,
15450            t if t < 0.6 => W::Heavy,
15451            _ => W::Black,
15452        }
15453    }
15454
15455    fn ui_weight(w: day_spec::FontWeight) -> objc2_ui_kit::UIFontWeight {
15456        use day_spec::FontWeight as W;
15457        use objc2_ui_kit::*;
15458        unsafe {
15459            match w {
15460                W::UltraLight => UIFontWeightUltraLight,
15461                W::Thin => UIFontWeightThin,
15462                W::Light => UIFontWeightLight,
15463                W::Regular => UIFontWeightRegular,
15464                W::Medium => UIFontWeightMedium,
15465                W::Semibold => UIFontWeightSemibold,
15466                W::Bold => UIFontWeightBold,
15467                W::Heavy => UIFontWeightHeavy,
15468                W::Black => UIFontWeightBlack,
15469            }
15470        }
15471    }
15472
15473    /// The iOS Dynamic Type DEFAULT (content size = Large) point size for a semantic style — the base
15474    /// that `UIFontMetrics` scales from. Used to build weighted fonts that still auto-scale.
15475    fn ui_default_size(f: Font) -> objc2_core_foundation::CGFloat {
15476        match f {
15477            Font::LargeTitle => 34.0,
15478            Font::Title => 28.0,
15479            Font::Title2 => 22.0,
15480            Font::Title3 => 20.0,
15481            #[expect(
15482                clippy::match_same_arms,
15483                reason = "one row per text style, in the order of Apple's Dynamic Type table"
15484            )]
15485            Font::Headline => 17.0,
15486            Font::Subheadline => 15.0,
15487            Font::Body => 17.0,
15488            Font::Callout => 16.0,
15489            Font::Footnote => 13.0,
15490            Font::Caption => 12.0,
15491            Font::Caption2 => 11.0,
15492            Font::System(pt) | Font::Custom(_, pt) => pt,
15493        }
15494    }
15495
15496    /// Resolve a [`day_spec::FontSpec`] to its concrete `UIFont` — semantic style, weight,
15497    /// italic, tabular figures, all Dynamic Type scaled. Shared by the `UILabel` path and the
15498    /// read-only `UITextView` a `.selectable()` label swaps to (`set_selectable`).
15499    fn resolve_font(spec: day_spec::FontSpec) -> Retained<objc2_ui_kit::UIFont> {
15500        use objc2_ui_kit::*;
15501        let base: Retained<UIFont> = match spec.style {
15502            Font::System(pt) => unsafe {
15503                // A custom size, weighted, then run through UIFontMetrics so it also honors Dynamic
15504                // Type (accessibility text scale) instead of being a fixed pixel size.
15505                let w = spec.weight.map_or(UIFontWeightRegular, ui_weight);
15506                let raw = UIFont::systemFontOfSize_weight(pt, w);
15507                UIFontMetrics::metricsForTextStyle(UIFontTextStyleBody).scaledFontForFont(&raw)
15508            },
15509            // A bundled family (§18.4): registered at launch from the DayPieces bundle (and
15510            // listed in UIAppFonts), then scaled through UIFontMetrics like Font::System so it
15511            // tracks Dynamic Type. Unknown families fall back to the system font, loudly. A
15512            // weight override maps to the bold trait below (the family decides what it has).
15513            Font::Custom(name, pt) => unsafe {
15514                let raw = if let Some(f) = UIFont::fontWithName_size(&NSString::from_str(name), pt)
15515                {
15516                    f
15517                } else {
15518                    log::warn!(
15519                        "unknown font family {name:?} — falling back to the system \
15520                         font (is the file in the project's fonts/ directory?)"
15521                    );
15522                    let w = spec.weight.map_or(UIFontWeightRegular, ui_weight);
15523                    UIFont::systemFontOfSize_weight(pt, w)
15524                };
15525                UIFontMetrics::metricsForTextStyle(UIFontTextStyleBody).scaledFontForFont(&raw)
15526            },
15527            style => unsafe {
15528                let ts = ui_text_style(style).expect("semantic style");
15529                match spec.weight {
15530                    // No weight override → preferredFont, which is Dynamic Type (auto-scales live).
15531                    None => UIFont::preferredFontForTextStyle(ts),
15532                    // A weight override: build the weighted system font at the style's DEFAULT size,
15533                    // then run it through the style's UIFontMetrics so it also auto-scales with Dynamic
15534                    // Type (a bare `systemFont(ofSize:weight:)` is a fixed size and would NOT re-scale).
15535                    Some(w) => {
15536                        let raw =
15537                            UIFont::systemFontOfSize_weight(ui_default_size(style), ui_weight(w));
15538                        UIFontMetrics::metricsForTextStyle(ts).scaledFontForFont(&raw)
15539                    }
15540                }
15541            },
15542        };
15543        // Symbolic-trait tweaks on the resolved font: italic, plus synthesized bold for a custom
15544        // family with a heavy weight override (system fonts got their weight above).
15545        let mut extra = UIFontDescriptorSymbolicTraits::empty();
15546        if spec.italic {
15547            extra |= UIFontDescriptorSymbolicTraits::TraitItalic;
15548        }
15549        if matches!(spec.style, Font::Custom(..))
15550            && spec
15551                .weight
15552                .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
15553        {
15554            extra |= UIFontDescriptorSymbolicTraits::TraitBold;
15555        }
15556        let font = if extra.is_empty() {
15557            base
15558        } else {
15559            unsafe {
15560                let desc = base.fontDescriptor();
15561                let traits = desc.symbolicTraits() | extra;
15562                match desc.fontDescriptorWithSymbolicTraits(traits) {
15563                    Some(d2) => UIFont::fontWithDescriptor_size(&d2, base.pointSize()),
15564                    None => base,
15565                }
15566            }
15567        };
15568        // Tabular figures: UIKit exposes them as a whole font (like AppKit), so re-pick the
15569        // system face at the resolved size/weight. System styles only — a bundled family keeps
15570        // its own figures rather than being silently swapped for the system typeface. The result
15571        // still goes through UIFontMetrics below, so Dynamic Type keeps working.
15572        let font = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
15573            unsafe {
15574                let w = spec.weight.map_or(UIFontWeightRegular, ui_weight);
15575                let raw = UIFont::monospacedDigitSystemFontOfSize_weight(font.pointSize(), w);
15576                UIFontMetrics::metricsForTextStyle(UIFontTextStyleBody).scaledFontForFont(&raw)
15577            }
15578        } else {
15579            font
15580        };
15581        // Monospace, by the same rule and for the same reason (docs/text-runs.md): a whole face
15582        // on UIKit too, kept inside UIFontMetrics so inline code still scales with Dynamic Type.
15583        let font = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
15584            unsafe {
15585                let w = spec.weight.map_or(UIFontWeightRegular, ui_weight);
15586                let raw = UIFont::monospacedSystemFontOfSize_weight(font.pointSize(), w);
15587                UIFontMetrics::metricsForTextStyle(UIFontTextStyleBody).scaledFontForFont(&raw)
15588            }
15589        } else {
15590            font
15591        };
15592        // Relative size (`FontSpec::scale`), applied last over whatever face the traits settled
15593        // on. `fontWithSize:` keeps the typeface, and because the size it scales is the one
15594        // Dynamic Type already produced, a scaled run keeps tracking the reader's setting.
15595        #[expect(
15596            clippy::float_cmp,
15597            reason = "1.0 is the exact unscaled default of `FontSpec::scale`"
15598        )]
15599        let unscaled = spec.scale == 1.0;
15600        let font = if unscaled {
15601            font
15602        } else {
15603            unsafe { font.fontWithSize(spec.resolved_points(font.pointSize())) }
15604        };
15605        with_font_features(font, spec)
15606    }
15607
15608    /// Small capitals and oldstyle figures (docs/text-runs.md "Font features"): AAT feature
15609    /// settings on the font descriptor, `kLowerCaseType`/`kLowerCaseSmallCapsSelector` (37/1)
15610    /// and `kNumberCaseType`/`kLowerCaseNumbersSelector` (21/0), appended to the settings the
15611    /// face already carries (the monospaced-digit setting of a tabular face). A face without
15612    /// the feature draws its ordinary glyphs; nothing is synthesized.
15613    fn with_font_features(
15614        font: Retained<objc2_ui_kit::UIFont>,
15615        spec: day_spec::FontSpec,
15616    ) -> Retained<objc2_ui_kit::UIFont> {
15617        use objc2_foundation::{NSArray, NSDictionary, NSNumber};
15618        use objc2_ui_kit::{
15619            UIFont, UIFontDescriptorFeatureSettingsAttribute, UIFontFeatureSelectorIdentifierKey,
15620            UIFontFeatureTypeIdentifierKey,
15621        };
15622        let wanted: Vec<(i64, i64)> =
15623            [(spec.small_caps, (37, 1)), (spec.oldstyle_figures, (21, 0))]
15624                .into_iter()
15625                .filter_map(|(on, pair)| on.then_some(pair))
15626                .collect();
15627        if wanted.is_empty() {
15628            return font;
15629        }
15630        unsafe {
15631            let desc = font.fontDescriptor();
15632            let mut settings: Vec<Retained<AnyObject>> = desc
15633                .objectForKey(UIFontDescriptorFeatureSettingsAttribute)
15634                .and_then(|v| v.downcast::<NSArray>().ok())
15635                .map_or_else(Vec::new, |a| a.to_vec());
15636            for (kind, selector) in wanted {
15637                let (kind, selector) = (NSNumber::new_i64(kind), NSNumber::new_i64(selector));
15638                let setting = NSDictionary::<NSString, NSNumber>::from_slices(
15639                    &[
15640                        UIFontFeatureTypeIdentifierKey,
15641                        UIFontFeatureSelectorIdentifierKey,
15642                    ],
15643                    &[&*kind, &*selector],
15644                );
15645                settings.push(setting.into());
15646            }
15647            let settings = NSArray::from_retained_slice(&settings);
15648            let attrs = NSDictionary::<NSString, AnyObject>::from_slices(
15649                &[UIFontDescriptorFeatureSettingsAttribute],
15650                &[settings.as_ref()],
15651            );
15652            let desc = desc.fontDescriptorByAddingAttributes(&attrs);
15653            // Size 0 keeps the descriptor's own size.
15654            UIFont::fontWithDescriptor_size(&desc, 0.0)
15655        }
15656    }
15657
15658    /// Build a `UILabel`'s attributed text from its runs (docs/text-runs.md).
15659    ///
15660    /// Byte ranges convert to UTF-16 per run: `NSAttributedString` indexes UTF-16, and any
15661    /// emoji or CJK in the string makes the two disagree.
15662    fn attributed_label(
15663        text: &str,
15664        base_font: &objc2_ui_kit::UIFont,
15665        color: Option<day_spec::Ink>,
15666        runs: &[day_spec::TextRun],
15667    ) -> Retained<objc2_foundation::NSAttributedString> {
15668        use objc2::AllocAnyThread as _;
15669        use objc2_foundation::{NSMutableAttributedString, NSRange};
15670        let ns = NSString::from_str(text);
15671        let s = unsafe {
15672            NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
15673        };
15674        let whole = NSRange::new(0, ns.length());
15675        unsafe {
15676            s.addAttribute_value_range(objc2_ui_kit::NSFontAttributeName, base_font, whole);
15677            // Always a foreground: a UITextView draws an attributed range with no color
15678            // attribute in black, which is invisible in dark mode. `labelColor` is the adaptive
15679            // default a plain label would have used.
15680            let fg = color.map_or_else(UIColor::labelColor, uiink);
15681            s.addAttribute_value_range(objc2_ui_kit::NSForegroundColorAttributeName, &fg, whole);
15682        }
15683        for r in runs {
15684            let Some(range) = utf16_range(text, &r.range) else {
15685                continue;
15686            };
15687            unsafe {
15688                s.addAttribute_value_range(
15689                    objc2_ui_kit::NSFontAttributeName,
15690                    &resolve_font(r.font),
15691                    range,
15692                );
15693                if let Some(c) = r.color {
15694                    s.addAttribute_value_range(
15695                        objc2_ui_kit::NSForegroundColorAttributeName,
15696                        &uiink(c),
15697                        range,
15698                    );
15699                }
15700                if let Some(c) = r.background {
15701                    s.addAttribute_value_range(
15702                        objc2_ui_kit::NSBackgroundColorAttributeName,
15703                        &uiink(c),
15704                        range,
15705                    );
15706                }
15707                // A line's color is its own attribute; without one UIKit draws the line in
15708                // the run's text color, which is what `color: None` means.
15709                if let Some(d) = r.underline {
15710                    let style = objc2_foundation::NSNumber::new_i64(ns_underline(d));
15711                    s.addAttribute_value_range(
15712                        objc2_ui_kit::NSUnderlineStyleAttributeName,
15713                        &style,
15714                        range,
15715                    );
15716                    if let Some(c) = d.color {
15717                        s.addAttribute_value_range(
15718                            objc2_ui_kit::NSUnderlineColorAttributeName,
15719                            &uiink(c),
15720                            range,
15721                        );
15722                    }
15723                }
15724                if let Some(d) = r.strikethrough {
15725                    let style = objc2_foundation::NSNumber::new_i64(ns_underline(d));
15726                    s.addAttribute_value_range(
15727                        objc2_ui_kit::NSStrikethroughStyleAttributeName,
15728                        &style,
15729                        range,
15730                    );
15731                    if let Some(c) = d.color {
15732                        s.addAttribute_value_range(
15733                            objc2_ui_kit::NSStrikethroughColorAttributeName,
15734                            &uiink(c),
15735                            range,
15736                        );
15737                    }
15738                }
15739                if let Some(url) = r.link.as_deref() {
15740                    // Drawn as a link. ACTIVATION needs a UITextView (a UILabel has no hit
15741                    // testing at all), which is Phase 4 — `Cap::TextLinks` stays Unsupported.
15742                    let value = NSString::from_str(url);
15743                    s.addAttribute_value_range(objc2_ui_kit::NSLinkAttributeName, &value, range);
15744                }
15745            }
15746        }
15747        s.into_super()
15748    }
15749
15750    /// A [`Decoration`](day_spec::Decoration)'s style as an `NSUnderlineStyle` bitmask, for an
15751    /// underline or a strikethrough alike — the line style in the low byte, the pattern in the
15752    /// second, the same encoding AppKit uses. UIKit has no public wave pattern, so wavy keeps
15753    /// the dash-dot-dot pattern (`0x0400`) this backend has always drawn for it.
15754    fn ns_underline(d: day_spec::Decoration) -> i64 {
15755        use day_spec::DecorationStyle as U;
15756        match d.style {
15757            U::Single => 0x01,
15758            U::Double => 0x09,
15759            U::Dotted => 0x01 | 0x0100,
15760            U::Wavy => 0x01 | 0x0400,
15761        }
15762    }
15763
15764    /// A byte range in `text` as an `NSRange` in UTF-16 units.
15765    fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
15766        let start = text.get(..r.start)?.encode_utf16().count();
15767        let len = text.get(r.clone())?.encode_utf16().count();
15768        Some(objc2_foundation::NSRange::new(start, len))
15769    }
15770
15771    fn apply_font(label: &UILabel, spec: day_spec::FontSpec) {
15772        let font = resolve_font(spec);
15773        unsafe {
15774            label.setFont(Some(&font));
15775            // Re-scale live when the user changes the accessibility text size (works for fonts derived
15776            // from preferredFont / UIFontMetrics).
15777            let _: () = objc2::msg_send![label, setAdjustsFontForContentSizeCategory: true];
15778        }
15779    }
15780
15781    /// Warn once per kind that this backend has no registered renderer for `kind`, before falling
15782    /// back to a visible placeholder. A missing renderer usually means the piece's `uikit` feature
15783    /// wasn't enabled (Tier A.2 derives it automatically under `day build`). Deduped per kind so a
15784    /// placeholder rendered every frame doesn't spam the log.
15785    fn warn_missing_renderer(kind: PieceKind) {
15786        day_spec::placeholder::report(kind, "uikit");
15787    }
15788
15789    /// The visible placeholder for a kind this backend cannot realize — no registered
15790    /// renderer, or a props payload of the wrong type (`day_spec::props_of` reports the
15791    /// mismatch before the arm degrades here).
15792    pub(crate) fn placeholder_view(kind: PieceKind) -> Handle {
15793        let label = unsafe { UILabel::new(mtm()) };
15794        unsafe { label.setText(Some(&NSString::from_str(&format!("⟨{kind}⟩")))) };
15795        view_of(&label)
15796    }
15797
15798    impl Toolkit for Uikit {
15799        type Handle = Handle;
15800
15801        /// iOS badges are NUMBERS only, and they are part of the notification grant: without the
15802        /// user allowing notifications the count is simply not drawn (docs/badge.md).
15803        ///
15804        /// `UNUserNotificationCenter.setBadgeCount:` (iOS 16+) rather than the deprecated
15805        /// `UIApplication.applicationIconBadgeNumber`. Hand-rolled through `msg_send!` on two
15806        /// nav hosts instead of taking `objc2-user-notifications` as a toolkit dependency — the
15807        /// same budget `day-part-permissions` keeps for this exact class.
15808        fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
15809            use day_spec::AppBadge;
15810            let count: isize = match badge {
15811                AppBadge::None => 0,
15812                AppBadge::Count(n) => *n as isize,
15813                // No text and no dot on iOS. Substituting a number here would invent a value the
15814                // caller never asked for, so these clear instead (Cap says they are unsupported).
15815                AppBadge::Text(_) | AppBadge::Dot => return,
15816            };
15817            let Some(cls) = objc2::runtime::AnyClass::get(c"UNUserNotificationCenter") else {
15818                return;
15819            };
15820            unsafe {
15821                let center: *mut objc2::runtime::AnyObject =
15822                    msg_send![cls, currentNotificationCenter];
15823                if center.is_null() {
15824                    return;
15825                }
15826                // A nil completion handler is allowed; a failure surfaces in the system log, and
15827                // there is nothing the caller could do with it synchronously.
15828                let _: () = msg_send![center, setBadgeCount: count, withCompletionHandler: std::ptr::null::<objc2::runtime::AnyObject>()];
15829            }
15830        }
15831
15832        fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
15833            // The bar is bar-button items rebuilt from the model on every page (a bar button
15834            // item belongs to one bar at a time), and none of them holds state of its own:
15835            // search rides the navigation item, never the bar. So an edit is applied to the
15836            // model and the bar re-filled from it, which is what UIKit does with an items array.
15837            let root = ptr_of(h);
15838            let empty = WINDOW_TOOLBARS.with(|t| {
15839                let mut t = t.borrow_mut();
15840                let w = t.entry(root).or_insert_with(|| WindowToolbar {
15841                    root: h.clone(),
15842                    items: Vec::new(),
15843                    targets: Vec::new(),
15844                    docked: None,
15845                });
15846                for op in ops {
15847                    op.apply_to(&mut w.items);
15848                }
15849                w.items.is_empty()
15850            });
15851            if empty {
15852                // Before the entry goes: the window's own bar lives in it, and a dropped
15853                // `Retained` would leave the strip on screen with nothing driving it.
15854                undock_window_toolbar(root, h);
15855                WINDOW_TOOLBARS.with(|t| {
15856                    t.borrow_mut().remove(&root);
15857                });
15858                clear_window_toolbar(h);
15859                // A page search field was the last item, and leaves with the bar.
15860                sync_page_search(root, h);
15861                return true;
15862            }
15863            reapply_window_toolbar(root);
15864            true
15865        }
15866
15867        fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
15868            let root = ptr_of(h);
15869            let (changed, in_place) = WINDOW_TOOLBARS.with(|t| {
15870                t.borrow_mut().get_mut(&root).map_or((false, false), |w| {
15871                    let changed = patch_toolbar_model(&mut w.items, patch);
15872                    (changed, changed && patch_bottom_in_place(&w.items, patch))
15873                })
15874            });
15875            if changed && !in_place {
15876                reapply_window_toolbar(root);
15877            }
15878            // A search item's values go to the live field on the page showing, never through
15879            // a re-apply (docs/search.md, "Page search").
15880            if patch.item() == day_spec::SEARCH_ITEM_ID
15881                && matches!(
15882                    patch,
15883                    day_spec::ToolbarPatch::Text { .. }
15884                        | day_spec::ToolbarPatch::Focus { .. }
15885                        | day_spec::ToolbarPatch::Placeholder { .. }
15886                )
15887            {
15888                patch_page_search(root, h, patch);
15889            }
15890        }
15891
15892        fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
15893            crate::transfer::source(h, source);
15894        }
15895        fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
15896            crate::transfer::target(h, target);
15897        }
15898        #[expect(
15899            clippy::match_same_arms,
15900            reason = "one arm per capability, each documented with the UIKit mechanism behind it"
15901        )]
15902        fn capability(&self, cap: Cap) -> Support {
15903            match cap {
15904            // A `UIActivity` per app action, listed with the sheet's own actions.
15905            Cap::ShareActions => Support::Native,
15906            Cap::SearchField => Support::Native,
15907            Cap::ComboBox => Support::Unsupported,
15908            Cap::Stepper => Support::Emulated,
15909            Cap::DateTimePicker => Support::Native,
15910            Cap::ColorPicker => Support::Native,
15911            Cap::PullRefresh => Support::Native,
15912            Cap::Pager => Support::Native,
15913            Cap::PullRefreshGesture => Support::Native,
15914                Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems => Support::Native,
15915                // A UIPointerInteraction per view answers pointer EFFECTS (beam, highlight,
15916                // lift, hidden) for the nearest shapes; iPadOS draws no arrows (docs/cursor.md).
15917                Cap::Cursor => Support::Emulated,
15918                // `UIFont.familyNames` + `fontNamesForFamilyName:` (docs/fonts.md).
15919                Cap::FontList => Support::Native,
15920                // Hit slop grows the hit test of Day's container and canvas views, which also
15921                // answer for the UIKit views placed in them (docs/gestures.md "Hit slop").
15922                Cap::HitSlop => Support::Native,
15923                // `pressesEnded:` for the release; a held key that types repeats as text
15924                // through `insertText:`. A held arrow does not repeat: UIKit sends one
15925                // `pressesBegan:` per press (docs/menus.md "Keys").
15926                Cap::KeyPhases => Support::Native,
15927                // A first-responder container in the hardware-keyboard focus system
15928                // (`canBecomeFocused`), focused by a touch, with focus reports both ways.
15929                Cap::Focusable => Support::Native,
15930                // `UIListContentView` with the cell's default content configuration
15931                // (docs/list.md "List items").
15932                Cap::ListItem => Support::Native,
15933                // The table's own layout pass and `scrollViewDidScroll:` report the rows
15934                // between its insets and the distance to the content's end (docs/list.md
15935                // "Visible rows").
15936                Cap::ListViewport => Support::Native,
15937                // `scrollViewDidScroll:` while the table `isDragging` (a finger, or a trackpad
15938                // or mouse on iPadOS) and `scrollViewShouldScrollToTop:` (a status bar tap)
15939                // mark the reader's scrolls; a hardware keyboard's scroll keys cannot be told
15940                // from the app's own animated scroll (docs/list.md "Following the end").
15941                Cap::ListReaderScroll => Support::Native,
15942                // `scrollToRowAtIndexPath:atScrollPosition:animated:` with `.none` / `.top` /
15943                // `.middle` / `.bottom` (docs/list.md "Programmatic scrolling").
15944                Cap::ListScrollAlign => Support::Native,
15945                // The scroll view's delegate: `scrollViewDidScroll:` for the offset, the
15946                // dragging and decelerating callbacks for the phase (docs/scroll.md "Offset
15947                // and phase").
15948                Cap::ScrollOffset | Cap::ScrollPhases => Support::Native,
15949                // `pagingEnabled` for pages; a grid through the target offset UIKit hands
15950                // `scrollViewWillEndDragging:withVelocity:targetContentOffset:`, with the fast
15951                // deceleration rate (docs/scroll.md "Snapping").
15952                Cap::ScrollSnap => Support::Native,
15953                // `minimumZoomScale`/`maximumZoomScale` over one content view, and
15954                // `zoomToRect:animated:` for the patch (docs/scroll.md "Zoom").
15955                Cap::ScrollZoom => Support::Native,
15956                // `keyboardDismissMode` `.onDrag` / `.interactive`, and a tap recognizer of
15957                // Day's own for `KeyboardTaps::Dismiss` (docs/scroll.md "Keyboard").
15958                Cap::ScrollKeyboardDismiss => Support::Native,
15959                // The page view controller's own scroll view, observed (docs/pager.md
15960                // "Progress").
15961                Cap::PagerProgress => Support::Native,
15962                // `UIImage(data:)` reads every container ImageIO knows, and UIKit writes back
15963                // PNG and JPEG (docs/images.md). `Cap::ImageProperties` is deliberately NOT here:
15964                // reading EXIF would mean linking ImageIO and going through `CGImageSource`, and
15965                // an empty struct would read as "this file records nothing" rather than "nobody
15966                // looked".
15967                Cap::ImageDecode | Cap::ImageEncode => Support::Native,
15968                // A canvas renders offscreen through `UIGraphicsImageRenderer` and to a vector PDF
15969                // through `UIGraphicsPDFRenderer`, both with the on-screen painter
15970                // (docs/canvas.md "Exporting").
15971                Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
15972                // `UIAccessibilityAnnouncementNotification`, queued or interrupting per the
15973                // speech attribute (docs/accessibility.md).
15974                Cap::Announce => Support::Native,
15975                // `UIAccessibilityIsReduceMotionEnabled`, re-read when UIKit posts the
15976                // reduce-motion status change (docs/accessibility.md).
15977                Cap::ReduceMotion => Support::Native,
15978                // UIGraphicsImageRenderer draws this app's own window into a bitmap
15979                // (docs/window-image.md).
15980                // A label carrying a link run is built as a read-only UITextView, whose delegate
15981                // reports the tap — a UILabel could draw the link but never hit-test it
15982                // (docs/text-runs.md).
15983                Cap::TextRuns
15984                | Cap::TextLinks
15985                // A selectable label is a read-only UITextView, whose delegate hears every
15986                // selection change (`textViewDidChangeSelection:`, docs/text.md).
15987                | Cap::LabelSelection
15988                // The window toolbar docks under the navigation controller's pages
15989                // (docs/toolbars.md): the phone's second bar, beside the navigation bar.
15990                | Cap::Toolbar
15991                // NSUndoManager fronted through the root VC's responder chain: three-finger
15992                // gestures, shake-to-undo, hardware ⌘Z and the iPad menu bar all land
15993                // (docs/model.md).
15994                | Cap::UndoBridge
15995                | Cap::Snapshot
15996                // UITextView natively honors editable / selectable / spell-check.
15997                | Cap::Dialogs
15998                | Cap::FileDialogs
15999                | Cap::EditBridge
16000                | Cap::Animation
16001                | Cap::Cover
16002                // `.sheet()` is a page sheet (`DayCoverVC`, docs/cover.md "Modal sheet").
16003                | Cap::CoverSheet
16004                // `prefersStatusBarHidden` on the root and cover VCs (docs/cover.md).
16005                | Cap::StatusBarHidden
16006                // Every page rides a UINavigationController, whose UINavigationBar names the
16007                // destination — content needn't repeat the title (docs/navigation.md).
16008                | Cap::NavHeader
16009                | Cap::TextEditable
16010                // A number on the home-screen icon, gated on the notification grant
16011                // (docs/badge.md). Text and Dot have no iOS equivalent.
16012                | Cap::AppBadgeCount
16013                | Cap::TextSelectable
16014                | Cap::TextSpellCheck
16015                // UITableView's own drag pipeline: long-press lift + gap, in and out of
16016                // editing mode.
16017                | Cap::ListReorder
16018                // UITableView reuses queued cells and discards surplus ones; a discarded
16019                // `DayListCell` releases the row Day built in it from `dealloc`, so the rows
16020                // alive stay bounded by the table's own pool (docs/list.md).
16021                | Cap::ListRecycling
16022                // `UITableView` editing: delete controls and reorder grips (docs/list.md).
16023                | Cap::ListEditing
16024                // A list-layout UICollectionView over one diffable SECTION snapshot hosts
16025                // day-built rows natively (docs/tree.md). `Cap::TreeMove` is deliberately
16026                // not here yet: native finger-drag lands after seam parity — the dayscript
16027                // `tree_move:` step drives the seam regardless.
16028                | Cap::Tree
16029            | Cap::TreeSections
16030                // Trailing swipe actions: the row tracks the finger, the destructive action
16031                // reveals behind it, and a full swipe commits (docs/list.md).
16032                | Cap::ListDelete
16033                // The same pipeline generalized: app-declared actions on either edge, with
16034                // the full-swipe shortcut on the first (docs/list.md).
16035                | Cap::ListSwipeActions
16036                // Plain-table section headers, pinned while their section scrolls
16037                // (docs/list.md "Sections").
16038                | Cap::ListSections
16039                // A `UISplitViewController` hosts every `nav(Sidebar)`, so two columns are
16040                // available wherever the window is wide enough — an iPad, and a Plus/Pro Max
16041                // iPhone in landscape (docs/size-classes.md).
16042                // `.tabSidebar` (docs/navigation.md): One `UITabBarController` that draws a tab
16043                // bar when compact and a sidebar when not — what SwiftUI's `.sidebarAdaptable`
16044                // compiles down to, and the container adaptive navigation exists for.
16045                //
16046                // Native on every version this backend deploys to, which was worth MEASURING
16047                // rather than reasoning about. `UITabBarController.mode` is annotated
16048                // `API_AVAILABLE(ios(18.0))`, so the obvious move is to answer `Unsupported`
16049                // below 18 and let the resolver fall back. That made iOS 15.5 and 17.5 worse,
16050                // not safer: the fallback lowers a different host shape and broke the scaffold's
16051                // walkthrough on both, while the unguarded call ran clean on both. Apple shipped
16052                // the nav host before annotating it. An app on iOS 15 therefore gets a plain tab
16053                // bar — what it would have drawn anyway — and only the sidebar half is new.
16054                | Cap::NavTabsAdaptive
16055                | Cap::NavTabs
16056                | Cap::NavSplit
16057                | Cap::Appearance => Support::Native,
16058                // Derived from the control's font: UIKit publishes baselines only as constraint
16059                // anchors, with no number to read (docs/baseline.md).
16060                Cap::BaselineAlignment => Support::Emulated,
16061                // EMULATED, and the distinction is the whole design: UIKit owns the collapse and
16062                // expand, on its own schedule and with its own animation, so Day observes it
16063                // through `Event::NavPresentationChanged` rather than pushing a presentation
16064                // into it (docs/size-classes.md).
16065                Cap::NavRepresent => Support::Emulated,
16066                // The supplementary column of a `.tripleColumn` UISplitViewController; EMULATED
16067                // because the pane MERGES into the stack when the host collapses, and the
16068                // pieces layer interposes it there (docs/navigation.md).
16069                Cap::NavContentList => Support::Emulated,
16070                // Fullscreen hides the status bar and lets the home indicator fade
16071                // (`prefersHomeIndicatorAutoHidden`); the app already fills the screen, so
16072                // nothing else changes (docs/windows.md).
16073                Cap::WindowFullscreen => Support::Emulated,
16074                // No switch exists: an opaque shield covers a protected window while its screen
16075                // is recorded or mirrored, and screenshots still capture it (docs/windows.md).
16076                Cap::ContentProtection => Support::Emulated,
16077                // Each scene's window takes its own `overrideUserInterfaceStyle`.
16078                Cap::WindowAppearance => Support::Native,
16079                // `UIApplication.shortcutItems`: Home Screen quick actions set at run time.
16080                Cap::DynamicShortcuts => Support::Native,
16081                // The one screen the app runs on, from its scene (docs/windows.md).
16082                Cap::Monitors => Support::Emulated,
16083                // `Cap::WindowStates` stays Unsupported: an iOS window is never minimized or
16084                // zoomed, so those requests report the state the window kept.
16085                // Real UIScenes on iPad (docs/windows.md); iPhone shows one scene, so the
16086                // cover fallback is the honest answer there.
16087                Cap::MultiWindow => {
16088                    let app = UIApplication::sharedApplication(mtm());
16089                    if unsafe { app.supportsMultipleScenes() } {
16090                        Support::Native
16091                    } else {
16092                        Support::Unsupported
16093                    }
16094                }
16095                _ => Support::Unsupported,
16096            }
16097        }
16098
16099        fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
16100            let mtm = mtm();
16101            match Builtin::from_key(kind) {
16102                Some(Builtin::Container) => {
16103                    // A mismatched payload still yields a usable (undecorated) container;
16104                    // `props_of` reports it.
16105                    let p = day_spec::props_of::<ContainerProps>(kind, "uikit", props);
16106                    let card =
16107                        p.is_some_and(|p| p.role == Some(day_spec::SurfaceRole::SectionCard));
16108                    // A gradient fill is the view's own layer, so it picks the view's class.
16109                    let v: Retained<UIView> = if p.is_some_and(|p| {
16110                        p.fill
16111                            .as_ref()
16112                            .is_some_and(|f| !matches!(f, day_spec::Paint::Solid(_)))
16113                    }) && !card
16114                    {
16115                        Retained::into_super(Retained::into_super(DayGradientContainer::new(mtm)))
16116                    } else {
16117                        Retained::into_super(DayFocusableContainer::new(mtm))
16118                    };
16119                    if let Some(p) = p {
16120                        if p.role == Some(day_spec::SurfaceRole::SectionCard) {
16121                            // The card half of the grouped pair (`DayNavPageView`): a card is
16122                            // what LIFTS off the grouped ground, so it takes the lighter of the
16123                            // two rather than a fill tinted over whatever is behind it —
16124                            // `tertiarySystemFill` is translucent, and on the grouped ground it
16125                            // read as grey on grey. Dynamic either way: UIKit re-resolves it on
16126                            // trait-collection (light/dark) changes automatically.
16127                            unsafe {
16128                                v.setBackgroundColor(Some(
16129                                    &UIColor::secondarySystemGroupedBackgroundColor(),
16130                                ));
16131                                let layer = v.layer();
16132                                layer.setCornerRadius(p.corner_radius);
16133                                layer.setMasksToBounds(true);
16134                            }
16135                        } else if p.fill.is_some()
16136                            || p.corner_radius > 0.0
16137                            || p.clips
16138                            || p.border.is_some()
16139                            || p.shadow.is_some()
16140                        {
16141                            apply_surface(&v, p);
16142                        }
16143                    }
16144                    view_of(&v)
16145                }
16146                Some(Builtin::Nav) => {
16147                    // Mismatched props degrade to the placeholder rather than panicking in a
16148                    // native up-call (§8.5); `props_of` reports once per kind. Same pattern on
16149                    // every arm below.
16150                    let Some(p) = day_spec::props_of::<NavProps>(kind, "uikit", props) else {
16151                        return placeholder_view(kind);
16152                    };
16153                    if p.documents.is_some() {
16154                        let controller = unsafe { UIViewController::new(mtm) };
16155                        let host = unsafe { UIView::new(mtm) };
16156                        unsafe {
16157                            controller.setView(Some(&host));
16158                        }
16159                        if let Some(root) = WINDOW
16160                            .with(|w| w.borrow().clone())
16161                            .and_then(|w| w.rootViewController())
16162                        {
16163                            unsafe {
16164                                root.addChildViewController(&controller);
16165                                controller.didMoveToParentViewController(Some(&root));
16166                            }
16167                        }
16168                        DOCUMENT_HOSTS.with(|m| {
16169                            m.borrow_mut().insert(
16170                                ptr_of(&host),
16171                                DocumentHost {
16172                                    controller,
16173                                    pages: Vec::new(),
16174                                    selected: 0,
16175                                },
16176                            )
16177                        });
16178                        return view_of(&host);
16179                    }
16180                    let nav = DayNavController::new(mtm, 0); // host ptr set just below
16181                    // Child-VC containment under the window's root VC (v1: app root).
16182                    let root_vc = WINDOW
16183                        .with(|w| w.borrow().clone())
16184                        .and_then(|w| w.rootViewController());
16185                    // `presentation: Stack` in props means a stack at every size — a nested
16186                    // `nav_stack()` under a split host (docs/size-classes.md) — realized as a PLAIN
16187                    // navigation controller. A `UISplitViewController` assumes it owns the
16188                    // window; nested inside a detail pane its column layout collapses into
16189                    // garbage (the embedded-split trap), which is exactly what a pane-sized
16190                    // gray void looked like.
16191                    // An ADAPTIVE TABS host (docs/navigation.md): `.tabSidebar` is the container
16192                    // that wears both chromes itself, so there is no split to build and no
16193                    // presentation for Day to drive — the controller decides, and reports once.
16194                    if p.presentation == day_spec::props::NavPresentation::Tabs {
16195                        let tabbar = unsafe { UITabBarController::new(mtm) };
16196                        // `mode` is annotated `ios(18.0)` but responds on 15.5 and 17.5, which is
16197                        // measured, not assumed (docs/size-classes.md). Guard on whether the
16198                        // object ANSWERS the nav host rather than on a version number: that is
16199                        // the fact the call actually depends on, it needs no table of which OS
16200                        // shipped what, and it degrades to a plain tab bar — an iOS 17 app's own
16201                        // shape — instead of dying, on any runtime that really lacks it.
16202                        if tabbar.respondsToSelector(objc2::sel!(setMode:)) {
16203                            unsafe {
16204                                tabbar.setMode(objc2_ui_kit::UITabBarControllerMode::TabSidebar);
16205                            }
16206                        }
16207                        if let Some(root_vc) = &root_vc {
16208                            unsafe {
16209                                root_vc.addChildViewController(&tabbar);
16210                                tabbar.didMoveToParentViewController(Some(root_vc));
16211                            }
16212                        }
16213                        let host = view_of(&unsafe { tabbar.view() }.expect("tabbar view"));
16214                        let hp = ptr_of(&host);
16215                        let delegate = DayNavTabsDelegate::new(mtm, hp);
16216                        unsafe { tabbar.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
16217                        NAV_TABS.with(|m| {
16218                            m.borrow_mut().insert(
16219                                hp,
16220                                NavTabsState {
16221                                    tabbar,
16222                                    vcs: Vec::new(),
16223                                    tabs: Vec::new(),
16224                                    rows: NavTabRows::default(),
16225                                    menu_view: std::cell::Cell::new(0),
16226                                    menu_node: std::cell::Cell::new(0),
16227                                    suppress: std::cell::Cell::new(false),
16228                                    pending_selection: std::cell::Cell::new(None),
16229                                    _delegate: delegate,
16230                                },
16231                            )
16232                        });
16233                        // Tell Day this host is a tabs host and stays one. Its pages are resident
16234                        // at every width, so day-core must not flip to push/pop as the window
16235                        // widens — UIKit swaps the chrome underneath without Day's help.
16236                        emit(
16237                            id,
16238                            Event::NavPresentationChanged(day_spec::props::NavPresentation::Tabs),
16239                        );
16240                        return host;
16241                    }
16242                    let (host, split) = if p.presentation == day_spec::props::NavPresentation::Stack
16243                    {
16244                        if let Some(root_vc) = root_vc {
16245                            unsafe {
16246                                root_vc.addChildViewController(&nav);
16247                                nav.didMoveToParentViewController(Some(&root_vc));
16248                            }
16249                        }
16250                        let host = view_of(&unsafe { nav.view() }.expect("nav view"));
16251                        // Day owns this frame. UIKit gives every controller's view a W+H
16252                        // autoresizing mask, and a masked child of a superview that grows FROM
16253                        // ZERO gets its own size plus the delta — a host Day had already sized
16254                        // to 420×810 came out 840×1620 under a tab page that took its bounds
16255                        // after Day's pass, with the list's trailing edge and the bar title off
16256                        // the phone. No mask: a frame set once is the frame.
16257                        unsafe {
16258                            host.setAutoresizingMask(objc2_ui_kit::UIViewAutoresizing::empty());
16259                        };
16260                        (host, None)
16261                    } else {
16262                        // The adaptive host (docs/size-classes.md): a two-column
16263                        // UISplitViewController whose SECONDARY column is Day's navigation stack
16264                        // and whose PRIMARY is the sidebar page. UIKit collapses it to a single
16265                        // stack at compact width and expands it at regular — which is a rotation
16266                        // away on a Plus/Pro Max iPhone and the standing state on an iPad.
16267                        //
16268                        // Collapsing MERGES: UIKit inserts the primary's controller at the bottom
16269                        // of the secondary's navigation stack. That lands on exactly the shape
16270                        // Day's model already has in a stack presentation — the sidebar page as
16271                        // the stack's root — so the phone path is unchanged and only the mirror
16272                        // needs rebasing.
16273                        // A content list (`NavProps::list_width`) makes this a TRIPLE-column
16274                        // host while the first destination shows it; the style is init-only,
16275                        // so a later change rebuilds the host (`rehost_split`,
16276                        // docs/navigation.md).
16277                        let list_width = p.list_width;
16278                        let triple = list_width.is_some() && p.list_visible;
16279                        let built = build_split(mtm, &nav, list_width, triple);
16280                        let split_vc = built.split_vc;
16281                        let primary_nav = built.primary_nav;
16282                        let supplementary_nav = built.supplementary_nav;
16283                        let secondary_placeholder = built.secondary_placeholder;
16284                        // Day's handle is a container the split's view fills, so a rebuild
16285                        // leaves the handle — and the tree — untouched.
16286                        let container: Retained<UIView> =
16287                            Retained::into_super(unsafe { DayNavContainer::new(mtm) });
16288                        mount_split(&split_vc, &container);
16289                        let host = container.clone();
16290                        primary_nav.ivars().host.set(ptr_of(&host));
16291                        let split_delegate = DaySplitDelegate::new(mtm, ptr_of(&host));
16292                        unsafe {
16293                            split_vc.setDelegate(Some(ProtocolObject::from_ref(&*split_delegate)));
16294                        };
16295                        (
16296                            host,
16297                            Some(SplitParts {
16298                                split_vc,
16299                                primary_nav,
16300                                supplementary_nav,
16301                                list_width,
16302                                list_shown: std::cell::Cell::new(p.list_visible),
16303                                container,
16304                                list_vc: std::cell::RefCell::new(None),
16305                                secondary_placeholder,
16306                                split_delegate,
16307                            }),
16308                        )
16309                    };
16310                    nav.ivars().host.set(ptr_of(&host));
16311                    let delegate = DayNavDelegate::new(mtm, ptr_of(&host));
16312                    // One delegate for every column: they are the same Day host, and only one
16313                    // of them owns the stack at a time.
16314                    unsafe {
16315                        nav.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
16316                        if let Some(parts) = split.as_ref() {
16317                            parts
16318                                .primary_nav
16319                                .setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
16320                            if let Some(snav) = parts.supplementary_nav.as_ref() {
16321                                snav.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
16322                                snav.ivars().host.set(ptr_of(&host));
16323                            }
16324                        }
16325                    }
16326                    // Inline search (docs/search.md): build the controller now; it is attached to
16327                    // the ROOT page's navigation item as that page joins the stack, which is what
16328                    // puts it behind the pull-down on the top-level list.
16329                    let search = p
16330                        .search
16331                        .as_ref()
16332                        // Every placement lands here, because on iOS the two name one surface.
16333                        // `UINavigationItem` owns the bar's buttons AND its search controller, and
16334                        // the window toolbar rides that same item (docs/toolbars.md) — so
16335                        // "in the toolbar" and "attached to the navigation surface" are the same
16336                        // control, and there is nothing for a placement to choose between.
16337                        //
16338                        // This was a filter on `Inline` alone, which silently dropped the field
16339                        // the day iOS gained `Cap::Toolbar`: `SearchPlacement::Automatic` resolves
16340                        // to `Toolbar` wherever a toolbar exists, and `build_toolbar_items` skips
16341                        // `K::Search` because a `UIBarButtonItem` cannot be a search field. So a
16342                        // `.searchable()` surface simply had no field on iOS at all.
16343                        .map(|sp| {
16344                            let updater = DaySearchUpdater::new(mtm, id);
16345                            let sc = unsafe {
16346                                objc2_ui_kit::UISearchController::initWithSearchResultsController(
16347                                    objc2_ui_kit::UISearchController::alloc(mtm),
16348                                    None,
16349                                )
16350                            };
16351                            unsafe {
16352                                sc.setSearchResultsUpdater(Some(ProtocolObject::from_ref(
16353                                    &*updater,
16354                                )));
16355                                // The results controller is the app's own list, not a separate
16356                                // one, so dimming it while typing would gray out the very rows
16357                                // being filtered.
16358                                sc.setObscuresBackgroundDuringPresentation(false);
16359                                let bar = sc.searchBar();
16360                                // The Search key reports a submission (`Event::SearchSubmitted`);
16361                                // UISearchController leaves its bar's delegate to the app.
16362                                bar.setDelegate(Some(ProtocolObject::from_ref(&*updater)));
16363                                bar.setPlaceholder(Some(&NSString::from_str(&sp.prompt)));
16364                                if !sp.text.is_empty() {
16365                                    bar.setText(Some(&NSString::from_str(&sp.text)));
16366                                }
16367                            }
16368                            (sc, updater)
16369                        });
16370                    NAV_STATE.with(|m| {
16371                        m.borrow_mut().insert(
16372                            ptr_of(&host),
16373                            NavState {
16374                                nav,
16375                                host_node: id,
16376                                split,
16377                                day_pop: std::cell::Cell::new(false),
16378                                pending_list: std::cell::Cell::new(None),
16379                                column_request: std::cell::Cell::new(None),
16380                                delegate,
16381                                search,
16382                                search_hides_on_scroll: p
16383                                    .search
16384                                    .as_ref()
16385                                    .is_some_and(|s| s.hides_on_scroll),
16386                                search_initially_hidden: p
16387                                    .search
16388                                    .as_ref()
16389                                    .is_some_and(|s| s.initially_hidden),
16390                            },
16391                        )
16392                    });
16393                    host
16394                }
16395                Some(Builtin::NavPage) => {
16396                    let Some(p) = day_spec::props_of::<NavPageProps>(kind, "uikit", props) else {
16397                        return placeholder_view(kind);
16398                    };
16399                    let outer = DayNavPageView::new(mtm, id, p.immersive);
16400                    let content = unsafe { UIView::new(mtm) };
16401                    unsafe { outer.addSubview(&content) };
16402                    let vc: Retained<UIViewController> =
16403                        Retained::into_super(unsafe { msg_send![DayPageVC::alloc(mtm), init] });
16404                    unsafe {
16405                        vc.setView(Some(&outer));
16406                        vc.setTitle(Some(&NSString::from_str(&p.title)));
16407                    }
16408                    let handle = view_of(&content);
16409                    PAGE_VCS.with(|m| m.borrow_mut().insert(ptr_of(&handle), vc));
16410                    NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&handle)));
16411                    PAGE_PANE.with(|t| t.insert(ptr_of(&handle), p.pane));
16412                    handle
16413                }
16414                // Fullscreen cover (docs/cover.md): a DayCoverVC over a DayNavPageView (safe-
16415                // area pinning + FrameChanged reports, like a nav page), created detached;
16416                // CoverPatch::Present shows it modally over the whole window.
16417                Some(Builtin::Cover) => {
16418                    let outer = DayNavPageView::new(mtm, id, false);
16419                    let content = unsafe { UIView::new(mtm) };
16420                    unsafe { outer.addSubview(&content) };
16421                    let cover_props = props.downcast_ref::<CoverProps>();
16422                    let half = cover_props.is_some_and(|p| p.half);
16423                    let sheet = half || cover_props.is_some_and(|p| p.sheet);
16424                    let vc = DayCoverVC::new(mtm, id, sheet, half);
16425                    unsafe {
16426                        vc.setView(Some(&outer));
16427                        // A large sheet is the page sheet at its full detent: the wider
16428                        // panel iPadOS gives a document (docs/cover.md "Large sheet").
16429                        let large = cover_props.is_some_and(|p| p.large);
16430                        vc.setModalPresentationStyle(if half || large {
16431                            UIModalPresentationStyle::PageSheet
16432                        } else if sheet {
16433                            UIModalPresentationStyle::FormSheet
16434                        } else {
16435                            UIModalPresentationStyle::FullScreen
16436                        });
16437                    }
16438                    let handle = view_of(&content);
16439                    COVER_STATE.with(|m| {
16440                        m.borrow_mut()
16441                            .insert(ptr_of(&handle), CoverState { vc, node: id })
16442                    });
16443                    // The content view's frame is native-owned (the cover VC lays it out).
16444                    NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&handle)));
16445                    handle
16446                }
16447                Some(Builtin::NavMenu) => {
16448                    let Some(p) = day_spec::props_of::<NavMenuProps>(kind, "uikit", props) else {
16449                        return placeholder_view(kind);
16450                    };
16451                    let data = DayNavTableData::new(
16452                        mtm,
16453                        id,
16454                        &p.items,
16455                        &p.icons,
16456                        &p.tints,
16457                        &p.menus,
16458                        &p.badges,
16459                        &p.badge_icons,
16460                        &p.badge_tints,
16461                        &p.sections,
16462                    );
16463                    // Section headings (`NavMenuProps::sections`), which macos-appkit and
16464                    // android-material already draw and iOS used to flatten away. A list header is the
16465                    // sidebar's own idiom for them, so the model needs no new vocabulary — the
16466                    // rows are grouped into sections and each carries its heading as a header
16467                    // supplementary.
16468                    let layout =
16469                        nav_list_layout(mtm, p.sections.iter().any(std::option::Option::is_some));
16470                    let table = unsafe {
16471                        objc2_ui_kit::UICollectionView::initWithFrame_collectionViewLayout(
16472                            objc2_ui_kit::UICollectionView::alloc(mtm),
16473                            CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(320.0, 400.0)),
16474                            &layout,
16475                        )
16476                    };
16477                    unsafe {
16478                        table.registerClass_forCellWithReuseIdentifier(
16479                            Some(
16480                                <objc2_ui_kit::UICollectionViewListCell as objc2::ClassType>::class(
16481                                ),
16482                            ),
16483                            &NSString::from_str(NAV_CELL_ID),
16484                        );
16485                        table.registerClass_forSupplementaryViewOfKind_withReuseIdentifier(
16486                            Some(
16487                                <objc2_ui_kit::UICollectionViewListCell as objc2::ClassType>::class(
16488                                ),
16489                            ),
16490                            objc2_ui_kit::UICollectionElementKindSectionHeader,
16491                            &NSString::from_str(NAV_HEADER_ID),
16492                        );
16493                        table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
16494                        table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
16495                        // The list draws its own ground; letting the page's grouped background
16496                        // show through is what puts the rows on it rather than on a white sheet.
16497                        table.setBackgroundColor(Some(&objc2_ui_kit::UIColor::clearColor()));
16498                        table.reloadData();
16499                    }
16500                    // The selection the model already carries (docs/navigation.md). A rebuilt
16501                    // sidebar — a language change, a data-driven item set — has to come back
16502                    // marking the same page, not blank. Through `data` rather than the map,
16503                    // which this row is not in until the insert below.
16504                    select_nav_path(&table, p.selected.and_then(|r| data.path_of(r)));
16505                    let view = view_of(&table);
16506                    NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (data, p.items.len())));
16507                    // Remember the rows for a `.tabSidebar` host: UIKit draws both its tab bar
16508                    // and its sidebar from the tabs, so a nav host's row labels have to reach the
16509                    // tabs rather than only this table (docs/navigation.md).
16510                    NAV_MENU_ROWS.with(|m| {
16511                        m.borrow_mut().insert(
16512                            ptr_of(&view),
16513                            (
16514                                id.0 as i64,
16515                                NavTabRows {
16516                                    titles: p.items.clone(),
16517                                    icons: p.icons.clone(),
16518                                    badges: p.badges.clone(),
16519                                },
16520                            ),
16521                        )
16522                    });
16523                    view
16524                }
16525
16526                Some(Builtin::Tree) => {
16527                    let Some(p) = day_spec::props_of::<TreeProps>(kind, "uikit", props) else {
16528                        return placeholder_view(kind);
16529                    };
16530                    let row_height = match p.row_height {
16531                        RowHeight::Uniform(h) => h,
16532                        RowHeight::Automatic => 44.0,
16533                    };
16534                    let config = unsafe {
16535                        objc2_ui_kit::UICollectionLayoutListConfiguration::initWithAppearance(
16536                            objc2_ui_kit::UICollectionLayoutListConfiguration::alloc(mtm),
16537                            if p.section_headers {
16538                                objc2_ui_kit::UICollectionLayoutListAppearance::Sidebar
16539                            } else {
16540                                objc2_ui_kit::UICollectionLayoutListAppearance::Plain
16541                            },
16542                        )
16543                    };
16544                    unsafe {
16545                        config.setShowsSeparators(false);
16546                        config.setBackgroundColor(Some(&objc2_ui_kit::UIColor::clearColor()));
16547                    }
16548                    let layout = unsafe {
16549                        objc2_ui_kit::UICollectionViewCompositionalLayout::layoutWithListConfiguration(&config)
16550                    };
16551                    let cv = unsafe {
16552                        objc2_ui_kit::UICollectionView::initWithFrame_collectionViewLayout(
16553                            objc2_ui_kit::UICollectionView::alloc(mtm),
16554                            CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(0.0, 0.0)),
16555                            &layout,
16556                        )
16557                    };
16558                    unsafe {
16559                        cv.registerClass_forCellWithReuseIdentifier(
16560                            Some(<DayTreeListCell as objc2::ClassType>::class()),
16561                            &NSString::from_str("day.tree.cell"),
16562                        );
16563                        cv.setBackgroundColor(Some(&objc2_ui_kit::UIColor::clearColor()));
16564                        cv.setAllowsSelection(p.selectable);
16565                        if p.multi_select {
16566                            cv.setAllowsMultipleSelection(true);
16567                        }
16568                    }
16569                    let data = DayTreeData::new(mtm, id, p.selectable, row_height);
16570                    unsafe {
16571                        cv.setDelegate(Some(ProtocolObject::from_ref(&*data)));
16572                    }
16573                    let key = Retained::as_ptr(&cv) as usize;
16574                    // The cell provider looks its tree up by the collection view it is handed
16575                    // — capturing `data` would tie a retain cycle through the data source.
16576                    let provider = block2::RcBlock::new(
16577                        move |cvp: core::ptr::NonNull<objc2_ui_kit::UICollectionView>,
16578                              ip: core::ptr::NonNull<objc2_foundation::NSIndexPath>,
16579                              item: core::ptr::NonNull<AnyObject>|
16580                              -> *mut objc2_ui_kit::UICollectionViewCell {
16581                            day_spec::ffi_guard::contain(core::ptr::null_mut(), || {
16582                                let cv = unsafe { cvp.as_ref() };
16583                                let ip = unsafe { ip.as_ref() };
16584                                let item = unsafe { item.as_ref() };
16585                                let cell = unsafe {
16586                                    cv.dequeueReusableCellWithReuseIdentifier_forIndexPath(
16587                                        &NSString::from_str("day.tree.cell"),
16588                                        ip,
16589                                    )
16590                                };
16591                                let Ok(cell) = cell.downcast::<DayTreeListCell>() else {
16592                                    return core::ptr::null_mut();
16593                                };
16594                                let Some(data) = tree_entry_u(std::ptr::from_ref(cv) as usize)
16595                                else {
16596                                    return Retained::autorelease_return(cell)
16597                                        .cast::<objc2_ui_kit::UICollectionViewCell>();
16598                                };
16599                                cell.ivars().row_height.set(data.ivars().row_height.get());
16600                                let Some(tok) = DayTreeData::token_of_item(item) else {
16601                                    return Retained::autorelease_return(cell)
16602                                        .cast::<objc2_ui_kit::UICollectionViewCell>();
16603                                };
16604                                let (expandable, header, bind) = {
16605                                    let src = data.ivars().source.borrow();
16606                                    match src.as_ref() {
16607                                        Some(s) => (
16608                                            (s.expandable)(tok),
16609                                            (s.section_header)(tok),
16610                                            Some(s.bind_row.clone()),
16611                                        ),
16612                                        None => (false, false, None),
16613                                    }
16614                                };
16615                                if expandable {
16616                                    // Day-owned disclosure (module comment): the accessory
16617                                    // only reports; the patch does the toggling.
16618                                    let mtm = unsafe { MainThreadMarker::new_unchecked() };
16619                                    let disc: Retained<
16620                                        objc2_ui_kit::UICellAccessoryOutlineDisclosure,
16621                                    > = unsafe {
16622                                        msg_send![
16623                                            objc2_ui_kit::UICellAccessoryOutlineDisclosure::alloc(
16624                                                mtm
16625                                            ),
16626                                            init
16627                                        ]
16628                                    };
16629                                    if header {
16630                                        unsafe {
16631                                            disc.setStyle(objc2_ui_kit::UICellAccessoryOutlineDisclosureStyle::Header);
16632                                        };
16633                                    }
16634                                    let cv_key = std::ptr::from_ref(cv) as usize;
16635                                    let handler = block2::RcBlock::new(move || {
16636                                        day_spec::ffi_guard::contain((), || {
16637                                            let Some(data) = tree_entry_u(cv_key) else {
16638                                                return;
16639                                            };
16640                                            let ds = data.ivars().ds.borrow().clone();
16641                                            let Some(ds) = ds else { return };
16642                                            let section = unsafe {
16643                                                Retained::cast_unchecked::<NSObject>(
16644                                                    DayTreeData::section(),
16645                                                )
16646                                            };
16647                                            let item = unsafe {
16648                                                Retained::cast_unchecked::<NSObject>(
16649                                                    data.intern(tok),
16650                                                )
16651                                            };
16652                                            let open =
16653                                                ds.snapshotForSection(&section).isExpanded(&item);
16654                                            emit(
16655                                                data.ivars().node,
16656                                                Event::TreeExpanded {
16657                                                    token: tok,
16658                                                    expanded: !open,
16659                                                },
16660                                            );
16661                                        });
16662                                    });
16663                                    unsafe { disc.setActionHandler(Some(&handler)) };
16664                                    let acc = unsafe {
16665                                        Retained::cast_unchecked::<objc2_ui_kit::UICellAccessory>(
16666                                            disc,
16667                                        )
16668                                    };
16669                                    cell.setAccessories(
16670                                        &objc2_foundation::NSArray::from_retained_slice(&[acc]),
16671                                    );
16672                                } else {
16673                                    cell.setAccessories(&objc2_foundation::NSArray::new());
16674                                }
16675                                if let Some(bind) = bind {
16676                                    let content = cell.contentView();
16677                                    bind(tok, Retained::as_ptr(&content) as RawHandle);
16678                                }
16679                                Retained::autorelease_return(cell)
16680                                    .cast::<objc2_ui_kit::UICollectionViewCell>()
16681                            })
16682                        },
16683                    );
16684                    let ds = unsafe {
16685                        objc2_ui_kit::UICollectionViewDiffableDataSource::<NSObject, NSObject>::initWithCollectionView_cellProvider(
16686                            objc2_ui_kit::UICollectionViewDiffableDataSource::alloc(mtm),
16687                            &cv,
16688                            &raw const *provider as *mut block2::DynBlock<_>,
16689                        )
16690                    };
16691                    data.ivars().ds.replace(Some(ds));
16692                    TREE_STATE.with(|m| m.borrow_mut().insert(key, data));
16693                    view_of(&cv)
16694                }
16695                Some(Builtin::List) => {
16696                    let Some(p) = day_spec::props_of::<ListProps>(kind, "uikit", props) else {
16697                        return placeholder_view(kind);
16698                    };
16699                    let row_height = match p.row_height {
16700                        RowHeight::Uniform(h) => h,
16701                        RowHeight::Automatic => 44.0,
16702                    };
16703                    let table = DayListTable::make(
16704                        mtm,
16705                        if p.inset_grouped {
16706                            objc2_ui_kit::UITableViewStyle::InsetGrouped
16707                        } else {
16708                            objc2_ui_kit::UITableViewStyle::Plain
16709                        },
16710                    );
16711                    let automatic = p.row_height == RowHeight::Automatic;
16712                    let data = DayListData::new(
16713                        mtm,
16714                        id,
16715                        p.selectable,
16716                        row_height,
16717                        automatic,
16718                        p.delete_label.clone(),
16719                        p.sections,
16720                    );
16721                    unsafe {
16722                        if p.sections {
16723                            // Section headers (docs/list.md "Sections"): self-sizing, and flush
16724                            // with the rows above them; iOS 15's automatic top padding would
16725                            // open a gap over every header.
16726                            table.setSectionHeaderHeight(
16727                                objc2_ui_kit::UITableViewAutomaticDimension,
16728                            );
16729                            table.setEstimatedSectionHeaderHeight(32.0);
16730                            table.setSectionHeaderTopPadding(0.0);
16731                        }
16732                        if automatic {
16733                            // Self-sizing cells (docs/list.md "Row heights"): each row is as
16734                            // tall as Day lays it, asked of the cell once it is bound.
16735                            table.setRowHeight(objc2_ui_kit::UITableViewAutomaticDimension);
16736                            table.setEstimatedRowHeight(row_height);
16737                        } else {
16738                            table.setRowHeight(row_height);
16739                        }
16740                        table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
16741                        table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
16742                        // The table owns its data source for as long as it lives, not only
16743                        // while Day's `LIST_STATE` entry does: UITableView holds `dataSource`
16744                        // weakly, and a table that lays out once more after its node went (a
16745                        // page still animating out, a late pass) asserts "UITableView
16746                        // dataSource is not set" and takes the app down. The source's closures
16747                        // are safe to call after the node is gone (they find no list).
16748                        objc2::ffi::objc_setAssociatedObject(
16749                            std::ptr::from_ref::<objc2::runtime::AnyObject>(&table).cast_mut(),
16750                            std::ptr::addr_of!(LIST_DATA_SOURCE_KEY).cast(),
16751                            std::ptr::from_ref::<objc2::runtime::AnyObject>(&data).cast_mut(),
16752                            objc2::ffi::OBJC_ASSOCIATION_RETAIN_NONATOMIC,
16753                        );
16754                        // Separators are UIKit's default; only a forced OFF changes anything
16755                        // (docs/list.md) — a list whose rows draw their own separation turns
16756                        // the native line off rather than showing both.
16757                        if p.separators == Some(false) {
16758                            table.setSeparatorStyle(
16759                                objc2_ui_kit::UITableViewCellSeparatorStyle::None,
16760                            );
16761                        }
16762                        if !p.selectable {
16763                            table.setAllowsSelection(false);
16764                        }
16765                        if p.reorderable {
16766                            // Native drag-to-reorder (docs/list.md): the drag delegate lifts a
16767                            // row on long-press (no editing mode); the data-source move methods
16768                            // + target-for-move delegate drive commit and the live guard.
16769                            table.setDragDelegate(Some(ProtocolObject::from_ref(&*data)));
16770                            table.setDragInteractionEnabled(true);
16771                        }
16772                        // Editing mode (docs/list.md): a tap still activates the row, as it
16773                        // does in Settings' and Mail's edit lists.
16774                        table.setAllowsSelectionDuringEditing(p.selectable);
16775                        if p.editing {
16776                            table.setEditing_animated(true, false);
16777                        }
16778                    }
16779                    let view = view_of(&table);
16780                    LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
16781                    view
16782                }
16783                Some(Builtin::Scroll) => {
16784                    // A scroll without props (a piece realizing `kinds::SCROLL` itself) is the
16785                    // plain scroll view Day always made.
16786                    let sv = match day_spec::props_of::<ScrollProps>(kind, "uikit", props) {
16787                        Some(p) => make_scroll(p, id, mtm),
16788                        None => unsafe { UIScrollView::new(mtm) },
16789                    };
16790                    view_of(&sv)
16791                }
16792                Some(Builtin::Label) => {
16793                    let Some(p) = day_spec::props_of::<LabelProps>(kind, "uikit", props) else {
16794                        return placeholder_view(kind);
16795                    };
16796                    // A UILabel does no hit testing at all, so a label that arrives with a link
16797                    // run is built as a read-only text view instead — the same backing
16798                    // `.selectable()` swaps to, and the only one UIKit can activate a link in
16799                    // (docs/text-runs.md). A link that first appears in a later patch cannot
16800                    // upgrade the backing: `patch` has no way to hand back a new handle.
16801                    if p.runs.iter().any(|r| r.link.is_some()) {
16802                        let view = view_of(&link_text_view(p, id, mtm));
16803                        track_label(&view, p, id);
16804                        return view;
16805                    }
16806                    let label = unsafe { UILabel::new(mtm) };
16807                    unsafe { label.setText(Some(&NSString::from_str(&p.text))) };
16808                    apply_font(&label, p.font);
16809                    // An explicit color wins; otherwise the ROLE chooses which adaptive system
16810                    // color applies, so a de-emphasized label stays legible in both appearances.
16811                    match (p.color, p.role) {
16812                        (Some(c), _) => unsafe { label.setTextColor(Some(&uiink(c))) },
16813                        (None, day_spec::props::TextRole::Secondary) => unsafe {
16814                            label.setTextColor(Some(&UIColor::secondaryLabelColor()));
16815                        },
16816                        (None, day_spec::props::TextRole::Primary) => {}
16817                    }
16818                    if !p.runs.is_empty() {
16819                        let s =
16820                            attributed_label(&p.text, &resolve_font(p.font), label_ink(p), &p.runs);
16821                        unsafe { label.setAttributedText(Some(&s)) };
16822                    }
16823                    // Line limit, truncation, spacing, line height, alignment (docs/text.md).
16824                    let view = view_of(&label);
16825                    track_label(&view, p, id);
16826                    view
16827                }
16828                Some(Builtin::Button) => {
16829                    let Some(p) = day_spec::props_of::<ButtonProps>(kind, "uikit", props) else {
16830                        return placeholder_view(kind);
16831                    };
16832                    let target = DayTarget::new(mtm, id);
16833                    let btn = unsafe { UIButton::buttonWithType(UIButtonType::System, mtm) };
16834                    apply_button_style(&btn, &p.title, p.style, mtm);
16835                    if p.icon.is_some() {
16836                        apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
16837                    }
16838                    unsafe { btn.setEnabled(p.enabled) };
16839                    if p.selected {
16840                        set_button_selected(&btn, true, mtm);
16841                    }
16842                    unsafe {
16843                        let tobj: &AnyObject = target.as_ref();
16844                        btn.addTarget_action_forControlEvents(
16845                            Some(tobj),
16846                            sel!(fire:),
16847                            UIControlEvents::TouchUpInside,
16848                        );
16849                    }
16850                    let view = view_of(&btn);
16851                    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
16852                    view
16853                }
16854                Some(Builtin::Toggle) => {
16855                    let Some(p) = day_spec::props_of::<ToggleProps>(kind, "uikit", props) else {
16856                        return placeholder_view(kind);
16857                    };
16858                    let target = DayTarget::new(mtm, id);
16859                    let sw = unsafe { UISwitch::new(mtm) };
16860                    unsafe {
16861                        sw.setOn(p.on);
16862                        sw.setEnabled(p.enabled);
16863                        let tobj: &AnyObject = target.as_ref();
16864                        sw.addTarget_action_forControlEvents(
16865                            Some(tobj),
16866                            sel!(fire:),
16867                            UIControlEvents::ValueChanged,
16868                        );
16869                    }
16870                    let view = view_of(&sw);
16871                    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
16872                    view
16873                }
16874                Some(Builtin::Slider) => {
16875                    let Some(p) = day_spec::props_of::<SliderProps>(kind, "uikit", props) else {
16876                        return placeholder_view(kind);
16877                    };
16878                    let target = DayTarget::new(mtm, id);
16879                    let sl = unsafe { UISlider::new(mtm) };
16880                    unsafe {
16881                        sl.setMinimumValue(p.min as f32);
16882                        sl.setMaximumValue(p.max as f32);
16883                        sl.setValue(p.value as f32);
16884                        let tobj: &AnyObject = target.as_ref();
16885                        sl.addTarget_action_forControlEvents(
16886                            Some(tobj),
16887                            sel!(fire:),
16888                            UIControlEvents::ValueChanged,
16889                        );
16890                        // Both lift events: a drag that ends off the track still ends.
16891                        sl.addTarget_action_forControlEvents(
16892                            Some(tobj),
16893                            sel!(commit:),
16894                            UIControlEvents::TouchUpInside | UIControlEvents::TouchUpOutside,
16895                        );
16896                    }
16897                    let view = view_of(&sl);
16898                    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
16899                    view
16900                }
16901                Some(Builtin::Picker) => crate::picker::realize_any(self, props, id),
16902                Some(Builtin::TextArea) => crate::textarea::realize_any(self, props, id),
16903                Some(Builtin::TextField) => {
16904                    let Some(p) = day_spec::props_of::<TextFieldProps>(kind, "uikit", props) else {
16905                        return placeholder_view(kind);
16906                    };
16907                    let target = DayTarget::new(mtm, id);
16908                    let tf = unsafe { UITextField::new(mtm) };
16909                    unsafe {
16910                        tf.setText(Some(&NSString::from_str(&p.text)));
16911                        tf.setPlaceholder(Some(&NSString::from_str(&p.placeholder)));
16912                        tf.setBorderStyle(UITextBorderStyle::RoundedRect);
16913                        // The delegate answers for `read_only` (`set_input_traits`).
16914                        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
16915                        let tobj: &AnyObject = target.as_ref();
16916                        tf.addTarget_action_forControlEvents(
16917                            Some(tobj),
16918                            sel!(fire:),
16919                            UIControlEvents::EditingChanged,
16920                        );
16921                        // Focus + submit (docs/focus.md): begin/end report the focus pair;
16922                        // end-on-exit is the Return key (and makes Return dismiss the keyboard).
16923                        tf.addTarget_action_forControlEvents(
16924                            Some(tobj),
16925                            sel!(editBegan:),
16926                            UIControlEvents::EditingDidBegin,
16927                        );
16928                        tf.addTarget_action_forControlEvents(
16929                            Some(tobj),
16930                            sel!(editEnded:),
16931                            UIControlEvents::EditingDidEnd,
16932                        );
16933                        tf.addTarget_action_forControlEvents(
16934                            Some(tobj),
16935                            sel!(editExit:),
16936                            UIControlEvents::EditingDidEndOnExit,
16937                        );
16938                    }
16939                    let view = view_of(&tf);
16940                    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
16941                    view
16942                }
16943                Some(Builtin::Divider) => {
16944                    let v = unsafe { UIView::new(mtm) };
16945                    unsafe { v.setBackgroundColor(Some(&UIColor::separatorColor())) };
16946                    // A rule takes no touches until a recognizer asks for them, so a press
16947                    // on it reaches what is behind it (docs/gestures.md "Pass-through").
16948                    unsafe { v.setUserInteractionEnabled(false) };
16949                    view_of(&v)
16950                }
16951                Some(Builtin::Progress) => {
16952                    let Some(p) = day_spec::props_of::<ProgressProps>(kind, "uikit", props) else {
16953                        return placeholder_view(kind);
16954                    };
16955                    if p.value.is_none() {
16956                        return crate::controls::spinner::make(self, p, id);
16957                    }
16958                    if let Some(v) = p.value {
16959                        let pv = unsafe { UIProgressView::new(mtm) };
16960                        unsafe { pv.setProgress(v as f32) };
16961                        view_of(&pv)
16962                    } else {
16963                        let ai = unsafe { UIActivityIndicatorView::new(mtm) };
16964                        unsafe { ai.startAnimating() };
16965                        view_of(&ai)
16966                    }
16967                }
16968                Some(Builtin::Canvas) => {
16969                    let canvas = DayCanvasView::new(mtm);
16970                    KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
16971                    view_of(&canvas)
16972                }
16973                Some(Builtin::Image) => {
16974                    let Some(p) = day_spec::props_of::<ImageProps>(kind, "uikit", props) else {
16975                        return placeholder_view(kind);
16976                    };
16977                    let iv = unsafe { objc2_ui_kit::UIImageView::new(mtm) };
16978                    // Scaling (§18.3): AspectFit / AspectFill (crop, clipped) / ScaleToFill.
16979                    let mode = match p.content_mode {
16980                        ContentMode::Fit => objc2_ui_kit::UIViewContentMode::ScaleAspectFit,
16981                        ContentMode::Fill => objc2_ui_kit::UIViewContentMode::ScaleAspectFill,
16982                        ContentMode::Stretch => objc2_ui_kit::UIViewContentMode::ScaleToFill,
16983                    };
16984                    unsafe {
16985                        iv.setContentMode(mode);
16986                        iv.setClipsToBounds(true);
16987                    }
16988                    // Named is the staged-asset path; Bytes and Decoded arrive from
16989                    // `day::decode_image` (docs/images.md), so an `image()` piece can show a
16990                    // download or a pasted PNG with no staged resource behind it.
16991                    if let Some(img) = uikit_image_for(&p.source) {
16992                        unsafe { iv.setImage(Some(&img)) };
16993                    }
16994                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's tint —
16995                    // UIKit recolors the alpha mask natively. A template with no tint of its own
16996                    // inherits the tint around it (a cell's, a bar's): the iOS idiom, and what
16997                    // the nav menu's own rows do.
16998                    if (p.tint.is_some() || p.template)
16999                        && let Some(img) = unsafe { iv.image() }
17000                    {
17001                        let templ = unsafe {
17002                            img.imageWithRenderingMode(
17003                                objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate,
17004                            )
17005                        };
17006                        unsafe { iv.setImage(Some(&templ)) };
17007                    }
17008                    if let Some(t) = p.tint {
17009                        unsafe { iv.setTintColor(Some(&uiink(t))) };
17010                    }
17011                    IMAGE_MODES.with(|t| {
17012                        t.insert(
17013                            ptr_of(&iv),
17014                            ImageMode {
17015                                template: p.template,
17016                                tinted: p.tint.is_some(),
17017                            },
17018                        )
17019                    });
17020                    view_of(&iv)
17021                }
17022                Some(Builtin::ListItem) => {
17023                    let Some(p) =
17024                        day_spec::props_of::<day_spec::props::ListItemProps>(kind, "uikit", props)
17025                    else {
17026                        return placeholder_view(kind);
17027                    };
17028                    make_list_item(p, mtm)
17029                }
17030                // A recycled list cell is ADOPTED from the native list, never realized
17031                // through this path; anything else is an extension piece.
17032                Some(
17033                    Builtin::ListCell
17034                    | Builtin::Inspector
17035                    | Builtin::InspectorPane
17036                    | Builtin::Split
17037                    | Builtin::SplitPane,
17038                )
17039                | None => {
17040                    if let Some(make) = self.registry.get(kind).map(|r| r.make) {
17041                        return make(self, props, id);
17042                    }
17043                    warn_missing_renderer(kind);
17044                    placeholder_view(kind)
17045                }
17046            }
17047        }
17048
17049        fn update(
17050            &mut self,
17051            h: &Handle,
17052            kind: PieceKind,
17053            patch: &dyn Any,
17054            anim: Option<&AnimSpec>,
17055        ) {
17056            match kind {
17057                kinds::LIST_ITEM => {
17058                    let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
17059                        return;
17060                    };
17061                    let props = LIST_ITEMS.with(|m| {
17062                        use day_spec::props::ListItemPatch as P;
17063                        let mut m = m.borrow_mut();
17064                        let props = m.get_mut(&ptr_of(h))?;
17065                        match p {
17066                            P::Title(t) => props.title.clone_from(t),
17067                            P::Subtitle(t) => props.subtitle.clone_from(t),
17068                            P::Detail(t) => props.detail.clone_from(t),
17069                            P::Icon(i) => props.icon.clone_from(i),
17070                            P::IconTint(c) => props.icon_tint = *c,
17071                            P::Checked(on) => props.checked = *on,
17072                        }
17073                        Some(props.clone())
17074                    });
17075                    if let Some(props) = props {
17076                        dress_list_item(h, &props);
17077                    }
17078                }
17079                kinds::IMAGE => {
17080                    if let (Some(p), Some(iv)) = (
17081                        patch.downcast_ref::<day_spec::props::ImagePatch>(),
17082                        h.downcast_ref::<objc2_ui_kit::UIImageView>(),
17083                    ) {
17084                        match p {
17085                            day_spec::props::ImagePatch::Tint(c) => {
17086                                // Template rendering + the view's tint, as at realize
17087                                // (docs/vectors.md). A template glyph stays one when the tint
17088                                // goes; it falls back to the inherited tint.
17089                                let template = IMAGE_MODES
17090                                    .with(|t| {
17091                                        t.with(ptr_of(iv), |m| {
17092                                            m.tinted = c.is_some();
17093                                            m.renders_template()
17094                                        })
17095                                    })
17096                                    .unwrap_or(c.is_some());
17097                                if let Some(img) = unsafe { iv.image() } {
17098                                    let mode = if template {
17099                                        objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate
17100                                    } else {
17101                                        objc2_ui_kit::UIImageRenderingMode::AlwaysOriginal
17102                                    };
17103                                    let next = unsafe { img.imageWithRenderingMode(mode) };
17104                                    unsafe { iv.setImage(Some(&next)) };
17105                                }
17106                                unsafe {
17107                                    iv.setTintColor(c.map(uiink).as_deref());
17108                                };
17109                            }
17110                            // A source swap repaints the same view (docs/images.md), so an
17111                            // `image()` bound to a signal shows new pixels without rebuilding
17112                            // its subtree.
17113                            day_spec::props::ImagePatch::Source(source) => {
17114                                if matches!(source, day_spec::ImageSource::Named(name) if name.is_empty())
17115                                {
17116                                    unsafe { iv.setImage(None) };
17117                                    return;
17118                                }
17119                                // A source that will not load leaves the view showing what it
17120                                // was — the patch's contract, and what GTK, Qt and Android do.
17121                                // The new image renders the way the view does: a tinted or
17122                                // template glyph stays one, so a recycled sidebar row shows
17123                                // the icon it was rebound to in the same color.
17124                                if let Some(img) = uikit_image_for(source) {
17125                                    let template = IMAGE_MODES
17126                                        .with(|t| t.get(ptr_of(iv)))
17127                                        .is_some_and(ImageMode::renders_template);
17128                                    let img = if template {
17129                                        unsafe {
17130                                            img.imageWithRenderingMode(
17131                                                objc2_ui_kit::UIImageRenderingMode::AlwaysTemplate,
17132                                            )
17133                                        }
17134                                    } else {
17135                                        img
17136                                    };
17137                                    unsafe { iv.setImage(Some(&img)) };
17138                                }
17139                            }
17140                        }
17141                    }
17142                }
17143                // A reactive fill or surface (docs/surfaces.md "Reactive surfaces"). A solid
17144                // fill to a solid fill animates its color with `anim`; to or from a gradient it
17145                // applies at once (a nil background on either side). A whole surface animates
17146                // its radius, border width and colors and shadow with it.
17147                kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
17148                    Some(ContainerPatch::Fill(fill)) => {
17149                        animate_channel(h, Channel::Background, anim, || {
17150                            patch_fill(h, fill.as_ref());
17151                        });
17152                    }
17153                    Some(ContainerPatch::Surface(p)) => {
17154                        animate_channel(h, Channel::Surface, anim, || apply_surface(h, p));
17155                    }
17156                    None => {}
17157                },
17158                // Data-driven sidebar rows (docs/navigation.md): rebuild the UITableView rows.
17159                kinds::NAV_MENU => {
17160                    if let Some(p) = patch.downcast_ref::<day_spec::props::RefreshPatch>() {
17161                        let Some(scroll) = h.downcast_ref::<UIScrollView>() else {
17162                            return;
17163                        };
17164                        let Some(node) = NAV_MENUS
17165                            .with(|m| m.borrow().get(&ptr_of(h)).map(|(d, _)| d.ivars().node))
17166                        else {
17167                            return;
17168                        };
17169                        let mtm = MainThreadMarker::new().expect("UIKit updates on main");
17170                        let control = unsafe { scroll.refreshControl() }.unwrap_or_else(|| {
17171                            let control = unsafe { objc2_ui_kit::UIRefreshControl::new(mtm) };
17172                            let target = DayTarget::new(mtm, node);
17173                            unsafe {
17174                                control.addTarget_action_forControlEvents(
17175                                    Some(&target),
17176                                    sel!(fire:),
17177                                    UIControlEvents::ValueChanged,
17178                                );
17179                                scroll.setRefreshControl(Some(&control));
17180                                // An empty or short sidebar must still be pullable.
17181                                scroll.setAlwaysBounceVertical(true);
17182                            }
17183                            TARGETS.with(|m| m.borrow_mut().insert(ptr_of(h), target));
17184                            control
17185                        });
17186                        unsafe {
17187                            if p.refreshing {
17188                                control.beginRefreshing();
17189                            } else {
17190                                control.endRefreshing();
17191                            }
17192                        }
17193                        return;
17194                    }
17195                    if let Some(NavMenuPatch::Items {
17196                        items,
17197                        icons,
17198                        tints,
17199                        menus,
17200                        badges,
17201                        badge_icons,
17202                        badge_tints,
17203                        selected,
17204                        sections,
17205                        rows_changed,
17206                        ..
17207                    }) = patch.downcast_ref::<NavMenuPatch>()
17208                    {
17209                        NAV_MENUS.with(|m| {
17210                            if let Some((data, n)) = m.borrow_mut().get_mut(&ptr_of(h)) {
17211                                data.set_items(
17212                                    items,
17213                                    icons,
17214                                    tints,
17215                                    menus,
17216                                    badges,
17217                                    badge_icons,
17218                                    badge_tints,
17219                                    sections,
17220                                );
17221                                *n = items.len();
17222                                if let Some(cv) = h.downcast_ref::<objc2_ui_kit::UICollectionView>()
17223                                {
17224                                    // Header mode is baked into the LAYOUT, so a data-driven set
17225                                    // that gains or loses its headings needs a new one — without
17226                                    // this those headings would simply never draw.
17227                                    let headers = sections.iter().any(std::option::Option::is_some);
17228                                    if headers != data.ivars().headers.get()
17229                                        && let Some(mtm) = MainThreadMarker::new()
17230                                    {
17231                                        data.ivars().headers.set(headers);
17232                                        unsafe {
17233                                            cv.setCollectionViewLayout(&nav_list_layout(
17234                                                mtm, headers,
17235                                            ));
17236                                        };
17237                                    }
17238                                    // The same rows with new words or counts: reconfigure
17239                                    // just those cells, which keeps each cell and the
17240                                    // selection where they are.
17241                                    if let Some(rows) = rows_changed {
17242                                        let paths: Vec<Retained<objc2_foundation::NSIndexPath>> =
17243                                            rows.iter()
17244                                                .filter_map(|r| data.path_of(*r))
17245                                                .map(|(section, item)| unsafe {
17246                                                    objc2_foundation::NSIndexPath::indexPathForItem_inSection(
17247                                                        item as isize,
17248                                                        section as isize,
17249                                                    )
17250                                                })
17251                                                .collect();
17252                                        if !paths.is_empty() {
17253                                            unsafe {
17254                                                cv.reconfigureItemsAtIndexPaths(
17255                                                    &objc2_foundation::NSArray::from_retained_slice(
17256                                                        &paths,
17257                                                    ),
17258                                                );
17259                                            };
17260                                        }
17261                                    } else {
17262                                        unsafe { cv.reloadData() };
17263                                        // Resolved from this data source, which the borrow
17264                                        // above holds: `select_nav_row` would borrow the same
17265                                        // map again.
17266                                        select_nav_path(
17267                                            cv,
17268                                            selected.and_then(|r| data.path_of(r)),
17269                                        );
17270                                    }
17271                                }
17272                            }
17273                        });
17274                        // The same rows are a `.tabSidebar` host's tabs, which UIKit draws from
17275                        // its `UITab`s rather than this list: without this a language change
17276                        // left the iPad's tab bar in the old language, and badges never moved.
17277                        let menu = ptr_of(h);
17278                        let host = NAV_TABS.with(|m| {
17279                            let mut m = m.borrow_mut();
17280                            let (host, t) =
17281                                m.iter_mut().find(|(_, t)| t.menu_view.get() == menu)?;
17282                            t.rows = NavTabRows {
17283                                titles: items.clone(),
17284                                icons: icons.clone(),
17285                                badges: badges.clone(),
17286                            };
17287                            Some(*host)
17288                        });
17289                        if let Some(host) = host {
17290                            match rows_changed {
17291                                Some(_) => nav_tabs_refresh(host),
17292                                None => nav_tabs_sync(host),
17293                            }
17294                        }
17295                    } else if let Some(NavMenuPatch::IconProgress(progress)) =
17296                        patch.downcast_ref::<NavMenuPatch>()
17297                    {
17298                        NAV_MENUS.with(|menus| {
17299                            let menus = menus.borrow();
17300                            let Some((data, _)) = menus.get(&ptr_of(h)) else {
17301                                return;
17302                            };
17303                            let previous = data.ivars().icon_progress.replace(progress.clone());
17304                            let Some(cv) = h.downcast_ref::<objc2_ui_kit::UICollectionView>()
17305                            else {
17306                                return;
17307                            };
17308                            unsafe {
17309                                for ip in cv.indexPathsForVisibleItems() {
17310                                    let Some(index) =
17311                                        data.row_of(ip.section() as usize, ip.item() as usize)
17312                                    else {
17313                                        continue;
17314                                    };
17315                                    let value =
17316                                        progress.iter().find(|(i, _)| *i == index).map(|(_, v)| *v);
17317                                    if previous.iter().find(|(i, _)| *i == index).map(|(_, v)| *v)
17318                                        == value
17319                                    {
17320                                        continue;
17321                                    }
17322                                    if let Some(cell) = cv.cellForItemAtIndexPath(&ip)
17323                                        && let Some(cell) = cell
17324                                            .downcast_ref::<objc2_ui_kit::UICollectionViewListCell>(
17325                                        )
17326                                    {
17327                                        crate::nav_progress::update(cell, value, self.mtm());
17328                                    }
17329                                }
17330                            }
17331                        });
17332                    } else if let Some(NavMenuPatch::Selected(sel)) =
17333                        patch.downcast_ref::<NavMenuPatch>()
17334                        && let Some(cv) = h.downcast_ref::<objc2_ui_kit::UICollectionView>()
17335                    {
17336                        // Applied without re-emitting: `selectRowAtIndexPath` does not call the
17337                        // delegate, so there is no echo to suppress here.
17338                        select_nav_row(cv, *sel);
17339                    }
17340                }
17341                kinds::COVER => {
17342                    if let Some(p) = patch.downcast_ref::<CoverPatch>() {
17343                        let state = COVER_STATE
17344                            .with(|m| m.borrow().get(&ptr_of(h)).map(|s| (s.vc.clone(), s.node)));
17345                        let Some((vc, node)) = state else { return };
17346                        match p {
17347                            CoverPatch::Present {
17348                                background,
17349                                dismiss_disabled,
17350                            } => {
17351                                if let (Some(c), Some(view)) = (background, vc.view()) {
17352                                    unsafe {
17353                                        view.setBackgroundColor(Some(&uiink(*c)));
17354                                    };
17355                                }
17356                                // Inert under .fullScreen, but honored if the presentation
17357                                // style ever becomes a sheet.
17358                                unsafe { vc.setModalInPresentation(*dismiss_disabled) };
17359                                cover_present(vc);
17360                            }
17361                            CoverPatch::DismissDisabled(d) => unsafe {
17362                                vc.setModalInPresentation(*d);
17363                            },
17364                            CoverPatch::Dismiss => cover_dismiss(vc, node),
17365                        }
17366                    }
17367                }
17368                // A PAGE's own items changed (docs/toolbars.md): store them and re-lower just
17369                // this page's chrome. The window's half is untouched, and so is every other
17370                // page — which is the point of contributions being per page.
17371                kinds::NAV => {
17372                    // Inline search: the app writing its query patches the live field, so the
17373                    // sync never rebuilds it or takes the insertion point (docs/search.md). The
17374                    // suppress flag stops UISearchResultsUpdating echoing our own write back.
17375                    if let Some(sp) = patch.downcast_ref::<day_spec::props::SearchPatch>() {
17376                        // Activating search can synchronously reenter navigation delegates.
17377                        // Retain the controller/updater and release NAV_STATE before UIKit calls.
17378                        let search = NAV_STATE
17379                            .with(|m| m.borrow().get(&ptr_of(h)).and_then(|st| st.search.clone()));
17380                        if let Some((sc, updater)) = search {
17381                            if matches!(sp, day_spec::props::SearchPatch::Focus) {
17382                                unsafe {
17383                                    sc.setActive(true);
17384                                    sc.searchBar().becomeFirstResponder();
17385                                }
17386                            }
17387                            if let day_spec::props::SearchPatch::Text(t) = sp {
17388                                updater.ivars().suppress.set(true);
17389                                unsafe { sc.searchBar().setText(Some(&NSString::from_str(t))) };
17390                                updater.ivars().suppress.set(false);
17391                            }
17392                            // Scope and suggestion patches have no UIKit surface yet.
17393                        }
17394                    }
17395                    let document = DOCUMENT_HOSTS.with(|m| {
17396                        let mut m = m.borrow_mut();
17397                        let Some(state) = m.get_mut(&ptr_of(h)) else {
17398                            return false;
17399                        };
17400                        match patch.downcast_ref::<NavPatch>() {
17401                            Some(NavPatch::Select(i)) => state.selected = *i,
17402                            Some(NavPatch::Reorder(order)) => {
17403                                let old = state.pages.clone();
17404                                state.pages =
17405                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
17406                            }
17407                            _ => {}
17408                        }
17409                        document_frames(h, state);
17410                        true
17411                    });
17412                    if document {
17413                        return;
17414                    }
17415                    if let Some(NavPatch::Reorder(order)) = patch.downcast_ref::<NavPatch>() {
17416                        let host = ptr_of(h);
17417                        NAV_TABS.with(|m| {
17418                            if let Some(t) = m.borrow_mut().get_mut(&host) {
17419                                let old = t.vcs.clone();
17420                                t.vcs = order.iter().filter_map(|i| old.get(*i).cloned()).collect();
17421                            }
17422                        });
17423                        nav_tabs_sync(host);
17424                        return;
17425                    }
17426                    if let Some(NavPatch::Select(i)) = patch.downcast_ref::<NavPatch>() {
17427                        // A `.tabSidebar` host has no `NavState` — it is not a navigation stack — so
17428                        // this is handled before that lookup.
17429                        if NAV_TABS.with(|m| m.borrow().contains_key(&ptr_of(h))) {
17430                            tabs_select_when_settled(ptr_of(h), *i);
17431                            return;
17432                        }
17433                    }
17434                    if let Some(p) = patch.downcast_ref::<NavPatch>() {
17435                        // Copy out of NAV_STATE before touching UIKit: push/pop can invoke
17436                        // the delegate synchronously, which re-borrows NAV_STATE.
17437                        enum Act {
17438                            Title(Retained<UIViewController>, String),
17439                            /// Show/hide the supplementary column (expanded triple only).
17440                            Column,
17441                            /// Collapsed triple only: the content list joins or leaves the
17442                            /// merged stack through UIKit's own column APIs.
17443                            TripleList {
17444                                show: bool,
17445                            },
17446                            None,
17447                        }
17448                        let act = NAV_STATE.with(|m| {
17449                            let mut m = m.borrow_mut();
17450                            let Some(state) = m.get_mut(&ptr_of(h)) else {
17451                                return Act::None;
17452                            };
17453                            let collapsed_triple = state.is_collapsed()
17454                                && state
17455                                    .split
17456                                    .as_ref()
17457                                    .is_some_and(|p| p.supplementary_nav.is_some());
17458                            match p {
17459                                // The page itself arrives through the insert duty and leaves
17460                                // through the remove duty, which carry its identity; the stack
17461                                // change is made there (`push_page`, `pop_page`).
17462                                #[expect(
17463                                    clippy::match_same_arms,
17464                                    reason = "each group of no-op patches keeps its own arm and the comment saying why"
17465                                )]
17466                                NavPatch::Pushed { .. } | NavPatch::Popped => Act::None,
17467                                // Retitle the TOP page's controller — the navigation bar
17468                                // mirrors the top item's title live.
17469                                NavPatch::Title(t) => current_top(ptr_of(h), &state.active_nav())
17470                                    .map_or(Act::None, |vc| Act::Title(vc, t.clone())),
17471                                // Arm the back guard: `shouldPopItem:` vetoes the button and
17472                                // `gestureRecognizerShouldBegin:` the swipe, both asking Day
17473                                // instead (docs/navigation.md). The gesture stays enabled.
17474                                NavPatch::GuardTop(on) => {
17475                                    state.active_nav().ivars().guarded.set(*on);
17476                                    Act::None
17477                                }
17478                                // `Presentation` never reaches a toolkit whose container
17479                                // re-presents (the pieces layer gates it on `Cap::NavRepresent`);
17480                                // `Select` belongs to tab hosts; representable split hosts
17481                                // already track presentation through UIKit (docs/navigation.md).
17482                                #[expect(
17483                                    clippy::match_same_arms,
17484                                    reason = "each group of no-op patches keeps its own arm and the comment saying why"
17485                                )]
17486                                NavPatch::Presentation(_)
17487                                | NavPatch::Select(_)
17488                                | NavPatch::Reorder(_) => Act::None,
17489                                // Re-entering a list-backed destination after native back does
17490                                // not change ListVisible. Explicitly restore its column to the
17491                                // collapsed stack on the first tap instead of waiting for a
17492                                // detail push to bring it along.
17493                                NavPatch::ListInStack(show) if collapsed_triple => {
17494                                    Act::TripleList { show: *show }
17495                                }
17496                                NavPatch::ListInStack(_) => Act::None,
17497                                // Per-destination content list: a column while expanded, an
17498                                // entry on the merged stack while collapsed.
17499                                NavPatch::ListVisible(v) => {
17500                                    if let Some(p) = state.split.as_ref() {
17501                                        p.list_shown.set(*v);
17502                                    }
17503                                    if !state.is_collapsed() {
17504                                        Act::Column
17505                                    } else if collapsed_triple {
17506                                        Act::TripleList { show: *v }
17507                                    } else {
17508                                        Act::None
17509                                    }
17510                                }
17511                            }
17512                        });
17513                        // Defer past any in-flight modal transition: a stack change issued the
17514                        // instant a (scripted) dialog dismissal starts races the dismissal
17515                        // transition and wedges the navigation controller.
17516                        match act {
17517                            Act::Title(vc, t) => unsafe {
17518                                vc.setTitle(Some(&NSString::from_str(&t)));
17519                            },
17520                            // The host the destination calls for (`SplitParts::list_shown`).
17521                            Act::Column => rehost_split(ptr_of(h)),
17522                            Act::TripleList { show } => {
17523                                let host = ptr_of(h);
17524                                modal_after_idle(move || request_compact_list(host, show));
17525                            }
17526                            Act::None => {}
17527                        }
17528                    }
17529                }
17530                kinds::LABEL => {
17531                    if let (Some(p), Some(label)) = (
17532                        patch.downcast_ref::<LabelPatch>(),
17533                        (**h).downcast_ref::<UILabel>(),
17534                    ) {
17535                        match p {
17536                            // Applied below with everything else the look decides.
17537                            LabelPatch::Paragraph(para) => set_label_paragraph(h, *para),
17538                            LabelPatch::Text(t) => unsafe {
17539                                label.setText(Some(&NSString::from_str(t)));
17540                            },
17541                            LabelPatch::Font(f) => apply_font(label, *f),
17542                            LabelPatch::Runs(text, runs) => {
17543                                let base = unsafe { label.font() };
17544                                if let Some(f) = base {
17545                                    let s = attributed_label(text, &f, own_ink(h), runs);
17546                                    unsafe { label.setAttributedText(Some(&s)) };
17547                                }
17548                            }
17549                            // `None` restores the adaptive default (labelColor tracks dark mode).
17550                            LabelPatch::Color(c) => {
17551                                set_own_ink(h, *c);
17552                                unsafe {
17553                                    match c {
17554                                        Some(c) => label.setTextColor(Some(&uiink(*c))),
17555                                        None => label.setTextColor(Some(&UIColor::labelColor())),
17556                                    }
17557                                }
17558                            }
17559                        }
17560                    } else if let (Some(p), Some(tv)) = (
17561                        patch.downcast_ref::<LabelPatch>(),
17562                        (**h).downcast_ref::<UITextView>(),
17563                    ) {
17564                        // A `.selectable()` label rides a read-only UITextView (the
17565                        // `set_selectable` swap); the same patches route there.
17566                        match p {
17567                            LabelPatch::Paragraph(para) => set_label_paragraph(h, *para),
17568                            LabelPatch::Text(t) => unsafe {
17569                                tv.setText(Some(&NSString::from_str(t)));
17570                            },
17571                            LabelPatch::Font(f) => {
17572                                let font = resolve_font(*f);
17573                                unsafe {
17574                                    tv.setFont(Some(&font));
17575                                    let _: () =
17576                                        msg_send![tv, setAdjustsFontForContentSizeCategory: true];
17577                                }
17578                            }
17579                            LabelPatch::Runs(text, runs) => {
17580                                // A selectable label is a UITextView, which renders attributed
17581                                // text the same way — and, unlike UILabel, could hit-test its
17582                                // links (Phase 4).
17583                                if let Some(f) = unsafe { tv.font() } {
17584                                    let s = attributed_label(text, &f, own_ink(h), runs);
17585                                    unsafe { tv.setAttributedText(Some(&s)) };
17586                                }
17587                            }
17588                            LabelPatch::Color(c) => {
17589                                set_own_ink(h, *c);
17590                                unsafe {
17591                                    match c {
17592                                        Some(c) => tv.setTextColor(Some(&uiink(*c))),
17593                                        None => tv.setTextColor(Some(&UIColor::labelColor())),
17594                                    }
17595                                }
17596                            }
17597                        }
17598                        // New text discards the selection without telling the delegate.
17599                        if matches!(p, LabelPatch::Text(_) | LabelPatch::Runs(..)) {
17600                            report_selection(tv);
17601                        }
17602                    }
17603                    // Every patch: new text, a new font or new runs replace the attributed
17604                    // string the kern and line height were on, and change the point size they
17605                    // are multiples of; the setters re-style the whole string too.
17606                    apply_paragraph(h);
17607                }
17608                kinds::BUTTON => {
17609                    if let (Some(p), Some(btn)) = (
17610                        patch.downcast_ref::<ButtonPatch>(),
17611                        (**h).downcast_ref::<UIButton>(),
17612                    ) {
17613                        match p {
17614                            ButtonPatch::Content(c) => {
17615                                apply_button_content(btn, &c.title, c.icon.as_ref(), c.icon_only);
17616                            }
17617                            ButtonPatch::Title(t) => unsafe {
17618                                // A configured (bordered/prominent) button titles via its
17619                                // configuration; a plain one via the state title.
17620                                if let Some(config) = btn.configuration() {
17621                                    config.setTitle(Some(&NSString::from_str(t)));
17622                                    btn.setConfiguration(Some(&config));
17623                                } else {
17624                                    btn.setTitle_forState(
17625                                        Some(&NSString::from_str(t)),
17626                                        UIControlState::Normal,
17627                                    );
17628                                }
17629                            },
17630                            ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
17631                            ButtonPatch::Selected(on) => set_button_selected(btn, *on, mtm()),
17632                            ButtonPatch::Style(s) => {
17633                                // Re-apply with the current title: a configured button carries
17634                                // its title in the configuration, which this replaces.
17635                                let title = unsafe {
17636                                    btn.configuration()
17637                                        .and_then(|c| c.title())
17638                                        .or_else(|| btn.titleForState(UIControlState::Normal))
17639                                        .map(|s| s.to_string())
17640                                }
17641                                .unwrap_or_default();
17642                                apply_button_style(btn, &title, *s, mtm());
17643                                if let Some(c) = BUTTON_CONTENT.with(|m| m.get(ptr_of(btn))) {
17644                                    apply_button_content(
17645                                        btn,
17646                                        &c.title,
17647                                        c.icon.as_ref(),
17648                                        c.icon_only,
17649                                    );
17650                                }
17651                            }
17652                        }
17653                    }
17654                }
17655                kinds::TOGGLE => {
17656                    if let (Some(p), Some(sw)) = (
17657                        patch.downcast_ref::<TogglePatch>(),
17658                        (**h).downcast_ref::<UISwitch>(),
17659                    ) {
17660                        match p {
17661                            TogglePatch::On(on) => {
17662                                if unsafe { sw.isOn() } != *on {
17663                                    unsafe { sw.setOn(*on) };
17664                                }
17665                            }
17666                            TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
17667                        }
17668                    }
17669                }
17670                kinds::SLIDER => {
17671                    if let (Some(p), Some(sl)) = (
17672                        patch.downcast_ref::<SliderPatch>(),
17673                        (**h).downcast_ref::<UISlider>(),
17674                    ) {
17675                        match p {
17676                            SliderPatch::Value(v) => {
17677                                if (f64::from(unsafe { sl.value() }) - v).abs() > 0.001 {
17678                                    unsafe { sl.setValue(*v as f32) };
17679                                }
17680                            }
17681                            SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
17682                        }
17683                    }
17684                }
17685                kinds::PROGRESS => {
17686                    if let Some(p @ ProgressPatch::Animating(_)) =
17687                        patch.downcast_ref::<ProgressPatch>()
17688                    {
17689                        crate::controls::spinner::update(self, h, p);
17690                        return;
17691                    }
17692
17693                    if let Some(ProgressPatch::Value(Some(val))) =
17694                        patch.downcast_ref::<ProgressPatch>()
17695                        && let Some(pv) = (**h).downcast_ref::<UIProgressView>()
17696                        && (f64::from(unsafe { pv.progress() }) - val).abs() > 0.0001
17697                    {
17698                        unsafe { pv.setProgress(*val as f32) };
17699                    }
17700                }
17701                kinds::PICKER => crate::picker::update_any(self, h, patch),
17702                kinds::TEXT_AREA => crate::textarea::update_any(self, h, patch),
17703                kinds::TEXT_FIELD => {
17704                    if let (Some(p), Some(tf)) = (
17705                        patch.downcast_ref::<TextFieldPatch>(),
17706                        (**h).downcast_ref::<UITextField>(),
17707                    ) {
17708                        match p {
17709                            TextFieldPatch::Text { text, from_native } => {
17710                                let cur = unsafe { tf.text() }.map_or_default(|s| s.to_string());
17711                                if !*from_native && cur != *text {
17712                                    unsafe { tf.setText(Some(&NSString::from_str(text))) };
17713                                }
17714                            }
17715                            TextFieldPatch::Placeholder(t) => unsafe {
17716                                tf.setPlaceholder(Some(&NSString::from_str(t)));
17717                            },
17718                            TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
17719                            // UITextInput positions count UTF-16 units. A field holds a
17720                            // selection only while it edits (docs/textfield.md "Selection"),
17721                            // and taking focus puts the caret at the end anyway.
17722                            TextFieldPatch::Select(sel) => unsafe {
17723                                if tf.isFirstResponder() {
17724                                    let text = tf.text().map_or_default(|s| s.to_string());
17725                                    let (start, end) = sel.utf16(&text);
17726                                    let begin = tf.beginningOfDocument();
17727                                    let at = |n: usize| {
17728                                        tf.positionFromPosition_offset(&begin, n as isize)
17729                                    };
17730                                    if let (Some(a), Some(b)) = (at(start), at(end))
17731                                        && let Some(range) =
17732                                            tf.textRangeFromPosition_toPosition(&a, &b)
17733                                    {
17734                                        tf.setSelectedTextRange(Some(&range));
17735                                    }
17736                                }
17737                            },
17738                        }
17739                    }
17740                }
17741                kinds::TREE => match patch.downcast_ref::<TreePatch>() {
17742                    // Deferred to the main queue: these arrive inside a `with_tree` borrow,
17743                    // and applying a snapshot binds cells synchronously.
17744                    Some(TreePatch::Reload) => {
17745                        let key = ptr_of(h);
17746                        <Uikit as Platform>::post(Box::new(move || {
17747                            if let Some(data) = tree_entry_u(key) {
17748                                data.apply_snapshot(false);
17749                            }
17750                        }));
17751                    }
17752                    Some(TreePatch::Expand(token, on)) => {
17753                        if let Some(data) = tree_entry_u(ptr_of(h)) {
17754                            if *on {
17755                                data.ivars().expanded.borrow_mut().insert(*token);
17756                            } else {
17757                                data.ivars().expanded.borrow_mut().remove(token);
17758                            }
17759                        }
17760                        let key = ptr_of(h);
17761                        <Uikit as Platform>::post(Box::new(move || {
17762                            if let Some(data) = tree_entry_u(key) {
17763                                // Re-derive from the recorded set — expand/collapse of one
17764                                // row animates as a section-snapshot difference.
17765                                data.apply_snapshot(true);
17766                            }
17767                        }));
17768                    }
17769                    Some(TreePatch::Selected(tokens)) => {
17770                        let (key, tokens) = (ptr_of(h), tokens.clone());
17771                        <Uikit as Platform>::post(Box::new(move || {
17772                            let Some(data) = tree_entry_u(key) else {
17773                                return;
17774                            };
17775                            let ds = data.ivars().ds.borrow().clone();
17776                            let Some(ds) = ds else { return };
17777                            let cv =
17778                                unsafe { (key as *const objc2_ui_kit::UICollectionView).as_ref() };
17779                            let Some(cv) = cv else { return };
17780                            // Programmatic (de)selects never fire the delegate — no echo.
17781                            if let Some(paths) = cv.indexPathsForSelectedItems() {
17782                                for ip in &paths {
17783                                    cv.deselectItemAtIndexPath_animated(&ip, false);
17784                                }
17785                            }
17786                            for t in &tokens {
17787                                let item = unsafe {
17788                                    Retained::cast_unchecked::<NSObject>(data.intern(*t))
17789                                };
17790                                if let Some(ip) = ds.indexPathForItemIdentifier(&item) {
17791                                    unsafe {
17792                                        cv.selectItemAtIndexPath_animated_scrollPosition(
17793                                            Some(&ip),
17794                                            false,
17795                                            objc2_ui_kit::UICollectionViewScrollPosition::empty(),
17796                                        );
17797                                    };
17798                                }
17799                            }
17800                        }));
17801                    }
17802                    Some(TreePatch::Reveal(token)) => {
17803                        let (key, token) = (ptr_of(h), *token);
17804                        <Uikit as Platform>::post(Box::new(move || {
17805                            let Some(data) = tree_entry_u(key) else {
17806                                return;
17807                            };
17808                            let ds = data.ivars().ds.borrow().clone();
17809                            let Some(ds) = ds else { return };
17810                            let cv =
17811                                unsafe { (key as *const objc2_ui_kit::UICollectionView).as_ref() };
17812                            let Some(cv) = cv else { return };
17813                            let item =
17814                                unsafe { Retained::cast_unchecked::<NSObject>(data.intern(token)) };
17815                            if let Some(ip) = ds.indexPathForItemIdentifier(&item) {
17816                                unsafe {
17817                                    cv.scrollToItemAtIndexPath_atScrollPosition_animated(
17818                                        &ip,
17819                                        objc2_ui_kit::UICollectionViewScrollPosition::CenteredVertically,
17820                                        false,
17821                                    );
17822                                };
17823                            }
17824                        }));
17825                    }
17826                    None => {}
17827                },
17828                kinds::SCROLL => {
17829                    if let Some(ScrollPatch::Zoom { scale, animated }) =
17830                        patch.downcast_ref::<ScrollPatch>()
17831                        && let Some(sv) = (**h).downcast_ref::<UIScrollView>()
17832                        && let Some(delegate) = DayScrollDelegate::of(sv)
17833                    {
17834                        // UIKit's zoom calls back only the delegate, which enqueues; nothing
17835                        // here re-enters the tree.
17836                        delegate.zoom(sv, *scale, *animated);
17837                    }
17838                }
17839                kinds::LIST => match patch.downcast_ref::<ListPatch>() {
17840                    // Held for the table and applied a turn later, outside this tree borrow
17841                    // (`DayListData::hold`): row updates realize and retire cells
17842                    // synchronously, and both need the tree.
17843                    Some(ListPatch::Splice(deltas)) => {
17844                        let key = ptr_of(h);
17845                        let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
17846                        if let Some((table, data)) = entry {
17847                            // The row count these deltas end on, read now: by the time the
17848                            // held batch runs, a later change may have moved the source on.
17849                            let after = data.ivars().source.borrow().as_ref().map(|s| (s.len)());
17850                            data.hold(key, &table, Some(deltas), after);
17851                        }
17852                    }
17853                    Some(ListPatch::Reload) => {
17854                        let key = ptr_of(h);
17855                        let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
17856                        if let Some((table, data)) = entry {
17857                            data.hold(key, &table, None, None);
17858                        }
17859                    }
17860                    Some(scroll @ (ListPatch::ScrollToEnd | ListPatch::ScrollToRow(_))) => {
17861                        let key = ptr_of(h);
17862                        let (row, position) = match scroll {
17863                            ListPatch::ScrollToRow(row) => {
17864                                (*row, objc2_ui_kit::UITableViewScrollPosition::Top)
17865                            }
17866                            _ => (usize::MAX, objc2_ui_kit::UITableViewScrollPosition::Bottom),
17867                        };
17868                        // Splices/reloads are deferred. Scroll after them, outside the tree
17869                        // borrow: scrolling can synchronously realize and recycle cells too.
17870                        <Uikit as Platform>::post(Box::new(move || {
17871                            let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
17872                            let Some((table, data)) = entry else { return };
17873                            // UIKit's committed count is authoritative, even if another model
17874                            // change has already advanced the source snapshot. Empty is a no-op.
17875                            let count = data.table_len(&table);
17876                            if count == 0 {
17877                                return;
17878                            }
17879                            let Some(ip) = data.path_of(row.min(count - 1)) else {
17880                                return;
17881                            };
17882                            unsafe {
17883                                table.scrollToRowAtIndexPath_atScrollPosition_animated(
17884                                    &ip, position, true,
17885                                );
17886                            }
17887                        }));
17888                    }
17889                    Some(ListPatch::Editing(on)) => {
17890                        let (key, on) = (ptr_of(h), *on);
17891                        // Deferred: the animated change lays the cells out, and their
17892                        // `layout_cell` re-lays rows, which needs the tree this patch holds.
17893                        <Uikit as Platform>::post(Box::new(move || {
17894                            let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
17895                            if let Some((table, _)) = entry {
17896                                unsafe { table.setEditing_animated(on, true) };
17897                            }
17898                        }));
17899                    }
17900                    Some(ListPatch::RowSizeInvalidated { .. }) => {
17901                        DayListData::post_row_heights(ptr_of(h));
17902                    }
17903                    // Not implemented: Selected (no programmatic selection sync on UIKit yet).
17904                    Some(ListPatch::Selected(_)) | None => {}
17905                },
17906                _ => {
17907                    if let Some(update) = self.registry.get(kind).map(|r| r.update) {
17908                        update(self, h, patch);
17909                    }
17910                }
17911            }
17912        }
17913
17914        /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
17915        fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
17916            // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
17917            // the hook needs it mutably.
17918            let f = self.registry.get(kind).and_then(|r| r.release);
17919            if let Some(f) = f {
17920                f(self, h);
17921            }
17922        }
17923        fn release(&mut self, h: Handle) {
17924            if let Some(state) = DOCUMENT_HOSTS.with(|m| m.borrow_mut().remove(&ptr_of(&h))) {
17925                unsafe {
17926                    state.controller.willMoveToParentViewController(None);
17927                    state.controller.removeFromParentViewController();
17928                }
17929            }
17930
17931            // Backstop for a released window root whose scene never disconnected
17932            // (docs/windows.md — disconnect normally prunes first).
17933            SCENES.with(|s| {
17934                s.borrow_mut()
17935                    .retain(|e| !std::ptr::eq(&raw const *e.root_view, &raw const *h));
17936            });
17937            TARGETS.with(|m| {
17938                m.borrow_mut().remove(&ptr_of(&h));
17939            });
17940            LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
17941            if let Some((table, _)) = LIST_STATE.with(|m| m.borrow_mut().remove(&ptr_of(&h)))
17942                && table.window().is_some()
17943            {
17944                // Diagnostic for the "dataSource is not set" class: the table may still lay
17945                // out after this; its data source lives on as the table's associated object.
17946                log::debug!(
17947                    "day-toolkit-uikit: list released while still in a window ({} rows)",
17948                    unsafe { table.numberOfRowsInSection(0) }
17949                );
17950            }
17951            TREE_STATE.with(|m| {
17952                m.borrow_mut().remove(&ptr_of(&h));
17953            });
17954            if let Some((old, _)) = CTX_MENU_FNS.with(|t| t.borrow_mut().remove(&ptr_of(&h))) {
17955                unsafe { h.removeInteraction(ProtocolObject::from_ref(&*old)) };
17956            }
17957            NAV_STATE.with(|m| {
17958                m.borrow_mut().remove(&ptr_of(&h));
17959            });
17960            NAV_OPS.with(|q| {
17961                q.borrow_mut().remove(&ptr_of(&h));
17962            });
17963            NAV_PAGES.with(|set| {
17964                set.borrow_mut().remove(&ptr_of(&h));
17965            });
17966            if let Some(vc) = PAGE_VCS.with(|m| m.borrow_mut().remove(&ptr_of(&h))) {
17967                PAGE_TOOLBARS.with(|m| {
17968                    m.borrow_mut().remove(&vc_key(&vc));
17969                });
17970                // The page's search field goes with it. Left on the navigation item, which the
17971                // page releases: deactivating it here would start a dismissal under a pop that
17972                // may still be animating.
17973                let search = PAGE_SEARCH.with(|m| m.borrow_mut().remove(&vc_key(&vc)));
17974                drop(search);
17975            }
17976            COVER_STATE.with(|m| {
17977                m.borrow_mut().remove(&ptr_of(&h));
17978            });
17979            NAV_MENUS.with(|m| {
17980                m.borrow_mut().remove(&ptr_of(&h));
17981            });
17982            GESTURES.with(|m| {
17983                m.borrow_mut().remove(&ptr_of(&h));
17984            });
17985            // A press under way on a view leaving the tree ends here: its `false` is owed.
17986            if let Some(observers) = OBSERVERS.with(|t| t.get(ptr_of(&h))) {
17987                for o in observers {
17988                    o.finish(true);
17989                }
17990            }
17991            // One sweep clears every `day_spec::sidetable::SideTable` on this thread —
17992            // CTX_MENUS (whose teardown detaches the interaction from the view first),
17993            // PAGE_PANE, canvas OPS, and the picker/textarea state tables — present and
17994            // future, so a new table can never be forgotten here again. The RefCell maps
17995            // above predate the mechanism and are still cleared by hand.
17996            day_spec::sidetable::sweep(ptr_of(&h));
17997            unsafe { h.removeFromSuperview() };
17998        }
17999
18000        fn insert(&mut self, parent: &Handle, child: &Handle, index: usize) {
18001            // A zooming scroll's children go in the one view UIKit scales (docs/scroll.md
18002            // "Zoom").
18003            if let Some(content) = zoom_content(parent) {
18004                unsafe { content.addSubview(child) };
18005                return;
18006            }
18007            let document = DOCUMENT_HOSTS.with(|m| {
18008                let mut m = m.borrow_mut();
18009                let Some(state) = m.get_mut(&ptr_of(parent)) else {
18010                    return false;
18011                };
18012                if PAGE_PANE.with(|t| t.get(ptr_of(child))) == Some(day_spec::props::Pane::Sidebar)
18013                {
18014                    unsafe {
18015                        parent.addSubview(child);
18016                        child.setHidden(true);
18017                    }
18018                    return true;
18019                }
18020                if let Some(vc) = PAGE_VCS.with(|p| p.borrow().get(&ptr_of(child)).cloned()) {
18021                    unsafe {
18022                        state.controller.addChildViewController(&vc);
18023                        if let Some(view) = vc.view() {
18024                            parent.addSubview(&view);
18025                        }
18026                        vc.didMoveToParentViewController(Some(&state.controller));
18027                    }
18028                    state.pages.push((ptr_of(child), vc));
18029                    document_frames(parent, state);
18030                }
18031                true
18032            });
18033            if document {
18034                return;
18035            }
18036
18037            // What a page or the root holds decides whether it pads by the safe area
18038            // (`DayNavPageView`/`DayHolderView::layoutSubviews`), so a child joining it re-asks.
18039            reask_content_frame(parent);
18040            // A NAV_MENU joining the tree: if it lands anywhere inside a `.tabSidebar` host, its
18041            // rows are that host's tabs. This is the first moment the menu has a superview chain
18042            // to find its host through.
18043            if let Some((node, rows)) =
18044                NAV_MENU_ROWS.with(|m| m.borrow_mut().remove(&ptr_of(child)))
18045                && let Some(hp) = enclosing_tabs_host(parent)
18046            {
18047                NAV_TABS.with(|m| {
18048                    if let Some(t) = m.borrow_mut().get_mut(&hp) {
18049                        t.menu_node.set(node);
18050                        t.menu_view.set(ptr_of(child));
18051                        t.rows = rows;
18052                    }
18053                });
18054                nav_tabs_sync(hp);
18055            }
18056            // Adaptive tabs host (`.tabSidebar`). Its DETAIL pages become tabs; its `Pane::Sidebar`
18057            // page does not, because UIKit draws the sidebar itself from the same tabs — adding
18058            // Day's rows as well would show the list twice, once in each chrome.
18059            let is_tabs_host = NAV_TABS.with(|m| m.borrow().contains_key(&ptr_of(parent)));
18060            if is_tabs_host {
18061                TABS_PAGE_HOST.with(|m| m.borrow_mut().insert(ptr_of(child), ptr_of(parent)));
18062                let pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
18063                if pane == Some(day_spec::props::Pane::Sidebar) {
18064                    // UIKit draws the sidebar from the tabs, so Day's rows page would show the
18065                    // list twice — once in each chrome. It stays out of the controller.
18066                    return;
18067                }
18068                if let Some(vc) = PAGE_VCS.with(|m| m.borrow().get(&ptr_of(child)).cloned()) {
18069                    // A tab holds a NAVIGATION CONTROLLER wherever the page will not bring one of
18070                    // its own — the shape every tabbed iOS app has, and the only thing that gives
18071                    // a tab a bar for the commands its page declares (docs/toolbars.md).
18072                    //
18073                    // WHERE the page brings one is not a guess: a list-backed destination
18074                    // composes a nested host for its two layers exactly when the window is too
18075                    // narrow to show them side by side, which is the same question
18076                    // `gated_detail_piece` asks. Both layers ask it, so they agree — and wrapping
18077                    // on top of that host is what stacked two bars with the destination's title
18078                    // on each.
18079                    let mtm =
18080                        MainThreadMarker::new().expect("uikit insert runs on the main thread");
18081                    // Asked of UIKit, which is the authority on it and answers before Day has
18082                    // reported a size class for this window.
18083                    let wide = NAV_TABS.with(|m| {
18084                        m.borrow().get(&ptr_of(parent)).is_some_and(|t| {
18085                            let tc: Option<Retained<objc2_ui_kit::UITraitCollection>> =
18086                                unsafe { objc2::msg_send![&*t.tabbar, traitCollection] };
18087                            tc.is_some_and(|tc| unsafe {
18088                                tc.horizontalSizeClass()
18089                                    == objc2_ui_kit::UIUserInterfaceSizeClass::Regular
18090                            })
18091                        })
18092                    });
18093                    let entry: Retained<UIViewController> = if wide {
18094                        let wrapper = unsafe {
18095                            let n =
18096                                objc2_ui_kit::UINavigationController::initWithRootViewController(
18097                                    objc2_ui_kit::UINavigationController::alloc(mtm),
18098                                    &vc,
18099                                );
18100                            // The strip above already names the destination; a large title over
18101                            // every tab would say it twice.
18102                            configure_navigation_bar(&n.navigationBar(), mtm);
18103                            n.navigationBar().setPrefersLargeTitles(false);
18104                            n
18105                        };
18106                        Retained::into_super(wrapper)
18107                    } else {
18108                        vc.clone()
18109                    };
18110                    NAV_TABS.with(|m| {
18111                        if let Some(t) = m.borrow_mut().get_mut(&ptr_of(parent)) {
18112                            let at = index.min(t.vcs.len());
18113                            t.vcs.insert(at, entry);
18114                        }
18115                    });
18116                    nav_tabs_sync(ptr_of(parent));
18117                }
18118                return;
18119            }
18120            // The SIDEBAR page is the split host's primary column, not a member of the stack
18121            // (docs/size-classes.md). It goes in whatever the current presentation calls for:
18122            // its own column while expanded, and the stack's root while collapsed — which is the
18123            // shape the phone path has always had, so nothing below changes for it.
18124            let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
18125            let is_sidebar = page_pane == Some(day_spec::props::Pane::Sidebar);
18126            // This page's OWN toolbar items (docs/toolbars.md). Every page kind takes them —
18127            // the sidebar column's, the content list's, and each detail — so a command sits on
18128            // the chrome of the content it acts on. Applied before the placement branches below,
18129            // and outside any `NAV_STATE` borrow, because building the items runs app code.
18130            // The CONTENT-LIST page is the supplementary column's root, the same shape one
18131            // column over (docs/navigation.md): never a member of the `vcs` mirror — while
18132            // collapsed the pieces layer interposes it explicitly (`NavPatch::ListInStack`).
18133            if page_pane == Some(day_spec::props::Pane::List) {
18134                let placed = NAV_STATE.with(|m| {
18135                    let mut m = m.borrow_mut();
18136                    let state = m.get_mut(&ptr_of(parent))?;
18137                    let vc = PAGE_VCS.with(|p| p.borrow().get(&ptr_of(child)).cloned())?;
18138                    let parts = state.split.as_ref()?;
18139                    // Kept whether or not the host has a column for it yet: a double-column
18140                    // host gains one on the first list-backed destination (`rehost_split`).
18141                    *parts.list_vc.borrow_mut() = Some(vc.clone());
18142                    let snav = parts.supplementary_nav.clone()?;
18143                    Some((snav, vc))
18144                });
18145                if let Some((snav, vc)) = placed {
18146                    // Like a detail page, the content list never takes a large title. Left at
18147                    // Automatic it inherits the sidebar's Always once a collapsed split pushes it
18148                    // over the sidebar, and the bar keeps an empty large-title band over a list
18149                    // whose insets never counted it (the list's top and its pinned section header
18150                    // sat under the opaque bar).
18151                    unsafe {
18152                        vc.navigationItem().setLargeTitleDisplayMode(
18153                            objc2_ui_kit::UINavigationItemLargeTitleDisplayMode::Never,
18154                        );
18155                        vc.setExtendedLayoutIncludesOpaqueBars(true);
18156                        snav.setExtendedLayoutIncludesOpaqueBars(true);
18157                    }
18158                    let arr = objc2_foundation::NSArray::from_retained_slice(&[vc]);
18159                    unsafe { snav.setViewControllers(&arr) };
18160                }
18161                return;
18162            }
18163            // Nav host: pages join the VC stack; the first one becomes the root VC now, later
18164            // pages are presented by the Pushed patch.
18165            // Copy out of NAV_STATE before setViewControllers (same re-entrancy rule).
18166            let placed = NAV_STATE.with(|m| {
18167                let mut m = m.borrow_mut();
18168                let state = m.get_mut(&ptr_of(parent))?;
18169                let vc = PAGE_VCS.with(|p| p.borrow().get(&ptr_of(child)).cloned())?;
18170                if is_sidebar && let Some((sc, _)) = state.search.as_ref() {
18171                    let item = unsafe { vc.navigationItem() };
18172                    unsafe {
18173                        item.setSearchController(Some(sc));
18174                        configure_sidebar_search(
18175                            &item,
18176                            &state.nav,
18177                            state.search_hides_on_scroll,
18178                            state.search_initially_hidden,
18179                        );
18180                        if let Some(parts) = state.split.as_ref() {
18181                            configure_sidebar_search(
18182                                &item,
18183                                &parts.primary_nav,
18184                                state.search_hides_on_scroll,
18185                                state.search_initially_hidden,
18186                            );
18187                        }
18188                        vc.setEdgesForExtendedLayout(objc2_ui_kit::UIRectEdge::All);
18189                        vc.setExtendedLayoutIncludesOpaqueBars(true);
18190                    }
18191                } else if !is_sidebar {
18192                    unsafe {
18193                        vc.navigationItem().setLargeTitleDisplayMode(
18194                            objc2_ui_kit::UINavigationItemLargeTitleDisplayMode::Never,
18195                        );
18196                    };
18197                }
18198                if is_sidebar && let Some(parts) = state.split.as_ref() {
18199                    let arr = objc2_foundation::NSArray::from_retained_slice(&[vc]);
18200                    unsafe { parts.primary_nav.setViewControllers(&arr) };
18201                    return Some(None);
18202                }
18203                Some(Some(vc))
18204            });
18205            let set_root = placed.map(|detail| detail.map(|vc| (ptr_of(parent), vc)));
18206            match set_root {
18207                Some(Some((host, vc))) => push_page(host, vc),
18208                Some(None) => {}
18209                None => {
18210                    // A cover's content view already lives inside its DayCoverVC's view —
18211                    // reparenting it into the tree slot (addSubview MOVES a view) would
18212                    // strand the presented cover empty (docs/cover.md).
18213                    if COVER_STATE.with(|m| m.borrow().contains_key(&ptr_of(child))) {
18214                        return;
18215                    }
18216                    // A controller-backed child (a nested nav host, or a tab bar) landing inside
18217                    // a PAGE's content view has to move its UIViewController containment to that
18218                    // page's controller. Every host parents itself to the WINDOW's root VC when
18219                    // it is realized, because at that moment it does not know where it will be
18220                    // inserted; leaving it there is what UIKit rejects the instant the view
18221                    // enters a window:
18222                    //
18223                    //     UIViewControllerHierarchyInconsistency: child view controller
18224                    //     <DayNavController> should have parent view controller <UIViewController>
18225                    //     but actual parent is <DayRootVC>
18226                    //
18227                    // Two stacks under a tab bar is what surfaced it (one per tab, Day Trader's
18228                    // phone shell). A single one hid: only the SELECTED tab's view reaches a
18229                    // window at launch, and the check runs on the way in.
18230                    let host_vc = host_controller(child);
18231                    let page_vc = PAGE_VCS
18232                        .with(|m| m.borrow().get(&ptr_of(parent)).cloned())
18233                        .or_else(|| enclosing_view_controller(parent));
18234                    match (host_vc, page_vc) {
18235                        (Some(host_vc), Some(page_vc)) => {
18236                            unsafe {
18237                                // Order is UIKit's: leave the old parent, join the new one, THEN
18238                                // the view move, then confirm. `didMove` last is what the
18239                                // containment contract asks for.
18240                                host_vc.willMoveToParentViewController(None);
18241                                host_vc.removeFromParentViewController();
18242                                page_vc.addChildViewController(&host_vc);
18243                                parent.addSubview(child);
18244                                host_vc.didMoveToParentViewController(Some(&page_vc));
18245                            }
18246                            // A navigation host brings its own bar; a tab bar does not.
18247                            let tab_bar =
18248                                NAV_TABS.with(|m| m.borrow().contains_key(&ptr_of(child)));
18249                            if !tab_bar {
18250                                unwrap_tab_page(&page_vc);
18251                            }
18252                        }
18253                        _ => unsafe { parent.addSubview(child) },
18254                    }
18255                }
18256            }
18257        }
18258
18259        fn remove(&mut self, parent: &Handle, child: &Handle) {
18260            // Conditional forms can disappear without a controller transition (e.g. login).
18261            unsafe { child.endEditing(false) };
18262            let document = DOCUMENT_HOSTS.with(|m| {
18263                let mut m = m.borrow_mut();
18264                let Some(state) = m.get_mut(&ptr_of(parent)) else {
18265                    return false;
18266                };
18267                if let Some(at) = state
18268                    .pages
18269                    .iter()
18270                    .position(|(key, _)| *key == ptr_of(child))
18271                {
18272                    let (_, vc) = state.pages.remove(at);
18273                    unsafe {
18274                        vc.willMoveToParentViewController(None);
18275                        if let Some(view) = vc.view() {
18276                            view.removeFromSuperview();
18277                        }
18278                        vc.removeFromParentViewController();
18279                    }
18280                    state.selected = state.selected.min(state.pages.len().saturating_sub(1));
18281                    document_frames(parent, state);
18282                } else {
18283                    unsafe {
18284                        child.removeFromSuperview();
18285                    }
18286                }
18287                true
18288            });
18289            if document {
18290                return;
18291            }
18292
18293            let nav_child = NAV_STATE.with(|m| m.borrow().contains_key(&ptr_of(parent)));
18294            if nav_child
18295                && let Some(vc) = PAGE_VCS.with(|p| p.borrow().get(&ptr_of(child)).cloned())
18296            {
18297                pop_page(ptr_of(parent), vc);
18298            }
18299            if !nav_child {
18300                unsafe { child.removeFromSuperview() };
18301                reask_content_frame(parent);
18302            }
18303        }
18304
18305        fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
18306            if let Some(content) = zoom_content(parent) {
18307                unsafe { content.addSubview(child) };
18308                return;
18309            }
18310            unsafe { parent.addSubview(child) };
18311        }
18312
18313        fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
18314            let key = Retained::as_ptr(h) as usize;
18315            if cursor == Cursor::Default {
18316                if let Some((_, interaction)) = self.pointers.remove(&key) {
18317                    unsafe { h.removeInteraction(ProtocolObject::from_ref(&*interaction)) };
18318                }
18319                return;
18320            }
18321            let Some(mtm) = MainThreadMarker::new() else {
18322                return;
18323            };
18324            if let Some((delegate, interaction)) = self.pointers.get(&key) {
18325                *delegate.ivars().cursor.borrow_mut() = cursor;
18326                // Re-request the style if the pointer is already over the view.
18327                unsafe { interaction.invalidate() };
18328            } else {
18329                let delegate = DayPointerDelegate::new(mtm, cursor);
18330                let interaction = unsafe {
18331                    UIPointerInteraction::initWithDelegate(
18332                        UIPointerInteraction::alloc(mtm),
18333                        Some(ProtocolObject::from_ref(&*delegate)),
18334                    )
18335                };
18336                unsafe { h.addInteraction(ProtocolObject::from_ref(&*interaction)) };
18337                self.pointers.insert(key, (delegate, interaction));
18338            }
18339        }
18340
18341        fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
18342            // Every member is a property on UIKit, so the field is dressed in place. Only a
18343            // `text_field` has a target here; an alert's or a search bar's field is not ours.
18344            let tf = (**h).downcast_ref::<UITextField>()?;
18345            let target = TARGETS.with(|m| m.borrow().get(&ptr_of(h)).cloned())?;
18346            let prev = target.ivars().traits.replace(traits.clone());
18347            if prev == *traits {
18348                return None;
18349            }
18350            let editing = tf.isFirstResponder();
18351            if prev.secure != traits.secure {
18352                let text = tf.text().filter(|t| t.length() > 0);
18353                let font = tf.font();
18354                let selection = if editing {
18355                    tf.selectedTextRange()
18356                } else {
18357                    None
18358                };
18359                tf.setSecureTextEntry(traits.secure);
18360                // Flipping a field that is being edited leaves UIKit in two odd states. Going
18361                // secure, the field treats its text as it would on a fresh focus: the next
18362                // keystroke replaces all of it. Going plain, the text keeps the secure
18363                // glyph metrics until it is set again, so the caret sits off the last
18364                // character. Re-entering the text settles both: through the keyboard's own
18365                // insertion path when going secure (which uses up the replace-on-first-key
18366                // state), by assignment otherwise. The caret then goes back where it was.
18367                if editing && let Some(text) = text {
18368                    tf.setText(None);
18369                    if traits.secure {
18370                        target.ivars().muted.set(true);
18371                        tf.insertText(&text);
18372                        target.ivars().muted.set(false);
18373                    } else {
18374                        tf.setFont(font.as_deref());
18375                        tf.setText(Some(&text));
18376                    }
18377                    if selection.is_some() {
18378                        tf.setSelectedTextRange(selection.as_deref());
18379                    }
18380                }
18381            }
18382            if prev.read_only != traits.read_only {
18383                // The delegate (reading the traits stored above) refuses the edits; an empty
18384                // input view keeps the keyboard down, while the field still takes focus, a
18385                // selection and Copy.
18386                let blank = traits.read_only.then(|| UIView::new(mtm()));
18387                tf.setInputView(blank.as_deref());
18388            }
18389            if prev.purpose != traits.purpose {
18390                let (keyboard, content_type, caps, corrects) = purpose_traits(traits.purpose);
18391                // UITextAutocorrectionType / UITextSpellCheckingType: 0 = Default, 1 = No.
18392                let correction: isize = isize::from(!corrects);
18393                let content_type: *const NSString =
18394                    content_type.map_or(std::ptr::null(), std::ptr::from_ref::<NSString>);
18395                // SAFETY: the enum traits are `NSInteger` properties and the content type an
18396                // `NSString *` (nil clears it), as `send_input_trait` requires.
18397                unsafe {
18398                    send_input_trait(tf, sel!(setKeyboardType:), keyboard.0);
18399                    send_input_trait(tf, sel!(setTextContentType:), content_type);
18400                    send_input_trait(tf, sel!(setAutocapitalizationType:), caps.0);
18401                    send_input_trait(tf, sel!(setAutocorrectionType:), correction);
18402                    send_input_trait(tf, sel!(setSpellCheckingType:), correction);
18403                }
18404            }
18405            if prev.submit_label != traits.submit_label {
18406                let key = match traits.submit_label {
18407                    SubmitLabel::Return => UIReturnKeyType::Default,
18408                    SubmitLabel::Done => UIReturnKeyType::Done,
18409                    SubmitLabel::Go => UIReturnKeyType::Go,
18410                    SubmitLabel::Next => UIReturnKeyType::Next,
18411                    SubmitLabel::Search => UIReturnKeyType::Search,
18412                    SubmitLabel::Send => UIReturnKeyType::Send,
18413                };
18414                // SAFETY: `returnKeyType` is an `NSInteger` property.
18415                unsafe { send_input_trait(tf, sel!(setReturnKeyType:), key.0) };
18416            }
18417            // A keyboard that is already up keeps its layout, action key and input view
18418            // until asked to reload them. No native length limit: day-pieces holds
18419            // `max_length`.
18420            if editing
18421                && (prev.read_only != traits.read_only
18422                    || prev.purpose != traits.purpose
18423                    || prev.submit_label != traits.submit_label)
18424            {
18425                tf.reloadInputViews();
18426            }
18427            None
18428        }
18429
18430        fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
18431            // A backing that already is a text view (an earlier swap): flip the flag in place.
18432            if let Some(tv) = (**h).downcast_ref::<UITextView>() {
18433                unsafe { tv.setSelectable(selectable) };
18434                // A link label's view already has its delegate; this covers any other.
18435                if let Some(look) = LABEL_LOOKS.with(|t| t.get(ptr_of(h)))
18436                    && look.reports
18437                {
18438                    DayTextLink::attach(tv, look.node, false, mtm());
18439                }
18440                return None;
18441            }
18442            // UIKit reserves selection for UITextInput views, so a UILabel has no flag to flip
18443            // (SwiftUI's selectable Text is its own renderer with the system selection UI
18444            // attached — not a UILabel either). The standard emulation ships here instead: the
18445            // label is rebuilt as a read-only, non-scrolling UITextView, geometry-matched to
18446            // the label (zero inset and padding, so `sizeThatFits` measures the same), and
18447            // day-core re-points the node's handle at the replacement (docs/text.md).
18448            let label = (**h).downcast_ref::<UILabel>()?;
18449            if !selectable {
18450                return None; // a plain UILabel is already unselectable
18451            }
18452            let tv = label_text_view(mtm());
18453            unsafe {
18454                tv.setFont(label.font().as_deref());
18455                tv.setTextColor(label.textColor().as_deref());
18456                // Styled runs live in the label's ATTRIBUTED text; copying `text()` alone would
18457                // hand the text view the plain string and silently drop every run. Font and
18458                // color go on first so they still stand as the view's defaults.
18459                match label.attributedText() {
18460                    Some(a) => tv.setAttributedText(Some(&a)),
18461                    None => tv.setText(label.text().as_deref()),
18462                }
18463                let adj: bool = msg_send![label, adjustsFontForContentSizeCategory];
18464                let _: () = msg_send![&*tv, setAdjustsFontForContentSizeCategory: adj];
18465                let align: isize = msg_send![label, textAlignment];
18466                let _: () = msg_send![&*tv, setTextAlignment: align];
18467                tv.setEditable(false);
18468                tv.setSelectable(true);
18469                tv.setScrollEnabled(false);
18470                tv.setBackgroundColor(None);
18471                tv.setTextContainerInset(UIEdgeInsets {
18472                    top: 0.0,
18473                    left: 0.0,
18474                    bottom: 0.0,
18475                    right: 0.0,
18476                });
18477                // The container pads 5pt per side by default; raw sends spare day-toolkit-uikit the
18478                // NSTextContainer binding for this one call.
18479                let container: *mut AnyObject = msg_send![&*tv, textContainer];
18480                let _: () = msg_send![container, setLineFragmentPadding: 0.0f64];
18481                // `.id()` may have run before `.selectable()` — carry the identifier over.
18482                let ident: Option<Retained<NSString>> = msg_send![&**h, accessibilityIdentifier];
18483                if let Some(i) = ident {
18484                    let _: () = msg_send![&*tv, setAccessibilityIdentifier: &*i];
18485                }
18486                // A swap on a LIVE node (a `.tweak` after mount): take the label's place in the
18487                // view tree; the re-pointed handle routes later layout and patches here.
18488                if let Some(sup) = label.superview() {
18489                    tv.setFrame(label.frame());
18490                    sup.insertSubview_aboveSubview(
18491                        <UITextView as AsRef<UIView>>::as_ref(&tv),
18492                        <UILabel as AsRef<UIView>>::as_ref(label),
18493                    );
18494                    label.removeFromSuperview();
18495                }
18496            }
18497            let view = view_of(&tv);
18498            // The look moves with the label: the line limit becomes the text container's,
18499            // the spacing and line height go back on the copied text, and a label that asked
18500            // for selection reports gets the delegate that hears them (docs/text.md).
18501            if let Some(mut look) = LABEL_LOOKS.with(|t| t.take(ptr_of(h))) {
18502                look.view = objc2::rc::Weak::from_retained(&view);
18503                let reports = look.reports.then_some(look.node);
18504                LABEL_LOOKS.with(|t| t.insert(ptr_of(&view), look));
18505                apply_paragraph(&view);
18506                if let Some(node) = reports {
18507                    DayTextLink::attach(&tv, node, false, mtm());
18508                }
18509            }
18510            Some(view)
18511        }
18512
18513        fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
18514            let fit = |w: f64, hh: f64| {
18515                let s = unsafe { h.sizeThatFits(CGSize::new(w, hh)) };
18516                Size::new(s.width.ceil(), s.height.ceil())
18517            };
18518            match kind {
18519                kinds::NAV_MENU => {
18520                    // Headings take room too, so a sectioned sidebar measures taller than its rows
18521                    // alone — the flat count under-reported it by a heading band per group.
18522                    let (rows, headings) = NAV_MENUS.with(|m| {
18523                        m.borrow().get(&ptr_of(h)).map_or((0, 0), |(data, n)| {
18524                            let headings =
18525                                data.groups().iter().filter(|(t, _, _)| t.is_some()).count();
18526                            (*n, headings)
18527                        })
18528                    });
18529                    Size::new(
18530                        p.width.unwrap_or(320.0),
18531                        p.height
18532                            .unwrap_or(rows as f64 * 44.0 + headings as f64 * 30.0 + 40.0),
18533                    )
18534                }
18535                kinds::LABEL => {
18536                    let w = p.width.unwrap_or(1.0e6);
18537                    let s = fit(w, 1.0e6);
18538                    Size::new(s.width.min(w), s.height)
18539                }
18540                kinds::BUTTON | kinds::TOGGLE => fit(1.0e6, 1.0e6),
18541                kinds::SLIDER => {
18542                    Size::new(p.width.unwrap_or(180.0), fit(1.0e6, 1.0e6).height.max(31.0))
18543                }
18544                kinds::PICKER => crate::picker::measure_any(self, h, p),
18545                kinds::TEXT_AREA => crate::textarea::measure_any(self, h, p),
18546                kinds::TEXT_FIELD => {
18547                    Size::new(p.width.unwrap_or(180.0), fit(1.0e6, 1.0e6).height.max(34.0))
18548                }
18549                kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
18550                // UIKit sizes its own row content: the stack fitted at the row's width.
18551                kinds::LIST_ITEM => {
18552                    let width = p.width.unwrap_or(1.0e4);
18553                    let s = unsafe {
18554                        h.systemLayoutSizeFittingSize_withHorizontalFittingPriority_verticalFittingPriority(
18555                            CGSize::new(width, 0.0),
18556                            if p.width.is_some() { 1000.0 } else { 50.0 },
18557                            50.0,
18558                        )
18559                    };
18560                    Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil())
18561                }
18562                kinds::PROGRESS => {
18563                    if (**h).downcast_ref::<UIActivityIndicatorView>().is_some() {
18564                        fit(1.0e6, 1.0e6)
18565                    } else {
18566                        Size::new(p.width.unwrap_or(180.0), 4.0)
18567                    }
18568                }
18569                kinds::LIST | kinds::TREE => {
18570                    Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
18571                }
18572                _ => {
18573                    if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
18574                        measure(self, h, p)
18575                    } else {
18576                        let s = fit(1.0e6, 1.0e6);
18577                        Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
18578                    }
18579                }
18580            }
18581        }
18582
18583        /// UIKit exposes baselines only as layout ANCHORS (`firstBaselineAnchor`), which are
18584        /// constraint endpoints with no readable number, so this derives the offset from the
18585        /// view's own font instead (docs/baseline.md — `Cap::BaselineAlignment` is `Emulated`
18586        /// here for exactly that reason).
18587        ///
18588        /// The model is the one UIKit itself uses for a single-line control: center the font's
18589        /// line box in the view's height, and the baseline sits an ascender below the line's
18590        /// top. For a label day has sized to its text that reduces to the ascender, and for a
18591        /// bordered field it accounts for the inset the border adds.
18592        fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
18593            if !day_spec::kind_has_baseline(kind) {
18594                return None;
18595            }
18596            let font = unsafe {
18597                if let Some(l) = (**h).downcast_ref::<UILabel>() {
18598                    l.font()
18599                } else if let Some(f) = (**h).downcast_ref::<UITextField>() {
18600                    f.font()
18601                } else if let Some(v) = (**h).downcast_ref::<UITextView>() {
18602                    v.font()
18603                } else if let Some(b) = (**h).downcast_ref::<UIButton>() {
18604                    b.titleLabel().and_then(|l| l.font())
18605                } else {
18606                    None
18607                }
18608            }?;
18609            let (ascender, line_height) = unsafe { (font.ascender(), font.lineHeight()) };
18610            // A fixed line height (docs/text.md "Line height"): the glyphs sit centered in the
18611            // first line box, half the difference from the natural height down.
18612            let fixed = LABEL_LOOKS
18613                .with(|t| t.get(ptr_of(h)))
18614                .and_then(|look| crate::label_text::line_height(look.para.line_height));
18615            if let Some(multiple) = fixed {
18616                let line = multiple * unsafe { font.pointSize() };
18617                return Some((line - line_height) / 2.0 + ascender);
18618            }
18619            Some(((size.height - line_height) / 2.0).max(0.0) + ascender)
18620        }
18621
18622        fn set_frame(&mut self, h: &Handle, frame: Rect, anim: Option<&AnimSpec>) {
18623            // Nav page content: the page view pins it to the safe area (native-owned).
18624            if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
18625                return;
18626            }
18627            let f = CGRect::new(
18628                CGPoint::new(frame.origin.x, frame.origin.y),
18629                CGSize::new(frame.size.width, frame.size.height),
18630            );
18631            let v = h;
18632            animate_channel(h, Channel::Frame, anim, || unsafe {
18633                // `frame` is undefined under a transform (`set_transform`): setting it fits the
18634                // transformed box into the rect, which cancels the scale and the offset. Size
18635                // and center are independent of the transform, so a transformed view takes
18636                // those. Others keep `setFrame`: a scroll view's bounds origin is its offset.
18637                let t = v.transform();
18638                #[expect(clippy::float_cmp, reason = "exact identity-transform test")]
18639                let identity = t.a == 1.0
18640                    && t.b == 0.0
18641                    && t.c == 0.0
18642                    && t.d == 1.0
18643                    && t.tx == 0.0
18644                    && t.ty == 0.0;
18645                if identity {
18646                    v.setFrame(f);
18647                } else {
18648                    let mut b = v.bounds();
18649                    b.size = f.size;
18650                    v.setBounds(b);
18651                    v.setCenter(CGPoint::new(
18652                        f.origin.x + f.size.width / 2.0,
18653                        f.origin.y + f.size.height / 2.0,
18654                    ));
18655                }
18656            });
18657            DOCUMENT_HOSTS.with(|m| {
18658                if let Some(state) = m.borrow().get(&ptr_of(h)) {
18659                    document_frames(h, state);
18660                }
18661            });
18662        }
18663
18664        fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
18665            animate_channel(h, Channel::Opacity, anim, || unsafe {
18666                h.setAlpha(opacity as CGFloat);
18667            });
18668        }
18669
18670        fn set_transform(
18671            &mut self,
18672            h: &Handle,
18673            t: Transform,
18674            _size: Size,
18675            anim: Option<&AnimSpec>,
18676        ) {
18677            let tf = cgaffine(t);
18678            animate_channel(h, Channel::Transform, anim, || unsafe {
18679                h.setTransform(tf);
18680            });
18681        }
18682
18683        fn set_scroll_content(&mut self, h: &Handle, content: Size) {
18684            let Some(sv) = (**h).downcast_ref::<UIScrollView>() else {
18685                return;
18686            };
18687            let Some(zoomed) = zoom_content(sv) else {
18688                unsafe { sv.setContentSize(CGSize::new(content.width, content.height)) };
18689                return;
18690            };
18691            // Day lays the content out at its natural size; UIKit scales the view by the zoom
18692            // transform, under which `frame` is undefined, so the view takes its size as
18693            // bounds and its place as center, and the scroll range is the scaled size.
18694            let scale = sv.zoomScale();
18695            let (w, h) = (content.width * scale, content.height * scale);
18696            zoomed.setBounds(CGRect::new(
18697                CGPoint::new(0.0, 0.0),
18698                CGSize::new(content.width, content.height),
18699            ));
18700            zoomed.setCenter(CGPoint::new(w / 2.0, h / 2.0));
18701            unsafe { sv.setContentSize(CGSize::new(w, h)) };
18702        }
18703
18704        /// UIKit's own row: the table's layout margins at the sides (16 or 20pt, by width), and
18705        /// the top/bottom margins and height of a stock cell showing one line of its default
18706        /// content configuration, measured by UIKit itself.
18707        fn list_row_metrics(&mut self, h: &Handle) -> day_spec::RowMetrics {
18708            let Some(table) = (**h).downcast_ref::<objc2_ui_kit::UITableView>() else {
18709                return day_spec::RowMetrics::default();
18710            };
18711            let sides = unsafe { table.layoutMargins() };
18712            let (vertical, height) = NATIVE_ROW.with(|r| *r.get_or_init(native_row));
18713            day_spec::RowMetrics {
18714                insets: day_spec::Insets {
18715                    top: vertical,
18716                    leading: sides.left,
18717                    bottom: vertical,
18718                    trailing: sides.right,
18719                },
18720                min_height: height,
18721            }
18722        }
18723
18724        fn nav_scroll_to_edge(&mut self, h: &Handle, bottom: bool) -> bool {
18725            let Some(cv) = h.downcast_ref::<objc2_ui_kit::UICollectionView>() else {
18726                return false;
18727            };
18728            let path = NAV_MENUS.with(|menus| {
18729                let menus = menus.borrow();
18730                let (data, count) = menus.get(&ptr_of(h))?;
18731                data.path_of(if bottom { count.checked_sub(1)? } else { 0 })
18732            });
18733            let Some((section, item)) = path else {
18734                return true; // An empty menu already fits.
18735            };
18736            unsafe {
18737                cv.layoutIfNeeded();
18738                let path = objc2_foundation::NSIndexPath::indexPathForItem_inSection(
18739                    item as isize,
18740                    section as isize,
18741                );
18742                cv.scrollToItemAtIndexPath_atScrollPosition_animated(
18743                    &path,
18744                    if bottom {
18745                        objc2_ui_kit::UICollectionViewScrollPosition::Bottom
18746                    } else {
18747                        objc2_ui_kit::UICollectionViewScrollPosition::Top
18748                    },
18749                    false,
18750                );
18751                if !bottom {
18752                    // Include the first section heading, above its first row.
18753                    cv.setContentOffset_animated(
18754                        CGPoint::new(cv.contentOffset().x, -cv.adjustedContentInset().top),
18755                        false,
18756                    );
18757                }
18758            }
18759            true
18760        }
18761
18762        /// The content offset from the content's top-leading corner (docs/scroll.md "Offset
18763        /// and phase"): the scroll view's own offset, less the insets UIKit adds around the
18764        /// content (a bar or safe area the content scrolls under), so a view at rest at its
18765        /// top answers zero.
18766        fn scroll_offset(&mut self, h: &Handle) -> day_spec::Point {
18767            (**h)
18768                .downcast_ref::<UIScrollView>()
18769                .map_or(day_spec::Point::ZERO, content_offset)
18770        }
18771
18772        /// Queued behind the splices and reloads posted before it, which may be what made its
18773        /// row (DESIGN.md §10), then aligned and animated by the table itself.
18774        fn list_scroll(&mut self, h: &Handle, to: day_spec::ListScroll) -> bool {
18775            let key = ptr_of(h);
18776            if !LIST_STATE.with(|m| m.borrow().contains_key(&key)) {
18777                return false;
18778            }
18779            <Uikit as Platform>::post(Box::new(move || {
18780                let entry = LIST_STATE.with(|m| m.borrow().get(&key).cloned());
18781                if let Some((table, data)) = entry {
18782                    data.scroll(&table, to);
18783                }
18784            }));
18785            true
18786        }
18787
18788        fn scroll_to(&mut self, h: &Handle, target: Rect, animated: bool) {
18789            if let Some(sv) = (**h).downcast_ref::<UIScrollView>() {
18790                unsafe {
18791                    sv.scrollRectToVisible_animated(
18792                        CGRect::new(
18793                            CGPoint::new(target.origin.x, target.origin.y),
18794                            CGSize::new(target.size.width, target.size.height),
18795                        ),
18796                        animated,
18797                    );
18798                };
18799            }
18800        }
18801
18802        fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
18803            if focusable {
18804                KEY_NODES.with(|t| t.insert(ptr_of(h), node));
18805            } else {
18806                KEY_NODES.with(|t| t.remove(ptr_of(h)));
18807            }
18808        }
18809
18810        fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
18811            // Focus IS the keyboard on iOS: becoming first responder raises it, resigning
18812            // dismisses it. Resign only while this view still owns it, so a stale release
18813            // can't drop a sibling's keyboard.
18814            unsafe {
18815                if !focused {
18816                    if h.isFirstResponder() {
18817                        h.resignFirstResponder();
18818                    }
18819                    return;
18820                }
18821                if h.becomeFirstResponder() {
18822                    return;
18823                }
18824            }
18825            // A refusal can be TRANSIENT — the outgoing responder is still tearing its keyboard
18826            // down, and UIKit will not hand focus over mid-transition — so retry once on the
18827            // next turn (GTK's un-mapped-widget retry, rule 4 in docs/focus.md).
18828            //
18829            // It can also be permanent, and correctly so: a view that is not in a WINDOW cannot
18830            // hold the keyboard, and a full-screen modal takes the presenting view out of the
18831            // window for as long as it covers it. A canvas behind a compact inspector sheet
18832            // (docs/inspector.md) refuses focus until the sheet closes — the retry lapses and
18833            // the binding's signal snaps back, which is rule 2.
18834            let Some(mtm) = MainThreadMarker::new() else {
18835                return;
18836            };
18837            let view = dispatch2::MainThreadBound::new(h.clone(), mtm);
18838            dispatch2::DispatchQueue::main().exec_async(move || {
18839                day_spec::ffi_guard::contain((), || {
18840                    let Some(mtm) = MainThreadMarker::new() else {
18841                        return;
18842                    };
18843                    let view = view.get(mtm);
18844                    if !view.isFirstResponder() {
18845                        let _ = unsafe { view.becomeFirstResponder() };
18846                    }
18847                });
18848            });
18849        }
18850
18851        fn set_event_sink(&mut self, sink: EventSink) {
18852            SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
18853        }
18854
18855        fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
18856            let key = ptr_of(h);
18857            let already = GESTURES.with(|m| {
18858                m.borrow()
18859                    .get(&key)
18860                    .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
18861            });
18862            if already {
18863                return;
18864            }
18865            let mtm = mtm();
18866            // Press and touches observe (docs/gestures.md "Press", "Touches"): a recognizer
18867            // that never recognizes, so nothing else on the view or around it changes.
18868            if matches!(
18869                kind,
18870                day_spec::GestureKind::Press | day_spec::GestureKind::Touches
18871            ) {
18872                let what = if kind == day_spec::GestureKind::Press {
18873                    Observe::Press
18874                } else {
18875                    Observe::Touches
18876                };
18877                let observers = OBSERVERS.with(|t| t.get(key)).unwrap_or_default();
18878                if observers.iter().any(|o| o.ivars().what == what) {
18879                    return;
18880                }
18881                let observer = DayObserver::new(mtm, node, what);
18882                unsafe {
18883                    if what == Observe::Touches {
18884                        h.setMultipleTouchEnabled(true);
18885                    }
18886                    allow_interaction(h);
18887                    h.addGestureRecognizer(&observer);
18888                }
18889                OBSERVERS.with(|t| {
18890                    let mut list = t.take(key).unwrap_or_default();
18891                    list.push(observer);
18892                    t.insert(key, list);
18893                });
18894                return;
18895            }
18896            let target = DayGesture::new(mtm, node, kind);
18897            unsafe {
18898                let recognizer: Retained<UIGestureRecognizer> = match kind {
18899                    day_spec::GestureKind::Drag => {
18900                        let pan = UIPanGestureRecognizer::initWithTarget_action(
18901                            UIPanGestureRecognizer::alloc(mtm),
18902                            Some(&target),
18903                            Some(sel!(fire:)),
18904                        );
18905                        // Weak; `target` is kept alive in GESTURES below. The axis hint and
18906                        // the claim on an enclosing scroll view ride on it.
18907                        pan.setDelegate(Some(ProtocolObject::from_ref(&*target)));
18908                        Retained::into_super(pan)
18909                    }
18910                    day_spec::GestureKind::Pinch => {
18911                        let pinch = UIPinchGestureRecognizer::initWithTarget_action(
18912                            UIPinchGestureRecognizer::alloc(mtm),
18913                            Some(&target),
18914                            Some(sel!(fire:)),
18915                        );
18916                        pinch.setDelegate(Some(ProtocolObject::from_ref(&*target)));
18917                        Retained::into_super(pinch)
18918                    }
18919                    day_spec::GestureKind::LongPress => {
18920                        // The platform's delay and movement allowance (0.5 s, 10 pt). A tap
18921                        // on the same view fails once this recognizes.
18922                        let press =
18923                            objc2_ui_kit::UILongPressGestureRecognizer::initWithTarget_action(
18924                                objc2_ui_kit::UILongPressGestureRecognizer::alloc(mtm),
18925                                Some(&target),
18926                                Some(sel!(fire:)),
18927                            );
18928                        press.setDelegate(Some(ProtocolObject::from_ref(&*target)));
18929                        Retained::into_super(press)
18930                    }
18931                    day_spec::GestureKind::DoubleTap => {
18932                        let tap = UITapGestureRecognizer::initWithTarget_action(
18933                            UITapGestureRecognizer::alloc(mtm),
18934                            Some(&target),
18935                            Some(sel!(fire:)),
18936                        );
18937                        tap.setNumberOfTapsRequired(2);
18938                        Retained::into_super(tap)
18939                    }
18940                    day_spec::GestureKind::Rotate => {
18941                        let rotate = UIRotationGestureRecognizer::initWithTarget_action(
18942                            UIRotationGestureRecognizer::alloc(mtm),
18943                            Some(&target),
18944                            Some(sel!(fire:)),
18945                        );
18946                        // Weak; `target` is kept alive in GESTURES below.
18947                        rotate.setDelegate(Some(ProtocolObject::from_ref(&*target)));
18948                        Retained::into_super(rotate)
18949                    }
18950                    day_spec::GestureKind::Pan => {
18951                        // Two fingers, so single-finger drags still reach a Drag gesture on
18952                        // the same view.
18953                        let pan = UIPanGestureRecognizer::initWithTarget_action(
18954                            UIPanGestureRecognizer::alloc(mtm),
18955                            Some(&target),
18956                            Some(sel!(fire:)),
18957                        );
18958                        pan.setMinimumNumberOfTouches(2);
18959                        pan.setMaximumNumberOfTouches(2);
18960                        Retained::into_super(pan)
18961                    }
18962                    day_spec::GestureKind::Hover => {
18963                        // UIKit does have a hover recognizer, and it fires only with a pointer:
18964                        // an iPad with a trackpad, a mouse, or an Apple Pencil hovering. A
18965                        // finger-only device attaches it and never hears from it, which is the
18966                        // contract (docs/canvas.md "Interaction").
18967                        let hover = objc2_ui_kit::UIHoverGestureRecognizer::initWithTarget_action(
18968                            objc2_ui_kit::UIHoverGestureRecognizer::alloc(mtm),
18969                            Some(&target),
18970                            Some(sel!(fire:)),
18971                        );
18972                        Retained::into_super(hover)
18973                    }
18974                    _ => {
18975                        let tap = UITapGestureRecognizer::initWithTarget_action(
18976                            UITapGestureRecognizer::alloc(mtm),
18977                            Some(&target),
18978                            Some(sel!(fire:)),
18979                        );
18980                        Retained::into_super(tap)
18981                    }
18982                };
18983                allow_interaction(h);
18984                h.addGestureRecognizer(&recognizer);
18985                // A single tap waits for the double tap on the same view to fail, whichever
18986                // of the two was enabled first (docs/gestures.md "Double tap").
18987                let partner = match kind {
18988                    day_spec::GestureKind::Tap => Some(day_spec::GestureKind::DoubleTap),
18989                    day_spec::GestureKind::DoubleTap => Some(day_spec::GestureKind::Tap),
18990                    _ => None,
18991                };
18992                if let Some(partner) = partner {
18993                    let other = GESTURES.with(|m| {
18994                        m.borrow().get(&key).and_then(|v| {
18995                            v.iter()
18996                                .find(|t| t.ivars().kind == partner)
18997                                .and_then(|t| t.ivars().recognizer.borrow().clone())
18998                        })
18999                    });
19000                    if let Some(other) = other {
19001                        let (single, double) = if kind == day_spec::GestureKind::Tap {
19002                            (&recognizer, &other)
19003                        } else {
19004                            (&other, &recognizer)
19005                        };
19006                        single.requireGestureRecognizerToFail(double);
19007                    }
19008                }
19009                target.ivars().recognizer.replace(Some(recognizer));
19010            }
19011            GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
19012        }
19013
19014        /// Dynamic Type's factor for `style` (docs/text.md "Text scale"): the style's
19015        /// preferred size now over its size at the default `.large` category, so a small style
19016        /// that grows faster than a large one answers for itself. Sized styles (`System`,
19017        /// `Custom`) scale through the body metrics, as `resolve_font` scales them.
19018        fn text_scale(&mut self, style: Font) -> f64 {
19019            use objc2_ui_kit::{
19020                UIContentSizeCategoryLarge, UIFont, UIFontMetrics, UITraitCollection,
19021            };
19022            let scale = match ui_text_style(style) {
19023                Some(ts) => unsafe {
19024                    let now = UIFont::preferredFontForTextStyle(ts).pointSize();
19025                    let large = UITraitCollection::traitCollectionWithPreferredContentSizeCategory(
19026                        UIContentSizeCategoryLarge,
19027                    );
19028                    let default = UIFont::preferredFontForTextStyle_compatibleWithTraitCollection(
19029                        ts,
19030                        Some(&large),
19031                    )
19032                    .pointSize();
19033                    now / default
19034                },
19035                None => unsafe { UIFontMetrics::defaultMetrics().scaledValueForValue(1.0) },
19036            };
19037            if scale.is_finite() && scale > 0.0 {
19038                scale
19039            } else {
19040                1.0
19041            }
19042        }
19043
19044        /// A subtree's reading direction on one widget (docs/localization.md "Direction of a
19045        /// subtree"): `semanticContentAttribute` forced on the control, which flips what is
19046        /// inside it (a switch's on side, a slider's fill, a segmented control's order, a
19047        /// field's natural alignment). Leaf controls only: Day places every child by frame,
19048        /// and a forced attribute on a list or collection view would mirror its own layout.
19049        /// A label also takes the direction as its base writing direction and as the edge
19050        /// `Leading`/`Trailing` resolve to (`apply_paragraph`).
19051        fn set_layout_direction(
19052            &mut self,
19053            h: &Handle,
19054            kind: PieceKind,
19055            direction: day_spec::LayoutDirection,
19056        ) {
19057            use objc2_ui_kit::UISemanticContentAttribute;
19058            if !matches!(
19059                kind,
19060                kinds::LABEL
19061                    | kinds::BUTTON
19062                    | kinds::TOGGLE
19063                    | kinds::SLIDER
19064                    | kinds::TEXT_FIELD
19065                    | kinds::TEXT_AREA
19066                    | kinds::PICKER
19067                    | kinds::PROGRESS
19068            ) {
19069                return;
19070            }
19071            let rtl = direction == day_spec::LayoutDirection::Rtl;
19072            unsafe {
19073                h.setSemanticContentAttribute(if rtl {
19074                    UISemanticContentAttribute::ForceRightToLeft
19075                } else {
19076                    UISemanticContentAttribute::ForceLeftToRight
19077                });
19078            }
19079            if kind == kinds::LABEL {
19080                LABEL_LOOKS.with(|t| t.with(ptr_of(h), |l| l.rtl = Some(rtl)));
19081                apply_paragraph(h);
19082            }
19083        }
19084
19085        fn gesture_support(&self, _kind: day_spec::GestureKind) -> Support {
19086            // Every kind is UIKit's own recognizer: UILongPressGestureRecognizer, a two-tap
19087            // UITapGestureRecognizer, and an observing recognizer subclass for press and for
19088            // multi-touch contacts (docs/gestures.md "Recognizers").
19089            Support::Native
19090        }
19091
19092        fn set_hit_slop(&mut self, h: &Handle, _node: NodeId, slop: day_spec::Insets) {
19093            if slop == day_spec::Insets::ZERO {
19094                HIT_SLOP.with(|t| t.remove(ptr_of(h)));
19095            } else {
19096                HIT_SLOP.with(|t| t.insert(ptr_of(h), slop));
19097            }
19098        }
19099
19100        fn set_drag_axis(&mut self, h: &Handle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
19101            match axis {
19102                Some(axis) => DRAG_AXIS.with(|t| t.insert(ptr_of(h), axis)),
19103                None => DRAG_AXIS.with(|t| t.remove(ptr_of(h))),
19104            };
19105        }
19106
19107        fn set_subtree_enabled(&mut self, h: &Handle, _node: NodeId, enabled: bool) {
19108            set_group_enabled(h, enabled);
19109        }
19110
19111        fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
19112            let key = ptr_of(h);
19113            if let Some((old, _)) = CTX_MENU_FNS.with(|t| t.borrow_mut().remove(&key)) {
19114                unsafe { h.removeInteraction(ProtocolObject::from_ref(&*old)) };
19115            }
19116            let mtm = mtm();
19117            let delegate = DayContextMenuFn::new(mtm, f);
19118            let proto = ProtocolObject::from_ref(&*delegate);
19119            let interaction = unsafe {
19120                UIContextMenuInteraction::initWithDelegate(
19121                    UIContextMenuInteraction::alloc(mtm),
19122                    proto,
19123                )
19124            };
19125            unsafe {
19126                allow_interaction(h);
19127                h.addInteraction(ProtocolObject::from_ref(&*interaction));
19128            }
19129            CTX_MENU_FNS.with(|t| t.borrow_mut().insert(key, (interaction, delegate)));
19130        }
19131
19132        fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
19133            /// The completion block UIKit hands a deferred element's provider.
19134            type Completion =
19135                block2::DynBlock<dyn Fn(NonNull<objc2_foundation::NSArray<UIMenuElement>>)>;
19136            // docs/menus.md "Menu buttons": the button's own menu is its primary action, and
19137            // the one element in it is deferred and uncached, so UIKit asks the provider each
19138            // time the menu opens and the entries are the current ones. Both APIs are iOS 14/15,
19139            // inside the iOS 15 floor the scaffold declares.
19140            let Some(btn) = h.downcast_ref::<UIButton>() else {
19141                return;
19142            };
19143            let mtm = mtm();
19144            let provider = block2::RcBlock::new(move |done: NonNull<Completion>| {
19145                // Guarded: the provider is app code. The same lowering a context menu
19146                // uses; its children (separator runs as inline sections) fill the menu.
19147                let items = day_spec::ffi_guard::contain(Vec::new(), || f(day_spec::Point::ZERO));
19148                let children = build_ui_menu(mtm, "", &items).children();
19149                // SAFETY: UIKit hands a live completion block and calls this provider
19150                // on the main thread; it copies the array it is given.
19151                unsafe { done.as_ref().call((NonNull::from(&*children),)) };
19152            });
19153            // SAFETY: the block's argument is the completion UIKit passes, used as declared.
19154            let deferred = unsafe {
19155                objc2_ui_kit::UIDeferredMenuElement::elementWithUncachedProvider(&provider, mtm)
19156            };
19157            let element: Retained<UIMenuElement> = Retained::into_super(deferred);
19158            let arr = objc2_foundation::NSArray::from_retained_slice(&[element]);
19159            let menu =
19160                unsafe { UIMenu::menuWithTitle_children(&NSString::from_str(""), &arr, mtm) };
19161            // The press opens the menu instead of reporting a tap: drop the realize-time
19162            // `fire:` target so `Pressed` can never ride along.
19163            unsafe {
19164                btn.removeTarget_action_forControlEvents(
19165                    None,
19166                    None,
19167                    UIControlEvents::TouchUpInside,
19168                );
19169            }
19170            btn.setMenu(Some(&menu));
19171            btn.setShowsMenuAsPrimaryAction(true);
19172        }
19173
19174        fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
19175            let key = ptr_of(h);
19176            // Remove any prior interaction (replace-on-reconfigure): the table's teardown
19177            // detaches it from the view before dropping the retains.
19178            CTX_MENUS.with(|t| t.remove(key));
19179            if items.is_empty() {
19180                return;
19181            }
19182            let mtm = mtm();
19183            let menu = build_ui_menu(mtm, "", items);
19184            let delegate = DayContextMenu::new(mtm, menu);
19185            let proto = ProtocolObject::from_ref(&*delegate);
19186            let interaction = unsafe {
19187                UIContextMenuInteraction::initWithDelegate(
19188                    UIContextMenuInteraction::alloc(mtm),
19189                    proto,
19190                )
19191            };
19192            unsafe {
19193                allow_interaction(h);
19194                h.addInteraction(ProtocolObject::from_ref(&*interaction));
19195            }
19196            CTX_MENUS.with(|t| t.insert(key, (interaction, delegate)));
19197        }
19198
19199        fn set_app_menu(&mut self, _items: &[day_spec::MenuItem]) {
19200            // iOS has no persistent global menu bar (that is a Mac Catalyst / iPad-with-keyboard
19201            // concern handled via UIMenuBuilder in `buildMenuWithBuilder:`). On iPhone the native
19202            // affordances are the per-view context menu (`set_context_menu`) and the system edit
19203            // menu; a global bar is intentionally a no-op here. See docs/menus.md.
19204        }
19205
19206        fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool {
19207            lifecycle_supported(phase)
19208        }
19209
19210        fn set_edit_state(&mut self, state: &day_spec::EditState) {
19211            EDIT_STATE.with(|s| s.set(*state));
19212        }
19213
19214        fn set_undo_state(&mut self, state: &day_spec::UndoState) {
19215            let front = undo_front(self.mtm());
19216            *front.ivars().state.borrow_mut() = state.clone();
19217        }
19218
19219        fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
19220            let key = ptr_of(host);
19221            if let Some(data) = tree_entry_u(key) {
19222                data.ivars().source.replace(Some(source));
19223            }
19224            // Prime outside this borrow: the one flat snapshot that creates the section,
19225            // then the first section snapshot from the (possibly still empty) hierarchy —
19226            // the piece's own initial Reload re-applies once the data lands.
19227            <Uikit as Platform>::post(Box::new(move || {
19228                day_spec::ffi_guard::contain((), || {
19229                    let Some(data) = tree_entry_u(key) else {
19230                        return;
19231                    };
19232                    let ds = data.ivars().ds.borrow().clone();
19233                    let Some(ds) = ds else { return };
19234                    let flat: Retained<
19235                        objc2_ui_kit::NSDiffableDataSourceSnapshot<NSObject, NSObject>,
19236                    > = unsafe {
19237                        msg_send![
19238                            <objc2_ui_kit::NSDiffableDataSourceSnapshot<NSObject, NSObject> as objc2::AnyThread>::alloc(),
19239                            init
19240                        ]
19241                    };
19242                    let section =
19243                        unsafe { Retained::cast_unchecked::<NSObject>(DayTreeData::section()) };
19244                    flat.appendSectionsWithIdentifiers(
19245                        &objc2_foundation::NSArray::from_retained_slice(&[section]),
19246                    );
19247                    ds.applySnapshot_animatingDifferences(&flat, false);
19248                    data.apply_snapshot(false);
19249                });
19250            }));
19251        }
19252
19253        fn attach_list(&mut self, host: &Handle, source: ListSource) {
19254            LIST_STATE.with(|m| {
19255                if let Some((table, data)) = m.borrow().get(&ptr_of(host)) {
19256                    data.ivars().source.replace(Some(source));
19257                    unsafe { table.reloadData() };
19258                }
19259            });
19260        }
19261
19262        fn adopt(&mut self, raw: RawHandle) -> Handle {
19263            // A recycling UITableViewCell's contentView — Day fills/rebinds its row content there.
19264            let ptr = raw.cast::<UIView>();
19265            unsafe { Retained::retain(ptr) }.expect("adopt: null list cell content")
19266        }
19267
19268        fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
19269            unsafe {
19270                if let Some(id) = &a11y.identifier {
19271                    let ns = NSString::from_str(id);
19272                    let _: () = msg_send![&**h, setAccessibilityIdentifier: &*ns];
19273                }
19274                if let Some(label) = &a11y.label {
19275                    APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
19276                    let ns = NSString::from_str(label);
19277                    let _: () = msg_send![&**h, setAccessibilityLabel: &*ns];
19278                }
19279                if let Some(hint) = &a11y.hint {
19280                    let ns = NSString::from_str(hint);
19281                    let _: () = msg_send![&**h, setAccessibilityHint: &*ns];
19282                }
19283                if let Some(value) = &a11y.value {
19284                    let ns = NSString::from_str(value);
19285                    let _: () = msg_send![&**h, setAccessibilityValue: &*ns];
19286                }
19287                // Explicit role → traits (canvas/custom; native controls self-describe, §13).
19288                if let Some(traits) = ui_traits(a11y.role) {
19289                    let _: () = msg_send![&**h, setAccessibilityTraits: traits];
19290                }
19291                // The selected trait, added to or removed from whatever the element reports.
19292                if let Some(on) = a11y.selected {
19293                    let traits: objc2_ui_kit::UIAccessibilityTraits =
19294                        msg_send![&**h, accessibilityTraits];
19295                    let selected = objc2_ui_kit::UIAccessibilityTraitSelected;
19296                    let traits = if on {
19297                        traits | selected
19298                    } else {
19299                        traits & !selected
19300                    };
19301                    let _: () = msg_send![&**h, setAccessibilityTraits: traits];
19302                }
19303                // Decorative / hidden: `accessibilityElementsHidden` drops only the
19304                // DESCENDANTS, so the view itself (a decorative image, a native control) is
19305                // unmarked as an element too. Hidden never flips back, so neither is restored.
19306                if a11y.hidden {
19307                    let _: () = msg_send![&**h, setAccessibilityElementsHidden: true];
19308                    let _: () = msg_send![&**h, setIsAccessibilityElement: false];
19309                }
19310            }
19311        }
19312
19313        /// VoiceOver's announcement notification: an urgent sentence interrupts the current
19314        /// one (the plain-string default); a polite one is wrapped in an attributed string
19315        /// that asks to queue behind it. Without VoiceOver the post goes unobserved.
19316        fn announce(&mut self, text: &str, urgent: bool) {
19317            use objc2::AllocAnyThread as _;
19318            use objc2_ui_kit::{
19319                UIAccessibilityAnnouncementNotification, UIAccessibilityPostNotification,
19320            };
19321            let ns = NSString::from_str(text);
19322            // SAFETY: the notification constant is UIKit's own, and the argument is the
19323            // NSString or NSAttributedString the announcement notification documents.
19324            unsafe {
19325                if urgent {
19326                    UIAccessibilityPostNotification(
19327                        UIAccessibilityAnnouncementNotification,
19328                        Some(&ns),
19329                    );
19330                } else {
19331                    // The queue attribute is deprecated in favor of the iOS 17 priority
19332                    // attribute, but the deployment floor is iOS 15, where only this one exists.
19333                    #[allow(deprecated)]
19334                    let key: &NSString =
19335                        objc2_ui_kit::UIAccessibilitySpeechAttributeQueueAnnouncement;
19336                    let queue = objc2_foundation::NSNumber::new_bool(true);
19337                    let keys: [&NSString; 1] = [key];
19338                    let objs: [&AnyObject; 1] = [queue.as_ref() as &AnyObject];
19339                    let attrs =
19340                        objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
19341                    let queued = objc2_foundation::NSAttributedString::initWithString_attributes(
19342                        objc2_foundation::NSAttributedString::alloc(),
19343                        &ns,
19344                        Some(&attrs),
19345                    );
19346                    UIAccessibilityPostNotification(
19347                        UIAccessibilityAnnouncementNotification,
19348                        Some(&queued),
19349                    );
19350                }
19351            }
19352        }
19353
19354        /// What the view shows now, mid-animation included (docs/tween.md "Mid-flight
19355        /// read-back"). A channel with a run in flight is read from Core Animation's
19356        /// presentation layer; one at rest from the model layer, which is what the next frame
19357        /// shows: the presentation layer catches up with a plain set (and with a run removed
19358        /// by one) only at the next commit, so reading it right after a set answers the value
19359        /// before it.
19360        fn read_displayed(&self, h: &Handle) -> day_spec::Displayed {
19361            let layer = h.layer();
19362            // SAFETY: the presentation layer is a read-only copy of what is on screen.
19363            let presentation = unsafe { layer.presentationLayer() };
19364            let source = |channel: Channel| match &presentation {
19365                Some(p) if channel_running(&layer, channel) => p.clone(),
19366                _ => layer.clone(),
19367            };
19368            // The frame before any transform: the shown position less the anchor's share of
19369            // the shown bounds, in the parent, converted to the window as `read_native` does.
19370            let frame = h.window().and(h.superview()).map(|parent| {
19371                let shown = source(Channel::Frame);
19372                let bounds = shown.bounds();
19373                let position = shown.position();
19374                let anchor = shown.anchorPoint();
19375                let local = CGRect::new(
19376                    CGPoint::new(
19377                        position.x - anchor.x * bounds.size.width,
19378                        position.y - anchor.y * bounds.size.height,
19379                    ),
19380                    bounds.size,
19381                );
19382                let r = parent.convertRect_toView(local, None);
19383                Rect::new(r.origin.x, r.origin.y, r.size.width, r.size.height)
19384            });
19385            let t = source(Channel::Transform).transform();
19386            day_spec::Displayed {
19387                opacity: Some(f64::from(source(Channel::Opacity).opacity())),
19388                frame,
19389                translation: Some(day_spec::Point::new(t.m41, t.m42)),
19390                background: source(Channel::Background)
19391                    .backgroundColor()
19392                    .and_then(|c| cgcolor_components(&c)),
19393            }
19394        }
19395
19396        fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
19397            unsafe {
19398                let traits: objc2_ui_kit::UIAccessibilityTraits =
19399                    msg_send![&**h, accessibilityTraits];
19400                let label: Option<Retained<NSString>> = msg_send![&**h, accessibilityLabel];
19401                let value: Option<Retained<NSString>> = msg_send![&**h, accessibilityValue];
19402                let ident: Option<Retained<NSString>> = msg_send![&**h, accessibilityIdentifier];
19403                // A picker answers its displayed selection and its enabled state itself: the
19404                // inline style is a stack of row buttons, not one control.
19405                let picker = crate::picker::read_native(h);
19406                day_spec::NativeSnapshot {
19407                    found: true,
19408                    role: day_role_from_traits(traits),
19409                    label: label.map(|s| s.to_string()),
19410                    value: value.map(|s| s.to_string()),
19411                    identifier: ident.map(|s| s.to_string()).filter(|s| !s.is_empty()),
19412                    text: match &picker {
19413                        Some((text, _)) => text.clone(),
19414                        None => native_text(h),
19415                    },
19416                    number: native_number(h),
19417                    // A toggle's state, or a button's selected state (`ButtonProps::selected`).
19418                    checked: if let Some(sw) = (**h).downcast_ref::<UISwitch>() {
19419                        Some(sw.isOn())
19420                    } else {
19421                        (**h).downcast_ref::<UIButton>().map(|b| b.isSelected())
19422                    },
19423                    // Only a UIControl takes input; a UILabel's `isEnabled` only dims it, and
19424                    // a text view (a text area or a selectable label) has no enabled state.
19425                    enabled: match &picker {
19426                        Some((_, on)) => *on,
19427                        None => (**h)
19428                            .downcast_ref::<UIControl>()
19429                            .map(objc2_ui_kit::UIControl::isEnabled),
19430                    },
19431                    visible: Some(native_visible(h)),
19432                    frame: native_frame(h),
19433                }
19434            }
19435        }
19436
19437        fn request_frame(
19438            &mut self,
19439            host: &Handle,
19440            cb: day_spec::FrameCallback,
19441        ) -> day_spec::CancelFrame {
19442            let key = ptr_of(host);
19443            let token = day_core::frame::native::register(cb);
19444            FRAMES.with(|s| {
19445                let mut sources = s.borrow_mut();
19446                let source = sources.entry(key).or_insert_with(|| {
19447                    let this = DayFrameTarget::alloc(mtm()).set_ivars(FrameState {
19448                        key,
19449                        token: Cell::new(0),
19450                    });
19451                    let target: Retained<DayFrameTarget> = unsafe { msg_send![super(this), init] };
19452                    // Bind to the window's screen, including external displays on iPad.
19453                    let screen = unsafe { host.window().map(|w| w.screen()) };
19454                    let link = if let Some(screen) = screen {
19455                        unsafe { screen.displayLinkWithTarget_selector(&target, sel!(step:)) }
19456                    } else {
19457                        None
19458                    }
19459                    .unwrap_or_else(|| unsafe {
19460                        CADisplayLink::displayLinkWithTarget_selector(&target, sel!(step:))
19461                    });
19462                    unsafe {
19463                        link.addToRunLoop_forMode(
19464                            &objc2_foundation::NSRunLoop::mainRunLoop(),
19465                            objc2_foundation::NSRunLoopCommonModes,
19466                        );
19467                    }
19468                    FrameSource { link, target }
19469                });
19470                source.target.ivars().token.set(token);
19471                unsafe { source.link.setPaused(false) };
19472            });
19473            Box::new(move || {
19474                day_core::frame::native::cancel(token);
19475                FRAMES.with(|s| {
19476                    let mut s = s.borrow_mut();
19477                    if s.get(&key)
19478                        .is_some_and(|s| s.target.ivars().token.get() == token)
19479                    {
19480                        s.remove(&key);
19481                    }
19482                });
19483            })
19484        }
19485
19486        fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
19487            OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
19488            unsafe { h.setNeedsDisplay() };
19489        }
19490
19491        /// Decode bytes with `UIImage(data:)` (docs/images.md), which reads every container
19492        /// ImageIO knows — PNG, JPEG, HEIF, GIF, TIFF, BMP and WebP on iOS 14+.
19493        fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
19494            let data = objc2_foundation::NSData::with_bytes(bytes);
19495            let event = match unsafe { objc2_ui_kit::UIImage::imageWithData(&data) } {
19496                Some(image) => {
19497                    // `size` is in POINTS; multiplying by the image's own scale is what turns it
19498                    // into the pixel dimensions a caller asked for. Bytes decode at scale 1, so
19499                    // the two agree here — but the multiplication is what keeps that true.
19500                    let (size, scale) = unsafe { (image.size(), image.scale()) };
19501                    let format = day_spec::ImageFormat::sniff(bytes);
19502                    let info = day_spec::BitmapInfo {
19503                        pixels: Size::new(size.width * scale, size.height * scale),
19504                        // Decoded bytes carry no density — a PNG is simply its pixels.
19505                        scale: 1.0,
19506                        format,
19507                        // Derived from the container, not measured: asking UIKit would mean
19508                        // reaching through `CGImage` for an alpha info flag. Unknown counts as
19509                        // "may have alpha", the harmless direction.
19510                        has_alpha: !matches!(
19511                            format,
19512                            Some(day_spec::ImageFormat::Jpeg | day_spec::ImageFormat::Bmp)
19513                        ),
19514                    };
19515                    BITMAPS.with(|m| m.borrow_mut().insert(id.0, UikitBitmap { image, info }));
19516                    Event::ImageDecoded {
19517                        req,
19518                        result: Ok(info),
19519                    }
19520                }
19521                None => Event::ImageDecoded {
19522                    req,
19523                    result: Err(day_spec::ImageError::Decode),
19524                },
19525            };
19526            emit(day_spec::WINDOW_NODE, event);
19527        }
19528
19529        /// Offscreen through `UIGraphicsImageRenderer` with the canvas's own painter
19530        /// (docs/canvas.md "Exporting"), kept in the table `decode_image` fills.
19531        ///
19532        /// The paint runs on a `day_spec::offscreen` thread, where the renderer is documented
19533        /// to work, so a long replay (a map tile of a thousand paths took 130 ms on an iPad
19534        /// Air 2) no longer holds a frame. The images and fonts the ops need are resolved here
19535        /// first, the `UIImage` comes back on the main queue, and the table insert and the
19536        /// answer happen there, in that order.
19537        fn render_bitmap(
19538            &mut self,
19539            req: u64,
19540            id: day_spec::BitmapId,
19541            ops: &[DrawOp],
19542            size: Size,
19543            scale: f64,
19544        ) {
19545            let resources = Sendable(OffscreenResources::collect(ops));
19546            let renderer = Sendable(offscreen_renderer(size, scale));
19547            let ops = ops.to_vec();
19548            day_spec::offscreen::spawn(move || {
19549                // Bound whole so the closure captures the `Send` wrappers, not their fields.
19550                let (resources, renderer) = (resources, renderer);
19551                let painted = day_spec::ffi_guard::contain(
19552                    Err(day_spec::ExportError::Failed(
19553                        "the offscreen painter panicked".into(),
19554                    )),
19555                    || {
19556                        let started = std::time::Instant::now();
19557                        let count = ops.len();
19558                        let painted = resources
19559                            .0
19560                            .with_installed(|| render_bitmap_image(&renderer.0, ops, size, scale));
19561                        // The painter's own cost, apart from the queuing a caller's clock sees.
19562                        log::debug!(
19563                            "day-toolkit-uikit: bitmap {}x{} painted in {:.1} ms ({} ops)",
19564                            size.width * scale,
19565                            size.height * scale,
19566                            started.elapsed().as_secs_f64() * 1000.0,
19567                            count
19568                        );
19569                        painted
19570                    },
19571                );
19572                let painted = Sendable(painted);
19573                <Uikit as Platform>::post(Box::new(move || {
19574                    let painted = painted;
19575                    let result = painted.0.map(|(image, info)| {
19576                        BITMAPS.with(|m| m.borrow_mut().insert(id.0, UikitBitmap { image, info }));
19577                        info
19578                    });
19579                    emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
19580                }));
19581            });
19582        }
19583
19584        /// One vector PDF through `UIGraphicsPDFRenderer`, a page per drawing.
19585        fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
19586            let result = render_pdf_data(pages, info);
19587            emit(day_spec::WINDOW_NODE, Event::PdfRendered { req, result });
19588        }
19589
19590        fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
19591            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
19592        }
19593
19594        fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
19595            let result = encode_bitmap(id, spec);
19596            emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
19597        }
19598
19599        /// What UIKit WRITES: `UIImagePNGRepresentation` and `UIImageJPEGRepresentation`, and
19600        /// nothing else. It READS far more, and the asymmetry is the platform's own — which is
19601        /// why this duty exists rather than letting `Cap::ImageEncode` imply symmetry.
19602        fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
19603            use day_spec::ImageFormat::{Jpeg, Png};
19604            vec![Png, Jpeg]
19605        }
19606
19607        fn release_image(&mut self, id: day_spec::BitmapId) {
19608            BITMAPS.with(|m| {
19609                m.borrow_mut().remove(&id.0);
19610            });
19611        }
19612
19613        // In-process capture uses drawViewHierarchy with afterScreenUpdates=true.
19614        // External simctl captures retain their own synchronization; no acknowledgment
19615        // of external freshness is fabricated from a main-thread/vsync callback.
19616        fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
19617            snapshot_uikit(false)
19618        }
19619
19620        /// `UIFont.familyNames` + `fontNamesForFamilyName:`, each member described through its
19621        /// `UIFontDescriptor`: the face name, the italic symbolic trait, and the weight trait
19622        /// (docs/fonts.md). `.`-prefixed families are the system's private UI faces.
19623        fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
19624            use objc2_ui_kit::*;
19625            let mut out = Vec::new();
19626            for family in &unsafe { UIFont::familyNames() } {
19627                let name = family.to_string();
19628                if name.starts_with('.') {
19629                    continue;
19630                }
19631                let mut faces = Vec::new();
19632                for font_name in &unsafe { UIFont::fontNamesForFamilyName(&family) } {
19633                    let Some(font) = (unsafe { UIFont::fontWithName_size(&font_name, 12.0) })
19634                    else {
19635                        continue;
19636                    };
19637                    // SAFETY: a font UIKit handed back; the descriptor is its own.
19638                    let desc = unsafe { font.fontDescriptor() };
19639                    let traits = unsafe { desc.symbolicTraits() };
19640                    let italic = traits.contains(UIFontDescriptorSymbolicTraits::TraitItalic);
19641                    // SAFETY: the keys are UIKit's own descriptor-attribute constants.
19642                    let face: Option<Retained<AnyObject>> =
19643                        unsafe { msg_send![&desc, objectForKey: UIFontDescriptorFaceAttribute] };
19644                    let trait_dict: Option<Retained<AnyObject>> =
19645                        unsafe { msg_send![&desc, objectForKey: UIFontDescriptorTraitsAttribute] };
19646                    let weight_trait = trait_dict.and_then(|d| {
19647                        let d = d.downcast::<objc2_foundation::NSDictionary>().ok()?;
19648                        let key: &NSString = unsafe { UIFontWeightTrait };
19649                        let n = d.objectForKey(key as &AnyObject)?;
19650                        n.downcast::<objc2_foundation::NSNumber>()
19651                            .ok()
19652                            .map(|n| n.doubleValue())
19653                    });
19654                    let weight = match weight_trait {
19655                        Some(t) => weight_from_trait(t),
19656                        None if traits.contains(UIFontDescriptorSymbolicTraits::TraitBold) => {
19657                            day_spec::FontWeight::Bold
19658                        }
19659                        None => day_spec::FontWeight::Regular,
19660                    };
19661                    let face = face
19662                        .and_then(|f| f.downcast::<NSString>().ok())
19663                        .map(|s| s.to_string())
19664                        .filter(|s| !s.is_empty())
19665                        .unwrap_or_else(|| day_spec::FontFace::synthesized_name(weight, italic));
19666                    faces.push(day_spec::FontFace {
19667                        name: face,
19668                        weight,
19669                        italic,
19670                    });
19671                }
19672                out.push(day_spec::FontFamilyInfo {
19673                    family: name,
19674                    faces,
19675                });
19676            }
19677            out
19678        }
19679
19680        /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
19681        /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
19682        fn measure_text(
19683            &mut self,
19684            text: &str,
19685            size: f64,
19686            font: &day_spec::CanvasFont,
19687        ) -> Option<day_spec::TextMetrics> {
19688            let uifont = canvas_uifont(size, font);
19689            let attrs = canvas_text_attrs(&uifont, day_spec::Color::BLACK);
19690            let ns = NSString::from_str(text);
19691            let sz: CGSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
19692            // SAFETY: a font UIKit handed back; these are plain metric reads.
19693            let (ascent, cap) = unsafe { (uifont.ascender(), uifont.capHeight()) };
19694            // The INK box (see the AppKit twin): `usesDeviceMetrics` turns the layout box into
19695            // the glyphs' own bounds, reported baseline-relative with y up.
19696            let unbounded = CGSize::new(f64::MAX, f64::MAX);
19697            let ink: CGRect = unsafe {
19698                msg_send![
19699                    &ns,
19700                    boundingRectWithSize: unbounded,
19701                    options: objc2_ui_kit::NSStringDrawingOptions::UsesDeviceMetrics,
19702                    attributes: &*attrs,
19703                    context: std::ptr::null::<objc2::runtime::AnyObject>(),
19704                ]
19705            };
19706            Some(day_spec::TextMetrics::from_baseline(
19707                sz.width,
19708                ascent,
19709                sz.height - ascent,
19710                cap,
19711                day_spec::Rect::new(
19712                    ink.origin.x,
19713                    -(ink.origin.y + ink.size.height),
19714                    ink.size.width,
19715                    ink.size.height,
19716                ),
19717            ))
19718        }
19719
19720        /// The window rather than Day's content view. On iOS the "chrome" is the navigation bar,
19721        /// which lives IN the window's own hierarchy — so this is a wider capture of the same
19722        /// tree, not a different mechanism. The status bar is not in it: that belongs to the
19723        /// system, not to this process, and no in-app API can draw it (docs/window-image.md).
19724        fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
19725            snapshot_uikit(true)
19726        }
19727
19728        /// A secondary "window" on iOS is a fullscreen cover (`open_window` below answers
19729        /// Unsupported for the Preferences kind), so `host` is the cover's content view —
19730        /// capture IT, not the key scene's root, which the cover's presentation has
19731        /// detached from the window (drawing a detached root raises, see `snapshot_view`).
19732        fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
19733            snapshot_view(host)
19734        }
19735
19736        fn native_document_tabs(&self) -> bool {
19737            false
19738        }
19739
19740        fn open_window(
19741            &mut self,
19742            id: NodeId,
19743            options: &day_spec::WindowOptions,
19744            kind: day_spec::WindowKind,
19745        ) -> day_spec::WindowOpenReply<Handle> {
19746            use objc2::AnyThread as _;
19747            let m = mtm();
19748            let app = UIApplication::sharedApplication(m);
19749            // A scene the platform already handed us is waiting for exactly one window's
19750            // content (the scene delegate calls day-core from inside willConnect). Take it
19751            // rather than asking for another scene, and name the node it is now the window of.
19752            if ADOPTING.with(std::cell::Cell::get) {
19753                ADOPTING.with(|a| a.set(false));
19754                ADOPTING_SCENE.with(|n| n.set(Some(id)));
19755                return day_spec::WindowOpenReply::Pending;
19756            }
19757            // iPhone (single visible scene) — and the Preferences kind everywhere on
19758            // mobile, where settings are modal, not a detached window (docs/windows.md).
19759            if !unsafe { app.supportsMultipleScenes() } || kind.is_panel() {
19760                return day_spec::WindowOpenReply::Unsupported;
19761            }
19762            // Ask UIKit for a new scene; its willConnect completes the open through
19763            // `finish_window_open` (the Pending path).
19764            let activity = unsafe {
19765                objc2_foundation::NSUserActivity::initWithActivityType(
19766                    objc2_foundation::NSUserActivity::alloc(),
19767                    &NSString::from_str(DAY_WINDOW_ACTIVITY),
19768                )
19769            };
19770            let key = NSString::from_str("day.node");
19771            let num = objc2_foundation::NSNumber::new_u64(id.0);
19772            let obj: Retained<AnyObject> = num.into_super().into_super().into();
19773            let dict: Retained<objc2_foundation::NSDictionary<NSString, AnyObject>> =
19774                objc2_foundation::NSDictionary::from_retained_objects(&[&*key], &[obj]);
19775            // The API takes the untyped dictionary; the typed one IS that object.
19776            let untyped =
19777                unsafe { &*Retained::as_ptr(&dict).cast::<objc2_foundation::NSDictionary>() };
19778            unsafe { activity.addUserInfoEntriesFromDictionary(untyped) };
19779            // The non-deprecated activateSceneSessionForRequest: needs iOS 17; this form
19780            // covers the whole deployment range.
19781            #[allow(deprecated)]
19782            unsafe {
19783                app.requestSceneSessionActivation_userActivity_options_errorHandler(
19784                    None,
19785                    Some(&activity),
19786                    None,
19787                    None,
19788                );
19789            }
19790            PENDING_WINDOWS.with(|p| p.borrow_mut().push((id, options.title.clone())));
19791            day_spec::WindowOpenReply::Pending
19792        }
19793
19794        fn close_window(&mut self, host: &Handle) {
19795            let m = mtm();
19796            let session = SCENES.with(|s| {
19797                s.borrow()
19798                    .iter()
19799                    .find(|e| std::ptr::eq(&raw const *e.root_view, &raw const **host))
19800                    .and_then(|e| e.window.windowScene())
19801                    .map(|ws| unsafe { ws.session() })
19802            });
19803            if let Some(session) = session {
19804                request_scene_destruction(m, &session);
19805            }
19806        }
19807
19808        fn focus_window(&mut self, host: &Handle) {
19809            let m = mtm();
19810            let app = UIApplication::sharedApplication(m);
19811            let session = SCENES.with(|s| {
19812                s.borrow()
19813                    .iter()
19814                    .find(|e| std::ptr::eq(&raw const *e.root_view, &raw const **host))
19815                    .and_then(|e| e.window.windowScene())
19816                    .map(|ws| unsafe { ws.session() })
19817            });
19818            if let Some(session) = session {
19819                // See open_window: the deprecated form covers pre-iOS-17 deployment.
19820                #[allow(deprecated)]
19821                unsafe {
19822                    app.requestSceneSessionActivation_userActivity_options_errorHandler(
19823                        Some(&session),
19824                        None,
19825                        None,
19826                        None,
19827                    );
19828                }
19829            }
19830        }
19831
19832        fn set_window_title(&mut self, host: &Handle, title: &str) {
19833            // Shown in the iPad app switcher / multitasking UI.
19834            SCENES.with(|s| {
19835                if let Some(ws) = s
19836                    .borrow()
19837                    .iter()
19838                    .find(|e| std::ptr::eq(&raw const *e.root_view, &raw const **host))
19839                    .and_then(|e| e.window.windowScene())
19840                {
19841                    unsafe { ws.setTitle(Some(&NSString::from_str(title))) };
19842                }
19843            });
19844        }
19845
19846        /// Window properties (docs/windows.md). `host` is a scene's Day root: a secondary
19847        /// window's, or the primary's. Fullscreen and content protection are emulated (see
19848        /// `refresh_window_chrome` and `refresh_capture_shields`); minimize and zoom do not
19849        /// exist on iOS, so those requests report the state the window kept.
19850        fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
19851            use day_spec::{WindowChange as C, WindowState as S};
19852            match change {
19853                C::State(S::Minimized | S::Maximized) => {
19854                    if let Some((node, ev)) =
19855                        with_scene_of_host(host, |e| scene_state_report(e, true)).flatten()
19856                    {
19857                        emit(node, ev);
19858                    }
19859                }
19860                C::State(state) => {
19861                    let on = *state == S::Fullscreen;
19862                    // The registry stays borrowed only to flip the flag; UIKit asks the VCs
19863                    // back through `with_scene_of` while the chrome updates.
19864                    let window = with_scene_of_host(host, |e| {
19865                        (e.fullscreen.replace(on) != on).then(|| e.window.clone())
19866                    })
19867                    .flatten();
19868                    if let Some(window) = window {
19869                        refresh_window_chrome(&window);
19870                    }
19871                    if let Some((node, ev)) =
19872                        with_scene_of_host(host, |e| scene_state_report(e, false)).flatten()
19873                    {
19874                        emit(node, ev);
19875                    }
19876                }
19877                C::ContentProtected(on) => {
19878                    with_scene_of_host(host, |e| e.protected.set(*on));
19879                    refresh_capture_shields();
19880                }
19881                // The scene window's own `overrideUserInterfaceStyle`; `None` hands it back to
19882                // the app-wide style.
19883                C::Appearance(dark) => {
19884                    with_scene_of_host(host, |e| e.appearance.set(*dark));
19885                    refresh_scene_styles();
19886                }
19887                // Size, position, stacking and window controls belong to the system on iOS
19888                // (Cap::WindowGeometry, WindowPosition, WindowLevel, WindowStates and
19889                // RequestAttention are Unsupported).
19890                _ => {}
19891            }
19892        }
19893
19894        /// The one screen the app runs on (`Cap::Monitors` Emulated): the primary scene's
19895        /// screen, in points, with the work area inside the window's safe area (the status bar,
19896        /// the home indicator and any cutout taken off).
19897        fn monitors(&self) -> Vec<day_spec::Monitor> {
19898            let primary = SCENES.with(|s| {
19899                s.borrow()
19900                    .iter()
19901                    .find(|e| e.node.is_none())
19902                    .map(|e| e.window.clone())
19903            });
19904            let Some(window) = primary else {
19905                return Vec::new();
19906            };
19907            let Some(scene) = window.windowScene() else {
19908                return Vec::new();
19909            };
19910            let screen = scene.screen();
19911            let b = screen.bounds();
19912            let insets = unsafe { window.safeAreaInsets() };
19913            let frame = day_spec::Rect::new(0.0, 0.0, b.size.width, b.size.height);
19914            let work_area = day_spec::Rect::new(
19915                insets.left,
19916                insets.top,
19917                (b.size.width - insets.left - insets.right).max(0.0),
19918                (b.size.height - insets.top - insets.bottom).max(0.0),
19919            );
19920            let name = objc2_ui_kit::UIDevice::currentDevice(mtm())
19921                .model()
19922                .to_string();
19923            vec![day_spec::Monitor {
19924                id: "0".into(),
19925                name,
19926                frame,
19927                work_area,
19928                scale: screen.scale(),
19929                primary: true,
19930            }]
19931        }
19932
19933        /// Home Screen quick actions the app sets while it runs, shown after the Info.plist
19934        /// ones. Each type string is the same saved deep link the static ones carry
19935        /// (`<scheme>://<route>`, docs/deep-links.md), so a press arrives through
19936        /// `performActionForShortcutItem` or the scene's connection options like theirs do.
19937        fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
19938            use objc2::AllocAnyThread as _;
19939            let scheme = bundle_url_scheme();
19940            let items: Vec<Retained<objc2_ui_kit::UIApplicationShortcutItem>> = shortcuts
19941                .iter()
19942                .map(|sc| {
19943                    let link = match &scheme {
19944                        Some(scheme) => format!("{scheme}://{}", sc.route),
19945                        None => sc.route.clone(),
19946                    };
19947                    let title = if sc.label.is_empty() {
19948                        &sc.route
19949                    } else {
19950                        &sc.label
19951                    };
19952                    objc2_ui_kit::UIApplicationShortcutItem::initWithType_localizedTitle(
19953                        objc2_ui_kit::UIApplicationShortcutItem::alloc(),
19954                        &NSString::from_str(&link),
19955                        &NSString::from_str(title),
19956                    )
19957                })
19958                .collect();
19959            let array = objc2_foundation::NSArray::from_retained_slice(&items);
19960            let app = UIApplication::sharedApplication(mtm());
19961            app.setShortcutItems(Some(&array));
19962            if log::log_enabled!(log::Level::Debug) {
19963                let set: Vec<String> = app
19964                    .shortcutItems()
19965                    .map_or_default(|items| items.iter().map(|i| i.r#type().to_string()).collect());
19966                log::debug!("uikit: launcher shortcuts now {set:?}");
19967            }
19968        }
19969
19970        fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
19971            use day_spec::present::{ButtonRole, PresentResult, PresentSpec};
19972            use objc2_ui_kit::{
19973                UIAlertAction, UIAlertActionStyle, UIAlertController, UIAlertControllerStyle,
19974            };
19975            let m = mtm();
19976            let (title, message) = (
19977                NSString::from_str(spec.title()),
19978                spec.message().map(NSString::from_str),
19979            );
19980            match spec {
19981                PresentSpec::Dialog { buttons, sheet, .. } => {
19982                    let style = if *sheet {
19983                        UIAlertControllerStyle::ActionSheet
19984                    } else {
19985                        UIAlertControllerStyle::Alert
19986                    };
19987                    let ac = unsafe {
19988                        UIAlertController::alertControllerWithTitle_message_preferredStyle(
19989                            Some(&title),
19990                            message.as_deref(),
19991                            style,
19992                            m,
19993                        )
19994                    };
19995                    for (i, b) in buttons.iter().enumerate() {
19996                        let astyle = match b.role {
19997                            ButtonRole::Cancel => UIAlertActionStyle::Cancel,
19998                            ButtonRole::Destructive => UIAlertActionStyle::Destructive,
19999                            ButtonRole::Default => UIAlertActionStyle::Default,
20000                        };
20001                        let idx = i as i64;
20002                        let handler = block2::RcBlock::new(move |_: NonNull<UIAlertAction>| {
20003                            emit(
20004                                WINDOW_NODE,
20005                                Event::PresentResult {
20006                                    req,
20007                                    result: PresentResult::Button(idx),
20008                                },
20009                            );
20010                            present_forget(req);
20011                        });
20012                        let action = unsafe {
20013                            UIAlertAction::actionWithTitle_style_handler(
20014                                Some(&NSString::from_str(&b.label)),
20015                                astyle,
20016                                Some(&handler),
20017                                m,
20018                            )
20019                        };
20020                        unsafe { ac.addAction(&action) };
20021                    }
20022                    // On iPad an action sheet presents as a POPOVER, and a popover without an
20023                    // anchor is an NSGenericException at transition time — the app dies. The
20024                    // dialog surface has no anchor concept (a sheet is logically modal,
20025                    // docs/dialogs.md), so anchor it to the window's center, arrowless: the
20026                    // pad convention for source-less sheets. On iPhone the popover controller
20027                    // is unused and this is inert.
20028                    if *sheet
20029                        && let Some(pop) = unsafe { ac.popoverPresentationController() }
20030                        && let Some(w) = WINDOW.with(|win| win.borrow().clone())
20031                    {
20032                        let b = w.bounds();
20033                        unsafe {
20034                            pop.setSourceView(Some(w.as_ref()));
20035                            pop.setSourceRect(CGRect::new(
20036                                CGPoint::new(b.size.width / 2.0, b.size.height / 2.0),
20037                                CGSize::new(0.0, 0.0),
20038                            ));
20039                            pop.setPermittedArrowDirections(
20040                                objc2_ui_kit::UIPopoverArrowDirection::empty(),
20041                            );
20042                        }
20043                    }
20044                    PRESENT_VCS.with(|p| p.borrow_mut().insert(req, ac.clone()));
20045                    modal_enqueue(ModalOp::Present(req, ac.into_super()));
20046                }
20047                PresentSpec::Prompt {
20048                    placeholder,
20049                    initial,
20050                    ok,
20051                    cancel,
20052                    ..
20053                } => {
20054                    let ac = unsafe {
20055                        UIAlertController::alertControllerWithTitle_message_preferredStyle(
20056                            Some(&title),
20057                            message.as_deref(),
20058                            UIAlertControllerStyle::Alert,
20059                            m,
20060                        )
20061                    };
20062                    let (ph, init) = (NSString::from_str(placeholder), NSString::from_str(initial));
20063                    let cfg =
20064                        block2::RcBlock::new(move |tf: NonNull<objc2_ui_kit::UITextField>| {
20065                            let tf = unsafe { tf.as_ref() };
20066                            unsafe {
20067                                tf.setPlaceholder(Some(&ph));
20068                                tf.setText(Some(&init));
20069                            }
20070                        });
20071                    unsafe { ac.addTextFieldWithConfigurationHandler(Some(&cfg)) };
20072                    let ac_ok = ac.clone();
20073                    let ok_handler = block2::RcBlock::new(move |_: NonNull<UIAlertAction>| {
20074                        let text = unsafe { ac_ok.textFields() }
20075                            .and_then(|fs| fs.firstObject())
20076                            .and_then(|f| unsafe { f.text() })
20077                            .map_or_default(|s| s.to_string());
20078                        emit(
20079                            WINDOW_NODE,
20080                            Event::PresentResult {
20081                                req,
20082                                result: PresentResult::Text(text),
20083                            },
20084                        );
20085                        present_forget(req);
20086                    });
20087                    let cancel_handler = block2::RcBlock::new(move |_: NonNull<UIAlertAction>| {
20088                        emit(
20089                            WINDOW_NODE,
20090                            Event::PresentResult {
20091                                req,
20092                                result: PresentResult::Dismissed,
20093                            },
20094                        );
20095                        present_forget(req);
20096                    });
20097                    unsafe {
20098                        ac.addAction(&UIAlertAction::actionWithTitle_style_handler(
20099                            Some(&NSString::from_str(ok)),
20100                            UIAlertActionStyle::Default,
20101                            Some(&ok_handler),
20102                            m,
20103                        ));
20104                        ac.addAction(&UIAlertAction::actionWithTitle_style_handler(
20105                            Some(&NSString::from_str(cancel)),
20106                            UIAlertActionStyle::Cancel,
20107                            Some(&cancel_handler),
20108                            m,
20109                        ));
20110                    }
20111                    PRESENT_VCS.with(|p| p.borrow_mut().insert(req, ac.clone()));
20112                    modal_enqueue(ModalOp::Present(req, ac.into_super()));
20113                }
20114                // Native file pickers: UIDocumentPickerViewController with a delegate. Open uses
20115                // `.import` mode (the system hands back an app-local copy, readable via std::fs);
20116                // save exports the Day-staged temp file to the chosen destination.
20117                PresentSpec::OpenFile { multiple, .. } => {
20118                    if dayscript_driven() {
20119                        return; // pending request resolved by the scripted `respond`
20120                    }
20121                    let types =
20122                        objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
20123                            "public.item",
20124                        )]);
20125                    #[allow(deprecated)]
20126                    let picker = unsafe {
20127                        UIDocumentPickerViewController::initWithDocumentTypes_inMode(
20128                            UIDocumentPickerViewController::alloc(m),
20129                            &types,
20130                            UIDocumentPickerMode::Import,
20131                        )
20132                    };
20133                    // Import mode copies every selection into the sandbox; the delegate's
20134                    // `didPickDocumentsAtURLs` reports each copy (docs/files.md).
20135                    picker.setAllowsMultipleSelection(*multiple);
20136                    present_doc_picker(req, m, picker);
20137                }
20138                // No folder chooser on iOS (`Cap::FolderDialog` is Unsupported): a folder's
20139                // security-scoped access is its own feature, so the request resolves at once.
20140                PresentSpec::OpenFolder { .. } => {
20141                    if dayscript_driven() {
20142                        return; // a scripted `respond` may still answer it
20143                    }
20144                    emit(
20145                        WINDOW_NODE,
20146                        Event::PresentResult {
20147                            req,
20148                            result: PresentResult::Dismissed,
20149                        },
20150                    );
20151                }
20152                PresentSpec::SaveFile { src_path, .. } => {
20153                    if dayscript_driven() {
20154                        return; // pending request resolved by the scripted `respond`
20155                    }
20156                    let url = unsafe {
20157                        objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(src_path))
20158                    };
20159                    #[allow(deprecated)]
20160                    let picker = unsafe {
20161                        UIDocumentPickerViewController::initWithURL_inMode(
20162                            UIDocumentPickerViewController::alloc(m),
20163                            &url,
20164                            UIDocumentPickerMode::ExportToService,
20165                        )
20166                    };
20167                    present_doc_picker(req, m, picker);
20168                }
20169            }
20170        }
20171
20172        fn dismiss(&mut self, req: u64) {
20173            modal_enqueue(ModalOp::Dismiss(req, 0));
20174        }
20175
20176        fn share_support(&self) -> day_spec::Support {
20177            day_spec::Support::Native
20178        }
20179        fn share(
20180            &mut self,
20181            spec: &day_spec::share::ShareSpec,
20182            anchor: Option<&Self::Handle>,
20183        ) -> bool {
20184            use objc2_ui_kit::UIActivityViewController;
20185            let Some(url) =
20186                (unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(&spec.url)) })
20187            else {
20188                return false;
20189            };
20190            let Some(mut parent) =
20191                WINDOW.with(|w| w.borrow().as_ref().and_then(|w| w.rootViewController()))
20192            else {
20193                return false;
20194            };
20195            unsafe {
20196                while let Some(next) = parent.presentedViewController() {
20197                    parent = next;
20198                }
20199                let items = objc2_foundation::NSArray::<AnyObject>::from_slice(&[url.as_ref()]);
20200                let activities: Vec<Retained<objc2_ui_kit::UIActivity>> = spec
20201                    .actions
20202                    .iter()
20203                    .map(|a| Retained::into_super(DayShareActivity::new(a)))
20204                    .collect();
20205                let activities = objc2_foundation::NSArray::from_retained_slice(&activities);
20206                let sheet = UIActivityViewController::initWithActivityItems_applicationActivities(
20207                    UIActivityViewController::alloc(mtm()),
20208                    &items,
20209                    (!spec.actions.is_empty()).then_some(&*activities),
20210                );
20211                if !spec.actions.is_empty() {
20212                    // UIKit calls this after the sheet is dismissed, which is when docs/sharing.md
20213                    // promises the app's action runs: never while the chooser is still up.
20214                    let finished = block2::RcBlock::new(
20215                        |activity: *mut NSString,
20216                         completed: objc2::runtime::Bool,
20217                         _items: *mut objc2_foundation::NSArray,
20218                         _error: *mut objc2_foundation::NSError| {
20219                            // SAFETY: UIKit passes the chosen activity's type, a valid NSString,
20220                            // or null when the sheet was cancelled.
20221                            let Some(activity) = (unsafe { activity.as_ref() }) else {
20222                                return;
20223                            };
20224                            if !completed.as_bool() {
20225                                return;
20226                            }
20227                            if let Some(id) = share_action_id(&activity.to_string()) {
20228                                day_spec::ffi_guard::contain((), || {
20229                                    emit(WINDOW_NODE, Event::MenuAction(id));
20230                                });
20231                            }
20232                        },
20233                    );
20234                    sheet.setCompletionWithItemsHandler(block2::RcBlock::as_ptr(&finished));
20235                }
20236                if let Some(popover) = sheet.popoverPresentationController() {
20237                    // An iPad presents the sheet as a popover: point it at the control that
20238                    // asked, or, without one, at the window's top trailing corner.
20239                    if let Some(view) = anchor {
20240                        popover.setSourceView(Some(view));
20241                        popover.setSourceRect(view.bounds());
20242                    } else {
20243                        let Some(view) = parent.view() else {
20244                            return false;
20245                        };
20246                        popover.setSourceView(Some(&view));
20247                        let bounds = view.bounds();
20248                        popover.setSourceRect(CGRect::new(
20249                            CGPoint::new(bounds.size.width - 30.0, 30.0),
20250                            CGSize::new(1.0, 1.0),
20251                        ));
20252                    }
20253                }
20254                parent.presentViewController_animated_completion(&sheet, true, None);
20255            }
20256            true
20257        }
20258
20259        fn open_url(&mut self, url: &str) {
20260            let Some(nsurl) =
20261                (unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) })
20262            else {
20263                return;
20264            };
20265            // `openURL:options:completionHandler:`, NOT the one-argument `openURL:`. The old form
20266            // is deprecated, and on a current iOS it returns NO and opens nothing — a link that
20267            // silently does nothing, with no exception and no log line to explain it. The options
20268            // dictionary is empty (the defaults are what a plain link wants) and the completion
20269            // block is nil, which this fire-and-forget call is allowed to pass.
20270            unsafe {
20271                UIApplication::sharedApplication(mtm()).openURL_options_completionHandler(
20272                    &nsurl,
20273                    &objc2_foundation::NSDictionary::new(),
20274                    None,
20275                );
20276            }
20277        }
20278
20279        fn defer_system_gestures(&mut self, edges: Edges) {
20280            DEFER_EDGES.with(|e| e.set(edges.0));
20281            // Re-query the override on the root VC and every cover VC (UIKit consults the
20282            // topmost presented VC, which is the cover while one is up).
20283            let root_vc = WINDOW
20284                .with(|w| w.borrow().clone())
20285                .and_then(|w| w.rootViewController());
20286            if let Some(vc) = root_vc {
20287                unsafe { vc.setNeedsUpdateOfScreenEdgesDeferringSystemGestures() };
20288            }
20289            let covers: Vec<Retained<DayCoverVC>> =
20290                COVER_STATE.with(|m| m.borrow().values().map(|s| s.vc.clone()).collect());
20291            for vc in covers {
20292                unsafe { vc.setNeedsUpdateOfScreenEdgesDeferringSystemGestures() };
20293            }
20294        }
20295
20296        fn set_status_bar_hidden(&mut self, hidden: bool) {
20297            if STATUS_BAR_HIDDEN.with(|h| h.replace(hidden)) == hidden {
20298                return;
20299            }
20300            // As for gesture deferral: re-query the root and every cover VC, since UIKit asks
20301            // the topmost fullscreen presentation, which is the cover while one is up. Inside
20302            // an animation block, so `preferredStatusBarUpdateAnimation`'s fade applies.
20303            let mut vcs: Vec<Retained<UIViewController>> = WINDOW
20304                .with(|w| w.borrow().clone())
20305                .and_then(|w| w.rootViewController())
20306                .into_iter()
20307                .collect();
20308            vcs.extend(
20309                COVER_STATE
20310                    .with(|m| {
20311                        m.borrow()
20312                            .values()
20313                            .map(|s| s.vc.clone())
20314                            .collect::<Vec<_>>()
20315                    })
20316                    .into_iter()
20317                    .map(objc2::rc::Retained::into_super),
20318            );
20319            let update = block2::RcBlock::new(move || {
20320                for vc in &vcs {
20321                    vc.setNeedsStatusBarAppearanceUpdate();
20322                }
20323            });
20324            unsafe { UIView::animateWithDuration_animations(0.25, &update, mtm()) };
20325        }
20326
20327        /// The app-wide style, on every window without one of its own: UIKit has no app-level
20328        /// switch, so each scene's window takes it (a secondary window included, and one that
20329        /// opens later through `build_scene_window`).
20330        fn set_appearance(&mut self, dark: Option<bool>) {
20331            let style = interface_style(dark);
20332            APP_STYLE.with(|a| a.set(Some(style)));
20333            if SCENES.with(|s| s.borrow().is_empty()) {
20334                WINDOW.with(|w| {
20335                    if let Some(window) = w.borrow().as_ref() {
20336                        unsafe { window.setOverrideUserInterfaceStyle(style) };
20337                    }
20338                });
20339            }
20340            refresh_scene_styles();
20341        }
20342
20343        /// Settings › Accessibility › Motion › "Reduce Motion" (docs/accessibility.md). The
20344        /// app delegate's `reduceMotionChanged:` observer re-reads it on a flip.
20345        fn reduce_motion(&mut self) -> bool {
20346            objc2_ui_kit::UIAccessibilityIsReduceMotionEnabled()
20347        }
20348
20349        /// All sixteen roles from UIKit's own adaptive colors (`role_uicolor`), resolved for
20350        /// the app's appearance: the same colors a role ink shows in a view.
20351        fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
20352            use objc2_ui_kit::{UITraitCollection, UIUserInterfaceStyle};
20353            let dark = self.dark_mode();
20354            let traits = UITraitCollection::traitCollectionWithUserInterfaceStyle(if dark {
20355                UIUserInterfaceStyle::Dark
20356            } else {
20357                UIUserInterfaceStyle::Light
20358            });
20359            let color = role_uicolor(role).resolvedColorWithTraitCollection(&traits);
20360            uicolor_components(&color).unwrap_or_else(|| role.fallback(dark))
20361        }
20362
20363        fn dark_mode(&mut self) -> bool {
20364            use objc2_ui_kit::UIUserInterfaceStyle as Style;
20365            // A DAY_THEME launch override wins (themed capture runs); else the current
20366            // trait collection's interface style.
20367            match std::env::var("DAY_THEME").ok().as_deref() {
20368                Some("dark") => return true,
20369                Some("light") => return false,
20370                _ => {}
20371            }
20372            // The WINDOW's own style, not the AMBIENT `currentTraitCollection`. An override
20373            // applied through `set_appearance` is on the window immediately, while the ambient
20374            // trait collection only picks it up at the next layout pass — and
20375            // `note_appearance_changed` reads this the instant the override is set. Reading the
20376            // ambient one there answers with the old appearance, so `dark_mode()`'s signal never
20377            // flips: every native view around it recolors and every canvas keeps its stale
20378            // palette, which is dark text on a dark ground.
20379            //
20380            // The app-wide choice, not the primary window's own style: that window may carry a
20381            // per-window override (`WindowChange::Appearance`), which is not the app's answer.
20382            let override_style = APP_STYLE
20383                .with(std::cell::Cell::get)
20384                .unwrap_or(Style::Unspecified);
20385            if override_style != Style::Unspecified {
20386                return override_style == Style::Dark;
20387            }
20388            // Read a persistent trait environment, not currentTraitCollection: the latter
20389            // is scoped to UIKit callbacks and can be stale/default on our deferred queue.
20390            // A per-window override is not the app-wide answer, so use its screen instead.
20391            let primary = SCENES
20392                .with(|s| {
20393                    s.borrow()
20394                        .iter()
20395                        .find(|e| e.node.is_none())
20396                        .map(|e| (e.window.clone(), e.appearance.get().is_some()))
20397                })
20398                .or_else(|| WINDOW.with(|w| w.borrow().clone().map(|w| (w, false))));
20399            if let Some((window, own_override)) = primary {
20400                use objc2_ui_kit::UITraitEnvironment as _;
20401                if own_override && let Some(scene) = window.windowScene() {
20402                    return unsafe { scene.screen().traitCollection().userInterfaceStyle() }
20403                        == Style::Dark;
20404                }
20405                return unsafe { window.traitCollection().userInterfaceStyle() } == Style::Dark;
20406            }
20407            unsafe {
20408                objc2_ui_kit::UITraitCollection::currentTraitCollection().userInterfaceStyle()
20409                    == Style::Dark
20410            }
20411        }
20412
20413        /// The back button, pressed: on the innermost navigation host that has a page to pop
20414        /// — the one whose controller sits deepest in the view hierarchy, since a `nav_stack`
20415        /// built inside a page nests its controller inside the outer host's — through
20416        /// `DayNavController::press_back`, so a scripted back runs `shouldPopItem:`, the pop
20417        /// override and the transition report, exactly as a tap does.
20418        fn native_back(&mut self) -> bool {
20419            let candidates: Vec<(usize, Retained<DayNavController>)> = NAV_STATE.with(|m| {
20420                m.borrow()
20421                    .iter()
20422                    .filter_map(|(h, s)| {
20423                        let nav = s.active_nav();
20424                        let shown = nav
20425                            .viewIfLoaded()
20426                            .is_some_and(|v| unsafe { v.window() }.is_some());
20427                        (shown && unsafe { nav.viewControllers() }.count() > 1).then_some((*h, nav))
20428                    })
20429                    .collect()
20430            });
20431            let depth = |nav: &DayNavController| {
20432                let mut n = 0usize;
20433                let mut v = nav.viewIfLoaded();
20434                while let Some(cur) = v {
20435                    n += 1;
20436                    v = unsafe { cur.superview() };
20437                }
20438                n
20439            };
20440            if *DIAG_NAV {
20441                let all: Vec<String> = NAV_STATE.with(|m| {
20442                    m.borrow()
20443                        .iter()
20444                        .map(|(h, s)| {
20445                            let nav = s.active_nav();
20446                            format!(
20447                                "host={h:x} collapsed={} count={} shown={} transitioning={}",
20448                                s.is_collapsed(),
20449                                unsafe { nav.viewControllers() }.count(),
20450                                nav.viewIfLoaded()
20451                                    .is_some_and(|v| unsafe { v.window() }.is_some()),
20452                                unsafe { nav.transitionCoordinator() }.is_some(),
20453                            )
20454                        })
20455                        .collect()
20456                });
20457                log::debug!(
20458                    "DAYDIAG native_back candidates={} of {:?}",
20459                    candidates.len(),
20460                    all
20461                );
20462            }
20463            let Some((_, nav)) = candidates.into_iter().max_by_key(|(_, nav)| depth(nav)) else {
20464                return false;
20465            };
20466            let pressed = nav.press_back();
20467            if *DIAG_NAV {
20468                log::debug!("DAYDIAG native_back pressed={pressed}");
20469            }
20470            pressed
20471        }
20472
20473        fn ui_idle(&mut self) -> bool {
20474            let modal = MODAL_BUSY.with(std::cell::Cell::get)
20475                || MODAL_QUEUE.with(|q| !q.borrow().is_empty());
20476            let top = topmost_vc().is_some_and(|top| top.transitionCoordinator().is_some());
20477            // A nav push/pop animates on its UINavigationController, which topmost_vc()
20478            // (presented modals only) never reaches — so without this a scripted screenshot
20479            // taken right after `navigate` catches the outgoing page (or a mid-slide frame),
20480            // the way the iOS gallery captures did. Only on-screen navigation hosts block
20481            // capture: a hidden tab can retain an interrupted coordinator indefinitely.
20482            let nav = NAV_STATE.with(|m| {
20483                m.borrow().iter().find_map(|(h, s)| {
20484                    let nav = s.active_nav();
20485                    let shown = nav.viewIfLoaded().is_some_and(|v| v.window().is_some());
20486                    (shown && nav.transitionCoordinator().is_some())
20487                        .then(|| (*h, shown, nav.viewControllers().count()))
20488                })
20489            });
20490            let selecting = NAV_TABS.with(|m| {
20491                m.borrow()
20492                    .values()
20493                    .any(|t| t.pending_selection.get().is_some())
20494            });
20495            let active = modal || top || nav.is_some() || selecting;
20496            if *DIAG_NAV && active {
20497                log::debug!("DAYDIAG ui_idle busy modal={modal} top={top} nav={nav:x?}");
20498            }
20499            if active {
20500                UI_LAST_ACTIVE.with(|t| t.set(Some(std::time::Instant::now())));
20501                return false;
20502            }
20503            // One settle margin past the last observed transition: the coordinator clears a
20504            // frame before the final composite, and a capture in that gap still shows a
20505            // sliver of the outgoing page.
20506            UI_LAST_ACTIVE
20507                .with(std::cell::Cell::get)
20508                .is_none_or(|t| t.elapsed() > std::time::Duration::from_millis(250))
20509        }
20510    }
20511
20512    /// One queued modal transition. UIKit view-controller presentation is transactional: a
20513    /// present or dismiss issued while another transition is in flight is silently dropped (or
20514    /// lands stacked on a half-presented alert, where a later `dismiss` hits the child instead
20515    /// of the alert) — exactly how scripted respond → present bursts left dialogs stuck on
20516    /// screen in CI. Every present/dismiss therefore goes through a FIFO pumped from each
20517    /// transition's completion block, so transitions never overlap.
20518    enum ModalOp {
20519        Present(u64, Retained<UIViewController>),
20520        /// Dismiss request + how many 50ms defer-retries it has already made.
20521        Dismiss(u64, u32),
20522        /// Present a cover (docs/cover.md) + how many 50ms defer-retries it has already made.
20523        ///
20524        /// Its OWN op rather than a `Run` closure, so it gets the same treatment a dialog does:
20525        /// `Run` executes unconditionally, and a cover presented across an animating transition is
20526        /// refused by UIKit with no completion — the same refusal `Present` below waits out. As a
20527        /// closure it also had nowhere to put a retry and no way to report the drop, so the panel
20528        /// just never appeared, with no watchdog (that is armed only after the closure's early
20529        /// returns) and nothing in the log.
20530        Cover(Retained<DayCoverVC>, u32),
20531        /// A deferred UI mutation (nav push/pop) that must not overlap a modal transition.
20532        Run(Box<dyn FnOnce()>),
20533    }
20534
20535    /// Whether a dayscript engine is driving this app (docs/testing): scripted sessions
20536    /// answer file pickers programmatically via `respond`, so the NATIVE picker UI is never
20537    /// touched — and the document picker is a REMOTE view controller whose hosted view can
20538    /// survive programmatic dismissal on the simulator, photobombing every later screenshot.
20539    /// Skip presenting it; the pending request still resolves through the normal channel.
20540    /// Alerts / prompts / sheets are in-process and still present natively.
20541    fn dayscript_driven() -> bool {
20542        std::env::var_os("DAYSCRIPT_PORT").is_some()
20543    }
20544
20545    fn modal_enqueue(op: ModalOp) {
20546        MODAL_QUEUE.with(|q| q.borrow_mut().push_back(op));
20547        modal_pump();
20548    }
20549
20550    /// Mark a transition in flight and arm a watchdog: if UIKit ever drops a transition's
20551    /// completion (observed with remote view controllers under scripted bursts), the queue
20552    /// would jam forever behind the stuck busy flag — after 2s the watchdog clears it and
20553    /// pumps, so one lost completion can't freeze every later dialog and deferred nav op.
20554    fn modal_begin_transition() {
20555        MODAL_BUSY.with(|c| c.set(true));
20556        let generation = MODAL_GEN.with(std::cell::Cell::get).wrapping_add(1);
20557        MODAL_GEN.with(|c| c.set(generation));
20558        let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_secs(4))
20559            .unwrap_or(dispatch2::DispatchTime::NOW);
20560        let _ = dispatch2::DispatchQueue::main().after(when, move || {
20561            if MODAL_BUSY.with(std::cell::Cell::get)
20562                && MODAL_GEN.with(std::cell::Cell::get) == generation
20563            {
20564                log::warn!("modal transition completion lost — unjamming the queue");
20565                MODAL_BUSY.with(|c| c.set(false));
20566                modal_pump();
20567            }
20568        });
20569    }
20570
20571    /// Normal end of a transition: clear busy, invalidate the watchdog, run the next op.
20572    fn modal_end_transition() {
20573        MODAL_GEN.with(|c| c.set(MODAL_GEN.with(std::cell::Cell::get).wrapping_add(1)));
20574        MODAL_BUSY.with(|c| c.set(false));
20575        modal_pump();
20576    }
20577
20578    /// Put `op` back at the queue's head and retry shortly: some other UIKit transition (a
20579    /// nav push/pop) is animating, and modal work issued across it is silently dropped.
20580    fn modal_defer_retry(op: ModalOp) {
20581        MODAL_QUEUE.with(|q| q.borrow_mut().push_front(op));
20582        MODAL_BUSY.with(|c| c.set(true)); // hold the queue while we wait
20583        MODAL_GEN.with(|c| c.set(MODAL_GEN.with(std::cell::Cell::get).wrapping_add(1)));
20584        let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
20585            .unwrap_or(dispatch2::DispatchTime::NOW);
20586        let _ = dispatch2::DispatchQueue::main().after(when, || {
20587            MODAL_BUSY.with(|c| c.set(false));
20588            modal_pump();
20589        });
20590    }
20591
20592    /// Run `f` now if no modal transition is in flight or queued, else queue it behind them.
20593    /// Mark the transition clock the instant a nav push/pop is REQUESTED. `pushViewController`
20594    /// sets up its transition coordinator on a later run-loop turn, so `ui_idle`'s coordinator
20595    /// check has a brief blind window right after the request; stamping here keeps `ui_idle` false
20596    /// across it (the 250ms settle margin), so a screenshot issued immediately after `navigate`
20597    /// never captures the outgoing page before the incoming one has begun to slide in.
20598    fn note_ui_transition() {
20599        UI_LAST_ACTIVE.with(|t| t.set(Some(std::time::Instant::now())));
20600    }
20601
20602    /// How long a size-class transition is given before its flag is released anyway. The
20603    /// coordinator's completion is what normally ends it; this is the floor under a
20604    /// completion that never arrives (an interrupted resize), because a stuck flag would
20605    /// swallow the user's next back.
20606    const CLASS_TRANSITION_CEILING: std::time::Duration = std::time::Duration::from_secs(2);
20607
20608    /// Hold the size-class flag for the length of `coordinator`'s transition
20609    /// (`CLASS_TRANSITIONS`, and `DayRootVC::willTransitionToTraitCollection:`).
20610    fn begin_class_transition(
20611        coordinator: &ProtocolObject<dyn objc2_ui_kit::UIViewControllerTransitionCoordinator>,
20612    ) {
20613        use objc2_ui_kit::{
20614            UIViewControllerTransitionCoordinator, UIViewControllerTransitionCoordinatorContext,
20615        };
20616        CLASS_TRANSITIONS.with(|c| c.set(c.get() + 1));
20617        let generation = CLASS_TRANSITION_GEN.with(|c| {
20618            let g = c.get().wrapping_add(1);
20619            c.set(g);
20620            g
20621        });
20622        if *DIAG_NAV {
20623            log::debug!(
20624                "DAYDIAG size-class transition begins (depth {})",
20625                CLASS_TRANSITIONS.with(std::cell::Cell::get)
20626            );
20627        }
20628        let completion = block2::RcBlock::new(
20629            move |_ctx: NonNull<
20630                ProtocolObject<dyn UIViewControllerTransitionCoordinatorContext>,
20631            >| {
20632                day_spec::ffi_guard::contain((), || {
20633                    CLASS_TRANSITIONS.with(|c| c.set(c.get().saturating_sub(1)));
20634                    if *DIAG_NAV {
20635                        log::debug!(
20636                            "DAYDIAG size-class transition ends (depth {})",
20637                            CLASS_TRANSITIONS.with(std::cell::Cell::get)
20638                        );
20639                    }
20640                });
20641            },
20642        );
20643        unsafe { coordinator.animateAlongsideTransition_completion(None, Some(&completion)) };
20644        // The floor under a completion that never arrives (an interrupted resize): a flag left
20645        // standing would swallow the user's next back. Generation-gated, so it only clears the
20646        // transition it was scheduled for.
20647        let when = dispatch2::DispatchTime::try_from(CLASS_TRANSITION_CEILING)
20648            .unwrap_or(dispatch2::DispatchTime::NOW);
20649        let _ = dispatch2::DispatchQueue::main().after(when, move || {
20650            day_spec::ffi_guard::contain((), || {
20651                if CLASS_TRANSITION_GEN.with(std::cell::Cell::get) == generation
20652                    && CLASS_TRANSITIONS.with(std::cell::Cell::get) > 0
20653                {
20654                    log::warn!("size-class transition completion lost — releasing the flag");
20655                    CLASS_TRANSITIONS.with(|c| c.set(0));
20656                }
20657            });
20658        });
20659    }
20660
20661    /// Switch a tabs host's selection once no ON-SCREEN navigation stack has a transition in
20662    /// flight. Switching tabs hides the outgoing tab's stack, and a push or pop still
20663    /// animating there never completes once its view has left the window: the transition
20664    /// coordinator stays alive, the popped page stays on the stack, and `ui_idle` reports a
20665    /// UI that never settles — a walkthrough's every later screenshot failed "still settling"
20666    /// on one variant in eight (Day-Trader's back-then-switch on an iOS 27 iPhone). The
20667    /// selection already moved in Day's tree; only the native switch waits, bounded so a
20668    /// coordinator that never clears still gets its switch.
20669    fn tabs_select_when_settled(hp: usize, i: usize) {
20670        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
20671        let ticket = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
20672        NAV_TABS.with(|m| {
20673            if let Some(t) = m.borrow().get(&hp) {
20674                t.pending_selection.set(Some(ticket));
20675            }
20676        });
20677        tabs_apply_when_settled(hp, i, 0, ticket);
20678    }
20679
20680    fn tabs_apply_when_settled(hp: usize, i: usize, attempt: u32, ticket: u64) {
20681        if !NAV_TABS.with(|m| {
20682            m.borrow()
20683                .get(&hp)
20684                .is_some_and(|t| t.pending_selection.get() == Some(ticket))
20685        }) {
20686            return; // host disposed, or a newer programmatic/user selection superseded this one
20687        }
20688        let in_flight = NAV_STATE.with(|m| {
20689            m.borrow().values().any(|s| {
20690                let nav = s.active_nav();
20691                unsafe { nav.transitionCoordinator() }.is_some()
20692                    && unsafe { nav.viewIfLoaded() }.is_some_and(|v| v.window().is_some())
20693            })
20694        });
20695        if in_flight && attempt < 120 {
20696            if *DIAG_NAV && attempt == 0 {
20697                log::debug!("DAYDIAG tabs select {i} waits for a stack transition");
20698            }
20699            // Plain data across the turn (a main-thread-only controller cannot).
20700            let when = dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(50))
20701                .unwrap_or(dispatch2::DispatchTime::NOW);
20702            let _ = dispatch2::DispatchQueue::main().after(when, move || {
20703                day_spec::ffi_guard::contain((), || {
20704                    tabs_apply_when_settled(hp, i, attempt + 1, ticket);
20705                });
20706            });
20707            return;
20708        }
20709        let found = NAV_TABS.with(|m| {
20710            let m = m.borrow();
20711            let t = m.get(&hp)?;
20712            Some((t.tabbar.clone(), t.tabs.get(i).cloned(), t.vcs.len()))
20713        });
20714        let Some((tabbar, tab, pages)) = found else {
20715            return;
20716        };
20717        NAV_TABS.with(|m| {
20718            if let Some(t) = m.borrow().get(&hp) {
20719                t.pending_selection.set(None);
20720                t.suppress.set(true);
20721            }
20722        });
20723        note_ui_transition();
20724        match tab {
20725            // `setSelectedTab`, not `setSelectedIndex`: the tab is the identity now, and an
20726            // index only ever meant "the nth ROOT tab".
20727            Some(tab) => unsafe { tabbar.setSelectedTab(Some(&tab)) },
20728            // No tabs means the pre-`UITab` shape (`nav_tabs_sync_classic`), where the index
20729            // IS the address.
20730            None if i < pages => unsafe { tabbar.setSelectedIndex(i) },
20731            None => {}
20732        }
20733        NAV_TABS.with(|m| {
20734            if let Some(t) = m.borrow().get(&hp) {
20735                t.suppress.set(false);
20736            }
20737        });
20738    }
20739
20740    fn modal_after_idle(f: impl FnOnce() + 'static) {
20741        let idle =
20742            !MODAL_BUSY.with(std::cell::Cell::get) && MODAL_QUEUE.with(|q| q.borrow().is_empty());
20743        if idle {
20744            f();
20745        } else {
20746            modal_enqueue(ModalOp::Run(Box::new(f)));
20747        }
20748    }
20749
20750    /// Run the next queued modal op if no transition is in flight. Each op's completion clears
20751    /// the busy flag and pumps again.
20752    fn modal_pump() {
20753        if MODAL_BUSY.with(std::cell::Cell::get) {
20754            return;
20755        }
20756        let Some(op) = MODAL_QUEUE.with(|q| q.borrow_mut().pop_front()) else {
20757            return;
20758        };
20759        match op {
20760            ModalOp::Present(req, vc) => {
20761                // Presenting while another transition animates (a nav push the script just
20762                // triggered, an appearance change) is refused by UIKit without ever calling
20763                // the completion — the original stuck-dialog bug. Wait it out.
20764                if topmost_vc().is_some_and(|top| top.transitionCoordinator().is_some()) {
20765                    modal_defer_retry(ModalOp::Present(req, vc));
20766                    return;
20767                }
20768                let Some(top) = topmost_vc() else {
20769                    // No window to present on: resolve as dismissed so the app future settles.
20770                    present_forget(req);
20771                    emit(
20772                        WINDOW_NODE,
20773                        Event::PresentResult {
20774                            req,
20775                            result: day_spec::present::PresentResult::Dismissed,
20776                        },
20777                    );
20778                    modal_pump();
20779                    return;
20780                };
20781                modal_begin_transition();
20782                let completion = block2::RcBlock::new(modal_end_transition);
20783                unsafe {
20784                    top.presentViewController_animated_completion(
20785                        &vc,
20786                        !day_core::testing::fast_animations(),
20787                        Some(&completion),
20788                    );
20789                };
20790            }
20791            ModalOp::Dismiss(req, tries) => {
20792                // If this request's Present is still queued it never reached the screen — drop
20793                // it (the result was already resolved; there is nothing to dismiss).
20794                let dropped_queued = MODAL_QUEUE.with(|q| {
20795                    let mut q = q.borrow_mut();
20796                    let before = q.len();
20797                    q.retain(|op| !matches!(op, ModalOp::Present(r, _) if *r == req));
20798                    before != q.len()
20799                });
20800                if dropped_queued {
20801                    present_forget(req);
20802                    modal_pump();
20803                    return;
20804                }
20805                let vc: Option<Retained<UIViewController>> = PRESENT_VCS
20806                    .with(|p| p.borrow().get(&req).map(|ac| ac.clone().into_super()))
20807                    .or_else(|| {
20808                        PRESENT_PICKERS.with(|p| {
20809                            p.borrow()
20810                                .get(&req)
20811                                .map(|(picker, _)| picker.clone().into_super())
20812                        })
20813                    });
20814                let Some(vc) = vc else {
20815                    // Already gone (the user answered natively, or a stale request).
20816                    present_forget(req);
20817                    modal_pump();
20818                    return;
20819                };
20820                // Not attached yet (its presentation transition is still in flight — e.g. the
20821                // watchdog unjammed the queue mid-present) or some other transition is still
20822                // animating: retry shortly, bounded. Skipping here would strand the dialog on
20823                // screen (the original CI bug); the bound keeps a never-presented controller
20824                // from wedging the queue forever.
20825                let attached = vc.presentingViewController().is_some();
20826                let animating = vc
20827                    .presentingViewController()
20828                    .is_some_and(|p| p.transitionCoordinator().is_some());
20829                if !attached || animating {
20830                    if tries < 100 {
20831                        modal_defer_retry(ModalOp::Dismiss(req, tries + 1));
20832                    } else {
20833                        present_forget(req);
20834                        modal_pump();
20835                    }
20836                    return;
20837                }
20838                present_forget(req);
20839                // Dismiss from the PRESENTING side: `dismiss` on the controller itself would
20840                // target any child IT presents (remote document pickers host internal view
20841                // controllers), reporting completion while the picker stays on screen. The
20842                // presenter tears down its whole presented stack. Animated: an UNANIMATED
20843                // dismissal of a remote view controller reports completion while the remote
20844                // layer stays visible on the simulator — the animated handshake is the path
20845                // that actually removes it (the queue serializes transitions either way).
20846                let presenting = vc
20847                    .presentingViewController()
20848                    .expect("attached checked above");
20849                modal_begin_transition();
20850                let completion = block2::RcBlock::new(modal_end_transition);
20851                unsafe {
20852                    presenting.dismissViewControllerAnimated_completion(true, Some(&completion));
20853                };
20854            }
20855            ModalOp::Cover(vc, tries) => {
20856                if vc.presentingViewController().is_some() {
20857                    modal_pump(); // already up (a re-present while closing was cancelled)
20858                    return;
20859                }
20860                // The same wait `Present` above does, and for the same reason: presenting across
20861                // an animating transition is refused with no completion, and a cover that loses
20862                // its presentation this way is invisible — no dialog future to resolve, no
20863                // watchdog, nothing in the log. 40 × 50ms is the two seconds a nav push and a
20864                // dismissal together take, well past any single transition.
20865                let animating = topmost_vc().is_some_and(|t| t.transitionCoordinator().is_some());
20866                if animating || topmost_vc().is_none() {
20867                    if tries < 40 {
20868                        modal_defer_retry(ModalOp::Cover(vc, tries + 1));
20869                        return;
20870                    }
20871                    // Out of retries: say so. Silence here is what made this cost a CI run to
20872                    // find — the panel simply never appeared and every later step read as a
20873                    // missing element.
20874                    log::warn!(
20875                        "a cover could not be presented after {tries} retries \
20876                         (transition still animating, or no window to present on) — \
20877                         the app continues without it"
20878                    );
20879                    modal_pump();
20880                    return;
20881                }
20882                let Some(top) = topmost_vc() else {
20883                    modal_pump();
20884                    return;
20885                };
20886                modal_begin_transition();
20887                // The sheet's dressing goes on the presentation controller UIKit makes for
20888                // THIS presentation (`CoverVcIvars`).
20889                if let Some(mtm) = MainThreadMarker::new() {
20890                    vc.configure_sheet(mtm);
20891                }
20892                let completion = block2::RcBlock::new(modal_end_transition);
20893                unsafe {
20894                    top.presentViewController_animated_completion(
20895                        &vc,
20896                        !day_core::testing::fast_animations(),
20897                        Some(&completion),
20898                    );
20899                }
20900            }
20901            ModalOp::Run(f) => {
20902                f();
20903                modal_pump();
20904            }
20905        }
20906    }
20907
20908    /// Drop the retained controller for `req` — on programmatic dismissal, or from the action
20909    /// handlers when the user answered natively (UIKit dismisses the alert itself on a tap).
20910    fn present_forget(req: u64) {
20911        PRESENT_VCS.with(|p| {
20912            p.borrow_mut().remove(&req);
20913        });
20914        PRESENT_PICKERS.with(|p| {
20915            p.borrow_mut().remove(&req);
20916        });
20917    }
20918
20919    /// Wire a document picker's delegate, retain both, and queue its presentation.
20920    fn present_doc_picker(
20921        req: u64,
20922        m: MainThreadMarker,
20923        picker: Retained<UIDocumentPickerViewController>,
20924    ) {
20925        unsafe { picker.setAllowsMultipleSelection(false) };
20926        let delegate = DayDocPicker::new(m, req);
20927        unsafe { picker.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) };
20928        PRESENT_PICKERS.with(|p| p.borrow_mut().insert(req, (picker.clone(), delegate)));
20929        modal_enqueue(ModalOp::Present(req, picker.into_super()));
20930    }
20931
20932    /// The frontmost view controller (walk past any already-presented modal, but stop short of
20933    /// one that is mid-dismissal — presenting on it would be dropped by UIKit).
20934    fn topmost_vc() -> Option<Retained<UIViewController>> {
20935        let mut vc = WINDOW.with(|w| w.borrow().clone())?.rootViewController()?;
20936        while let Some(p) = vc.presentedViewController() {
20937            if p.isBeingDismissed() {
20938                break;
20939            }
20940            vc = p;
20941        }
20942        Some(vc)
20943    }
20944
20945    struct DocPickerIvars {
20946        req: u64,
20947    }
20948
20949    define_class!(
20950        #[unsafe(super(NSObject))]
20951        #[thread_kind = MainThreadOnly]
20952        #[name = "DayUIKitDocPicker"]
20953        #[ivars = DocPickerIvars]
20954        struct DayDocPicker;
20955
20956        unsafe impl NSObjectProtocol for DayDocPicker {}
20957
20958        unsafe impl UIDocumentPickerDelegate for DayDocPicker {
20959            #[unsafe(method(documentPicker:didPickDocumentsAtURLs:))]
20960            fn did_pick(
20961                &self,
20962                _picker: &UIDocumentPickerViewController,
20963                urls: &objc2_foundation::NSArray<objc2_foundation::NSURL>,
20964            ) {
20965                day_spec::ffi_guard::contain((), || {
20966                    let req = self.ivars().req;
20967                    let mut paths = Vec::new();
20968                    for i in 0..urls.count() {
20969                        let url = urls.objectAtIndex(i);
20970                        if let Some(p) = unsafe { url.path() } {
20971                            paths.push(p.to_string());
20972                        }
20973                    }
20974                    let result = if paths.is_empty() {
20975                        day_spec::present::PresentResult::Dismissed
20976                    } else {
20977                        day_spec::present::PresentResult::Files(paths)
20978                    };
20979                    emit(WINDOW_NODE, Event::PresentResult { req, result });
20980                    PRESENT_PICKERS.with(|m| {
20981                        m.borrow_mut().remove(&req);
20982                    });
20983                    present_forget(req);
20984                });
20985            }
20986
20987            #[unsafe(method(documentPickerWasCancelled:))]
20988            fn was_cancelled(&self, _picker: &UIDocumentPickerViewController) {
20989                day_spec::ffi_guard::contain((), || {
20990                    let req = self.ivars().req;
20991                    emit(
20992                        WINDOW_NODE,
20993                        Event::PresentResult {
20994                            req,
20995                            result: day_spec::present::PresentResult::Dismissed,
20996                        },
20997                    );
20998                    PRESENT_PICKERS.with(|m| {
20999                        m.borrow_mut().remove(&req);
21000                    });
21001                    present_forget(req);
21002                });
21003            }
21004        }
21005    );
21006
21007    impl DayDocPicker {
21008        fn new(mtm: MainThreadMarker, req: u64) -> Retained<Self> {
21009            let this = Self::alloc(mtm).set_ivars(DocPickerIvars { req });
21010            unsafe { msg_send![super(this), init] }
21011        }
21012    }
21013
21014    // -----------------------------------------------------------------------
21015    // App delegate + Platform (UIApplicationMain)
21016    // -----------------------------------------------------------------------
21017
21018    define_class!(
21019        // UIResponder, not NSObject: nil-target actions (`sendAction(cut:, nil)` from the
21020        // menu, the system's edit commands) reach the app delegate only when it is a
21021        // responder — the standard iOS template shape, and the same end-of-chain catch the
21022        // macOS window delegate provides.
21023        #[unsafe(super(objc2_ui_kit::UIResponder))]
21024        #[thread_kind = MainThreadOnly]
21025        #[name = "DayAppDelegate"]
21026        struct AppDelegate;
21027
21028        unsafe impl NSObjectProtocol for AppDelegate {}
21029
21030        /// The end of the responder chain for the standard edit nav hosts: a focused text
21031        /// field answered them long before the chain got here, so what arrives is the app's.
21032        impl AppDelegate {
21033            #[unsafe(method(cut:))]
21034            fn edit_cut(&self, _sender: Option<&AnyObject>) {
21035                day_spec::ffi_guard::contain((), || {
21036                    emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut));
21037                });
21038            }
21039
21040            #[unsafe(method(copy:))]
21041            fn edit_copy(&self, _sender: Option<&AnyObject>) {
21042                day_spec::ffi_guard::contain((), || {
21043                    emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy));
21044                });
21045            }
21046
21047            #[unsafe(method(paste:))]
21048            fn edit_paste(&self, _sender: Option<&AnyObject>) {
21049                day_spec::ffi_guard::contain((), || {
21050                    emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste));
21051                });
21052            }
21053
21054            #[unsafe(method(selectAll:))]
21055            fn edit_select_all(&self, _sender: Option<&AnyObject>) {
21056                day_spec::ffi_guard::contain((), || {
21057                    emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
21058                });
21059            }
21060
21061            /// UIKit's enablement question for the standard commands — the bridge state
21062            /// answers for the edit trio; everything else falls to UIResponder's default.
21063            #[unsafe(method(canPerformAction:withSender:))]
21064            fn can_perform(&self, action: objc2::runtime::Sel, sender: *mut AnyObject) -> bool {
21065                day_spec::ffi_guard::contain(false, || {
21066                    let state = EDIT_STATE.with(std::cell::Cell::get);
21067                    if action == sel!(selectAll:) {
21068                        state.can_select_all
21069                    } else if action == sel!(cut:) {
21070                        state.can_cut
21071                    } else if action == sel!(copy:) {
21072                        state.can_copy
21073                    } else if action == sel!(paste:) {
21074                        state.can_paste
21075                            && unsafe { let pb = objc2_ui_kit::UIPasteboard::generalPasteboard(); !pb.pasteboardTypes().is_empty() }
21076                    } else {
21077                        unsafe {
21078                            msg_send![super(self), canPerformAction: action, withSender: sender]
21079                        }
21080                    }
21081                })
21082            }
21083        }
21084
21085        unsafe impl UIApplicationDelegate for AppDelegate {
21086            #[unsafe(method(application:didRegisterForRemoteNotificationsWithDeviceToken:))]
21087            fn push_registered(&self, _app: &UIApplication, token: &objc2_foundation::NSData) {
21088                day_process::services::notification(
21089                    day_process::services::NotificationEvent::Registered(token.to_vec()),
21090                );
21091            }
21092
21093            #[unsafe(method(application:didFailToRegisterForRemoteNotificationsWithError:))]
21094            fn push_registration_failed(&self, _app: &UIApplication, error: &objc2_foundation::NSError) {
21095                day_process::services::notification(
21096                    day_process::services::NotificationEvent::RegistrationFailed(error.localizedDescription().to_string()),
21097                );
21098            }
21099
21100            // Foreground notifications and taps arrive through the shared UserNotifications
21101            // delegate. Silent background pushes need a separate execution/completion contract;
21102            // advertising the fetch callback here would require a background mode in every app.
21103
21104            // The no-scene-manifest compat path reads `delegate.window` (pane's hard-won lesson).
21105            #[unsafe(method(window))]
21106            fn window(&self) -> *mut UIWindow {
21107                WINDOW.with(|w| {
21108                    w.borrow()
21109                        .as_ref()
21110                        .map_or(std::ptr::null_mut(), |r| (&raw const **r).cast_mut())
21111                })
21112            }
21113            #[unsafe(method(setWindow:))]
21114            fn set_window(&self, window: *mut UIWindow) {
21115                let retained = unsafe { window.as_ref() }.map(Retained::from);
21116                WINDOW.with(|w| *w.borrow_mut() = retained);
21117            }
21118
21119            // Scene-based lifecycle (docs/windows.md): the window is built by
21120            // DaySceneDelegate when the (primary) scene connects; launching only arms the
21121            // app-level observers that stay app-scoped under scenes.
21122            #[unsafe(method(application:didFinishLaunchingWithOptions:))]
21123            fn did_finish_launching(&self, _app: &UIApplication, _opts: *mut AnyObject) -> bool {
21124                day_process::services::initialize();
21125                // Keyboard avoidance (docs/focus.md): one app-level observer; the handler
21126                // resolves the KEY window's scene, so it follows whichever Day window the
21127                // field lives in. WillChangeFrame covers show, hide, and height changes.
21128                unsafe {
21129                    objc2_foundation::NSNotificationCenter::defaultCenter()
21130                        .addObserver_selector_name_object(
21131                            self,
21132                            sel!(keyboardWillChange:),
21133                            Some(objc2_ui_kit::UIKeyboardWillChangeFrameNotification),
21134                            None,
21135                        );
21136                };
21137                // The system reduce-motion switch (docs/accessibility.md): app-scoped like
21138                // the setting itself; the handler re-reads it into day-core's gate.
21139                unsafe {
21140                    objc2_foundation::NSNotificationCenter::defaultCenter()
21141                        .addObserver_selector_name_object(
21142                            self,
21143                            sel!(reduceMotionChanged:),
21144                            Some(objc2_ui_kit::UIAccessibilityReduceMotionStatusDidChangeNotification),
21145                            None,
21146                        );
21147                };
21148                // The system text size (Dynamic Type) changing under a running app: labels
21149                // take the new size by themselves, Day's measurements of them do not.
21150                unsafe {
21151                    objc2_foundation::NSNotificationCenter::defaultCenter()
21152                        .addObserver_selector_name_object(
21153                            self,
21154                            sel!(textSizeChanged:),
21155                            Some(objc2_ui_kit::UIContentSizeCategoryDidChangeNotification),
21156                            None,
21157                        );
21158                };
21159                // Screen recording and mirroring starting or stopping (docs/windows.md): the
21160                // content-protection shields follow it. Any screen will do: the handler
21161                // re-reads every scene's own capture state.
21162                unsafe {
21163                    objc2_foundation::NSNotificationCenter::defaultCenter()
21164                        .addObserver_selector_name_object(
21165                            self,
21166                            sel!(screenCaptureChanged:),
21167                            Some(objc2_ui_kit::UIScreenCapturedDidChangeNotification),
21168                            None,
21169                        );
21170                };
21171                true
21172            }
21173
21174            // Every connecting scene — the primary at launch, each secondary day window
21175            // (docs/windows.md), and any system-restored session — runs DaySceneDelegate.
21176            #[unsafe(method_id(application:configurationForConnectingSceneSession:options:))]
21177            fn configuration_for_scene(
21178                &self,
21179                _app: &UIApplication,
21180                session: &objc2_ui_kit::UISceneSession,
21181                _options: &objc2_ui_kit::UISceneConnectionOptions,
21182            ) -> Retained<objc2_ui_kit::UISceneConfiguration> {
21183                use objc2::ClassType as _;
21184                let role = unsafe { session.role() };
21185                let config = objc2_ui_kit::UISceneConfiguration::configurationWithName_sessionRole(
21186                    None,
21187                    &role,
21188                    self.mtm(),
21189                );
21190                unsafe { config.setDelegateClass(Some(DaySceneDelegate::class())) };
21191                config
21192            }
21193
21194            // Custom-scheme deep link (docs/navigation.md): route = URL host + path,
21195            // delivered to the active nav host as RouteRequested.
21196            #[unsafe(method(application:openURL:options:))]
21197            fn open_url(
21198                &self,
21199                _app: &UIApplication,
21200                url: &objc2_foundation::NSURL,
21201                _options: *mut AnyObject,
21202            ) -> bool {
21203                // The shared URL → route mapping (docs/deep-links.md): absoluteString keeps
21204                // the query (route params ride it) and the original percent-encoding — the
21205                // route parser decodes, not this layer.
21206                day_spec::ffi_guard::contain(false, || {
21207                    deliver_open_url(url);
21208                    true
21209                })
21210            }
21211
21212            // Lifecycle (docs/lifecycle.md): under the scene lifecycle the activation and
21213            // foreground phases are SCENE events — DaySceneDelegate derives the app-level
21214            // day phases from all scenes (debounced, docs/windows.md). Memory warnings and
21215            // termination stay app-scoped and keep arriving here.
21216            #[unsafe(method(applicationDidReceiveMemoryWarning:))]
21217            fn did_receive_memory_warning(&self, _app: &UIApplication) {
21218                day_spec::ffi_guard::contain((), || {
21219                    emit(
21220                        WINDOW_NODE,
21221                        Event::Lifecycle(day_spec::Lifecycle::DidReceiveMemoryWarning),
21222                    );
21223                });
21224            }
21225            #[unsafe(method(applicationWillTerminate:))]
21226            fn will_terminate(&self, _app: &UIApplication) {
21227                day_spec::ffi_guard::contain((), || {
21228                    emit(
21229                        WINDOW_NODE,
21230                        Event::Lifecycle(day_spec::Lifecycle::WillTerminate),
21231                    );
21232                    // The process ends when this returns, so DidExit follows here
21233                    // (docs/lifecycle.md).
21234                    emit(WINDOW_NODE, Event::Lifecycle(day_spec::Lifecycle::DidExit));
21235                });
21236            }
21237        }
21238
21239        // Inherent (non-protocol) nav hosts: NSNotificationCenter targets land here — objc2
21240        // verifies protocol impl blocks against the protocol, and keyboardWillChange: is ours.
21241        impl AppDelegate {
21242            /// Keyboard show/hide/height change: clamp the root's bottom to the keyboard top
21243            /// (screen coords), tell Day the root resized, then reveal the focused field.
21244            #[unsafe(method(keyboardWillChange:))]
21245            fn keyboard_will_change(&self, notification: &objc2_foundation::NSNotification) {
21246                day_spec::ffi_guard::contain((), || {
21247                    use objc2_ui_kit::NSValueUIGeometryExtensions;
21248                    // The KEY window's scene (docs/windows.md): the keyboard belongs to
21249                    // whichever Day window holds the focused field.
21250                    let Some((root, base, target)) = with_key_scene(|e| {
21251                        (e.root_view.clone(), e.base_frame.get(), key_scene_target(e))
21252                    }) else {
21253                        return;
21254                    };
21255                    let Some(info) = (unsafe { notification.userInfo() }) else {
21256                        return;
21257                    };
21258                    let Some(val) = info
21259                        .objectForKey(unsafe { objc2_ui_kit::UIKeyboardFrameEndUserInfoKey })
21260                        .and_then(|o| o.downcast::<objc2_foundation::NSValue>().ok())
21261                    else {
21262                        return;
21263                    };
21264                    let kb = unsafe { val.CGRectValue() };
21265                    avoid_keyboard_in_covers(kb);
21266                    // The holder fills the window, so the root's frame is in window == screen
21267                    // coordinates; a hidden keyboard reports an off-screen frame (top >= bottom).
21268                    let base_bottom = base.origin.y + base.size.height;
21269                    KEYBOARD_UP.with(|up| up.set(kb.origin.y < base_bottom && kb.size.height > 0.0));
21270                    let new_h = if kb.origin.y < base_bottom {
21271                        (kb.origin.y - base.origin.y).max(0.0)
21272                    } else {
21273                        base.size.height
21274                    };
21275                    let f = CGRect::new(base.origin, CGSize::new(base.size.width, new_h));
21276                    #[expect(
21277                        clippy::float_cmp,
21278                        reason = "unchanged-value check against the exact height set last time"
21279                    )]
21280                    let resized = unsafe { root.frame() }.size.height != new_h;
21281                    if resized {
21282                        unsafe { root.setFrame(f) };
21283                        // The shrink is the keyboard's, so the size class keeps the window's
21284                        // own height, as the trait collection does (docs/size-classes.md).
21285                        let size = Size::new(f.size.width, f.size.height);
21286                        day_core::note_keyboard_overlap(target, size, base.size.height - new_h);
21287                        emit(target, Event::WindowResized(size));
21288                    }
21289                    if new_h < base.size.height {
21290                        reveal_focused_field();
21291                    }
21292                });
21293            }
21294
21295            /// Reduce Motion flipped in Settings: UIKit posts the status change on the main
21296            /// thread with `UIAccessibilityIsReduceMotionEnabled` already answering the new
21297            /// value, so the re-read runs right here.
21298            #[unsafe(method(reduceMotionChanged:))]
21299            fn reduce_motion_changed(&self, _notification: &objc2_foundation::NSNotification) {
21300                day_spec::ffi_guard::contain((), day_core::note_motion_changed);
21301            }
21302
21303            /// The system text size changed. The notification arrives before the new size
21304            /// has reached the views' trait collections, and a label adjusts its font from its
21305            /// own trait change, so re-measure on the next turn of the main queue, once they
21306            /// have.
21307            #[unsafe(method(textSizeChanged:))]
21308            fn text_size_changed(&self, _notification: &objc2_foundation::NSNotification) {
21309                schedule_text_size_remeasure();
21310            }
21311
21312            /// A recording or mirroring of some screen started or stopped. The scene trait the
21313            /// shields read can settle a moment after the notification, so look again on the
21314            /// next turn of the main queue as well.
21315            #[unsafe(method(screenCaptureChanged:))]
21316            fn screen_capture_changed(&self, _notification: &objc2_foundation::NSNotification) {
21317                day_spec::ffi_guard::contain((), refresh_capture_shields);
21318                dispatch2::DispatchQueue::main().exec_async(|| {
21319                    day_spec::ffi_guard::contain((), refresh_capture_shields);
21320                });
21321            }
21322        }
21323    );
21324
21325    // -----------------------------------------------------------------------------------
21326    // DaySceneDelegate — every scene's window lifecycle (docs/windows.md). The PRIMARY
21327    // scene (the one consuming the parked `run` payload) mounts the day tree exactly as
21328    // the pre-scene app delegate did; a SECONDARY scene completes a pending
21329    // `day::open_window` through `finish_window_open`, or — when the record is gone or the
21330    // session is a stale restoration — asks the system to destroy itself.
21331    // -----------------------------------------------------------------------------------
21332
21333    use objc2_ui_kit::{UISceneDelegate, UIWindowSceneDelegate};
21334
21335    define_class!(
21336        #[unsafe(super(NSObject))]
21337        #[thread_kind = MainThreadOnly]
21338        #[name = "DaySceneDelegate"]
21339        #[ivars = ()]
21340        struct DaySceneDelegate;
21341
21342        unsafe impl NSObjectProtocol for DaySceneDelegate {}
21343
21344        unsafe impl UISceneDelegate for DaySceneDelegate {
21345            #[unsafe(method(scene:willConnectToSession:options:))]
21346            fn scene_will_connect(
21347                &self,
21348                scene: &objc2_ui_kit::UIScene,
21349                session: &objc2_ui_kit::UISceneSession,
21350                options: &objc2_ui_kit::UISceneConnectionOptions,
21351            ) {
21352                // Contained (§8.5): `ready` mounts the whole day tree, and
21353                // `finish_window_open` re-enters day-core.
21354                day_spec::ffi_guard::contain((), || {
21355                    let mtm = self.mtm();
21356                    let Some(win_scene) = scene.downcast_ref::<objc2_ui_kit::UIWindowScene>()
21357                    else {
21358                        return;
21359                    };
21360                    // Secondary day window? The request's NSUserActivity names the root node.
21361                    let node = scene_activity_node(options);
21362                    if PENDING.with(|p| p.borrow().is_some()) && node.is_none() {
21363                        // The primary scene: build the window and mount the day tree. The
21364                        // parked launch options carry the app's own minimum window size;
21365                        // read without taking, since the take below is what mounts the tree.
21366                        let min =
21367                            PENDING.with(|p| p.borrow().as_ref().and_then(|(_, o, _)| o.min_size));
21368                        let (window, root_view, inner) = build_scene_window(mtm, win_scene, min);
21369                        WINDOW.with(|w| *w.borrow_mut() = Some(window.clone()));
21370                        ROOT_VIEW.with(|r| *r.borrow_mut() = Some(root_view.clone()));
21371                        ROOT_BASE_FRAME.with(|f| f.set(inner));
21372                        SCENES.with(|s| {
21373                            s.borrow_mut().push(SceneEntry::new(
21374                                window,
21375                                root_view.clone(),
21376                                inner,
21377                                None,
21378                            ));
21379                        });
21380                        // The take() cannot miss: the `is_some` gate above just read it, and
21381                        // both run on the main thread.
21382                        let Some((backend, _options, ready)) =
21383                            PENDING.with(|p| p.borrow_mut().take())
21384                        else {
21385                            return;
21386                        };
21387                        let size = Size::new(inner.size.width, inner.size.height);
21388                        ready(backend, view_of(&root_view), size);
21389                        // Cold launch via deep link or quick action (docs/deep-links.md): both
21390                        // ride the connection options; `request_route` buffers until the mount
21391                        // that `ready` just kicked off completes.
21392                        scene_connection_routes(options);
21393                        return;
21394                    }
21395                    let Some(node) = node else {
21396                        // A window the platform opened by itself: iPadOS's Window ▸ New Window,
21397                        // an app icon dragged into Split View, or a session restored from a
21398                        // previous run. Nothing named a root node, so ask day-core for another
21399                        // window of the app's own new-window content and adopt this scene for
21400                        // it (`open_window` above takes the flag). An app that registered no
21401                        // new-window builder has nothing to show, and the scene goes back.
21402                        adopt_platform_scene(mtm, win_scene, session);
21403                        return;
21404                    };
21405                    PENDING_WINDOWS.with(|p| p.borrow_mut().retain(|(n, _)| *n != node));
21406                    // A secondary window is the same app at the same minimum; day-core hands
21407                    // `open_new_window` the launch options, so `None` here falls back to the
21408                    // Day.toml value the primary used (docs/size-classes.md).
21409                    let (window, root_view, inner) = build_scene_window(mtm, win_scene, None);
21410                    let size = Size::new(inner.size.width, inner.size.height);
21411                    let raw = Retained::as_ptr(&root_view) as *mut std::ffi::c_void
21412                        as day_spec::RawHandle;
21413                    SCENES.with(|s| {
21414                        s.borrow_mut().push(SceneEntry::new(
21415                            window,
21416                            root_view.clone(),
21417                            inner,
21418                            Some(node),
21419                        ));
21420                    });
21421                    // Keep the adopted root alive for the entry's lifetime; the tree holds the
21422                    // other retain through `Toolkit::adopt`.
21423                    if !day_core::finish_window_open(node, raw, size) {
21424                        // Closed before the scene connected — drop the scene again.
21425                        SCENES.with(|s| s.borrow_mut().retain(|e| e.node != Some(node)));
21426                        request_scene_destruction(mtm, session);
21427                    }
21428                });
21429            }
21430
21431            #[unsafe(method(sceneDidDisconnect:))]
21432            fn scene_did_disconnect(&self, scene: &objc2_ui_kit::UIScene) {
21433                day_spec::ffi_guard::contain((), || {
21434                    let mtm = self.mtm();
21435                    if let Some(node) = scene_entry_node_for(scene) {
21436                        SCENES.with(|s| s.borrow_mut().retain(|e| e.node != Some(node)));
21437                        // The platform committed the close (app-switcher swipe or our
21438                        // destruction request): day-core tears the subtree down on receipt.
21439                        emit(node, Event::WindowClosed);
21440                    }
21441                    note_scene_lifecycle_changed(mtm);
21442                });
21443            }
21444
21445            #[unsafe(method(sceneDidBecomeActive:))]
21446            fn scene_did_become_active(&self, scene: &objc2_ui_kit::UIScene) {
21447                day_spec::ffi_guard::contain((), || {
21448                    let mtm = self.mtm();
21449                    if let Some(node) = scene_entry_node_for(scene) {
21450                        emit(node, Event::WindowFocused(true));
21451                    }
21452                    note_scene_lifecycle_changed(mtm);
21453                });
21454            }
21455
21456            #[unsafe(method(sceneWillResignActive:))]
21457            fn scene_will_resign_active(&self, scene: &objc2_ui_kit::UIScene) {
21458                day_spec::ffi_guard::contain((), || {
21459                    let mtm = self.mtm();
21460                    if let Some(node) = scene_entry_node_for(scene) {
21461                        emit(node, Event::WindowFocused(false));
21462                    }
21463                    note_scene_lifecycle_changed(mtm);
21464                });
21465            }
21466
21467            #[unsafe(method(sceneWillEnterForeground:))]
21468            fn scene_will_enter_foreground(&self, _scene: &objc2_ui_kit::UIScene) {
21469                day_spec::ffi_guard::contain((), || {
21470                    note_scene_lifecycle_changed(self.mtm());
21471                });
21472            }
21473
21474            #[unsafe(method(sceneDidEnterBackground:))]
21475            fn scene_did_enter_background(&self, _scene: &objc2_ui_kit::UIScene) {
21476                day_spec::ffi_guard::contain((), || {
21477                    note_scene_lifecycle_changed(self.mtm());
21478                });
21479            }
21480
21481            // Warm deep link under the scene lifecycle (docs/deep-links.md): once an app
21482            // adopts scenes, URL opens arrive here, not at the app delegate's
21483            // `application:openURL:options:` (kept for the pre-scene path).
21484            #[unsafe(method(scene:openURLContexts:))]
21485            fn scene_open_url_contexts(
21486                &self,
21487                _scene: &objc2_ui_kit::UIScene,
21488                contexts: &objc2_foundation::NSSet<objc2_ui_kit::UIOpenURLContext>,
21489            ) {
21490                day_spec::ffi_guard::contain((), || {
21491                    for ctx in contexts {
21492                        deliver_open_url(&ctx.URL());
21493                    }
21494                });
21495            }
21496        }
21497
21498        unsafe impl UIWindowSceneDelegate for DaySceneDelegate {
21499            // A home-screen quick action while the app runs (cold arrivals ride the
21500            // connection options). Its type string IS the saved deep link
21501            // (docs/deep-links.md "Shortcuts are saved deep links").
21502            #[unsafe(method(windowScene:performActionForShortcutItem:completionHandler:))]
21503            fn perform_shortcut(
21504                &self,
21505                _scene: &objc2_ui_kit::UIWindowScene,
21506                item: &objc2_ui_kit::UIApplicationShortcutItem,
21507                completion: &block2::DynBlock<dyn Fn(objc2::runtime::Bool)>,
21508            ) {
21509                day_spec::ffi_guard::contain((), || {
21510                    day_core::request_route(&day_spec::route_of_url(&item.r#type().to_string()));
21511                });
21512                // Report handled even when the route dispatch was contained — the system's
21513                // completion contract is unconditional.
21514                completion.call((objc2::runtime::Bool::YES,));
21515            }
21516        }
21517    );
21518
21519    /// Deep links riding a scene's connection options — the URL that launched the app, or a
21520    /// quick action's type string. One rail either way: `day_core::request_route`, buffered
21521    /// until the first mount (docs/deep-links.md).
21522    fn deliver_open_url(url: &objc2_foundation::NSURL) {
21523        if let Some(s) = unsafe { url.absoluteString() } {
21524            if url.isFileURL() {
21525                day_core::request_open_files(vec![s.to_string()]);
21526            } else {
21527                day_core::request_open_url(&s.to_string());
21528            }
21529        }
21530    }
21531
21532    fn scene_connection_routes(options: &objc2_ui_kit::UISceneConnectionOptions) {
21533        // Raw message send: the generated `URLContexts()` binding declares the return
21534        // non-null, but a plain launch (no URL) hands back nil and the binding panics —
21535        // caught by the dayscript walkthrough on first run.
21536        let contexts: Option<Retained<objc2_foundation::NSSet<objc2_ui_kit::UIOpenURLContext>>> =
21537            unsafe { objc2::msg_send![options, URLContexts] };
21538        for ctx in contexts.into_iter().flatten() {
21539            deliver_open_url(&ctx.URL());
21540        }
21541        if let Some(item) = options.shortcutItem() {
21542            day_core::request_route(&day_spec::route_of_url(&item.r#type().to_string()));
21543        }
21544    }
21545
21546    /// The day root node a secondary-scene connection carries (`DAY_WINDOW_ACTIVITY`
21547    /// userActivity, `day.node` userInfo), if any.
21548    fn scene_activity_node(options: &objc2_ui_kit::UISceneConnectionOptions) -> Option<NodeId> {
21549        for activity in unsafe { options.userActivities() } {
21550            if unsafe { activity.activityType() }.to_string() == DAY_WINDOW_ACTIVITY
21551                && let Some(info) = unsafe { activity.userInfo() }
21552                && let Some(num) = info
21553                    .objectForKey(&*objc2_foundation::NSString::from_str("day.node"))
21554                    .and_then(|o| o.downcast::<objc2_foundation::NSNumber>().ok())
21555            {
21556                return Some(NodeId(num.as_u64()));
21557            }
21558        }
21559        None
21560    }
21561
21562    /// The registry node of the scene owning this window, if it is a secondary day window.
21563    fn scene_entry_node_for(scene: &objc2_ui_kit::UIScene) -> Option<NodeId> {
21564        let win_scene = scene.downcast_ref::<objc2_ui_kit::UIWindowScene>()?;
21565        SCENES.with(|s| {
21566            s.borrow()
21567                .iter()
21568                .find(|e| {
21569                    e.window
21570                        .windowScene()
21571                        .is_some_and(|ws| std::ptr::eq(&raw const *ws, win_scene))
21572                })
21573                .and_then(|e| e.node)
21574        })
21575    }
21576
21577    /// Fill a scene the platform opened on its own with another window of the app.
21578    ///
21579    /// iPadOS 26 offers Window ▸ New Window for any app that supports multiple scenes, and the
21580    /// same connection arrives when an app icon is dragged into Split View or a session is
21581    /// restored from a previous run. None of those name a day root node the way
21582    /// `Toolkit::open_window` does, so the content comes from what the app registered with
21583    /// `day::register_new_window` — the same builder behind File ▸ New Window on desktop.
21584    ///
21585    /// The window is built first so day-core has something to adopt, and `ADOPTING` makes the
21586    /// `open_window` that `open_new_window` calls back into take this scene instead of asking
21587    /// the system for another one. With no builder registered there is nothing to put in the
21588    /// window, and the scene is handed back rather than left blank.
21589    fn adopt_platform_scene(
21590        mtm: MainThreadMarker,
21591        win_scene: &objc2_ui_kit::UIWindowScene,
21592        session: &objc2_ui_kit::UISceneSession,
21593    ) {
21594        let (window, root_view, inner) = build_scene_window(mtm, win_scene, None);
21595        let size = Size::new(inner.size.width, inner.size.height);
21596        let raw = Retained::as_ptr(&root_view) as *mut std::ffi::c_void as day_spec::RawHandle;
21597        ADOPTING.with(|a| a.set(true));
21598        ADOPTING_SCENE.with(|n| n.set(None));
21599        let opened = day_core::open_new_window();
21600        ADOPTING.with(|a| a.set(false));
21601        let node = ADOPTING_SCENE.with(std::cell::Cell::take);
21602        let (Some(_), Some(node)) = (opened, node) else {
21603            log::info!("day-toolkit-uikit: no new-window content registered; returning the scene");
21604            request_scene_destruction(mtm, session);
21605            return;
21606        };
21607        SCENES.with(|s| {
21608            s.borrow_mut()
21609                .push(SceneEntry::new(window, root_view, inner, Some(node)));
21610        });
21611        if !day_core::finish_window_open(node, raw, size) {
21612            SCENES.with(|s| s.borrow_mut().retain(|e| e.node != Some(node)));
21613            request_scene_destruction(mtm, session);
21614        }
21615    }
21616
21617    /// Ask the system to drop a scene session (no undo UI, no animation preference).
21618    fn request_scene_destruction(mtm: MainThreadMarker, session: &objc2_ui_kit::UISceneSession) {
21619        let app = UIApplication::sharedApplication(mtm);
21620        unsafe {
21621            app.requestSceneSessionDestruction_options_errorHandler(session, None, None);
21622        }
21623    }
21624
21625    /// Mobile backends deliver the FULL lifecycle (docs/lifecycle.md), including the background,
21626    /// foreground, and memory-warning phases desktops lack. `const` for `day::require_lifecycle!`.
21627    #[must_use]
21628    pub const fn lifecycle_supported(_phase: day_spec::Lifecycle) -> bool {
21629        true
21630    }
21631
21632    /// Register bundled font files (§18.4) with CoreText so `Font::Custom` families resolve via
21633    /// `UIFont(name:)`. The files ride the `DayPieces` SwiftPM bundle (`fonts/` copied by `day
21634    /// build`, which also lists them in the app's `UIAppFonts` — this call covers dev builds and
21635    /// doubles as the loud failure path). Duplicate registration (`UIAppFonts` already loaded the
21636    /// file) fails harmlessly, so failures here are only logged when the family is then missing.
21637    fn register_bundled_fonts() {
21638        // CFURLRef is toll-free bridged with NSURL.
21639        #[link(name = "CoreText", kind = "framework")]
21640        unsafe extern "C" {
21641            fn CTFontManagerRegisterFontsForURL(
21642                font_url: *const std::ffi::c_void,
21643                scope: u32, // kCTFontManagerScopeProcess = 1
21644                error: *mut *const std::ffi::c_void,
21645            ) -> bool;
21646        }
21647        let mut dirs: Vec<std::path::PathBuf> = Vec::new();
21648        // The DayPieces bundle's fonts/ directory (SwiftPM `.copy` resource inside the app).
21649        let main = unsafe { objc2_foundation::NSBundle::mainBundle() };
21650        if let Some(res) = unsafe { main.resourcePath() } {
21651            dirs.push(
21652                std::path::PathBuf::from(res.to_string())
21653                    .join("DayPieces_DayPieces.bundle")
21654                    .join("fonts"),
21655            );
21656        }
21657        if let Some(dev) = day_spec::fonts::font_dir() {
21658            dirs.push(dev);
21659        }
21660        for dir in dirs {
21661            for path in day_spec::fonts::font_files_in(&dir) {
21662                let url = unsafe {
21663                    objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(
21664                        &path.to_string_lossy(),
21665                    ))
21666                };
21667                unsafe {
21668                    let _ = CTFontManagerRegisterFontsForURL(
21669                        Retained::as_ptr(&url).cast::<std::ffi::c_void>(),
21670                        1,
21671                        std::ptr::null_mut(),
21672                    );
21673                }
21674            }
21675        }
21676    }
21677
21678    impl Platform for Uikit {
21679        const TARGET: &'static str = "ios-uikit";
21680        const TOOLKIT: &'static str = "uikit";
21681
21682        fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
21683            // Bundled custom fonts (§18.4) must be registered before the first label realizes.
21684            register_bundled_fonts();
21685            PENDING.with(|p| *p.borrow_mut() = Some((self, options, ready)));
21686            // Force-register the delegate class: UIApplicationMain looks it up by name before
21687            // any Rust code touches it (pane's exact fix).
21688            let _ = <AppDelegate as objc2::ClassType>::class();
21689            let arg0 = c"Day".as_ptr().cast_mut();
21690            let mut argv = [arg0];
21691            let argv_ptr = NonNull::new(argv.as_mut_ptr()).unwrap();
21692            let delegate = NSString::from_str("DayAppDelegate");
21693            #[allow(deprecated)]
21694            unsafe {
21695                UIApplicationMain(1 as c_int, argv_ptr, None, Some(&delegate));
21696            }
21697        }
21698
21699        fn post(f: Box<dyn FnOnce() + Send>) {
21700            dispatch2::DispatchQueue::main().exec_async(f);
21701        }
21702
21703        fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
21704            // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
21705            // queue, no helper thread. The closure is app code inside dispatch's C frame, so it
21706            // runs contained (§8.5).
21707            let when =
21708                dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
21709                    .unwrap_or(dispatch2::DispatchTime::FOREVER);
21710            if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
21711                day_spec::ffi_guard::contain((), f);
21712            }) {
21713                log::error!("day-toolkit-uikit: dispatch_after refused a timer: {e:?}");
21714            }
21715        }
21716
21717        fn locale_hints(&self) -> Vec<String> {
21718            // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
21719            // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
21720            objc2_foundation::NSLocale::preferredLanguages()
21721                .iter()
21722                .map(|s| s.to_string())
21723                .collect()
21724        }
21725    }
21726}