Skip to main content

bhoo/systems/android/xml/
mod.rs

1//! Runtime for the deliberately limited, build-time Android XML importer.
2use crate::*;
3mod relative_layout;
4use std::collections::HashMap;
5use unicode_segmentation::UnicodeSegmentation;
6use unicode_linebreak::{linebreaks, BreakOpportunity};
7#[derive(Clone, Copy)]
8pub enum Kind {
9    Linear,
10    Frame,
11    MediaController,
12    VideoView,
13    Relative,
14    ConstraintLayout,
15    Grid,
16    Table,
17    TableRow,
18    Absolute,
19    ViewAnimator,
20    ViewSwitcher,
21    TextSwitcher,
22    ImageSwitcher,
23    ViewFlipper,
24    AdapterViewFlipper,
25    StackView,
26    Gallery,
27    TabWidget,
28    TabHost,
29    DialerFilter,
30    SlidingDrawer,
31    Scroll,
32    HorizontalScroll,
33    Text,
34    Chronometer,
35    TextClock,
36    AnalogClock,
37    CheckedText,
38    Button,
39    CheckBox,
40    RadioButton,
41    RadioGroup,
42    Switch,
43    SeekBar,
44    ProgressBar,
45    RatingBar,
46    ToggleButton,
47    Icon,
48    Zoom,
49    ZoomControls,
50    Image,
51    QuickContactBadge,
52    Edit,
53    View,
54    Space,
55    MaterialDivider,
56    MaterialCard,
57    Spinner,
58    ListView,
59    GridView,
60    ExpandableListView,
61    SearchView,
62    Toolbar,
63    ActionMenuView,
64    TimePicker,
65    NumberPicker,
66    DatePicker,
67    CalendarView,
68    AutoComplete,
69    MultiAutoComplete,
70}
71#[derive(Clone, Copy)]
72pub enum Size {
73    Match,
74    Wrap,
75    Dp(f32),
76}
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Visibility {
79    Visible,
80    Invisible,
81    Gone,
82}
83/// Visual theme preset for Android XML rendering.
84/// `Bhoo` (default) preserves Bhoo's native dark theme and existing behavior.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
86pub enum AndroidTheme {
87    #[default]
88    Bhoo,
89    MaterialLight,
90    MaterialDark,
91    Material3Light,
92    Material3Dark,
93}
94impl AndroidTheme {
95    /// Active Android window background color for themes other than `Bhoo`.
96    pub fn window_background(self) -> Option<Color> {
97        match self {
98            Self::Bhoo => None,
99            Self::MaterialLight => Some(Color(0xFA, 0xFA, 0xFA, 255)),
100            Self::MaterialDark => Some(Color(0x30, 0x30, 0x30, 255)),
101            Self::Material3Light => Some(Color(0xFE, 0xF7, 0xFF, 255)),
102            Self::Material3Dark => Some(Color(0x14, 0x12, 0x18, 255)),
103        }
104    }
105    /// Default Toolbar surface color for themes other than `Bhoo`.
106    fn toolbar_surface(self) -> Option<Color> {
107        match self {
108            Self::Bhoo => None,
109            Self::MaterialLight => Some(Color(0xF5, 0xF5, 0xF5, 255)),
110            Self::MaterialDark => Some(Color(0x21, 0x21, 0x21, 255)),
111            Self::Material3Light => Some(Color(0xFE, 0xF7, 0xFF, 255)),
112            Self::Material3Dark => Some(Color(0x14, 0x12, 0x18, 255)),
113        }
114    }
115    /// Line-height multiplier relative to scaled font size.
116    /// `Bhoo` keeps 1.5x; Android Material themes match AOSP Roboto `includeFontPadding=true` (~1.34x).
117    fn text_line_height_factor(self) -> f32 {
118        match self {
119            Self::Bhoo => 1.5,
120            Self::MaterialLight
121            | Self::MaterialDark
122            | Self::Material3Light
123            | Self::Material3Dark => 1.34,
124        }
125    }
126    /// Map an Android Material / Material 3 theme to a matching `bhoo::Theme`
127    /// using pinned AOSP `themes_material.xml` and `material-android` tokens.
128    fn bhoo_theme(self) -> Option<Theme> {
129        match self {
130            Self::Bhoo => None,
131            Self::MaterialLight => Some(Theme {
132                background: Color(0xFA, 0xFA, 0xFA, 255),
133                text: Color(0x00, 0x00, 0x00, 0xDE),
134                control: Color(0xD6, 0xD7, 0xD7, 255),
135                hovered: Color(0xEA, 0xEA, 0xEA, 255),
136                pressed: Color(0xC2, 0xC2, 0xC2, 255),
137                radius: 2.0,
138                primary: Color(0x00, 0x96, 0x88, 255),
139                on_primary: Color(0xFF, 0xFF, 0xFF, 255),
140                secondary: Color(0x00, 0x79, 0x6B, 255),
141                outline: Color(0x00, 0x00, 0x00, 0x8A),
142                error: Color(0xD3, 0x2F, 0x2F, 255),
143                on_error: Color(0xFF, 0xFF, 0xFF, 255),
144                on_secondary: Color(0xFF, 0xFF, 0xFF, 255),
145                secondary_container: Color(0xB2, 0xDF, 0xDB, 255),
146                on_secondary_container: Color(0x00, 0x4D, 0x40, 255),
147                surface_low: Color(0xF5, 0xF5, 0xF5, 255),
148                surface_high: Color(0xFF, 0xFF, 0xFF, 255),
149                surface_highest: Color(0xE0, 0xE0, 0xE0, 255),
150                outline_variant: Color(0x00, 0x00, 0x00, 0x1F),
151                primary_container: Color(0xB2, 0xDF, 0xDB, 255),
152                on_primary_container: Color(0x00, 0x4D, 0x40, 255),
153                tertiary_container: Color(0xE0, 0xF2, 0xF1, 255),
154                on_tertiary_container: Color(0x00, 0x4D, 0x40, 255),
155                inverse_surface: Color(0x30, 0x30, 0x30, 255),
156                inverse_on_surface: Color(0xFF, 0xFF, 0xFF, 255),
157                inverse_primary: Color(0x80, 0xCB, 0xC4, 255),
158                on_surface_variant: Color(0x00, 0x00, 0x00, 0x8A),
159                surface_variant: Color(0xCC, 0xCC, 0xCC, 255),
160            }),
161            Self::MaterialDark => Some(Theme {
162                background: Color(0x30, 0x30, 0x30, 255),
163                text: Color(0xFF, 0xFF, 0xFF, 255),
164                control: Color(0x5A, 0x59, 0x5B, 255),
165                hovered: Color(0x6B, 0x6A, 0x6C, 255),
166                pressed: Color(0x48, 0x47, 0x49, 255),
167                radius: 2.0,
168                primary: Color(0x80, 0xCB, 0xC4, 255),
169                on_primary: Color(0x00, 0x00, 0x00, 255),
170                secondary: Color(0x4D, 0xB6, 0xAC, 255),
171                outline: Color(0xFF, 0xFF, 0xFF, 0xB3),
172                error: Color(0xFF, 0x70, 0x43, 255),
173                on_error: Color(0x00, 0x00, 0x00, 255),
174                on_secondary: Color(0x00, 0x00, 0x00, 255),
175                secondary_container: Color(0x00, 0x4D, 0x40, 255),
176                on_secondary_container: Color(0xB2, 0xDF, 0xDB, 255),
177                surface_low: Color(0x21, 0x21, 0x21, 255),
178                surface_high: Color(0x42, 0x42, 0x42, 255),
179                surface_highest: Color(0x55, 0x55, 0x55, 255),
180                outline_variant: Color(0xFF, 0xFF, 0xFF, 0x1F),
181                primary_container: Color(0x00, 0x4D, 0x40, 255),
182                on_primary_container: Color(0xB2, 0xDF, 0xDB, 255),
183                tertiary_container: Color(0x00, 0x4D, 0x40, 255),
184                on_tertiary_container: Color(0xB2, 0xDF, 0xDB, 255),
185                inverse_surface: Color(0xFA, 0xFA, 0xFA, 255),
186                inverse_on_surface: Color(0x00, 0x00, 0x00, 0xDE),
187                inverse_primary: Color(0x00, 0x96, 0x88, 255),
188                on_surface_variant: Color(0xFF, 0xFF, 0xFF, 0xB3),
189                surface_variant: Color(0x55, 0x55, 0x55, 255),
190            }),
191            Self::Material3Light => Some(Theme {
192                background: Color(0xFE, 0xF7, 0xFF, 255),
193                text: Color(0x1D, 0x1B, 0x20, 255),
194                control: Color(0xF3, 0xED, 0xF7, 255),
195                hovered: Color(0xEC, 0xE6, 0xF0, 255),
196                pressed: Color(0xE6, 0xE0, 0xE9, 255),
197                radius: 12.0,
198                primary: Color(0x67, 0x50, 0xA4, 255),
199                on_primary: Color(0xFF, 0xFF, 0xFF, 255),
200                secondary: Color(0x62, 0x5B, 0x71, 255),
201                outline: Color(0x79, 0x74, 0x7E, 255),
202                error: Color(0xB3, 0x26, 0x1E, 255),
203                on_error: Color(0xFF, 0xFF, 0xFF, 255),
204                on_secondary: Color(0xFF, 0xFF, 0xFF, 255),
205                secondary_container: Color(0xE8, 0xDE, 0xF8, 255),
206                on_secondary_container: Color(0x1D, 0x19, 0x2B, 255),
207                surface_low: Color(0xF7, 0xF2, 0xFA, 255),
208                surface_high: Color(0xEC, 0xE6, 0xF0, 255),
209                surface_highest: Color(0xE6, 0xE0, 0xE9, 255),
210                outline_variant: Color(0xCA, 0xC4, 0xD0, 255),
211                primary_container: Color(0xEA, 0xDD, 0xFF, 255),
212                on_primary_container: Color(0x21, 0x00, 0x5D, 255),
213                tertiary_container: Color(0xFF, 0xD8, 0xE4, 255),
214                on_tertiary_container: Color(0x31, 0x11, 0x1D, 255),
215                inverse_surface: Color(0x32, 0x2F, 0x35, 255),
216                inverse_on_surface: Color(0xF5, 0xEF, 0xF7, 255),
217                inverse_primary: Color(0xD0, 0xBC, 0xFF, 255),
218                on_surface_variant: Color(0x49, 0x45, 0x4F, 255),
219                surface_variant: Color(0xE7, 0xE0, 0xEC, 255),
220            }),
221            Self::Material3Dark => Some(Theme {
222                background: Color(0x14, 0x12, 0x18, 255),
223                text: Color(0xE6, 0xE0, 0xE9, 255),
224                control: Color(0x21, 0x1F, 0x26, 255),
225                hovered: Color(0x2B, 0x29, 0x30, 255),
226                pressed: Color(0x36, 0x34, 0x3B, 255),
227                radius: 12.0,
228                primary: Color(0xD0, 0xBC, 0xFF, 255),
229                on_primary: Color(0x38, 0x1E, 0x72, 255),
230                secondary: Color(0xCC, 0xC2, 0xDC, 255),
231                outline: Color(0x93, 0x8F, 0x99, 255),
232                error: Color(0xF2, 0xB8, 0xB5, 255),
233                on_error: Color(0x60, 0x14, 0x10, 255),
234                on_secondary: Color(0x33, 0x2D, 0x41, 255),
235                secondary_container: Color(0x4A, 0x44, 0x58, 255),
236                on_secondary_container: Color(0xE8, 0xDE, 0xF8, 255),
237                surface_low: Color(0x1D, 0x1B, 0x20, 255),
238                surface_high: Color(0x2B, 0x29, 0x30, 255),
239                surface_highest: Color(0x36, 0x34, 0x3B, 255),
240                outline_variant: Color(0x49, 0x45, 0x4F, 255),
241                primary_container: Color(0x4F, 0x37, 0x8B, 255),
242                on_primary_container: Color(0xEA, 0xDD, 0xFF, 255),
243                tertiary_container: Color(0x63, 0x3B, 0x48, 255),
244                on_tertiary_container: Color(0xFF, 0xD8, 0xE4, 255),
245                inverse_surface: Color(0xE6, 0xE0, 0xE9, 255),
246                inverse_on_surface: Color(0x32, 0x2F, 0x35, 255),
247                inverse_primary: Color(0x67, 0x50, 0xA4, 255),
248                on_surface_variant: Color(0xCA, 0xC4, 0xD0, 255),
249                surface_variant: Color(0x49, 0x45, 0x4F, 255),
250            }),
251        }
252    }
253}
254/// Map an unscaled Android elevation in dp to a discrete Material elevation level.
255fn elevation_level_from_dp(dp: f32) -> u8 {
256    if dp <= 0.0 {
257        0
258    } else if dp <= 1.0 {
259        1
260    } else if dp <= 3.0 {
261        2
262    } else if dp <= 6.0 {
263        3
264    } else if dp <= 8.0 {
265        4
266    } else {
267        5
268    }
269}
270/// Paint a discrete Material elevation shadow with geometry scaled by `density`.
271fn paint_elevation_level(f: &mut Frame<'_>, bounds: Rect, radius: f32, level: u8, density: f32) {
272    paint_elevation_level_alpha(f, bounds, radius, level, density, 1.0);
273}
274/// Paint a discrete Material elevation shadow with alpha modulated by `alpha_scale`.
275fn paint_elevation_level_alpha(
276    f: &mut Frame<'_>,
277    bounds: Rect,
278    radius: f32,
279    level: u8,
280    density: f32,
281    alpha_scale: f32,
282) {
283    let scale = alpha_scale.clamp(0.0, 1.0);
284    if scale <= 0.001 || level == 0 {
285        return;
286    }
287    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
288    let black = Color(0, 0, 0, 255);
289    let specs = if level >= 6 {
290        [
291            (0.0, 3.0, 5.0, -1.0, 0.2),
292            (0.0, 6.0, 10.0, 0.0, 0.14),
293            (0.0, 1.0, 18.0, 0.0, 0.12),
294        ]
295    } else if level <= 1 {
296        [
297            (0.0, 2.0, 1.0, -1.0, 0.2),
298            (0.0, 1.0, 1.0, 0.0, 0.14),
299            (0.0, 1.0, 3.0, 0.0, 0.12),
300        ]
301    } else {
302        [
303            (0.0, 3.0, 1.0, -2.0, 0.2),
304            (0.0, 2.0, 2.0, 0.0, 0.14),
305            (0.0, 1.0, 5.0, 0.0, 0.12),
306        ]
307    };
308    for (x, y, blur, spread, alpha) in specs {
309        f.shadow(bounds, radius, [x * d, y * d], blur * d, spread * d, black.opacity(alpha * scale));
310    }
311}
312/// Paint a continuous Android elevation (in unscaled dp) with shadow geometry scaled by `density`.
313fn paint_elevation_dp(f: &mut Frame<'_>, bounds: Rect, radius: f32, dp: f32, density: f32) {
314    if !dp.is_finite() || dp <= 0.0 {
315        return;
316    }
317    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
318    const LOW: [[f32; 5]; 3] = [[0., 2., 1., -1., 0.2], [0., 1., 1., 0., 0.14], [0., 1., 3., 0., 0.12]];
319    const MID: [[f32; 5]; 3] = [[0., 3., 1., -2., 0.2], [0., 2., 2., 0., 0.14], [0., 1., 5., 0., 0.12]];
320    const HIGH: [[f32; 5]; 3] = [[0., 3., 5., -1., 0.2], [0., 6., 10., 0., 0.14], [0., 1., 18., 0., 0.12]];
321    let (a, b_spec, t) = if dp <= 1.0 {
322        (LOW, LOW, 0.0)
323    } else if dp <= 2.0 {
324        (LOW, MID, dp - 1.0)
325    } else {
326        (MID, HIGH, ((dp - 2.0) / 4.0).min(1.0))
327    };
328    let scale = (if dp > 6.0 { (dp / 6.0).sqrt().min(2.0) } else { 1.0 }) * d;
329    for i in 0..3 {
330        let p = std::array::from_fn::<_, 5, _>(|j| a[i][j] + (b_spec[i][j] - a[i][j]) * t);
331        f.shadow(
332            bounds,
333            radius,
334            [p[0] * scale, p[1] * scale],
335            p[2] * scale,
336            p[3] * scale,
337            Color(0, 0, 0, 255).opacity(p[4] * dp.min(1.0)),
338        );
339    }
340}
341/// Subtle 2dp resting shadow for AOSP `Widget.Material.Button` (`btn_default_material`).
342/// Scaled by `density` to match Android's ~2px top / ~3px bottom / <=4px side halo (~9-12% peak alpha)
343/// without overflowing the 4dp horizontal button inset.
344fn paint_material_button_shadow(f: &mut Frame<'_>, bounds: Rect, radius: f32, density: f32) {
345    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
346    let black = Color(0, 0, 0, 255);
347    f.shadow(bounds, radius, [0.0, 0.25 * d], 2.8 * d, 0.0, black.opacity(0.07));
348    f.shadow(bounds, radius, [0.0, 1.0 * d], 2.0 * d, 0.0, black.opacity(0.07));
349}
350/// A ColorStateList entry: enabled, pressed, focused, selected, activated,
351/// hovered and checked are encoded in bits 0 through 6 respectively.
352#[derive(Clone, Copy)]
353pub struct TintState { pub required:u8, pub forbidden:u8, pub color:Color }
354/// One RelativeLayout rule; sibling anchors are Android XML IDs.
355#[derive(Clone, Copy)]
356pub struct RelativeRule { pub kind:u16, pub anchor:&'static str }
357/// RelativeRule kind for `android:elevation` in dp (e.g. `"4"`).
358pub const RULE_ELEVATION: u16 = 193;
359/// RelativeRule kind for `android:backgroundTint` as `"r,g,b,a"` (e.g. `"255,0,0,255"`).
360pub const RULE_BACKGROUND_TINT: u16 = 194;
361/// RelativeRule kind for `android:textAlignment` (`"start"`, `"center"`, `"end"`, `"left"`, `"right"`).
362pub const RULE_TEXT_ALIGNMENT: u16 = 195;
363/// ConstraintLayout `app:layout_constraintStart_toStartOf` (`"parent"` or sibling XML ID).
364pub const RULE_CONSTRAINT_START_TO_START: u16 = 196;
365/// ConstraintLayout `app:layout_constraintStart_toEndOf` (`"parent"` or sibling XML ID).
366pub const RULE_CONSTRAINT_START_TO_END: u16 = 197;
367/// ConstraintLayout `app:layout_constraintEnd_toEndOf` (`"parent"` or sibling XML ID).
368pub const RULE_CONSTRAINT_END_TO_END: u16 = 198;
369/// ConstraintLayout `app:layout_constraintEnd_toStartOf` (`"parent"` or sibling XML ID).
370pub const RULE_CONSTRAINT_END_TO_START: u16 = 199;
371/// ConstraintLayout `app:layout_constraintTop_toTopOf` (`"parent"` or sibling XML ID).
372pub const RULE_CONSTRAINT_TOP_TO_TOP: u16 = 200;
373/// ConstraintLayout `app:layout_constraintTop_toBottomOf` (`"parent"` or sibling XML ID).
374pub const RULE_CONSTRAINT_TOP_TO_BOTTOM: u16 = 201;
375/// ConstraintLayout `app:layout_constraintBottom_toBottomOf` (`"parent"` or sibling XML ID).
376pub const RULE_CONSTRAINT_BOTTOM_TO_BOTTOM: u16 = 202;
377/// ConstraintLayout `app:layout_constraintBottom_toTopOf` (`"parent"` or sibling XML ID).
378pub const RULE_CONSTRAINT_BOTTOM_TO_TOP: u16 = 203;
379/// ConstraintLayout `app:layout_constraintHorizontal_bias` (float in `0.0..=1.0`, default `0.5`).
380pub const RULE_CONSTRAINT_HORIZONTAL_BIAS: u16 = 204;
381/// ConstraintLayout `app:layout_constraintVertical_bias` (float in `0.0..=1.0`, default `0.5`).
382pub const RULE_CONSTRAINT_VERTICAL_BIAS: u16 = 205;
383/// Per-corner radii `"tl,tr,br,bl"` in dp for asymmetric rounded rectangles.
384pub const RULE_CORNER_RADII: u16 = 206;
385/// Gradient background (`linear` comma/pipe, `radial|<cx>,<cy>,<radius_dp>|<start>|<center>|<end>`, or `sweep|<cx>,<cy>|<start>|<center>|<end>`).
386pub const RULE_GRADIENT: u16 = 207;
387/// Stacked layer-list / inset drawable layer (repeatable in draw order): `"l,t,r,b|radius|fill_r,g,b,a|stroke_w,sr,sg,sb,sa"`.
388pub const RULE_DRAWABLE_LAYER: u16 = 208;
389/// Custom ripple color and optional unbounded mask: `"r,g,b,a"` or `"r,g,b,a|unbounded"`.
390pub const RULE_RIPPLE_COLOR: u16 = 209;
391/// ConstraintLayout Guideline orientation (`"vertical"` or `"horizontal"`).
392pub const RULE_GUIDE_ORIENTATION: u16 = 210;
393/// ConstraintLayout Guideline begin offset in dp.
394pub const RULE_GUIDE_BEGIN: u16 = 211;
395/// ConstraintLayout Guideline end offset in dp.
396pub const RULE_GUIDE_END: u16 = 212;
397/// ConstraintLayout Guideline percent offset (`0.0..=1.0`).
398pub const RULE_GUIDE_PERCENT: u16 = 213;
399/// ConstraintLayout horizontal chain style (`"spread"`, `"spread_inside"`, `"packed"`).
400pub const RULE_CHAIN_STYLE_H: u16 = 214;
401/// ConstraintLayout vertical chain style (`"spread"`, `"spread_inside"`, `"packed"`).
402pub const RULE_CHAIN_STYLE_V: u16 = 215;
403/// ConstraintLayout horizontal chain weight (positive float).
404pub const RULE_CONSTRAINT_H_WEIGHT: u16 = 216;
405/// ConstraintLayout vertical chain weight (positive float).
406pub const RULE_CONSTRAINT_V_WEIGHT: u16 = 217;
407/// Explicit override for `android:textAllCaps` (`"true"` or `"false"`), allowing
408/// buttons under Material themes to opt out of default uppercase styling.
409pub const RULE_TEXT_ALL_CAPS: u16 = 218;
410/// ConstraintLayout `app:layout_constraintDimensionRatio` (`"16:9"`, `"H,16:9"`, `"W,4:3"`, `"1.5"`).
411pub const RULE_CONSTRAINT_DIMENSION_RATIO: u16 = 219;
412/// ConstraintLayout `app:layout_constraintWidth_percent` (`0.0..=1.0`).
413pub const RULE_CONSTRAINT_WIDTH_PERCENT: u16 = 220;
414/// ConstraintLayout `app:layout_constraintHeight_percent` (`0.0..=1.0`).
415pub const RULE_CONSTRAINT_HEIGHT_PERCENT: u16 = 221;
416/// ConstraintLayout `app:layout_constraintBaseline_toBaselineOf` (sibling XML ID).
417pub const RULE_CONSTRAINT_BASELINE_TO_BASELINE: u16 = 222;
418/// ConstraintLayout gone margins `"l,t,r,b,s,e"` (6-value), `"l,t,r,b,s,e,baseline"` (7-value),
419/// or `"s,t,e,b,baseline"` (5-value) in dp (`< 0.0` or empty means unset).
420pub const RULE_CONSTRAINT_GONE_MARGINS: u16 = 223;
421/// Alias for `RULE_CONSTRAINT_GONE_MARGINS` (`223`).
422pub const RULE_CONSTRAINT_GONE_MARGIN: u16 = RULE_CONSTRAINT_GONE_MARGINS;
423/// ConstraintLayout Barrier `"<dir>:<id1>,<id2>,..."` or `"<dir>|<id1>,<id2>,...|<margin_dp>|<allows_gone:0|1>"` (`start|end|left|right|top|bottom`).
424pub const RULE_BARRIER: u16 = 224;
425/// Alias for `RULE_BARRIER` (`224`).
426pub const RULE_CONSTRAINT_BARRIER: u16 = RULE_BARRIER;
427/// ConstraintLayout Group `"<id1>,<id2>,..."` (propagates `Gone`/`Invisible` to referenced siblings).
428pub const RULE_GROUP_REFS: u16 = 225;
429/// CoordinatorLayout scrolling view behavior (`app:layout_behavior` scrolling below top app bar).
430pub const RULE_COORDINATOR_SCROLL_BEHAVIOR: u16 = 226;
431/// CoordinatorLayout anchor placement `"<target_id>:<gravity_tokens>"` (e.g. `"appbar:bottom|end"`).
432pub const RULE_COORDINATOR_ANCHOR: u16 = 227;
433/// Material TextInputLayout box chrome `"<mode>|<corner_dp>|<stroke_rgba>|<hint>|<helper>|<error_enabled>|<end_icon>"`.
434pub const RULE_TEXT_INPUT_BOX: u16 = 228;
435/// MaterialButton / Button visual variant (`"filled"`, `"outlined"`, `"tonal"`, `"text"`, `"elevated"`).
436pub const RULE_BUTTON_VARIANT: u16 = 229;
437/// Material 3 Chip style `"<kind>|<close_visible>"` (e.g. `"filter|1"`).
438pub const RULE_CHIP_STYLE: u16 = 230;
439/// Stateful drawable layer (repeatable): `"<req_mask>,<forbid_mask>|<l,t,r,b>|<radius>|<fill_r,g,b,a>|<stroke_w,sr,sg,sb,sa>"`.
440pub const RULE_STATEFUL_DRAWABLE_LAYER: u16 = 231;
441/// ConstraintLayout Flow helper:
442/// - legacy: `"<orient:0|1>|<wrap:none|chain|aligned>|<h_gap_dp>|<v_gap_dp>|<max_wrap>|<id1>,<id2>,..."`
443/// - compact/extended: `"<orient:h|v>|<wrap:none|chain|aligned>|<hgap_dp>,<vgap_dp>|<id1>,<id2>,...[|<hstyle>,<vstyle>,<hbias>,<vbias>,<halign>,<valign>,<max_wrap>]"`.
444pub const RULE_FLOW: u16 = 232;
445/// ConstraintLayout circular positioning `"<target_id>,<radius>,<angle_deg>"`; radius accepts dp, px or sp (bare values are dp), and 0 degrees is 12 o'clock clockwise.
446pub const RULE_CONSTRAINT_CIRCLE: u16 = 233;
447/// Clips child draw commands inside the view's rounded outline bounds (`"true"`).
448pub const RULE_CLIP_TO_OUTLINE: u16 = 234;
449/// Explicit text line height in dp/sp (positive float).
450pub const RULE_LINE_HEIGHT: u16 = 235;
451/// Android `includeFontPadding` override (`"true"` or `"false"`).
452pub const RULE_INCLUDE_FONT_PADDING: u16 = 236;
453/// Material 3 navigation container `"<kind:bar|rail|drawer>|<label_mode:auto|labeled|selected|unlabeled>"`.
454pub const RULE_NAV_BAR: u16 = 237;
455/// Material 3 navigation item (repeatable) `"<id>|<title>|<icon_name_or_empty>"`.
456pub const RULE_NAV_ITEM: u16 = 238;
457/// Material 3 SearchBar hint text `"<hint>"` on `Kind::SearchView`.
458pub const RULE_SEARCH_BAR: u16 = 239;
459/// MaterialButtonToggleGroup `"<single_selection:0|1>|<selection_required:0|1>|<checked_id>"`.
460pub const RULE_TOGGLE_GROUP: u16 = 240;
461/// Material 3 ExtendedFloatingActionButton `"<extended:0|1>"` on `Kind::Button`.
462pub const RULE_EXTENDED_FAB: u16 = 242;
463/// Material 3 BottomAppBar `"<fab_alignment:center|end>"` on `Kind::Toolbar`.
464pub const RULE_BOTTOM_APP_BAR: u16 = 243;
465/// Material 3 navigation destination badge (repeatable) `"<item_id>:<badge_text>"`.
466pub const RULE_NAV_BADGE: u16 = 244;
467/// Material 3 CollapsingToolbarLayout `"<title>|<expanded_h_dp>|<scrim_rgba>"` on `Kind::Frame`.
468pub const RULE_COLLAPSING_TOOLBAR: u16 = 245;
469/// AndroidX SwipeRefreshLayout container marker on `Kind::Frame`.
470pub const RULE_SWIPE_REFRESH: u16 = 246;
471/// AndroidX DrawerLayout container marker on `Kind::Frame`.
472pub const RULE_DRAWER_LAYOUT: u16 = 247;
473/// AndroidX ViewPager / ViewPager2 orientation `"<horizontal|vertical>"` on `Kind::ViewFlipper`.
474pub const RULE_VIEW_PAGER: u16 = 248;
475/// Material 3 RangeSlider initial two-thumb values `"<v0>,<v1>"` on `Kind::SeekBar`.
476pub const RULE_RANGE_SLIDER: u16 = 250;
477/// Static background bitmap/9-patch image `"<image_key>|<stretch_spec>"` (`stretch_spec` = `""` or `"sx0,sx1,...;sy0,sy1,..."`).
478pub const RULE_BACKGROUND_IMAGE: u16 = 251;
479/// Nine-patch stretch bands `"sx0,sx1,...;sy0,sy1,..."` (stripped image pixel coordinates, even count >= 2 per axis) on `ImageView`/`ImageButton`.
480pub const RULE_IMAGE_NINE_PATCH: u16 = 252;
481/// Stateful image `src` `<selector>` entry (repeatable in match order): `"<req_mask>,<forbid_mask>|<image_key>|<stretch_spec>"`.
482pub const RULE_STATEFUL_IMAGE_SRC: u16 = 253;
483/// Stateful background image `<selector>` entry (repeatable in match order): `"<req_mask>,<forbid_mask>|<image_key>|<stretch_spec>"`.
484pub const RULE_STATEFUL_BG_IMAGE: u16 = 254;
485/// RTL horizontal mirroring marker (`"true"`) from `android:autoMirrored="true"`.
486pub const RULE_AUTO_MIRRORED: u16 = 255;
487/// 2D view transform `"<tx_dp>,<ty_dp>,<sx>,<sy>,<rot_deg>,<px>,<py>"` (`px`/`py` `"center"`, `"<pct>%"`, or float dp).
488pub const RULE_VIEW_TRANSFORM: u16 = 256;
489/// Extended text styling `"<italic:0|1>|<family:sans|serif|mono>"`.
490pub const RULE_TEXT_STYLE_EXT: u16 = 257;
491/// Material tooltip text from `android:tooltipText`.
492pub const RULE_TOOLTIP_TEXT: u16 = 258;
493/// Material 3 BottomSheet behavior `"<peek_h_dp>|<hideable:0|1>|<fit_to_contents:0|1>|<half_ratio>|<skip_collapsed:0|1>"`.
494pub const RULE_BOTTOM_SHEET: u16 = 259;
495/// Material 3 BottomSheetDragHandleView pill marker (`""`).
496pub const RULE_DRAG_HANDLE: u16 = 260;
497/// Material 3 SideSheet behavior `"<edge:end|start>|<coplanar:0|1>"`.
498pub const RULE_SIDE_SHEET: u16 = 261;
499/// Material 3 Expressive LoadingIndicator `"<contained:0|1>"` on `Kind::ProgressBar`.
500pub const RULE_LOADING_INDICATOR: u16 = 262;
501/// Material 3 Expressive Wavy / flat-with-gap ProgressIndicator `"<wavelength_dp>|<amplitude_dp>|<wave_speed_dp>|<stop_size_dp>|<track_gap_dp>"` on `Kind::ProgressBar`.
502pub const RULE_WAVY_PROGRESS: u16 = 263;
503/// Material 3 AlertDialog container `"<icon_name_or_empty>"` on `Kind::Linear`.
504pub const RULE_ALERT_DIALOG: u16 = 264;
505/// Material 3 Snackbar container (`""`) on `Kind::Linear`.
506pub const RULE_SNACKBAR: u16 = 265;
507/// Material 3 TabLayout options `"<mode:fixed|scrollable>|<style:primary|secondary>|<indicator_rgba>"` on `Kind::TabWidget`.
508pub const RULE_TAB_OPTIONS: u16 = 266;
509/// Material 3 Slider / RangeSlider options `"<step_size>|<min_separation>|<label_behavior:floating|withinBounds|gone|visible>|<expressive:0|1>"` on `Kind::SeekBar`.
510pub const RULE_SLIDER_OPTIONS: u16 = 267;
511/// Material 3 TextInputLayout extensions `"<counter_enabled:0|1>|<counter_max>|<prefix>|<suffix>|<start_icon>"` on `Kind::Linear` with `RULE_TEXT_INPUT_BOX`.
512pub const RULE_TEXT_INPUT_EXT: u16 = 268;
513/// Material 3 ChipGroup wrap & selection `"<single_line:0|1>|<single_selection:0|1>|<h_spacing_dp>|<v_spacing_dp>"` on `Kind::Linear`.
514pub const RULE_CHIP_GROUP_WRAP: u16 = 269;
515/// Material 3 Expressive FloatingToolbar pill container (`""`) on `Kind::Linear`.
516pub const RULE_FLOATING_TOOLBAR: u16 = 270;
517/// Material 3 Expressive MaterialButtonGroup `"<spacing_dp>"` on `Kind::Linear`.
518pub const RULE_BUTTON_GROUP: u16 = 271;
519/// Material 3 Expressive MaterialSplitButton (`""`) on `Kind::Linear`.
520pub const RULE_SPLIT_BUTTON: u16 = 272;
521/// Material 3 Carousel MaskableFrameLayout item (`""`) on `Kind::Frame`.
522pub const RULE_CAROUSEL_ITEM: u16 = 273;
523/// Scale transition animation for incoming `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child:
524/// `"<from_sx>,<to_sx>,<from_sy>,<to_sy>|<px>,<py>|<duration_s>|<start_offset_s>|<linear:0|1>"`.
525pub const RULE_SCALE_IN: u16 = 274;
526/// Scale transition animation for outgoing `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child.
527pub const RULE_SCALE_OUT: u16 = 275;
528/// Rotate transition animation for incoming `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child:
529/// `"<from_deg>,<to_deg>|<px>,<py>|<duration_s>|<start_offset_s>|<linear:0|1>"`.
530pub const RULE_ROTATE_IN: u16 = 276;
531/// Rotate transition animation for outgoing `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child.
532pub const RULE_ROTATE_OUT: u16 = 277;
533/// Per-corner family `"<tl>,<tr_>,<br>,<bl>"` where each token is `"r"` (rounded) or `"c"` (cut/chamfered).
534pub const RULE_CORNER_FAMILY: u16 = 278;
535/// AppBarLayout dynamic `liftOnScroll`: `"1"` (auto-detect sibling scroll) or `"1|<target_xml_id>"`.
536pub const RULE_APP_BAR_LIFT_ON_SCROLL: u16 = 279;
537/// ConstraintLayout constrained wrap and min/max bounds `"<cw:0|1>,<ch:0|1>|<wmin_dp>,<wmax_dp>,<hmin_dp>,<hmax_dp>"`.
538pub const RULE_CONSTRAINT_SIZE_BOUNDS: u16 = 280;
539/// ConstraintLayout Layer helper `"<id1>,<id2>,..."` applying shared background, elevation, transform, and alpha.
540pub const RULE_CONSTRAINT_LAYER: u16 = 281;
541/// ConstraintLayout Placeholder helper `"<content_id>|<empty_vis:gone|invisible|visible>"`.
542pub const RULE_CONSTRAINT_PLACEHOLDER: u16 = 282;
543/// AppBarLayout child `app:layout_scrollFlags` comma-separated flags (`scroll`, `enterAlways`, `enterAlwaysCollapsed`, `exitUntilCollapsed`, `snap`).
544pub const RULE_APP_BAR_SCROLL_FLAGS: u16 = 284;
545/// Animated `<animation-list>` frame playback `"<oneshot:0|1>|<img_key_0>:<dur_ms_0>,<img_key_1>:<dur_ms_1>,..."`.
546pub const RULE_ANIMATION_LIST: u16 = 285;
547/// Dynamic wrapper drawables (`level-list`, `clip`, `rotate`, `scale`, `transition`) with optional `bg:`/`src:` prefix:
548/// - `"level|<min0>:<max0>:<img_key0>,<min1>:<max1>:<img_key1>,..."`
549/// - `"clip|<h|v>|<start|end|center|top|bottom>|<img_key>"`
550/// - `"rotate|<from_deg>,<to_deg>|<px>,<py>|<img_key>"`
551/// - `"scale|<sw_frac>,<sh_frac>|<center|start|end|top|bottom>|<img_key>"`
552/// - `"transition|<dur_ms>|<img_key_0>,<img_key_1>"`
553pub const RULE_DRAWABLE_DYNAMIC: u16 = 286;
554/// ConstraintLayout physical vs. logical horizontal pinning bitmask `"<bitmask_u8>"`:
555/// bit 0 (`1`) = left-edge (`196`/`197`) physical `Left`; bit 1 (`2`) = right-edge (`198`/`199`) physical `Right`;
556/// bit 2 (`4`) = bias (`204`) and left/right margins physical when both anchors are physical.
557pub const RULE_CONSTRAINT_PHYS_FLAGS: u16 = 287;
558/// Incoming `elevation` / `translationZ` object animator transition on `ViewAnimator`/`ViewSwitcher`/
559/// `TextSwitcher`/`ImageSwitcher`/`ViewFlipper`/`AdapterViewFlipper`:
560/// `"<from_dp>,<to_dp>|<dur_ms>|<offset_ms>|<interp>"`.
561pub const RULE_ELEVATION_IN: u16 = 288;
562/// Outgoing `elevation` / `translationZ` object animator transition on `ViewAnimator`/`ViewSwitcher`/
563/// `TextSwitcher`/`ImageSwitcher`/`ViewFlipper`/`AdapterViewFlipper`.
564pub const RULE_ELEVATION_OUT: u16 = 289;
565/// AppBarLayout extended options:
566/// - on `AppBarLayout`: `"lift_color=<r>,<g>,<b>,<a>"` (custom `liftOnScrollColor`)
567/// - on `AppBarLayout` direct scrolling child: `"effect=compress"` (`app:layout_scrollEffect="compress"`)
568pub const RULE_APP_BAR_EXT: u16 = 290;
569/// DrawerLayout lock mode (`"unlocked"`/`"0"`, `"locked_closed"`/`"1"`, `"locked_open"`/`"2"`, `"undefined"`/`"3"`).
570pub const RULE_DRAWER_LOCK_MODE: u16 = 291;
571/// ConstraintLayout Flow per-first/last-line chain style & bias overrides:
572/// `"<first_hstyle>,<last_hstyle>,<first_hbias>,<last_hbias>,<first_vstyle>,<last_vstyle>,<first_vbias>,<last_vbias>"`.
573pub const RULE_CONSTRAINT_FLOW_EXT: u16 = 292;
574/// `<animated-selector>` transition frame playback (repeatable, one per `<transition>`):
575/// `"<ctx:src|bg>:<from_mask>:<to_mask>:<rev:0|1>|<img_key_0>:<dur_ms_0>,..."`.
576pub const RULE_ANIMATED_SELECTOR: u16 = 293;
577/// ConstraintLayout `app:layout_constraintWidth_default` / `app:layout_constraintHeight_default`:
578/// `"<w_def:spread|wrap|percent>,<h_def:spread|wrap|percent>"`.
579pub const RULE_CONSTRAINT_DEFAULT_SIZE: u16 = 294;
580/// Timed `<animation-list>` frame playback on compound drawables, checkable button drawables,
581/// `SeekBar` tick marks, and `ExpandableListView` group indicators (repeatable):
582/// `"<slot:start|top|end|bottom|left|right|button|tick|indicator>:<oneshot:0|1>|<img_key_0>:<dur_ms_0>,..."`.
583pub const RULE_COMPOUND_ANIMATION_LIST: u16 = 295;
584/// Extended `TextView`/`Button` text layout options:
585/// `"<break:simple|high_quality|balanced>|<hyphen:none|normal|full>|<just:none|inter_word>|<auto_min_sp>,<auto_max_sp>,<auto_step_sp>"`.
586pub const RULE_TEXT_LAYOUT_EXT: u16 = 296;
587/// Material `BadgeDrawable` extended options (repeatable):
588/// `"<item_index|-1|self>|<gravity:top_end|top_start|bottom_end|bottom_start>|<max_chars>|<hoff_dp>,<voff_dp>"`.
589pub const RULE_MATERIAL_BADGE_EXT: u16 = 297;
590/// CollapsingToolbarLayout extended options:
591/// - on `CollapsingToolbarLayout`: `"<mode:scale|fade>|<max_lines>|<scrim_dur_ms>|<subtitle>"`
592/// - on `CollapsingToolbarLayout` direct children: `"collapse:<none|pin|parallax>:<mult>"`.
593pub const RULE_COLLAPSING_TOOLBAR_EXT: u16 = 298;
594/// Material 3 ExtendedFloatingActionButton extended options:
595/// `"<extended:0|1>|<collapsed_size_dp>|<strategy:auto|wrap_content|match_parent>"`.
596pub const RULE_EXTENDED_FAB_EXT: u16 = 299;
597/// Material BottomAppBar extended options:
598/// `"<align:center|end>|<anchor:cradle|embed>|<cradle_margin_dp>,<cradle_rad_dp>,<cradle_voff_dp>|<hide_on_scroll:0|1>"`.
599pub const RULE_BOTTOM_APP_BAR_EXT: u16 = 300;
600/// RecyclerView layout manager extended options on `Kind::ListView` / `Kind::GridView`:
601/// `"<mgr:linear|grid|staggered>|<orient:v|h>|<span_count>|<reverse:0|1>|<stack_end:0|1>"`.
602pub const RULE_RECYCLER_LAYOUT_EXT: u16 = 301;
603/// Material `SearchView` fullscreen/modal search overlay coupled to `SearchBar` on `Kind::Frame` / `Kind::Linear`:
604/// `"<anchor_bar_id>|<hint>|<hide_nav:0|1>|<use_drawer_arrow:0|1>"`.
605pub const RULE_SEARCH_VIEW_EXT: u16 = 302;
606/// AndroidX `SwipeRefreshLayout` extended options (paired with `RULE_SWIPE_REFRESH` on `Kind::Frame`):
607/// `"<bg_rgba>|<scheme_rgba_list>|<size:default|large>|<start_off_dp>,<end_off_dp>"`.
608pub const RULE_SWIPE_REFRESH_EXT: u16 = 303;
609/// Material 3 `CarouselLayoutManager` keyline focal sizing & snap scrolling on `Kind::ListView`/`Kind::GridView`/`Kind::HorizontalScroll`/`Kind::Linear`:
610/// `"<strategy:multi_browse|hero|uncontained|full_screen>|<spacing_dp>|<align:start|center>"`.
611pub const RULE_CAROUSEL_LAYOUT: u16 = 304;
612/// AndroidX `ViewPager` / `ViewPager2` extended options (paired with `RULE_VIEW_PAGER` on `Kind::ViewFlipper`):
613/// `"<orient:h|v>|<user_input:0|1>|<page_margin_dp>|<transformer:none|zoom_out|depth>"`.
614pub const RULE_VIEW_PAGER_EXT: u16 = 305;
615/// Extended `TextView` / `EditText` auto-link detection & styling:
616/// `"<mask:all|web|email|phone|none>|<link_rgba>|<clickable:0|1>"`.
617pub const RULE_TEXT_LINKS_SPANS: u16 = 306;
618/// Sampled `<animated-vector>` frame sequence playback (repeatable, one per `src` / `bg`):
619/// `"<ctx:src|bg>:<repeat:0|1>:<dur_ms>|<img_key_0>,<img_key_1>,..."`.
620pub const RULE_ANIMATED_VECTOR: u16 = 309;
621/// Static translation along the elevation axis, in dp.
622pub const RULE_TRANSLATION_Z: u16 = 310;
623/// Original logical and physical horizontal anchors, retained for runtime overrides.
624pub const RULE_CONSTRAINT_ANCHOR_SOURCES: u16 = 311;
625/// ConstraintLayout baseline aligned to a sibling's top or bottom edge.
626pub const RULE_CONSTRAINT_BASELINE_TO_TOP: u16 = 312;
627pub const RULE_CONSTRAINT_BASELINE_TO_BOTTOM: u16 = 313;
628/// Baseline anchor margin, with optional dp, px or sp suffix.
629pub const RULE_CONSTRAINT_BASELINE_MARGIN: u16 = 314;
630
631/// Use Android View.layout's integer edges for an imported MotionLayout.
632pub const RULE_MOTION_LAYOUT_PIXEL_BOUNDS: u16 = 315;
633/// DrawerLayout lock mode: unlocked (normal open/close, edge swipe, scrim dismiss).
634pub const DRAWER_LOCK_MODE_UNLOCKED: u8 = 0;
635/// DrawerLayout lock mode: locked closed (forces panel closed, blocks edge swipe-to-open).
636pub const DRAWER_LOCK_MODE_LOCKED_CLOSED: u8 = 1;
637/// DrawerLayout lock mode: locked open (forces panel open, blocks drag-to-close and scrim dismissal).
638pub const DRAWER_LOCK_MODE_LOCKED_OPEN: u8 = 2;
639/// DrawerLayout lock mode: undefined (behaves as unlocked).
640pub const DRAWER_LOCK_MODE_UNDEFINED: u8 = 3;
641/// Material BottomSheet/SideSheet expanded state (`BottomSheetBehavior.STATE_EXPANDED`).
642pub const SHEET_STATE_EXPANDED: u8 = 3;
643/// Material BottomSheet collapsed/peeking state (`BottomSheetBehavior.STATE_COLLAPSED`).
644pub const SHEET_STATE_COLLAPSED: u8 = 4;
645/// Material BottomSheet/SideSheet hidden state (`BottomSheetBehavior.STATE_HIDDEN`).
646pub const SHEET_STATE_HIDDEN: u8 = 5;
647/// Material BottomSheet half-expanded state (`BottomSheetBehavior.STATE_HALF_EXPANDED`).
648pub const SHEET_STATE_HALF_EXPANDED: u8 = 6;
649#[derive(Clone)]
650struct TilDropdownAnchor {
651    key: String,
652    til_key: String,
653    id: u64,
654    xml_id: &'static str,
655    bounds: Rect,
656    rtl: bool,
657}
658#[derive(Clone, Copy)]
659pub struct AnimationDelta { pub value: f32, pub mode: u8 }
660impl AnimationDelta { fn resolve(self, own:f32, parent:f32) -> f32 { self.value * match self.mode { 1 => own, 2 => parent, _ => 1.0 } } }
661#[derive(Clone, Copy)]
662pub struct TranslateAnimation { pub deltas: [AnimationDelta; 4], pub duration:f64, pub start_offset:f64, pub linear:bool, pub y_timing:Option<(f64,bool,f64)> }
663#[derive(Clone)]
664struct SpinnerAnchor { key:String, id:u64, bounds:Rect, xml_id:&'static str, dialog:bool, prompt:&'static str, rtl:bool, width:&'static str, offset_x:f32, offset_y:f32, padding:[f32;4] }
665impl TranslateAnimation {
666    fn sample(self, elapsed:f64, child:Rect, parent:Rect, object:bool) -> [f32;2] {
667        let progress = |duration:f64,linear:bool,offset:f64| { let t=if elapsed<offset {0.0} else if duration<=0.0 {1.0} else {((elapsed-offset)/duration).clamp(0.0,1.0) as f32}; if linear {t} else {(1.0-(std::f32::consts::PI*t).cos())*0.5} };
668        let tx=progress(self.duration,self.linear,self.start_offset);
669        let (yd,yl,yo)=self.y_timing.unwrap_or((self.duration,self.linear,self.start_offset));
670        let ty=progress(yd,yl,yo);
671        let [a,b,c,d] = self.deltas;
672        let mix = |x:f32,y:f32,t:f32| x+(y-x)*t;
673        [if object && elapsed<self.start_offset {0.0} else {mix(a.resolve(child.width,parent.width), b.resolve(child.width,parent.width),tx)},if object && elapsed<yo {0.0} else {mix(c.resolve(child.height,parent.height), d.resolve(child.height,parent.height),ty)}]
674    }
675    fn total_duration(self)->f64 { (self.start_offset+self.duration).max(self.y_timing.map_or(0.0,|timing|timing.0+timing.2)) }
676}
677#[derive(Clone, Copy)]
678pub struct AlphaAnimation { pub from: f32, pub to: f32, pub duration: f64, pub start_offset: f64, pub linear: bool }
679impl AlphaAnimation {
680    fn total_duration(self) -> f64 { self.start_offset + self.duration }
681    fn sample(self, elapsed: f64, object:bool) -> f32 {
682        if object && elapsed<self.start_offset {return 1.0;}
683        let t = if elapsed < self.start_offset { 0.0 } else if self.duration <= 0.0 { 1.0 } else { ((elapsed-self.start_offset) / self.duration).clamp(0.0, 1.0) as f32 };
684        let t = if self.linear { t } else { (1.0 - (std::f32::consts::PI * t).cos()) * 0.5 };
685        self.from + (self.to - self.from) * t
686    }
687}
688#[derive(Clone, Copy)]
689pub struct ViewTransition { current: usize, previous: usize, started: f64, active: bool }
690#[derive(Clone, Copy)]
691pub struct FlipperClock { running: bool, next: f64, epoch:u64, pause_generation:u64, visible:bool }
692#[derive(Clone, Copy)]
693pub struct ChronometerState { pub base:f64, pub running:bool }
694#[derive(Clone, Copy)]
695pub struct WallClock { pub unix_seconds:f64, pub offset_seconds:i32, pub is_24_hour:bool }
696#[derive(Clone, Copy, Debug)]
697pub struct ZoomControlsFade { from:f32, target_visible:bool, start:f64 }
698impl ZoomControlsFade {
699    fn value(self, now:f64) -> f32 {
700        let t=((now-self.start)/0.5).clamp(0.0,1.0) as f32;
701        let eased=(1.0-(std::f32::consts::PI*t).cos())*0.5;
702        self.from+(f32::from(self.target_visible)-self.from)*eased
703    }
704}
705#[derive(Clone, Copy)]
706pub struct Node {
707    pub kind: Kind,
708    pub id: &'static str,
709    pub width: Size,
710    pub height: Size,
711    pub min_width: f32,
712    pub min_height: f32,
713    pub horizontal: bool,
714    pub measure_all_children: bool,
715    /// 0 inherits, 1 is left-to-right, and 2 is right-to-left.
716    pub layout_direction: u8,
717    pub fill_viewport: bool,
718    /// Android ViewGroup clips children to its padding by default.
719    pub clip_to_padding_disabled: bool,
720    /// Android ViewGroup clips each child to its bounds by default.
721    pub clip_children_disabled: bool,
722    pub weight: f32,
723    /// Zero uses the sum of the visible child weights.
724    pub weight_sum: f32,
725    pub divider_color: Option<Color>,
726    pub divider_thickness: f32,
727    pub divider_flags: u8,
728    pub divider_padding: f32,
729    /// Physical left, top, right and bottom padding and optional relative overrides.
730    pub padding_edges: [f32; 4],
731    pub padding_explicit: [bool; 4],
732    pub background_padding: Option<[f32; 4]>,
733    pub background_min_size: [f32; 2],
734    pub padding_relative: [Option<f32>; 2],
735    /// Physical left, top, right and bottom margins.
736    pub margin: [f32; 4],
737    /// Optional start and end margins override the physical side in the current direction.
738    pub margin_relative: [Option<f32>; 2],
739    /// FrameLayout gravity: horizontal start/center/end/left/right, vertical top/center/bottom.
740    pub layout_gravity: [u8; 2],
741    /// Physical coordinates for children of deprecated AbsoluteLayout.
742    pub absolute_position: [f32; 2],
743    pub relative_rules: &'static [RelativeRule],
744    pub layout_gravity_explicit: bool,
745    pub content_gravity: [u8; 2],
746    pub text: &'static str,
747    pub hint: &'static str,
748    pub chrono_format: &'static str,
749    pub count_down: bool,
750    pub clock_12: &'static str,
751    pub clock_24: &'static str,
752    /// 0 text, 1 email, 2 telephone, 3 numeric, 4 password, 5 decimal.
753    pub input_type: u8,
754    pub text_on: &'static str,
755    pub text_off: &'static str,
756    pub text_size: f32,
757    /// Android letter spacing in em units.
758    pub letter_spacing_em: f32,
759    pub line_spacing_extra: f32,
760    pub line_spacing_multiplier: f32,
761    pub text_bold: bool,
762    pub text_all_caps: bool,
763    /// Zero means no explicit line limit.
764    pub max_lines: usize,
765    pub min_lines: usize,
766    pub ellipsize_end: bool,
767    /// 1 truncates at the start, 2 in the middle.
768    pub ellipsize_side: u8,
769    pub single_line: bool,
770    pub align: u8,
771    pub color: Option<Color>,
772    pub text_color_states: &'static [TintState],
773    pub background: Option<Color>,
774    /// Solid foreground painted over this view and its descendants.
775    pub foreground: Option<Color>,
776    /// Negative radius represents an oval foreground.
777    pub foreground_radius: f32,
778    pub foreground_size: [f32; 2],
779    pub foreground_padding: Option<[f32; 4]>,
780    /// Horizontal/vertical foreground gravity; 5 means fill.
781    pub foreground_gravity: [u8; 2],
782    pub foreground_excludes_padding: bool,
783    pub background_stroke: Option<Color>,
784    pub background_stroke_width: f32,
785    pub foreground_stroke: Option<Color>,
786    pub foreground_stroke_width: f32,
787    pub radius: f32,
788    pub clickable: bool,
789    pub icon: MaterialIcon,
790    pub image_src: &'static str,
791    /// Image scale mode encoded by the Android XML importer.
792    pub image_scale: u8,
793    /// Preserve drawable aspect ratio when a view dimension can wrap.
794    pub image_adjust_bounds: bool,
795    pub image_max_width: Option<f32>,
796    pub image_max_height: Option<f32>,
797    pub image_tint: Option<Color>,
798    pub image_tint_states: &'static [TintState],
799    /// 0 SRC_ATOP (XML default), 1 SRC_IN, 2 SRC_OVER, 3 MULTIPLY,
800    /// 4 SCREEN, 5 ADD.
801    pub image_tint_mode: u8,
802    /// Drawable opacity in the Android imageAlpha range.
803    pub image_alpha: u8,
804    /// Opacity applied to the view and its children.
805    pub view_alpha: f32,
806    pub image_builtin: bool,
807    pub enabled: bool,
808    pub checked: bool,
809    pub checked_button: &'static str,
810    pub min: f32,
811    pub max: f32,
812    pub progress: f32,
813    pub secondary_progress: f32,
814    pub indeterminate: bool,
815    pub num_stars: usize,
816    pub rating: f32,
817    pub step_size: f32,
818    pub indicator: bool,
819    pub mirror_for_rtl: bool,
820    pub animation_in: Option<AlphaAnimation>,
821    pub animation_out: Option<AlphaAnimation>,
822    pub translate_in: Option<TranslateAnimation>,
823    pub translate_out: Option<TranslateAnimation>,
824    pub auto_start: bool,
825    pub flip_interval: f64,
826    pub visibility: Visibility,
827    pub children: &'static [Node],
828}
829/// A vector drawable tint resolved against the current theme when painted.
830#[derive(Clone,Copy,Debug,PartialEq,Eq)]
831pub enum AndroidDrawableTint {Fixed(Color),ControlNormal}
832/// Contact information supplied by the embedding application.
833#[derive(Clone,Debug,PartialEq,Eq)]
834pub enum QuickContactTarget { Uri(String), Email(String), Phone(String) }
835/// A contact lookup delegated to the host. Resolve using its token.
836#[derive(Clone,Debug,PartialEq,Eq)]
837pub struct QuickContactLookup { pub token:u64,pub target:QuickContactTarget,pub open_after_lookup:bool }
838#[derive(Clone,Debug,PartialEq,Eq)]
839pub enum QuickContactAction { Show(String), Create(QuickContactTarget) }
840/// Host player state shown by an XML MediaController.
841#[derive(Clone,Copy,Debug,Default,PartialEq,Eq)]
842pub struct MediaPlayerSnapshot {pub position_ms:u64,pub duration_ms:u64,pub buffered_percent:u8,pub playing:bool}
843/// Player capabilities and whether previous/next listeners are installed.
844#[derive(Clone,Copy,Debug,PartialEq,Eq)]
845pub struct MediaControllerCapabilities {pub can_pause:bool,pub can_seek_backward:bool,pub can_seek_forward:bool,pub has_previous:bool,pub has_next:bool}
846impl Default for MediaControllerCapabilities {fn default()->Self{Self{can_pause:true,can_seek_backward:true,can_seek_forward:true,has_previous:false,has_next:false}}}
847#[derive(Clone,Copy,Debug,PartialEq,Eq)]
848pub enum MediaControllerAction {Play,Pause,SeekTo(u64),Previous,Next}
849#[derive(Clone,Copy,Debug,PartialEq,Eq)]
850pub enum VideoMeasureSpec {Exactly(u32),AtMost(u32),Unspecified}
851/// Android VideoView.onMeasure, using integer pixel dimensions.
852pub fn measure_video_view(video:(u32,u32),width:VideoMeasureSpec,height:VideoMeasureSpec)->(u32,u32) {
853    use VideoMeasureSpec::*;
854    let default=|natural,spec|match spec {Exactly(size)|AtMost(size)=>size,Unspecified=>natural};
855    let (vw,vh)=video;let (mut w,mut h)=(default(vw,width),default(vh,height));
856    if vw==0||vh==0{return (w,h);}
857    let ratio=|size:u32,numerator:u32,denominator:u32|((size as u64*numerator as u64/denominator as u64).min(u32::MAX as u64)) as u32;
858    match (width,height) {
859        (Exactly(sw),Exactly(sh))=>{w=sw;h=sh;if (vw as u64)*(h as u64)<(w as u64)*(vh as u64){w=ratio(h,vw,vh);}else if (vw as u64)*(h as u64)>(w as u64)*(vh as u64){h=ratio(w,vh,vw);}},
860        (Exactly(sw),other)=>{w=sw;h=ratio(w,vh,vw);if let AtMost(limit)=other{h=h.min(limit);}},
861        (other,Exactly(sh))=>{h=sh;w=ratio(h,vw,vh);if let AtMost(limit)=other{w=w.min(limit);}},
862        (ws,hs)=>{w=vw;h=vh;if let AtMost(limit)=hs && h>limit{h=limit;w=ratio(h,vw,vh);}if let AtMost(limit)=ws && w>limit{w=limit;h=ratio(w,vh,vw);}},
863    }
864    (w,h)
865}
866#[derive(Clone,Copy,Debug,Default)]
867struct MediaControllerFloating {visible:bool,deadline:Option<f64>,dragging:bool}
868/// Android menu item action placement policy.
869#[derive(Clone,Copy,Debug,PartialEq,Eq)]
870pub enum AndroidShowAsAction {Never,IfRoom,Always}
871/// Host-provided Android Toolbar menu item.
872#[derive(Clone,Debug)]
873pub struct AndroidToolbarMenuItem {pub id:u64,pub group_id:u64,pub label:String,pub icon:Option<MaterialIcon>,pub icon_drawable:Option<String>,pub show_text_with_icon:bool,pub show_as_action:AndroidShowAsAction,pub enabled:bool,pub visible:bool,pub checkable:bool,pub checked:bool,pub exclusive:bool}
874/// Allocate fixed-width actions using Android's group promotion and demotion rules.
875/// Slot widths remain an approximation of ActionMenuPresenter's view measurement.
876pub fn allocate_android_toolbar_actions(items:&[AndroidToolbarMenuItem],slots:usize)->(Vec<usize>,Vec<usize>) {
877    let required=items.iter().filter(|x|x.visible&&x.show_as_action==AndroidShowAsAction::Always).count();
878    let requested=items.iter().filter(|x|x.visible&&x.show_as_action==AndroidShowAsAction::IfRoom).count();
879    let never=items.iter().any(|x|x.visible&&x.show_as_action==AndroidShowAsAction::Never);
880    let reserve=usize::from(never||required+requested>slots);
881    let mut remaining=slots as isize-reserve as isize-required as isize;
882    let mut width=slots.saturating_sub(reserve) as isize;
883    let mut groups=std::collections::HashSet::new();let mut selected=vec![false;items.len()];
884    for (i,item) in items.iter().enumerate() {if !item.visible{continue;}match item.show_as_action {
885        AndroidShowAsAction::Always=>{selected[i]=true;width-=1;if item.group_id!=0 {groups.insert(item.group_id);}},
886        AndroidShowAsAction::IfRoom=>{
887            let grouped=item.group_id!=0&&groups.contains(&item.group_id);
888            if (remaining>0||grouped)&&width>0 {selected[i]=true;width-=1;remaining-=1;if item.group_id!=0 {groups.insert(item.group_id);}}
889            else if grouped {groups.remove(&item.group_id);for j in 0..i {if items[j].group_id==item.group_id && selected[j] {selected[j]=false;remaining+=1;}}}
890        },
891        AndroidShowAsAction::Never=>{},
892    }}
893    let mut visible=Vec::new();let mut overflow=Vec::new();
894    for (i,item) in items.iter().enumerate() {if item.visible {if selected[i] {visible.push(i)}else{overflow.push(i)}}}
895    (visible,overflow)
896}
897// ActionMenuView text items need at least two cells; icon items need one.
898fn allocate_action_menu_items(items:&[AndroidToolbarMenuItem],costs:&[usize],slots:usize)->(Vec<usize>,Vec<usize>) {
899    if slots==0 {return (Vec::new(),items.iter().enumerate().filter_map(|(i,item)|item.visible.then_some(i)).collect());}
900    let requested=items.iter().enumerate().filter(|(_,item)|item.visible&&item.show_as_action!=AndroidShowAsAction::Never).map(|(i,_)|costs[i]).sum::<usize>();
901    let reserve=usize::from(requested>slots||items.iter().any(|item|item.visible&&item.show_as_action==AndroidShowAsAction::Never));
902    let required=items.iter().enumerate().filter(|(_,item)|item.visible&&item.show_as_action==AndroidShowAsAction::Always).map(|(i,_)|costs[i]).sum::<usize>();
903    let mut remaining=slots.saturating_sub(reserve) as isize-required as isize;let mut selected=vec![false;items.len()];let mut groups=std::collections::HashSet::new();
904    for (i,item) in items.iter().enumerate().filter(|(_,item)|item.visible) {
905        if item.show_as_action==AndroidShowAsAction::Always {selected[i]=true;if item.group_id!=0{groups.insert(item.group_id);}continue;}
906        if item.show_as_action!=AndroidShowAsAction::IfRoom {continue;}
907        let grouped=item.group_id!=0&&groups.contains(&item.group_id);
908        if remaining>=costs[i] as isize {selected[i]=true;remaining-=costs[i] as isize;if item.group_id!=0{groups.insert(item.group_id);}}
909        else if grouped {groups.remove(&item.group_id);for j in 0..i {if items[j].group_id==item.group_id && selected[j] {selected[j]=false;remaining+=costs[j] as isize;}}}
910    }
911    let mut visible=Vec::new();let mut overflow=Vec::new();for (i,item) in items.iter().enumerate() {if item.visible {if selected[i]{visible.push(i)}else{overflow.push(i)}}}(visible,overflow)
912}
913/// Static, noninteractive XML views used to display a Spinner adapter item.
914#[derive(Clone,Copy)]
915pub struct SpinnerItemTemplates {
916    pub selected: &'static Node,
917    pub dropdown: &'static Node,
918    /// XML TextView ID receiving the item's text in both templates.
919    pub text_id: &'static str,
920}
921/// Static noninteractive XML view used for each ListView adapter row.
922#[derive(Clone,Copy)]
923pub struct ListItemTemplate {
924    pub row: &'static Node,
925    pub text_id: &'static str,
926}
927/// Additional text and drawable bindings for one ListView or GridView item.
928#[derive(Clone,Default)]
929pub struct AdapterItemBinding {
930    /// Optional XML layout override for this item; otherwise the adapter default is used.
931    pub template:Option<ListItemTemplate>,
932    pub text:HashMap<String,String>,
933    pub images:HashMap<String,String>,
934}
935fn adapter_item_template(default:Option<ListItemTemplate>,binding:Option<&AdapterItemBinding>)->Option<ListItemTemplate> {
936    binding.and_then(|binding|binding.template).or(default)
937}
938fn hash_item_binding<H:std::hash::Hasher>(hash:&mut H,binding:Option<&AdapterItemBinding>) {
939    use std::hash::{Hash,Hasher};
940    if let Some(binding)=binding {
941        binding.template.map(|template|(template.row as *const Node as usize,template.text_id)).hash(hash);
942        for map in [&binding.text,&binding.images] {
943            let mut combined=0u64;
944            for (key,value) in map {let mut h=std::collections::hash_map::DefaultHasher::new();key.hash(&mut h);value.hash(&mut h);combined^=h.finish();}
945            map.len().hash(hash);combined.hash(hash);
946        }
947    } else {Option::<(usize,&str)>::None.hash(hash);0usize.hash(hash);0usize.hash(hash);}
948}
949fn with_adapter_binding<T>(state:&mut LayoutState,text_id:&str,label:&str,binding:Option<&AdapterItemBinding>,run:impl FnOnce(&mut LayoutState)->T)->T {
950    state.text.clear();let mut saved=Vec::new();
951    if let Some(binding)=binding {
952        state.text.extend(binding.text.iter().map(|(key,value)|(key.clone(),value.clone())));
953        for (key,value) in &binding.images {saved.push((key.clone(),state.image_sources.insert(key.clone(),value.clone())));}
954    }
955    state.text.insert(text_id.to_owned(),label.to_owned());
956    let result=run(state);
957    for (key,old) in saved {if let Some(value)=old {state.image_sources.insert(key,value);}else{state.image_sources.remove(&key);}}
958    result
959}
960/// An XML view placed before or after ListView adapter rows.
961#[derive(Clone,Copy)]
962pub struct ListFixedView { pub view:&'static Node, pub selectable:bool, pub label:&'static str }
963fn inspect_expandable_template(node:&Node,text_id:&str)->(bool,bool,bool) {
964    let allowed=matches!(node.kind,Kind::Text|Kind::Image|Kind::Space|Kind::View|Kind::Linear|Kind::Frame|Kind::CheckBox|Kind::Switch|Kind::Button|Kind::Edit);
965    let interactive=matches!(node.kind,Kind::CheckBox|Kind::Switch|Kind::Button|Kind::Edit);
966    let safe=allowed && (!node.clickable||interactive) && (!interactive||!node.id.is_empty());
967    node.children.iter().fold((safe,matches!(node.kind,Kind::Text)&&node.id==text_id,interactive),|(ok,found,has),child|{let (a,b,c)=inspect_expandable_template(child,text_id);(ok&&a,found||b,has||c)})
968}
969fn inspect_adapter_template(node:&Node,text_id:&str)->(bool,bool) {
970    let safe=!node.clickable && matches!(node.kind,Kind::Text|Kind::Image|Kind::Space|Kind::View|Kind::Linear|Kind::Frame);
971    node.children.iter().fold((safe,matches!(node.kind,Kind::Text) && node.id==text_id),|(ok,found),child| {let (child_ok,child_found)=inspect_adapter_template(child,text_id);(ok&&child_ok,found||child_found)})
972}
973/// Lightweight performance and retention counters for Android XML adapter lists.
974#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
975pub struct ListPerfStats {
976    /// Number of list render passes recorded.
977    pub frames: u64,
978    /// Total adapter rows built/painted across frames.
979    pub rows_built: u64,
980    /// Total adapter rows actually measured (layout/wrap executed on cache miss).
981    pub rows_measured: u64,
982    /// Total row measurement checks satisfied from cache without remeasuring.
983    pub measure_cache_hits: u64,
984    /// Total rows that reused cached row layout / wrapped-line data during paint.
985    pub row_cache_hits: u64,
986    /// Total `LayoutState` clones executed while preparing/drawing list rows.
987    pub row_state_clones: u64,
988    /// Number of times list geometry was freshly constructed or invalidated.
989    pub geometry_rebuilds: u64,
990    /// Peak retained measured/cached row entries observed.
991    pub peak_retained_rows: usize,
992    /// Peak retained control-state row entries observed.
993    pub peak_retained_control_rows: usize,
994    /// Peak retained list cache & control-state bytes (excluding caller adapter strings).
995    pub peak_retained_bytes: usize,
996}
997// Estimated row heights are refined only when rows become visible. The Fenwick
998// tree keeps scroll position lookup and individual height updates logarithmic.
999#[derive(Clone)]
1000struct ListTextGeometry { signature:u64, heights:Vec<f32>, cross_sizes:Vec<f32>, fingerprints:Vec<Option<u64>>, tree:Vec<f32>, divider:f32, measured_count:usize }
1001impl ListTextGeometry {
1002    fn new(signature:u64,count:usize,divider:f32)->Self {
1003        let step=48.0+divider;let mut tree=vec![0.0;count+1];
1004        for i in 1..=count {tree[i]=step*(i & i.wrapping_neg()) as f32;}
1005        Self {signature,heights:vec![48.0;count],cross_sizes:Vec::new(),fingerprints:vec![None;count],tree,divider,measured_count:0}
1006    }
1007    fn retained_bytes(&self)->usize {
1008        self.heights.capacity()*std::mem::size_of::<f32>()
1009            + self.cross_sizes.capacity()*std::mem::size_of::<f32>()
1010            + self.fingerprints.capacity()*std::mem::size_of::<Option<u64>>()
1011            + self.tree.capacity()*std::mem::size_of::<f32>()
1012    }
1013    fn prefix(&self,mut i:usize)->f32 {let mut sum=0.0;while i>0 {sum+=self.tree[i];i&=i-1;}sum}
1014    fn index_at(&self,target:f32)->usize {
1015        let n=self.heights.len();if n==0{return 0;}
1016        let mut bit=1usize;while bit<=n/2 {bit*=2;}
1017        let (mut index,mut sum)=(0usize,0.0f32);
1018        while bit>0 {let next=index+bit;if next<=n && sum+self.tree[next]<=target {index=next;sum+=self.tree[next];}bit/=2;}
1019        index
1020    }
1021    #[allow(clippy::too_many_arguments)]
1022    fn measure(&mut self,index:usize,label:&str,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:Option<&mut LayoutState>,id:u64,binding:Option<&AdapterItemBinding>,perf:&mut ListPerfStats)->bool {
1023        use std::hash::{Hash,Hasher};let mut hash=std::collections::hash_map::DefaultHasher::new();label.hash(&mut hash);hash_item_binding(&mut hash,binding);let fingerprint=hash.finish();
1024        if self.fingerprints[index]==Some(fingerprint) {perf.measure_cache_hits+=1;return false;}
1025        if self.fingerprints[index].is_none() {self.measured_count+=1;}
1026        self.fingerprints[index]=Some(fingerprint);
1027        perf.rows_measured+=1;
1028        let template=adapter_item_template(template,binding);
1029        let height=if let (Some(template),Some(row_state))=(template,row_state) {
1030            with_adapter_binding(row_state,template.text_id,label,binding,|state|match template.row.height {Size::Match=>48.0,_=>template.row.layout_intrinsic(false,state,width,metrics,anonymous_child_id(id,1024+index))})
1031        } else {let lines=wrapped_text_lines(label,(width-32.0).max(1.0),TextStyle::default(),metrics,|_|{}).max(1);24.0*lines as f32};
1032        let height=if height.is_finite() {height.clamp(if template.is_some(){1.0}else{48.0},4096.0)}else{48.0};
1033        let delta=height-self.heights[index];self.heights[index]=height;
1034        if delta.abs()<0.01 {return false;}
1035        let mut pos=index+1;while pos<self.tree.len(){self.tree[pos]+=delta;pos+=pos & pos.wrapping_neg();}true
1036    }
1037    #[allow(clippy::too_many_arguments)]
1038    fn measure_grid_row(&mut self,row:usize,entries:&[String],columns:usize,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,mut row_state:Option<&mut LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>,perf:&mut ListPerfStats)->bool {
1039        use std::hash::{Hash,Hasher};let start=row*columns;let end=(start+columns).min(entries.len());
1040        let mut hash=std::collections::hash_map::DefaultHasher::new();entries[start..end].hash(&mut hash);for index in start..end {hash_item_binding(&mut hash,bindings.and_then(|items|items.get(&index)));}let fingerprint=hash.finish();
1041        if self.fingerprints[row]==Some(fingerprint) {perf.measure_cache_hits+=1;return false;}
1042        if self.fingerprints[row].is_none() {self.measured_count+=1;}
1043        self.fingerprints[row]=Some(fingerprint);
1044        perf.rows_measured+=1;
1045        let mut height=0.0_f32;
1046        for (offset,label) in entries[start..end].iter().enumerate() {
1047            let (_,measured)=grid_item_size(template,row_state.as_deref_mut(),label,width,metrics,anonymous_child_id(id,1024+start+offset),bindings.and_then(|items|items.get(&(start+offset))));
1048            height=height.max(measured);
1049        }
1050        let delta=height-self.heights[row];self.heights[row]=height;if delta.abs()<0.01{return false;}
1051        let mut pos=row+1;while pos<self.tree.len(){self.tree[pos]+=delta;pos+=pos & pos.wrapping_neg();}true
1052    }
1053    #[allow(clippy::too_many_arguments)]
1054    fn measure_grid_window(&mut self,entries:&[String],columns:usize,scroll:f32,height:f32,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,mut row_state:Option<&mut LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>,perf:&mut ListPerfStats)->bool {
1055        if scroll+height<=0.0{return false;}let mut row=self.index_at(scroll.max(0.0));let mut y=self.prefix(row);let mut changed=false;
1056        while row<self.heights.len() && y<scroll+height {changed|=self.measure_grid_row(row,entries,columns,width,metrics,template,row_state.as_deref_mut(),id,bindings,perf);y+=self.heights[row]+self.divider;row+=1;}changed
1057    }
1058    #[allow(clippy::too_many_arguments)]
1059    fn measure_window(&mut self,entries:&[String],scroll:f32,height:f32,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,mut row_state:Option<&mut LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>,perf:&mut ListPerfStats)->bool {
1060        if scroll+height<=0.0 {return false;}
1061        let mut index=self.index_at(scroll.max(0.0));let mut y=self.prefix(index);let mut changed=false;
1062        while index<entries.len() && y<scroll+height {changed|=self.measure(index,&entries[index],width,metrics,template,row_state.as_deref_mut(),id,bindings.and_then(|items|items.get(&index)),perf);y+=self.heights[index]+self.divider;index+=1;}
1063        changed
1064    }
1065    #[allow(clippy::too_many_arguments)]
1066    fn measure_recycler_linear(
1067        &mut self,
1068        vis_pos: usize,
1069        adapter_idx: usize,
1070        label: &str,
1071        horizontal: bool,
1072        track_size: f32,
1073        viewport_width: f32,
1074        metrics: TextMetrics,
1075        template: Option<ListItemTemplate>,
1076        row_state: Option<&mut LayoutState>,
1077        id: u64,
1078        binding: Option<&AdapterItemBinding>,
1079        perf: &mut ListPerfStats,
1080    ) -> bool {
1081        use std::hash::{Hash, Hasher};
1082        let mut hash = std::collections::hash_map::DefaultHasher::new();
1083        label.hash(&mut hash);
1084        hash_item_binding(&mut hash, binding);
1085        let fingerprint = hash.finish();
1086        if self.fingerprints[vis_pos] == Some(fingerprint) {
1087            perf.measure_cache_hits += 1;
1088            return false;
1089        }
1090        if self.fingerprints[vis_pos].is_none() {
1091            self.measured_count += 1;
1092        }
1093        self.fingerprints[vis_pos] = Some(fingerprint);
1094        perf.rows_measured += 1;
1095        let item_tmpl = adapter_item_template(template, binding);
1096        let cid = anonymous_child_id(id, 1024 + adapter_idx);
1097        let (w, h) = if let (Some(tmpl), Some(rs)) = (item_tmpl, row_state) {
1098            with_adapter_binding(rs, tmpl.text_id, label, binding, |rs| {
1099                if horizontal {
1100                    let h = match tmpl.row.height {
1101                        Size::Match => track_size,
1102                        Size::Dp(v) => rs.dp(v).min(track_size),
1103                        Size::Wrap => tmpl.row.layout_intrinsic(false, rs, viewport_width.max(48.0), metrics, cid).min(track_size),
1104                    }
1105                    .max(1.0);
1106                    let w = match tmpl.row.width {
1107                        Size::Match => rs.dp(120.0).min(viewport_width.max(48.0)),
1108                        Size::Dp(v) => rs.dp(v),
1109                        Size::Wrap => tmpl.row.layout_intrinsic(true, rs, viewport_width.max(48.0), metrics, cid),
1110                    };
1111                    (if w.is_finite() { w.clamp(1.0, 4096.0) } else { rs.dp(120.0) }, h)
1112                } else {
1113                    let w = match tmpl.row.width {
1114                        Size::Match => track_size,
1115                        Size::Dp(v) => rs.dp(v).min(track_size),
1116                        Size::Wrap => tmpl.row.layout_intrinsic(true, rs, track_size, metrics, cid).min(track_size),
1117                    }
1118                    .max(1.0);
1119                    let h = match tmpl.row.height {
1120                        Size::Match => rs.dp(48.0),
1121                        Size::Dp(v) => rs.dp(v),
1122                        Size::Wrap => tmpl.row.layout_intrinsic(false, rs, w, metrics, cid),
1123                    };
1124                    (w, if h.is_finite() { h.clamp(1.0, 4096.0) } else { rs.dp(48.0) })
1125                }
1126            })
1127        } else if horizontal {
1128            let tw = metrics.width(label, TextStyle::default());
1129            let w = (tw.ceil() + 34.0).clamp(48.0, 4096.0);
1130            (w, track_size)
1131        } else {
1132            let lines = wrapped_text_lines(label, (track_size - 32.0).max(1.0), TextStyle::default(), metrics, |_| {}).max(1);
1133            (track_size, (24.0 * lines as f32).clamp(48.0, 4096.0))
1134        };
1135        let (main_len, cross_len) = if horizontal { (w, h) } else { (h, w) };
1136        if (cross_len - track_size).abs() >= 0.01 || !self.cross_sizes.is_empty() {
1137            if self.cross_sizes.len() < self.heights.len() {
1138                self.cross_sizes.resize(self.heights.len(), track_size);
1139            }
1140            self.cross_sizes[vis_pos] = cross_len;
1141        }
1142        let delta = main_len - self.heights[vis_pos];
1143        self.heights[vis_pos] = main_len;
1144        if delta.abs() < 0.01 {
1145            return false;
1146        }
1147        let mut pos = vis_pos + 1;
1148        while pos < self.tree.len() {
1149            self.tree[pos] += delta;
1150            pos += pos & pos.wrapping_neg();
1151        }
1152        true
1153    }
1154    #[allow(clippy::too_many_arguments)]
1155    fn measure_recycler_linear_window(
1156        &mut self,
1157        entries: &[String],
1158        reverse: bool,
1159        horizontal: bool,
1160        scroll: f32,
1161        viewport_main: f32,
1162        track_size: f32,
1163        viewport_width: f32,
1164        metrics: TextMetrics,
1165        template: Option<ListItemTemplate>,
1166        mut row_state: Option<&mut LayoutState>,
1167        id: u64,
1168        bindings: Option<&HashMap<usize, AdapterItemBinding>>,
1169        perf: &mut ListPerfStats,
1170    ) -> bool {
1171        let count = entries.len();
1172        if count == 0 || scroll + viewport_main <= 0.0 {
1173            return false;
1174        }
1175        let mut vis_pos = self.index_at(scroll.max(0.0));
1176        let mut main_pos = self.prefix(vis_pos);
1177        let mut changed = false;
1178        while vis_pos < count && main_pos < scroll + viewport_main {
1179            let adapter_idx = if reverse { count - 1 - vis_pos } else { vis_pos };
1180            changed |= self.measure_recycler_linear(
1181                vis_pos,
1182                adapter_idx,
1183                &entries[adapter_idx],
1184                horizontal,
1185                track_size,
1186                viewport_width,
1187                metrics,
1188                template,
1189                row_state.as_deref_mut(),
1190                id,
1191                bindings.and_then(|items| items.get(&adapter_idx)),
1192                perf,
1193            );
1194            main_pos += self.heights[vis_pos] + self.divider;
1195            vis_pos += 1;
1196        }
1197        changed
1198    }
1199}
1200fn list_text_signature(entries:&[String],width:f32,divider:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:Option<&LayoutState>)->u64 {
1201    use std::hash::{Hash,Hasher};let mut hash=std::collections::hash_map::DefaultHasher::new();
1202    (entries.as_ptr() as usize).hash(&mut hash);entries.len().hash(&mut hash);width.to_bits().hash(&mut hash);divider.to_bits().hash(&mut hash);
1203    for advance in metrics.normal.iter().chain(metrics.medium.iter()) {advance.to_bits().hash(&mut hash);}
1204    template.map(|t|(t.row as *const Node as usize,t.text_id)).hash(&mut hash);
1205    if let Some(state)=row_state {hash_adapter_environment(&mut hash,state);}
1206    hash.finish()
1207}
1208#[derive(Default)]
1209struct RowScratchState(Option<Box<LayoutState>>);
1210impl Clone for RowScratchState {
1211    fn clone(&self) -> Self {
1212        Self(None)
1213    }
1214}
1215#[derive(Clone)]
1216struct AutoAnchor {key:String,id:u64,xml_id:&'static str,bounds:Rect,threshold:usize,width:&'static str,height:&'static str,offset_x:f32,offset_y:f32,rtl:bool,multi:bool,search:bool}
1217#[derive(Clone)]
1218struct AutoMatches {query:Option<String>,indices:Vec<usize>}
1219#[derive(Clone,Copy)]
1220struct ListHold { item_id:u64, origin:[f32;2], deadline:f64, fired:bool }
1221#[derive(Clone,Default)]
1222struct StackGesture {origin:Option<[f32;2]>,offset:f32,offset_x:f32,dragging:bool,tap_in_front:bool,direction:i8,drag_delta:f32,settle:Option<(f64,f32,f32,f64)>,outgoing:Option<(f64,f32,f32,f32,usize,f64)>,incoming:Option<(f64,f32,f32,f64)>,last_wheel:Option<f64>}
1223#[derive(Clone,Default)]
1224struct GalleryGesture { rtl:bool, origin:Option<[f32;2]>, offset:f32, drag_base:f32, dragging:bool, settle:Option<(f64,f32,f64)>, fling:Option<(f64,f32,f32,f64,usize)>, samples:Vec<(f64,f32)> }
1225#[derive(Clone, Default)]
1226struct ViewPagerGesture {
1227    origin: Option<[f32; 2]>,
1228    offset: f32,
1229    dragging: bool,
1230    settle: Option<(f64, f32, f64)>,
1231    last_page: usize,
1232    from_page: Option<usize>,
1233    last_time: f64,
1234    initialized: bool,
1235    samples: Vec<(f64, f32)>,
1236}
1237#[derive(Clone, Copy, Default)]
1238struct SwipeRefreshMotion {
1239    initialized: bool,
1240    last_refreshing: bool,
1241    last_time: f64,
1242    origin: Option<[f32; 2]>,
1243    dragging: bool,
1244    pull_px: f32,
1245    offset_px: f32,
1246    settle: Option<(f64, f32, f32, f64)>,
1247}
1248#[derive(Clone, Default)]
1249struct CarouselMotion {
1250    origin: Option<[f32; 2]>,
1251    drag_base: f32,
1252    dragging: bool,
1253    was_touch_dragging: bool,
1254    snap: Option<(f64, f32, f32, f64)>,
1255    samples: Vec<(f64, f32)>,
1256}
1257#[derive(Clone, Default)]
1258struct XmlSheetMotion {
1259    origin: Option<[f32; 2]>,
1260    drag_base: f32,
1261    drag_offset: f32,
1262    current_h: Option<f32>,
1263    dragging: bool,
1264    settle: Option<(f64, f32, f32, f64)>,
1265    last_state: u8,
1266    samples: Vec<(f64, f32)>,
1267}
1268#[derive(Clone, Default)]
1269struct XmlDrawerMotion {
1270    initialized: bool,
1271    last_open: bool,
1272    last_time: f64,
1273    progress: f32,
1274    anim: Option<(f64, f32, f32, f64)>,
1275    origin: Option<[f32; 2]>,
1276    drag_base_progress: f32,
1277    drag_align_right: bool,
1278    drag_panel_w: f32,
1279    dragging: bool,
1280    edge_opening: bool,
1281    samples: Vec<(f64, f32)>,
1282}
1283#[derive(Clone, Copy, Default)]
1284struct AppBarScrollState {
1285    initialized: bool,
1286    last_scroll: f32,
1287    collapse_px: f32,
1288    last_scroll_time: f64,
1289    last_time: f64,
1290    was_dragging: bool,
1291    snap_anim: Option<(f64, f32, f32, f64)>,
1292}
1293#[derive(Clone, Copy, Default)]
1294struct AnimatedSelectorState {
1295    initialized: bool,
1296    last_mask: u8,
1297    active: Option<(f64, bool, usize)>,
1298}
1299#[derive(Clone, Copy, Default)]
1300struct XmlLiftMotion {
1301    initialized: bool,
1302    last_lifted: bool,
1303    last_time: f64,
1304    progress: f32,
1305    anim: Option<(f64, f32, f32, f64)>,
1306}
1307#[derive(Clone, Copy, Default)]
1308struct DrawableTransitionMotion {
1309    initialized: bool,
1310    last_active: bool,
1311    progress: f32,
1312    anim: Option<(f64, f32, f32, f64)>,
1313}
1314#[derive(Clone, Copy, Default)]
1315struct BottomAppBarHideState {
1316    initialized: bool,
1317    last_scroll: f32,
1318    hidden: bool,
1319    last_time: f64,
1320    progress: f32,
1321    anim: Option<(f64, f32, f32, f64)>,
1322}
1323#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1324struct BottomAppBarCradleCacheKey {
1325    w: u16,
1326    h: u16,
1327    cx_q: u16,
1328    voff_q: i16,
1329    cradle_r_q: u16,
1330    fillet_r_q: u16,
1331    color: [u8; 4],
1332}
1333#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1334struct GradientCacheKey {
1335    kind_tag: u8,
1336    w: u16,
1337    h: u16,
1338    p0: i32,
1339    p1: i32,
1340    p2: i32,
1341    start: [u8; 4],
1342    center: Option<([u8; 4], u16)>,
1343    end: [u8; 4],
1344    tint: Option<[u8; 4]>,
1345    mask_tag: u8,
1346    mask_radii: [u16; 4],
1347    mask_cut: [bool; 4],
1348}
1349#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1350struct CutShapeCacheKey {
1351    w: u16,
1352    h: u16,
1353    radii_q: [u16; 4],
1354    cut: [bool; 4],
1355    color: [u8; 4],
1356}
1357fn pointer_velocity(samples: &[(f64, f32)], now: f64) -> f32 {
1358    samples
1359        .last()
1360        .and_then(|&(last_t, last_v)| {
1361            if now - last_t < 0.12 {
1362                samples
1363                    .iter()
1364                    .rev()
1365                    .find(|(t, _)| last_t - *t >= 0.005)
1366                    .map(|&(first_t, first_v)| (last_v - first_v) / (last_t - first_t) as f32)
1367            } else {
1368                None
1369            }
1370        })
1371        .unwrap_or(0.0)
1372}
1373// Android Scroller samples its fling spline at 100 intervals and linearly
1374// interpolates between those samples. The binary search solves its Bezier x.
1375fn gallery_spline_sample(index:usize)->f32 {
1376    if index==0{return 0.0;}if index>=100{return 1.0;}
1377    let target=index as f32/100.0;let(mut lo,mut hi)=(0.0,1.0);
1378    for _ in 0..20 {let x=(lo+hi)*0.5;let c=3.0*x*(1.0-x);let t=c*((1.0-x)*0.175+x*0.35)+x*x*x;if t<target{lo=x;}else{hi=x;}}
1379    let x=(lo+hi)*0.5;let c=3.0*x*(1.0-x);c*((1.0-x)*0.5+x)+x*x*x
1380}
1381fn gallery_spline_position(progress:f32)->f32 {
1382    let scaled=progress.clamp(0.0,1.0)*100.0;let index=scaled as usize;if index>=100{return 1.0;}
1383    let a=gallery_spline_sample(index);let b=gallery_spline_sample(index+1);a+(b-a)*(scaled-index as f32)
1384}
1385/// View-ID based tabs configured by a host for Android TabHost.
1386#[derive(Clone,Default)]
1387pub struct TabHostState {pub widget_id:String,pub content_ids:Vec<String>,pub labels:Vec<String>,pub tags:Vec<String>,pub selected:usize,pub factories:Vec<Option<fn(&str)-> &'static Node>>}
1388/// Content of a TabHost tab: an existing XML view or a lazy XML factory.
1389#[derive(Clone)]
1390pub enum TabHostContent { View(String), Factory(fn(&str)-> &'static Node) }
1391fn tab_host_find<'a>(node:&'a Node,id:&str)->Option<&'a Node> {
1392    if node.id==id {return Some(node);}node.children.iter().find_map(|child|tab_host_find(child,id))
1393}
1394fn radio_descendant_by_id(node:&Node,id:u64)->Option<&Node> {
1395    if !node.id.is_empty() && view_id(node.id)==id {return Some(node);}
1396    node.children.iter().find_map(|child|radio_descendant_by_id(child,id))
1397}
1398/// SlidingDrawer notifications corresponding to Android's listeners.
1399#[derive(Clone,Copy,Debug,PartialEq,Eq)]
1400pub enum SlidingDrawerEvent { ScrollStarted, ScrollEnded, Opened, Closed }
1401#[derive(Clone,Default)]
1402pub struct SlidingDrawerState {pub open:bool,pub locked:bool,pending:Option<(bool,bool)>,position:f32,drag:Option<(f32,f32)>,dragging:bool,motion:Option<(f64,f32,f32,f64,f32,f32)>,samples:Vec<(f64,f32)>,events:Vec<SlidingDrawerEvent>}
1403impl SlidingDrawerState {
1404    fn record(&mut self,event:SlidingDrawerEvent) {
1405        if self.events.len()==32 {self.events.remove(0);}
1406        self.events.push(event);
1407    }
1408    fn complete(&mut self,open:bool) {
1409        if self.open!=open {
1410            self.open=open;
1411            self.record(if open{SlidingDrawerEvent::Opened}else{SlidingDrawerEvent::Closed});
1412        }
1413    }
1414}
1415#[derive(Clone)]
1416pub struct LayoutState {
1417    motion_scenes: HashMap<&'static str, MotionScene>,
1418    motion_layout_policies: HashMap<(&'static str, Option<usize>), motion_layout::MotionLayoutPolicy>,
1419    motion_spring_configs: HashMap<(&'static str, usize), motion_layout::MotionSpringConfig>,
1420    motion_layout_bounds_cache: HashMap<&'static str, motion_layout::MotionLayoutBoundsCache>,
1421    motion_wrap_available: std::cell::RefCell<HashMap<(&'static str, bool), ((f32, bool, bool), bool)>>,
1422    motion_measure_frame: Option<(f64, bool)>,
1423    motion_measure_input: Option<Input>,
1424    motion_measure_swipe_fallback: std::cell::RefCell<HashMap<&'static str, (f64, usize, f32, [f32; 2], f32, f32, f32)>>,
1425    motion_transition_arcs: HashMap<(&'static str, Option<usize>), MotionPathArc>,
1426    motion_transition_durations: HashMap<(&'static str, Option<usize>), f64>,
1427    motion_scene_default_durations: HashMap<&'static str, f64>,
1428    motion_transition_templates: HashMap<(&'static str, Option<&'static str>), usize>,
1429    motion_transition_enabled: HashMap<(&'static str, &'static str), bool>,
1430    motion_transitions: HashMap<&'static str, (std::sync::Arc<[MotionTransition]>, usize)>,
1431    motion_inserted_set_bases: HashMap<(&'static str, &'static str), &'static Node>,
1432    motion_inserted_set_defaults: HashMap<(&'static str, &'static str), motion_layout::MotionConstraintSet>,
1433    motion_inserted_edge_start_sets: HashMap<(&'static str, usize), &'static str>,
1434    motion_inserted_edge_templates: HashMap<(&'static str, usize), usize>,
1435    motion_inserted_edge_source_config: HashMap<(&'static str, usize), motion_layout::MotionSourceConfig>,
1436    motion_runtime_set_source_config: HashMap<(&'static str, &'static str), motion_layout::MotionSourceConfig>,
1437    motion_declared_transition_indices: HashMap<&'static str, Vec<usize>>,
1438    motion_variant_units: HashMap<(&'static str, &'static str), Vec<[MotionDimensionUnit; 4]>>,
1439    motion_all_states_deltas: HashMap<&'static str, Vec<MotionViewTransition>>,
1440    motion_independent_views: HashMap<(&'static str, &'static str), motion_layout::MotionIndependentView>,
1441    motion_finished_independent: HashMap<(&'static str, &'static str), motion_layout::MotionIndependentView>,
1442    motion_independent_sequence: u64,
1443    motion_shared_values: HashMap<&'static str, i32>,
1444    motion_shared_subscription: Option<motion_layout::MotionSharedSubscription>,
1445    motion_shared_listener_values: HashMap<(&'static str, &'static str), i32>,
1446    motion_view_tags: std::collections::HashSet<(&'static str, &'static str, &'static str)>,
1447    motion_view_enabled: HashMap<(&'static str, &'static str), bool>,
1448    motion_view_patterns: HashMap<(&'static str, &'static str), motion_layout::MotionTargetPattern>,
1449    motion_constraint_tags: HashMap<(&'static str, &'static str), String>,
1450    motion_set_tags: HashMap<(&'static str, &'static str), &'static [(&'static str, &'static str)]>,
1451    motion_set_pivot_targets: HashMap<(&'static str, &'static str), &'static [(&'static str, &'static str)]>,
1452    motion_set_path_rotations: HashMap<(&'static str, &'static str), &'static [(&'static str, f32)]>,
1453    motion_runtime_set_pivots: HashMap<(&'static str, &'static str), HashMap<&'static str, &'static str>>,
1454    motion_runtime_set_visibility_modes: HashMap<(&'static str, &'static str), HashMap<&'static str, bool>>,
1455    motion_set_visibility_modes: HashMap<(&'static str, &'static str), &'static [&'static str]>,
1456    motion_view_pivot_deltas: HashMap<(&'static str, &'static str), &'static str>,
1457    motion_all_set_pivot_deltas: HashMap<(&'static str, &'static str), &'static str>,
1458    motion_runtime_set_tags: HashMap<(&'static str, &'static str), HashMap<&'static str, String>>,
1459    motion_set_custom: HashMap<(&'static str, &'static str), &'static [(&'static str, &'static str, MotionCustomValue)]>,
1460    motion_runtime_set_custom: HashMap<(&'static str, &'static str), HashMap<(&'static str, &'static str), MotionCustomValue>>,
1461    motion_runtime_set_native: HashMap<(&'static str, &'static str), HashMap<(&'static str, MotionProperty), MotionNativeValue>>,
1462    motion_runtime_set_biases: HashMap<(&'static str, &'static str), HashMap<(&'static str, bool), f32>>,
1463    motion_runtime_set_percents: HashMap<(&'static str, &'static str), HashMap<(&'static str, bool), f32>>,
1464    motion_runtime_set_ratios: HashMap<(&'static str, &'static str), HashMap<&'static str, String>>,
1465    motion_runtime_set_size_bounds: HashMap<(&'static str, &'static str), HashMap<(&'static str, MotionSizeBound), MotionSizeValue>>,
1466    motion_view_size_deltas: HashMap<(&'static str, &'static str), Vec<(MotionSizeBound, MotionSizeValue)>>,
1467    motion_all_set_size_deltas: HashMap<(&'static str, &'static str, MotionSizeBound), MotionSizeValue>,
1468    motion_view_ratio_deltas: HashMap<(&'static str, &'static str), &'static str>,
1469    motion_all_set_ratio_deltas: HashMap<(&'static str, &'static str), String>,
1470    motion_view_percent_deltas: HashMap<(&'static str, &'static str), Vec<(bool, f32)>>,
1471    motion_all_set_percent_deltas: HashMap<(&'static str, &'static str, bool), f32>,
1472    motion_view_bias_deltas: HashMap<(&'static str, &'static str), Vec<(bool, f32)>>,
1473    motion_all_set_bias_deltas: HashMap<(&'static str, &'static str, bool), f32>,
1474    motion_view_native_deltas: HashMap<(&'static str, &'static str), Vec<(MotionProperty, MotionNativeValue)>>,
1475    motion_all_set_native_deltas: HashMap<(&'static str, &'static str, MotionProperty), MotionNativeValue>,
1476    motion_view_custom_deltas: HashMap<(&'static str, &'static str), &'static [(&'static str, MotionCustomValue)]>,
1477    motion_all_set_custom_deltas: HashMap<(&'static str, &'static str, &'static str), MotionCustomValue>,
1478    motion_view_constraint_tag_deltas: HashMap<(&'static str, &'static str), &'static str>,
1479    motion_all_set_tag_deltas: HashMap<(&'static str, &'static str), String>,
1480    motion_responsive_tag_sets: HashMap<(&'static str, &'static str), &'static [&'static str]>,
1481    motion_view_transitions: HashMap<&'static str, &'static [MotionViewTransition]>,
1482    motion_view_key_triggers: HashMap<(&'static str, &'static str), &'static [MotionKeyTrigger]>,
1483    motion_view_key_units: HashMap<(&'static str, &'static str, &'static str, MotionProperty), &'static [MotionDimensionUnit]>,
1484    motion_abstract_clicks: HashMap<(&'static str, &'static str), &'static str>,
1485    motion_abstract_click_templates: HashMap<(&'static str, &'static str), usize>,
1486    motion_set_animations: HashMap<&'static str, motion_layout::MotionSetAnimation>,
1487    motion_finished_temporary: HashMap<&'static str, motion_layout::MotionSetAnimation>,
1488    motion_runtime_sets: HashMap<(&'static str, &'static str), std::sync::Arc<[Node]>>,
1489    motion_layout_derivatives: HashMap<(&'static str, &'static str), motion_layout::MotionViewDerivatives>,
1490    motion_rendered_poses: HashMap<(&'static str, &'static str), motion_layout::MotionViewSample>,
1491    motion_dynamic_starts: HashMap<&'static str, motion_layout::MotionDynamicStart>,
1492    motion_descendant_bounds: HashMap<(&'static str, &'static str), Rect>,
1493    motion_nested_gesture_owner: HashMap<&'static str, &'static str>,
1494    motion_intercept_touch_flags: std::collections::HashSet<(&'static str, usize)>,
1495    motion_declined_touch: std::collections::HashSet<&'static str>,
1496    motion_collision_bounds: HashMap<(&'static str, &'static str), (Rect, Rect, Rect)>,
1497    motion_anonymous_bounds: HashMap<(&'static str, u64), Rect>,
1498    motion_collect_anonymous_bounds: bool,
1499    motion_parent_bounds: Vec<Rect>,
1500    motion_parent_scroll: Vec<[f32; 2]>,
1501    motion_collision_probe_visible: std::collections::HashSet<usize>,
1502    motion_descendant_clips: HashMap<(&'static str, &'static str), Rect>,
1503    motion_descendant_transforms: HashMap<(&'static str, &'static str), Vec<motion_layout::MotionHitTransform>>,
1504    motion_hit_stack: Vec<motion_layout::MotionHitTransform>,
1505    motion_descendant_roots: HashMap<&'static str, Rect>,
1506    motion_root_viewports: HashMap<&'static str, Rect>,
1507    motion_root_parent_origins: HashMap<&'static str, [f32; 2]>,
1508    motion_descendant_signatures: HashMap<&'static str, u64>,
1509    motion_descendant_scroll_limits: HashMap<(&'static str, u64), f32>,
1510    motion_collect_scene: Option<&'static str>,
1511    motion_playback: HashMap<&'static str, motion_layout::MotionPlayback>,
1512    motion_custom_values: HashMap<(&'static str, &'static str, &'static str), MotionCustomValue>,
1513    motion_animated_view_progress: HashMap<(&'static str, &'static str), f32>,
1514    motion_set_progress_values: HashMap<(&'static str, &'static str), &'static [(&'static str, f32)]>,
1515    motion_time_phases: HashMap<(&'static str, &'static str, MotionProperty), motion_layout::MotionTimePhase>,
1516    motion_trigger_states: HashMap<(&'static str, usize), motion_layout::MotionTriggerState>,
1517    motion_trigger_history: HashMap<(&'static str, usize, usize), (MotionKeyTrigger, motion_layout::MotionTriggerState)>,
1518    motion_trigger_edge_groups: HashMap<(&'static str, usize), usize>,
1519    motion_trigger_key_groups: HashMap<(&'static str, usize, usize, usize), usize>,
1520    motion_trigger_key_order: HashMap<(&'static str, usize, usize, usize), (usize, bool)>,
1521    motion_trigger_key_identity: HashMap<(&'static str, usize, usize, usize), usize>,
1522    motion_trigger_key_patterns: HashMap<(&'static str, usize, usize, usize), (Option<motion_layout::MotionTargetPattern>, bool)>,
1523    motion_trigger_pattern_matches: HashMap<(&'static str, usize), bool>,
1524    motion_trigger_patterns_dirty: std::collections::HashSet<&'static str>,
1525    motion_position_key_patterns: HashMap<(&'static str, usize, usize, usize, usize), (Option<motion_layout::MotionTargetPattern>, bool)>,
1526    motion_position_key_fits: HashMap<(&'static str, usize, usize, usize, usize), (usize, bool, usize, bool)>,
1527    motion_position_selected_keys: HashMap<(&'static str, &'static str), Vec<MotionPositionKey>>,
1528    motion_position_selected_fits: HashMap<(&'static str, &'static str), bool>,
1529    motion_position_patterns_dirty: std::collections::HashSet<&'static str>,
1530    motion_property_key_candidates: HashMap<(&'static str, usize, usize, &'static str, MotionProperty), Vec<motion_layout::MotionPropertyKeyCandidate>>,
1531    motion_property_selected_keys: HashMap<(&'static str, &'static str, MotionProperty), motion_layout::MotionSelectedPropertyKeys>,
1532    motion_custom_key_candidates: HashMap<(&'static str, usize, usize, &'static str, &'static str), Vec<motion_layout::MotionCustomKeyCandidate>>,
1533    motion_custom_selected_keys: HashMap<(&'static str, &'static str, &'static str), motion_layout::MotionSelectedCustomKeys>,
1534    motion_cycle_key_candidates: HashMap<(&'static str, usize, usize, &'static str, MotionProperty), Vec<motion_layout::MotionCycleKeyCandidate>>,
1535    motion_cycle_selected_keys: HashMap<(&'static str, &'static str, MotionProperty), motion_layout::MotionSelectedCycleKeys>,
1536    motion_time_cycle_key_candidates: HashMap<(&'static str, usize, usize, &'static str, MotionProperty), Vec<motion_layout::MotionCycleKeyCandidate>>,
1537    motion_time_cycle_selected_keys: HashMap<(&'static str, &'static str, MotionProperty), motion_layout::MotionSelectedCycleKeys>,
1538    motion_trigger_identity_history: HashMap<(&'static str, usize, usize), motion_layout::MotionTriggerState>,
1539    motion_trigger_events: std::collections::VecDeque<MotionTriggerEvent>,
1540    motion_transition_events: std::collections::VecDeque<MotionTransitionEvent>,
1541    motion_schedules: HashMap<&'static str, std::collections::VecDeque<&'static str>>,
1542    motion_child_visual: Option<(u64, motion_layout::MotionChildVisual)>,
1543    /// Active Android Material / Material 3 theme preset; defaults to `AndroidTheme::Bhoo`.
1544    pub theme_style: AndroidTheme,
1545    /// Runtime display density multiplier (`dp` -> logical px). Defaults to `1.0`.
1546    pub density: f32,
1547    /// Runtime font scale multiplier (`sp` = `dp * font_scale`). Defaults to `1.0`.
1548    pub font_scale: f32,
1549    pub dialer_filters: HashMap<String,crate::android_dialer_filter::DialerFilterState>,
1550    pub tab_widget_clicked: HashMap<String,usize>,
1551    pub tab_hosts: HashMap<String,TabHostState>,
1552    tab_host_factory_cache: HashMap<(String,usize),&'static Node>,
1553    active_tab_host: Option<String>,
1554    gallery_gestures: HashMap<String,GalleryGesture>,
1555    gallery_rendered_generation: HashMap<String,u64>,
1556    pub gallery_clicked: HashMap<String,usize>,
1557    /// State for Android SlidingDrawer views, keyed by XML ID.
1558    pub sliding_drawers: HashMap<String,SlidingDrawerState>,
1559    /// Most recently clicked adapter position in a StackView.
1560    pub stack_clicked: HashMap<String,usize>,
1561    /// Runtime loop policy for each StackView. XML defaults to non-looping.
1562    pub stack_looping: HashMap<String,bool>,
1563    stack_gestures: HashMap<String,StackGesture>,
1564    stack_pending_step: HashMap<String,(usize,isize)>,
1565    stack_rendered_generation: HashMap<String,u64>,
1566    /// Override the Android screen-configuration policy for labels beside action icons.
1567    pub menu_allow_text_with_icon: Option<bool>,
1568    /// Host theme's GridLayout default gap in logical pixels. None uses Android's 8dp default.
1569    pub grid_default_gap: Option<f32>,
1570    /// Decoded frames supplied by the host; VideoView does not decode media itself.
1571    pub video_frames: HashMap<String,Image>,
1572    /// Original source dimensions when different from the decoded frame size.
1573    pub video_dimensions: HashMap<String,(u32,u32)>,
1574    /// IDs of videos whose host player is prepared for interaction.
1575    pub video_ready: std::collections::HashSet<String>,
1576    /// Video ID to floating controller ID and height in logical pixels.
1577    pub video_controllers: HashMap<String,(String,f32)>,
1578    pub media_players: HashMap<String,MediaPlayerSnapshot>,
1579    pub media_controller_actions: HashMap<String,MediaControllerAction>,
1580    pub media_controller_capabilities: HashMap<String,MediaControllerCapabilities>,
1581    media_active_capabilities: Option<MediaControllerCapabilities>,
1582    media_seek_progress: HashMap<String,f32>,
1583    media_floating: HashMap<String,MediaControllerFloating>,
1584    /// Host-provided contact targets; no Android contacts provider is accessed.
1585    pub quick_contact_targets: HashMap<String,QuickContactTarget>,
1586    /// Last activated target for each QuickContactBadge.
1587    pub quick_contact_clicked: HashMap<String,QuickContactTarget>,
1588    quick_contact_pressed: HashMap<String,QuickContactTarget>,
1589    pub quick_contact_lookups: HashMap<String,QuickContactLookup>,
1590    pub quick_contact_actions: HashMap<String,QuickContactAction>,
1591    quick_contact_generation: u64,
1592    /// Layout direction for relative FrameLayout start/end gravity.
1593    pub rtl: bool,
1594    /// Per-table overrides for Android TableLayout.setColumnCollapsed.
1595    pub table_collapsed: HashMap<(u64,usize),bool>,
1596    pub text: HashMap<String, String>,
1597    pub input_types: HashMap<String, u8>,
1598    /// Calendar widget state keyed by Android view ID.
1599    pub calendars: HashMap<String,crate::android_calendar::CalendarState>,
1600    /// NumberPicker values and displayed labels supplied by the host.
1601    pub number_pickers: HashMap<String,crate::android_number_picker::NumberPickerState>,
1602    pub date_spinners: HashMap<String,crate::android_date_spinner::DateSpinnerState>,
1603    pub time_spinners: HashMap<String,crate::android_time_spinner::TimeSpinnerState>,
1604    /// Expanded state, submit-button policy and last submitted query per SearchView ID.
1605    /// Caller-supplied groups and most recent user event for each expandable list.
1606    pub expandable_lists: HashMap<String,crate::android_expandable_list::ExpandableListState>,
1607    pub expandable_events: HashMap<String,crate::android_expandable_list::ExpandableEvent>,
1608    /// Most recent Toolbar navigation action, keyed by XML view ID.
1609    pub toolbar_navigation_clicked: std::collections::HashSet<String>,
1610    pub toolbar_title_colors: HashMap<String,Color>,
1611    pub toolbar_subtitle_colors: HashMap<String,Color>,
1612    /// Toolbar menu entries supplied by the host, in display order.
1613    pub toolbar_menu_items: HashMap<String,Vec<AndroidToolbarMenuItem>>,
1614    /// The ID of the last activated menu item for each toolbar.
1615    pub toolbar_menu_clicked: HashMap<String,u64>,
1616    toolbar_menu_overlays: HashMap<String,OverlayState>,
1617    /// Group IDs whose clicks are handled by the host before expansion.
1618    pub expandable_intercepted_groups: HashMap<String,std::collections::HashSet<u64>>,
1619    /// Most recent group position clicked, including intercepted clicks.
1620    pub expandable_group_clicked: HashMap<String,usize>,
1621    expandable_templates: HashMap<String,(Option<ListItemTemplate>,Option<ListItemTemplate>)>,
1622    expandable_bindings: HashMap<String,HashMap<(u64,Option<u64>),AdapterItemBinding>>,
1623    expandable_control_states: HashMap<(String,u64,Option<u64>),HashMap<String,bool>>,
1624    adapter_namespace: Option<u64>,
1625    /// Last XML control activated within an expandable row.
1626    pub expandable_control_events: HashMap<String,(crate::android_expandable_list::FlatPosition,&'static str)>,
1627    pub search_open: HashMap<String,bool>,
1628    pub search_submit_enabled: std::collections::HashSet<String>,
1629    pub search_submitted: HashMap<String,String>,
1630    /// Last activated local suggestion index for each SearchView.
1631    pub search_suggestion_clicked: HashMap<String,usize>,
1632    /// Minimum query length before showing local suggestions; defaults to one.
1633    pub search_suggestion_threshold: HashMap<String,usize>,
1634    // Keep the original filter while keyboard selection previews suggestion text.
1635    search_suggestion_preview: HashMap<String,(String,String)>,
1636    search_pending: std::collections::HashSet<String>,
1637    search_focus_requested: std::collections::HashSet<String>,
1638    pub time_clocks: HashMap<String,crate::android_time_clock::TimeClockState>,
1639    time_clock_dragging: std::collections::HashSet<String>,
1640    time_clock_transition: HashMap<String,TimeClockTransition>,
1641    pub time_clock_text_mode: std::collections::HashSet<String>,
1642    time_clock_field_owner: HashMap<String,(String,crate::android_time_clock::DialPart)>,
1643    time_clock_invalid: std::collections::HashSet<String>,
1644    time_clock_changed: std::collections::HashSet<String>,
1645    number_picker_motion: HashMap<String,NumberPickerMotion>,
1646    /// Fields currently showing the host text editor.
1647    pub number_picker_editing: std::collections::HashSet<String>,
1648    number_picker_committed: std::collections::HashSet<String>,
1649    /// Localized Gregorian labels and default week start, supplied by the host.
1650    pub calendar_locale: crate::android_calendar::CalendarLocale,
1651    calendar_motion: HashMap<String,CalendarMotion>,
1652    datepicker_year_open: std::collections::HashSet<String>,
1653    datepicker_year_scroll: HashMap<String,f32>,
1654    datepicker_fades: HashMap<String,DatePickerFade>,
1655    autocomplete_items: HashMap<String,Vec<String>>,
1656    /// UTF-16 selection end supplied by the host text editor.
1657    pub text_selection_end: HashMap<String,usize>,
1658    /// Fields configured by the host with Android’s comma tokenizer.
1659    pub comma_tokenizers: std::collections::HashSet<String>,
1660    autocomplete_matches: HashMap<String,AutoMatches>,
1661    autocomplete_anchor: Option<AutoAnchor>,
1662    autocomplete_open: Option<String>,
1663    autocomplete_panel: Option<Rect>,
1664    autocomplete_dismissed: HashMap<String,String>,
1665    autocomplete_highlight: HashMap<String,usize>,
1666    autocomplete_scroll: HashMap<String,f32>,
1667    /// Most recently selected suggestion index, keyed by field ID.
1668    pub autocomplete_selected: HashMap<String,usize>,
1669    /// Decoded drawable images supplied by the application, keyed by resource name.
1670    pub images: HashMap<String, crate::Image>,
1671    /// Source pixel size in density-independent units per drawable.
1672    pub image_scales: HashMap<String, f32>,
1673    /// Axis-aligned matrix scale and translation (sx, sy, tx, ty), keyed by view ID.
1674    pub image_matrices: HashMap<String, [f32; 4]>,
1675    pub drawable_tints: HashMap<String,AndroidDrawableTint>,
1676    /// Runtime drawable-name overrides by ImageView ID.
1677    pub image_sources: HashMap<String, String>,
1678    /// Application-owned selected and activated state for Android views.
1679    pub view_selected: HashMap<String,bool>,
1680    pub view_activated: HashMap<String,bool>,
1681    /// Caller-owned MaterialCardView dragged states, keyed by XML ID.
1682    pub view_dragged: HashMap<String,bool>,
1683    #[doc(hidden)] pub tinted_images: HashMap<(u32,[u8;4],u8),Image>,
1684    #[doc(hidden)] pub tinted_image_bytes: usize,
1685    /// Per-view long-press repeat deadline and whether repetition started.
1686    pub zoom_holds: HashMap<u64,(f64,bool,bool)>,
1687    /// ZoomButton repeat intervals in milliseconds, keyed by XML view ID.
1688    /// The default is 1000 ms; zero is limited to 1 ms to avoid a busy loop.
1689    pub zoom_speed_ms: HashMap<String,u64>,
1690    /// Per-control enabled state for the zoom-out and zoom-in buttons.
1691    pub zoom_controls_enabled: HashMap<String,[bool;2]>,
1692    /// Most recent action for a rendered ZoomControls: -1 out or 1 in.
1693    pub zoom_controls_actions: HashMap<String,i8>,
1694    pub zoom_controls_fades: HashMap<String,ZoomControlsFade>,
1695    pub checked: HashMap<String, bool>,
1696    /// Adapter entries and selected index for Android Spinner views.
1697    pub spinner_items: HashMap<String,Vec<String>>,
1698    pub spinner_selected: HashMap<String,usize>,
1699    /// Optional stable IDs supplied alongside adapter entries.
1700    pub spinner_item_ids: HashMap<String,Vec<i64>>,
1701    /// Optional per-item enabled flags; missing positions are enabled.
1702    pub spinner_enabled: HashMap<String,Vec<bool>>,
1703    /// Host-supplied ListView adapter labels, checked indices, and last click.
1704    pub list_items: HashMap<String,Vec<String>>,
1705    /// Optional unique stable IDs corresponding to ListView adapter items.
1706    pub list_item_ids: HashMap<String,Vec<i64>>,
1707    pub list_checked: HashMap<String,Vec<usize>>,
1708    list_control_states: HashMap<String,HashMap<i64,HashMap<String,bool>>>,
1709    list_edit_states: HashMap<String,HashMap<i64,HashMap<String,String>>>,
1710    list_kept_alive_focus: HashMap<String,(i64,u64,bool)>,
1711    row_scratch: RowScratchState,
1712    /// Most recent ListView child-control activation, as adapter position and XML view ID.
1713    pub list_control_clicked: HashMap<String,(usize,&'static str)>,
1714    pub list_clicked: HashMap<String,usize>,
1715    list_item_bindings: HashMap<String,HashMap<usize,AdapterItemBinding>>,
1716    /// Enable and retrieve handled item long presses by ListView ID.
1717    pub list_long_click_enabled: HashMap<String,bool>,
1718    pub list_long_clicked: HashMap<String,usize>,
1719    list_holds: HashMap<String,Option<ListHold>>,
1720    /// Missing item enabled flags default to true.
1721    pub list_enabled: HashMap<String,Vec<bool>>,
1722    /// Most recent selectable fixed-view click: (is_footer, index within that group).
1723    pub list_fixed_clicked: HashMap<String,(bool,usize)>,
1724    /// Most recent control activation in a fixed view: footer flag, view index, XML ID.
1725    pub list_fixed_control_clicked: HashMap<String,(bool,usize,&'static str)>,
1726    list_fixed_control_states: HashMap<(String,bool,usize),HashMap<String,bool>>,
1727    list_fixed_views: HashMap<String,(Vec<ListFixedView>,Vec<ListFixedView>)>,
1728    adapter_root_response: Option<(u64,Response)>,
1729    list_templates: HashMap<String,ListItemTemplate>,
1730    list_text_geometry: HashMap<String,std::sync::Arc<ListTextGeometry>>,
1731    list_pending_focus: HashMap<String,usize>,
1732    spinner_templates: HashMap<String,SpinnerItemTemplates>,
1733    spinner_row_cache: HashMap<String,(u64,std::sync::Arc<Vec<f32>>)>,
1734    spinner_highlight: HashMap<String,usize>,
1735    spinner_scroll: HashMap<String,crate::scroll::ScrollPhysics>,
1736    pub spinner_open: Option<String>,
1737    spinner_anchor: Option<SpinnerAnchor>,
1738    spinner_dialogs: HashMap<String,OverlayState>,
1739    spinner_closing: Option<String>,
1740    pub radio_groups: HashMap<u64, Option<u64>>,
1741    radio_group_requests: HashMap<String, Option<String>>,
1742    radio_group_events: HashMap<String, Vec<Option<u64>>>,
1743    pub progress: HashMap<String, f32>,
1744    pub secondary_progress: HashMap<String, f32>,
1745    pub ratings: HashMap<String, f32>,
1746    pub offsets: HashMap<String, f32>,
1747    expandable_scrolls: HashMap<String, crate::android_expandable_list::ExpansionScroll>,
1748    expandable_pending_scroll: HashMap<String,u64>,
1749    expandable_geometry: HashMap<String,std::sync::Arc<ListTextGeometry>>,
1750    /// Displayed child index for ViewAnimator and ViewSwitcher, keyed by view ID.
1751    pub displayed_children: HashMap<String, usize>,
1752    pub transitions: HashMap<u64, ViewTransition>,
1753    pub flipper_running: HashMap<String, bool>,
1754    /// Most recent clicked adapter position for an AdapterViewFlipper.
1755    pub adapter_flipper_clicked: HashMap<String,usize>,
1756    /// Flippers advanced by their host rather than by their own timer.
1757    pub adapter_flipper_host_advanced: std::collections::HashSet<String>,
1758    adapter_flipper_data_generation: HashMap<String,u64>,
1759    adapter_flipper_rendered_generation: HashMap<String,u64>,
1760    adapter_flipper_animated: std::collections::HashSet<String>,
1761    pub flipper_clocks: HashMap<u64, FlipperClock>,
1762    pub chronometers: HashMap<String, ChronometerState>,
1763    /// Wall-clock snapshot supplied by the host, including local UTC offset.
1764    pub wall_clock: Option<WallClock>,
1765    /// Runtime overrides for views with Android IDs.
1766    pub visibility: HashMap<String, Visibility>,
1767    /// Per-field password visibility toggle state for TextInputLayout password_toggle end icon.
1768    text_input_password_visible: HashMap<String, bool>,
1769    /// Active TextInputLayout box context while rendering its EditText child.
1770    text_input_active_box: Option<TextInputChildBox>,
1771    /// Selected destination index for `RULE_NAV_BAR` containers (`bar`/`rail`/`drawer`), keyed by XML ID.
1772    pub selected_index: HashMap<String, usize>,
1773    /// Runtime badges for `RULE_NAV_BAR` destinations (`bar`/`rail`), keyed by nav item XML ID.
1774    /// Empty string `""` renders a 6dp circular dot badge; non-empty text renders a 16dp pill badge.
1775    pub nav_badges: HashMap<String, String>,
1776    /// Refreshing state for `RULE_SWIPE_REFRESH` (`SwipeRefreshLayout`) containers, keyed by XML ID.
1777    pub refreshing: HashMap<String, bool>,
1778    /// Open state for `RULE_DRAWER_LAYOUT` (`DrawerLayout`) containers, keyed by XML ID.
1779    pub drawer_open: HashMap<String, bool>,
1780    /// Lock mode for `RULE_DRAWER_LAYOUT` (`DrawerLayout`) drawers, keyed by `"{id}"` (start) and `"{id}:end"` (end).
1781    /// Values: `0 = UNLOCKED`, `1 = LOCKED_CLOSED`, `2 = LOCKED_OPEN`, `3 = UNDEFINED`.
1782    pub drawer_lock_mode: HashMap<String, u8>,
1783    /// Active DrawerLayout drawer panel context while rendering a drawer child.
1784    drawer_panel_active: bool,
1785    /// Active MaterialButtonToggleGroup segment context while rendering a child button.
1786    toggle_group_segment: Option<ToggleGroupSegment>,
1787    /// Toggle groups whose initial `checked_id` / child `checked` flags have been seeded into `state.checked`.
1788    toggle_groups_initialized: std::collections::HashSet<u64>,
1789    /// Two-thumb values `[start, end]` for `RULE_RANGE_SLIDER` (`RangeSlider`) views, keyed by XML ID.
1790    pub range_values: HashMap<String, [f32; 2]>,
1791    /// Active dragged thumb index (`0` or `1`) for `RULE_RANGE_SLIDER`, keyed by view ID.
1792    range_slider_active_thumb: HashMap<u64, usize>,
1793    /// Interactive swipe/settle gesture state for `RULE_VIEW_PAGER` views, keyed by XML ID.
1794    view_pager_gestures: HashMap<String, ViewPagerGesture>,
1795    /// Scroll offset from sibling scrolling view propagated to `RULE_COLLAPSING_TOOLBAR`.
1796    collapsing_scroll_offset: Option<f32>,
1797    /// Active CollapsingToolbarLayout context while rendering a child Toolbar.
1798    collapsing_toolbar_child: bool,
1799    /// Sheet state for `RULE_BOTTOM_SHEET` / `RULE_SIDE_SHEET` views, keyed by XML ID
1800    /// (`SHEET_STATE_EXPANDED=3`, `SHEET_STATE_COLLAPSED=4`, `SHEET_STATE_HIDDEN=5`, `SHEET_STATE_HALF_EXPANDED=6`).
1801    pub sheet_state: HashMap<String, u8>,
1802    /// Exposed dropdown menu entries for `TextInputLayout` (`end_icon == "dropdown_menu"`), keyed by child Edit ID.
1803    pub entries: HashMap<String, Vec<String>>,
1804    /// Per-node morph state for `RULE_LOADING_INDICATOR` (`LoadingIndicator`) views.
1805    loading_states: HashMap<u64, crate::loading::LoadingState>,
1806    /// Currently open `TextInputLayout` exposed dropdown key.
1807    til_dropdown_open: Option<String>,
1808    /// Anchor metadata for open `TextInputLayout` exposed dropdown popup.
1809    til_dropdown_anchor: Option<TilDropdownAnchor>,
1810    /// Rendered popup bounds for open `TextInputLayout` exposed dropdown.
1811    til_dropdown_panel: Option<Rect>,
1812    /// Horizontal scroll offsets for scrollable `RULE_TAB_OPTIONS` tab strips, keyed by XML ID.
1813    tab_scroll_offsets: HashMap<String, f32>,
1814    /// Active `RULE_SNACKBAR` context while rendering Snackbar children.
1815    snackbar_active: bool,
1816    /// Active `RULE_SPLIT_BUTTON` segment role while rendering split button child buttons.
1817    split_button_role: Option<SplitButtonRole>,
1818    /// `RULE_CHIP_GROUP_WRAP` groups whose initial single-selection exclusion has been seeded.
1819    chip_groups_initialized: std::collections::HashSet<u64>,
1820    /// Two-way synchronization links between `TabWidget` (`TabLayout`) and `RULE_VIEW_PAGER` (`ViewPager2`) XML IDs.
1821    pub tab_pager_links: HashMap<String, String>,
1822    /// Interactive drag and settle motion state for `RULE_BOTTOM_SHEET` and modal `RULE_SIDE_SHEET` views.
1823    sheet_motion: HashMap<String, XmlSheetMotion>,
1824    /// Animated slide-in/out and drag-to-close motion state for `RULE_DRAWER_LAYOUT` containers.
1825    drawer_motion: HashMap<String, XmlDrawerMotion>,
1826    /// Active `RULE_BOTTOM_SHEET` key while rendering its children (for `RULE_DRAG_HANDLE` click toggle).
1827    active_bottom_sheet: Option<String>,
1828    /// Set when a `RULE_DRAG_HANDLE` child inside an active bottom sheet is clicked without dragging.
1829    drag_handle_toggled: bool,
1830    /// Last observed tab selection per `TabWidget` key to synchronize `selected_index` and `displayed_children`.
1831    tab_last_index: HashMap<String, usize>,
1832    /// Runtime alpha multiplier overrides (`0.0..=1.0`, matching Android `View.setAlpha`), keyed by XML ID.
1833    pub view_alpha: HashMap<String, f32>,
1834    /// Runtime scale overrides `[sx, sy]` (matching Android `View.setScaleX`/`setScaleY`), keyed by XML ID.
1835    pub view_scale: HashMap<String, [f32; 2]>,
1836    /// Runtime translation overrides `[tx_dp, ty_dp]` (matching Android `View.setTranslationX`/`setTranslationY`), keyed by XML ID.
1837    pub view_translation: HashMap<String, [f32; 2]>,
1838    /// Camera projection distances in Skia points, keyed by XML ID.
1839    view_camera_distance: HashMap<String, f32>,
1840    /// Bounded cache of rasterized radial/sweep (and cut-corner linear) gradient images.
1841    gradient_images: HashMap<GradientCacheKey, Image>,
1842    gradient_image_bytes: usize,
1843    /// Bounded cache of rasterized chamfered cut-corner shape fills.
1844    cut_shape_images: HashMap<CutShapeCacheKey, Image>,
1845    cut_shape_image_bytes: usize,
1846    /// Smooth liftOnScroll transition progress per AppBarLayout / Toolbar XML ID.
1847    app_bar_lift_motion: HashMap<String, XmlLiftMotion>,
1848    /// Active lifted AppBarLayout context while rendering its child Toolbar.
1849    lifted_appbar_active: bool,
1850    /// Dynamic target sibling XML ID override for `RULE_CONSTRAINT_PLACEHOLDER` views, keyed by placeholder XML ID.
1851    pub placeholder_content: HashMap<String, String>,
1852    /// Scroll-delta collapse tracking for `RULE_APP_BAR_SCROLL_FLAGS` (`enterAlways`) children, keyed by view key.
1853    app_bar_scroll_motion: HashMap<String, AppBarScrollState>,
1854    /// Runtime drawable level (`0..=10000`, Android `Drawable.setLevel`) for `RULE_DRAWABLE_DYNAMIC`, keyed by XML ID.
1855    pub drawable_level: HashMap<String, u32>,
1856    /// Runtime transition state (`false` = layer 0, `true` = layer 1) for `RULE_DRAWABLE_DYNAMIC` `"transition|..."`, keyed by XML ID.
1857    pub drawable_transition_active: HashMap<String, bool>,
1858    /// Internal crossfade animation state for `RULE_DRAWABLE_DYNAMIC` `"transition|..."` drawables.
1859    drawable_transition_motion: HashMap<String, DrawableTransitionMotion>,
1860    /// Suppresses direct-child static `RULE_ELEVATION` when parent `ViewAnimator`/`AdapterViewFlipper` renders an elevation transition.
1861    suppress_next_elevation: bool,
1862    /// Bounded internal state tracking previous 7-bit state masks and active `<animated-selector>` transitions.
1863    animated_selector_states: HashMap<String, AnimatedSelectorState>,
1864    /// Runtime extended/collapsed override for `ExtendedFloatingActionButton`, keyed by node `id`.
1865    pub fab_extended: HashMap<String, bool>,
1866    /// Bounded internal scrim alpha fade motion for `RULE_COLLAPSING_TOOLBAR_EXT`.
1867    collapsing_scrim_motion: HashMap<String, XmlLiftMotion>,
1868    /// Bounded internal expand/collapse width motion for `ExtendedFloatingActionButton`.
1869    extended_fab_motion: HashMap<String, XmlLiftMotion>,
1870    /// Bounded internal hide-on-scroll slide motion for `RULE_BOTTOM_APP_BAR_EXT`.
1871    bottom_app_bar_hide_motion: HashMap<String, BottomAppBarHideState>,
1872    /// Bounded cache of rasterized `BottomAppBar` cradle-cutout surfaces.
1873    bottom_app_bar_images: HashMap<BottomAppBarCradleCacheKey, Image>,
1874    bottom_app_bar_image_bytes: usize,
1875    /// True while entering top-level `Node::render_inner` root `draw` (before descending into children).
1876    at_root_draw: bool,
1877    /// Suppresses double-applying `hide_on_scroll` offset when CoordinatorLayout already shifted `BottomAppBar`.
1878    bab_hide_applied_by_parent: bool,
1879    /// Current frame clock & motion/scroll snapshot for pure layout evaluation (AppBarLayout snap settle).
1880    frame_time: f64,
1881    frame_reduced_motion: bool,
1882    frame_scroll_dragging: bool,
1883    /// Bounded open/close ease-out animation state for `RULE_SEARCH_VIEW_EXT` overlays.
1884    search_view_motion: HashMap<String, XmlLiftMotion>,
1885    /// Transient per-frame `(anchor_bar_id, search_view_key)` coupling table populated at root render.
1886    search_bar_links: Vec<(String, String)>,
1887    /// Bounded pull-to-refresh drag/retract physics state for `RULE_SWIPE_REFRESH` / `RULE_SWIPE_REFRESH_EXT`.
1888    swipe_refresh_motion: HashMap<String, SwipeRefreshMotion>,
1889    /// Bounded drag & focal snap settle state for `RULE_CAROUSEL_LAYOUT` containers.
1890    carousel_motion: HashMap<String, CarouselMotion>,
1891    /// Most recently clicked auto-link span text from `RULE_TEXT_LINKS_SPANS`, overwritten on each link click.
1892    pub last_clicked_link: Option<String>,
1893    /// Performance and retention counters for Android XML adapter lists.
1894    pub list_perf: ListPerfStats,
1895}
1896
1897mod constraint_layout;
1898mod draw;
1899mod draw_adapter_views;
1900mod draw_containers;
1901mod motion_layout;
1902pub use motion_layout::{MotionAutoTransition, MotionClick, MotionClickAction, MotionConstraintSet, MotionCustomTrack, MotionCustomValue, MotionNativeValue, MotionSizeBound, MotionSizeValue, MotionSizeMode, MotionChainStyle, MotionDimensionUnit, MotionCycleKey, MotionCycleTrack, MotionOffsetUnit, MotionWave, MotionEasing, MotionKeyTrigger, MotionPathArc, MotionPositionKey, MotionPositionMode, MotionPositionTrack, MotionProperty, MotionPropertyTrack, MotionQuantizer, MotionScene, MotionStateVariant, MotionResponsivePair, MotionSpringConfig, MotionSwipe, MotionSwipeDirection, MotionSwipeRelease, MotionSwipeSide, MotionTransition, MotionTransitionEvent, MotionTransitionEventKind, MotionViewTransition, MotionViewTouch, MotionTriggerEvent};
1903pub use motion_layout::{MotionSharedValues, MotionSharedValuesListener};
1904pub use motion_layout::MotionLayoutPolicy;
1905mod draw_widgets;
1906mod drawables;
1907mod helpers;
1908mod measure;
1909mod render;
1910mod specs;
1911mod state;
1912mod text;
1913
1914use constraint_layout::*;
1915use drawables::*;
1916use helpers::*;
1917use specs::*;
1918use text::*;
1919pub use helpers::{quick_contact_default_avatar, view_id};
1920
1921#[cfg(test)]
1922mod object_animation_offset_tests {
1923    use super::*;
1924    #[test]
1925    fn object_delays_leave_properties_at_identity_and_each_axis_has_own_timing() {
1926        let a=AlphaAnimation{from:0.0,to:1.0,duration:0.4,start_offset:0.2,linear:true};
1927        assert_eq!(a.sample(0.1,true),1.0);
1928        assert_eq!(a.sample(0.1,false),0.0);
1929        assert!((a.sample(0.4,true)-0.5).abs()<0.001);
1930        let zero=AnimationDelta{value:0.0,mode:0};
1931        let t=TranslateAnimation{deltas:[AnimationDelta{value:40.0,mode:0},zero,AnimationDelta{value:20.0,mode:0},zero],duration:0.4,start_offset:0.2,linear:true,y_timing:Some((0.4,true,0.5))};
1932        let b=Rect{x:0.,y:0.,width:100.,height:100.};
1933        assert_eq!(t.sample(0.1,b,b,true),[0.0,0.0]);
1934        assert_eq!(t.sample(0.1,b,b,false),[40.0,20.0]);
1935        let v=t.sample(0.4,b,b,true);assert!((v[0]-20.0).abs()<0.001);assert_eq!(v[1],0.0);
1936        let v=t.sample(0.7,b,b,true);assert_eq!(v[0],0.0);assert!((v[1]-10.0).abs()<0.001);
1937        assert!((t.total_duration()-0.9).abs()<0.001);
1938    }
1939}