Skip to main content

day_toolkit_material/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-material: the android-material backend (DESIGN.md §9). jni + the `DayBridge` Java shim
5//! (java/dev/daybrite/day/bridge/, the Java analogue of the Qt C++ shim; controls are Material 3
6//! components from com.google.android.material, M3 Expressive themed).
7//! `Handle = AHandle(GlobalRef)`. Coordinates: Day works in dp; `set_frame` scales by density to
8//! px and `measure` scales back. The JVM owns the main loop: `Platform::run` hands the
9//! pre-registered root straight to `ready` (the Activity already called `init`).
10
11#![allow(clippy::missing_safety_doc)]
12
13#[cfg(target_os = "android")]
14pub use imp::*;
15
16/// Parity test for the event-kind wire table: the Java shim's `K_*` constants block in
17/// DayBridge.java must mirror `day_spec::bridge::BridgeKind` exactly. Host-runnable (pure
18/// text against the enum, no JNI), so a drifted or colliding kind fails `cargo test` on
19/// any host as well as on a device.
20#[cfg(target_os = "android")]
21mod controls;
22
23#[cfg(test)]
24mod bridge_kinds_parity {
25    #[test]
26    fn java_constants_match_the_rust_enum() {
27        use day_spec::bridge::BridgeKind;
28        let java = include_str!("../java/dev/daybrite/day/bridge/DayBridge.java");
29        let mut found = std::collections::BTreeMap::new();
30        for line in java.lines() {
31            let line = line.trim();
32            if let Some(rest) = line.strip_prefix("public static final int K_")
33                && let Some((name, value)) = rest.split_once(" = ")
34            {
35                let value: i32 = value
36                    .trim_end_matches(';')
37                    .parse()
38                    .unwrap_or_else(|_| panic!("unparsable K_{name} line: {line}"));
39                assert!(
40                    found.insert(format!("K_{name}"), value).is_none(),
41                    "duplicate Java constant K_{name}"
42                );
43            }
44        }
45        let expect = [
46            ("K_PRESSED", BridgeKind::Pressed),
47            ("K_REFRESH_REQUESTED", BridgeKind::RefreshRequested),
48            ("K_TEXT_CHANGED", BridgeKind::TextChanged),
49            ("K_TOGGLE_CHANGED", BridgeKind::ToggleChanged),
50            ("K_VALUE_CHANGED", BridgeKind::ValueChanged),
51            ("K_VALUE_COMMITTED", BridgeKind::ValueCommitted),
52            ("K_SEARCH_CHANGED", BridgeKind::SearchChanged),
53            ("K_NAV_PRESENTATION", BridgeKind::NavPresentation),
54            ("K_SELECTION_CHANGED", BridgeKind::SelectionChanged),
55            ("K_LIST_ACTIVATED", BridgeKind::ListActivated),
56            ("K_NAV_BACK", BridgeKind::NavBack),
57            ("K_FRAME_CHANGED", BridgeKind::FrameChanged),
58            ("K_DEEPLINK", BridgeKind::Deeplink),
59            ("K_DOCUMENT_OPENED", BridgeKind::DocumentOpened),
60            ("K_SHARED_TEXT", BridgeKind::SharedText),
61            ("K_PRESENT_BUTTON", BridgeKind::PresentButton),
62            ("K_PRESENT_TEXT", BridgeKind::PresentText),
63            ("K_PRESENT_DISMISSED", BridgeKind::PresentDismissed),
64            ("K_GESTURE", BridgeKind::Gesture),
65            ("K_CUSTOM", BridgeKind::Custom),
66            ("K_MENU_ACTION", BridgeKind::MenuAction),
67            ("K_LIFECYCLE", BridgeKind::Lifecycle),
68            ("K_PRESENT_FILE", BridgeKind::PresentFile),
69            ("K_FOCUS_CHANGED", BridgeKind::FocusChanged),
70            ("K_SUBMITTED", BridgeKind::Submitted),
71            ("K_WINDOW_RESIZED", BridgeKind::WindowResized),
72            ("K_SAFE_AREA", BridgeKind::SafeArea),
73            // These two were absent from this table while present in DayBridge.java, so the
74            // parity assertion below was failing before the search work touched it.
75            ("K_WINDOW_CLOSED", BridgeKind::WindowClosed),
76            ("K_WINDOW_FOCUSED", BridgeKind::WindowFocused),
77            // Same story again: DayBridge.java gained K_APPEARANCE_CHANGED without this row.
78            ("K_APPEARANCE_CHANGED", BridgeKind::AppearanceChanged),
79            ("K_REDUCE_MOTION_CHANGED", BridgeKind::ReduceMotionChanged),
80            ("K_COVER_HIDDEN", BridgeKind::CoverHidden),
81            ("K_LINK_ACTIVATED", BridgeKind::LinkActivated),
82            ("K_TOOLBAR_CHANGED", BridgeKind::ToolbarChanged),
83            ("K_KEY", BridgeKind::Key),
84            ("K_TEXT", BridgeKind::Text),
85            ("K_WINDOW_STATE_CHANGED", BridgeKind::WindowStateChanged),
86        ];
87        assert_eq!(
88            found.len(),
89            expect.len(),
90            "Java K_* count differs from the enum: {found:?}"
91        );
92        for (name, kind) in expect {
93            assert_eq!(
94                found.get(name).copied(),
95                Some(kind as i32),
96                "{name} drifted from BridgeKind::{kind:?}"
97            );
98        }
99    }
100}
101
102#[cfg(target_os = "android")]
103mod picker;
104#[cfg(target_os = "android")]
105mod textarea;
106
107/// A color as the packed `0xAARRGGBB` the Java shim takes.
108#[cfg(any(target_os = "android", test))]
109fn argb_u32(c: day_spec::Color) -> u32 {
110    let ch = |x: f64| (x.clamp(0.0, 1.0) * 255.0).round() as u32;
111    (ch(c.a) << 24) | (ch(c.r) << 16) | (ch(c.g) << 8) | ch(c.b)
112}
113
114/// Whether a container's props ask for more than a color and one radius: a gradient, a
115/// border, a shadow, or a radius on some corners only (docs/surfaces.md). Those go to
116/// `DayFixed.setSurfaceStyle`; the rest keep the `GradientDrawable` background they always had.
117#[cfg(any(target_os = "android", test))]
118fn is_styled_surface(p: &day_spec::props::ContainerProps) -> bool {
119    p.fill
120        .as_ref()
121        .is_some_and(|f| !matches!(f, day_spec::Paint::Solid(_)))
122        || p.border.is_some()
123        || p.shadow.is_some()
124        || (p.corner_radius > 0.0 && p.corners != day_spec::Corners::ALL)
125}
126
127/// The number of slots in a styled surface spec before its gradient stops.
128#[cfg(any(target_os = "android", test))]
129const SURFACE_HEADER: usize = 18;
130
131/// A styled surface as the numbers `DayFixed.setSurfaceStyle` reads, lengths scaled to px by
132/// `density` and colors packed ARGB: `[0]` has fill, `[1]` fill, `[2..=5]` radii top-left,
133/// top-right, bottom-right, bottom-left, `[6]` border color, `[7]` border width, `[8]` shadow
134/// color (0 for none), `[9]` blur, `[10]` dx, `[11]` dy, then the gradient from `[12]` as
135/// [`gradient_spec`] lays it out. Every ink is resolved against the current palette: a light
136/// or dark switch recreates the activity, and the re-mounted tree resolves again.
137#[cfg(any(target_os = "android", test))]
138fn surface_spec(p: &day_spec::props::ContainerProps, density: f64) -> Vec<f64> {
139    let color = |c: day_spec::Ink| f64::from(argb_u32(c.resolved()));
140    let background = solid_fill(p.fill.as_ref());
141    let radii = p.corners.radii(p.corner_radius.max(0.0) * density);
142    let mut spec = vec![
143        f64::from(u8::from(background.is_some())),
144        background.map_or(0.0, |c| f64::from(argb_u32(c))),
145        radii.top_left,
146        radii.top_right,
147        radii.bottom_right,
148        radii.bottom_left,
149    ];
150    // A border or shadow whose color is fully transparent draws nothing: both ride as "none".
151    let border = p.border.filter(|b| b.width > 0.0);
152    spec.extend([
153        border.map_or(0.0, |b| color(b.color)),
154        border.map_or(0.0, |b| b.width * density),
155    ]);
156    let shadow = p.shadow;
157    spec.extend([
158        shadow.map_or(0.0, |s| color(s.color)),
159        shadow.map_or(0.0, |s| s.blur.max(0.0) * density),
160        shadow.map_or(0.0, |s| s.dx * density),
161        shadow.map_or(0.0, |s| s.dy * density),
162    ]);
163    spec.extend(gradient_spec(p.fill.as_ref()));
164    spec
165}
166
167/// A gradient fill as `DayFixed.setSurfaceGradient` reads it: `[0]` stop count (0 for a solid
168/// fill or none), `[1]` kind (0 linear, 1 radial, 2 conic), `[2..=5]` its geometry in the unit
169/// space of the surface's frame (linear: start and end points; radial: center, radius, 0;
170/// conic: center, start angle in degrees clockwise from +x, 0), then `(offset, color)` per stop
171/// with the colors packed ARGB.
172#[cfg(any(target_os = "android", test))]
173fn gradient_spec(fill: Option<&day_spec::Paint>) -> Vec<f64> {
174    use day_spec::Paint;
175    let (kind, geometry, stops) = match fill {
176        Some(Paint::Linear(g)) => (0.0, [g.start.x, g.start.y, g.end.x, g.end.y], &g.stops),
177        Some(Paint::Radial(g)) => (1.0, [g.center.x, g.center.y, g.radius, 0.0], &g.stops),
178        Some(Paint::Conic(g)) => (
179            2.0,
180            [g.center.x, g.center.y, g.start.degrees(), 0.0],
181            &g.stops,
182        ),
183        Some(Paint::Solid(_)) | None => return vec![0.0; SURFACE_HEADER - 12],
184    };
185    if stops.is_empty() {
186        return vec![0.0; SURFACE_HEADER - 12];
187    }
188    let mut spec = vec![stops.len() as f64, kind];
189    spec.extend(geometry);
190    for (offset, c) in day_spec::resolved_stops(stops) {
191        spec.extend([offset.clamp(0.0, 1.0), f64::from(argb_u32(c))]);
192    }
193    spec
194}
195
196/// The solid color of a container's fill, resolved against the current palette; `None` for
197/// no fill and for a gradient, which [`gradient_spec`] carries.
198#[cfg(any(target_os = "android", test))]
199fn solid_fill(fill: Option<&day_spec::Paint>) -> Option<day_spec::Color> {
200    match fill {
201        Some(day_spec::Paint::Solid(ink)) => Some(ink.resolved()),
202        _ => None,
203    }
204}
205
206#[cfg(test)]
207mod surface_spec_tests {
208    use super::{is_styled_surface, surface_spec};
209    use day_spec::props::ContainerProps;
210    use day_spec::{
211        Angle, Border, Color, ConicGradient, Corners, LinearGradient, RadialGradient, Shadow,
212        UnitPoint,
213    };
214
215    #[test]
216    fn plain_surfaces_keep_the_drawable_path() {
217        let plain = ContainerProps {
218            fill: Some(Color::rgb(1.0, 0.0, 0.0).into()),
219            corner_radius: 8.0,
220            clips: true,
221            ..Default::default()
222        };
223        assert!(!is_styled_surface(&plain));
224        // Named corners with no radius round nothing, so they are plain too.
225        let square = ContainerProps {
226            corners: Corners::TOP,
227            ..Default::default()
228        };
229        assert!(!is_styled_surface(&square));
230        for styled in [
231            ContainerProps {
232                corner_radius: 8.0,
233                corners: Corners::TOP,
234                ..Default::default()
235            },
236            ContainerProps {
237                border: Some(Border::new(Color::rgb(0.0, 0.0, 0.0), 1.0)),
238                ..Default::default()
239            },
240            ContainerProps {
241                shadow: Some(Shadow::new(Color::rgb(0.0, 0.0, 0.0), 4.0)),
242                ..Default::default()
243            },
244            ContainerProps {
245                fill: Some(
246                    LinearGradient::vertical(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0))
247                        .into(),
248                ),
249                ..Default::default()
250            },
251        ] {
252            assert!(is_styled_surface(&styled), "{styled:?}");
253        }
254    }
255
256    #[test]
257    fn lengths_scale_and_corners_select() {
258        let p = ContainerProps {
259            fill: Some(Color::rgba(0.0, 0.0, 1.0, 1.0).into()),
260            corner_radius: 10.0,
261            corners: Corners::TOP_LEFT | Corners::BOTTOM_RIGHT,
262            border: Some(Border::new(Color::rgb(1.0, 0.0, 0.0), 2.0)),
263            shadow: Some(Shadow::new(Color::rgba(0.0, 0.0, 0.0, 0.5), 4.0).offset(1.0, -3.0)),
264            ..Default::default()
265        };
266        let spec = surface_spec(&p, 2.0);
267        assert_eq!(spec.len(), super::SURFACE_HEADER);
268        assert_eq!(spec[0], 1.0);
269        assert_eq!(spec[1], f64::from(0xFF00_00FF_u32));
270        assert_eq!(&spec[2..6], &[20.0, 0.0, 20.0, 0.0]);
271        assert_eq!(spec[6], f64::from(0xFFFF_0000_u32));
272        assert_eq!(spec[7], 4.0);
273        assert_eq!(spec[8], f64::from(0x8000_0000_u32));
274        assert_eq!(&spec[9..12], &[8.0, 2.0, -6.0]);
275        assert_eq!(spec[12], 0.0);
276    }
277
278    #[test]
279    fn gradient_stops_follow_the_header() {
280        let p = ContainerProps {
281            fill: Some(
282                LinearGradient::vertical(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0))
283                    .into(),
284            ),
285            // A zero-width border is no border.
286            border: Some(Border::new(Color::rgb(1.0, 0.0, 0.0), 0.0)),
287            ..Default::default()
288        };
289        let spec = surface_spec(&p, 3.0);
290        assert_eq!(spec[0], 0.0);
291        assert_eq!(&spec[6..8], &[0.0, 0.0]);
292        assert_eq!(spec[8], 0.0);
293        assert_eq!(&spec[12..14], &[2.0, 0.0]);
294        // Unit points are not lengths: the density leaves them alone.
295        assert_eq!(&spec[14..18], &[0.5, 0.0, 0.5, 1.0]);
296        assert_eq!(
297            &spec[18..],
298            &[
299                0.0,
300                f64::from(0xFFFF_0000_u32),
301                1.0,
302                f64::from(0xFF00_00FF_u32)
303            ]
304        );
305    }
306
307    #[test]
308    fn radial_and_conic_fills_carry_their_geometry() {
309        let radial = ContainerProps {
310            fill: Some(
311                RadialGradient::new(
312                    UnitPoint::new(0.25, 0.75),
313                    0.5,
314                    [
315                        (0.0, Color::rgb(1.0, 0.0, 0.0)),
316                        (1.0, Color::rgb(0.0, 0.0, 1.0)),
317                    ],
318                )
319                .into(),
320            ),
321            ..Default::default()
322        };
323        assert!(is_styled_surface(&radial));
324        let spec = surface_spec(&radial, 2.0);
325        assert_eq!(&spec[12..18], &[2.0, 1.0, 0.25, 0.75, 0.5, 0.0]);
326        let conic = ContainerProps {
327            fill: Some(
328                ConicGradient::centered(
329                    Angle::rad(std::f64::consts::FRAC_PI_2),
330                    [
331                        (0.0, Color::rgb(1.0, 0.0, 0.0)),
332                        (1.0, Color::rgb(0.0, 0.0, 1.0)),
333                    ],
334                )
335                .into(),
336            ),
337            ..Default::default()
338        };
339        assert!(is_styled_surface(&conic));
340        let spec = surface_spec(&conic, 2.0);
341        assert_eq!(&spec[12..14], &[2.0, 2.0]);
342        assert_eq!(&spec[14..16], &[0.5, 0.5]);
343        assert!((spec[16] - 90.0).abs() < 1e-9);
344        assert_eq!(spec.len(), super::SURFACE_HEADER + 4);
345    }
346
347    #[test]
348    fn inks_resolve_against_the_current_palette() {
349        use day_spec::{Ink, Palette};
350        let pair = Ink::adaptive(Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
351        let p = ContainerProps {
352            fill: Some(pair.into()),
353            border: Some(Border::new(pair, 1.0)),
354            ..Default::default()
355        };
356        Palette::set_current(Palette::fallback(true));
357        let dark = surface_spec(&p, 1.0);
358        Palette::set_current(Palette::fallback(false));
359        let light = surface_spec(&p, 1.0);
360        assert_eq!(dark[1], f64::from(0xFF00_00FF_u32));
361        assert_eq!(dark[6], f64::from(0xFF00_00FF_u32));
362        assert_eq!(light[1], f64::from(0xFFFF_0000_u32));
363        assert_eq!(light[6], f64::from(0xFFFF_0000_u32));
364    }
365}
366
367/// The `BridgeKind::Gesture` codes this backend sends besides the shared
368/// [`day_spec::bridge::gesture`] ones (4 to 11): a tap and a drag's phases below them, and this
369/// toolkit's own pinch, rotation, wheel pan and hover above them. DayBridge.java's `G_*`
370/// constants mirror these; `gesture_codes_parity` holds the two files together.
371#[cfg(any(target_os = "android", test))]
372mod gesture_wire {
373    pub const TAP: i32 = 0;
374    pub const DRAG_BEGAN: i32 = 1;
375    pub const DRAG_CHANGED: i32 = 2;
376    pub const DRAG_ENDED: i32 = 3;
377    pub const ROTATE_BEGAN: i32 = 13;
378    pub const ROTATE_CHANGED: i32 = 14;
379    pub const ROTATE_ENDED: i32 = 15;
380    pub const PINCH_BEGAN: i32 = 16;
381    pub const PINCH_CHANGED: i32 = 17;
382    pub const PINCH_ENDED: i32 = 18;
383    pub const PAN: i32 = 19;
384    pub const HOVER_BEGAN: i32 = 20;
385    pub const HOVER_CHANGED: i32 = 21;
386    pub const HOVER_ENDED: i32 = 22;
387}
388
389/// One `K_GESTURE` report as the event it stands for (docs/gestures.md): `code` is the gesture
390/// code, `text` its payload in px, `density` px per point. The pointer kind is the one report
391/// that names no node: the caller sends it to the window. `None` for an unknown code or a
392/// payload that does not parse.
393#[cfg(any(target_os = "android", test))]
394fn gesture_event(code: i32, text: &str, density: f64) -> Option<day_spec::Event> {
395    use day_spec::bridge::gesture as shared;
396    use day_spec::{DragPhase, Event, GestureKind, Point, PointerKind};
397    use gesture_wire as own;
398    match code {
399        shared::POINTER_KIND => return PointerKind::from_name(text).map(Event::PointerKindChanged),
400        shared::TOUCHES => return touches(text, density).map(Event::Touches),
401        _ => {}
402    }
403    let p: Vec<f64> = text
404        .split(',')
405        .filter_map(|s| s.trim().parse().ok())
406        .collect();
407    if p.len() < 2 {
408        return None;
409    }
410    let at = Point::new(p[0] / density, p[1] / density);
411    match code {
412        shared::LONG_PRESS => return Some(Event::LongPress(at)),
413        shared::DOUBLE_TAP => return Some(Event::DoubleTap(at)),
414        shared::PRESS_IN | shared::PRESS_OUT => {
415            return Some(Event::Press {
416                pressed: code == shared::PRESS_IN,
417                location: at,
418            });
419        }
420        // The platform recognizer's release velocity, px per second: just before `Ended`.
421        shared::DRAG_VELOCITY | shared::PAN_VELOCITY => {
422            let kind = if code == shared::DRAG_VELOCITY {
423                GestureKind::Drag
424            } else {
425                GestureKind::Pan
426            };
427            return Some(Event::GestureVelocity { kind, velocity: at });
428        }
429        _ => {}
430    }
431    if p.len() < 4 {
432        return None;
433    }
434    let tr = Point::new(p[2] / density, p[3] / density);
435    let phase = |began, ended| {
436        if code == began {
437            DragPhase::Began
438        } else if code == ended {
439            DragPhase::Ended
440        } else {
441            DragPhase::Changed
442        }
443    };
444    Some(match code {
445        own::TAP => Event::Tap(at),
446        // A drag's Began carries the translation already applied: a drag along an axis begins
447        // once its movement has shown the direction (docs/gestures.md "Velocity").
448        own::DRAG_BEGAN | own::DRAG_CHANGED | own::DRAG_ENDED => Event::Drag {
449            phase: phase(own::DRAG_BEGAN, own::DRAG_ENDED),
450            location: at,
451            translation: tr,
452        },
453        // Pinch (docs/canvas.md "Zoom and pan"): the ScaleGestureDetector's focus and its span
454        // relative to the span at Began, a cumulative scale.
455        own::PINCH_BEGAN | own::PINCH_CHANGED | own::PINCH_ENDED => Event::Pinch {
456            phase: phase(own::PINCH_BEGAN, own::PINCH_ENDED),
457            scale: p[2],
458            location: at,
459        },
460        // Rotation: the angle the line between the first two fingers turned since the second
461        // went down, cumulative radians, clockwise positive on the y-down screen.
462        own::ROTATE_BEGAN | own::ROTATE_CHANGED | own::ROTATE_ENDED => Event::Rotate {
463            phase: phase(own::ROTATE_BEGAN, own::ROTATE_ENDED),
464            rotation: p[2],
465            location: at,
466        },
467        own::PAN => Event::Pan {
468            phase: DragPhase::Changed,
469            location: at,
470            delta: tr,
471        },
472        // Hover (docs/canvas.md "Interaction"): a mouse or a stylus over the view. A finger
473        // produces none: Android's hover events come from MotionEvent's HOVER_* actions only.
474        own::HOVER_BEGAN | own::HOVER_CHANGED | own::HOVER_ENDED => Event::Hover {
475            phase: phase(own::HOVER_BEGAN, own::HOVER_ENDED),
476            location: at,
477        },
478        _ => return None,
479    })
480}
481
482/// A touch report (`"id,phase,x,y,pressure,kind"` per contact, joined by `;`, px) as the
483/// contacts it lists, in points. `None` when no contact parses.
484#[cfg(any(target_os = "android", test))]
485fn touches(text: &str, density: f64) -> Option<Vec<day_spec::Touch>> {
486    use day_spec::{Point, PointerKind, Touch, TouchPhase};
487    let list: Vec<Touch> = text
488        .split(';')
489        .filter_map(|contact| {
490            let f: Vec<f64> = contact
491                .split(',')
492                .map(|s| s.trim().parse().ok())
493                .collect::<Option<_>>()?;
494            let [id, phase, x, y, pressure, kind] = f[..] else {
495                return None;
496            };
497            let phase = match phase as i32 {
498                0 => TouchPhase::Began,
499                1 => TouchPhase::Moved,
500                2 => TouchPhase::Stationary,
501                3 => TouchPhase::Ended,
502                _ => TouchPhase::Cancelled,
503            };
504            let kind = match kind as i32 {
505                1 => PointerKind::Mouse,
506                2 => PointerKind::Stylus,
507                _ => PointerKind::Touch,
508            };
509            Some(
510                Touch::new(
511                    id.max(0.0) as u64,
512                    phase,
513                    Point::new(x / density, y / density),
514                )
515                .with_pressure(pressure)
516                .with_kind(kind),
517            )
518        })
519        .collect();
520    (!list.is_empty()).then_some(list)
521}
522
523/// A key report (`K_KEY`, or `K_TEXT` when `typed`) as its event: `num` holds the modifier
524/// mask in its low byte and the phase in bits 8 and 9 (docs/menus.md "Keys").
525#[cfg(any(target_os = "android", test))]
526fn key_event(typed: bool, name: String, num: f64) -> day_spec::KeyEvent {
527    let mods = ((num as u32) & 0xff) as u8;
528    let event = if typed {
529        day_spec::KeyEvent::typed_text(name, mods)
530    } else {
531        day_spec::KeyEvent::named(name, mods)
532    };
533    event.with_phase(day_spec::KeyPhase::from_wire(num))
534}
535
536#[cfg(test)]
537mod input_wire_tests {
538    use super::{gesture_event, gesture_wire, key_event};
539    use day_spec::bridge::gesture;
540    use day_spec::{
541        DragPhase, Event, GestureKind, Key, KeyPhase, Modifiers, Point, PointerKind, TouchPhase,
542    };
543
544    /// DayBridge.java's `G_*` constants are this file's codes, the shared and the own ones.
545    #[test]
546    fn gesture_codes_parity() {
547        let java = include_str!("../java/dev/daybrite/day/bridge/DayBridge.java");
548        let mut found = std::collections::BTreeMap::new();
549        for line in java.lines() {
550            if let Some(rest) = line.trim().strip_prefix("static final int G_")
551                && let Some((name, value)) = rest.split_once(" = ")
552            {
553                let value: i32 = value.trim_end_matches(';').parse().expect("a number");
554                assert!(
555                    found.insert(name.to_owned(), value).is_none(),
556                    "G_{name} twice"
557                );
558            }
559        }
560        let expect = [
561            ("TAP", gesture_wire::TAP),
562            ("DRAG_BEGAN", gesture_wire::DRAG_BEGAN),
563            ("DRAG_CHANGED", gesture_wire::DRAG_CHANGED),
564            ("DRAG_ENDED", gesture_wire::DRAG_ENDED),
565            ("LONG_PRESS", gesture::LONG_PRESS),
566            ("DOUBLE_TAP", gesture::DOUBLE_TAP),
567            ("PRESS_IN", gesture::PRESS_IN),
568            ("PRESS_OUT", gesture::PRESS_OUT),
569            ("TOUCHES", gesture::TOUCHES),
570            ("DRAG_VELOCITY", gesture::DRAG_VELOCITY),
571            ("POINTER_KIND", gesture::POINTER_KIND),
572            ("ROTATE_BEGAN", gesture_wire::ROTATE_BEGAN),
573            ("ROTATE_CHANGED", gesture_wire::ROTATE_CHANGED),
574            ("ROTATE_ENDED", gesture_wire::ROTATE_ENDED),
575            ("PINCH_BEGAN", gesture_wire::PINCH_BEGAN),
576            ("PINCH_CHANGED", gesture_wire::PINCH_CHANGED),
577            ("PINCH_ENDED", gesture_wire::PINCH_ENDED),
578            ("PAN", gesture_wire::PAN),
579            ("HOVER_BEGAN", gesture_wire::HOVER_BEGAN),
580            ("HOVER_CHANGED", gesture_wire::HOVER_CHANGED),
581            ("HOVER_ENDED", gesture_wire::HOVER_ENDED),
582        ];
583        assert_eq!(found.len(), expect.len(), "{found:?}");
584        let mut codes = std::collections::BTreeSet::new();
585        for (name, code) in expect {
586            assert_eq!(found.get(name), Some(&code), "G_{name}");
587            assert!(codes.insert(code), "G_{name} collides with another code");
588        }
589        // The shared codes this backend never sends still must not collide with its own.
590        assert!(!codes.contains(&gesture::PAN_VELOCITY));
591    }
592
593    fn p(x: f64, y: f64) -> Point {
594        Point::new(x, y)
595    }
596
597    #[test]
598    fn shared_gestures_decode_in_points() {
599        let d = 2.0;
600        assert_eq!(
601            gesture_event(gesture::LONG_PRESS, "20,40", d),
602            Some(Event::LongPress(p(10.0, 20.0)))
603        );
604        assert_eq!(
605            gesture_event(gesture::DOUBLE_TAP, "2,4", d),
606            Some(Event::DoubleTap(p(1.0, 2.0)))
607        );
608        assert_eq!(
609            gesture_event(gesture::PRESS_IN, "2,4", d),
610            Some(Event::Press {
611                pressed: true,
612                location: p(1.0, 2.0)
613            })
614        );
615        assert_eq!(
616            gesture_event(gesture::PRESS_OUT, "-2,4", d),
617            Some(Event::Press {
618                pressed: false,
619                location: p(-1.0, 2.0)
620            })
621        );
622        assert_eq!(
623            gesture_event(gesture::DRAG_VELOCITY, "1200,-1600", d),
624            Some(Event::GestureVelocity {
625                kind: GestureKind::Drag,
626                velocity: p(600.0, -800.0)
627            })
628        );
629        assert_eq!(
630            gesture_event(gesture::POINTER_KIND, "stylus", d),
631            Some(Event::PointerKindChanged(PointerKind::Stylus))
632        );
633        assert_eq!(gesture_event(gesture::POINTER_KIND, "pen", d), None);
634        assert_eq!(gesture_event(gesture::LONG_PRESS, "2", d), None);
635    }
636
637    #[test]
638    fn own_gestures_keep_their_meaning() {
639        let d = 2.0;
640        assert_eq!(
641            gesture_event(gesture_wire::TAP, "4,6,0,0", d),
642            Some(Event::Tap(p(2.0, 3.0)))
643        );
644        // A Began after movement (an axis drag) keeps its translation.
645        assert_eq!(
646            gesture_event(gesture_wire::DRAG_BEGAN, "30,10,20,2", d),
647            Some(Event::Drag {
648                phase: DragPhase::Began,
649                location: p(15.0, 5.0),
650                translation: p(10.0, 1.0)
651            })
652        );
653        assert!(matches!(
654            gesture_event(gesture_wire::DRAG_CHANGED, "0,0,2,2", d),
655            Some(Event::Drag {
656                phase: DragPhase::Changed,
657                ..
658            })
659        ));
660        assert_eq!(
661            gesture_event(gesture_wire::PINCH_ENDED, "10,10,1.5,0", d),
662            Some(Event::Pinch {
663                phase: DragPhase::Ended,
664                scale: 1.5,
665                location: p(5.0, 5.0)
666            })
667        );
668        assert_eq!(
669            gesture_event(gesture_wire::ROTATE_BEGAN, "10,10,0,0", d),
670            Some(Event::Rotate {
671                phase: DragPhase::Began,
672                rotation: 0.0,
673                location: p(5.0, 5.0)
674            })
675        );
676        assert_eq!(
677            gesture_event(gesture_wire::PAN, "0,0,8,-4", d),
678            Some(Event::Pan {
679                phase: DragPhase::Changed,
680                location: p(0.0, 0.0),
681                delta: p(4.0, -2.0)
682            })
683        );
684        assert_eq!(
685            gesture_event(gesture_wire::HOVER_ENDED, "2,2,0,0", d),
686            Some(Event::Hover {
687                phase: DragPhase::Ended,
688                location: p(1.0, 1.0)
689            })
690        );
691        assert_eq!(gesture_event(12, "0,0,0,0", d), None);
692    }
693
694    #[test]
695    fn touches_list_every_contact() {
696        let Some(Event::Touches(list)) =
697            gesture_event(gesture::TOUCHES, "0,2,10,20,1,0;3,3,40,60,0.5,2", 2.0)
698        else {
699            panic!("a touch list");
700        };
701        assert_eq!(list.len(), 2);
702        assert_eq!((list[0].id, list[0].phase), (0, TouchPhase::Stationary));
703        assert_eq!(list[0].location, p(5.0, 10.0));
704        assert_eq!(list[0].kind, PointerKind::Touch);
705        assert_eq!((list[1].id, list[1].phase), (3, TouchPhase::Ended));
706        assert!(!list[1].is_down());
707        assert!((list[1].pressure - 0.5).abs() < f64::EPSILON);
708        assert_eq!(list[1].kind, PointerKind::Stylus);
709        assert_eq!(gesture_event(gesture::TOUCHES, "", 2.0), None);
710        assert_eq!(gesture_event(gesture::TOUCHES, "1,2,3", 2.0), None);
711    }
712
713    #[test]
714    fn key_phases_ride_above_the_modifiers() {
715        let shift = f64::from(Modifiers::SHIFT.bits());
716        let down = key_event(false, "ArrowRight".into(), shift);
717        assert_eq!(down.key, Key::ArrowRight);
718        assert_eq!(down.phase, KeyPhase::Down);
719        assert!(down.modifiers.shift());
720        let repeat = key_event(true, "a".into(), 256.0 + shift);
721        assert_eq!(repeat.phase, KeyPhase::Repeat);
722        assert_eq!(repeat.text.as_deref(), Some("a"));
723        assert!(repeat.modifiers.shift());
724        let up = key_event(false, "5".into(), 512.0);
725        assert_eq!(up.phase, KeyPhase::Up);
726        assert_eq!(up.modifiers, Modifiers::NONE);
727        assert_eq!(up.text, None);
728    }
729}
730
731/// The label wire shared with `DayBridge.setLabelRuns` / `DayLabel` (docs/text-runs.md): the
732/// per-run flag bits, the custom-drawn decoration entries, and the selection report.
733#[cfg(any(target_os = "android", test))]
734mod text_wire {
735    use day_spec::props::{TextAlign, Truncation};
736    use day_spec::{Decoration, DecorationStyle, FontSpec, TextRun};
737
738    /// `flags[i]` bits read by `DayBridge.setLabelRuns`.
739    pub const BOLD: i32 = 1;
740    pub const ITALIC: i32 = 2;
741    pub const MONOSPACE: i32 = 4;
742    /// A single strikethrough in the text color: the native `StrikethroughSpan`.
743    pub const STRIKE: i32 = 8;
744    pub const COLOR: i32 = 16;
745    pub const BACKGROUND: i32 = 32;
746    /// A single underline in the text color: the native `UnderlineSpan`.
747    pub const UNDERLINE: i32 = 64;
748    pub const SMALL_CAPS: i32 = 1024;
749    pub const OLDSTYLE: i32 = 2048;
750    pub const TABULAR: i32 = 4096;
751
752    /// `DayLabel.DECO_*`: five ints per custom-drawn line (start, end, info, color, size per
753    /// mille); the info word is bit 0 strikethrough, bits 1-2 the style, bit 3 an own color.
754    pub const DECO_STRIDE: usize = 5;
755    const DECO_STRIKE: i32 = 1;
756    const DECO_COLORED: i32 = 8;
757
758    /// The prefix of the selection report `DayLabel` sends through the custom channel.
759    pub const SELECTION_PREFIX: &str = "day:text-selected:";
760
761    /// The flag word for one run: the styles that ride a native span.
762    pub fn run_flags(r: &TextRun) -> i32 {
763        let mut f = 0;
764        if r.font
765            .weight
766            .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
767        {
768            f |= BOLD;
769        }
770        if r.font.italic {
771            f |= ITALIC;
772        }
773        if r.font.monospace {
774            f |= MONOSPACE;
775        }
776        if r.strikethrough.is_some_and(|d| natively_drawn(&d)) {
777            f |= STRIKE;
778        }
779        if r.color.is_some() {
780            f |= COLOR;
781        }
782        if r.background.is_some() {
783            f |= BACKGROUND;
784        }
785        if r.underline.is_some_and(|d| natively_drawn(&d)) {
786            f |= UNDERLINE;
787        }
788        if r.font.small_caps {
789            f |= SMALL_CAPS;
790        }
791        if r.font.oldstyle_figures {
792            f |= OLDSTYLE;
793        }
794        if r.font.tabular {
795            f |= TABULAR;
796        }
797        f
798    }
799
800    /// Whether Android's own span draws this line: a single line in the text color.
801    fn natively_drawn(d: &Decoration) -> bool {
802        d.style == DecorationStyle::Single && d.color.is_none()
803    }
804
805    /// The custom-drawn decoration entries of one run spanning UTF-16 `start..end`: the lines
806    /// Android has no span for (a double, dotted or wavy line, or one in its own color).
807    pub fn decoration_entries(r: &TextRun, start: i32, end: i32, out: &mut Vec<i32>) {
808        let scale = (r.font.scale * 1000.0).round() as i32;
809        for (deco, strike) in [(r.underline, false), (r.strikethrough, true)] {
810            let Some(d) = deco else { continue };
811            if natively_drawn(&d) {
812                continue;
813            }
814            let style = match d.style {
815                DecorationStyle::Single => 0,
816                DecorationStyle::Double => 1,
817                DecorationStyle::Dotted => 2,
818                DecorationStyle::Wavy => 3,
819            };
820            // No own color: the line takes the run's text color, which is the label's when
821            // the run has none (DayLabel reads it at draw time, so it follows the theme).
822            let color = d.color.or(r.color);
823            let mut info = style << 1;
824            if strike {
825                info |= DECO_STRIKE;
826            }
827            if color.is_some() {
828                info |= DECO_COLORED;
829            }
830            let entry: [i32; DECO_STRIDE] = [
831                start,
832                end,
833                info,
834                color.map_or(0, |c| super::argb_u32(c.resolved()) as i32),
835                scale,
836            ];
837            out.extend_from_slice(&entry);
838        }
839    }
840
841    /// `FontSpec::feature_tags` as Android's `setFontFeatureSettings` string (`None` for none).
842    pub fn features(spec: &FontSpec) -> Option<String> {
843        let tags = spec.feature_tags();
844        (!tags.is_empty()).then(|| tags.join(","))
845    }
846
847    /// `DayLabel.TRUNCATE_*`.
848    pub fn truncation_code(t: Truncation) -> i32 {
849        match t {
850            Truncation::Tail => 0,
851            Truncation::Head => 1,
852            Truncation::Middle => 2,
853        }
854    }
855
856    /// `DayBridge.setLabelAlignment`'s code; 0 (leading) needs no call.
857    pub fn align_code(a: TextAlign) -> i32 {
858        match a {
859            TextAlign::Leading => 0,
860            TextAlign::Center => 1,
861            TextAlign::Trailing => 2,
862            TextAlign::Justified => 3,
863        }
864    }
865
866    /// A paragraph value as `setLabelParagraph` takes it: nonpositive or nonfinite spacing
867    /// and height mean the font's own.
868    pub fn paragraph_args(p: &day_spec::props::LabelParagraph) -> (i32, i32, f32, f32) {
869        let finite = |v: f64, positive: bool| {
870            if !v.is_finite() || (positive && v <= 0.0) {
871                0.0
872            } else {
873                v as f32
874            }
875        };
876        (
877            p.max_lines.min(i32::MAX as u32) as i32,
878            truncation_code(p.truncation),
879            finite(p.letter_spacing, false),
880            finite(p.line_height, true),
881        )
882    }
883
884    /// A selection report's payload (after [`SELECTION_PREFIX`]) as byte offsets, `start <=
885    /// end`. `None` when it does not parse.
886    pub fn selection(payload: &str) -> Option<(usize, usize)> {
887        let (a, b) = payload.split_once(',')?;
888        let (a, b): (usize, usize) = (a.trim().parse().ok()?, b.trim().parse().ok()?);
889        Some((a.min(b), a.max(b)))
890    }
891}
892
893#[cfg(test)]
894mod text_wire_tests {
895    use super::text_wire::{
896        DECO_STRIDE, OLDSTYLE, SMALL_CAPS, STRIKE, TABULAR, UNDERLINE, align_code,
897        decoration_entries, features, paragraph_args, run_flags, selection,
898    };
899    use day_spec::props::{LabelParagraph, TextAlign, Truncation};
900    use day_spec::{Color, Decoration, DecorationStyle, FontSpec, TextRun};
901
902    fn run(underline: Option<Decoration>, strikethrough: Option<Decoration>) -> TextRun {
903        TextRun {
904            range: 0..3,
905            underline,
906            strikethrough,
907            ..TextRun::default()
908        }
909    }
910
911    #[test]
912    fn plain_lines_stay_native_spans() {
913        let r = run(Some(Decoration::SINGLE), Some(Decoration::SINGLE));
914        assert_eq!(run_flags(&r) & (UNDERLINE | STRIKE), UNDERLINE | STRIKE);
915        let mut out = Vec::new();
916        decoration_entries(&r, 0, 3, &mut out);
917        assert_eq!(out, Vec::<i32>::new());
918    }
919
920    /// DayLabel.java reads the same wire: the decoration stride, the selection prefix and the
921    /// feature flag bits.
922    #[test]
923    fn java_side_parity() {
924        let label = include_str!("../java/dev/daybrite/day/bridge/DayLabel.java");
925        assert!(label.contains(&format!("DECO_STRIDE = {DECO_STRIDE};")));
926        assert!(label.contains(&format!("\"{}\"", super::text_wire::SELECTION_PREFIX)));
927        let bridge = include_str!("../java/dev/daybrite/day/bridge/DayBridge.java");
928        for (bit, tag) in [(TABULAR, "tnum"), (SMALL_CAPS, "smcp"), (OLDSTYLE, "onum")] {
929            assert!(
930                bridge.contains(&format!("(f & {bit}) != 0 ? \"{tag},\"")),
931                "{tag} is bit {bit}"
932            );
933        }
934    }
935
936    #[test]
937    fn styled_and_colored_lines_are_drawn() {
938        let red = Color::hex(0x00D0_021B);
939        let r = run(
940            Some(Decoration::wavy().color(red)),
941            Some(Decoration::from(DecorationStyle::Double)),
942        );
943        assert_eq!(run_flags(&r) & (UNDERLINE | STRIKE), 0);
944        let mut out = Vec::new();
945        decoration_entries(&r, 2, 9, &mut out);
946        assert_eq!(out.len(), 2 * DECO_STRIDE);
947        // The wavy underline: style 3, its own color.
948        assert_eq!(&out[..3], &[2, 9, (3 << 1) | 8]);
949        assert_eq!(out[3], super::argb_u32(red) as i32);
950        assert_eq!(out[4], 1000);
951        // The double strikethrough: style 1, struck, in the text color.
952        assert_eq!(&out[5..8], &[2, 9, (1 << 1) | 1]);
953        // A single line in a color of its own is drawn too.
954        let colored = run(Some(Decoration::SINGLE.color(red)), None);
955        let mut out = Vec::new();
956        decoration_entries(&colored, 0, 3, &mut out);
957        assert_eq!(out[2], 8);
958    }
959
960    #[test]
961    fn features_follow_the_tags() {
962        let mut f = FontSpec::default();
963        assert_eq!(features(&f), None);
964        f.small_caps = true;
965        f.oldstyle_figures = true;
966        f.tabular = true;
967        assert_eq!(features(&f).as_deref(), Some("tnum,smcp,onum"));
968        let r = TextRun {
969            font: f,
970            ..TextRun::default()
971        };
972        assert_eq!(
973            run_flags(&r) & (SMALL_CAPS | OLDSTYLE),
974            SMALL_CAPS | OLDSTYLE
975        );
976    }
977
978    #[test]
979    fn paragraph_and_alignment_codes() {
980        let p = LabelParagraph {
981            max_lines: 2,
982            truncation: Truncation::Middle,
983            letter_spacing: -0.02,
984            line_height: f64::NAN,
985        };
986        assert_eq!(paragraph_args(&p), (2, 2, -0.02, 0.0));
987        let p = LabelParagraph {
988            line_height: -1.0,
989            letter_spacing: f64::INFINITY,
990            ..LabelParagraph::default()
991        };
992        assert_eq!(paragraph_args(&p), (0, 0, 0.0, 0.0));
993        assert_eq!(align_code(TextAlign::Justified), 3);
994        assert_eq!(align_code(TextAlign::Leading), 0);
995    }
996
997    #[test]
998    fn selection_reports_parse() {
999        assert_eq!(selection("3,9"), Some((3, 9)));
1000        assert_eq!(selection("9,3"), Some((3, 9)));
1001        assert_eq!(selection("0,0"), Some((0, 0)));
1002        assert_eq!(selection("x,1"), None);
1003        assert_eq!(selection("4"), None);
1004    }
1005}
1006
1007/// The lists wire shared with `DayBridge` and `DayPager` (docs/list.md, docs/scroll.md,
1008/// docs/pager.md): a splice as `notifyItemRange*` operations, a scroll view's preference
1009/// word, a row scroll's alignment, and the reports that travel back.
1010#[cfg(any(target_os = "android", test))]
1011mod list_wire {
1012    use day_spec::props::ScrollSnap;
1013    use day_spec::props::{KeyboardDismiss, KeyboardTaps, RowDelta, ScrollIndicators, ScrollProps};
1014    use day_spec::{ListViewport, Point, RowAlign, ScrollPhase};
1015
1016    /// `DayBridge.listSplice` operation kinds, each followed by two ints: rows inserted at
1017    /// `a`, `b` of them; rows removed at `a`, `b` of them; one row moved from `a` to `b`.
1018    pub const SPLICE_INSERT: i32 = 0;
1019    pub const SPLICE_REMOVE: i32 = 1;
1020    pub const SPLICE_MOVE: i32 = 2;
1021
1022    /// Day's sequential row deltas as the adapter's range notifications, in order. Runs that
1023    /// stay contiguous fold into one range: an append of 200 rows (200 `Insert(n)`, each above
1024    /// the one before) is one `notifyItemRangeInserted(n, 200)`, and the highest-first removals
1025    /// day-core emits for a block are one `notifyItemRangeRemoved`.
1026    pub fn splice_ops(deltas: &[RowDelta]) -> Vec<i32> {
1027        let mut ops: Vec<i32> = Vec::with_capacity(deltas.len().min(64) * 3);
1028        for delta in deltas {
1029            let n = ops.len();
1030            let last = (n >= 3).then(|| (ops[n - 3], ops[n - 2], ops[n - 1]));
1031            match *delta {
1032                RowDelta::Insert(at) => {
1033                    let at = to_i32(at);
1034                    // A row inserted anywhere inside, or right after, a block just inserted
1035                    // keeps that block contiguous.
1036                    if let Some((SPLICE_INSERT, start, count)) = last
1037                        && (start..=start + count).contains(&at)
1038                    {
1039                        ops[n - 1] += 1;
1040                    } else {
1041                        ops.extend([SPLICE_INSERT, at, 1]);
1042                    }
1043                }
1044                RowDelta::Remove(at) => {
1045                    let at = to_i32(at);
1046                    match last {
1047                        // The row now at the block's start was right after it.
1048                        Some((SPLICE_REMOVE, start, _)) if at == start => ops[n - 1] += 1,
1049                        // The row right before the block.
1050                        Some((SPLICE_REMOVE, start, _)) if at + 1 == start => {
1051                            ops[n - 2] = at;
1052                            ops[n - 1] += 1;
1053                        }
1054                        _ => ops.extend([SPLICE_REMOVE, at, 1]),
1055                    }
1056                }
1057                RowDelta::Move(from, to) if from != to => {
1058                    ops.extend([SPLICE_MOVE, to_i32(from), to_i32(to)]);
1059                }
1060                RowDelta::Move(..) => {}
1061            }
1062        }
1063        ops
1064    }
1065
1066    fn to_i32(n: usize) -> i32 {
1067        i32::try_from(n).unwrap_or(i32::MAX)
1068    }
1069
1070    /// `DayBridge.makeScroll` preference bits (docs/scroll.md).
1071    pub const SCROLL_HIDE_INDICATORS: i32 = 1;
1072    pub const SCROLL_BOUNCE_NEVER: i32 = 2;
1073    pub const SCROLL_BOUNCE_ALWAYS: i32 = 4;
1074    pub const SCROLL_SNAP_PAGE: i32 = 8;
1075    pub const SCROLL_SNAP_INTERVAL: i32 = 16;
1076    pub const SCROLL_KEYBOARD_DRAG: i32 = 32;
1077    pub const SCROLL_KEYBOARD_TAPS: i32 = 64;
1078    pub const SCROLL_TRACK_OFFSET: i32 = 128;
1079    pub const SCROLL_TRACK_PHASE: i32 = 256;
1080
1081    /// A scroll view's preference word and its snap interval in px (0 without one), unrounded
1082    /// so that the stops do not drift from multiples of the interval in points.
1083    pub fn scroll_flags(p: &ScrollProps, density: f64) -> (i32, f32) {
1084        let mut f = 0;
1085        if p.indicators == ScrollIndicators::Hidden {
1086            f |= SCROLL_HIDE_INDICATORS;
1087        }
1088        match p.bounce {
1089            Some(false) => f |= SCROLL_BOUNCE_NEVER,
1090            Some(true) => f |= SCROLL_BOUNCE_ALWAYS,
1091            None => {}
1092        }
1093        let mut interval = 0.0;
1094        match p.snap {
1095            ScrollSnap::Page => f |= SCROLL_SNAP_PAGE,
1096            ScrollSnap::Interval(points) if points.is_finite() && points > 0.0 => {
1097                let px = points * density;
1098                if px >= 1.0 {
1099                    f |= SCROLL_SNAP_INTERVAL;
1100                    interval = px.min(f64::from(f32::MAX)) as f32;
1101                }
1102            }
1103            ScrollSnap::Interval(_) | ScrollSnap::None => {}
1104        }
1105        if p.keyboard_dismiss != KeyboardDismiss::Never {
1106            f |= SCROLL_KEYBOARD_DRAG;
1107        }
1108        if p.keyboard_taps == KeyboardTaps::Dismiss {
1109            f |= SCROLL_KEYBOARD_TAPS;
1110        }
1111        if p.track_offset {
1112            f |= SCROLL_TRACK_OFFSET;
1113        }
1114        if p.track_phase {
1115            f |= SCROLL_TRACK_PHASE;
1116        }
1117        (f, interval)
1118    }
1119
1120    /// `DayBridge.listScroll`'s alignment code.
1121    pub fn align_code(align: RowAlign) -> i32 {
1122        match align {
1123            RowAlign::Nearest => 0,
1124            RowAlign::Start => 1,
1125            RowAlign::Center => 2,
1126            RowAlign::End => 3,
1127        }
1128    }
1129
1130    /// One viewport report from `DayListView` (rows, and the distance to the content's end in
1131    /// px) for a list of `len` rows, clamped to the contract: no report without rows, `last`
1132    /// never before `first`, the distance never negative.
1133    pub fn viewport(
1134        first: i32,
1135        last: i32,
1136        end_px: i32,
1137        density: f64,
1138        len: usize,
1139    ) -> Option<ListViewport> {
1140        if len == 0 || first < 0 || density <= 0.0 {
1141            return None;
1142        }
1143        let first = (first as usize).min(len - 1);
1144        let last = usize::try_from(last)
1145            .map_or(first, |l| l.min(len - 1))
1146            .max(first);
1147        Some(ListViewport {
1148            first,
1149            last,
1150            end_distance: f64::from(end_px.max(0)) / density,
1151        })
1152    }
1153
1154    /// The prefix of a scroll view's offset report on the custom channel: `"x,y"` in px.
1155    pub const OFFSET_PREFIX: &str = "day:scroll:";
1156    /// The prefix of a scroll view's phase report: `0` idle, `1` dragging, `2` coasting.
1157    pub const PHASE_PREFIX: &str = "day:scroll-phase:";
1158
1159    /// An offset report's point, in points.
1160    pub fn offset(payload: &str, density: f64) -> Option<Point> {
1161        let (x, y) = payload.split_once(',')?;
1162        let (x, y) = (x.trim().parse::<f64>().ok()?, y.trim().parse::<f64>().ok()?);
1163        (density > 0.0).then(|| Point::new(x / density, y / density))
1164    }
1165
1166    /// A phase report's phase.
1167    pub fn phase(payload: &str) -> Option<ScrollPhase> {
1168        match payload.trim() {
1169            "0" => Some(ScrollPhase::Idle),
1170            "1" => Some(ScrollPhase::Dragging),
1171            "2" => Some(ScrollPhase::Coasting),
1172            _ => None,
1173        }
1174    }
1175}
1176
1177#[cfg(test)]
1178mod list_wire_tests {
1179    use super::list_wire::{
1180        OFFSET_PREFIX, PHASE_PREFIX, SCROLL_BOUNCE_ALWAYS, SCROLL_BOUNCE_NEVER,
1181        SCROLL_HIDE_INDICATORS, SCROLL_KEYBOARD_DRAG, SCROLL_KEYBOARD_TAPS, SCROLL_SNAP_INTERVAL,
1182        SCROLL_SNAP_PAGE, SCROLL_TRACK_OFFSET, SCROLL_TRACK_PHASE, SPLICE_INSERT, SPLICE_MOVE,
1183        SPLICE_REMOVE, align_code, offset, phase, scroll_flags, splice_ops, viewport,
1184    };
1185    use day_spec::props::{
1186        KeyboardDismiss, KeyboardTaps, RowDelta, ScrollIndicators, ScrollProps, ScrollSnap,
1187    };
1188    use day_spec::{Point, RowAlign, ScrollPhase};
1189
1190    /// Replays sequential deltas on a list of row ids; a fresh row is `100 + n`.
1191    fn replay_deltas(rows: &mut Vec<u32>, deltas: &[RowDelta]) {
1192        let mut fresh = 100;
1193        for d in deltas {
1194            match *d {
1195                RowDelta::Insert(at) => {
1196                    rows.insert(at, fresh);
1197                    fresh += 1;
1198                }
1199                RowDelta::Remove(at) => {
1200                    rows.remove(at);
1201                }
1202                RowDelta::Move(from, to) => {
1203                    let row = rows.remove(from);
1204                    rows.insert(to, row);
1205                }
1206            }
1207        }
1208    }
1209
1210    /// Replays range operations the way `RecyclerView` reads them: the count and, for rows
1211    /// that survive, the order. Fresh rows are any id >= 100.
1212    fn replay_ops(rows: &mut Vec<u32>, ops: &[i32]) {
1213        let mut fresh = 100;
1214        for op in ops.chunks(3) {
1215            let (a, b) = (op[1] as usize, op[2] as usize);
1216            match op[0] {
1217                SPLICE_INSERT => {
1218                    for i in 0..b {
1219                        rows.insert(a + i, fresh);
1220                        fresh += 1;
1221                    }
1222                }
1223                SPLICE_REMOVE => {
1224                    rows.drain(a..a + b);
1225                }
1226                SPLICE_MOVE => {
1227                    let row = rows.remove(a);
1228                    rows.insert(b, row);
1229                }
1230                _ => panic!("unknown op"),
1231            }
1232        }
1233    }
1234
1235    fn agree(start: &[u32], deltas: &[RowDelta]) -> Vec<i32> {
1236        let ops = splice_ops(deltas);
1237        let (mut a, mut b) = (start.to_vec(), start.to_vec());
1238        replay_deltas(&mut a, deltas);
1239        replay_ops(&mut b, &ops);
1240        let old = |v: &Vec<u32>| {
1241            v.iter()
1242                .map(|r| if *r >= 100 { 100 } else { *r })
1243                .collect::<Vec<_>>()
1244        };
1245        assert_eq!(old(&a), old(&b), "{deltas:?} -> {ops:?}");
1246        ops
1247    }
1248
1249    #[test]
1250    fn an_append_is_one_range() {
1251        let deltas: Vec<_> = (0..200).map(|_| RowDelta::Insert(3)).collect();
1252        assert_eq!(agree(&[0, 1, 2], &deltas), vec![SPLICE_INSERT, 3, 200]);
1253    }
1254
1255    #[test]
1256    fn a_removed_block_is_one_range() {
1257        // day-core removes highest first.
1258        let deltas = [
1259            RowDelta::Remove(4),
1260            RowDelta::Remove(3),
1261            RowDelta::Remove(2),
1262        ];
1263        assert_eq!(
1264            agree(&[0, 1, 2, 3, 4, 5], &deltas),
1265            vec![SPLICE_REMOVE, 2, 3]
1266        );
1267        let forward = [RowDelta::Remove(1), RowDelta::Remove(1)];
1268        assert_eq!(agree(&[0, 1, 2, 3], &forward), vec![SPLICE_REMOVE, 1, 2]);
1269    }
1270
1271    #[test]
1272    fn mixed_deltas_keep_their_order() {
1273        let deltas = [
1274            RowDelta::Remove(5),
1275            RowDelta::Remove(1),
1276            RowDelta::Insert(0),
1277            RowDelta::Move(4, 0),
1278            RowDelta::Insert(2),
1279            RowDelta::Insert(2),
1280            RowDelta::Move(1, 1),
1281        ];
1282        let ops = agree(&[0, 1, 2, 3, 4, 5, 6], &deltas);
1283        assert_eq!(ops.len() % 3, 0);
1284        // The no-op move is dropped; the two inserts at 2 fold.
1285        assert_eq!(&ops[ops.len() - 3..], &[SPLICE_INSERT, 2, 2]);
1286    }
1287
1288    #[test]
1289    fn the_keyed_case_lands_in_order() {
1290        // list-keyed-changes-land-in-order: insert at the top, the last row to the top.
1291        agree(&[1, 2, 3], &[RowDelta::Insert(0)]);
1292        assert_eq!(
1293            agree(&[9, 1, 2, 3], &[RowDelta::Move(3, 0)]),
1294            vec![SPLICE_MOVE, 3, 0]
1295        );
1296    }
1297
1298    #[test]
1299    fn scroll_preferences_become_bits() {
1300        let plain = ScrollProps::default();
1301        assert_eq!(scroll_flags(&plain, 2.0), (0, 0.0));
1302        let all = ScrollProps {
1303            indicators: ScrollIndicators::Hidden,
1304            bounce: Some(false),
1305            snap: ScrollSnap::Interval(292.0),
1306            keyboard_dismiss: KeyboardDismiss::Interactive,
1307            keyboard_taps: KeyboardTaps::Dismiss,
1308            track_offset: true,
1309            track_phase: true,
1310            ..Default::default()
1311        };
1312        let (f, px) = scroll_flags(&all, 2.625);
1313        assert!((px - 766.5).abs() < 1e-3);
1314        assert_eq!(
1315            f,
1316            SCROLL_HIDE_INDICATORS
1317                | SCROLL_BOUNCE_NEVER
1318                | SCROLL_SNAP_INTERVAL
1319                | SCROLL_KEYBOARD_DRAG
1320                | SCROLL_KEYBOARD_TAPS
1321                | SCROLL_TRACK_OFFSET
1322                | SCROLL_TRACK_PHASE
1323        );
1324        let paged = ScrollProps {
1325            bounce: Some(true),
1326            snap: ScrollSnap::Page,
1327            ..Default::default()
1328        };
1329        assert_eq!(
1330            scroll_flags(&paged, 1.0),
1331            (SCROLL_BOUNCE_ALWAYS | SCROLL_SNAP_PAGE, 0.0)
1332        );
1333        let nothing = ScrollProps {
1334            snap: ScrollSnap::Interval(-4.0),
1335            ..Default::default()
1336        };
1337        assert_eq!(scroll_flags(&nothing, 1.0), (0, 0.0));
1338    }
1339
1340    #[test]
1341    fn reports_decode_and_clamp() {
1342        assert_eq!(align_code(RowAlign::Nearest), 0);
1343        assert_eq!(align_code(RowAlign::End), 3);
1344        let v = viewport(3, 1, -5, 2.0, 10).map(|v| (v.first, v.last, v.end_distance));
1345        assert_eq!(v, Some((3, 3, 0.0)));
1346        let v = viewport(8, 40, 64, 2.0, 10).map(|v| (v.first, v.last, v.end_distance));
1347        assert_eq!(v, Some((8, 9, 32.0)));
1348        assert!(viewport(0, 0, 0, 2.0, 0).is_none());
1349        assert!(viewport(-1, 0, 0, 2.0, 4).is_none());
1350        assert_eq!(offset("2835,0", 2.625), Some(Point::new(1080.0, 0.0)));
1351        assert_eq!(offset("4", 1.0), None);
1352        assert_eq!(phase("2"), Some(ScrollPhase::Coasting));
1353        assert_eq!(phase("7"), None);
1354    }
1355
1356    #[test]
1357    fn java_side_parity() {
1358        let bridge = include_str!("../java/dev/daybrite/day/bridge/DayBridge.java");
1359        for (name, value) in [
1360            ("SPLICE_INSERT", SPLICE_INSERT),
1361            ("SPLICE_REMOVE", SPLICE_REMOVE),
1362            ("SPLICE_MOVE", SPLICE_MOVE),
1363            ("SCROLL_HIDE_INDICATORS", SCROLL_HIDE_INDICATORS),
1364            ("SCROLL_BOUNCE_NEVER", SCROLL_BOUNCE_NEVER),
1365            ("SCROLL_BOUNCE_ALWAYS", SCROLL_BOUNCE_ALWAYS),
1366            ("SCROLL_SNAP_PAGE", SCROLL_SNAP_PAGE),
1367            ("SCROLL_SNAP_INTERVAL", SCROLL_SNAP_INTERVAL),
1368            ("SCROLL_KEYBOARD_DRAG", SCROLL_KEYBOARD_DRAG),
1369            ("SCROLL_KEYBOARD_TAPS", SCROLL_KEYBOARD_TAPS),
1370            ("SCROLL_TRACK_OFFSET", SCROLL_TRACK_OFFSET),
1371            ("SCROLL_TRACK_PHASE", SCROLL_TRACK_PHASE),
1372        ] {
1373            assert!(
1374                bridge.contains(&format!("static final int {name} = {value};")),
1375                "{name} = {value}"
1376            );
1377        }
1378        for (name, align) in [
1379            ("LIST_ALIGN_NEAREST", RowAlign::Nearest),
1380            ("LIST_ALIGN_START", RowAlign::Start),
1381            ("LIST_ALIGN_CENTER", RowAlign::Center),
1382            ("LIST_ALIGN_END", RowAlign::End),
1383        ] {
1384            let value = align_code(align);
1385            assert!(
1386                bridge.contains(&format!("static final int {name} = {value};")),
1387                "{name} = {value}"
1388            );
1389        }
1390        assert!(bridge.contains(&format!("\"{OFFSET_PREFIX}\"")));
1391        assert!(bridge.contains(&format!("\"{PHASE_PREFIX}\"")));
1392    }
1393}
1394
1395/// How an `AnimSpec` crosses the bridge (docs/tween.md "The animation contract"): a timing
1396/// `int[]` for the `ValueAnimator` and the cycle's curve as a `float[]` of evenly spaced
1397/// progress samples, which `DayBridge.SampledCurve` plays as its interpolator; and how
1398/// `DayBridge.readDisplayed` comes back. Host-compiled so the arithmetic is unit tested.
1399#[cfg(any(target_os = "android", test))]
1400mod motion_wire {
1401    use day_spec::{AnimSpec, Color, Curve, Displayed, Point, Rect};
1402
1403    /// `timing` slots, `DayBridge.T_*`: cycle length and delay in ms, the cycles after the
1404    /// first, autoreverse.
1405    pub const T_DURATION: usize = 0;
1406    pub const T_DELAY: usize = 1;
1407    pub const T_REPEAT: usize = 2;
1408    pub const T_REVERSE: usize = 3;
1409    pub const T_COUNT: usize = 4;
1410
1411    /// `ValueAnimator.INFINITE`: the repeat of a spec that runs until the property is next set.
1412    pub const FOREVER: i32 = -1;
1413
1414    /// The timing slots of `anim`, all zero for `None` (applied at once). Android's repeat
1415    /// count counts each pass after the first, reversed ones included, as `AnimSpec::repeat`
1416    /// does, so it is passed as is.
1417    pub fn timing(anim: Option<&AnimSpec>) -> [i32; T_COUNT] {
1418        let mut out = [0; T_COUNT];
1419        let Some(a) = anim else {
1420            return out;
1421        };
1422        let int = |v: u32| i32::try_from(v).unwrap_or(i32::MAX);
1423        out[T_DURATION] = int(a.duration_ms);
1424        out[T_DELAY] = int(a.delay_ms);
1425        out[T_REPEAT] = if a.repeats_forever() {
1426            FOREVER
1427        } else {
1428            int(a.repeat)
1429        };
1430        out[T_REVERSE] = i32::from(a.autoreverse);
1431        out
1432    }
1433
1434    /// One forward cycle's progress at even offsets (`AnimSpec::keyframes`); empty for a
1435    /// linear cycle (and for `None`), which plays on a `LinearInterpolator`. The easing
1436    /// curves go as samples too, so each has the shape Day defines rather than the nearest
1437    /// Android interpolator's, and a spring is the physical one, overshoot included.
1438    pub fn keys(anim: Option<&AnimSpec>) -> Vec<f32> {
1439        match anim {
1440            Some(a) if !matches!(a.curve, Curve::Linear) && a.duration_ms > 0 => {
1441                a.keyframes().iter().map(|k| k.progress as f32).collect()
1442            }
1443            _ => Vec::new(),
1444        }
1445    }
1446
1447    /// `DayBridge.readDisplayed`'s slots as a [`Displayed`]: `[0]` alpha, `[1]`/`[2]` the
1448    /// translation in dp, `[3]` 1 when a frame was read, `[4..=7]` that frame in dp, `[8]` 1
1449    /// when the view has a fill, `[9]` the fill as packed ARGB.
1450    pub fn displayed(slots: &[f64]) -> Displayed {
1451        let [alpha, tx, ty, has_frame, x, y, w, h, has_fill, fill] = slots else {
1452            return Displayed::default();
1453        };
1454        let channel = |argb: u32, shift: u32| f64::from((argb >> shift) & 0xff) / 255.0;
1455        // A packed ARGB is at most 0xFFFF_FFFF, which an f64 holds exactly.
1456        let argb = fill.clamp(0.0, f64::from(u32::MAX)) as u32;
1457        Displayed {
1458            opacity: Some(*alpha),
1459            frame: (*has_frame != 0.0).then(|| Rect::new(*x, *y, *w, *h)),
1460            translation: Some(Point::new(*tx, *ty)),
1461            background: (*has_fill != 0.0).then(|| {
1462                Color::rgba(
1463                    channel(argb, 16),
1464                    channel(argb, 8),
1465                    channel(argb, 0),
1466                    channel(argb, 24),
1467                )
1468            }),
1469        }
1470    }
1471}
1472
1473#[cfg(test)]
1474mod motion_wire_tests {
1475    use super::motion_wire::*;
1476    use day_spec::{AnimSpec, Color, Point, Rect};
1477
1478    #[test]
1479    fn timing_carries_delay_repeat_and_reverse() {
1480        assert_eq!(timing(None), [0; T_COUNT]);
1481        let t = timing(Some(&AnimSpec::linear(600).delay(900)));
1482        assert_eq!(t, [600, 900, 0, 0]);
1483        let t = timing(Some(&AnimSpec::linear(800).repeat(2, true)));
1484        assert_eq!((t[T_REPEAT], t[T_REVERSE]), (2, 1));
1485        let t = timing(Some(&AnimSpec::linear(600).repeat_forever(false)));
1486        assert_eq!((t[T_REPEAT], t[T_REVERSE]), (FOREVER, 0));
1487    }
1488
1489    #[test]
1490    fn keys_sample_every_curve_but_linear() {
1491        assert_eq!(keys(None), Vec::<f32>::new());
1492        assert_eq!(keys(Some(&AnimSpec::linear(300))), Vec::<f32>::new());
1493        let ease = keys(Some(&AnimSpec::ease_in(1000)));
1494        assert_eq!(ease.len(), 61);
1495        assert!((ease[30] - 0.25).abs() < 1e-6, "t² at half way");
1496        let spring = AnimSpec::spring(0.9, 0.25);
1497        let k = keys(Some(&spring));
1498        assert_eq!(k.first().copied(), Some(0.0));
1499        assert_eq!(k.last().copied(), Some(1.0));
1500        assert!(k.iter().any(|&p| p > 1.3), "a loose spring overshoots");
1501    }
1502
1503    /// The interpolator `DayBridge.SampledCurve` is, in Rust: what a spring cycle reads at
1504    /// an offset between two samples is within a hair of the spring itself.
1505    #[test]
1506    fn sampled_curve_follows_the_spring() {
1507        let spring = AnimSpec::spring(0.9, 0.25);
1508        let k = keys(Some(&spring));
1509        let last = (k.len() - 1) as f32;
1510        let read = |t: f32| {
1511            let x = t * last;
1512            let i = x as usize;
1513            let f = x - i as f32;
1514            k[i] + (k[(i + 1).min(k.len() - 1)] - k[i]) * f
1515        };
1516        for step in 0..100_u8 {
1517            let t = f64::from(step) / 100.0 + 0.003;
1518            let want = spring.cycle_progress(t);
1519            assert!(
1520                (f64::from(read(t as f32)) - want).abs() < 0.02,
1521                "{t}: {want}"
1522            );
1523        }
1524    }
1525
1526    #[test]
1527    fn displayed_decodes_every_slot() {
1528        let d = displayed(&[
1529            0.5,
1530            10.0,
1531            -4.0,
1532            1.0,
1533            1.0,
1534            2.0,
1535            80.0,
1536            40.0,
1537            1.0,
1538            f64::from(0xFF80_4020_u32),
1539        ]);
1540        assert_eq!(d.opacity, Some(0.5));
1541        assert_eq!(d.translation, Some(Point::new(10.0, -4.0)));
1542        assert_eq!(d.frame, Some(Rect::new(1.0, 2.0, 80.0, 40.0)));
1543        let c = d.background.unwrap_or(Color::BLACK);
1544        assert!((c.r - 128.0 / 255.0).abs() < 1e-9 && (c.b - 32.0 / 255.0).abs() < 1e-9);
1545        let bare = displayed(&[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
1546        assert_eq!((bare.frame, bare.background), (None, None));
1547        assert_eq!(displayed(&[]).opacity, None);
1548    }
1549
1550    #[test]
1551    fn java_side_parity() {
1552        let bridge = include_str!("../java/dev/daybrite/day/bridge/DayBridge.java");
1553        for (name, value) in [
1554            ("T_DURATION", T_DURATION),
1555            ("T_DELAY", T_DELAY),
1556            ("T_REPEAT", T_REPEAT),
1557            ("T_REVERSE", T_REVERSE),
1558            ("T_COUNT", T_COUNT),
1559        ] {
1560            assert!(
1561                bridge.contains(&format!("static final int {name} = {value};")),
1562                "{name} = {value}"
1563            );
1564        }
1565        assert!(bridge.contains("double[] out = new double[10];"));
1566    }
1567}
1568
1569/// A typed binding to one Java class (docs/android-jni.md): `jni::bind_java_type!` with Day's
1570/// policies applied. Java names are kept verbatim; classes load through the app's class loader;
1571/// native methods catch panics and log a returned error; every binding is resolved by `init`; and
1572/// the class and members bound are kept from R8. Call bound methods inside [`java`].
1573#[cfg(target_os = "android")]
1574pub use day_platform_android::java_class;
1575
1576#[cfg(target_os = "android")]
1577pub mod ext;
1578#[cfg(target_os = "android")]
1579pub use ext::*;
1580
1581#[cfg(target_os = "android")]
1582mod imp {
1583    pub use day_platform_android::*;
1584
1585    use framework::DayListItem;
1586
1587    use std::any::Any;
1588    use std::cell::{Cell, RefCell};
1589    use std::rc::Rc;
1590    use std::sync::OnceLock;
1591
1592    use jni::Env;
1593    use jni::objects::{Global, JClass, JObject, JString};
1594    use linkme::distributed_slice;
1595
1596    /// A shared global reference to a native View. jni 0.22's `Global` is a bare `'static` ref that
1597    /// is not `Clone` (cloning a global ref is a JNI call), so we wrap it in `Arc`, restoring the
1598    /// `Arc`-backed sharing `GlobalRef` had in 0.21, which `AHandle: Clone` (a day-core `Handle`)
1599    /// requires. The underlying JNI global ref is released when the last `Arc` owner drops.
1600    type Gref = std::sync::Arc<Global<JObject<'static>>>;
1601
1602    use day_spec::bridge;
1603    use day_spec::props::*;
1604    use day_spec::{
1605        A11yProps, AnimSpec, Builtin, Cap, Cursor, DrawOp, Event, EventSink, Font, ListSource,
1606        NodeId, PieceKind, Platform, Point, Proposal, RawHandle, Rect, Registry, Renderer, Role,
1607        Size, Support, Toolkit, Transform, WindowOptions, kinds,
1608    };
1609
1610    day_core::tls_group! {
1611        static CONTEXT_MENU_FNS: day_spec::sidetable::SideTable<day_spec::ContextMenuFn> = day_spec::sidetable::SideTable::new();
1612        /// Menu buttons' providers (`set_button_menu`, docs/menus.md "Menu buttons"), keyed
1613        /// like `CONTEXT_MENU_FNS` by the button's global ref, so a button may carry both.
1614        static BUTTON_MENU_FNS: day_spec::sidetable::SideTable<day_spec::ContextMenuFn> = day_spec::sidetable::SideTable::new();
1615        static TRANSFER_SOURCES: day_spec::sidetable::SideTable<day_spec::transfer::Source> = day_spec::sidetable::SideTable::new();
1616        static TRANSFER_TARGETS: day_spec::sidetable::SideTable<day_spec::transfer::Target> = day_spec::sidetable::SideTable::new();
1617
1618        /// Recycling list (docs/list.md): row-pull sources keyed by list node id (Java passes it
1619        /// back in nativeListBind), and a stable GlobalRef per physical cell so day-core's cell
1620        /// map keys consistently across ListView recycling. Cells are grouped by list so that
1621        /// releasing a list frees its cells' JNI global refs with it; a long session would
1622        /// otherwise leak one global ref per physical cell toward the JNI table limit. Within a
1623        /// list, cells key by `identityHashCode`, the only stable identity the wire carries
1624        /// (nativeListBind sends `(hostId, position, cell)` and nothing else). Collisions are
1625        /// possible in principle; one would conflate two physical cells of the same list, and
1626        /// carrying a bridge-assigned cell id would widen the wire for a case never observed.
1627        static LIST_SOURCES: std::cell::RefCell<std::collections::HashMap<i64, ListSource>> =
1628            std::cell::RefCell::new(std::collections::HashMap::new());
1629        /// Latest logical row of a physical holder; invalidates deferred binds on recycle.
1630        static LIST_BINDINGS: std::cell::RefCell<std::collections::HashMap<(i64, i32), (usize, u64)>> =
1631            std::cell::RefCell::new(std::collections::HashMap::new());
1632        static LIST_NODE: std::cell::RefCell<std::collections::HashMap<usize, i64>> =
1633            std::cell::RefCell::new(std::collections::HashMap::new());
1634        /// A realized NAV_MENU's rows, by its own view ptr: `(node, joined titles, joined icons,
1635        /// joined document keys, joined badge texts)`.
1636        ///
1637        /// Recorded at realize, which is where the props are, and handed to the navigation suite
1638        /// at insert, the first moment the menu is in a hierarchy whose ancestors reach the
1639        /// suite. Where there is no suite above it (every presentation but `Tabs`) the handover
1640        /// finds nothing and the rows stay a list. Entries drop in `release`.
1641        /// Each realized list item's props, by its view ptr: a patch changes one part, and the
1642        /// Java view takes its three texts together (docs/list.md "List items").
1643        static LIST_ITEM_PROPS: std::cell::RefCell<
1644            std::collections::HashMap<usize, day_spec::props::ListItemProps>,
1645        > = std::cell::RefCell::new(std::collections::HashMap::new());
1646        static NAV_MENU_ROWS: std::cell::RefCell<
1647            std::collections::HashMap<usize, (i64, String, String, String, String)>,
1648        > = std::cell::RefCell::new(std::collections::HashMap::new());
1649        /// Each window's toolbar model (docs/toolbars.md), by its root view ptr: what the app-bar
1650        /// menu is repainted from.
1651        static WINDOW_BARS: std::cell::RefCell<
1652            std::collections::HashMap<usize, day_spec::ToolbarMirror>,
1653        > = std::cell::RefCell::new(std::collections::HashMap::new());
1654        /// Navigation-suite hosts by view ptr, so `NavPatch::Select` knows to drive the suite
1655        /// rather than a DayNavHost.
1656        static NAV_SUITES: std::cell::RefCell<std::collections::HashSet<usize>> =
1657            std::cell::RefCell::new(std::collections::HashSet::new());
1658        /// Label view ptr → node id, so a `LabelPatch::Runs` (which carries no id) can still tell
1659        /// a link's ClickableSpan which node to report against. Entries drop in `release`.
1660        static LABEL_NODE: std::cell::RefCell<std::collections::HashMap<usize, i64>> =
1661            std::cell::RefCell::new(std::collections::HashMap::new());
1662        #[allow(clippy::type_complexity)] // host id → (cell identityHashCode → its GlobalRef)
1663        static LIST_CELLS: std::cell::RefCell<
1664            std::collections::HashMap<i64, std::collections::HashMap<i32, Gref>>,
1665        > = std::cell::RefCell::new(std::collections::HashMap::new());
1666        /// The lists whose rows size themselves (`RowHeight::Automatic`), by node id: each bind
1667        /// hands the native row the height day-core laid it at.
1668        static LIST_AUTOMATIC: std::cell::RefCell<std::collections::HashSet<i64>> =
1669            std::cell::RefCell::new(std::collections::HashSet::new());
1670        /// Programmatic selection per list (docs/list.md `ListPatch::Selected`): the Java side
1671        /// paints from this at bind (nativeListIsSelected) and on a sync
1672        /// (listPaintSelection walking the visible holders).
1673        static LIST_SELECTED: std::cell::RefCell<
1674            std::collections::HashMap<i64, std::collections::BTreeSet<usize>>,
1675        > = std::cell::RefCell::new(std::collections::HashMap::new());
1676
1677        static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1678        static DENSITY: Cell<f64> = const { Cell::new(1.0) };
1679        static ROOT: RefCell<Option<(AHandle, Size)>> = const { RefCell::new(None) };
1680
1681        /// Secondary DayWindowActivity roots (docs/windows.md): (day node, the root's
1682        /// global ref, kept alive alongside the tree's adopted ref).
1683        static SECONDARY: RefCell<Vec<(u64, Gref)>> = const { RefCell::new(Vec::new()) };
1684
1685    }
1686
1687    type SectionTreeEntry = (day_spec::TreeSource, Vec<u64>, Vec<u64>);
1688    thread_local! {
1689        static TREE_SOURCES: RefCell<std::collections::HashMap<i64, SectionTreeEntry>> = RefCell::new(std::collections::HashMap::new());
1690    }
1691    fn tree_reload(host: &AHandle) {
1692        use std::fmt::Write as _;
1693        let handle = host.clone();
1694        let id = LIST_NODE.with(|m| {
1695            m.borrow()
1696                .get(&(host.0.as_obj().as_raw() as usize))
1697                .copied()
1698        });
1699        let Some(id) = id else {
1700            return;
1701        };
1702        Material::post(Box::new(move || {
1703            let source = TREE_SOURCES.with(|m| m.borrow().get(&id).map(|e| e.0.clone()));
1704            let Some(source) = source else {
1705                return;
1706            };
1707            let mut tokens = Vec::new();
1708            let mut data = String::new();
1709            for g in 0..(source.children_len)(None) {
1710                let token = (source.child_token)(None, g);
1711                let index = tokens.len();
1712                tokens.push(token);
1713                let _ = writeln!(
1714                    data,
1715                    "{token}:-1:{}:{}",
1716                    u8::from((source.section_header)(token)),
1717                    u8::from((source.expanded)(token))
1718                );
1719                for c in 0..(source.children_len)(Some(token)) {
1720                    let child = (source.child_token)(Some(token), c);
1721                    tokens.push(child);
1722                    let _ = writeln!(data, "{child}:{index}:0:0");
1723                }
1724            }
1725            TREE_SOURCES.with(|m| {
1726                if let Some(e) = m.borrow_mut().get_mut(&id) {
1727                    e.1 = tokens;
1728                    let selected =
1729                        e.1.iter()
1730                            .enumerate()
1731                            .filter(|(_, t)| e.2.contains(t))
1732                            .map(|(i, _)| i)
1733                            .collect();
1734                    LIST_SELECTED.with(|m| m.borrow_mut().insert(id, selected));
1735                }
1736            });
1737            with_env(|env| {
1738                let data = jstr(env, &data);
1739                let _ = java_in(env, |env| {
1740                    DayBridge::treeReload(env, handle.0.as_obj(), &data)
1741                });
1742            });
1743        }));
1744    }
1745    fn tree_patch(host: &AHandle, patch: &TreePatch) {
1746        match patch {
1747            TreePatch::Reload => tree_reload(host),
1748            TreePatch::Expand(token, open) => {
1749                // ExpandableListView synchronously recycles children on collapse. Run
1750                // outside the core update borrow so their Day IDs can actually be cleared.
1751                let (host, token, open) = (host.clone(), *token, *open);
1752                Material::post(Box::new(move || {
1753                    bridge(|env| DayBridge::treeExpand(env, host.0.as_obj(), token as i64, open));
1754                }));
1755            }
1756            TreePatch::Reveal(token) => {
1757                bridge(|env| DayBridge::treeReveal(env, host.0.as_obj(), *token as i64));
1758            }
1759            TreePatch::Selected(tokens) => {
1760                if let Some(id) = LIST_NODE.with(|m| {
1761                    m.borrow()
1762                        .get(&(host.0.as_obj().as_raw() as usize))
1763                        .copied()
1764                }) {
1765                    let selected = TREE_SOURCES.with(|m| {
1766                        m.borrow_mut().get_mut(&id).map_or_default(|e| {
1767                            e.2.clone_from(tokens);
1768                            e.1.iter()
1769                                .enumerate()
1770                                .filter(|(_, t)| tokens.contains(t))
1771                                .map(|(i, _)| i)
1772                                .collect()
1773                        })
1774                    });
1775                    LIST_SELECTED.with(|m| m.borrow_mut().insert(id, selected));
1776                }
1777                bridge(|env| DayBridge::treeSelection(env, host.0.as_obj()));
1778            }
1779        }
1780    }
1781
1782    /// Row count, pulled by the Java adapter's getCount (reads the snapshot only; no tree).
1783    /// A JNI up-call entry: the body is contained, since a panic unwinding the frame would abort.
1784    #[must_use]
1785    pub fn list_len(host_id: i64) -> usize {
1786        day_spec::ffi_guard::contain(0, || {
1787            LIST_SOURCES.with(|m| m.borrow().get(&host_id).map_or(0, |s| (s.len)()))
1788        })
1789    }
1790
1791    /// Give a self-sizing list's native row the height day-core laid its row at (docs/list.md
1792    /// "Row heights"). Called right after `bind_row`, inside `RecyclerView`'s own bind, which is
1793    /// where a row's layout params belong: the layout manager measures the holder next. A
1794    /// uniform list's rows keep the height their holders were made with, except a section
1795    /// header and a supplementary row (the list's header, footer, empty state, padding), which
1796    /// size to their content in every list (docs/list.md "Sections", "Header, footer and empty
1797    /// state"); both pool apart from items, so the height never reaches an item's holder.
1798    fn size_list_cell(
1799        host_id: i64,
1800        source: &ListSource,
1801        index: usize,
1802        cell: &JObject,
1803        raw: RawHandle,
1804    ) {
1805        let header = source.is_header.as_ref().is_some_and(|f| f(index))
1806            || source.is_supplement.as_ref().is_some_and(|f| f(index));
1807        if !header && !LIST_AUTOMATIC.with(|m| m.borrow().contains(&host_id)) {
1808            return;
1809        }
1810        let height = (source.cell_height)(raw);
1811        if height > 0.0 {
1812            set_list_cell_height(cell, height);
1813        }
1814    }
1815
1816    /// Set one native row's height, in points (`DayBridge.setListCellHeight`).
1817    fn set_list_cell_height(cell: &JObject, height: f64) {
1818        let px = (height * DENSITY.with(std::cell::Cell::get)).round() as i32;
1819        bridge(|env| DayBridge::setListCellHeight(env, cell, px));
1820    }
1821
1822    /// Fill a recycled cell; the Java adapter's getView calls this. A stable `GlobalRef` per
1823    /// physical cell (keyed by identityHashCode under its list) gives day-core a consistent
1824    /// cell key. A JNI up-call entry running app row builders: contained like `list_len`.
1825    /// `pinned`: the cell is the list's pinned header copy, bound through
1826    /// `ListSource::bind_pinned` (docs/list.md "Sections").
1827    #[expect(
1828        clippy::needless_pass_by_value,
1829        reason = "public signature; the JNI entry hands over the cell's local reference"
1830    )]
1831    pub fn list_bind(env: &mut Env, host_id: i64, position: i32, cell: JObject, pinned: bool) {
1832        day_spec::ffi_guard::contain((), || {
1833            let hash = framework::System::identityHashCode(env, &cell).unwrap_or(0);
1834            let cached = LIST_CELLS.with(|m| {
1835                m.borrow()
1836                    .get(&host_id)
1837                    .and_then(|cells| cells.get(&hash).cloned())
1838            });
1839            let gref = if let Some(g) = cached {
1840                g
1841            } else {
1842                // A failed global ref (JNI table exhausted) skips this bind (the next
1843                // bind retries) rather than panicking out of the up-call.
1844                let Ok(g) = env.new_global_ref(&cell) else {
1845                    return;
1846                };
1847                let g = std::sync::Arc::new(g);
1848                LIST_CELLS.with(|m| {
1849                    m.borrow_mut()
1850                        .entry(host_id)
1851                        .or_default()
1852                        .insert(hash, g.clone())
1853                });
1854                g
1855            };
1856            let raw = gref.as_obj().as_raw() as RawHandle;
1857            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
1858            if let Some(source) = source {
1859                let index = position as usize;
1860                if index >= (source.len)() {
1861                    return;
1862                }
1863                let token = (source.token_at)(index);
1864                LIST_BINDINGS.with(|m| m.borrow_mut().insert((host_id, hash), (index, token)));
1865                let bind = move |source: &ListSource| {
1866                    if pinned {
1867                        source.bind_pinned.clone()
1868                    } else {
1869                        source.bind_row.clone()
1870                    }
1871                };
1872                if day_core::try_with_tree(|_| ()).is_some() {
1873                    bind(&source)(index, raw);
1874                    size_list_cell(host_id, &source, index, &cell, raw);
1875                } else {
1876                    // DayFixed.measure can make RecyclerView bind during Day's layout borrow.
1877                    // Core refuses reentry, but RecyclerView considers that empty holder bound
1878                    // and need not ask again. Retain the JNI cell and retry on the next UI turn,
1879                    // rejecting a stale row or disposed list before touching it.
1880                    <Material as Platform>::post(Box::new(move || {
1881                        if !LIST_BINDINGS
1882                            .with(|m| m.borrow().get(&(host_id, hash)) == Some(&(index, token)))
1883                        {
1884                            return;
1885                        }
1886                        let current = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
1887                        if let Some(current) = current
1888                            && index < (current.len)()
1889                            && (current.token_at)(index) == token
1890                        {
1891                            let raw = gref.as_obj().as_raw() as RawHandle;
1892                            bind(&current)(index, raw);
1893                            size_list_cell(host_id, &current, index, gref.as_obj(), raw);
1894                        }
1895                    }));
1896                }
1897            } else {
1898                let entry = TREE_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
1899                if let Some((source, tokens, _)) = entry
1900                    && let Some(token) = tokens.get(position as usize)
1901                {
1902                    (source.bind_row)(*token, raw);
1903                    // SAFETY: a list cell is the DayFixed View the adapter created.
1904                    let width = unsafe { env.as_cast_unchecked::<framework::View>(&cell) }
1905                        .getWidth(env)
1906                        .unwrap_or(0);
1907                    if width > 0 {
1908                        (source.layout_cell)(
1909                            raw,
1910                            f64::from(width) / DENSITY.with(std::cell::Cell::get),
1911                        );
1912                    }
1913                }
1914            }
1915        });
1916    }
1917
1918    /// A holder left the visible set (`RecyclerView`'s onViewRecycled): clear the cell
1919    /// subtree's dayscript ids so pooled rows stop answering lookups, through day-core's
1920    /// `list_recycle_cell`, keyed by the same per-cell `GlobalRef` `list_bind` binds with.
1921    /// A JNI up-call entry: contained.
1922    #[expect(
1923        clippy::needless_pass_by_value,
1924        reason = "public signature; the JNI entry hands over the cell's local reference"
1925    )]
1926    pub fn list_recycle(env: &mut Env, host_id: i64, cell: JObject) {
1927        day_spec::ffi_guard::contain((), || {
1928            let hash = framework::System::identityHashCode(env, &cell).unwrap_or(0);
1929            LIST_BINDINGS.with(|m| m.borrow_mut().remove(&(host_id, hash)));
1930            let gref = LIST_CELLS.with(|m| {
1931                m.borrow()
1932                    .get(&host_id)
1933                    .and_then(|cells| cells.get(&hash).cloned())
1934            });
1935            let Some(gref) = gref else { return };
1936            if day_core::try_with_tree(|_| ()).is_some() {
1937                recycle_cell(host_id, &gref);
1938            } else {
1939                // Inside Day's borrow: a reload or splice the tree is applying, which makes
1940                // RecyclerView recycle its cached holders (a row it prefetched while scrolling)
1941                // on the spot. `ListSource::recycle` would drop the park there and leave the
1942                // row's ids answering; park on the next turn instead, unless the cell was bound
1943                // again in between.
1944                <Material as Platform>::post(Box::new(move || {
1945                    if !LIST_BINDINGS.with(|m| m.borrow().contains_key(&(host_id, hash))) {
1946                        recycle_cell(host_id, &gref);
1947                    }
1948                }));
1949            }
1950        });
1951    }
1952
1953    /// Hand a cell that left the visible set to its list's (or tree's) source.
1954    fn recycle_cell(host_id: i64, gref: &Gref) {
1955        let raw = gref.as_obj().as_raw() as RawHandle;
1956        let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
1957        if let Some(source) = source {
1958            (source.recycle)(raw);
1959        } else if let Some(source) =
1960            TREE_SOURCES.with(|m| m.borrow().get(&host_id).map(|e| e.0.clone()))
1961        {
1962            (source.recycle)(raw);
1963        }
1964    }
1965
1966    /// A sectioned list is going away: hand day-core its pinned header cell for good
1967    /// (`ListSource::release`), the one cell `RecyclerView` never pooled (docs/list.md
1968    /// "Sections"). The cell keys by the `GlobalRef` `list_bind` made for it.
1969    fn release_pinned_header(list: &AHandle, nid: i64) {
1970        let Some(source) = LIST_SOURCES.with(|m| m.borrow().get(&nid).cloned()) else {
1971            return;
1972        };
1973        if source.is_header.is_none() {
1974            return;
1975        }
1976        let gref = with_env(|env| {
1977            let Ok(cell) = DayBridge::listPinnedCell(env, list.0.as_obj()) else {
1978                if env.exception_check() {
1979                    env.exception_clear();
1980                }
1981                return None;
1982            };
1983            if cell.is_null() {
1984                return None;
1985            }
1986            let hash = framework::System::identityHashCode(env, &cell).ok()?;
1987            LIST_CELLS.with(|m| m.borrow().get(&nid).and_then(|c| c.get(&hash).cloned()))
1988        });
1989        if let Some(gref) = gref {
1990            (source.release)(gref.as_obj().as_raw() as RawHandle);
1991        }
1992    }
1993
1994    /// Whether row `position` is in the list's programmatic selection; the Java bind path
1995    /// paints newly bound holders from this. A JNI up-call entry: contained.
1996    #[must_use]
1997    pub fn list_is_selected(host_id: i64, position: i32) -> bool {
1998        day_spec::ffi_guard::contain(false, || {
1999            LIST_SELECTED.with(|m| {
2000                m.borrow()
2001                    .get(&host_id)
2002                    .is_some_and(|set| set.contains(&(position.max(0) as usize)))
2003            })
2004        })
2005    }
2006
2007    /// The adapter's view type for row `position` (`getItemViewType`): 1 for a section header
2008    /// (docs/list.md "Sections"), 2 for a supplementary row (the list's header, footer, empty
2009    /// state or content padding, docs/list.md "Header, footer and empty state"), 0 for an
2010    /// item. Each pools apart, so a recycled cell never carries one kind's height or chrome
2011    /// to another. A JNI up-call entry: contained.
2012    #[must_use]
2013    pub fn list_row_kind(host_id: i64, position: i32) -> i32 {
2014        day_spec::ffi_guard::contain(0, || {
2015            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2016            let Some(s) = source else { return 0 };
2017            let index = position.max(0) as usize;
2018            if index >= (s.len)() {
2019                return 0;
2020            }
2021            if s.is_supplement.as_ref().is_some_and(|f| f(index)) {
2022                return 2;
2023            }
2024            i32::from(s.is_header.as_ref().is_some_and(|f| f(index)))
2025        })
2026    }
2027
2028    /// The list's viewport report from `DayListView.reportViewport` (docs/list.md "Visible
2029    /// rows"), passed to `ListSource::viewport`, which only enqueues. A JNI up-call entry:
2030    /// contained.
2031    pub fn list_viewport(host_id: i64, first: i32, last: i32, end_px: i32) {
2032        day_spec::ffi_guard::contain((), || {
2033            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2034            let Some(source) = source else { return };
2035            let Some(report) = &source.viewport else {
2036                return;
2037            };
2038            if let Some(v) = crate::list_wire::viewport(
2039                first,
2040                last,
2041                end_px,
2042                DENSITY.with(std::cell::Cell::get),
2043                (source.len)(),
2044            ) {
2045                report(v);
2046            }
2047        });
2048    }
2049
2050    /// The reader moved the list (`DayListView.onScrolled`, docs/list.md "Following the end"),
2051    /// passed to `ListSource::reader_scroll`, which only enqueues. A JNI up-call entry:
2052    /// contained.
2053    pub fn list_reader_scroll(host_id: i64) {
2054        day_spec::ffi_guard::contain((), || {
2055            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2056            if let Some(report) = source.as_ref().and_then(|s| s.reader_scroll.as_ref()) {
2057                report();
2058            }
2059        });
2060    }
2061
2062    /// The display row of the header that opens the section holding row `position`, or -1:
2063    /// which header the pinned copy shows (docs/list.md "Sections"). Walks back from the row;
2064    /// row 0 of a sectioned list is always a header. A JNI up-call entry: contained.
2065    #[must_use]
2066    pub fn list_header_of(host_id: i64, position: i32) -> i32 {
2067        day_spec::ffi_guard::contain(-1, || {
2068            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2069            let Some(source) = source else { return -1 };
2070            let Some(is_header) = source.is_header.as_ref() else {
2071                return -1;
2072            };
2073            let len = (source.len)();
2074            if position < 0 || len == 0 {
2075                return -1;
2076            }
2077            let start = (position as usize).min(len - 1);
2078            // The list's own header, footer or padding at the top: no section is pinned.
2079            if source.is_supplement.as_ref().is_some_and(|f| f(start)) {
2080                return -1;
2081            }
2082            (0..=start)
2083                .rev()
2084                .find(|&i| is_header(i))
2085                .map_or(-1, |i| i32::try_from(i).unwrap_or(-1))
2086        })
2087    }
2088
2089    /// One drag-and-drop up-call from `DayTransfer` (docs/drag-and-drop.md): `kind` 0 asks the
2090    /// source `token` for its encoded offer, 1 asks the target `token` whether it accepts the
2091    /// types listed in `bytes`, 2 delivers the offer encoded in `bytes`, and 3 tells the target
2092    /// the session left it or ended. Answers the reply bytes for Java.
2093    ///
2094    /// # Errors
2095    ///
2096    /// Returns the JNI error when `bytes` cannot be read or the reply array cannot be made.
2097    #[expect(
2098        clippy::needless_pass_by_value,
2099        reason = "public signature; the JNI entry hands over the array's local reference"
2100    )]
2101    pub fn transfer_call<'l>(
2102        env: &mut Env<'l>,
2103        kind: i32,
2104        token: i64,
2105        x: f64,
2106        y: f64,
2107        bytes: jni::objects::JByteArray,
2108        local: bool,
2109    ) -> Result<jni::objects::JByteArray<'l>, jni::errors::Error> {
2110        use day_spec::transfer::*;
2111        let input = env.convert_byte_array(&bytes)?;
2112        let output = day_spec::ffi_guard::contain(Vec::new(), || match kind {
2113            0 => TRANSFER_SOURCES
2114                .with(|t| t.get(token as usize))
2115                .and_then(|f| f(Point::new(x, y)))
2116                .and_then(|o| o.encode())
2117                .unwrap_or_default(),
2118            1 => {
2119                let at = Location {
2120                    position: Point::new(x, y),
2121                    types: String::from_utf8_lossy(&input)
2122                        .split('\n')
2123                        .map(str::to_owned)
2124                        .collect(),
2125                    allowed: vec![Operation::Copy],
2126                    local,
2127                };
2128                vec![u8::from(
2129                    TRANSFER_TARGETS
2130                        .with(|t| t.get(token as usize))
2131                        .is_some_and(|t| t.proposal(&at) == Operation::Copy),
2132                )]
2133            }
2134            2 => {
2135                let ok = Offer::decode(&input).is_some_and(|offer| {
2136                    TRANSFER_TARGETS
2137                        .with(|t| t.get(token as usize))
2138                        .is_some_and(|t| {
2139                            t.deliver(
2140                                Location {
2141                                    position: Point::new(x, y),
2142                                    types: offer.types(),
2143                                    allowed: vec![Operation::Copy],
2144                                    local,
2145                                },
2146                                offer,
2147                            )
2148                        })
2149                });
2150                vec![u8::from(ok)]
2151            }
2152            // The session left the target without dropping, or ended: the hover is over.
2153            3 => {
2154                if let Some(t) = TRANSFER_TARGETS.with(|t| t.get(token as usize)) {
2155                    t.leave();
2156                }
2157                Vec::new()
2158            }
2159            _ => Vec::new(),
2160        });
2161        env.byte_array_from_slice(&output)
2162    }
2163    /// Make `h` a drag source (`DayTransfer.source`) or a drop target (`DayTransfer.target`),
2164    /// keyed by its view pointer.
2165    fn transfer_install(h: &AHandle, source: bool) {
2166        let view = h.0.as_obj();
2167        let token = view.as_raw() as i64;
2168        bridge(|env| {
2169            if source {
2170                DayTransfer::source(env, view, token)
2171            } else {
2172                DayTransfer::target(env, view, token)
2173            }
2174        });
2175    }
2176
2177    /// The reorder guard's verdict for a hovered drop (docs/list.md), pulled synchronously by
2178    /// `ItemTouchHelper`'s canDropOver. `ItemTouchHelper` cannot relocate the gap, so a Retarget
2179    /// verdict (accepted != proposed) reads as a deny for that hover. The source is cloned out
2180    /// before the guard runs, so no thread-local borrow is held.
2181    #[must_use]
2182    pub fn list_can_drop(host_id: i64, from: i32, to: i32) -> bool {
2183        // JNI up-call entry (ItemTouchHelper's canDropOver): contain the app's guard.
2184        day_spec::ffi_guard::contain(false, || {
2185            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2186            let Some(source) = source else { return false };
2187            let Some(r) = source.reorder.as_ref() else {
2188                return false;
2189            };
2190            let len = (source.len)();
2191            let (from, to) = (from.max(0) as usize, to.max(0) as usize);
2192            if from >= len || to >= len {
2193                return false;
2194            }
2195            (r.can_move)(from, to) == to as i64
2196        })
2197    }
2198
2199    /// Commit one incremental `ItemTouchHelper` swap through the source's synchronous `move_row`
2200    /// (rotates day's snapshot, defers the app callback). Returns whether the swap was accepted.
2201    #[must_use]
2202    pub fn list_move(host_id: i64, from: i32, to: i32) -> bool {
2203        // JNI up-call entry: contain the synchronous commit.
2204        day_spec::ffi_guard::contain(false, || {
2205            if !list_can_drop(host_id, from, to) {
2206                return false;
2207            }
2208            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2209            let Some(r) = source.and_then(|s| s.reorder) else {
2210                return false;
2211            };
2212            let (from, to) = (from as usize, to as usize);
2213            if from != to {
2214                (r.move_row)(from, to);
2215            }
2216            true
2217        })
2218    }
2219
2220    /// May this row be swiped away? Consulted from `getMovementFlags`, so a protected row
2221    /// reports no swipe direction and never moves under the finger (docs/list.md).
2222    #[must_use]
2223    pub fn list_can_delete(host_id: i64, index: i32) -> bool {
2224        // JNI up-call entry (getMovementFlags): contain the app's guard.
2225        day_spec::ffi_guard::contain(false, || {
2226            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2227            let Some(source) = source else { return false };
2228            let Some(d) = source.delete.as_ref() else {
2229                return false;
2230            };
2231            let index = index.max(0) as usize;
2232            index < (source.len)() && (d.can_delete)(index)
2233        })
2234    }
2235
2236    /// Commit a swipe-to-delete through the source's synchronous `delete_row` (shortens day's
2237    /// snapshot, defers the app callback). Returns whether the delete was accepted.
2238    #[must_use]
2239    pub fn list_delete(host_id: i64, index: i32) -> bool {
2240        // JNI up-call entry: contain the synchronous commit.
2241        day_spec::ffi_guard::contain(false, || {
2242            if !list_can_delete(host_id, index) {
2243                return false;
2244            }
2245            let source = LIST_SOURCES.with(|m| m.borrow().get(&host_id).cloned());
2246            let Some(d) = source.and_then(|s| s.delete) else {
2247                return false;
2248            };
2249            (d.delete_row)(index as usize);
2250            true
2251        })
2252    }
2253
2254    pub const BRIDGE: &str = "dev/daybrite/day/bridge/DayBridge";
2255
2256    // DayBridge (java/dev/daybrite/day/bridge/DayBridge.java): every static method Rust calls,
2257    // named exactly as Java names it (docs/android-jni.md). `init` resolves the whole class, so a
2258    // method renamed or retyped on the Java side stops a debug or scripted launch by name.
2259    crate::java_class! {
2260        pub DayBridge => dev.daybrite.day.bridge.DayBridge,
2261        methods {
2262        static fn addChild(parent: android.view.View, child: android.view.View),
2263        static fn announce(text: JString, urgent: jboolean),
2264        static fn baselineAt(v: android.view.View, w_px: jint, h_px: jint) -> jint,
2265        static fn cancelFrame(token: jlong),
2266        static fn canSetAppearance() -> jboolean,
2267        static fn canSetLauncherShortcuts() -> jboolean,
2268        static fn closeWindow(node: jlong),
2269        static fn coverDismiss(cover: android.view.View),
2270        static fn coverPresent(cover: android.view.View, bg: jint, has_bg: jboolean, dismiss_disabled: jboolean),
2271        static fn coverSetDismissDisabled(cover: android.view.View, d: jboolean),
2272        static fn dismissPresent(req: jlong),
2273        static fn displayInfo() -> JString,
2274        static fn documentNavChrome(suite: android.view.View, visible: jboolean),
2275        static fn documentNavSuite(suite: android.view.View, new_label: JString, close_label: JString, can_add: jboolean),
2276        static fn enableGesture(v: android.view.View, id: jlong, is_drag: jboolean),
2277        static fn enableRecognizer(v: android.view.View, id: jlong, kind: jint),
2278        static fn enableHover(v: android.view.View, id: jlong),
2279        static fn enableKeys(v: android.view.View, id: jlong),
2280        static fn enablePan(v: android.view.View, id: jlong),
2281        static fn enablePinch(v: android.view.View, id: jlong),
2282        static fn enableRotate(v: android.view.View, id: jlong),
2283        static fn focusNavSearch(nav_host: android.view.View),
2284        static fn focusView(v: android.view.View, focused: jboolean),
2285        static fn focusWindow(node: jlong),
2286        static fn fontFamilies() -> JString,
2287        static fn imageDecode(id: jlong, bytes: jbyte[]) -> JString,
2288        static fn imageEncode(id: jlong, format: JString, quality: jint, fit_w: jdouble, fit_h: jdouble) -> jbyte[],
2289        static fn imageRelease(id: jlong),
2290        static fn isDarkMode() -> jboolean,
2291        static fn systemColor(role: jint) -> jint,
2292        static fn listPaintSelection(v: android.view.View, host_id: jlong),
2293        static fn listReload(v: android.view.View),
2294        static fn listConfigure(v: android.view.View, viewport: jboolean, reader: jboolean, supplements: jboolean),
2295        static fn listSplice(v: android.view.View, ops: jint[]),
2296        static fn listScroll(v: android.view.View, row: jint, align: jint, animated: jboolean),
2297        static fn listScrollToEnd(v: android.view.View),
2298        static fn listScrollToRow(v: android.view.View, row: jint),
2299        static fn listSetSections(v: android.view.View, on: jboolean),
2300        static fn listPinnedCell(v: android.view.View) -> android.view.View,
2301        static fn localeTags() -> JString,
2302        static fn makeButton(id: jlong, title: JString) -> android.view.View,
2303        static fn makeCanvas(id: jlong) -> android.view.View,
2304        static fn makeContainer() -> android.view.View,
2305        static fn makeCover(node: jlong, half: jboolean) -> android.view.View,
2306        static fn makeDivider(vertical: jboolean) -> android.view.View,
2307        static fn makeImage(name: JString, mode: jint, tint: jint) -> android.view.View,
2308        static fn makeImageBitmap(id: jlong, mode: jint) -> android.view.View,
2309        static fn makeImageBytes(bytes: jbyte[], mode: jint) -> android.view.View,
2310        static fn makeLabel(text: JString) -> android.view.View,
2311        static fn makeList(host_id: jlong, row_height_px: jint, selectable: jboolean, reorderable: jboolean, deletable: jboolean, delete_label: JString) -> android.view.View,
2312        static fn makeNavHost(id: jlong, title: JString, adaptive: jboolean, tile_min_dp: jfloat) -> android.view.View,
2313        static fn makeNavMenu(id: jlong, joined_items: JString, joined_icons: JString, joined_sections: JString) -> android.view.View,
2314        static fn makeNavPage(id: jlong, immersive: jboolean) -> android.view.View,
2315        static fn makeNavSuite(id: jlong, initial: jint) -> android.view.View,
2316        static fn makeProgress(determinate: jboolean, fraction: jdouble) -> android.view.View,
2317        static fn makeScroll(horizontal: jboolean, flags: jint, snap_px: jfloat, node: jlong) -> android.view.View,
2318        static fn makeSlider(id: jlong, value: jdouble, min: jdouble, max: jdouble) -> android.view.View,
2319        static fn makeTextField(id: jlong, value: JString, placeholder: JString) -> android.view.View,
2320        static fn makeToggle(id: jlong, value: jboolean, enabled: jboolean) -> android.view.View,
2321        static fn makeTree(id: jlong, height: jint, selectable: jboolean) -> android.view.View,
2322        static fn markNavChromePage(page: android.view.View),
2323        static fn measureHeight(v: android.view.View) -> jint,
2324        static fn measureHeightForWidth(v: android.view.View, w_px: jint) -> jint,
2325        static fn measureText(text: JString, size: jdouble, weight: jint, italic: jboolean, family: JString) -> JString,
2326        static fn measureWidth(v: android.view.View) -> jint,
2327        static fn mountSettled(),
2328        static fn moveChild(parent: android.view.View, child: android.view.View, index: jint),
2329        static fn nativeBack() -> jboolean,
2330        static fn navLoad(key: JString) -> JString,
2331        static fn navPop(host: android.view.View),
2332        static fn navPush(host: android.view.View, title: JString, immersive: jboolean),
2333        static fn navSave(key: JString, value: JString),
2334        static fn navSetGuard(host: android.view.View, on: jboolean),
2335        static fn navSetTitle(host: android.view.View, title: JString),
2336        static fn navTake(key: JString) -> JString,
2337        static fn openUrl(url: JString),
2338        static fn openWindow(node: jlong, title: JString),
2339        static fn prepareSnapshot(host: android.view.View, revision: jlong) -> jint,
2340        static fn present(req: jlong, sheet: jboolean, title: JString, message: JString, buttons_joined: JString, roles_joined: JString),
2341        static fn presentFileOpen(req: jlong, title: JString, filters_joined: JString, multiple: jboolean),
2342        static fn presentFileSave(req: jlong, title: JString, suggested: JString, src_path: JString, filters_joined: JString),
2343        static fn presentPrompt(req: jlong, title: JString, message: JString, placeholder: JString, initial: JString, ok: JString, cancel: JString),
2344        static fn readNative(v: android.view.View) -> JString[],
2345        static fn reduceMotion() -> jboolean,
2346        static fn removeChild(child: android.view.View),
2347        static fn reorderNavSuite(suite: android.view.View, order: JString),
2348        static fn requestFrame(token: jlong),
2349        static fn scrollToRect(v: android.view.View, x: jint, y: jint, w: jint, h: jint, animated: jboolean),
2350        static fn navScrollToEdge(v: android.view.View, bottom: jboolean) -> jboolean,
2351        static fn setA11y(v: android.view.View, label: JString, hint: JString, value: JString, id: JString, role: jint, level: jint, hidden: jboolean, selected: jint),
2352        static fn setAppBack(on: jboolean),
2353        static fn setAppearance(mode: jint),
2354        static fn setAppMenu(spec: JString),
2355        static fn setButtonContent(view: android.view.View, title: JString, icon_name: JString, icon_only: jboolean),
2356        static fn setButtonSelected(v: android.view.View, on: jboolean),
2357        static fn setButtonStyle(v: android.view.View, kind: jint, argb: jint, fg_argb: jint),
2358        static fn setCanvasOps(v: android.view.View, nums: jdouble[], texts_joined: JString,
2359            geometry: jdouble[]),
2360        static fn setContextMenu(v: android.view.View, spec: JString),
2361        static fn setDragAxis(v: android.view.View, axis: jint),
2362        static fn setHitSlop(v: android.view.View, top: jint, leading: jint, bottom: jint, trailing: jint),
2363        static fn setSubtreeEnabled(root: android.view.View, enabled: jboolean),
2364        static fn primaryPointer() -> JString,
2365        static fn setContextMenuFn(v: android.view.View, token: jlong),
2366        static fn setButtonMenu(v: android.view.View, token: jlong),
2367        static fn releaseContextMenu(v: android.view.View),
2368        static fn setDeferSystemGestures(on: jboolean),
2369        static fn setDocumentTabKeys(menu: android.view.View, keys: JString),
2370        static fn setEnabled(v: android.view.View, b: jboolean),
2371        static fn setFrame(v: android.view.View, x: jint, y: jint, w: jint, h: jint, timing: jint[], keys: jfloat[]),
2372        static fn setViewDirection(v: android.view.View, rtl: jboolean),
2373        static fn textScale(sp: jfloat) -> jfloat,
2374        static fn setImageBitmap(v: android.view.View, id: jlong),
2375        static fn setImageBytes(v: android.view.View, bytes: jbyte[]),
2376        static fn setImageName(v: android.view.View, name: JString),
2377        static fn setImageTint(v: android.view.View, tint: jint),
2378        static fn initImageTint(v: android.view.View, tint: jint),
2379        static fn setInputTraits(v: android.view.View, secure: jboolean, read_only: jboolean, purpose: jint, submit_label: jint),
2380        static fn setLabel(v: android.view.View, text: JString),
2381        static fn setLabelAlignment(view: android.view.View, align: jint),
2382        static fn setLabelColor(v: android.view.View, argb: jint, on: jboolean),
2383        static fn setLabelFont(v: android.view.View, sp: jfloat, weight: jint, italic: jboolean, family: JString, tabular: jboolean),
2384        static fn setLabelRuns(v: android.view.View, node: jlong, text: JString, starts: jint[], ends: jint[], flags: jint[], colors: jint[], backgrounds: jint[], scales: jint[], links_joined: JString, decorations: jint[]),
2385        static fn setLabelSecondary(v: android.view.View, on: jboolean),
2386        static fn setLabelSingleLine(view: android.view.View),
2387        static fn setLabelParagraph(view: android.view.View, max_lines: jint, truncation: jint, letter_spacing: jfloat, line_height: jfloat),
2388        static fn setLabelReportsSelection(view: android.view.View, node: jlong),
2389        static fn setLabelFeatures(view: android.view.View, features: JString),
2390        static fn setLauncherShortcuts(packed: JString),
2391        static fn setListCellHeight(cell: android.view.View, px: jint),
2392        static fn setNavMenuBadges(nav_menu: android.view.View, joined_icons: JString, joined_tints: JString, joined_texts: JString),
2393        static fn setNavMenuSelected(nav_menu: android.view.View, index: jint),
2394        static fn setNavMenuTints(nav_menu: android.view.View, joined_tints: JString),
2395        static fn setNavRefreshing(view: android.view.View, busy: jboolean),
2396        static fn setNavRowMenus(nav_menu: android.view.View, joined_specs: JString),
2397        static fn setNavSearch(nav_host: android.view.View, id: jlong, prompt: JString, text: JString, hides_on_scroll: jboolean, initially_hidden: jboolean),
2398        static fn setNavSearchText(nav_host: android.view.View, text: JString),
2399        static fn setNavSuiteRows(menu: android.view.View, titles: JString, icons: JString, badges: JString, menu_node: jlong),
2400        static fn updateNavMenuRows(v: android.view.View, joined_rows: JString, joined_items: JString, joined_icons: JString),
2401        static fn setNavSuiteSelected(suite: android.view.View, index: jint),
2402        static fn setOpacity(v: android.view.View, alpha: jfloat, timing: jint[], keys: jfloat[]),
2403        static fn setPlaceholder(v: android.view.View, value: JString),
2404        static fn setPrimaryWindowTitle(title: JString),
2405        static fn setProgress(v: android.view.View, fraction: jdouble),
2406        static fn setScrollContent(v: android.view.View, w: jint, h: jint),
2407        static fn setSectionCard(v: android.view.View, radius_px: jfloat),
2408        static fn setSlider(v: android.view.View, value: jdouble, ignored_min: jdouble),
2409        static fn setStatusBarHidden(hidden: jboolean),
2410        static fn setSurface(v: android.view.View, argb: jint, has_bg: jboolean, radius_px: jfloat, clips: jboolean),
2411        static fn setSurfaceFill(v: android.view.View, argb: jint, has_bg: jboolean),
2412        static fn animateSurfaceFill(v: android.view.View, argb: jint, has_bg: jboolean, timing: jint[], keys: jfloat[]),
2413        static fn setSurfaceStyle(v: android.view.View, spec: jdouble[], clips: jboolean),
2414        static fn setSurfaceGradient(v: android.view.View, spec: jdouble[]),
2415        static fn resetSurface(v: android.view.View),
2416        static fn setTextField(v: android.view.View, value: JString),
2417        static fn setTextFieldSelection(v: android.view.View, start: jint, end: jint),
2418        static fn setToggle(v: android.view.View, value: jboolean),
2419        static fn setTransform(v: android.view.View, tx: jfloat, ty: jfloat, sx: jfloat, sy: jfloat, rot: jfloat, timing: jint[], keys: jfloat[]),
2420        static fn readDisplayed(v: android.view.View) -> jdouble[],
2421        static fn setWindowSecure(node: jlong, on: jboolean),
2422        static fn setWindowState(node: jlong, code: jint),
2423        static fn setWindowSurface(v: android.view.View, radius_px: jfloat, clips: jboolean),
2424        static fn setWindowTitle(node: jlong, title: JString),
2425        static fn setWindowToolbar(root: android.view.View, spec: JString),
2426        static fn share(url: JString, title: JString, actions: JString) -> jboolean,
2427        static fn snapshotOrigin(root: android.view.View) -> JString,
2428        static fn treeExpand(view: android.view.View, token: jlong, open: jboolean),
2429        static fn treeReload(view: android.view.View, data: JString),
2430        static fn treeReveal(view: android.view.View, token: jlong),
2431        static fn treeSelection(view: android.view.View),
2432        static fn uiIdle() -> jboolean,
2433        static fn updateNavMenu(v: android.view.View, joined_items: JString, joined_icons: JString, joined_sections: JString),
2434        static fn updateWindowToolbar(root: android.view.View, id: JString, op: jint, num: jdouble),
2435        static fn updateWindowToolbarText(root: android.view.View, id: JString, text: JString),
2436        static fn windowImage(chrome: jboolean) -> jbyte[],
2437            // Read by pieces outside the toolkit (day-piece-crash-reporter's crash store root).
2438            static fn postMain(token: jlong),
2439            static fn postMainDelayed(token: jlong, delay_ms: jlong),
2440        },
2441        // Java's way into Rust, registered when `init` resolves the binding (nativeStart and
2442        // nativeStartWindow stay with the app's `day_start_android!`: they start the app's root).
2443        native_methods {
2444            static fn nativeOnEvent(id: jlong, kind: jint, num: jdouble, text: JString),
2445            static fn nativeHandlesKeys(id: jlong) -> jboolean,
2446            static fn nativeHandlesText(id: jlong) -> jboolean,
2447            static fn nativeContextMenu(token: jlong, x: jfloat, y: jfloat) -> JString,
2448            static fn nativeButtonMenu(token: jlong) -> JString,
2449            static fn nativeRunPosted(token: jlong),
2450            static fn nativeDoFrame(token: jlong, frame_time_nanos: jlong),
2451            static fn nativeListLen(host_id: jlong) -> jint,
2452            static fn nativeListBind(host_id: jlong, position: jint, cell: android.view.View),
2453            static fn nativeListBindPinned(host_id: jlong, position: jint, cell: android.view.View),
2454            static fn nativeListRecycle(host_id: jlong, cell: android.view.View),
2455            static fn nativeListIsSelected(host_id: jlong, position: jint) -> jboolean,
2456            static fn nativeListRowKind(host_id: jlong, position: jint) -> jint,
2457            static fn nativeListViewport(host_id: jlong, first: jint, last: jint, end_px: jint),
2458            static fn nativeListReaderScroll(host_id: jlong),
2459            static fn nativeListHeaderOf(host_id: jlong, position: jint) -> jint,
2460            static fn nativeListCanDrop(host_id: jlong, from: jint, to: jint) -> jboolean,
2461            static fn nativeListMove(host_id: jlong, from: jint, to: jint) -> jboolean,
2462            static fn nativeListCanDelete(host_id: jlong, index: jint) -> jboolean,
2463            static fn nativeListDelete(host_id: jlong, index: jint) -> jboolean,
2464        },
2465    }
2466
2467    /// Android and Java classes the toolkit calls instance methods on, each bound where the
2468    /// method is declared. Platform classes are never shrunk by R8, so their keep rules change
2469    /// nothing; the bindings give the calls types and the startup check a say.
2470    pub(crate) mod framework {
2471        // A list row's standard content (docs/list.md "List items"): DayListItem.java.
2472        crate::java_class! {
2473            pub DayListItem => dev.daybrite.day.bridge.DayListItem,
2474            methods {
2475                static fn make(title: JString, subtitle: JString, detail: JString, icon: JString,
2476                    tint: jint, checked: jboolean) -> android.view.View,
2477                static fn setTexts(v: android.view.View, title: JString, subtitle: JString,
2478                    detail: JString),
2479                static fn setIcon(v: android.view.View, name: JString, tint: jint),
2480                static fn setChecked(v: android.view.View, on: jboolean),
2481            },
2482        }
2483
2484        crate::java_class! {
2485            pub System => java.lang.System,
2486            methods {
2487                static fn identityHashCode(object: JObject) -> jint,
2488            },
2489        }
2490
2491        crate::java_class! {
2492            pub Context => android.content.Context,
2493            methods {
2494                fn getAssets() -> android.content.res.AssetManager,
2495            },
2496        }
2497
2498        crate::java_class! {
2499            pub View => android.view.View,
2500            methods {
2501                fn getWidth() -> jint,
2502                fn setPointerIcon(icon: android.view.PointerIcon),
2503            },
2504        }
2505
2506        crate::java_class! {
2507            pub TextView => android.widget.TextView,
2508            methods {
2509                fn setTextIsSelectable(selectable: jboolean),
2510            },
2511        }
2512
2513        crate::java_class! {
2514            pub PointerIcon => android.view.PointerIcon,
2515            methods {
2516                static fn getSystemIcon(context: android.content.Context, kind: jint)
2517                    -> android.view.PointerIcon,
2518            },
2519        }
2520    }
2521
2522    // DayTransfer (java/dev/daybrite/day/bridge/DayTransfer.java): drag-and-drop sources and
2523    // targets (docs/drag-and-drop.md).
2524    crate::java_class! {
2525        DayTransfer => dev.daybrite.day.bridge.DayTransfer,
2526        methods {
2527            static fn source(view: android.view.View, token: jlong),
2528            static fn target(view: android.view.View, token: jlong),
2529            static fn release(view: android.view.View),
2530        },
2531        native_methods {
2532            static fn nativeCall(kind: jint, token: jlong, x: jdouble, y: jdouble, bytes: jbyte[],
2533                local: jboolean) -> jbyte[],
2534        },
2535    }
2536
2537    // DayCanvasView (java/dev/daybrite/day/bridge/DayCanvasView.java): the canvas exports, which
2538    // paint with the OpPainter the view's own onDraw uses (docs/canvas.md "Exporting").
2539    crate::java_class! {
2540        DayCanvasView => dev.daybrite.day.bridge.DayCanvasView,
2541        methods {
2542            static fn exportError() -> JString,
2543            static fn renderBitmap(id: jlong, nums: jdouble[], texts_joined: JString,
2544                geometry: jdouble[], pw: jint, ph: jint, scale: jdouble) -> JString,
2545            static fn renderPdf(nums: jdouble[], num_counts: jint[], texts_joined: JString,
2546                text_counts: jint[], sizes: jdouble[]) -> jbyte[],
2547        },
2548    }
2549
2550    /// The natives `DayBridge` declares, each forwarding to the function that does the work.
2551    /// jni's wrapper around each catches a panic and logs a returned error, so none of these
2552    /// can unwind into the JVM.
2553    impl DayBridgeNativeInterface for DayBridgeAPI {
2554        type Error = jni::errors::Error;
2555
2556        fn nativeOnEvent<'l>(
2557            env: &mut Env<'l>,
2558            _class: JClass<'l>,
2559            id: i64,
2560            kind: i32,
2561            num: f64,
2562            text: JString<'l>,
2563        ) -> Result<(), Self::Error> {
2564            dispatch_event(env, id, kind, num, &text);
2565            Ok(())
2566        }
2567
2568        fn nativeContextMenu<'l>(
2569            env: &mut Env<'l>,
2570            _class: JClass<'l>,
2571            token: i64,
2572            x: f32,
2573            y: f32,
2574        ) -> Result<JString<'l>, Self::Error> {
2575            let spec = day_spec::ffi_guard::contain(String::new(), || {
2576                // Clone before calling app code: a provider may replace or release its view.
2577                let provider = CONTEXT_MENU_FNS.with(|menus| menus.get(token as usize));
2578                let mut spec = String::new();
2579                if let Some(provider) = provider {
2580                    let items = provider(Point {
2581                        x: f64::from(x) / density(),
2582                        y: f64::from(y) / density(),
2583                    });
2584                    serialize_menu(&items, &mut spec);
2585                }
2586                spec
2587            });
2588            env.new_string(spec)
2589        }
2590
2591        fn nativeButtonMenu<'l>(
2592            env: &mut Env<'l>,
2593            _class: JClass<'l>,
2594            token: i64,
2595        ) -> Result<JString<'l>, Self::Error> {
2596            let spec = day_spec::ffi_guard::contain(String::new(), || {
2597                // Cloned before the call: the provider is app code and may release its button.
2598                let provider = BUTTON_MENU_FNS.with(|menus| menus.get(token as usize));
2599                let mut spec = String::new();
2600                if let Some(provider) = provider {
2601                    // The provider may remove its button; then no menu opens (docs/menus.md).
2602                    let still = || {
2603                        BUTTON_MENU_FNS
2604                            .with(|menus| menus.get(token as usize))
2605                            .is_some()
2606                    };
2607                    if let Some(items) = day_spec::resolve_button_menu(&provider, still) {
2608                        serialize_menu(&items, &mut spec);
2609                    }
2610                }
2611                spec
2612            });
2613            env.new_string(spec)
2614        }
2615
2616        fn nativeHandlesKeys<'l>(
2617            _env: &mut Env<'l>,
2618            _class: JClass<'l>,
2619            id: i64,
2620        ) -> Result<bool, Self::Error> {
2621            Ok(handles_keys(id))
2622        }
2623
2624        fn nativeHandlesText<'l>(
2625            _env: &mut Env<'l>,
2626            _class: JClass<'l>,
2627            id: i64,
2628        ) -> Result<bool, Self::Error> {
2629            Ok(handles_text(id))
2630        }
2631
2632        fn nativeRunPosted<'l>(
2633            _env: &mut Env<'l>,
2634            _class: JClass<'l>,
2635            token: i64,
2636        ) -> Result<(), Self::Error> {
2637            run_posted(token);
2638            Ok(())
2639        }
2640
2641        fn nativeDoFrame<'l>(
2642            _env: &mut Env<'l>,
2643            _class: JClass<'l>,
2644            token: i64,
2645            frame_time_nanos: i64,
2646        ) -> Result<(), Self::Error> {
2647            run_frame(token, frame_time_nanos);
2648            Ok(())
2649        }
2650
2651        fn nativeListLen<'l>(
2652            _env: &mut Env<'l>,
2653            _class: JClass<'l>,
2654            host_id: i64,
2655        ) -> Result<i32, Self::Error> {
2656            Ok(i32::try_from(list_len(host_id)).unwrap_or(i32::MAX))
2657        }
2658
2659        fn nativeListBind<'l>(
2660            env: &mut Env<'l>,
2661            _class: JClass<'l>,
2662            host_id: i64,
2663            position: i32,
2664            cell: JObject<'l>,
2665        ) -> Result<(), Self::Error> {
2666            list_bind(env, host_id, position, cell, false);
2667            Ok(())
2668        }
2669
2670        fn nativeListBindPinned<'l>(
2671            env: &mut Env<'l>,
2672            _class: JClass<'l>,
2673            host_id: i64,
2674            position: i32,
2675            cell: JObject<'l>,
2676        ) -> Result<(), Self::Error> {
2677            list_bind(env, host_id, position, cell, true);
2678            Ok(())
2679        }
2680
2681        fn nativeListRecycle<'l>(
2682            env: &mut Env<'l>,
2683            _class: JClass<'l>,
2684            host_id: i64,
2685            cell: JObject<'l>,
2686        ) -> Result<(), Self::Error> {
2687            list_recycle(env, host_id, cell);
2688            Ok(())
2689        }
2690
2691        fn nativeListIsSelected<'l>(
2692            _env: &mut Env<'l>,
2693            _class: JClass<'l>,
2694            host_id: i64,
2695            position: i32,
2696        ) -> Result<bool, Self::Error> {
2697            Ok(list_is_selected(host_id, position))
2698        }
2699
2700        fn nativeListRowKind<'l>(
2701            _env: &mut Env<'l>,
2702            _class: JClass<'l>,
2703            host_id: i64,
2704            position: i32,
2705        ) -> Result<i32, Self::Error> {
2706            Ok(list_row_kind(host_id, position))
2707        }
2708
2709        fn nativeListViewport<'l>(
2710            _env: &mut Env<'l>,
2711            _class: JClass<'l>,
2712            host_id: i64,
2713            first: i32,
2714            last: i32,
2715            end_px: i32,
2716        ) -> Result<(), Self::Error> {
2717            list_viewport(host_id, first, last, end_px);
2718            Ok(())
2719        }
2720
2721        fn nativeListReaderScroll<'l>(
2722            _env: &mut Env<'l>,
2723            _class: JClass<'l>,
2724            host_id: i64,
2725        ) -> Result<(), Self::Error> {
2726            list_reader_scroll(host_id);
2727            Ok(())
2728        }
2729
2730        fn nativeListHeaderOf<'l>(
2731            _env: &mut Env<'l>,
2732            _class: JClass<'l>,
2733            host_id: i64,
2734            position: i32,
2735        ) -> Result<i32, Self::Error> {
2736            Ok(list_header_of(host_id, position))
2737        }
2738
2739        fn nativeListCanDrop<'l>(
2740            _env: &mut Env<'l>,
2741            _class: JClass<'l>,
2742            host_id: i64,
2743            from: i32,
2744            to: i32,
2745        ) -> Result<bool, Self::Error> {
2746            Ok(list_can_drop(host_id, from, to))
2747        }
2748
2749        fn nativeListMove<'l>(
2750            _env: &mut Env<'l>,
2751            _class: JClass<'l>,
2752            host_id: i64,
2753            from: i32,
2754            to: i32,
2755        ) -> Result<bool, Self::Error> {
2756            Ok(list_move(host_id, from, to))
2757        }
2758
2759        fn nativeListCanDelete<'l>(
2760            _env: &mut Env<'l>,
2761            _class: JClass<'l>,
2762            host_id: i64,
2763            index: i32,
2764        ) -> Result<bool, Self::Error> {
2765            Ok(list_can_delete(host_id, index))
2766        }
2767
2768        fn nativeListDelete<'l>(
2769            _env: &mut Env<'l>,
2770            _class: JClass<'l>,
2771            host_id: i64,
2772            index: i32,
2773        ) -> Result<bool, Self::Error> {
2774            Ok(list_delete(host_id, index))
2775        }
2776    }
2777
2778    impl DayTransferNativeInterface for DayTransferAPI {
2779        type Error = jni::errors::Error;
2780
2781        #[allow(clippy::too_many_arguments)]
2782        fn nativeCall<'l>(
2783            env: &mut Env<'l>,
2784            _class: JClass<'l>,
2785            kind: i32,
2786            token: i64,
2787            x: f64,
2788            y: f64,
2789            bytes: jni::objects::JByteArray<'l>,
2790            local: bool,
2791        ) -> Result<jni::objects::JByteArray<'l>, Self::Error> {
2792            transfer_call(env, kind, token, x, y, bytes, local)
2793        }
2794    }
2795
2796    #[derive(Clone)]
2797    pub struct AHandle(pub Gref);
2798
2799    // --- Bundled data resources via the NDK AAssetManager (§18.3) --------------------------------
2800    // `resource("name")` reads the APK asset `name` with a zero-copy pointer into the (uncompressed)
2801    // asset via AAsset_getBuffer, the native AssetManager path the user asked for.
2802    #[allow(non_camel_case_types)]
2803    mod aasset {
2804        use std::os::raw::{c_char, c_int, c_void};
2805        pub enum AAssetManager {}
2806        pub enum AAsset {}
2807        pub const AASSET_MODE_BUFFER: c_int = 3;
2808        #[link(name = "android")]
2809        unsafe extern "C" {
2810            pub fn AAssetManager_fromJava(
2811                env: *mut jni::sys::JNIEnv,
2812                mgr: jni::sys::jobject,
2813            ) -> *mut AAssetManager;
2814            pub fn AAssetManager_open(
2815                mgr: *mut AAssetManager,
2816                filename: *const c_char,
2817                mode: c_int,
2818            ) -> *mut AAsset;
2819            pub fn AAsset_getBuffer(asset: *mut AAsset) -> *const c_void;
2820            pub fn AAsset_getLength64(asset: *mut AAsset) -> i64;
2821            pub fn AAsset_close(asset: *mut AAsset);
2822        }
2823    }
2824
2825    /// The app's `AAssetManager` plus a `GlobalRef` to the Java `AssetManager` that keeps it alive.
2826    struct AssetMgr {
2827        aam: *mut aasset::AAssetManager,
2828        _keepalive: Global<JObject<'static>>,
2829    }
2830    // The AAssetManager pointer is valid for the app lifetime; resource() runs on the main thread.
2831    unsafe impl Send for AssetMgr {}
2832    unsafe impl Sync for AssetMgr {}
2833    static ASSET_MGR: OnceLock<AssetMgr> = OnceLock::new();
2834
2835    /// Capture the `AAssetManager` from `DayBridge.ctx.getAssets()` and register the opener (init).
2836    fn register_resource_opener(env: &mut Env) {
2837        // Held globally: the native manager is valid only while its Java one is reachable.
2838        let Some(keepalive) = java_in(env, |env| {
2839            let ctx = DayRuntime::ctx(env)?;
2840            // SAFETY: `DayBridge.ctx` is declared `android.content.Context`.
2841            let am = unsafe { env.as_cast_unchecked::<framework::Context>(&ctx) }.getAssets(env)?;
2842            env.new_global_ref(am)
2843        }) else {
2844            return;
2845        };
2846        let aam =
2847            unsafe { aasset::AAssetManager_fromJava(env.get_raw(), keepalive.as_obj().as_raw()) };
2848        if aam.is_null() {
2849            return;
2850        }
2851        let _ = ASSET_MGR.set(AssetMgr {
2852            aam,
2853            _keepalive: keepalive,
2854        });
2855        day_spec::resource::set_resource_opener(open_resource);
2856    }
2857
2858    /// Opener: `resource("name")` -> the APK asset `name`, zero-copy from `AAsset_getBuffer`.
2859    fn open_resource(name: &str) -> Option<day_spec::resource::Resource> {
2860        struct AssetGuard(*mut aasset::AAsset);
2861        impl Drop for AssetGuard {
2862            fn drop(&mut self) {
2863                unsafe { aasset::AAsset_close(self.0) };
2864            }
2865        }
2866        let mgr = ASSET_MGR.get()?.aam;
2867        let cname = std::ffi::CString::new(name).ok()?;
2868        let asset =
2869            unsafe { aasset::AAssetManager_open(mgr, cname.as_ptr(), aasset::AASSET_MODE_BUFFER) };
2870        if asset.is_null() {
2871            return None;
2872        }
2873        let len = unsafe { aasset::AAsset_getLength64(asset) };
2874        let ptr = unsafe { aasset::AAsset_getBuffer(asset) }.cast::<u8>();
2875        if ptr.is_null() || len < 0 {
2876            unsafe { aasset::AAsset_close(asset) };
2877            return None;
2878        }
2879        // Safety: `ptr`/`len` are the asset's buffer, valid until AAsset_close (held by the guard).
2880        Some(unsafe {
2881            day_spec::resource::Resource::from_raw(ptr, len as usize, Box::new(AssetGuard(asset)))
2882        })
2883    }
2884
2885    /// The day-core event sink (node-id keyed).
2886    type Sink = Rc<dyn Fn(NodeId, Event)>;
2887
2888    pub fn emit(id: NodeId, ev: Event) {
2889        let sink = SINK.with(|s| s.borrow().clone());
2890        if let Some(sink) = sink {
2891            sink(id, ev);
2892        }
2893    }
2894
2895    fn density() -> f64 {
2896        DENSITY.with(std::cell::Cell::get)
2897    }
2898
2899    /// Run with an attached `Env` (public: external renderers use this too). jni 0.22's
2900    /// `attach_current_thread` is callback-scoped; the callback returns `Ok` so the outer
2901    /// `Result` just unwraps.
2902    /// `PointerIcon.TYPE_*` for a [`Cursor`] (docs/cursor.md): the full CSS vocabulary has a
2903    /// system icon on Android, so nothing here approximates. `None` releases the view.
2904    fn pointer_icon_type(c: &Cursor) -> Option<i32> {
2905        Some(match c {
2906            Cursor::Default => return None,
2907            Cursor::Pointer => 1002,
2908            Cursor::Text => 1008,
2909            Cursor::VerticalText => 1009,
2910            Cursor::Crosshair => 1007,
2911            Cursor::Move => 1013,
2912            Cursor::Grab => 1020,
2913            Cursor::Grabbing => 1021,
2914            Cursor::NotAllowed => 1012,
2915            Cursor::Wait | Cursor::Progress => 1004,
2916            Cursor::Help => 1003,
2917            Cursor::ContextMenu => 1001,
2918            Cursor::Copy => 1011,
2919            Cursor::Alias => 1010,
2920            Cursor::Cell => 1006,
2921            Cursor::ZoomIn => 1018,
2922            Cursor::ZoomOut => 1019,
2923            Cursor::None => 0,
2924            Cursor::NsResize | Cursor::RowResize => 1015,
2925            Cursor::EwResize | Cursor::ColResize => 1014,
2926            Cursor::NeswResize => 1016,
2927            Cursor::NwseResize => 1017,
2928            Cursor::Native(name) => match &**name {
2929                "all_scroll" => 1013,
2930                "no_drop" => 1012,
2931                "top_right_diagonal_double_arrow" => 1016,
2932                "top_left_diagonal_double_arrow" => 1017,
2933                _ => return None,
2934            },
2935        })
2936    }
2937
2938    /// A View returned by a Java factory, as a Day handle: `Err` for a null View, which a
2939    /// factory returns when it could not build one.
2940    ///
2941    /// # Errors
2942    ///
2943    /// Returns [`jni::errors::Error::NullPtr`] for a null View, and the JNI error when no
2944    /// global reference to the View can be made.
2945    pub fn view_handle(env: &mut Env, view: JObject) -> jni::errors::Result<AHandle> {
2946        if view.is_null() {
2947            return Err(jni::errors::Error::NullPtr("factory returned a null View"));
2948        }
2949        Ok(AHandle(std::sync::Arc::new(env.new_global_ref(view)?)))
2950    }
2951
2952    /// A piece's native view, made by a Java factory through a [`java_class!`](crate::java_class)
2953    /// binding: the factory's View as a Day handle, or, when the factory throws or returns null,
2954    /// the visible `⟨what⟩` placeholder. A failed make must not panic inside realize: the panic
2955    /// would unwind through a JNI up-call and abort the process.
2956    ///
2957    /// ```ignore
2958    /// day_toolkit_material::realize("activity", |env| DayActivity::makeActivity(env, true, false))
2959    /// ```
2960    pub fn realize<F>(what: &str, make: F) -> AHandle
2961    where
2962        F: for<'a, 'l> FnOnce(&'a mut Env<'l>) -> jni::errors::Result<JObject<'l>>,
2963    {
2964        java(|env| {
2965            let view = make(env)?;
2966            view_handle(env, view)
2967        })
2968        .unwrap_or_else(|| {
2969            log::warn!(
2970                "day-toolkit-material: {what}: the Java factory failed; substituting a placeholder"
2971            );
2972            AHandle(with_env(|env| placeholder_view(env, what)))
2973        })
2974    }
2975
2976    /// Pack a color the way `android.graphics.Color` wants it (`0xAARRGGBB`, as a signed int).
2977    #[must_use]
2978    pub fn argb(c: day_spec::Color) -> i32 {
2979        let f = |v: f64| (v.clamp(0.0, 1.0) * 255.0) as u32;
2980        ((f(c.a) << 24) | (f(c.r) << 16) | (f(c.g) << 8) | f(c.b)) as i32
2981    }
2982
2983    fn apply_button_content(
2984        env: &mut Env,
2985        view: &Gref,
2986        title: &str,
2987        icon: Option<&day_spec::Icon>,
2988        icon_only: bool,
2989    ) {
2990        let title = jstr(env, title);
2991        let icon = jstr(env, &icon_name(icon));
2992        let _ = java_in(env, |env| {
2993            DayBridge::setButtonContent(env, view.as_obj(), &title, &icon, icon_only)
2994        });
2995    }
2996
2997    /// Style a button in place through the bridge. The view stays a `MaterialButton`, so its
2998    /// ripple, state overlays, focus and accessibility role are Material's, not ours.
2999    pub fn apply_button_style(env: &mut Env, v: &Gref, style: day_spec::props::ButtonStyleSpec) {
3000        use day_spec::props::ButtonStyleSpec as S;
3001        let (kind, fill) = match style {
3002            S::Automatic => (0, day_spec::Color::CLEAR),
3003            S::Bordered => (1, day_spec::Color::CLEAR),
3004            S::Prominent => (2, day_spec::Color::CLEAR),
3005            S::Tinted(c) => (3, c.resolved()),
3006            // Kind 4 drops Material's 88 dp minimum width and its wide insets (docs/buttons.md).
3007            S::Compact => (4, day_spec::Color::CLEAR),
3008            S::Plain => (5, day_spec::Color::CLEAR),
3009        };
3010        let _ = java_in(env, |env| {
3011            DayBridge::setButtonStyle(env, v.as_obj(), kind, argb(fill), argb(S::on_tint(fill)))
3012        });
3013    }
3014
3015    /// Send a label's text + runs across in one call (docs/text-runs.md).
3016    ///
3017    /// Offsets convert from Rust BYTES to Java's UTF-16 indices here, per run: any emoji or CJK
3018    /// in the string makes the two disagree, and an off-by-N range styles the wrong words.
3019    pub fn set_label_runs(
3020        env: &mut Env,
3021        node: i64,
3022        v: &Gref,
3023        text: &str,
3024        runs: &[day_spec::TextRun],
3025    ) {
3026        // Flat parallel arrays: one JNI call rather than one per run, on a path that runs for
3027        // every label patch.
3028        let mut starts = Vec::with_capacity(runs.len());
3029        let mut ends = Vec::with_capacity(runs.len());
3030        let mut flags = Vec::with_capacity(runs.len());
3031        let mut colors = Vec::with_capacity(runs.len());
3032        let mut backgrounds = Vec::with_capacity(runs.len());
3033        // Relative size, in per-mille: an int array so it rides the same cheap `set_region`
3034        // path as the rest rather than needing a float array of its own.
3035        let mut scales = Vec::with_capacity(runs.len());
3036        let mut links: Vec<Option<String>> = Vec::with_capacity(runs.len());
3037        // The lines Android has no span for, five ints each (`DayLabel.DECO_STRIDE`).
3038        let mut decorations = Vec::new();
3039        for r in runs {
3040            let Some(slice) = text.get(r.range.clone()) else {
3041                continue;
3042            };
3043            let start = text[..r.range.start].encode_utf16().count() as i32;
3044            let end = start + slice.encode_utf16().count() as i32;
3045            starts.push(start);
3046            ends.push(end);
3047            let f = crate::text_wire::run_flags(r);
3048            crate::text_wire::decoration_entries(r, start, end, &mut decorations);
3049            flags.push(f);
3050            colors.push(r.color.map_or(0, |c| argb(c.resolved())));
3051            backgrounds.push(r.background.map_or(0, |c| argb(c.resolved())));
3052            scales.push((r.font.scale * 1000.0).round() as i32);
3053            links.push(r.link.clone());
3054        }
3055        let (Ok(sa), Ok(se), Ok(sf), Ok(sc), Ok(sb), Ok(sz), Ok(sd)) = (
3056            env.new_int_array(starts.len()),
3057            env.new_int_array(ends.len()),
3058            env.new_int_array(flags.len()),
3059            env.new_int_array(colors.len()),
3060            env.new_int_array(backgrounds.len()),
3061            env.new_int_array(scales.len()),
3062            env.new_int_array(decorations.len()),
3063        ) else {
3064            return;
3065        };
3066        if sa.set_region(env, 0, &starts).is_err()
3067            || se.set_region(env, 0, &ends).is_err()
3068            || sf.set_region(env, 0, &flags).is_err()
3069            || sc.set_region(env, 0, &colors).is_err()
3070            || sb.set_region(env, 0, &backgrounds).is_err()
3071            || sz.set_region(env, 0, &scales).is_err()
3072            || sd.set_region(env, 0, &decorations).is_err()
3073        {
3074            return;
3075        }
3076        // Link targets ride one joined string, as the canvas op stream already does: a Java
3077        // object array through JNI costs a class lookup and a per-element store for a payload
3078        // that is empty in almost every label.
3079        let joined = links
3080            .iter()
3081            .map(|l| l.clone().unwrap_or_default())
3082            .collect::<Vec<_>>()
3083            .join("\u{1f}");
3084        let s = jstr(env, text);
3085        let jl = jstr(env, &joined);
3086        let _ = java_in(env, |env| {
3087            DayBridge::setLabelRuns(
3088                env,
3089                v.as_obj(),
3090                node,
3091                &s,
3092                &sa,
3093                &se,
3094                &sf,
3095                &sc,
3096                &sb,
3097                &sz,
3098                &jl,
3099                &sd,
3100            )
3101        });
3102    }
3103
3104    /// A View from a `DayBridge` factory, or the visible `⟨what⟩` placeholder when the factory
3105    /// throws or returns null (degrade loudly, keep the tree building).
3106    fn bridge_view<F>(env: &mut Env, what: &str, make: F) -> Gref
3107    where
3108        F: for<'a, 'l> FnOnce(&'a mut Env<'l>) -> jni::errors::Result<JObject<'l>>,
3109    {
3110        match try_bridge_view(env, make) {
3111            Ok(g) => g,
3112            Err(e) => {
3113                log::warn!(
3114                    "day-toolkit-material: DayBridge.{what} failed ({e}); substituting a placeholder view"
3115                );
3116                placeholder_view(env, what)
3117            }
3118        }
3119    }
3120
3121    /// [`bridge_view`] without the placeholder: `Err` on a Java throw (described and cleared) or
3122    /// a null View.
3123    fn try_bridge_view<F>(env: &mut Env, make: F) -> Result<Gref, jni::errors::Error>
3124    where
3125        F: for<'a, 'l> FnOnce(&'a mut Env<'l>) -> jni::errors::Result<JObject<'l>>,
3126    {
3127        let made = match make(env) {
3128            Ok(view) => view_handle(env, view).map(|h| h.0),
3129            Err(e) => Err(e),
3130        };
3131        if made.is_err() && env.exception_check() {
3132            env.exception_describe();
3133            env.exception_clear();
3134        }
3135        made
3136    }
3137
3138    /// The visible stand-in for a native make that failed: the same `⟨name⟩` label the
3139    /// missing-renderer path shows (degrade loudly, keep the tree building).
3140    ///
3141    /// # Panics
3142    ///
3143    /// Panics when `DayBridge.makeLabel` itself fails, which means the bridge is not staged
3144    /// and nothing can render.
3145    pub fn placeholder_view(env: &mut Env, what: &str) -> Gref {
3146        let text = format!("⟨{what}⟩");
3147        try_bridge_view(env, |env| {
3148            let text = JString::from_str(env, &text)?;
3149            DayBridge::makeLabel(env, &text)
3150        })
3151        // The bridge itself cannot build a plain label: nothing can render. Aborting
3152        // here is warranted, and it is the only remaining panic on this path.
3153        .expect("day-toolkit-material: DayBridge.makeLabel unavailable — bridge not staged?")
3154    }
3155
3156    /// One `DayBridge` call made for its effect, inside [`java`]: a throw is logged and cleared.
3157    fn bridge(call: impl FnOnce(&mut Env) -> jni::errors::Result<()>) {
3158        let _ = java(call);
3159    }
3160
3161    /// An `AnimSpec` as the bridge's animation arguments (`motion_wire`): the timing `int[]`
3162    /// and the cycle's sampled curve as a `float[]`. `None` is all zeros and no samples, which
3163    /// `DayBridge` applies at once, ending any run on that property.
3164    fn anim_arrays<'local>(
3165        env: &mut Env<'local>,
3166        anim: Option<&AnimSpec>,
3167    ) -> jni::errors::Result<(
3168        jni::objects::JIntArray<'local>,
3169        jni::objects::JFloatArray<'local>,
3170    )> {
3171        let timing = crate::motion_wire::timing(anim);
3172        let keys = crate::motion_wire::keys(anim);
3173        let t = env.new_int_array(timing.len())?;
3174        t.set_region(env, 0, &timing)?;
3175        let k = env.new_float_array(keys.len())?;
3176        k.set_region(env, 0, &keys)?;
3177        Ok((t, k))
3178    }
3179
3180    /// Apply a `background`/`corner_radius` surface: a rounded `GradientDrawable` background +
3181    /// `clipToOutline`. The radius is density-scaled here (Java takes px). Idempotent; used at
3182    /// realize and on a reactive background patch.
3183    fn apply_surface(h: &AHandle, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
3184        let d = DENSITY.with(std::cell::Cell::get);
3185        bridge(|env| {
3186            DayBridge::setSurface(
3187                env,
3188                h.0.as_obj(),
3189                bg.map_or(0, argb_i32),
3190                bg.is_some(),
3191                (corner_radius * d) as f32,
3192                clips,
3193            )
3194        });
3195    }
3196
3197    /// Apply a surface with a gradient, a border, named corners or a shadow
3198    /// (docs/surfaces.md): the container draws it itself, from [`super::surface_spec`].
3199    fn apply_styled_surface(h: &AHandle, p: &ContainerProps) {
3200        let spec = super::surface_spec(p, DENSITY.with(std::cell::Cell::get));
3201        bridge(|env| {
3202            let arr = env.new_double_array(spec.len())?;
3203            arr.set_region(env, 0, &spec)?;
3204            DayBridge::setSurfaceStyle(env, h.0.as_obj(), &arr, p.clips)
3205        });
3206    }
3207
3208    /// A container's surface from its props, at realize (`fresh`) and again for every
3209    /// `ContainerPatch::Surface`: the styled path for a gradient, a border, named corners or a
3210    /// shadow, the plain `GradientDrawable` path for the rest. On a patch,
3211    /// `DayBridge.resetSurface` first clears what the previous style left (a drawable, an
3212    /// outline clip, a self-drawn surface), so a surface moves between the two paths in place.
3213    fn apply_container_surface(h: &AHandle, p: &ContainerProps, fresh: bool) {
3214        if !fresh {
3215            bridge(|env| DayBridge::resetSurface(env, h.0.as_obj()));
3216        }
3217        if super::is_styled_surface(p) {
3218            apply_styled_surface(h, p);
3219        } else if p.fill.is_some() || p.corner_radius > 0.0 || p.clips {
3220            apply_surface(
3221                h,
3222                super::solid_fill(p.fill.as_ref()),
3223                p.corner_radius,
3224                p.clips,
3225            );
3226        }
3227    }
3228
3229    /// A `DayBridge` measurement of `h`'s View, in px. Runs inside the layout pass (a JNI
3230    /// up-call): a Java throw degrades to a zero measurement, never a panic-abort.
3231    fn measure_call<F>(h: &AHandle, measure: F) -> f64
3232    where
3233        F: for<'a, 'l> FnOnce(&'a mut Env<'l>, &JObject) -> jni::errors::Result<i32>,
3234    {
3235        f64::from(java(|env| measure(env, h.0.as_obj())).unwrap_or(0))
3236    }
3237
3238    /// Initialize globals from the Activity's nativeStart (called by `day::android_start`).
3239    /// A JNI up-call entry: contained, so a startup failure logs instead of aborting.
3240    pub fn init(env: &mut Env, root: JObject, density_: f32, w: i32, h: i32) {
3241        day_spec::ffi_guard::contain((), || {
3242            // A re-mount (docs/settings.md "Appearance on Android"): an activity recreation
3243            // calls this a second time with a brand-new view hierarchy. Everything below maps a native view pointer (or a
3244            // host id) to something owned by the tree that is going away, and `LIST_SOURCES` in
3245            // particular holds closures that captured the previous mount's state. Left in place,
3246            // a callback from a stale view (or a recycled pointer that now means something else)
3247            // dispatches into the old graph and reads signals that were disposed with it.
3248            //
3249            // Cleared unconditionally rather than behind a "did we already start" flag: `init`
3250            // means "a tree is being mounted here", and on a first launch these are empty anyway.
3251            LIST_SOURCES.with(|m| m.borrow_mut().clear());
3252            LIST_NODE.with(|m| m.borrow_mut().clear());
3253            LIST_CELLS.with(|m| m.borrow_mut().clear());
3254            LIST_BINDINGS.with(|m| m.borrow_mut().clear());
3255            LIST_SELECTED.with(|m| m.borrow_mut().clear());
3256            LIST_AUTOMATIC.with(|m| m.borrow_mut().clear());
3257            NAV_MENU_ROWS.with(|m| m.borrow_mut().clear());
3258            NAV_SUITES.with(|m| m.borrow_mut().clear());
3259            WINDOW_BARS.with(|m| m.borrow_mut().clear());
3260            LABEL_NODE.with(|m| m.borrow_mut().clear());
3261            // Secondary windows do not survive the primary's recreation: their activities were
3262            // torn down with it, so the day-side records are stale global refs.
3263            SECONDARY.with(|m| m.borrow_mut().clear());
3264            if java_in(env, |env| {
3265                let class = env.find_class(jni::jni_str!("dev/daybrite/day/bridge/DayRuntime"))?;
3266                day_platform_android::init(env, &class)
3267            })
3268            .is_none()
3269            {
3270                return;
3271            }
3272            day_process::services::initialize();
3273            register_resource_opener(env);
3274            let d = f64::from(density_);
3275            DENSITY.with(|x| x.set(d));
3276            // Only fails when the JNI global-ref table is already exhausted; without a root
3277            // there is nothing to run, so degrade loudly rather than panic-abort the up-call.
3278            let Ok(root_ref) = env.new_global_ref(root) else {
3279                log::error!(
3280                    "day-toolkit-material: init could not take a global ref on the root view"
3281                );
3282                return;
3283            };
3284            let handle = AHandle(std::sync::Arc::new(root_ref));
3285            let size = Size::new(f64::from(w) / d, f64::from(h) / d);
3286            ROOT.with(|r| *r.borrow_mut() = Some((handle, size)));
3287            // Android's OS temp dir isn't app-writable; use the app cache dir for the file-save
3288            // staging area (docs/files.md) so `save_file(..)` can write its temp before handing
3289            // off to SAF.
3290            if let Some(path) = java_in(env, |env| {
3291                let dir = DayRuntime::cacheDirPath(env)?;
3292                string_of(env, &dir)
3293            }) && !path.is_empty()
3294            {
3295                day_spec::present::set_app_temp_dir(path);
3296            }
3297        });
3298    }
3299
3300    /// A secondary `DayWindowActivity`'s first laid-out root (the `nativeStartWindow` JNI
3301    /// export lands here): adopt it as the parked day window's content
3302    /// (docs/windows.md). `false` ⇒ the window was closed before the activity finished
3303    /// connecting, and the activity finishes itself.
3304    #[expect(
3305        clippy::needless_pass_by_value,
3306        reason = "public signature; the JNI entry hands over the root's local reference"
3307    )]
3308    pub fn window_started(env: &mut Env, root: JObject, node: i64, w: i32, h: i32) -> bool {
3309        // JNI up-call entry (nativeStartWindow): contain the adoption + day-core completion.
3310        day_spec::ffi_guard::contain(false, || {
3311            let d = DENSITY.with(std::cell::Cell::get);
3312            let Ok(gref) = env.new_global_ref(&root) else {
3313                return false;
3314            };
3315            let gref = std::sync::Arc::new(gref);
3316            let raw = gref.as_obj().as_raw() as day_spec::RawHandle;
3317            SECONDARY.with(|s| s.borrow_mut().push((node as u64, gref)));
3318            let ok = day_core::finish_window_open(
3319                day_spec::NodeId(node as u64),
3320                raw,
3321                Size::new(f64::from(w) / d, f64::from(h) / d),
3322            );
3323            if !ok {
3324                SECONDARY.with(|s| s.borrow_mut().retain(|(n, _)| *n != node as u64));
3325            }
3326            ok
3327        })
3328    }
3329
3330    /// The day node of the secondary window whose adopted content is `host`, if any.
3331    fn secondary_node_of(env: &mut Env, host: &AHandle) -> Option<u64> {
3332        SECONDARY.with(|s| {
3333            s.borrow()
3334                .iter()
3335                .find(|(_, gref)| {
3336                    env.is_same_object(host.0.as_obj(), gref.as_obj())
3337                        .unwrap_or(false)
3338                })
3339                .map(|(n, _)| *n)
3340        })
3341    }
3342
3343    // The wire table (day_spec::bridge) as const match patterns; the Java side's K_* constants
3344    // mirror these, and day-toolkit-material's parity test holds the two files together.
3345    const K_PRESSED: i32 = bridge::BridgeKind::Pressed as i32;
3346    const K_TEXT_CHANGED: i32 = bridge::BridgeKind::TextChanged as i32;
3347    const K_TOGGLE_CHANGED: i32 = bridge::BridgeKind::ToggleChanged as i32;
3348    const K_VALUE_CHANGED: i32 = bridge::BridgeKind::ValueChanged as i32;
3349    const K_VALUE_COMMITTED: i32 = bridge::BridgeKind::ValueCommitted as i32;
3350    const K_SEARCH_CHANGED: i32 = bridge::BridgeKind::SearchChanged as i32;
3351    const K_NAV_PRESENTATION: i32 = bridge::BridgeKind::NavPresentation as i32;
3352    const K_LIST_ACTIVATED: i32 = bridge::BridgeKind::ListActivated as i32;
3353    const K_SELECTION_CHANGED: i32 = bridge::BridgeKind::SelectionChanged as i32;
3354    const K_NAV_BACK: i32 = bridge::BridgeKind::NavBack as i32;
3355    const K_FRAME_CHANGED: i32 = bridge::BridgeKind::FrameChanged as i32;
3356    const K_DEEPLINK: i32 = bridge::BridgeKind::Deeplink as i32;
3357    const K_PRESENT_BUTTON: i32 = bridge::BridgeKind::PresentButton as i32;
3358    const K_PRESENT_TEXT: i32 = bridge::BridgeKind::PresentText as i32;
3359    const K_PRESENT_DISMISSED: i32 = bridge::BridgeKind::PresentDismissed as i32;
3360    const K_GESTURE: i32 = bridge::BridgeKind::Gesture as i32;
3361    const K_CUSTOM: i32 = bridge::BridgeKind::Custom as i32;
3362    const K_MENU_ACTION: i32 = bridge::BridgeKind::MenuAction as i32;
3363    const K_LIFECYCLE: i32 = bridge::BridgeKind::Lifecycle as i32;
3364    const K_PRESENT_FILE: i32 = bridge::BridgeKind::PresentFile as i32;
3365    const K_FOCUS_CHANGED: i32 = bridge::BridgeKind::FocusChanged as i32;
3366    const K_SUBMITTED: i32 = bridge::BridgeKind::Submitted as i32;
3367    const K_WINDOW_RESIZED: i32 = bridge::BridgeKind::WindowResized as i32;
3368    const K_SAFE_AREA: i32 = bridge::BridgeKind::SafeArea as i32;
3369    const K_WINDOW_CLOSED: i32 = bridge::BridgeKind::WindowClosed as i32;
3370    const K_WINDOW_FOCUSED: i32 = bridge::BridgeKind::WindowFocused as i32;
3371    const K_APPEARANCE_CHANGED: i32 = bridge::BridgeKind::AppearanceChanged as i32;
3372    const K_REDUCE_MOTION_CHANGED: i32 = bridge::BridgeKind::ReduceMotionChanged as i32;
3373    const K_COVER_HIDDEN: i32 = bridge::BridgeKind::CoverHidden as i32;
3374    const K_LINK_ACTIVATED: i32 = bridge::BridgeKind::LinkActivated as i32;
3375    const K_TOOLBAR_CHANGED: i32 = bridge::BridgeKind::ToolbarChanged as i32;
3376    const K_KEY: i32 = bridge::BridgeKind::Key as i32;
3377    const K_TEXT: i32 = bridge::BridgeKind::Text as i32;
3378    const K_WINDOW_STATE_CHANGED: i32 = bridge::BridgeKind::WindowStateChanged as i32;
3379
3380    /// The single native trampoline (the app's `nativeOnEvent` forwards here). The kind
3381    /// numbers are `day_spec::bridge::BridgeKind`, the shared wire table. A JNI up-call
3382    /// entry: the decode + dispatch is contained (`day_spec::ffi_guard`), since a panic
3383    /// unwinding this frame would abort the process.
3384    pub fn dispatch_event(env: &mut Env, id: i64, kind: i32, num: f64, jstr: &JString) {
3385        day_spec::ffi_guard::contain((), || {
3386            dispatch_event_inner(env, id, kind, num, jstr);
3387        });
3388    }
3389
3390    /// Whether node `id` has a `Decorate::on_key` handler (docs/menus.md). A canvas asks before
3391    /// it claims a key or takes focus on a press, so one nobody wanted keys from leaves them to
3392    /// the platform's own focus navigation. A JNI up-call entry, contained.
3393    #[must_use]
3394    pub fn handles_keys(id: i64) -> bool {
3395        day_spec::ffi_guard::contain(false, || day_spec::keys::handled(NodeId(id as u64)))
3396    }
3397
3398    /// Whether node `id` took the whole keyboard (`Decorate::keyboard`, docs/menus.md). A
3399    /// canvas asks before it raises the soft keyboard or names a letter. A JNI up-call
3400    /// entry, contained.
3401    #[must_use]
3402    pub fn handles_text(id: i64) -> bool {
3403        day_spec::ffi_guard::contain(false, || day_spec::keys::text(NodeId(id as u64)))
3404    }
3405
3406    fn dispatch_event_inner(env: &mut Env, id: i64, kind: i32, num: f64, jstr: &JString) {
3407        if kind == K_CUSTOM {
3408            let text = string_of(env, jstr).ok().unwrap_or_default();
3409            // DayActivity is about to recreate itself (DayBridge.willRecreate): the route goes
3410            // into the activity's instance state before the tree it belongs to is torn down.
3411            if text == "day:will-recreate" {
3412                save_route_for_remount(env);
3413                return;
3414            }
3415            // A label's selection changed (`DayLabel.onSelectionChanged`, Label::on_selection):
3416            // byte offsets into the text the label displays, computed on the Java side where
3417            // the UTF-16 text is. Rides the custom channel because the kind table is shared
3418            // wire format and no kind carries a selection.
3419            if let Some(payload) = text.strip_prefix(crate::text_wire::SELECTION_PREFIX) {
3420                if let Some((start, end)) = crate::text_wire::selection(payload) {
3421                    emit(NodeId(id as u64), Event::TextSelected { start, end });
3422                }
3423                return;
3424            }
3425            // A scroll view's offset and phase (docs/scroll.md "Offset and phase"), sent by its
3426            // ScrollTrack only when the props asked: the shared kind table has neither.
3427            if let Some(payload) = text.strip_prefix(crate::list_wire::OFFSET_PREFIX) {
3428                if let Some(at) = crate::list_wire::offset(payload, density()) {
3429                    emit(NodeId(id as u64), Event::ScrollChanged(at));
3430                }
3431                return;
3432            }
3433            if let Some(payload) = text.strip_prefix(crate::list_wire::PHASE_PREFIX) {
3434                if let Some(phase) = crate::list_wire::phase(payload) {
3435                    emit(NodeId(id as u64), Event::ScrollPhase(phase));
3436                }
3437                return;
3438            }
3439            for tag in ["day:tab-new", "day:tab-close", "day:tab-move"] {
3440                if let Some(key) = text.strip_prefix(tag).and_then(|s| s.strip_prefix(':')) {
3441                    emit(
3442                        NodeId(id as u64),
3443                        Event::Custom {
3444                            tag,
3445                            num,
3446                            text: key.to_owned(),
3447                        },
3448                    );
3449                    return;
3450                }
3451            }
3452            if let Some(token) = text
3453                .strip_prefix("day-tree-expand:")
3454                .and_then(|s| s.parse::<u64>().ok())
3455            {
3456                emit(
3457                    NodeId(id as u64),
3458                    Event::TreeExpanded {
3459                        token,
3460                        expanded: num != 0.0,
3461                    },
3462                );
3463                return;
3464            }
3465            if let Some(token) = text
3466                .strip_prefix("day-tree-select:")
3467                .and_then(|s| s.parse::<u64>().ok())
3468            {
3469                TREE_SOURCES.with(|m| {
3470                    if let Some(e) = m.borrow_mut().get_mut(&id) {
3471                        e.2 = vec![token];
3472                    }
3473                });
3474                emit(NodeId(id as u64), Event::TreeSelection(vec![token]));
3475                return;
3476            }
3477        }
3478
3479        if kind == K_CUSTOM
3480            && string_of(env, jstr).ok().as_deref() == Some("day-list-first-visible")
3481        {
3482            let source = LIST_SOURCES.with(|map| map.borrow().get(&id).cloned());
3483            if let Some(source) = source
3484                && let Some(report) = &source.first_visible
3485            {
3486                report((num.max(0.0) as usize).min((source.len)().saturating_sub(1)));
3487            }
3488            return;
3489        }
3490        let ev = match kind {
3491            K_PRESSED => Event::Pressed,
3492            k if k == bridge::BridgeKind::RefreshRequested as i32 => Event::RefreshRequested,
3493            K_TEXT_CHANGED => {
3494                let text = string_of(env, jstr).ok().unwrap_or_default();
3495                Event::TextChanged(text)
3496            }
3497            K_TOGGLE_CHANGED => Event::ToggleChanged(num != 0.0),
3498            K_VALUE_CHANGED => Event::ValueChanged(num),
3499            K_VALUE_COMMITTED => Event::ValueCommitted(num),
3500            // Inline search on the nav list (docs/search.md): the field's new text, or with
3501            // `num` 1 the text the keyboard's Search key submitted (DayNavHost sends that after
3502            // the last change).
3503            K_SEARCH_CHANGED => {
3504                let text = string_of(env, jstr).ok().unwrap_or_default();
3505                #[expect(
3506                    clippy::float_cmp,
3507                    reason = "`DayNavHost` sends the submit flag as exactly 1"
3508                )]
3509                let submitted = num == 1.0;
3510                if submitted {
3511                    Event::SearchSubmitted(text)
3512                } else {
3513                    Event::SearchChanged(text)
3514                }
3515            }
3516            // SlidingPaneLayout settled on a presentation; Day reconciles rather than drives.
3517            K_NAV_PRESENTATION => Event::NavPresentationChanged(if num >= 0.5 {
3518                day_spec::props::NavPresentation::Split
3519            } else {
3520                day_spec::props::NavPresentation::Stack
3521            }),
3522            K_SELECTION_CHANGED => Event::SelectionChanged(num as i64),
3523            K_LIST_ACTIVATED => Event::ListActivated(num as usize),
3524            // Navigation (docs/navigation.md): system back / gesture / toolbar up. num == 1.0
3525            // means the native FragmentManager already popped (predictive back commit, back
3526            // button, up arrow), so Rust updates the path without re-issuing the pop.
3527            // Id 0 is the app's own system-back callback (DayBridge.appBack, armed by
3528            // `set_system_back`): a back no cover or nav host took, for the app's handlers.
3529            K_NAV_BACK if id == 0 => {
3530                emit(
3531                    day_spec::WINDOW_NODE,
3532                    Event::NavBack {
3533                        already_popped: false,
3534                    },
3535                );
3536                return;
3537            }
3538            K_NAV_BACK => Event::NavBack {
3539                already_popped: num != 0.0,
3540            },
3541            // Nav page size report, "w,h" in px.
3542            K_FRAME_CHANGED => {
3543                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3544                let Some((w, h)) = text.split_once(',') else {
3545                    return;
3546                };
3547                let d = DENSITY.with(std::cell::Cell::get);
3548                let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>()) else {
3549                    return;
3550                };
3551                Event::FrameChanged(Size::new(w / d, h / d))
3552            }
3553            // Warm deep link: the nav piece handles RouteRequested.
3554            k if k == bridge::BridgeKind::DocumentOpened as i32 => {
3555                if let Ok(path) = string_of(env, jstr) {
3556                    day_core::request_open_files(vec![path]);
3557                }
3558                return;
3559            }
3560            K_DEEPLINK => {
3561                let route: String = string_of(env, jstr).ok().unwrap_or_default();
3562                day_core::request_open_url(&route);
3563                return;
3564            }
3565            // The share sheet (docs/deep-links.md): a web link in it takes the deep-link path.
3566            k if k == bridge::BridgeKind::SharedText as i32 => {
3567                let payload: String = string_of(env, jstr).ok().unwrap_or_default();
3568                let (text, subject) = match payload.split_once('\u{1f}') {
3569                    Some((text, subject)) => (text, Some(subject)),
3570                    None => (payload.as_str(), None),
3571                };
3572                day_core::request_shared_text(text, subject);
3573                return;
3574            }
3575            // Presentation answers (docs/dialogs.md): id == request id.
3576            K_PRESENT_BUTTON => Event::PresentResult {
3577                req: id as u64,
3578                result: day_spec::present::PresentResult::Button(num as i64),
3579            },
3580            K_PRESENT_TEXT => {
3581                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3582                Event::PresentResult {
3583                    req: id as u64,
3584                    result: day_spec::present::PresentResult::Text(text),
3585                }
3586            }
3587            K_PRESENT_DISMISSED => Event::PresentResult {
3588                req: id as u64,
3589                result: day_spec::present::PresentResult::Dismissed,
3590            },
3591            // File-picker answer (docs/files.md): string = chosen locators (a cache path for open,
3592            // a content:// URI for save), joined by the unit separator. Reuse the `decode` tag 3.
3593            K_PRESENT_FILE => {
3594                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3595                Event::PresentResult {
3596                    req: id as u64,
3597                    result: day_spec::present::PresentResult::decode(3, 0, text),
3598                }
3599            }
3600            // Gestures (docs/gestures.md): `num` = the gesture code, `text` = its payload in
3601            // px (`gesture_event`). The input kind is the window's, whatever node sent it.
3602            K_GESTURE => {
3603                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3604                let d = DENSITY.with(std::cell::Cell::get);
3605                match crate::gesture_event(num as i32, &text, d) {
3606                    Some(ev @ Event::PointerKindChanged(_)) => {
3607                        emit(day_spec::WINDOW_NODE, ev);
3608                        return;
3609                    }
3610                    Some(ev) => ev,
3611                    None => return,
3612                }
3613            }
3614            // Piece-defined custom event (§8.2's open event channel): a `&'static str` tag can't cross
3615            // JNI, so the tag is empty and the piece reads the primitive `num`/`text` payload. A piece
3616            // (e.g. day-piece-webview) calls `DayBridge.nativeOnEvent(id, 12, num, text)`.
3617            K_CUSTOM => {
3618                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3619                Event::Custom { tag: "", num, text }
3620            }
3621            // A cover's hide slide finished (docs/cover.md): DayCover reports so Rust can
3622            // dispose the content.
3623            K_COVER_HIDDEN => Event::CoverHidden,
3624            // A styled run's link was tapped (docs/text-runs.md): the ClickableSpan reports its
3625            // target, and day-core routes it to the label's `.on_link()`.
3626            K_LINK_ACTIVATED => Event::LinkActivated(string_of(env, jstr).ok().unwrap_or_default()),
3627            // A key from a focused canvas or focusable view (docs/menus.md): the day key name,
3628            // with the modifier mask and the phase in `num`. The view already asked whether
3629            // this node claims keys.
3630            K_KEY => Event::Key(crate::key_event(
3631                false,
3632                string_of(env, jstr).ok().unwrap_or_default(),
3633                num,
3634            )),
3635            // Text the full route committed (docs/menus.md "The full route"): what a key or
3636            // the input method typed, with the modifier mask and the phase in `num`.
3637            K_TEXT => Event::Key(crate::key_event(
3638                true,
3639                string_of(env, jstr).ok().unwrap_or_default(),
3640                num,
3641            )),
3642            // A toolbar item's value (docs/toolbars.md): "sel" carries a segment index, a page
3643            // search field's "text:" / "submit:" its text after the prefix, anything else a
3644            // toggle's new state. Plain buttons arrive as MENU_ACTION, like the menus.
3645            K_TOOLBAR_CHANGED => {
3646                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3647                let value = if text == "sel" {
3648                    day_spec::ToolbarValue::Selected(num.max(0.0) as usize)
3649                } else if let Some(t) = text.strip_prefix("text:") {
3650                    note_search_text(id as u64, t);
3651                    day_spec::ToolbarValue::Text(t.to_string())
3652                } else if let Some(t) = text.strip_prefix("submit:") {
3653                    day_spec::ToolbarValue::Submit(t.to_string())
3654                } else {
3655                    day_spec::ToolbarValue::On(num != 0.0)
3656                };
3657                Event::ToolbarChanged {
3658                    action: id as u64,
3659                    value,
3660                }
3661            }
3662            // Menu selection (docs/menus.md): `id` == the chosen action's dispatch id (0 for a
3663            // role/standard item, which dispatches to nothing). Routed by the pump to the closure.
3664            K_MENU_ACTION => Event::MenuAction(id as u64),
3665            // Activity lifecycle (docs/lifecycle.md): `num` is the phase code (day_spec::Lifecycle
3666            // order). DayActivity forwards onResume/onPause/onStart/onStop/onTrimMemory/onDestroy.
3667            K_LIFECYCLE => match android_lifecycle(num as i32) {
3668                Some(phase) => Event::Lifecycle(phase),
3669                None => return,
3670            },
3671            // Root size change (px as "w,h" text): the safe-area root grew or shrank (a late
3672            // inset pass, the soft keyboard, rotation, or a system-bar change). Routed to the
3673            // root as a window resize so Day relayouts; same rail as appkit's windowDidResize.
3674            // (18: the first free kind; 15 already carries file-picker answers.)
3675            // Safe-area report (edge-to-edge mode, docs/layout.md): update the global insets
3676            // signal; apps read `day::safe_area()`. Not an Event: nothing to route to a node.
3677            K_SAFE_AREA => {
3678                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3679                let p: Vec<f64> = text.split(',').filter_map(|s| s.parse().ok()).collect();
3680                if p.len() < 4 {
3681                    return;
3682                }
3683                let d = DENSITY.with(std::cell::Cell::get);
3684                day_core::set_safe_area(day_spec::Insets {
3685                    top: p[0] / d,
3686                    bottom: p[1] / d,
3687                    leading: p[2] / d,
3688                    trailing: p[3] / d,
3689                });
3690                return;
3691            }
3692            // Light/dark switch (DayActivity.onConfigurationChanged). Not an Event: nothing to
3693            // route to a node; day-core restyles what it owns and rebuilds app-painted surfaces.
3694            K_APPEARANCE_CHANGED => {
3695                day_core::note_appearance_changed();
3696                return;
3697            }
3698            // The user's "Remove animations" switch (DayBridge.watchReduceMotion). Likewise not
3699            // an Event: day-core re-reads `reduce_motion` and lands every finite animation
3700            // (docs/accessibility.md).
3701            K_REDUCE_MOTION_CHANGED => {
3702                day_core::note_motion_changed();
3703                return;
3704            }
3705            K_WINDOW_RESIZED => {
3706                let text: String = string_of(env, jstr).ok().unwrap_or_default();
3707                let p: Vec<f64> = text.split(',').filter_map(|s| s.parse().ok()).collect();
3708                if p.len() < 2 {
3709                    return;
3710                }
3711                let d = DENSITY.with(std::cell::Cell::get);
3712                // id 0 = the primary activity (WINDOW_NODE); a secondary DayWindowActivity
3713                // reports against its own day root (docs/windows.md).
3714                let target = if id == 0 {
3715                    day_spec::WINDOW_NODE
3716                } else {
3717                    day_spec::NodeId(id as u64)
3718                };
3719                let size = Size::new(p[0] / d, p[1] / d);
3720                // The third field: the soft keyboard's share of the shrink, which the size
3721                // class adds back (docs/size-classes.md).
3722                let keyboard = p.get(2).map_or(0.0, |k| k.max(0.0) / d);
3723                day_core::note_keyboard_overlap(target, size, keyboard);
3724                emit(target, Event::WindowResized(size));
3725                return;
3726            }
3727            // A window's display state (docs/windows.md): the system bars hid or showed for a
3728            // fullscreen request, or a request the platform declined reports what the window
3729            // kept. Id 0 is the primary activity (WINDOW_NODE), like the resize rail.
3730            K_WINDOW_STATE_CHANGED => {
3731                let state = day_spec::WindowState::from_code(num as i32);
3732                log::debug!("android: window state now {state:?}");
3733                let target = if id == 0 {
3734                    day_spec::WINDOW_NODE
3735                } else {
3736                    day_spec::NodeId(id as u64)
3737                };
3738                emit(target, Event::WindowStateChanged(state));
3739                return;
3740            }
3741            // Secondary-window lifecycle (docs/windows.md): the id is the window's root.
3742            K_WINDOW_CLOSED => Event::WindowClosed,
3743            K_WINDOW_FOCUSED => Event::WindowFocused(num != 0.0),
3744            // Focus pair + IME submit action (docs/focus.md).
3745            K_FOCUS_CHANGED => Event::FocusChanged(num != 0.0),
3746            K_SUBMITTED => Event::Submitted,
3747            unknown => {
3748                // A silently dropped kind is how the kind-15 collision hid for weeks: say so
3749                // once per kind in debug builds (release stays quiet; this is a dev signal).
3750                #[cfg(debug_assertions)]
3751                {
3752                    use std::sync::{Mutex, OnceLock};
3753                    static SEEN: OnceLock<Mutex<std::collections::BTreeSet<i32>>> = OnceLock::new();
3754                    let seen = SEEN.get_or_init(|| Mutex::new(std::collections::BTreeSet::new()));
3755                    if let Ok(mut g) = seen.lock()
3756                        && g.insert(unknown)
3757                    {
3758                        log::warn!("day-toolkit-material: dropping unknown event kind {unknown}");
3759                    }
3760                }
3761                let _ = unknown;
3762                return;
3763            }
3764        };
3765        emit(NodeId(id as u64), ev);
3766    }
3767
3768    /// Posted-closure trampoline (the app's `nativeRunPosted` forwards here). The closure is
3769    /// arbitrary app/day-core code inside a JNI up-call, so it runs contained.
3770    pub fn run_posted(token: i64) {
3771        // SAFETY: `token` is the Box::into_raw pointer `Platform::post` minted; Java hands it
3772        // back exactly once.
3773        let f: Box<Box<dyn FnOnce() + Send>> =
3774            unsafe { Box::from_raw(token as *mut Box<dyn FnOnce() + Send>) };
3775        day_spec::ffi_guard::contain((), f);
3776    }
3777
3778    /// Frame-callback trampoline (the app's `nativeDoFrame` forwards here). `frame_nanos` is
3779    /// `Choreographer`'s frame time in nanoseconds; day-core wants seconds. Runs on the UI
3780    /// thread, contained like `run_posted`.
3781    pub fn run_frame(token: i64, frame_nanos: i64) {
3782        day_core::frame::native::deliver(
3783            token as u64,
3784            day_spec::FrameStamp::new(frame_nanos as f64 / 1_000_000_000.0),
3785        );
3786    }
3787
3788    #[distributed_slice]
3789    pub static RENDERERS: [fn() -> Renderer<Material>];
3790
3791    pub struct Material {
3792        registry: Registry<Material>,
3793    }
3794
3795    impl Material {
3796        #[must_use]
3797        pub fn new() -> Self {
3798            let mut registry = Registry::default();
3799            for f in RENDERERS {
3800                registry.register(f());
3801            }
3802            Material { registry }
3803        }
3804    }
3805
3806    impl Default for Material {
3807        fn default() -> Self {
3808            Self::new()
3809        }
3810    }
3811
3812    /// `DayBridge.displayInfo()`'s tab-separated line as a [`day_spec::Monitor`]: id, name,
3813    /// scale, frame width and height, work-area left, top, width and height (dp).
3814    fn parse_display_info(line: &str) -> Option<day_spec::Monitor> {
3815        let f: Vec<&str> = line.split('\t').collect();
3816        let [id, name, rest @ ..] = f.as_slice() else {
3817            return None;
3818        };
3819        let n: Vec<f64> = rest
3820            .iter()
3821            .map(|s| s.parse::<f64>().ok())
3822            .collect::<Option<_>>()?;
3823        let [scale, w, h, wl, wt, ww, wh] = n.as_slice() else {
3824            return None;
3825        };
3826        Some(day_spec::Monitor {
3827            id: (*id).to_string(),
3828            name: (*name).to_string(),
3829            frame: day_spec::Rect::new(0.0, 0.0, *w, *h),
3830            work_area: day_spec::Rect::new(*wl, *wt, *ww, *wh),
3831            scale: *scale,
3832            primary: true,
3833        })
3834    }
3835
3836    fn jstr(env: &mut Env, s: &str) -> jni::objects::JString<'static> {
3837        // SAFETY: local ref used immediately within the same JNI frame.
3838        unsafe { std::mem::transmute(env.new_string(s).expect("new_string")) }
3839    }
3840
3841    /// Map an Android lifecycle phase code (`day_spec::Lifecycle` order) to the enum (docs/lifecycle.md).
3842    fn android_lifecycle(code: i32) -> Option<day_spec::Lifecycle> {
3843        use day_spec::Lifecycle::{
3844            DidBecomeActive, DidEnterBackground, DidExit, DidReceiveMemoryWarning,
3845            WillEnterForeground, WillResignActive, WillTerminate,
3846        };
3847        Some(match code {
3848            2 => DidBecomeActive,
3849            3 => WillResignActive,
3850            4 => WillEnterForeground,
3851            5 => DidEnterBackground,
3852            6 => DidReceiveMemoryWarning,
3853            7 => WillTerminate,
3854            8 => DidExit,
3855            _ => return None,
3856        })
3857    }
3858
3859    /// Mobile backends deliver the full lifecycle (docs/lifecycle.md). `const` for
3860    /// `day::require_lifecycle!` compile-time guards.
3861    #[must_use]
3862    pub const fn lifecycle_supported(_phase: day_spec::Lifecycle) -> bool {
3863        true
3864    }
3865
3866    /// Default label for a standard role left unlabeled by the app. (Android's own text-selection
3867    /// toolbar handles the actual Cut/Copy/Paste on editable views; a role in a day menu is shown
3868    /// for parity and dispatches nothing; see docs/menus.md.)
3869    fn android_role_label(role: day_spec::MenuRole) -> &'static str {
3870        use day_spec::MenuRole::{
3871            About, CheckForUpdates, CloseWindow, Copy, Cut, Delete, Fullscreen, Minimize,
3872            NewWindow, Paste, Preferences, Quit, Redo, SelectAll, Undo,
3873        };
3874        match role {
3875            Cut => "Cut",
3876            Copy => "Copy",
3877            Paste => "Paste",
3878            SelectAll => "Select All",
3879            Undo => "Undo",
3880            Redo => "Redo",
3881            Delete => "Delete",
3882            About => "About",
3883            Quit => "Quit",
3884            Preferences => "Settings",
3885            Minimize => "Minimize",
3886            CloseWindow => "Close",
3887            Fullscreen => "Full Screen",
3888            NewWindow => "New Window",
3889            CheckForUpdates => "Check for Updates…",
3890        }
3891    }
3892
3893    /// Flatten the day-neutral menu tree to the line format `DayBridge.buildMenu` parses:
3894    /// `kind \t action \t enabled \t checked \t label` per line, where kind ∈ {A action,
3895    /// S submenu-open, E submenu-close, `-` separator}. Roles become plain actions with action 0,
3896    /// and `checked` is -1 for a plain command or 0/1 for a checkable one.
3897    /// The window toolbar as one record per item: `\u{1e}` between records, `\u{1f}` between
3898    /// fields: id, kind, label, icon, enabled, action, extra. A menu item's extra is the app-menu
3899    /// spec `serialize_menu` writes (its own `\t`/`\n` never collide with these separators); a
3900    /// segmented item's is the selected index and the segment titles, `\u{1d}`-separated, each
3901    /// title followed by its glyph after a `\u{1c}`. A page's search field (`day::search`,
3902    /// docs/search.md) is a `search` record whose extra is its text and its placeholder,
3903    /// `\u{1d}`-separated: the bar draws it as a collapsible search action. The sidebar toggle
3904    /// never reaches a phone's bar and is left out: this backend has no pane the toggle could
3905    /// move (`toggle_sidebar` answers false). A navigation surface's own search never arrives
3906    /// here either: it rides the navigation list (`Cap::ToolbarSearch` is unsupported).
3907    ///
3908    /// The showing page's own commands are written first, ahead of the window's chrome. A
3909    /// Material app bar shows icon actions in order and folds the rest into its overflow, and
3910    /// the page's commands are what a person came to the page for; the window's New Window and
3911    /// appearance chooser are one tap further away, in the overflow, when the bar is that
3912    /// narrow. The item's `column` tells the two apart: a destination's commands come from the
3913    /// detail (or list) column, the host's own from the sidebar column, and both ride the same
3914    /// merged window model here.
3915    fn serialize_toolbar(items: &[day_spec::ToolbarItem]) -> String {
3916        use day_spec::ToolbarItemKind as K;
3917        fn clean(s: &str) -> String {
3918            s.replace(['\u{1d}', '\u{1e}', '\u{1f}'], " ")
3919        }
3920        let (page, window): (Vec<_>, Vec<_>) = items
3921            .iter()
3922            .filter(|i| i.id != day_spec::SIDEBAR_TOGGLE_ID)
3923            .partition(|i| {
3924                matches!(
3925                    i.column,
3926                    day_spec::ToolbarColumn::Detail | day_spec::ToolbarColumn::List
3927                )
3928            });
3929        let mut out = String::new();
3930        for item in page.into_iter().chain(window) {
3931            let (kind, extra) = match &item.kind {
3932                K::Button => ("button", String::new()),
3933                K::Toggle { on } => ("toggle", u8::from(*on).to_string()),
3934                K::Menu { items } => {
3935                    let mut spec = String::new();
3936                    serialize_menu(items, &mut spec);
3937                    ("menu", spec)
3938                }
3939                K::Segmented { segments, selected } => {
3940                    // Each segment carries its title and its glyph (0x1C between them): the bar
3941                    // shows the control as one icon button (the segment in force's glyph)
3942                    // that opens the choices, so it needs every segment's art.
3943                    let mut e = selected.to_string();
3944                    for seg in segments {
3945                        e.push('\u{1d}');
3946                        e.push_str(&clean(&seg.title));
3947                        e.push('\u{1c}');
3948                        e.push_str(&clean(&icon_name(seg.icon.as_ref())));
3949                    }
3950                    ("segmented", e)
3951                }
3952                K::Label => ("label", String::new()),
3953                K::Separator => ("sep", String::new()),
3954                K::Search {
3955                    text, placeholder, ..
3956                } => (
3957                    "search",
3958                    format!("{}\u{1d}{}", clean(text), clean(placeholder)),
3959                ),
3960            };
3961            // A search action without an icon of its own shows the magnifier, the glyph every
3962            // Android app bar uses for it.
3963            let icon = match (&item.kind, &item.icon) {
3964                (K::Search { .. }, None) => symbol_drawable(day_spec::Symbol::Search),
3965                (_, icon) => icon_name(icon.as_ref()),
3966            };
3967            if !out.is_empty() {
3968                out.push('\u{1e}');
3969            }
3970            // An eighth field: the item's placement (docs/toolbars.md). The Java parser reads
3971            // fields positionally with `f.length >` guards, so a spec without it still parses.
3972            let placement = match item.placement {
3973                day_spec::ToolbarPlacement::Navigation => "nav",
3974                day_spec::ToolbarPlacement::Principal => "mid",
3975                day_spec::ToolbarPlacement::Primary => "primary",
3976                day_spec::ToolbarPlacement::Secondary => "secondary",
3977                // The nav host's bottom app bar; a docked bar folds these into its overflow.
3978                day_spec::ToolbarPlacement::Bottom => "bottom",
3979                day_spec::ToolbarPlacement::Automatic => "auto",
3980            };
3981            out.push_str(
3982                &[
3983                    clean(&item.id),
3984                    kind.to_string(),
3985                    clean(&item.label),
3986                    clean(&icon),
3987                    u8::from(item.enabled).to_string(),
3988                    item.action.to_string(),
3989                    extra,
3990                    placement.to_string(),
3991                ]
3992                .join("\u{1f}"),
3993            );
3994        }
3995        out
3996    }
3997
3998    /// Record text the user typed into a page's search action in the bar's model, so the next
3999    /// repaint carries what the field shows. day-core's own copy follows the same event
4000    /// (`mirror_value`), but this backend repaints from its mirror, and a repaint carrying
4001    /// the text from before the typing would put it back into the field.
4002    fn note_search_text(action: u64, text: &str) {
4003        WINDOW_BARS.with(|m| {
4004            for bar in m.borrow_mut().values_mut() {
4005                let Some(item) = bar
4006                    .by_action(action)
4007                    .filter(|i| matches!(i.kind, day_spec::ToolbarItemKind::Search { .. }))
4008                    .map(|i| i.id.clone())
4009                else {
4010                    continue;
4011                };
4012                bar.patch(&day_spec::ToolbarPatch::Text {
4013                    item,
4014                    text: text.to_string(),
4015                });
4016            }
4017        });
4018    }
4019
4020    /// The drawable name an item's icon resolves to on the Java side. A bundled image is named
4021    /// after itself (docs/vectors.md); a `Symbol` names the toolkit's glyph for it,
4022    /// `day_symbol_<snake_case>`, one Material Symbols vector per variant shipped in this crate's
4023    /// `res/`, so a symbol-only item has an icon to show in the bar, the way an SF Symbol gives
4024    /// it one on Apple. A variant with no glyph resolves to nothing and lands as text.
4025    fn icon_name(icon: Option<&day_spec::Icon>) -> String {
4026        match icon {
4027            Some(day_spec::Icon::Image(name)) => name.clone(),
4028            Some(day_spec::Icon::Symbol(sym)) => symbol_drawable(*sym),
4029            None => String::new(),
4030        }
4031    }
4032
4033    /// `Symbol::ZoomIn` → `day_symbol_zoom_in`: the variant's name in snake case. Public so a
4034    /// piece drawing a standard glyph in its own Java view (day-piece-settings' group rows)
4035    /// resolves the same drawable a nav item does.
4036    #[must_use]
4037    pub fn symbol_drawable(sym: day_spec::Symbol) -> String {
4038        let mut out = String::from("day_symbol");
4039        for c in format!("{sym:?}").chars() {
4040            if c.is_ascii_uppercase() {
4041                out.push('_');
4042                out.push(c.to_ascii_lowercase());
4043            } else {
4044                out.push(c);
4045            }
4046        }
4047        out
4048    }
4049
4050    fn serialize_menu(items: &[day_spec::MenuItem], out: &mut String) {
4051        use std::fmt::Write as _;
4052        fn clean(s: &str) -> String {
4053            s.replace(['\t', '\n'], " ")
4054        }
4055        // `kind \t action \t enabled \t checked \t label`. The label stays last so its own
4056        // spaces need no escaping, and every kind writes the full field count so the Java side
4057        // can index it; `checked` is -1 for a plain command, 0/1 for a checkable one.
4058        for item in items {
4059            match item {
4060                day_spec::MenuItem::Separator => out.push_str("-\t0\t1\t-1\t\n"),
4061                day_spec::MenuItem::Submenu { label, items, .. } => {
4062                    let _ = writeln!(out, "S\t0\t1\t-1\t{}", clean(label));
4063                    serialize_menu(items, out);
4064                    out.push_str("E\t0\t1\t-1\t\n");
4065                }
4066                day_spec::MenuItem::Action {
4067                    action,
4068                    label,
4069                    shortcut: _,
4070                    enabled,
4071                    checked,
4072                    role,
4073                    // The rest go unread: Material's overflow menu is text-only by
4074                    // convention (an app-bar action carries the icon), so `icon` never applies
4075                    // here, and `id` is the app's name for a script rather than anything the
4076                    // native item needs.
4077                    ..
4078                } => {
4079                    let text = match role {
4080                        Some(r) if label.is_empty() => android_role_label(*r).to_string(),
4081                        _ => label.clone(),
4082                    };
4083                    let _ = writeln!(
4084                        out,
4085                        "A\t{}\t{}\t{}\t{}",
4086                        action,
4087                        i32::from(*enabled),
4088                        checked.map_or(-1, i32::from),
4089                        clean(&text)
4090                    );
4091                }
4092            }
4093        }
4094    }
4095
4096    /// Size (in **sp**, which scales with Settings ▸ Display ▸ Font size, the Android
4097    /// accessibility text scale) + the style's inherent weight for a logical [`Font`]. Mobile
4098    /// scale, aligned with iOS. Public for standalone pieces (docs/extending.md), which resolve
4099    /// the same scale.
4100    #[must_use]
4101    pub fn font_style(f: Font) -> (f32, day_spec::FontWeight) {
4102        use day_spec::FontWeight::{Regular, Semibold};
4103        match f {
4104            Font::LargeTitle => (34.0, Regular),
4105            Font::Title => (28.0, Regular),
4106            Font::Title2 => (22.0, Regular),
4107            Font::Title3 => (20.0, Regular),
4108            Font::Headline => (17.0, Semibold),
4109            Font::Subheadline => (15.0, Regular),
4110            Font::Body => (17.0, Regular),
4111            Font::Callout => (16.0, Regular),
4112            Font::Footnote => (13.0, Regular),
4113            Font::Caption => (12.0, Regular),
4114            Font::Caption2 => (11.0, Regular),
4115            Font::System(pt) | Font::Custom(_, pt) => (pt as f32, Regular),
4116        }
4117    }
4118
4119    /// The bundled family name when the spec is `Font::Custom` (§18.4), passed to Java as the
4120    /// nullable `family` argument of `DayBridge.setLabelFont`, which resolves it to the
4121    /// `res/font/` resource `day build` staged from the project's `fonts/` directory.
4122    fn custom_family(spec: day_spec::FontSpec) -> Option<&'static str> {
4123        match spec.style {
4124            Font::Custom(name, _) => Some(name),
4125            _ => None,
4126        }
4127    }
4128
4129    /// Day weight → Android font weight (Thin=100 … Black=900, for `Typeface.create(_, weight, _)`).
4130    fn android_weight(w: day_spec::FontWeight) -> i32 {
4131        use day_spec::FontWeight as W;
4132        match w {
4133            W::Thin => 100,
4134            W::UltraLight => 200,
4135            W::Light => 300,
4136            W::Regular => 400,
4137            W::Medium => 500,
4138            W::Semibold => 600,
4139            W::Bold => 700,
4140            W::Heavy => 800,
4141            W::Black => 900,
4142        }
4143    }
4144
4145    /// (sp size, Android weight, italic, tabular) for `DayBridge.setLabelFont`. The size is
4146    /// the style's times [`day_spec::FontSpec::scale`], still in sp, so it keeps following the
4147    /// reader's font size setting (and a `max_text_scale` cap's scale lands here).
4148    fn font_params(spec: day_spec::FontSpec) -> (f32, i32, bool, bool) {
4149        let (sp, inherent) = font_style(spec.style);
4150        let weight = android_weight(spec.weight.unwrap_or(inherent));
4151        let sp = spec.resolved_points(f64::from(sp)) as f32;
4152        (sp, weight, spec.italic, spec.tabular)
4153    }
4154
4155    /// A label's whole font (`LabelProps::font`, `LabelPatch::Font`): size, weight, slant, the
4156    /// family (a bundled one, or Android's `monospace` alias for `FontSpec::monospace`) and
4157    /// the OpenType features (`tnum`, `smcp`, `onum`).
4158    fn apply_label_font(env: &mut Env, view: &Gref, spec: day_spec::FontSpec) {
4159        let (sp, weight, italic, tabular) = font_params(spec);
4160        // A whole-label monospace ask rides the family parameter: "monospace" is Android's own
4161        // alias for the system fixed-pitch face, so this is the same request
4162        // `TypefaceSpan("monospace")` makes for a single run.
4163        let fam = match (custom_family(spec), spec.monospace) {
4164            (Some(f), _) => jstr(env, f),
4165            (None, true) => jstr(env, "monospace"),
4166            (None, false) => JString::default(),
4167        };
4168        let _ = java_in(env, |env| {
4169            DayBridge::setLabelFont(env, view.as_obj(), sp, weight, italic, &fam, tabular)
4170        });
4171        // `setLabelFont` asks for tabular figures alone; small capitals or oldstyle figures
4172        // replace that with the whole list.
4173        if spec.small_caps || spec.oldstyle_figures {
4174            let features = crate::text_wire::features(&spec).unwrap_or_default();
4175            let f = jstr(env, &features);
4176            let _ = java_in(env, |env| {
4177                DayBridge::setLabelFeatures(env, view.as_obj(), &f)
4178            });
4179        }
4180    }
4181
4182    /// A label's paragraph attributes (`LabelProps::paragraph`, `LabelPatch::Paragraph`):
4183    /// the line limit, the truncation, the letter spacing and the line height, whole. Day
4184    /// measures the label again afterward, and the `TextView`'s own measurement honors them.
4185    fn apply_label_paragraph(env: &mut Env, view: &Gref, p: &day_spec::props::LabelParagraph) {
4186        let (lines, truncation, spacing, height) = crate::text_wire::paragraph_args(p);
4187        let _ = java_in(env, |env| {
4188            DayBridge::setLabelParagraph(env, view.as_obj(), lines, truncation, spacing, height)
4189        });
4190    }
4191
4192    /// Day `Color` (0–1 floats) → a packed `0xAARRGGBB` int for `android.graphics.Color`.
4193    /// Per-row nav icon tints as an index-aligned joined string ("0" = untinted), the
4194    /// best-effort `setNavMenuTints` wire format (docs/vectors.md).
4195    fn nav_tints_joined(tints: &[Option<day_spec::Color>]) -> String {
4196        tints
4197            .iter()
4198            .map(|t| t.map_or(0, argb_i32).to_string())
4199            .collect::<Vec<_>>()
4200            .join("\u{1f}")
4201    }
4202
4203    /// Per-row nav context menus (docs/menus.md) as one string: each row's
4204    /// [`serialize_menu`] spec (empty = no menu), joined by U+001E, a separator the line
4205    /// format itself never contains. Ridden best-effort after makeNavMenu/updateNavMenu,
4206    /// like the tints.
4207    /// Move the sidebar's active indicator to `sel`, or clear it (`NavMenuProps::selected`).
4208    ///
4209    /// Best-effort, like the tint and badge follow-ups: a decoration is never worth taking the
4210    /// nav host's build path down with it (the navhost lesson, docs/navigation.md).
4211    fn nav_menu_select(env: &mut Env, h: &AHandle, sel: Option<usize>) {
4212        let _ = java_in(env, |env| {
4213            DayBridge::setNavMenuSelected(env, h.0.as_obj(), sel.map_or(-1, |i| i as i32))
4214        });
4215        if env.exception_check() {
4216            env.exception_clear();
4217        }
4218    }
4219
4220    fn nav_menus_joined(menus: &[Vec<day_spec::MenuItem>]) -> String {
4221        menus
4222            .iter()
4223            .map(|items| {
4224                let mut spec = String::new();
4225                serialize_menu(items, &mut spec);
4226                spec
4227            })
4228            .collect::<Vec<_>>()
4229            .join("\u{1e}")
4230    }
4231
4232    fn argb_i32(c: day_spec::Color) -> i32 {
4233        super::argb_u32(c) as i32
4234    }
4235
4236    /// `makeImage`/`setImageTint`'s "theme text color" value (docs/vectors.md "Template"):
4237    /// alpha 0, which no real tint has. The bridge's `TEMPLATE_TINT`.
4238    const TEMPLATE_TINT: i32 = 1;
4239
4240    /// The bridge's image-tint channel: a packed ARGB, `0` for the authored colors, or
4241    /// [`TEMPLATE_TINT`] for a template glyph that takes the theme's text color.
4242    /// A list item's glyph as a drawable name: a staged image by its own name, a standard
4243    /// symbol by the `day_symbol_*` drawable it ships as.
4244    fn list_item_icon(icon: Option<&day_spec::Icon>) -> String {
4245        match icon {
4246            Some(day_spec::Icon::Image(name)) => name.clone(),
4247            Some(day_spec::Icon::Symbol(sym)) => symbol_drawable(*sym),
4248            None => String::new(),
4249        }
4250    }
4251
4252    /// Apply one change to a realized list item (docs/list.md "List items"). The Java view
4253    /// sets its texts together, so the props are kept here to hand it the other two.
4254    fn list_item_patch(h: &AHandle, patch: &day_spec::props::ListItemPatch) {
4255        use day_spec::props::ListItemPatch as P;
4256        let key = h.0.as_obj().as_raw() as usize;
4257        let Some(p) = LIST_ITEM_PROPS.with(|m| {
4258            let mut m = m.borrow_mut();
4259            let p = m.get_mut(&key)?;
4260            match patch {
4261                P::Title(t) => p.title.clone_from(t),
4262                P::Subtitle(t) => p.subtitle.clone_from(t),
4263                P::Detail(t) => p.detail.clone_from(t),
4264                P::Icon(i) => p.icon.clone_from(i),
4265                P::IconTint(c) => p.icon_tint = *c,
4266                P::Checked(on) => p.checked = *on,
4267            }
4268            Some(p.clone())
4269        }) else {
4270            return;
4271        };
4272        with_env(|env| {
4273            let _ = match patch {
4274                P::Title(_) | P::Subtitle(_) | P::Detail(_) => {
4275                    let (t, s, d) = (
4276                        jstr(env, &p.title),
4277                        jstr(env, &p.subtitle),
4278                        jstr(env, &p.detail),
4279                    );
4280                    java_in(env, |env| {
4281                        DayListItem::setTexts(env, h.0.as_obj(), &t, &s, &d)
4282                    })
4283                }
4284                P::Icon(_) | P::IconTint(_) => {
4285                    let name = jstr(env, &list_item_icon(p.icon.as_ref()));
4286                    let tint = p.icon_tint.map_or(0, |c| argb_i32(c.resolved()));
4287                    java_in(env, |env| {
4288                        DayListItem::setIcon(env, h.0.as_obj(), &name, tint)
4289                    })
4290                }
4291                P::Checked(on) => {
4292                    java_in(env, |env| DayListItem::setChecked(env, h.0.as_obj(), *on))
4293                }
4294            };
4295            if env.exception_check() {
4296                env.exception_clear();
4297            }
4298        });
4299    }
4300
4301    fn image_tint(tint: Option<day_spec::Color>, template: bool) -> i32 {
4302        match tint {
4303            Some(c) => argb_i32(c),
4304            None if template => TEMPLATE_TINT,
4305            None => 0,
4306        }
4307    }
4308
4309    /// Warn once per kind that this backend has no registered renderer for `kind`, before falling
4310    /// back to a visible placeholder. A missing renderer usually means the piece's `material` feature
4311    /// wasn't enabled (Tier A.2 derives it automatically under `day build`). The message goes to
4312    /// both stderr (which `redirect_stdio_to_logcat` routes to logcat) and directly to logcat at
4313    /// `ERROR`, so it surfaces even before the redirect installs. Deduped per kind so it doesn't
4314    /// spam the log.
4315    fn warn_missing_renderer(kind: PieceKind) {
4316        day_spec::placeholder::report(kind, "android");
4317    }
4318
4319    /// Realize fallback for a builtin arm whose props failed to downcast
4320    /// ([`day_spec::props_of`] already reported it): the same visible `⟨kind⟩` label a
4321    /// missing renderer shows, so one mismatched piece cannot abort the tree build.
4322    fn realize_placeholder(kind: PieceKind) -> AHandle {
4323        with_env(|env| AHandle(placeholder_view(env, kind)))
4324    }
4325
4326    thread_local! {
4327        /// `BitmapId` → what the decode reported (docs/images.md). Only the METADATA lives here;
4328        /// the pixels are the shim's, in `DayBridge.bitmaps` under the same id.
4329        static BITMAP_INFO: RefCell<std::collections::HashMap<u64, day_spec::BitmapInfo>> =
4330            RefCell::new(std::collections::HashMap::new());
4331    }
4332
4333    /// Re-encode a decoded bitmap through the shim (docs/images.md).
4334    ///
4335    /// A free function rather than the duty's body so each refusal reads as an early return
4336    /// instead of another copy of the same emit. The pixels never cross the boundary: Java
4337    /// compresses and hands back one `byte[]`.
4338    fn encode_bitmap(
4339        id: day_spec::BitmapId,
4340        spec: &day_spec::EncodeSpec,
4341    ) -> Result<Vec<u8>, day_spec::ImageError> {
4342        use day_spec::ImageFormat as F;
4343        let format = match spec.format {
4344            F::Png => "png",
4345            F::Jpeg => "jpeg",
4346            // `Bitmap.compress` writes nothing else under this minSdk; `encode_formats` says so
4347            // before an app asks.
4348            _ => return Err(day_spec::ImageError::Encode),
4349        };
4350        if !BITMAP_INFO.with(|m| m.borrow().contains_key(&id.0)) {
4351            return Err(day_spec::ImageError::Gone);
4352        }
4353        if !vm_ready() {
4354            return Err(day_spec::ImageError::Unsupported);
4355        }
4356        // Android takes quality as 0..=100; -1 means the format's own default.
4357        let quality = spec
4358            .quality
4359            .map_or(-1, |q| (q.clamp(0.0, 1.0) * 100.0).round() as i32);
4360        let (fit_w, fit_h) = spec.fit.map_or((0.0, 0.0), |f| (f.width, f.height));
4361        with_env(|env| {
4362            let jfmt = jstr(env, format);
4363            java_in(env, |env| {
4364                let arr = DayBridge::imageEncode(env, id.0 as i64, &jfmt, quality, fit_w, fit_h)?;
4365                if arr.is_null() {
4366                    return Ok(None);
4367                }
4368                env.convert_byte_array(&arr).map(Some)
4369            })
4370            .flatten()
4371        })
4372        .ok_or(day_spec::ImageError::Encode)
4373    }
4374
4375    /// The platform's reason for the export that just failed, or `fallback` when the call
4376    /// itself failed before Java could record one.
4377    fn export_failure(env: &mut Env, fallback: &str) -> day_spec::ExportError {
4378        let why = java_string(env, DayCanvasView::exportError)
4379            .filter(|s| !s.is_empty())
4380            .unwrap_or_else(|| fallback.to_string());
4381        day_spec::ExportError::Failed(why)
4382    }
4383
4384    /// `render_bitmap`'s body, on a painting thread (docs/canvas.md "Exporting"): the ops
4385    /// encoded for the wire, then one JNI call that paints and stores the bitmap, with the
4386    /// facts of what was stored as the answer. `with_env` attaches this thread to the JVM for
4387    /// the call, and the binding resolves `DayCanvasView` through the app class loader, so
4388    /// the call works from a thread Java never saw. A free function so each refusal is an
4389    /// early return.
4390    fn export_bitmap(
4391        id: day_spec::BitmapId,
4392        ops: &[DrawOp],
4393        pw: u32,
4394        ph: u32,
4395        scale: f64,
4396    ) -> Result<day_spec::BitmapInfo, day_spec::ExportError> {
4397        // day-core caps a side at 16,384 pixels, so both fit an `int`.
4398        let (Ok(jw), Ok(jh)) = (i32::try_from(pw), i32::try_from(ph)) else {
4399            return Err(day_spec::ExportError::TooLarge {
4400                width: pw,
4401                height: ph,
4402            });
4403        };
4404        let (nums, texts, geometry) = day_spec::encode_ops_with_geometry(ops);
4405        with_env(|env| {
4406            let refused = java_in(env, |env| {
4407                let arr = env.new_double_array(nums.len())?;
4408                arr.set_region(env, 0, &nums)?;
4409                let geo = env.new_double_array(geometry.len())?;
4410                geo.set_region(env, 0, &geometry)?;
4411                let joined = JString::from_str(env, texts.join("\u{1f}"))?;
4412                let why = DayCanvasView::renderBitmap(
4413                    env,
4414                    id.0 as i64,
4415                    &arr,
4416                    &joined,
4417                    &geo,
4418                    jw,
4419                    jh,
4420                    scale,
4421                )?;
4422                if why.is_null() {
4423                    return Ok(None);
4424                }
4425                Ok(Some(string_of(env, &why).unwrap_or_default()))
4426            });
4427            match refused {
4428                Some(None) => Ok(day_spec::BitmapInfo {
4429                    pixels: Size::new(f64::from(pw), f64::from(ph)),
4430                    scale,
4431                    format: None,
4432                    // Created ARGB_8888 on a transparent field.
4433                    has_alpha: true,
4434                }),
4435                Some(Some(why)) => Err(day_spec::ExportError::Failed(if why.is_empty() {
4436                    "the bitmap could not be created".to_string()
4437                } else {
4438                    why
4439                })),
4440                None => Err(day_spec::ExportError::Failed(
4441                    "the bitmap render call failed".into(),
4442                )),
4443            }
4444        })
4445    }
4446
4447    /// `render_pdf`'s body. The pages cross JNI in one call: every page's numbers in one
4448    /// `double[]` and its texts in one joined string, with per-page counts to split them by,
4449    /// so no page state lives in Java between calls.
4450    fn export_pdf(pages: &[day_spec::PdfPage]) -> Result<Vec<u8>, day_spec::ExportError> {
4451        if !vm_ready() {
4452            return Err(day_spec::ExportError::Unsupported);
4453        }
4454        let mut nums = Vec::new();
4455        let mut texts = Vec::new();
4456        let mut num_counts = Vec::with_capacity(pages.len());
4457        let mut text_counts = Vec::with_capacity(pages.len());
4458        let mut sizes = Vec::with_capacity(pages.len() * 2);
4459        for page in pages {
4460            let (n, t) = day_spec::encode_ops(&page.ops);
4461            let counts = (i32::try_from(n.len()), i32::try_from(t.len()));
4462            let (Ok(nc), Ok(tc)) = counts else {
4463                return Err(day_spec::ExportError::Invalid);
4464            };
4465            num_counts.push(nc);
4466            text_counts.push(tc);
4467            nums.extend_from_slice(&n);
4468            texts.extend(t);
4469            sizes.push(page.size.width);
4470            sizes.push(page.size.height);
4471        }
4472        with_env(|env| {
4473            let bytes = java_in(env, |env| {
4474                let jnums = env.new_double_array(nums.len())?;
4475                jnums.set_region(env, 0, &nums)?;
4476                let jnum_counts = env.new_int_array(num_counts.len())?;
4477                jnum_counts.set_region(env, 0, &num_counts)?;
4478                let jtext_counts = env.new_int_array(text_counts.len())?;
4479                jtext_counts.set_region(env, 0, &text_counts)?;
4480                let jsizes = env.new_double_array(sizes.len())?;
4481                jsizes.set_region(env, 0, &sizes)?;
4482                let joined = JString::from_str(env, texts.join("\u{1f}"))?;
4483                let arr = DayCanvasView::renderPdf(
4484                    env,
4485                    &jnums,
4486                    &jnum_counts,
4487                    &joined,
4488                    &jtext_counts,
4489                    &jsizes,
4490                )?;
4491                if arr.is_null() {
4492                    return Ok(None);
4493                }
4494                env.convert_byte_array(&arr).map(Some)
4495            });
4496            match bytes {
4497                Some(Some(pdf)) => Ok(pdf),
4498                Some(None) => Err(export_failure(env, "the PDF could not be written")),
4499                None => Err(day_spec::ExportError::Failed(
4500                    "the PDF render call failed".into(),
4501                )),
4502            }
4503        })
4504    }
4505
4506    /// Ask the bridge for a PNG of this app's window (docs/window-image.md).
4507    ///
4508    /// The bytes come back as a Java `byte[]` and are copied out with `convert_byte_array`: no
4509    /// base64 round trip for what is already binary.
4510    fn android_window_image(chrome: bool) -> Result<Vec<u8>, String> {
4511        with_env(|env| {
4512            let arr = DayBridge::windowImage(env, chrome).map_err(|e| {
4513                env.exception_clear();
4514                format!("windowImage: {e}")
4515            })?;
4516            if arr.is_null() {
4517                return Err("no window to capture".to_string());
4518            }
4519            env.convert_byte_array(&arr)
4520                .map_err(|e| format!("windowImage: {e}"))
4521        })
4522    }
4523
4524    impl Toolkit for Material {
4525        type Handle = AHandle;
4526
4527        fn set_drag_source(&mut self, h: &AHandle, source: day_spec::transfer::Source) {
4528            TRANSFER_SOURCES.with(|t| t.insert(h.0.as_obj().as_raw() as usize, source));
4529            transfer_install(h, true);
4530        }
4531        fn set_drop_target(&mut self, h: &AHandle, target: day_spec::transfer::Target) {
4532            TRANSFER_TARGETS.with(|t| t.insert(h.0.as_obj().as_raw() as usize, target));
4533            transfer_install(h, false);
4534        }
4535        #[expect(
4536            clippy::match_same_arms,
4537            reason = "one arm per capability, each documented with the Android mechanism behind it"
4538        )]
4539        fn capability(&self, cap: Cap) -> Support {
4540            match cap {
4541            // `ChooserAction`s on the system chooser, which Android 14 (API 34) introduced.
4542            Cap::ShareActions if day_platform_android::sdk_int() >= 34 => Support::Native,
4543            Cap::ShareActions => Support::Unsupported,
4544            Cap::SearchField => Support::Native,
4545            Cap::ComboBox => Support::Native,
4546            Cap::Stepper => Support::Emulated,
4547            Cap::DateTimePicker => Support::Native,
4548            Cap::ColorPicker => Support::Emulated,
4549            Cap::PullRefresh => Support::Native,
4550            Cap::Pager => Support::Native,
4551            Cap::PullRefreshGesture => Support::Native,
4552                Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems => Support::Native,
4553                // `View.setPointerIcon` with a system `PointerIcon` per view (docs/cursor.md).
4554                Cap::Cursor => Support::Native,
4555                // `.focusable()` (DayBridge.enableKeys): focusable in touch mode, focus on a
4556                // primary press, both focus reports, the short and full key routes, the
4557                // platform's default focus highlight for keyboard focus (docs/focus.md).
4558                Cap::Focusable => Support::Native,
4559                // `KeyEvent.getRepeatCount` for repeats and `ACTION_UP` for releases, each
4560                // only for the node its down was delivered to (DayCanvasView.sendKey).
4561                Cap::KeyPhases => Support::Native,
4562                // The parent's TouchDelegate (DayBridge `SlopDelegate`); it cannot reach past
4563                // the parent's own bounds (docs/gestures.md "Toolkit support").
4564                Cap::HitSlop => Support::Native,
4565                // The families `fonts.xml` names, the ones `Typeface.create` resolves
4566                // (docs/fonts.md).
4567                Cap::FontList => Support::Native,
4568                // DayListItem: a Material 3 list item (docs/list.md "List items").
4569                Cap::ListItem => Support::Native,
4570                // RecyclerView has no sticky headers: header rows take their own view type, and
4571                // DayListView pins a copy of the current one in the list's overlay, pushed up by
4572                // the next (docs/list.md "Sections").
4573                Cap::ListSections => Support::Emulated,
4574                // `RecyclerView.OnScrollListener` and every layout pass report the first and
4575                // last visible rows (`findFirst/LastVisibleItemPosition`) and the distance to
4576                // the end (docs/list.md "Visible rows").
4577                Cap::ListViewport => Support::Native,
4578                // DayListView reports the first move of a drag (`SCROLL_STATE_DRAGGING`, which
4579                // a touch that catches a glide also enters) and of the scroll a wheel, a
4580                // scrolling key or an accessibility scroll action starts; Day's own scrolls
4581                // settle without dragging (docs/list.md "Following the end").
4582                Cap::ListReaderScroll => Support::Native,
4583                // `scrollToPositionWithOffset` for a jump, RecyclerView's `smoothScrollBy` over
4584                // the aligned distance for an animation (docs/list.md "Programmatic scrolling").
4585                Cap::ListScrollAlign => Support::Native,
4586                // `onScrollChanged`, one report per frame plus the resting one (docs/scroll.md).
4587                Cap::ScrollOffset => Support::Native,
4588                // ScrollView has no scroll-state callback; its subclass reads the moments from
4589                // its own touch stream and `fling()`: a drag moving the content, a fling or
4590                // snap after the lift, the content still for four frames (docs/scroll.md).
4591                Cap::ScrollPhases => Support::Native,
4592                // ScrollView does not snap: its subclass takes over `fling()` and the release
4593                // and `smoothScrollTo`s the stop the fling would reach, rounded to the page or
4594                // the interval (docs/scroll.md "Paging and snapping").
4595                Cap::ScrollSnap => Support::Emulated,
4596                // The IME is hidden (`hideSoftInputFromWindow`, focus cleared) when a drag
4597                // begins; `KeyboardTaps::Dismiss` intercepts a tap off a text field while it is
4598                // up. No interactive mode: it behaves as `OnDrag` (docs/scroll.md "Keyboard").
4599                Cap::ScrollKeyboardDismiss => Support::Native,
4600                // No Android scroll view zooms; `ScrollProps::zoom` and `ScrollPatch::Zoom` are
4601                // ignored (docs/scroll.md "Zoom").
4602                Cap::ScrollZoom => Support::Unsupported,
4603                // ViewPager's `onPageScrolled` (docs/pager.md "Progress").
4604                Cap::PagerProgress => Support::Native,
4605                // `BitmapFactory` decodes every container Android reads, and `Bitmap.compress`
4606                // writes back PNG and JPEG (docs/images.md). WebP decodes here but is not
4607                // offered for encode: the modern `WEBP_LOSSY`/`WEBP_LOSSLESS` constants are
4608                // API 30 and the scaffold's minSdk is 24. `Cap::ImageProperties` is
4609                // absent because there is no metadata reader on this path, and an empty struct
4610                // would read as "this file records nothing" rather than "nobody looked".
4611                Cap::ImageDecode | Cap::ImageEncode => Support::Native,
4612                // Canvas exports paint with DayCanvasView's own OpPainter: into a `Bitmap` for the
4613                // bitmap, onto `PdfDocument` pages for the PDF (docs/canvas.md "Exporting").
4614                Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
4615                // `View.draw(Canvas)` renders this app's own window into a bitmap
4616                // (docs/window-image.md); surface-backed content is the documented gap.
4617                Cap::Snapshot => Support::Native,
4618                // An app-level light/dark override, through `UiModeManager` (API 31 and up).
4619                // Answered from the device rather than pinned for the backend: below 31 the only
4620                // route is AppCompat's delegate, which does not restyle the plain
4621                // `FragmentActivity` Day runs in, so there the answer is that there is no such
4622                // control, and `day-piece-settings` draws no appearance row rather than one
4623                // that does nothing.
4624                Cap::Appearance => {
4625                    if with_env(|env| {
4626                        DayBridge::canSetAppearance(env)
4627                        .unwrap_or(false)
4628                    }) {
4629                        Support::Native
4630                    } else {
4631                        Support::Unsupported
4632                    }
4633                }
4634                // SpannableString spans, drawn by the one TextView (docs/text-runs.md).
4635                // A link run is a ClickableSpan; the TextView takes LinkMovementMethod when one
4636                // is present, which is what makes the tap land.
4637                Cap::TextRuns | Cap::TextLinks => Support::Native,
4638                // A selectable label is a `DayLabel` (a TextView) whose `onSelectionChanged`
4639                // reports each new range (docs/text.md "Hearing about the selection").
4640                Cap::LabelSelection => Support::Native,
4641                // `announceForAccessibility` on the window's content view: the platform's
4642                // announcement event, sent only while an accessibility service is enabled
4643                // (docs/accessibility.md).
4644                Cap::Announce => Support::Native,
4645                // The global animator duration scale, zero under Accessibility's "Remove
4646                // animations", read from the settings provider and watched through a
4647                // ContentObserver (docs/accessibility.md).
4648                Cap::ReduceMotion => Support::Native,
4649                // EditText honors editable / selectable / spell-check (DayTextArea shim).
4650                Cap::Dialogs
4651                | Cap::FileDialogs
4652                | Cap::Animation
4653                | Cap::Cover
4654                // WindowInsetsControllerCompat hides the status bar (docs/cover.md).
4655                | Cap::StatusBarHidden
4656                // The MaterialToolbar names the destination on every page (DayNavHost
4657                // syncChrome), so content needn't repeat the title (docs/navigation.md).
4658                | Cap::NavHeader
4659                // The window toolbar goes in the nav host's app bar (docs/toolbars.md), as
4660                // menu items shown as actions: one bar per window, at every width, with what
4661                // the bar cannot fit folding into its overflow.
4662                | Cap::Toolbar
4663                // A SlidingPaneLayout hosts every `nav(Sidebar)`, so two panes are
4664                // available wherever they fit: a tablet, a foldable open, a phone in landscape
4665                // if the widths allow (docs/size-classes.md).
4666                | Cap::NavSplit
4667                | Cap::TextEditable
4668                | Cap::TextSelectable
4669                | Cap::TextSpellCheck
4670                // ItemTouchHelper on the RecyclerView list: long-press lift, elevation,
4671                // incremental swaps: the platform's own reorder (docs/list.md).
4672                | Cap::ListReorder
4673                // RecyclerView's holder pool: `onBindViewHolder` rebinds Day's cells for new
4674                // rows and `onViewRecycled` parks them (docs/list.md).
4675                | Cap::ListRecycling
4676                // ItemTouchHelper's swipe half, with the Material red field revealing behind
4677                // the row (docs/list.md).
4678                | Cap::ListDelete
4679                // The window's insets controller hides the system bars, swipe to reveal them
4680                // transiently; the state reports once the bars have moved (docs/windows.md).
4681                | Cap::WindowFullscreen
4682                // FLAG_SECURE on the window's activity: screenshots, recordings, casting and
4683                // the recents thumbnail see black (docs/windows.md). `Cap::WindowStates` stays
4684                // Unsupported: an app cannot minimize or maximize its own window here, so
4685                // those requests report the state the window kept.
4686                | Cap::ContentProtection
4687                // Document-style DayWindowActivity instances (docs/windows.md): separate
4688                // recents entries; side-by-side in split-screen/freeform/desktop windowing.
4689                | Cap::MultiWindow
4690                // View.getBaseline(), the platform's own answer (docs/baseline.md).
4691                | Cap::BaselineAlignment
4692                // The navigation suite (DayTabs): a BottomNavigationView, a NavigationRailView or
4693                // a permanent NavigationView drawer over resident pages: Material's own
4694                // destination chrome, in the form the width calls for (docs/navigation.md).
4695                | Cap::NavTabs
4696                // And Android should grow one as it narrows: a bottom bar is the idiomatic
4697                // compact answer here, the way it is on iOS and unlike any desktop.
4698                | Cap::NavTabsAdaptive => Support::Native,
4699                // Keep navigation on Material NavigationView. A reorderable RecyclerView
4700                // substitutes generic rows and its long-press drag steals feed menus.
4701                // Generic lists still support reordering; navigation needs an edit-mode API.
4702                Cap::NavReorder => Support::Unsupported,
4703                // `Emulated`: SlidingPaneLayout decides at measure time whether both panes fit, so
4704                // the platform owns the presentation and Day observes it through
4705                // `Event::NavPresentationChanged` rather than pushing one in
4706                // (docs/size-classes.md).
4707                Cap::NavRepresent => Support::Emulated,
4708                // The display the primary window is on: one, however many are attached
4709                // (docs/windows.md).
4710                Cap::Monitors => Support::Emulated,
4711                // ShortcutManager's dynamic shortcuts, from API 25 (docs/deep-links.md).
4712                Cap::DynamicShortcuts => {
4713                    if with_env(|env| {
4714                        DayBridge::canSetLauncherShortcuts(env)
4715                            .unwrap_or(false)
4716                    }) {
4717                        Support::Native
4718                    } else {
4719                        Support::Unsupported
4720                    }
4721                }
4722                // The composed tree (docs/tree.md M2/M5): the piece flattens onto this
4723                // backend's RecyclerView list; disclosure, indentation and row content are
4724                // day pieces. No native drag wiring yet, so `Cap::TreeMove` stays
4725                // Unsupported (`tree_move:` drives the move synthetically).
4726                Cap::Tree => Support::Emulated,
4727                Cap::TreeSections => Support::Native,
4728                _ => Support::Unsupported,
4729            }
4730        }
4731
4732        fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
4733            // Any non-empty request enters swipe-to-reveal immersive mode (docs/cover.md).
4734            bridge(|env| DayBridge::setDeferSystemGestures(env, !edges.is_empty()));
4735        }
4736
4737        fn set_status_bar_hidden(&mut self, hidden: bool) {
4738            // The insets controller hides the status bar; the edge-to-edge root then sees the
4739            // smaller top inset through its usual inset listener (docs/cover.md).
4740            bridge(|env| DayBridge::setStatusBarHidden(env, hidden));
4741        }
4742
4743        fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
4744            use day_spec::present::PresentSpec;
4745            let reqj = req as i64;
4746            match spec {
4747                PresentSpec::Dialog { sheet, .. } => with_env(|env| {
4748                    let title = jstr(env, spec.title());
4749                    let message = jstr(env, spec.message().unwrap_or(""));
4750                    let buttons = jstr(env, &spec.buttons_joined());
4751                    let roles = jstr(env, &spec.roles_joined());
4752                    let _ = java_in(env, |env| {
4753                        DayBridge::present(env, reqj, *sheet, &title, &message, &buttons, &roles)
4754                    });
4755                }),
4756                PresentSpec::Prompt {
4757                    placeholder,
4758                    initial,
4759                    ok,
4760                    cancel,
4761                    ..
4762                } => with_env(|env| {
4763                    let title = jstr(env, spec.title());
4764                    let message = jstr(env, spec.message().unwrap_or(""));
4765                    let ph = jstr(env, placeholder);
4766                    let init = jstr(env, initial);
4767                    let okj = jstr(env, ok);
4768                    let cancelj = jstr(env, cancel);
4769                    let _ = java_in(env, |env| {
4770                        DayBridge::presentPrompt(
4771                            env, reqj, &title, &message, &ph, &init, &okj, &cancelj,
4772                        )
4773                    });
4774                }),
4775                // Storage Access Framework (docs/files.md). Java launches ACTION_OPEN_DOCUMENT /
4776                // ACTION_CREATE_DOCUMENT and, on result, copies through the ContentResolver: open →
4777                // an app cache file (readable path); save → the chosen content:// URI.
4778                PresentSpec::OpenFile { multiple, .. } => with_env(|env| {
4779                    let title = jstr(env, spec.title());
4780                    let filters = jstr(env, &spec.filters_joined());
4781                    let _ = java_in(env, |env| {
4782                        DayBridge::presentFileOpen(env, reqj, &title, &filters, *multiple)
4783                    });
4784                }),
4785                // No folder chooser on Android (`Cap::FolderDialog` is Unsupported): a tree
4786                // URI's persisted access is its own feature, so the request resolves at once.
4787                PresentSpec::OpenFolder { .. } => emit(
4788                    day_spec::WINDOW_NODE,
4789                    Event::PresentResult {
4790                        req,
4791                        result: day_spec::present::PresentResult::Dismissed,
4792                    },
4793                ),
4794                PresentSpec::SaveFile {
4795                    suggested_name,
4796                    src_path,
4797                    ..
4798                } => with_env(|env| {
4799                    let title = jstr(env, spec.title());
4800                    let name = jstr(env, suggested_name);
4801                    let src = jstr(env, src_path);
4802                    let filters = jstr(env, &spec.filters_joined());
4803                    let _ = java_in(env, |env| {
4804                        DayBridge::presentFileSave(env, reqj, &title, &name, &src, &filters)
4805                    });
4806                }),
4807            }
4808        }
4809
4810        fn dismiss(&mut self, req: u64) {
4811            bridge(|env| DayBridge::dismissPresent(env, req as i64));
4812        }
4813
4814        fn share_support(&self) -> day_spec::Support {
4815            day_spec::Support::Native
4816        }
4817        fn share(
4818            &mut self,
4819            spec: &day_spec::share::ShareSpec,
4820            _anchor: Option<&Self::Handle>,
4821        ) -> bool {
4822            use std::fmt::Write as _;
4823            // The app's actions cross as lines of `id \t drawable \t title`; the drawable is
4824            // the action's symbol (`day_symbol_*`), or empty for the chooser's default glyph.
4825            let actions = spec.actions.iter().fold(String::new(), |mut out, a| {
4826                let title: String = a
4827                    .title
4828                    .chars()
4829                    .map(|c| if c == '\t' || c == '\n' { ' ' } else { c })
4830                    .collect();
4831                let icon = a.symbol.map_or_default(symbol_drawable);
4832                let _ = writeln!(out, "{}\t{icon}\t{title}", a.id);
4833                out
4834            });
4835            with_env(|env| {
4836                let url = jstr(env, &spec.url);
4837                let title = jstr(env, &spec.title);
4838                let actions = jstr(env, &actions);
4839                java_in(env, |env| DayBridge::share(env, &url, &title, &actions)).unwrap_or(false)
4840            })
4841        }
4842
4843        fn open_url(&mut self, url: &str) {
4844            with_env(|env| {
4845                let u = jstr(env, url);
4846                let _ = java_in(env, |env| DayBridge::openUrl(env, &u));
4847            });
4848        }
4849
4850        fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> AHandle {
4851            let idj = id.0 as i64;
4852            match Builtin::from_key(kind) {
4853                Some(Builtin::Container) => {
4854                    let h = with_env(|env| {
4855                        AHandle(bridge_view(env, "makeContainer", |env| {
4856                            DayBridge::makeContainer(env)
4857                        }))
4858                    });
4859                    if let Some(p) = props.downcast_ref::<ContainerProps>() {
4860                        if p.role == Some(day_spec::SurfaceRole::SectionCard) {
4861                            let d = DENSITY.with(std::cell::Cell::get);
4862                            bridge(|env| {
4863                                DayBridge::setSectionCard(
4864                                    env,
4865                                    h.0.as_obj(),
4866                                    (p.corner_radius * d) as f32,
4867                                )
4868                            });
4869                        } else if p.role == Some(day_spec::SurfaceRole::Window) {
4870                            let d = DENSITY.with(std::cell::Cell::get);
4871                            bridge(|env| {
4872                                DayBridge::setWindowSurface(
4873                                    env,
4874                                    h.0.as_obj(),
4875                                    (p.corner_radius * d) as f32,
4876                                    p.clips,
4877                                )
4878                            });
4879                        } else {
4880                            apply_container_surface(&h, p, true);
4881                        }
4882                    }
4883                    h
4884                }
4885                Some(Builtin::Scroll) => {
4886                    // The preferences ride one flag word (docs/scroll.md; `list_wire`): Android
4887                    // has no zoom, so `zoom` is left out (`Cap::ScrollZoom` is Unsupported).
4888                    let p = props.downcast_ref::<day_spec::props::ScrollProps>();
4889                    let horizontal = p.is_some_and(|p| p.horizontal);
4890                    let (flags, snap_px) =
4891                        p.map_or((0, 0.0), |p| crate::list_wire::scroll_flags(p, density()));
4892                    with_env(|env| {
4893                        AHandle(bridge_view(env, "makeScroll", |env| {
4894                            DayBridge::makeScroll(env, horizontal, flags, snap_px, id.0 as i64)
4895                        }))
4896                    })
4897                }
4898                Some(Builtin::Tree) => {
4899                    let Some(p) = day_spec::props_of::<TreeProps>(kind, "android", props) else {
4900                        return realize_placeholder(kind);
4901                    };
4902                    let height = match p.row_height {
4903                        RowHeight::Uniform(h) => h,
4904                        RowHeight::Automatic => 36.0,
4905                    };
4906                    let handle = with_env(|env| {
4907                        AHandle(bridge_view(env, "makeTree", |env| {
4908                            DayBridge::makeTree(
4909                                env,
4910                                id.0 as i64,
4911                                (height * DENSITY.with(std::cell::Cell::get)).round() as i32,
4912                                p.selectable,
4913                            )
4914                        }))
4915                    });
4916                    LIST_NODE.with(|m| {
4917                        m.borrow_mut()
4918                            .insert(handle.0.as_obj().as_raw() as usize, id.0 as i64)
4919                    });
4920                    handle
4921                }
4922                Some(Builtin::List) => {
4923                    let Some(p) = day_spec::props_of::<ListProps>(kind, "android", props) else {
4924                        return realize_placeholder(kind);
4925                    };
4926                    let d = DENSITY.with(std::cell::Cell::get);
4927                    let rowh = match p.row_height {
4928                        RowHeight::Uniform(h) => h,
4929                        RowHeight::Automatic => 44.0,
4930                    };
4931                    let handle = with_env(|env| {
4932                        let del_label = jstr(env, &p.delete_label);
4933                        AHandle(bridge_view(env, "makeList", |env| {
4934                            DayBridge::makeList(
4935                                env,
4936                                id.0 as i64,
4937                                (rowh * d).round() as i32,
4938                                p.selectable,
4939                                p.reorderable,
4940                                p.deletable,
4941                                &del_label,
4942                            )
4943                        }))
4944                    });
4945                    LIST_NODE.with(|m| {
4946                        m.borrow_mut()
4947                            .insert(handle.0.as_obj().as_raw() as usize, id.0 as i64)
4948                    });
4949                    if p.row_height == RowHeight::Automatic {
4950                        LIST_AUTOMATIC.with(|m| m.borrow_mut().insert(id.0 as i64));
4951                    }
4952                    // Before the first bind (attach_list reloads): headers take their own view
4953                    // type from the start (docs/list.md "Sections").
4954                    if p.sections {
4955                        bridge(|env| DayBridge::listSetSections(env, handle.0.as_obj(), true));
4956                    }
4957                    handle
4958                }
4959                Some(Builtin::Nav) => {
4960                    let Some(p) = day_spec::props_of::<NavProps>(kind, "android", props) else {
4961                        return realize_placeholder(kind);
4962                    };
4963                    // Where the rows are the chrome, the host is a navigation suite rather than a
4964                    // pane layout: pages resident behind a bottom bar, a rail or a permanent
4965                    // drawer, whichever the width calls for (DayTabs). One container across every
4966                    // width is what lets the host report `Tabs` once and keep it, so day-core
4967                    // holds the pages and drives them with `Select` instead of push/pop, the
4968                    // same contract `.tabSidebar` gives on iOS.
4969                    if p.presentation.rows_are_chrome() {
4970                        let host = with_env(|env| {
4971                            AHandle(bridge_view(env, "makeNavSuite", |env| {
4972                                DayBridge::makeNavSuite(env, idj, 0)
4973                            }))
4974                        });
4975                        if let Some(config) = &p.documents {
4976                            with_env(|env| {
4977                                let new_label = jstr(env, &config.new_label);
4978                                let close_label = jstr(env, &config.close_label);
4979                                let _ = java_in(env, |env| {
4980                                    DayBridge::documentNavSuite(
4981                                        env,
4982                                        host.0.as_obj(),
4983                                        &new_label,
4984                                        &close_label,
4985                                        config.can_add,
4986                                    )
4987                                });
4988                            });
4989                        }
4990                        NAV_SUITES
4991                            .with(|m| m.borrow_mut().insert(host.0.as_obj().as_raw() as usize));
4992                        // Tell day-core what it got. The suite changes its chrome as it resizes
4993                        // but never its presentation, so this is reported once and never revised.
4994                        emit(
4995                            id,
4996                            Event::NavPresentationChanged(day_spec::props::NavPresentation::Tabs),
4997                        );
4998                        return host;
4999                    }
5000                    // `Stack` in props is literal, a host that is a stack at every size (a
5001                    // nested `nav_stack()` under a split host, docs/size-classes.md), so it gets a
5002                    // plain single-pane host. Only an adaptive host builds a SlidingPaneLayout;
5003                    // nesting one inside a pane re-runs the whole tiling decision at pane width.
5004                    let adaptive = p.presentation != day_spec::props::NavPresentation::Stack;
5005                    let host = with_env(|env| {
5006                        let s = jstr(env, &p.title);
5007                        // The tiling threshold comes from Day's breakpoint table, so the platform's
5008                        // measure-time answer agrees with it.
5009                        let split = day_spec::SizeClass::SPLIT_MIN_WIDTH as f32;
5010                        AHandle(bridge_view(env, "makeNavHost", |env| {
5011                            DayBridge::makeNavHost(env, idj, &s, adaptive, split)
5012                        }))
5013                    });
5014                    // Inline search (docs/search.md): the field above the navigation list. The app
5015                    // bar holds actions, never a field (`Cap::ToolbarSearch` is unsupported), so
5016                    // every placement resolves here. Applied after the host is built, and
5017                    // best-effort, since a throw on the host's own build path blanks the app.
5018                    if let Some(sp) = p
5019                        .search
5020                        .as_ref()
5021                        .filter(|sp| sp.placement == day_spec::props::SearchPlacement::Inline)
5022                    {
5023                        let (prompt, text) = (sp.prompt.clone(), sp.text.clone());
5024                        with_env(|env| {
5025                            let pr = jstr(env, &prompt);
5026                            let tx = jstr(env, &text);
5027                            let _ = java_in(env, |env| {
5028                                DayBridge::setNavSearch(
5029                                    env,
5030                                    host.0.as_obj(),
5031                                    idj,
5032                                    &pr,
5033                                    &tx,
5034                                    sp.hides_on_scroll,
5035                                    sp.initially_hidden,
5036                                )
5037                            });
5038                            if env.exception_check() {
5039                                env.exception_clear();
5040                            }
5041                        });
5042                    }
5043                    host
5044                }
5045                Some(Builtin::NavPage) => with_env(|env| {
5046                    let h = AHandle(bridge_view(env, "makeNavPage", |env| {
5047                        DayBridge::makeNavPage(
5048                            env,
5049                            idj,
5050                            day_spec::props_of::<NavPageProps>(kind, "android", props)
5051                                .is_some_and(|p| p.immersive),
5052                        )
5053                    }));
5054                    // A sidebar page inside a navigation suite is the page whose rows BECAME the
5055                    // chrome, so the suite keeps it attached but never shows it (drawing the rows
5056                    // again as a list would be the same navigation twice). Marked here because
5057                    // `insert` sees only handles; harmless anywhere else, where nothing reads it.
5058                    let sidebar = day_spec::props_of::<NavPageProps>(kind, "android", props)
5059                        .is_some_and(|p| p.pane == day_spec::props::Pane::Sidebar);
5060                    if sidebar {
5061                        let _ = java_in(env, |env| DayBridge::markNavChromePage(env, h.0.as_obj()));
5062                    }
5063                    h
5064                }),
5065                // Fullscreen cover (docs/cover.md): a DayCover shell whose content pane is the
5066                // Day mount point; CoverPatch::Present re-homes it over the activity content.
5067                // A half sheet (`CoverProps::half`) is the same shell as a Material bottom
5068                // sheet over the bottom half of the window.
5069                Some(Builtin::Cover) => {
5070                    let half = day_spec::props_of::<CoverProps>(kind, "android", props)
5071                        .is_some_and(|p| p.half);
5072                    with_env(|env| {
5073                        AHandle(bridge_view(env, "makeCover", |env| {
5074                            DayBridge::makeCover(env, idj, half)
5075                        }))
5076                    })
5077                }
5078                Some(Builtin::NavMenu) => {
5079                    let Some(p) = day_spec::props_of::<NavMenuProps>(kind, "android", props) else {
5080                        return realize_placeholder(kind);
5081                    };
5082                    let joined = p.items.join("\u{1f}");
5083                    // Parallel, index-aligned icon NAMES ("" = no icon for that row).
5084                    let joined_icons = p
5085                        .icons
5086                        .iter()
5087                        .map(|o| o.clone().unwrap_or_default())
5088                        .collect::<Vec<_>>()
5089                        .join("\u{1f}");
5090                    let joined_tints = nav_tints_joined(
5091                        &p.tints
5092                            .iter()
5093                            .map(|t| t.map(day_spec::Ink::resolved))
5094                            .collect::<Vec<_>>(),
5095                    );
5096                    let joined_badge_icons = p
5097                        .badge_icons
5098                        .iter()
5099                        .map(|o| o.clone().unwrap_or_default())
5100                        .collect::<Vec<_>>()
5101                        .join("\u{1f}");
5102                    let joined_badge_tints = nav_tints_joined(
5103                        &p.badge_tints
5104                            .iter()
5105                            .map(|t| t.map(day_spec::Ink::resolved))
5106                            .collect::<Vec<_>>(),
5107                    );
5108                    let joined_menus = nav_menus_joined(&p.menus);
5109                    // Headings, index-aligned with the rows ("" continues the current group).
5110                    // NavigationView draws them as M3 subheaders; the flat list this replaced
5111                    // dropped them, so the showcase's eight groups arrived as twenty bare rows.
5112                    let joined_sections = p
5113                        .sections
5114                        .iter()
5115                        .map(|o| o.clone().unwrap_or_default())
5116                        .collect::<Vec<_>>()
5117                        .join("\u{1f}");
5118                    with_env(|env| {
5119                        let s = jstr(env, &joined);
5120                        let si = jstr(env, &joined_icons);
5121                        let ss = jstr(env, &joined_sections);
5122                        let handle = AHandle(bridge_view(env, "makeNavMenu", |env| {
5123                            DayBridge::makeNavMenu(env, idj, &s, &si, &ss)
5124                        }));
5125                        // Keep the rows for `insert`, which is where a navigation suite above
5126                        // this menu can finally be found and handed them.
5127                        let texts = p
5128                            .badges
5129                            .iter()
5130                            .map(|s| s.as_deref().unwrap_or(""))
5131                            .collect::<Vec<_>>()
5132                            .join("\u{1f}");
5133                        NAV_MENU_ROWS.with(|m| {
5134                            m.borrow_mut().insert(
5135                                handle.0.as_obj().as_raw() as usize,
5136                                (
5137                                    idj,
5138                                    joined.clone(),
5139                                    joined_icons.clone(),
5140                                    p.document_keys.join("\u{1f}"),
5141                                    texts.clone(),
5142                                ),
5143                            )
5144                        });
5145                        // Per-row icon tints ride a best-effort follow-up (docs/vectors.md):
5146                        // decoration stays off makeNavMenu's critical path, so a tint problem
5147                        // can never abort the tree build (the navhost lesson).
5148                        let st = jstr(env, &joined_tints);
5149                        let _ = java_in(env, |env| {
5150                            DayBridge::setNavMenuTints(env, handle.0.as_obj(), &st)
5151                        });
5152                        // The trailing status glyph (docs/navigation.md), same best-effort rule.
5153                        let counts = jstr(env, &texts);
5154                        let sb = jstr(env, &joined_badge_icons);
5155                        let sbt = jstr(env, &joined_badge_tints);
5156                        let _ = java_in(env, |env| {
5157                            DayBridge::setNavMenuBadges(env, handle.0.as_obj(), &sb, &sbt, &counts)
5158                        });
5159                        // The active indicator the model already carries: a rebuilt sidebar
5160                        // (a language change, a data-driven item set) has to come back marking
5161                        // the same page rather than blank.
5162                        nav_menu_select(env, &handle, p.selected);
5163                        // Per-row context menus (docs/menus.md): same best-effort follow-up.
5164                        let sm = jstr(env, &joined_menus);
5165                        let _ = java_in(env, |env| {
5166                            DayBridge::setNavRowMenus(env, handle.0.as_obj(), &sm)
5167                        });
5168                        if env.exception_check() {
5169                            env.exception_clear();
5170                        }
5171                        handle
5172                    })
5173                }
5174                Some(Builtin::Label) => {
5175                    let Some(p) = day_spec::props_of::<LabelProps>(kind, "android", props) else {
5176                        return realize_placeholder(kind);
5177                    };
5178                    with_env(|env| {
5179                        let s = jstr(env, &p.text);
5180                        let view =
5181                            bridge_view(env, "makeLabel", |env| DayBridge::makeLabel(env, &s));
5182                        // The font first: a line height is a multiple of its size.
5183                        apply_label_font(env, &view, p.font);
5184                        if !p.wraps {
5185                            let _ = java_in(env, |env| {
5186                                DayBridge::setLabelSingleLine(env, view.as_obj())
5187                            });
5188                        }
5189                        let paragraph = p.paragraph();
5190                        if paragraph != day_spec::props::LabelParagraph::default() {
5191                            apply_label_paragraph(env, &view, &paragraph);
5192                        }
5193                        if let Some(col) = p.color {
5194                            let _ = java_in(env, |env| {
5195                                DayBridge::setLabelColor(
5196                                    env,
5197                                    view.as_obj(),
5198                                    argb_i32(col.resolved()),
5199                                    true,
5200                                )
5201                            });
5202                        } else if p.role == day_spec::props::TextRole::Secondary {
5203                            // The theme's own secondary color, resolved on the Java side so it
5204                            // follows the app's theme and the system's light/dark setting.
5205                            let _ = java_in(env, |env| {
5206                                DayBridge::setLabelSecondary(env, view.as_obj(), true)
5207                            });
5208                        }
5209                        // A label patch carries no node id, and a link's ClickableSpan needs one
5210                        // to report through, so remember it here, where the id is in hand.
5211                        LABEL_NODE
5212                            .with(|m| m.borrow_mut().insert(view.as_obj().as_raw() as usize, idj));
5213                        if !p.runs.is_empty() {
5214                            set_label_runs(env, idj, &view, &p.text, &p.runs);
5215                        }
5216                        let align = crate::text_wire::align_code(p.align);
5217                        if align != 0 {
5218                            let _ = java_in(env, |env| {
5219                                DayBridge::setLabelAlignment(env, view.as_obj(), align)
5220                            });
5221                        }
5222                        // `Label::on_selection` (docs/text.md "Hearing about the selection"):
5223                        // `set_selectable` follows right after realize.
5224                        if p.reports_selection {
5225                            let _ = java_in(env, |env| {
5226                                DayBridge::setLabelReportsSelection(env, view.as_obj(), idj)
5227                            });
5228                        }
5229                        AHandle(view)
5230                    })
5231                }
5232                Some(Builtin::Button) => {
5233                    let Some(p) = day_spec::props_of::<ButtonProps>(kind, "android", props) else {
5234                        return realize_placeholder(kind);
5235                    };
5236                    with_env(|env| {
5237                        let s = jstr(env, &p.title);
5238                        let v = bridge_view(env, "makeButton", |env| {
5239                            DayBridge::makeButton(env, idj, &s)
5240                        });
5241                        let _ =
5242                            java_in(env, |env| DayBridge::setEnabled(env, v.as_obj(), p.enabled));
5243                        let _ = java_in(env, |env| {
5244                            DayBridge::setButtonSelected(env, v.as_obj(), p.selected)
5245                        });
5246                        apply_button_style(env, &v, p.style);
5247                        if p.icon.is_some() {
5248                            apply_button_content(env, &v, &p.title, p.icon.as_ref(), p.icon_only);
5249                        }
5250                        AHandle(v)
5251                    })
5252                }
5253                Some(Builtin::Toggle) => {
5254                    let Some(p) = day_spec::props_of::<ToggleProps>(kind, "android", props) else {
5255                        return realize_placeholder(kind);
5256                    };
5257                    with_env(|env| {
5258                        AHandle(bridge_view(env, "makeToggle", |env| {
5259                            DayBridge::makeToggle(env, idj, p.on, p.enabled)
5260                        }))
5261                    })
5262                }
5263                Some(Builtin::Slider) => {
5264                    let Some(p) = day_spec::props_of::<SliderProps>(kind, "android", props) else {
5265                        return realize_placeholder(kind);
5266                    };
5267                    with_env(|env| {
5268                        AHandle(bridge_view(env, "makeSlider", |env| {
5269                            DayBridge::makeSlider(env, idj, p.value, p.min, p.max)
5270                        }))
5271                    })
5272                }
5273                Some(Builtin::Picker) => crate::picker::realize_any(self, props, id),
5274                Some(Builtin::TextArea) => crate::textarea::realize_any(self, props, id),
5275                Some(Builtin::TextField) => {
5276                    let Some(p) = day_spec::props_of::<TextFieldProps>(kind, "android", props)
5277                    else {
5278                        return realize_placeholder(kind);
5279                    };
5280                    with_env(|env| {
5281                        let v = jstr(env, &p.text);
5282                        let ph = jstr(env, &p.placeholder);
5283                        AHandle(bridge_view(env, "makeTextField", |env| {
5284                            DayBridge::makeTextField(env, idj, &v, &ph)
5285                        }))
5286                    })
5287                }
5288                Some(Builtin::Divider) => {
5289                    let vertical = day_spec::props_of::<DividerProps>(kind, "android", props)
5290                        .is_some_and(|p| p.vertical);
5291                    with_env(|env| {
5292                        AHandle(bridge_view(env, "makeDivider", |env| {
5293                            DayBridge::makeDivider(env, vertical)
5294                        }))
5295                    })
5296                }
5297                Some(Builtin::Progress) => {
5298                    let Some(p) = day_spec::props_of::<ProgressProps>(kind, "android", props)
5299                    else {
5300                        return realize_placeholder(kind);
5301                    };
5302                    if p.value.is_none() {
5303                        return crate::controls::spinner::make(self, p, id);
5304                    }
5305                    with_env(|env| {
5306                        AHandle(bridge_view(env, "makeProgress", |env| {
5307                            DayBridge::makeProgress(env, p.value.is_some(), p.value.unwrap_or(0.0))
5308                        }))
5309                    })
5310                }
5311                Some(Builtin::Canvas) => with_env(|env| {
5312                    AHandle(bridge_view(env, "makeCanvas", |env| {
5313                        DayBridge::makeCanvas(env, idj)
5314                    }))
5315                }),
5316                Some(Builtin::Image) => {
5317                    let Some(p) = day_spec::props_of::<ImageProps>(kind, "android", props) else {
5318                        return realize_placeholder(kind);
5319                    };
5320                    // Scaling (§18.3): 0=fit (FIT_CENTER), 1=fill (CENTER_CROP), 2=stretch (FIT_XY).
5321                    let mode = match p.content_mode {
5322                        ContentMode::Fit => 0,
5323                        ContentMode::Fill => 1,
5324                        ContentMode::Stretch => 2,
5325                    };
5326                    // Vector-glyph tint (docs/vectors.md) as ARGB; 0 = none (a real tint always
5327                    // has alpha 0xFF, so 0 is unambiguous), and `TEMPLATE_TINT` asks for the
5328                    // theme's primary text color — a template glyph with no tint of its own.
5329                    let tint = image_tint(p.tint.map(day_spec::Ink::resolved), p.template);
5330                    // Named is the staged-drawable path; Bytes and Decoded arrive from
5331                    // `day::decode_image` (docs/images.md), so an `image()` piece can show a
5332                    // download or a pasted PNG with no staged resource behind it. Every source
5333                    // takes the tint (docs/images.md "Tinting"): it is the image view's tint
5334                    // list, which recolors whatever drawable the view holds by its alpha.
5335                    let handle = with_env(|env| match &p.source {
5336                        day_spec::ImageSource::Named(named) => {
5337                            let s = jstr(env, named);
5338                            AHandle(bridge_view(env, "makeImage", |env| {
5339                                DayBridge::makeImage(env, &s, mode, tint)
5340                            }))
5341                        }
5342                        day_spec::ImageSource::Bytes(bytes) => {
5343                            let Ok(arr) = env.byte_array_from_slice(bytes) else {
5344                                return AHandle(bridge_view(env, "makeImageBytes", |env| {
5345                                    DayBridge::makeImageBytes(
5346                                        env,
5347                                        jni::objects::JByteArray::default(),
5348                                        mode,
5349                                    )
5350                                }));
5351                            };
5352                            AHandle(bridge_view(env, "makeImageBytes", |env| {
5353                                DayBridge::makeImageBytes(env, &arr, mode)
5354                            }))
5355                        }
5356                        day_spec::ImageSource::Decoded(id) => {
5357                            AHandle(bridge_view(env, "makeImageBitmap", |env| {
5358                                DayBridge::makeImageBitmap(env, id.0 as i64, mode)
5359                            }))
5360                        }
5361                    });
5362                    if tint != 0 && !matches!(p.source, day_spec::ImageSource::Named(_)) {
5363                        bridge(|env| DayBridge::initImageTint(env, handle.0.as_obj(), tint));
5364                    }
5365                    handle
5366                }
5367                Some(Builtin::ListItem) => {
5368                    let Some(p) = day_spec::props_of::<day_spec::props::ListItemProps>(
5369                        kind, "android", props,
5370                    ) else {
5371                        return realize_placeholder(kind);
5372                    };
5373                    let handle = with_env(|env| {
5374                        let (t, s, d) = (
5375                            jstr(env, &p.title),
5376                            jstr(env, &p.subtitle),
5377                            jstr(env, &p.detail),
5378                        );
5379                        let icon = jstr(env, &list_item_icon(p.icon.as_ref()));
5380                        let tint = p.icon_tint.map_or(0, |c| argb_i32(c.resolved()));
5381                        AHandle(bridge_view(env, "makeListItem", |env| {
5382                            DayListItem::make(env, &t, &s, &d, &icon, tint, p.checked)
5383                        }))
5384                    });
5385                    LIST_ITEM_PROPS.with(|m| {
5386                        m.borrow_mut()
5387                            .insert(handle.0.as_obj().as_raw() as usize, p.clone())
5388                    });
5389                    handle
5390                }
5391                // A recycled list cell is adopted from the native list, never realized
5392                // through this path; anything else is an extension piece.
5393                Some(
5394                    Builtin::ListCell
5395                    | Builtin::Inspector
5396                    | Builtin::InspectorPane
5397                    | Builtin::Split
5398                    | Builtin::SplitPane,
5399                )
5400                | None => {
5401                    if let Some(make) = self.registry.get(kind).map(|r| r.make) {
5402                        return make(self, props, id);
5403                    }
5404                    warn_missing_renderer(kind);
5405                    with_env(|env| {
5406                        let s = jstr(env, &format!("⟨{kind}⟩"));
5407                        AHandle(bridge_view(env, "makeLabel", |env| {
5408                            DayBridge::makeLabel(env, &s)
5409                        }))
5410                    })
5411                }
5412            }
5413        }
5414
5415        fn update(
5416            &mut self,
5417            h: &AHandle,
5418            kind: PieceKind,
5419            patch: &dyn Any,
5420            anim: Option<&AnimSpec>,
5421        ) {
5422            if let Some(patch) = patch.downcast_ref::<TreePatch>() {
5423                tree_patch(h, patch);
5424                return;
5425            }
5426            match kind {
5427                kinds::LIST_ITEM => {
5428                    if let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() {
5429                        list_item_patch(h, p);
5430                    }
5431                }
5432                kinds::IMAGE => {
5433                    if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
5434                        match p {
5435                            day_spec::props::ImagePatch::Tint(c) => {
5436                                // Drawable tint, as at realize (docs/vectors.md); 0 = authored
5437                                // colors, or the theme text color again on a template glyph —
5438                                // the bridge remembers which views were realized as one.
5439                                let tint = image_tint((*c).map(day_spec::Ink::resolved), false);
5440                                with_env(|env| {
5441                                    let _ = java_in(env, |env| {
5442                                        DayBridge::setImageTint(env, h.0.as_obj(), tint)
5443                                    });
5444                                });
5445                            }
5446                            // A source swap repaints the same view (docs/images.md), so an
5447                            // `image()` bound to a signal shows new pixels without rebuilding
5448                            // its subtree.
5449                            day_spec::props::ImagePatch::Source(source) => {
5450                                with_env(|env| match source {
5451                                    day_spec::ImageSource::Named(named) => {
5452                                        let s = jstr(env, named);
5453                                        let _ = java_in(env, |env| {
5454                                            DayBridge::setImageName(env, h.0.as_obj(), &s)
5455                                        });
5456                                    }
5457                                    day_spec::ImageSource::Bytes(bytes) => {
5458                                        if let Ok(arr) = env.byte_array_from_slice(bytes) {
5459                                            let _ = java_in(env, |env| {
5460                                                DayBridge::setImageBytes(env, h.0.as_obj(), &arr)
5461                                            });
5462                                        }
5463                                    }
5464                                    day_spec::ImageSource::Decoded(id) => {
5465                                        let _ = java_in(env, |env| {
5466                                            DayBridge::setImageBitmap(
5467                                                env,
5468                                                h.0.as_obj(),
5469                                                id.0 as i64,
5470                                            )
5471                                        });
5472                                    }
5473                                });
5474                            }
5475                        }
5476                    }
5477                }
5478                kinds::CONTAINER => match patch.downcast_ref::<ContainerPatch>() {
5479                    // A solid fill (or none) keeps the motion contract: through `update` with
5480                    // an animation, it passes between the two colors (docs/tween.md, rule 8).
5481                    // A styled surface keeps its border, corners and shadow and takes only the
5482                    // color; a plain one is repainted as it always was.
5483                    Some(ContainerPatch::Fill(fill @ (None | Some(day_spec::Paint::Solid(_))))) => {
5484                        let c = super::solid_fill(fill.as_ref());
5485                        bridge(|env| {
5486                            let (timing, keys) = anim_arrays(env, anim)?;
5487                            DayBridge::animateSurfaceFill(
5488                                env,
5489                                h.0.as_obj(),
5490                                c.map_or(0, argb_i32),
5491                                c.is_some(),
5492                                &timing,
5493                                &keys,
5494                            )
5495                        });
5496                    }
5497                    // A gradient applies at once, and the surface keeps the rest of its style.
5498                    Some(ContainerPatch::Fill(fill)) => {
5499                        let spec = super::gradient_spec(fill.as_ref());
5500                        bridge(|env| {
5501                            let arr = env.new_double_array(spec.len())?;
5502                            arr.set_region(env, 0, &spec)?;
5503                            DayBridge::setSurfaceGradient(env, h.0.as_obj(), &arr)
5504                        });
5505                    }
5506                    // A reactive surface, border, radius or shadow, or a frame-relative radius
5507                    // re-resolved (docs/surfaces.md "Reactive surfaces"): the realize-time
5508                    // surface again, on the same view, at once.
5509                    Some(ContainerPatch::Surface(p)) => apply_container_surface(h, p, false),
5510                    None => {}
5511                },
5512                kinds::NAV_MENU => {
5513                    if let Some(p) = patch.downcast_ref::<day_spec::props::RefreshPatch>() {
5514                        with_env(|env| {
5515                            let _ = java_in(env, |env| {
5516                                DayBridge::setNavRefreshing(env, h.0.as_obj(), p.refreshing)
5517                            });
5518                        });
5519                        return;
5520                    }
5521                    match patch.downcast_ref::<NavMenuPatch>() {
5522                        // A data-driven `.items(signal, …)` block re-derived: rebuild the native
5523                        // rows so each click listener reports its current index; stale rows
5524                        // shift every selection after a removed item by one and drop the last
5525                        // row's selection entirely.
5526                        Some(NavMenuPatch::Items {
5527                            items,
5528                            icons,
5529                            tints,
5530                            menus,
5531                            badges,
5532                            badge_icons,
5533                            badge_tints,
5534                            sections,
5535                            selected,
5536                            document_keys,
5537                            rows_changed,
5538                            // `movable` is for toolkits whose own sidebar drags (Cap::NavReorder).
5539                            ..
5540                        }) => {
5541                            let joined = items.join("\u{1f}");
5542                            let joined_icons = icons
5543                                .iter()
5544                                .map(|o| o.clone().unwrap_or_default())
5545                                .collect::<Vec<_>>()
5546                                .join("\u{1f}");
5547                            let joined_tints = nav_tints_joined(
5548                                &tints
5549                                    .iter()
5550                                    .map(|t| t.map(day_spec::Ink::resolved))
5551                                    .collect::<Vec<_>>(),
5552                            );
5553                            let joined_badge_icons = badge_icons
5554                                .iter()
5555                                .map(|o| o.clone().unwrap_or_default())
5556                                .collect::<Vec<_>>()
5557                                .join("\u{1f}");
5558                            let joined_badge_tints = nav_tints_joined(
5559                                &badge_tints
5560                                    .iter()
5561                                    .map(|t| t.map(day_spec::Ink::resolved))
5562                                    .collect::<Vec<_>>(),
5563                            );
5564                            let joined_menus = nav_menus_joined(menus);
5565                            let joined_sections = sections
5566                                .iter()
5567                                .map(|o| o.clone().unwrap_or_default())
5568                                .collect::<Vec<_>>()
5569                                .join("\u{1f}");
5570                            with_env(|env| {
5571                                let s = jstr(env, &joined);
5572                                let si = jstr(env, &joined_icons);
5573                                let ss = jstr(env, &joined_sections);
5574                                // The same rows with new words or counts: update those rows
5575                                // where they stand. A new row set is rebuilt.
5576                                let _ = match rows_changed {
5577                                    Some(rows) => {
5578                                        let r = jstr(
5579                                            env,
5580                                            &rows
5581                                                .iter()
5582                                                .map(std::string::ToString::to_string)
5583                                                .collect::<Vec<_>>()
5584                                                .join(","),
5585                                        );
5586                                        java_in(env, |env| {
5587                                            DayBridge::updateNavMenuRows(
5588                                                env,
5589                                                h.0.as_obj(),
5590                                                &r,
5591                                                &s,
5592                                                &si,
5593                                            )
5594                                        })
5595                                    }
5596                                    None => java_in(env, |env| {
5597                                        DayBridge::updateNavMenu(env, h.0.as_obj(), &s, &si, &ss)
5598                                    }),
5599                                };
5600                                let keys = jstr(env, &document_keys.join("\u{1f}"));
5601                                let _ = java_in(env, |env| {
5602                                    DayBridge::setDocumentTabKeys(env, h.0.as_obj(), &keys)
5603                                });
5604                                // A rebuilt menu comes back unchecked, so re-apply the selection
5605                                // the patch carries with it.
5606                                nav_menu_select(env, h, *selected);
5607                                let st = jstr(env, &joined_tints);
5608                                let _ = java_in(env, |env| {
5609                                    DayBridge::setNavMenuTints(env, h.0.as_obj(), &st)
5610                                });
5611                                let texts = badges
5612                                    .iter()
5613                                    .map(|s| s.as_deref().unwrap_or(""))
5614                                    .collect::<Vec<_>>()
5615                                    .join("\u{1f}");
5616                                let counts = jstr(env, &texts);
5617                                let sb = jstr(env, &joined_badge_icons);
5618                                let sbt = jstr(env, &joined_badge_tints);
5619                                let _ = java_in(env, |env| {
5620                                    DayBridge::setNavMenuBadges(
5621                                        env,
5622                                        h.0.as_obj(),
5623                                        &sb,
5624                                        &sbt,
5625                                        &counts,
5626                                    )
5627                                });
5628                                let sm = jstr(env, &joined_menus);
5629                                let _ = java_in(env, |env| {
5630                                    DayBridge::setNavRowMenus(env, h.0.as_obj(), &sm)
5631                                });
5632                                if env.exception_check() {
5633                                    env.exception_clear();
5634                                }
5635                            });
5636                        }
5637                        // The active indicator follows the model (docs/navigation.md). This
5638                        // used to be a no-op on the grounds that "mobile selection is transient
5639                        // (rows ripple, then push)", which was true of the hand-built list that
5640                        // could not draw a resting state; a NavigationView can, and a sidebar
5641                        // beside its detail is exactly where that state means "you are here".
5642                        Some(NavMenuPatch::Selected(sel)) => {
5643                            with_env(|env| nav_menu_select(env, h, *sel));
5644                        }
5645                        Some(NavMenuPatch::IconProgress(_)) | None => {}
5646                    }
5647                }
5648                kinds::NAV => {
5649                    if let Some(p) = patch.downcast_ref::<day_spec::props::DocumentTabsPatch>() {
5650                        with_env(|env| {
5651                            let _ = java_in(env, |env| {
5652                                DayBridge::documentNavChrome(env, h.0.as_obj(), p.native)
5653                            });
5654                        });
5655                        return;
5656                    }
5657                    // Inline search (docs/search.md): the app writing its query patches the live
5658                    // field, so a sync never rebuilds it or takes the insertion point. The Java
5659                    // side guards the echo while it writes.
5660                    if matches!(
5661                        patch.downcast_ref::<day_spec::props::SearchPatch>(),
5662                        Some(day_spec::props::SearchPatch::Focus)
5663                    ) {
5664                        with_env(|env| {
5665                            let _ =
5666                                java_in(env, |env| DayBridge::focusNavSearch(env, h.0.as_obj()));
5667                            if env.exception_check() {
5668                                env.exception_clear();
5669                            }
5670                        });
5671                    }
5672                    if let Some(day_spec::props::SearchPatch::Text(t)) =
5673                        patch.downcast_ref::<day_spec::props::SearchPatch>()
5674                    {
5675                        let text = t.clone();
5676                        with_env(|env| {
5677                            let tx = jstr(env, &text);
5678                            let _ = java_in(env, |env| {
5679                                DayBridge::setNavSearchText(env, h.0.as_obj(), &tx)
5680                            });
5681                            if env.exception_check() {
5682                                env.exception_clear();
5683                            }
5684                        });
5685                    }
5686                    if let Some(p) = patch.downcast_ref::<NavPatch>() {
5687                        match p {
5688                            NavPatch::Pushed { title, immersive } => with_env(|env| {
5689                                let s = jstr(env, title);
5690                                let _ = java_in(env, |env| {
5691                                    DayBridge::navPush(env, h.0.as_obj(), &s, *immersive)
5692                                });
5693                            }),
5694                            NavPatch::Popped => bridge(|env| DayBridge::navPop(env, h.0.as_obj())),
5695                            NavPatch::Title(t) => with_env(|env| {
5696                                let s = jstr(env, t);
5697                                let _ = java_in(env, |env| {
5698                                    DayBridge::navSetTitle(env, h.0.as_obj(), &s)
5699                                });
5700                            }),
5701                            NavPatch::GuardTop(on) => with_env(|env| {
5702                                let _ = java_in(env, |env| {
5703                                    DayBridge::navSetGuard(env, h.0.as_obj(), *on)
5704                                });
5705                            }),
5706                            // Unreachable: this backend answers `Cap::NavRepresent =
5707                            // Unsupported`, so the pieces layer never sends it. The plan for
5708                            // Android is `SlidingPaneLayout`, which decides at measure time and
5709                            // is OBSERVED rather than told (docs/size-classes.md).
5710                            #[expect(
5711                                clippy::match_same_arms,
5712                                reason = "each group of no-op patches keeps its own arm and the comment saying why"
5713                            )]
5714                            NavPatch::Presentation(_) => {}
5715                            NavPatch::Reorder(order) => with_env(|env| {
5716                                let text = jstr(
5717                                    env,
5718                                    &order
5719                                        .iter()
5720                                        .map(usize::to_string)
5721                                        .collect::<Vec<_>>()
5722                                        .join(","),
5723                                );
5724                                let _ = java_in(env, |env| {
5725                                    DayBridge::reorderNavSuite(env, h.0.as_obj(), &text)
5726                                });
5727                            }),
5728                            // The resident-page switch (docs/navigation.md): the app moved the
5729                            // selection, so the suite shows that page and syncs its chrome
5730                            // Without reporting the move back as a tap.
5731                            NavPatch::Select(i) => {
5732                                bridge(|env| {
5733                                    DayBridge::setNavSuiteSelected(env, h.0.as_obj(), *i as i32)
5734                                });
5735                            }
5736                            // Never arrives: this backend answers `Cap::NavContentList`
5737                            // Unsupported, so the pieces layer composes the pane itself
5738                            // (docs/navigation.md).
5739                            NavPatch::ListVisible(_) | NavPatch::ListInStack(_) => {}
5740                        }
5741                    }
5742                }
5743                kinds::COVER => {
5744                    if let Some(p) = patch.downcast_ref::<CoverPatch>() {
5745                        match p {
5746                            CoverPatch::Present {
5747                                background,
5748                                dismiss_disabled,
5749                            } => bridge(|env| {
5750                                DayBridge::coverPresent(
5751                                    env,
5752                                    h.0.as_obj(),
5753                                    background.map_or(0, |c| argb_i32(c.resolved())),
5754                                    background.is_some(),
5755                                    *dismiss_disabled,
5756                                )
5757                            }),
5758                            CoverPatch::DismissDisabled(d) => bridge(|env| {
5759                                DayBridge::coverSetDismissDisabled(env, h.0.as_obj(), *d)
5760                            }),
5761                            CoverPatch::Dismiss => {
5762                                bridge(|env| DayBridge::coverDismiss(env, h.0.as_obj()));
5763                            }
5764                        }
5765                    }
5766                }
5767                kinds::LABEL => {
5768                    if let Some(p) = patch.downcast_ref::<LabelPatch>() {
5769                        match p {
5770                            LabelPatch::Paragraph(p) => {
5771                                with_env(|env| apply_label_paragraph(env, &h.0, p));
5772                            }
5773                            LabelPatch::Text(t) => with_env(|env| {
5774                                let s = jstr(env, t);
5775                                let _ =
5776                                    java_in(env, |env| DayBridge::setLabel(env, h.0.as_obj(), &s));
5777                            }),
5778                            LabelPatch::Font(f) => with_env(|env| apply_label_font(env, &h.0, *f)),
5779                            LabelPatch::Runs(text, runs) => {
5780                                let node = LABEL_NODE.with(|m| {
5781                                    m.borrow()
5782                                        .get(&(h.0.as_obj().as_raw() as usize))
5783                                        .copied()
5784                                        .unwrap_or(0)
5785                                });
5786                                with_env(|env| set_label_runs(env, node, &h.0, text, runs));
5787                            }
5788                            LabelPatch::Color(c) => {
5789                                bridge(|env| {
5790                                    DayBridge::setLabelColor(
5791                                        env,
5792                                        h.0.as_obj(),
5793                                        c.map_or(0, |c| argb_i32(c.resolved())),
5794                                        c.is_some(),
5795                                    )
5796                                });
5797                            }
5798                        }
5799                    }
5800                }
5801                kinds::BUTTON => {
5802                    if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
5803                        match p {
5804                            ButtonPatch::Content(c) => with_env(|env| {
5805                                apply_button_content(
5806                                    env,
5807                                    &h.0,
5808                                    &c.title,
5809                                    c.icon.as_ref(),
5810                                    c.icon_only,
5811                                );
5812                            }),
5813                            ButtonPatch::Title(t) => with_env(|env| {
5814                                let s = jstr(env, t);
5815                                let _ =
5816                                    java_in(env, |env| DayBridge::setLabel(env, h.0.as_obj(), &s));
5817                            }),
5818                            ButtonPatch::Enabled(e) => {
5819                                bridge(|env| DayBridge::setEnabled(env, h.0.as_obj(), *e));
5820                            }
5821                            ButtonPatch::Selected(on) => {
5822                                bridge(|env| DayBridge::setButtonSelected(env, h.0.as_obj(), *on));
5823                            }
5824                            ButtonPatch::Style(s) => {
5825                                with_env(|env| apply_button_style(env, &h.0, *s));
5826                            }
5827                        }
5828                    }
5829                }
5830                kinds::TOGGLE => {
5831                    if let Some(p) = patch.downcast_ref::<TogglePatch>() {
5832                        match p {
5833                            TogglePatch::On(on) => {
5834                                bridge(|env| DayBridge::setToggle(env, h.0.as_obj(), *on));
5835                            }
5836                            TogglePatch::Enabled(e) => {
5837                                bridge(|env| DayBridge::setEnabled(env, h.0.as_obj(), *e));
5838                            }
5839                        }
5840                    }
5841                }
5842                kinds::SLIDER => {
5843                    if let Some(p) = patch.downcast_ref::<SliderPatch>() {
5844                        match p {
5845                            SliderPatch::Value(v) => {
5846                                // min recovered from the widget tag
5847                                bridge(|env| DayBridge::setSlider(env, h.0.as_obj(), *v, 0.0));
5848                            }
5849                            SliderPatch::Enabled(e) => {
5850                                bridge(|env| DayBridge::setEnabled(env, h.0.as_obj(), *e));
5851                            }
5852                        }
5853                    }
5854                }
5855                kinds::PROGRESS => {
5856                    if let Some(p @ ProgressPatch::Animating(_)) =
5857                        patch.downcast_ref::<ProgressPatch>()
5858                    {
5859                        crate::controls::spinner::update(self, h, p);
5860                        return;
5861                    }
5862
5863                    if let Some(ProgressPatch::Value(Some(v))) =
5864                        patch.downcast_ref::<ProgressPatch>()
5865                    {
5866                        bridge(|env| DayBridge::setProgress(env, h.0.as_obj(), *v));
5867                    }
5868                }
5869                kinds::PICKER => crate::picker::update_any(self, h, patch),
5870                kinds::TEXT_AREA => crate::textarea::update_any(self, h, patch),
5871                kinds::TEXT_FIELD => {
5872                    if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
5873                        match p {
5874                            TextFieldPatch::Text { text, from_native } => {
5875                                if !*from_native {
5876                                    with_env(|env| {
5877                                        let s = jstr(env, text);
5878                                        let _ = java_in(env, |env| {
5879                                            DayBridge::setTextField(env, h.0.as_obj(), &s)
5880                                        });
5881                                    });
5882                                }
5883                            }
5884                            TextFieldPatch::Placeholder(t) => with_env(|env| {
5885                                let s = jstr(env, t);
5886                                let _ = java_in(env, |env| {
5887                                    DayBridge::setPlaceholder(env, h.0.as_obj(), &s)
5888                                });
5889                            }),
5890                            TextFieldPatch::Enabled(e) => {
5891                                bridge(|env| DayBridge::setEnabled(env, h.0.as_obj(), *e));
5892                            }
5893                            TextFieldPatch::Select(sel) => {
5894                                let at = |n: usize| n.min(i32::MAX as usize) as i32;
5895                                bridge(|env| {
5896                                    DayBridge::setTextFieldSelection(
5897                                        env,
5898                                        h.0.as_obj(),
5899                                        at(sel.start),
5900                                        at(sel.end),
5901                                    )
5902                                });
5903                            }
5904                        }
5905                    }
5906                }
5907                kinds::LIST => match patch.downcast_ref::<ListPatch>() {
5908                    Some(ListPatch::Reload) => {
5909                        // notifyDataSetChanged: getCount reads the snapshot, getView is deferred to
5910                        // the next layout, so it is safe inside a with_tree borrow.
5911                        bridge(|env| DayBridge::listReload(env, h.0.as_obj()));
5912                    }
5913                    Some(ListPatch::Splice(deltas)) => {
5914                        // The deltas as the adapter's range notifications, in one bridge call
5915                        // (docs/list.md "Keyed updates"). Like a reload, they only mark the rows
5916                        // changed; RecyclerView binds at its next layout, outside this borrow.
5917                        let ops = crate::list_wire::splice_ops(deltas);
5918                        java(|env| {
5919                            let array = env.new_int_array(ops.len())?;
5920                            array.set_region(env, 0, &ops)?;
5921                            DayBridge::listSplice(env, h.0.as_obj(), &array)
5922                        });
5923                    }
5924                    Some(ListPatch::ScrollToEnd) => {
5925                        // Posts smoothScrollToPosition(count-1) on the RecyclerView (no-op if empty).
5926                        bridge(|env| DayBridge::listScrollToEnd(env, h.0.as_obj()));
5927                    }
5928                    Some(ListPatch::ScrollToRow(row)) => {
5929                        bridge(|env| DayBridge::listScrollToRow(env, h.0.as_obj(), *row as i32));
5930                    }
5931                    Some(ListPatch::Selected(rows)) => {
5932                        // Record, then repaint the visible holders; newly bound holders pick
5933                        // the state up from nativeListIsSelected in the bind path. Paint
5934                        // only; no selection event echoes back.
5935                        let key = h.0.as_obj().as_raw() as usize;
5936                        if let Some(nid) = LIST_NODE.with(|m| m.borrow().get(&key).copied()) {
5937                            LIST_SELECTED.with(|m| {
5938                                m.borrow_mut().insert(nid, rows.iter().copied().collect());
5939                            });
5940                            bridge(|env| DayBridge::listPaintSelection(env, h.0.as_obj(), nid));
5941                        }
5942                    }
5943                    Some(ListPatch::RowSizeInvalidated { cell, height }) => {
5944                        // A row re-laid at a new height after its bind (its text changed). This
5945                        // arrives inside day-core's layout pass, so the resize waits for the next
5946                        // turn, and it carries its height: nothing asks the source back.
5947                        let key = h.0.as_obj().as_raw() as usize;
5948                        let list = LIST_NODE.with(|m| m.borrow().get(&key).copied());
5949                        let (cell, height) = (*cell, *height);
5950                        if let Some(nid) = list {
5951                            <Material as Platform>::post(Box::new(move || {
5952                                // The cell's own GlobalRef, while its list still holds it.
5953                                let gref = LIST_CELLS.with(|m| {
5954                                    m.borrow().get(&nid).and_then(|cells| {
5955                                        cells
5956                                            .values()
5957                                            .find(|g| g.as_obj().as_raw() as usize == cell)
5958                                            .cloned()
5959                                    })
5960                                });
5961                                if let Some(gref) = gref {
5962                                    set_list_cell_height(gref.as_obj(), height);
5963                                }
5964                            }));
5965                        }
5966                    }
5967                    // No editing mode (Cap::ListEditing is Unsupported): rows drag and swipe
5968                    // as they are.
5969                    Some(ListPatch::Editing(_)) | None => {}
5970                },
5971                _ => {
5972                    if let Some(update) = self.registry.get(kind).map(|r| r.update) {
5973                        update(self, h, patch);
5974                    }
5975                }
5976            }
5977        }
5978
5979        /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
5980        fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
5981            // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
5982            // the hook needs it mutably.
5983            let f = self.registry.get(kind).and_then(|r| r.release);
5984            if let Some(f) = f {
5985                f(self, h);
5986            }
5987        }
5988        fn release(&mut self, h: AHandle) {
5989            bridge(|env| DayBridge::releaseContextMenu(env, h.0.as_obj()));
5990            bridge(|env| DayTransfer::release(env, h.0.as_obj()));
5991            // A released window root drops its `SECONDARY` record (docs/windows.md teardown;
5992            // the activity itself already finished or is finishing).
5993            with_env(|env| {
5994                SECONDARY.with(|s| {
5995                    s.borrow_mut().retain(|(_, gref)| {
5996                        !env.is_same_object(h.0.as_obj(), gref.as_obj())
5997                            .unwrap_or(false)
5998                    });
5999                });
6000            });
6001            let key = h.0.as_obj().as_raw() as usize;
6002            // One sweep drops this view's entry from every registered `SideTable`, present
6003            // and future, so ptr-keyed side state cannot outlive the handle
6004            // (day_spec::sidetable; the maps below predate it and stay manual).
6005            day_spec::sidetable::sweep(key);
6006            LABEL_NODE.with(|m| m.borrow_mut().remove(&key));
6007            NAV_MENU_ROWS.with(|m| m.borrow_mut().remove(&key));
6008            LIST_ITEM_PROPS.with(|m| m.borrow_mut().remove(&key));
6009            if let Some(nid) = LIST_NODE.with(|m| m.borrow_mut().remove(&key)) {
6010                release_pinned_header(&h, nid);
6011                TREE_SOURCES.with(|m| m.borrow_mut().remove(&nid));
6012                LIST_SOURCES.with(|m| {
6013                    m.borrow_mut().remove(&nid);
6014                });
6015                // Drop the list's per-cell GlobalRefs with it (see LIST_CELLS): each Arc drop
6016                // releases its JNI global ref, keeping long sessions off the JNI table limit.
6017                LIST_CELLS.with(|m| {
6018                    m.borrow_mut().remove(&nid);
6019                });
6020                LIST_BINDINGS.with(|m| m.borrow_mut().retain(|(host, _), _| *host != nid));
6021                LIST_SELECTED.with(|m| {
6022                    m.borrow_mut().remove(&nid);
6023                });
6024                LIST_AUTOMATIC.with(|m| m.borrow_mut().remove(&nid));
6025            }
6026            bridge(|env| DayBridge::removeChild(env, h.0.as_obj()));
6027        }
6028
6029        fn insert(&mut self, parent: &AHandle, child: &AHandle, _index: usize) {
6030            bridge(|env| DayBridge::addChild(env, parent.0.as_obj(), child.0.as_obj()));
6031            // A nav menu now has ancestors: if one of them is a navigation suite, its rows are
6032            // that suite's chrome. Best-effort and after the insert, like every other decoration
6033            // on this backend: a failure here must not abort the tree build.
6034            let rows = NAV_MENU_ROWS.with(|m| {
6035                m.borrow()
6036                    .get(&(child.0.as_obj().as_raw() as usize))
6037                    .cloned()
6038            });
6039            if let Some((node, titles, icons, keys, badges)) = rows {
6040                with_env(|env| {
6041                    let t = jstr(env, &titles);
6042                    let i = jstr(env, &icons);
6043                    let b = jstr(env, &badges);
6044                    let _ = java_in(env, |env| {
6045                        DayBridge::setNavSuiteRows(env, child.0.as_obj(), &t, &i, &b, node)
6046                    });
6047                    let keys = jstr(env, &keys);
6048                    let _ = java_in(env, |env| {
6049                        DayBridge::setDocumentTabKeys(env, child.0.as_obj(), &keys)
6050                    });
6051                    if env.exception_check() {
6052                        env.exception_clear();
6053                    }
6054                });
6055            }
6056        }
6057
6058        fn remove(&mut self, _parent: &AHandle, child: &AHandle) {
6059            bridge(|env| DayBridge::removeChild(env, child.0.as_obj()));
6060        }
6061
6062        fn move_child(&mut self, parent: &AHandle, child: &AHandle, to: usize) {
6063            bridge(|env| DayBridge::moveChild(env, parent.0.as_obj(), child.0.as_obj(), to as i32));
6064        }
6065
6066        fn measure(&mut self, h: &AHandle, kind: PieceKind, p: Proposal) -> Size {
6067            let d = density();
6068            match kind {
6069                kinds::LABEL => {
6070                    let natural_w = measure_call(h, |env, v| DayBridge::measureWidth(env, v)) / d;
6071                    match p.width {
6072                        Some(pw) if natural_w > pw => {
6073                            let wpx = (pw * d).round() as i32;
6074                            let hh = with_env(|env| {
6075                                f64::from(
6076                                    DayBridge::measureHeightForWidth(env, h.0.as_obj(), wpx)
6077                                        .unwrap_or(0),
6078                                )
6079                            });
6080                            Size::new(pw, hh / d)
6081                        }
6082                        _ => Size::new(
6083                            natural_w,
6084                            measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d,
6085                        ),
6086                    }
6087                }
6088                kinds::NAV_MENU => Size::new(
6089                    p.width.unwrap_or(320.0),
6090                    p.height.unwrap_or_else(|| {
6091                        measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d
6092                    }),
6093                ),
6094                // The Material list item measures itself: its height at the row's width.
6095                kinds::LIST_ITEM => {
6096                    let w = p.width.unwrap_or_else(|| {
6097                        measure_call(h, |env, v| DayBridge::measureWidth(env, v)) / d
6098                    });
6099                    let wpx = (w * d).round() as i32;
6100                    let hh = with_env(|env| {
6101                        f64::from(
6102                            DayBridge::measureHeightForWidth(env, h.0.as_obj(), wpx).unwrap_or(0),
6103                        )
6104                    });
6105                    Size::new(w, hh / d)
6106                }
6107                kinds::SLIDER => Size::new(
6108                    p.width.unwrap_or(180.0),
6109                    (measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d).max(24.0),
6110                ),
6111                // `PICKER` falls to the native measureWidth/measureHeight default below.
6112                kinds::TEXT_AREA => crate::textarea::measure_any(self, h, p),
6113                kinds::TEXT_FIELD => Size::new(
6114                    p.width.unwrap_or(180.0),
6115                    (measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d).max(40.0),
6116                ),
6117                kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
6118                kinds::LIST => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
6119                // A canvas has no content of its own to measure (`DayCanvasView` is a bare
6120                // `View`, which measures 0×0), so it takes what the layout offers, the way the
6121                // other toolkits' default arms already answer (`p.width.unwrap_or(natural)`).
6122                // Without this a canvas in a form row got the row's height from `.height(…)`
6123                // and no width at all: the Showcase's sensor strip charts drew nothing here
6124                // while they filled their rows on iOS.
6125                kinds::CANVAS => Size::new(
6126                    p.width.unwrap_or_else(|| {
6127                        measure_call(h, |env, v| DayBridge::measureWidth(env, v)) / d
6128                    }),
6129                    p.height.unwrap_or_else(|| {
6130                        measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d
6131                    }),
6132                ),
6133                _ => {
6134                    if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
6135                        return measure(self, h, p);
6136                    }
6137                    Size::new(
6138                        measure_call(h, |env, v| DayBridge::measureWidth(env, v)) / d,
6139                        measure_call(h, |env, v| DayBridge::measureHeight(env, v)) / d,
6140                    )
6141                }
6142            }
6143        }
6144
6145        /// `View.getBaseline()`, the same answer `LinearLayout`'s `baselineAligned` uses
6146        /// (docs/baseline.md). `TextView` and everything built on it override it; the base View
6147        /// returns -1, which is "no baseline".
6148        fn first_baseline(&mut self, h: &AHandle, kind: PieceKind, size: Size) -> Option<f64> {
6149            if !day_spec::kind_has_baseline(kind) {
6150                return None;
6151            }
6152            let d = density();
6153            let px = java(|env| {
6154                DayBridge::baselineAt(
6155                    env,
6156                    h.0.as_obj(),
6157                    (size.width * d).round() as i32,
6158                    (size.height * d).round() as i32,
6159                )
6160            })?;
6161            (px >= 0).then(|| f64::from(px) / d)
6162        }
6163
6164        fn set_frame(&mut self, h: &AHandle, frame: Rect, anim: Option<&AnimSpec>) {
6165            // DayFixed placement; animated, a ValueAnimator places the child at the frames in
6166            // between, from the one it shows (docs/tween.md "The animation contract").
6167            let d = density();
6168            bridge(|env| {
6169                let (timing, keys) = anim_arrays(env, anim)?;
6170                DayBridge::setFrame(
6171                    env,
6172                    h.0.as_obj(),
6173                    (frame.origin.x * d).round() as i32,
6174                    (frame.origin.y * d).round() as i32,
6175                    (frame.size.width * d).round() as i32,
6176                    (frame.size.height * d).round() as i32,
6177                    &timing,
6178                    &keys,
6179                )
6180            });
6181        }
6182
6183        fn set_opacity(&mut self, h: &AHandle, opacity: f64, anim: Option<&AnimSpec>) {
6184            bridge(|env| {
6185                let (timing, keys) = anim_arrays(env, anim)?;
6186                DayBridge::setOpacity(env, h.0.as_obj(), opacity as f32, &timing, &keys)
6187            });
6188        }
6189
6190        fn set_transform(
6191            &mut self,
6192            h: &AHandle,
6193            t: Transform,
6194            _size: Size,
6195            anim: Option<&AnimSpec>,
6196        ) {
6197            let d = density();
6198            bridge(|env| {
6199                let (timing, keys) = anim_arrays(env, anim)?;
6200                DayBridge::setTransform(
6201                    env,
6202                    h.0.as_obj(),
6203                    (t.tx * d) as f32,
6204                    (t.ty * d) as f32,
6205                    t.sx as f32,
6206                    t.sy as f32,
6207                    t.rotation.degrees() as f32,
6208                    &timing,
6209                    &keys,
6210                )
6211            });
6212        }
6213
6214        /// `DayBridge.readDisplayed`: the view's own alpha, translation, frame and fill, which
6215        /// a run writes every frame, so a read mid-flight is what is on screen and a read at
6216        /// rest is the model value (docs/tween.md "The animation contract").
6217        fn read_displayed(&self, h: &AHandle) -> day_spec::Displayed {
6218            if !vm_ready() {
6219                return day_spec::Displayed::default();
6220            }
6221            java(|env| {
6222                let arr = DayBridge::readDisplayed(env, h.0.as_obj())?;
6223                let mut slots = vec![0.0; arr.len(env)?];
6224                arr.get_region(env, 0, &mut slots)?;
6225                Ok(crate::motion_wire::displayed(&slots))
6226            })
6227            .unwrap_or_default()
6228        }
6229
6230        fn set_selectable(&mut self, h: &AHandle, selectable: bool) -> Option<AHandle> {
6231            // A plain label is an android.widget.TextView; make its text selectable (long-press →
6232            // copy, docs/text.md). A direct instance call; no DayBridge method needed.
6233            bridge(|env| {
6234                downcast::<framework::TextView>(env, h.0.as_obj())?
6235                    .setTextIsSelectable(env, selectable)
6236            });
6237            None
6238        }
6239
6240        fn set_input_traits(
6241            &mut self,
6242            h: &AHandle,
6243            traits: &day_spec::InputTraits,
6244        ) -> Option<AHandle> {
6245            use day_spec::{InputPurpose, SubmitLabel};
6246            // One EditText takes every member as a property (docs/textfield.md), so the handle
6247            // never changes. Secure and purpose merge into a single Android input type, which
6248            // is why the whole set crosses in one call; `DayBridge.setInputTraits` documents
6249            // the same integer codes and ignores a view that is not a text field.
6250            let purpose = match traits.purpose {
6251                InputPurpose::Text => 0,
6252                InputPurpose::Name => 1,
6253                InputPurpose::Email => 2,
6254                InputPurpose::Url => 3,
6255                InputPurpose::Phone => 4,
6256                InputPurpose::Number => 5,
6257                InputPurpose::Decimal => 6,
6258                InputPurpose::Username => 7,
6259                InputPurpose::Password => 8,
6260                InputPurpose::NewPassword => 9,
6261                InputPurpose::OneTimeCode => 10,
6262            };
6263            let submit = match traits.submit_label {
6264                SubmitLabel::Return => 0,
6265                SubmitLabel::Done => 1,
6266                SubmitLabel::Go => 2,
6267                SubmitLabel::Next => 3,
6268                SubmitLabel::Search => 4,
6269                SubmitLabel::Send => 5,
6270            };
6271            // `max_length` stays with day-pieces: it counts characters, and Android's
6272            // `LengthFilter` counts UTF-16 units, so a native bound would refuse text the
6273            // bound allows.
6274            with_env(|env| {
6275                let _ = DayBridge::setInputTraits(
6276                    env,
6277                    h.0.as_obj(),
6278                    traits.secure,
6279                    traits.read_only,
6280                    purpose,
6281                    submit,
6282                );
6283                if env.exception_check() {
6284                    env.exception_clear();
6285                }
6286            });
6287            None
6288        }
6289
6290        fn set_cursor(&mut self, h: &AHandle, cursor: Cursor) {
6291            // `View.setPointerIcon` (API 24): a system icon by `PointerIcon.TYPE_*`, or null to
6292            // release the view to the platform's own choice (docs/cursor.md). Only a mouse or
6293            // trackpad ever shows it; a finger never does, which is correct.
6294            let ty = pointer_icon_type(&cursor);
6295            bridge(|env| {
6296                let icon = match ty {
6297                    None => JObject::null(),
6298                    Some(t) => {
6299                        let ctx = DayRuntime::ctx(env)?;
6300                        framework::PointerIcon::getSystemIcon(env, &ctx, t)?.into()
6301                    }
6302                };
6303                downcast::<framework::View>(env, h.0.as_obj())?.setPointerIcon(env, &icon)
6304            });
6305        }
6306
6307        fn set_scroll_content(&mut self, h: &AHandle, content: Size) {
6308            let d = density();
6309            bridge(|env| {
6310                DayBridge::setScrollContent(
6311                    env,
6312                    h.0.as_obj(),
6313                    (content.width * d).round() as i32,
6314                    (content.height * d).round() as i32,
6315                )
6316            });
6317        }
6318
6319        /// Material's one-line list item: 16dp sides, 56dp tall (8dp keeps taller content off the edges).
6320        fn list_row_metrics(&mut self, _h: &AHandle) -> day_spec::RowMetrics {
6321            day_spec::RowMetrics {
6322                insets: day_spec::Insets {
6323                    top: 8.0,
6324                    leading: 16.0,
6325                    bottom: 8.0,
6326                    trailing: 16.0,
6327                },
6328                min_height: 56.0,
6329            }
6330        }
6331
6332        /// A row scroll (docs/list.md "Programmatic scrolling"): `DayBridge.listScroll` posts
6333        /// it behind any pending row update, then `scrollToPositionWithOffset` for a jump or
6334        /// `smoothScrollBy` over the aligned distance for an animation. The list's viewport
6335        /// report follows from its scroll and layout callbacks.
6336        fn list_scroll(&mut self, h: &AHandle, to: day_spec::ListScroll) -> bool {
6337            let row = to.row.map_or(-1, |r| i32::try_from(r).unwrap_or(i32::MAX));
6338            let align = crate::list_wire::align_code(to.align);
6339            java(|env| DayBridge::listScroll(env, h.0.as_obj(), row, align, to.animated)).is_some()
6340        }
6341
6342        fn nav_scroll_to_edge(&mut self, h: &AHandle, bottom: bool) -> bool {
6343            with_env(|env| DayBridge::navScrollToEdge(env, h.0.as_obj(), bottom).unwrap_or(false))
6344        }
6345
6346        fn scroll_to(&mut self, h: &AHandle, target: Rect, animated: bool) {
6347            let d = density();
6348            bridge(|env| {
6349                DayBridge::scrollToRect(
6350                    env,
6351                    h.0.as_obj(),
6352                    (target.origin.x * d).round() as i32,
6353                    (target.origin.y * d).round() as i32,
6354                    (target.size.width * d).round() as i32,
6355                    (target.size.height * d).round() as i32,
6356                    animated,
6357                )
6358            });
6359        }
6360
6361        fn set_focusable(&mut self, h: &AHandle, node: NodeId, focusable: bool) {
6362            if focusable {
6363                bridge(|env| DayBridge::enableKeys(env, h.0.as_obj(), node.0 as i64));
6364            }
6365        }
6366
6367        fn focus(&mut self, h: &AHandle, _node: NodeId, focused: bool) {
6368            // DayBridge pairs the request with the IME (show on gain, hide on resign) and
6369            // resigns to the focusable content root, since Android focus is never "nowhere".
6370            bridge(|env| DayBridge::focusView(env, h.0.as_obj(), focused));
6371        }
6372
6373        fn set_event_sink(&mut self, sink: EventSink) {
6374            SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
6375        }
6376
6377        fn enable_gesture(&mut self, h: &AHandle, node: NodeId, kind: day_spec::GestureKind) {
6378            // Pan is a wheel listener and pinch a ScaleGestureDetector fed from the shared
6379            // touch listener (docs/canvas.md "Zoom and pan"); neither falls through to the tap
6380            // wire below.
6381            if kind == day_spec::GestureKind::Pan {
6382                bridge(|env| DayBridge::enablePan(env, h.0.as_obj(), node.0 as i64));
6383                return;
6384            }
6385            if kind == day_spec::GestureKind::Pinch {
6386                bridge(|env| DayBridge::enablePinch(env, h.0.as_obj(), node.0 as i64));
6387                return;
6388            }
6389            // Rotation is a two-pointer tracker in the bridge, on the same touch listener
6390            // (ScaleGestureDetector reports no angle), so it runs alongside the pinch.
6391            if kind == day_spec::GestureKind::Rotate {
6392                bridge(|env| DayBridge::enableRotate(env, h.0.as_obj(), node.0 as i64));
6393                return;
6394            }
6395            // Hover is a separate listener (`setOnHoverListener`), not a touch one: MotionEvent's
6396            // HOVER_* actions arrive only from a mouse or a stylus, so wiring it into the touch
6397            // path would mean testing for a pointer kind on every finger event.
6398            if matches!(kind, day_spec::GestureKind::Hover) {
6399                bridge(|env| DayBridge::enableHover(env, h.0.as_obj(), node.0 as i64));
6400                return;
6401            }
6402            // Long press and double tap are the platform's GestureDetector, press an observer
6403            // that never claims the stream, touches every pointer of the MotionEvent; all of
6404            // them ride the shared touch listener beside the tap and the drag (DayBridge
6405            // `Recognizers`, docs/gestures.md).
6406            let recognizer = match kind {
6407                day_spec::GestureKind::LongPress => Some(bridge::gesture::LONG_PRESS),
6408                day_spec::GestureKind::DoubleTap => Some(bridge::gesture::DOUBLE_TAP),
6409                day_spec::GestureKind::Press => Some(bridge::gesture::PRESS_IN),
6410                day_spec::GestureKind::Touches => Some(bridge::gesture::TOUCHES),
6411                _ => None,
6412            };
6413            if let Some(code) = recognizer {
6414                bridge(|env| DayBridge::enableRecognizer(env, h.0.as_obj(), node.0 as i64, code));
6415                return;
6416            }
6417            let is_drag = matches!(kind, day_spec::GestureKind::Drag);
6418            bridge(|env| DayBridge::enableGesture(env, h.0.as_obj(), node.0 as i64, is_drag));
6419        }
6420
6421        fn gesture_support(&self, _kind: day_spec::GestureKind) -> Support {
6422            // Every kind has its recognizer here: `GestureDetector` for the long press and
6423            // the double tap, the MotionEvent's own pointers for press and touches, and the
6424            // tap, drag, pinch, rotation, wheel pan and hover listeners there always were.
6425            Support::Native
6426        }
6427
6428        fn set_hit_slop(&mut self, h: &AHandle, _node: NodeId, slop: day_spec::Insets) {
6429            // The parent's TouchDelegate (DayBridge `SlopDelegate`), in px.
6430            let d = density();
6431            let px = |v: f64| (v.max(0.0) * d).round() as i32;
6432            bridge(|env| {
6433                DayBridge::setHitSlop(
6434                    env,
6435                    h.0.as_obj(),
6436                    px(slop.top),
6437                    px(slop.leading),
6438                    px(slop.bottom),
6439                    px(slop.trailing),
6440                )
6441            });
6442        }
6443
6444        fn set_drag_axis(&mut self, h: &AHandle, _node: NodeId, axis: Option<day_spec::DragAxis>) {
6445            let code = match axis {
6446                None => 0,
6447                Some(day_spec::DragAxis::Horizontal) => 1,
6448                Some(day_spec::DragAxis::Vertical) => 2,
6449            };
6450            bridge(|env| DayBridge::setDragAxis(env, h.0.as_obj(), code));
6451        }
6452
6453        fn set_subtree_enabled(&mut self, h: &AHandle, _node: NodeId, enabled: bool) {
6454            bridge(|env| DayBridge::setSubtreeEnabled(env, h.0.as_obj(), enabled));
6455        }
6456
6457        fn primary_pointer(&self) -> day_spec::PointerKind {
6458            // Touch where the device has a touch screen, a mouse where it has none (a
6459            // Chromebook, a TV box with a mouse).
6460            with_env(|env| java_string(env, DayBridge::primaryPointer))
6461                .and_then(|name| day_spec::PointerKind::from_name(&name))
6462                .unwrap_or_else(day_spec::PointerKind::platform_default)
6463        }
6464
6465        fn set_context_menu_fn(&mut self, h: &AHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
6466            let key = h.0.as_obj().as_raw() as usize;
6467            CONTEXT_MENU_FNS.with(|menus| menus.insert(key, f));
6468            bridge(|env| DayBridge::setContextMenuFn(env, h.0.as_obj(), key as i64));
6469        }
6470
6471        fn set_button_menu(&mut self, h: &AHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
6472            // The click opens a PopupMenu under the button (DayBridge.setButtonMenu), built from
6473            // the spec the provider lowers at that moment, in place of the `Pressed` report.
6474            let key = h.0.as_obj().as_raw() as usize;
6475            BUTTON_MENU_FNS.with(|menus| menus.insert(key, f));
6476            bridge(|env| DayBridge::setButtonMenu(env, h.0.as_obj(), key as i64));
6477        }
6478
6479        fn set_context_menu(&mut self, h: &AHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
6480            CONTEXT_MENU_FNS.with(|menus| menus.remove(h.0.as_obj().as_raw() as usize));
6481            let mut spec = String::new();
6482            serialize_menu(items, &mut spec);
6483            with_env(|env| {
6484                let jspec = jstr(env, &spec);
6485                let _ = java_in(env, |env| {
6486                    DayBridge::setContextMenu(env, h.0.as_obj(), &jspec)
6487                });
6488            });
6489        }
6490
6491        fn edit_toolbar(&mut self, h: &AHandle, ops: &[day_spec::ToolbarOp]) -> bool {
6492            // The window toolbar (docs/toolbars.md) is the nav host's app-bar menu: actions the
6493            // platform lays out and folds into its overflow itself, built on the Java side from
6494            // a record-per-item spec. A menu item holds no state of its own, so an edit is
6495            // applied to the model and the menu repainted from it. The one exception, a page's
6496            // search action, keeps its SearchView across the repaint (DayNavHost.WindowBar). Best-effort like every other nav decoration: a throw must never
6497            // reach the tree build.
6498            let key = h.0.as_obj().as_raw() as usize;
6499            let spec = WINDOW_BARS.with(|m| {
6500                let mut m = m.borrow_mut();
6501                let bar = m.entry(key).or_default();
6502                for op in ops {
6503                    bar.apply(op);
6504                }
6505                serialize_toolbar(bar.items())
6506            });
6507            with_env(|env| {
6508                let jspec = jstr(env, &spec);
6509                let _ = java_in(env, |env| {
6510                    DayBridge::setWindowToolbar(env, h.0.as_obj(), &jspec)
6511                });
6512                if env.exception_check() {
6513                    env.exception_clear();
6514                }
6515            });
6516            true
6517        }
6518
6519        fn update_toolbar(&mut self, h: &AHandle, patch: &day_spec::ToolbarPatch) {
6520            use day_spec::ToolbarPatch as P;
6521            // The model first, so the next repaint shows the value too.
6522            let key = h.0.as_obj().as_raw() as usize;
6523            WINDOW_BARS.with(|m| {
6524                if let Some(bar) = m.borrow_mut().get_mut(&key) {
6525                    bar.patch(patch);
6526                }
6527            });
6528            let (item, op, num) = match patch {
6529                P::Enabled { item, on } => (item, 0, f64::from(u8::from(*on))),
6530                P::On { item, on } => (item, 1, f64::from(u8::from(*on))),
6531                P::Selected { item, index } => (item, 2, *index as f64),
6532                // A page's search action (docs/search.md): reveal the field and give it focus.
6533                P::Focus { item } => (item, 3, 0.0),
6534                // The app wrote the page's query: into the live field, without its listeners
6535                // echoing it back, and without rebuilding the field under the user's typing.
6536                P::Text { item, text } => {
6537                    with_env(|env| {
6538                        let jid = jstr(env, item);
6539                        let jtext = jstr(env, text);
6540                        let _ = java_in(env, |env| {
6541                            DayBridge::updateWindowToolbarText(env, h.0.as_obj(), &jid, &jtext)
6542                        });
6543                        if env.exception_check() {
6544                            env.exception_clear();
6545                        }
6546                    });
6547                    return;
6548                }
6549                // The app bar's SearchView offers no completions (docs/search.md).
6550                P::Suggestions { .. } => return,
6551                // New words or a new prompt: the menu is repainted from the model, which is how
6552                // an Android app bar takes a changed item (its SearchView survives the repaint).
6553                // The bottom bar's status takes new words in place, the way the page's search
6554                // field takes its text: a repaint would rebuild the bar's buttons for every
6555                // step of a sync.
6556                P::Label { item, label, .. }
6557                    if WINDOW_BARS.with(|m| {
6558                        m.borrow().get(&key).is_some_and(|bar| {
6559                            bar.items().iter().any(|i| {
6560                                i.id == *item
6561                                    && i.placement == day_spec::ToolbarPlacement::Bottom
6562                                    && matches!(i.kind, day_spec::ToolbarItemKind::Label)
6563                            })
6564                        })
6565                    }) =>
6566                {
6567                    with_env(|env| {
6568                        let jid = jstr(env, item);
6569                        let jtext = jstr(env, label);
6570                        let _ = java_in(env, |env| {
6571                            DayBridge::updateWindowToolbarText(env, h.0.as_obj(), &jid, &jtext)
6572                        });
6573                        if env.exception_check() {
6574                            env.exception_clear();
6575                        }
6576                    });
6577                    return;
6578                }
6579                P::Label { .. } | P::Placeholder { .. } => {
6580                    let spec = WINDOW_BARS.with(|m| {
6581                        m.borrow()
6582                            .get(&key)
6583                            .map(|bar| serialize_toolbar(bar.items()))
6584                    });
6585                    if let Some(spec) = spec {
6586                        with_env(|env| {
6587                            let jspec = jstr(env, &spec);
6588                            let _ = java_in(env, |env| {
6589                                DayBridge::setWindowToolbar(env, h.0.as_obj(), &jspec)
6590                            });
6591                            if env.exception_check() {
6592                                env.exception_clear();
6593                            }
6594                        });
6595                    }
6596                    return;
6597                }
6598            };
6599            with_env(|env| {
6600                let jid = jstr(env, item);
6601                let _ = java_in(env, |env| {
6602                    DayBridge::updateWindowToolbar(env, h.0.as_obj(), &jid, op, num)
6603                });
6604                if env.exception_check() {
6605                    env.exception_clear();
6606                }
6607            });
6608        }
6609
6610        fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
6611            // Android has no persistent menu bar; the platform convention for a global app menu is
6612            // the app-bar overflow (⋮). DayActivity.onCreateOptionsMenu builds from this spec.
6613            let mut spec = String::new();
6614            serialize_menu(items, &mut spec);
6615            with_env(|env| {
6616                let jspec = jstr(env, &spec);
6617                let _ = java_in(env, |env| DayBridge::setAppMenu(env, &jspec));
6618            });
6619        }
6620
6621        fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool {
6622            lifecycle_supported(phase)
6623        }
6624
6625        fn attach_tree(&mut self, host: &AHandle, source: day_spec::TreeSource) {
6626            if let Some(id) = LIST_NODE.with(|m| {
6627                m.borrow()
6628                    .get(&(host.0.as_obj().as_raw() as usize))
6629                    .copied()
6630            }) {
6631                TREE_SOURCES.with(|m| m.borrow_mut().insert(id, (source, Vec::new(), Vec::new())));
6632                tree_reload(host);
6633            }
6634        }
6635        fn attach_list(&mut self, host: &AHandle, source: ListSource) {
6636            // A source that observes the viewport gets the whole report (DayListView reports
6637            // after its first layout with rows), and never the first-row-only one.
6638            let viewport = source.viewport.is_some();
6639            if !viewport && let Some(report) = &source.first_visible {
6640                report(0);
6641            }
6642            let reader = source.reader_scroll.is_some();
6643            let supplements = source.is_supplement.is_some();
6644            bridge(|env| {
6645                DayBridge::listConfigure(env, host.0.as_obj(), viewport, reader, supplements)
6646            });
6647            let key = host.0.as_obj().as_raw() as usize;
6648            if let Some(nid) = LIST_NODE.with(|m| m.borrow().get(&key).copied()) {
6649                LIST_SOURCES.with(|m| {
6650                    m.borrow_mut().insert(nid, source);
6651                });
6652            }
6653            bridge(|env| DayBridge::listReload(env, host.0.as_obj()));
6654        }
6655
6656        fn adopt(&mut self, raw: RawHandle) -> AHandle {
6657            // A recycling ListView cell (a DayFixed); Day fills/rebinds its row content in place.
6658            with_env(|env| {
6659                let obj = unsafe { JObject::from_raw(env, raw as jni::sys::jobject) };
6660                AHandle(std::sync::Arc::new(
6661                    // Only fails when the JNI global-ref table is exhausted (a process-fatal
6662                    // leak elsewhere); there is no cell to hand back without the ref.
6663                    env.new_global_ref(&obj).expect("adopt: global ref"),
6664                ))
6665            })
6666        }
6667
6668        fn native_document_tabs(&self) -> bool {
6669            true
6670        }
6671
6672        fn open_window(
6673            &mut self,
6674            id: NodeId,
6675            options: &day_spec::WindowOptions,
6676            kind: day_spec::WindowKind,
6677        ) -> day_spec::WindowOpenReply<AHandle> {
6678            // Preferences stay modal on mobile (docs/windows.md); the cover fallback is
6679            // the platform settings idiom; Normal windows become document activities.
6680            if kind.is_panel() {
6681                return day_spec::WindowOpenReply::Unsupported;
6682            }
6683            let ok = with_env(|env| {
6684                let Ok(title) = env.new_string(&options.title) else {
6685                    return false;
6686                };
6687                java_in(env, |env| DayBridge::openWindow(env, id.0 as i64, &title)).is_some()
6688            });
6689            if ok {
6690                day_spec::WindowOpenReply::Pending
6691            } else {
6692                day_spec::WindowOpenReply::Unsupported
6693            }
6694        }
6695
6696        fn close_window(&mut self, host: &AHandle) {
6697            with_env(|env| {
6698                if let Some(node) = secondary_node_of(env, host) {
6699                    let _ = java_in(env, |env| DayBridge::closeWindow(env, node as i64));
6700                }
6701            });
6702        }
6703
6704        fn focus_window(&mut self, host: &AHandle) {
6705            with_env(|env| {
6706                if let Some(node) = secondary_node_of(env, host) {
6707                    let _ = java_in(env, |env| DayBridge::focusWindow(env, node as i64));
6708                }
6709            });
6710        }
6711
6712        /// Window properties (docs/windows.md): fullscreen through the activity window's
6713        /// insets controller, content protection through `FLAG_SECURE`. `DayBridge` addresses
6714        /// a window by its day node, 0 for the primary activity, and reports the outcome
6715        /// back as `K_WINDOW_STATE_CHANGED`.
6716        fn apply_window(&mut self, host: &AHandle, change: &day_spec::WindowChange) {
6717            use day_spec::WindowChange as C;
6718            with_env(|env| {
6719                let node = secondary_node_of(env, host).unwrap_or(0) as i64;
6720                match change {
6721                    C::State(state) => {
6722                        let _ = java_in(env, |env| {
6723                            DayBridge::setWindowState(env, node, state.code())
6724                        });
6725                    }
6726                    C::ContentProtected(on) => {
6727                        let _ = java_in(env, |env| DayBridge::setWindowSecure(env, node, *on));
6728                    }
6729                    // Size, position and stacking belong to the system and the user here.
6730                    // `Appearance` stays Unsupported too: the activities are FragmentActivity,
6731                    // and the one per-activity route (an overridden uiMode configuration)
6732                    // recreates the activity, losing what the window shows; the app-wide
6733                    // `set_appearance` still applies to every window.
6734                    _ => {}
6735                }
6736            });
6737        }
6738
6739        /// The display the primary window is on (`Cap::Monitors` Emulated), in dp, with the
6740        /// work area inside the system bars and any cutout.
6741        fn monitors(&self) -> Vec<day_spec::Monitor> {
6742            let line = with_env(|env| {
6743                let info = DayBridge::displayInfo(env).ok()?;
6744                if info.is_null() {
6745                    return None;
6746                }
6747                string_of(env, &info).ok()
6748            });
6749            line.and_then(|l| parse_display_info(&l))
6750                .into_iter()
6751                .collect()
6752        }
6753
6754        /// Dynamic shortcuts through `ShortcutManager` (docs/deep-links.md): each opens its
6755        /// route through the same deep-link intent the Day.toml `[[shortcuts]]` carry.
6756        fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
6757            // One string over JNI: records split by U+001E, route and label by U+001F.
6758            let packed = shortcuts
6759                .iter()
6760                .map(|sc| {
6761                    let clean = |s: &str| s.replace(['\u{1e}', '\u{1f}'], " ");
6762                    format!("{}\u{1f}{}", clean(&sc.route), clean(&sc.label))
6763                })
6764                .collect::<Vec<_>>()
6765                .join("\u{1e}");
6766            with_env(|env| {
6767                let jpacked = jstr(env, &packed);
6768                let _ = java_in(env, |env| DayBridge::setLauncherShortcuts(env, &jpacked));
6769            });
6770        }
6771
6772        fn set_window_title(&mut self, host: &AHandle, title: &str) {
6773            with_env(|env| {
6774                let Ok(jtitle) = env.new_string(title) else {
6775                    return;
6776                };
6777                match secondary_node_of(env, host) {
6778                    Some(node) => {
6779                        let _ = java_in(env, |env| {
6780                            DayBridge::setWindowTitle(env, node as i64, &jtitle)
6781                        });
6782                    }
6783                    // The primary is an ordinary window (docs/windows.md) and gets a recents
6784                    // card of its own, so it takes a label like any other; it just has no
6785                    // `day.node` to be addressed by.
6786                    None => {
6787                        let _ = java_in(env, |env| DayBridge::setPrimaryWindowTitle(env, &jtitle));
6788                    }
6789                }
6790            });
6791        }
6792
6793        fn set_a11y(&mut self, h: &AHandle, a11y: &A11yProps) {
6794            // The role crosses as its `day_spec::Role` declaration index (DayBridge's
6795            // `ROLE_*` constants) with the heading level beside it; an empty string is an
6796            // unset member, and the bridge leaves those alone.
6797            let (role, level) = match a11y.role {
6798                Role::None => (0, 0),
6799                Role::Button => (1, 0),
6800                Role::Toggle => (2, 0),
6801                Role::Slider => (3, 0),
6802                Role::TextInput => (4, 0),
6803                Role::Heading(level) => (5, i32::from(level)),
6804                Role::Image => (6, 0),
6805                Role::Meter => (7, 0),
6806                Role::Group => (8, 0),
6807                Role::Tree => (9, 0),
6808                Role::TreeItem => (10, 0),
6809                Role::Tab => (11, 0),
6810                Role::TabList => (12, 0),
6811            };
6812            with_env(|env| {
6813                let label = jstr(env, a11y.label.as_deref().unwrap_or(""));
6814                let hint = jstr(env, a11y.hint.as_deref().unwrap_or(""));
6815                let value = jstr(env, a11y.value.as_deref().unwrap_or(""));
6816                let id = jstr(env, a11y.identifier.as_deref().unwrap_or(""));
6817                // -1 leaves the view's own selected state alone.
6818                let selected = a11y.selected.map_or(-1, i32::from);
6819                let _ = java_in(env, |env| {
6820                    DayBridge::setA11y(
6821                        env,
6822                        h.0.as_obj(),
6823                        &label,
6824                        &hint,
6825                        &value,
6826                        &id,
6827                        role,
6828                        level,
6829                        a11y.hidden,
6830                        selected,
6831                    )
6832                });
6833            });
6834        }
6835
6836        /// `DayBridge.readNative`: every field in one call, as a `String[]` whose slots (the
6837        /// bridge's `RN_*` order) are null where the view was not read.
6838        fn read_native(&self, h: &AHandle) -> day_spec::NativeSnapshot {
6839            if !vm_ready() {
6840                return day_spec::NativeSnapshot::default();
6841            }
6842            let slots: Vec<Option<String>> = java(|env| {
6843                let arr = DayBridge::readNative(env, h.0.as_obj())?;
6844                let len = arr.len(env)?;
6845                let mut slots = Vec::with_capacity(len);
6846                for i in 0..len {
6847                    let s = arr.get_element(env, i)?;
6848                    slots.push(read_jstring(env, &s));
6849                }
6850                Ok(slots)
6851            })
6852            .unwrap_or_default();
6853            let slot = |i: usize| slots.get(i).cloned().flatten();
6854            let flag = |i: usize| slot(i).map(|s| s == "1");
6855            let found = flag(0) == Some(true);
6856            // `DayBridge.ROLE_*`, `set_a11y`'s numbering; the node carries no heading level.
6857            let role = match slot(1).and_then(|s| s.parse::<i32>().ok()) {
6858                Some(1) => Role::Button,
6859                Some(2) => Role::Toggle,
6860                Some(3) => Role::Slider,
6861                Some(4) => Role::TextInput,
6862                Some(5) => Role::Heading(1),
6863                Some(6) => Role::Image,
6864                Some(7) => Role::Meter,
6865                Some(8) => Role::Group,
6866                _ => Role::None,
6867            };
6868            let frame = slot(10).and_then(|s| {
6869                let v: Vec<f64> = s.split(',').filter_map(|n| n.parse().ok()).collect();
6870                match v[..] {
6871                    [x, y, w, h] => Some(Rect::new(x, y, w, h)),
6872                    _ => None,
6873                }
6874            });
6875            day_spec::NativeSnapshot {
6876                found,
6877                role,
6878                label: found.then(|| slot(2)).flatten(),
6879                value: found.then(|| slot(3)).flatten(),
6880                identifier: found.then(|| slot(4)).flatten().filter(|s| !s.is_empty()),
6881                text: slot(5),
6882                number: slot(6).and_then(|s| s.parse().ok()),
6883                checked: flag(7),
6884                enabled: flag(8),
6885                visible: flag(9),
6886                frame,
6887            }
6888        }
6889
6890        fn announce(&mut self, text: &str, urgent: bool) {
6891            with_env(|env| {
6892                let text = jstr(env, text);
6893                let _ = java_in(env, |env| DayBridge::announce(env, &text, urgent));
6894            });
6895        }
6896
6897        fn request_frame(
6898            &mut self,
6899            _host: &AHandle,
6900            cb: day_spec::FrameCallback,
6901        ) -> day_spec::CancelFrame {
6902            let token = day_core::frame::native::register(cb);
6903            bridge(|env| DayBridge::requestFrame(env, token as i64));
6904            Box::new(move || {
6905                day_core::frame::native::cancel(token);
6906                bridge(|env| DayBridge::cancelFrame(env, token as i64));
6907            })
6908        }
6909
6910        /// The display list to `DayCanvasView` on three channels: the records, the texts, and
6911        /// the path and polygon points as numbers (`encode_ops_with_geometry`), which cross JNI
6912        /// as one `double[]` instead of being formatted here and parsed there every frame.
6913        fn replay(&mut self, h: &AHandle, ops: &[DrawOp], _size: Size) {
6914            let (nums, texts, geometry) = day_spec::encode_ops_with_geometry(ops);
6915            with_env(|env| {
6916                // Allocation failure (OOM-class) skips the frame instead of panicking out
6917                // of a JNI up-call (which aborts); the next replay redraws in full.
6918                let Ok(arr) = env.new_double_array(nums.len()) else {
6919                    return;
6920                };
6921                if arr.set_region(env, 0, &nums).is_err() {
6922                    return;
6923                }
6924                let Ok(geo) = env.new_double_array(geometry.len()) else {
6925                    return;
6926                };
6927                if geo.set_region(env, 0, &geometry).is_err() {
6928                    return;
6929                }
6930                let joined = jstr(env, &texts.join("\u{1f}"));
6931                let _ = java_in(env, |env| {
6932                    DayBridge::setCanvasOps(env, h.0.as_obj(), &arr, &joined, &geo)
6933                });
6934            });
6935        }
6936
6937        /// `DayBridge.fontFamilies()`: the `fonts.xml` families in Day's list text
6938        /// (docs/fonts.md), one string across JNI like `locale_hints`.
6939        /// `DayBridge.snapshotOrigin`: the root's offset in the edge-to-edge content capture.
6940        fn snapshot_origin(&mut self, root: &AHandle) -> Option<Point> {
6941            if !vm_ready() {
6942                return None;
6943            }
6944            let text = with_env(|env| {
6945                let obj = DayBridge::snapshotOrigin(env, root.0.as_obj()).ok()?;
6946                if obj.is_null() {
6947                    return None;
6948                }
6949                string_of(env, &obj).ok()
6950            })?;
6951            let (x, y) = text.split_once(',')?;
6952            Some(Point::new(x.parse().ok()?, y.parse().ok()?))
6953        }
6954
6955        fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
6956            if !vm_ready() {
6957                return Vec::new();
6958            }
6959            let text = with_env(|env| {
6960                let obj = DayBridge::fontFamilies(env).ok()?;
6961                if obj.is_null() {
6962                    return None;
6963                }
6964                string_of(env, &obj).ok()
6965            });
6966            day_spec::parse_font_list(&text.unwrap_or_default())
6967        }
6968
6969        /// `DayBridge.measureText(...)`: "width,height,ascent" in dp from the same `Paint`
6970        /// the canvas draws with (docs/fonts.md).
6971        fn measure_text(
6972            &mut self,
6973            text: &str,
6974            size: f64,
6975            font: &day_spec::CanvasFont,
6976        ) -> Option<day_spec::TextMetrics> {
6977            if !vm_ready() {
6978                return None;
6979            }
6980            let reply = with_env(|env| {
6981                let jtext = jstr(env, text);
6982                let jfamily = jstr(env, font.family_str());
6983                let weight = i32::from(font.css_weight());
6984                java_string(env, |env| {
6985                    DayBridge::measureText(env, &jtext, size, weight, font.italic, &jfamily)
6986                })
6987            })?;
6988            // The eight numbers `DayBridge.measureText` joins, in the order `from_slots` reads.
6989            let mut out = [0.0f64; 8];
6990            let mut it = reply.split(',');
6991            for slot in &mut out {
6992                *slot = it.next()?.trim().parse::<f64>().ok()?;
6993            }
6994            Some(day_spec::TextMetrics::from_slots(&out))
6995        }
6996
6997        /// Decode bytes with `BitmapFactory` (docs/images.md), which reads every container
6998        /// Android knows: PNG, JPEG, WebP, GIF, BMP and HEIF on API 28+.
6999        ///
7000        /// The reply is the same comma-joined shape `measureText` uses, because that is this
7001        /// backend's established way to bring a few numbers back across JNI.
7002        fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
7003            let reply = if vm_ready() {
7004                with_env(|env| {
7005                    let arr = env.byte_array_from_slice(bytes).ok()?;
7006                    java_string(env, |env| DayBridge::imageDecode(env, id.0 as i64, &arr))
7007                })
7008            } else {
7009                None
7010            };
7011            // "w,h,alpha", and unlike most backends here, the alpha answer is read from the
7012            // decoded bitmap rather than inferred from the container format.
7013            let parsed = reply.and_then(|r| {
7014                let mut it = r.split(',');
7015                let w = it.next()?.trim().parse::<f64>().ok()?;
7016                let h = it.next()?.trim().parse::<f64>().ok()?;
7017                let alpha = it.next()?.trim().parse::<i32>().ok()?;
7018                Some((w, h, alpha != 0))
7019            });
7020            let event = match parsed {
7021                Some((w, h, has_alpha)) => {
7022                    let info = day_spec::BitmapInfo {
7023                        pixels: Size::new(w, h),
7024                        // Decoded bytes carry no density; a PNG is its pixels.
7025                        scale: 1.0,
7026                        format: day_spec::ImageFormat::sniff(bytes),
7027                        has_alpha,
7028                    };
7029                    BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
7030                    Event::ImageDecoded {
7031                        req,
7032                        result: Ok(info),
7033                    }
7034                }
7035                None => Event::ImageDecoded {
7036                    req,
7037                    result: Err(day_spec::ImageError::Decode),
7038                },
7039            };
7040            emit(day_spec::WINDOW_NODE, event);
7041        }
7042
7043        fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
7044            BITMAP_INFO.with(|m| m.borrow().get(&id.0).copied())
7045        }
7046
7047        fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
7048            let result = encode_bitmap(id, spec);
7049            emit(day_spec::WINDOW_NODE, Event::ImageEncoded { req, result });
7050        }
7051
7052        /// What `Bitmap.compress` writes under this scaffold's minSdk (24). Android reads more
7053        /// (WebP among them), and the asymmetry is the platform's own: `WEBP_LOSSY` and
7054        /// `WEBP_LOSSLESS` arrived in API 30, and the pre-30 `WEBP` constant is deprecated there.
7055        fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
7056            use day_spec::ImageFormat::{Jpeg, Png};
7057            vec![Png, Jpeg]
7058        }
7059
7060        fn release_image(&mut self, id: day_spec::BitmapId) {
7061            BITMAP_INFO.with(|m| {
7062                m.borrow_mut().remove(&id.0);
7063            });
7064            if vm_ready() {
7065                with_env(|env| {
7066                    let _ = DayBridge::imageRelease(env, id.0 as i64);
7067                });
7068            }
7069        }
7070
7071        /// Paint `ops` into a new `Bitmap` with the painter `replay` drives (`DayCanvasView`'s
7072        /// `OpPainter`), stored in `DayBridge.bitmaps` beside decoded bitmaps, so every image
7073        /// duty and the image piece take it (docs/canvas.md "Exporting").
7074        ///
7075        /// The whole job — encoding the ops for the wire, the JNI call, Skia's software paint
7076        /// into the `Bitmap` — runs on a `day_spec::offscreen` thread: a `Bitmap`-backed
7077        /// `Canvas` draws from any thread, and a map tile of a thousand paths took most of a
7078        /// second on a Pixel 6. `DayBridge.bitmaps` is a concurrent map, so the images the ops
7079        /// draw are read there directly and a bitmap that lands is visible to the UI thread at
7080        /// once; the answer, and the `BITMAP_INFO` entry before it, are posted back here.
7081        fn render_bitmap(
7082            &mut self,
7083            req: u64,
7084            id: day_spec::BitmapId,
7085            ops: &[DrawOp],
7086            size: Size,
7087            scale: f64,
7088        ) {
7089            if !vm_ready() {
7090                let result = Err(day_spec::ExportError::Unsupported);
7091                emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
7092                return;
7093            }
7094            let (pw, ph) = day_spec::export_pixels(size, scale);
7095            let ops = ops.to_vec();
7096            day_spec::offscreen::spawn(move || {
7097                let result = day_spec::ffi_guard::contain(
7098                    Err(day_spec::ExportError::Failed(
7099                        "the offscreen painter panicked".into(),
7100                    )),
7101                    || export_bitmap(id, &ops, pw, ph, scale),
7102                );
7103                <Material as Platform>::post(Box::new(move || {
7104                    if let Ok(info) = result {
7105                        BITMAP_INFO.with(|m| m.borrow_mut().insert(id.0, info));
7106                    }
7107                    emit(day_spec::WINDOW_NODE, Event::BitmapRendered { req, result });
7108                }));
7109            });
7110        }
7111
7112        /// One `PdfDocument` page per drawing, painted by the same `OpPainter`. The writer has
7113        /// no metadata API, so `info` (title, author) goes unwritten, and its pages take whole
7114        /// points.
7115        fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], _info: &day_spec::PdfInfo) {
7116            let result = export_pdf(pages);
7117            emit(day_spec::WINDOW_NODE, Event::PdfRendered { req, result });
7118        }
7119
7120        fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
7121            android_window_image(false)
7122        }
7123
7124        /// The decor view rather than the content view: the window with its action bar and
7125        /// system-bar backgrounds (docs/window-image.md).
7126        fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
7127            android_window_image(true)
7128        }
7129
7130        /// Apply an app-level appearance (docs/settings.md "Appearance on Android"). The uiMode
7131        /// change the platform makes comes straight back as a configuration change that
7132        /// `DayActivity` turns into `appearanceChanged()` and a recreation, so nothing has to
7133        /// be reported from here.
7134        fn set_appearance(&mut self, dark: Option<bool>) {
7135            let mode = match dark {
7136                Some(false) => 0i32,
7137                Some(true) => 1,
7138                None => 2,
7139            };
7140            with_env(|env| {
7141                let _ = DayBridge::setAppearance(env, mode);
7142            });
7143        }
7144
7145        /// The theme's Material 3 color for each role (DayBridge.systemColor, by the role's
7146        /// wire number), so custom drawing matches the window and the status bar behind it.
7147        /// Success and warning have no Material 3 role and take Day's fallback, as every role
7148        /// does before a themed context exists.
7149        fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
7150            use day_spec::SystemColor;
7151            if matches!(role, SystemColor::Success | SystemColor::Warning) {
7152                return role.fallback(self.dark_mode());
7153            }
7154            let index = i32::from(role.wire());
7155            let argb = with_env(|env| DayBridge::systemColor(env, index).unwrap_or(0)) as u32;
7156            if argb == 0 {
7157                return role.fallback(self.dark_mode());
7158            }
7159            let channel = |shift: u32| f64::from((argb >> shift) & 0xff) / 255.0;
7160            day_spec::Color::rgba(channel(16), channel(8), channel(0), channel(24))
7161        }
7162
7163        /// The system color mode, `DAY_THEME` override first (themed capture runs).
7164        fn dark_mode(&mut self) -> bool {
7165            match std::env::var("DAY_THEME").ok().as_deref() {
7166                Some("dark") => return true,
7167                Some("light") => return false,
7168                _ => {}
7169            }
7170            with_env(|env| DayBridge::isDarkMode(env).unwrap_or(false))
7171        }
7172
7173        /// The user's "Remove animations" setting (docs/accessibility.md): the global animator
7174        /// duration scale read as zero (DayBridge.reduceMotion). The observer `DayActivity`
7175        /// registers reports each flip as `K_REDUCE_MOTION_CHANGED`, after which day-core asks
7176        /// here again.
7177        fn reduce_motion(&mut self) -> bool {
7178            with_env(|env| DayBridge::reduceMotion(env).unwrap_or(false))
7179        }
7180
7181        /// The reader's font size setting for `style` (docs/text.md "Text scale"): the pixels
7182        /// Android gives the style's sp size over those it gives it at the default setting
7183        /// (DayBridge.textScale). That is `Configuration.fontScale`, except on Android 14+,
7184        /// whose non-linear scaling grows large sizes less, so the answer is per style. A
7185        /// change recreates the activity (DayActivity.onConfigurationChanged), and the next
7186        /// mount reports it ([`mount_settled`]).
7187        fn text_scale(&mut self, style: Font) -> f64 {
7188            let sp = font_style(style).0;
7189            let scale = java(|env| DayBridge::textScale(env, sp)).map_or(1.0, f64::from);
7190            if scale.is_finite() && scale > 0.0 {
7191                scale
7192            } else {
7193                1.0
7194            }
7195        }
7196
7197        /// A widget's reading direction (docs/localization.md "Direction of a subtree"):
7198        /// `setLayoutDirection` + `setTextDirection` on the leaf (DayBridge.setViewDirection).
7199        /// Day's hosts are skipped: Day mirrors their children's frames itself, and the
7200        /// property on a view group only re-resolves start and end for those children.
7201        fn set_layout_direction(
7202            &mut self,
7203            h: &AHandle,
7204            kind: PieceKind,
7205            direction: day_spec::LayoutDirection,
7206        ) {
7207            if matches!(
7208                kind,
7209                kinds::CONTAINER
7210                    | kinds::SCROLL
7211                    | kinds::NAV
7212                    | kinds::NAV_PAGE
7213                    | kinds::LIST
7214                    | kinds::LIST_CELL
7215                    | kinds::TREE
7216                    | kinds::COVER
7217                    | kinds::INSPECTOR
7218                    | kinds::INSPECTOR_PANE
7219                    | kinds::SPLIT
7220                    | kinds::SPLIT_PANE
7221            ) {
7222                return;
7223            }
7224            let rtl = direction == day_spec::LayoutDirection::Rtl;
7225            bridge(|env| DayBridge::setViewDirection(env, h.0.as_obj(), rtl));
7226        }
7227
7228        /// The system back, pressed (dayscript's `nav_back: { native: true }`): through the
7229        /// activity's `OnBackPressedDispatcher`, so the guard callback and the fragment
7230        /// manager's own pop run exactly as a gesture does (DayBridge.nativeBack). `false`
7231        /// when nothing would pop, since the dispatcher would finish the activity instead.
7232        fn native_back(&mut self) -> bool {
7233            with_env(|env| DayBridge::nativeBack(env).unwrap_or(false))
7234        }
7235
7236        /// The app's own `OnBackPressedCallback`, beneath every other (DayBridge.appBack):
7237        /// enabled while an `on_system_back` handler is, so a back no cover or pushed page
7238        /// takes reaches Day instead of finishing the activity, and disabled otherwise, so the
7239        /// predictive "back to home" preview still shows when the press would leave.
7240        fn set_system_back(&mut self, armed: bool) {
7241            with_env(|env| {
7242                let _ = java_in(env, |env| DayBridge::setAppBack(env, armed));
7243            });
7244        }
7245
7246        /// Whether native transitions have settled (dayscript screenshots wait on this):
7247        /// currently the cover slide, since a capture mid-present/mid-dismiss shows a half-slid
7248        /// surface (DayBridge.uiIdle / DayCover.slidesInFlight).
7249        fn prepare_snapshot(
7250            &mut self,
7251            host: Option<&Self::Handle>,
7252            revision: u32,
7253        ) -> Result<day_spec::capture::Readiness, String> {
7254            with_env(|env| {
7255                let null = JObject::null();
7256                let obj = host.map_or(&null, |h| h.0.as_obj());
7257                let ready = DayBridge::prepareSnapshot(env, obj, i64::from(revision))
7258                    .map_err(|e| format!("frame commit: {e}"))?;
7259                Ok(if ready == 1 {
7260                    day_spec::capture::Readiness::Ready
7261                } else {
7262                    day_spec::capture::Readiness::Pending
7263                })
7264            })
7265        }
7266
7267        fn ui_idle(&mut self) -> bool {
7268            with_env(|env| DayBridge::uiIdle(env).unwrap_or(true))
7269        }
7270    }
7271
7272    /// The `DayBridge.navState` key the full route of a mount being torn down travels under
7273    /// (docs/settings.md "Appearance on Android"). Reserved: `.restore` keys are the app's,
7274    /// and none of Day's own start with `day.`.
7275    const REMOUNT_ROUTE_KEY: &str = "day.route";
7276
7277    /// `DayActivity` is about to recreate itself (a theme or language switch): save the full
7278    /// current route, so the re-mounted tree can come back to it. The activity recreation
7279    /// re-runs the app's `root()`, so every signal made there starts over; only a nav surface
7280    /// with a `.restore(key)` reads its place back by itself, and an app without one came back
7281    /// on its first tab. Saved straight into `DayBridge.navState`, not through the installed
7282    /// `NavStore`: the map is the activity's own instance state, exactly the lifetime a
7283    /// recreation needs, and an app that installed a disk-backed store must not find a
7284    /// transient route in it.
7285    fn save_route_for_remount(env: &mut Env) {
7286        let Some(route) = day_core::current_route() else {
7287            return;
7288        };
7289        let k = jstr(env, REMOUNT_ROUTE_KEY);
7290        let v = jstr(env, &route);
7291        let _ = java_in(env, |env| DayBridge::navSave(env, &k, &v));
7292    }
7293
7294    /// Read and clear a `DayBridge.navState` entry (`DayBridge.navTake`).
7295    fn nav_take(env: &mut Env, key: &str) -> Option<String> {
7296        let k = jstr(env, key);
7297        java_string(env, |env| DayBridge::navTake(env, &k))
7298    }
7299
7300    /// A mount's first build is done (`day::android::start`, after the tree is up). On a
7301    /// re-mount, put the app back where the previous mount left it; then tell the activity the
7302    /// tree has settled (`DayBridge.mountSettled`), which is what brings the recreation's
7303    /// crossfade down (docs/settings.md "Appearance on Android").
7304    ///
7305    /// Deferred one turn, behind the closure `launch_with` defers its own launch deep link
7306    /// into, for the same reason that one is: the first frame mounts before a destination
7307    /// pushes. A pending launch deep link wins over the saved route, as it wins over
7308    /// `.restore`; the saved route is consumed either way, so it can never apply to a later
7309    /// mount. A route a nav surface's `.restore` already restored is a no-op here, since the
7310    /// current route then equals the saved one.
7311    pub fn mount_settled(remount: bool) {
7312        day_reactive::on_main(move || {
7313            if remount {
7314                let saved = with_env(|env| nav_take(env, REMOUNT_ROUTE_KEY));
7315                if let Some(route) = saved {
7316                    if day_core::has_launch_deeplink() {
7317                        log::info!(
7318                            "day-toolkit-material: re-mount keeps the launch deep link over {route:?}"
7319                        );
7320                    } else if day_core::current_route().as_deref() != Some(route.as_str())
7321                        && !day_core::navigate(&route)
7322                    {
7323                        log::warn!(
7324                            "day-toolkit-material: re-mount could not restore route {route:?}"
7325                        );
7326                    }
7327                }
7328            }
7329            note_text_scale_of_mount();
7330            with_env(|env| {
7331                let _ = DayBridge::mountSettled(env);
7332            });
7333        });
7334    }
7335
7336    thread_local! {
7337        /// The reader's font scale the previous mount was built at (`Toolkit::text_scale` for
7338        /// `Body`). Outlives a re-mount on purpose: it is what tells this mount whether the
7339        /// setting moved.
7340        static MOUNT_TEXT_SCALE: std::cell::Cell<Option<f64>> = const { std::cell::Cell::new(None) };
7341    }
7342
7343    /// A change of the reader's font size recreates the activity
7344    /// (`DayActivity.onConfigurationChanged`), so the views come back at the new size. What lives above the
7345    /// tree does not: a `day::text_scale()` reader in the app's root scope, or a
7346    /// `max_text_scale` cap's font binding. When this mount's scale differs from the last one,
7347    /// tell day-core (`note_text_size_changed`), as UIKit does from its content-size
7348    /// notification.
7349    fn note_text_scale_of_mount() {
7350        let now = day_core::text_scale_of(Font::Body);
7351        let before = MOUNT_TEXT_SCALE.with(|c| c.replace(Some(now)));
7352        if let Some(b) = before.filter(|b| (b - now).abs() > 1e-6) {
7353            log::info!("day-toolkit-material: text scale {b:.2} -> {now:.2}, re-notifying");
7354            day_core::note_text_size_changed();
7355        }
7356    }
7357
7358    /// Navigation persistence backed by the Activity's saved instance state (docs/navigation.md).
7359    /// The map lives on the Java side (`DayBridge.navState`) because that is where the platform
7360    /// hands it out and takes it back: `DayActivity` restores it in `onCreate` before native
7361    /// starts, and writes it into the outgoing Bundle in `onSaveInstanceState`. Its lifetime is
7362    /// the task's: a process the system reclaims comes back on the page the user left, while a
7363    /// cold launch, or a task the user swiped off Recents, starts clean.
7364    struct InstanceNavStore;
7365
7366    impl day_core::NavStore for InstanceNavStore {
7367        fn load(&self, key: &str) -> Option<String> {
7368            if !vm_ready() {
7369                return None;
7370            }
7371            with_env(|env| {
7372                let k = jstr(env, key);
7373                java_string(env, |env| DayBridge::navLoad(env, &k))
7374            })
7375        }
7376
7377        fn save(&self, key: &str, value: &str) {
7378            if !vm_ready() {
7379                return;
7380            }
7381            with_env(|env| {
7382                let k = jstr(env, key);
7383                let v = jstr(env, value);
7384                let _ = java_in(env, |env| DayBridge::navSave(env, &k, &v));
7385            });
7386        }
7387    }
7388
7389    impl Platform for Material {
7390        const TARGET: &'static str = "android-material";
7391        const TOOLKIT: &'static str = "material";
7392        // The host owns the loop: `run` hands back at once, and DidExit is its last callback.
7393        const RUN_ENDS_APP: bool = false;
7394
7395        fn run(self, _options: WindowOptions, ready: Box<dyn FnOnce(Self, AHandle, Size)>) {
7396            // The ActivityThread owns the loop; init() already registered the root.
7397            let (root, size) = ROOT
7398                .with(|r| r.borrow_mut().take())
7399                .expect("day-toolkit-material: init() not called");
7400            // Navigation restore is the platform's own instance-state contract here, not an app
7401            // opt-in (docs/navigation.md): every Android app is expected to come back where the
7402            // user left it after the system reclaims its process. Installed before `ready` builds
7403            // the tree, so the first build of a `.restore(key)` surface reads it; an app that
7404            // installs its own store later still replaces this one.
7405            day_core::set_nav_store(std::rc::Rc::new(InstanceNavStore));
7406            ready(self, root, size);
7407        }
7408
7409        fn locale_hints(&self) -> Vec<String> {
7410            // The device's ordered language preference, which is the ambient locale Day
7411            // negotiates its catalogs against (§12.2, docs/localization.md). Comma-joined on the
7412            // Java side because a `String[]` return would need array marshaling for a list that
7413            // is never more than a handful of tags.
7414            if !vm_ready() {
7415                return Vec::new();
7416            }
7417            let joined = with_env(|env| {
7418                let obj = DayBridge::localeTags(env).ok()?;
7419                if obj.is_null() {
7420                    return None;
7421                }
7422                string_of(env, &obj).ok()
7423            });
7424            joined
7425                .unwrap_or_default()
7426                .split(',')
7427                .map(str::trim)
7428                .filter(|t| !t.is_empty())
7429                .map(str::to_string)
7430                .collect()
7431        }
7432
7433        fn post(f: Box<dyn FnOnce() + Send>) {
7434            let token = Box::into_raw(Box::new(f)) as i64;
7435            // The binding loads DayBridge through the app class loader, so this works from the
7436            // native-spawned threads that see only the system loader.
7437            bridge(|env| DayBridge::postMain(env, token));
7438        }
7439
7440        fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
7441            // The timer door behind `day::sleep` (docs/async.md): the main `Handler`'s
7442            // `postDelayed`, which hands the token back through `nativeRunPosted` exactly like
7443            // `postMain`. No helper thread; the delay travels as a `long`, whole.
7444            let token = Box::into_raw(Box::new(f)) as i64;
7445            bridge(|env| DayBridge::postMainDelayed(env, token, i64::from(ms)));
7446        }
7447    }
7448}