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 <= 1.0 {
257        1
258    } else if dp <= 3.0 {
259        2
260    } else if dp <= 6.0 {
261        3
262    } else if dp <= 8.0 {
263        4
264    } else {
265        5
266    }
267}
268/// Paint a discrete Material elevation shadow with geometry scaled by `density`.
269fn paint_elevation_level(f: &mut Frame<'_>, bounds: Rect, radius: f32, level: u8, density: f32) {
270    paint_elevation_level_alpha(f, bounds, radius, level, density, 1.0);
271}
272/// Paint a discrete Material elevation shadow with alpha modulated by `alpha_scale`.
273fn paint_elevation_level_alpha(
274    f: &mut Frame<'_>,
275    bounds: Rect,
276    radius: f32,
277    level: u8,
278    density: f32,
279    alpha_scale: f32,
280) {
281    let scale = alpha_scale.clamp(0.0, 1.0);
282    if scale <= 0.001 {
283        return;
284    }
285    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
286    let black = Color(0, 0, 0, 255);
287    let specs = if level >= 6 {
288        [
289            (0.0, 3.0, 5.0, -1.0, 0.2),
290            (0.0, 6.0, 10.0, 0.0, 0.14),
291            (0.0, 1.0, 18.0, 0.0, 0.12),
292        ]
293    } else if level <= 1 {
294        [
295            (0.0, 2.0, 1.0, -1.0, 0.2),
296            (0.0, 1.0, 1.0, 0.0, 0.14),
297            (0.0, 1.0, 3.0, 0.0, 0.12),
298        ]
299    } else {
300        [
301            (0.0, 3.0, 1.0, -2.0, 0.2),
302            (0.0, 2.0, 2.0, 0.0, 0.14),
303            (0.0, 1.0, 5.0, 0.0, 0.12),
304        ]
305    };
306    for (x, y, blur, spread, alpha) in specs {
307        f.shadow(bounds, radius, [x * d, y * d], blur * d, spread * d, black.opacity(alpha * scale));
308    }
309}
310/// Paint a continuous Android elevation (in unscaled dp) with shadow geometry scaled by `density`.
311fn paint_elevation_dp(f: &mut Frame<'_>, bounds: Rect, radius: f32, dp: f32, density: f32) {
312    if !dp.is_finite() || dp <= 0.0 {
313        return;
314    }
315    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
316    const LOW: [[f32; 5]; 3] = [[0., 2., 1., -1., 0.2], [0., 1., 1., 0., 0.14], [0., 1., 3., 0., 0.12]];
317    const MID: [[f32; 5]; 3] = [[0., 3., 1., -2., 0.2], [0., 2., 2., 0., 0.14], [0., 1., 5., 0., 0.12]];
318    const HIGH: [[f32; 5]; 3] = [[0., 3., 5., -1., 0.2], [0., 6., 10., 0., 0.14], [0., 1., 18., 0., 0.12]];
319    let (a, b_spec, t) = if dp <= 1.0 {
320        (LOW, LOW, 0.0)
321    } else if dp <= 2.0 {
322        (LOW, MID, dp - 1.0)
323    } else {
324        (MID, HIGH, ((dp - 2.0) / 4.0).min(1.0))
325    };
326    let scale = (if dp > 6.0 { (dp / 6.0).sqrt().min(2.0) } else { 1.0 }) * d;
327    for i in 0..3 {
328        let p = std::array::from_fn::<_, 5, _>(|j| a[i][j] + (b_spec[i][j] - a[i][j]) * t);
329        f.shadow(
330            bounds,
331            radius,
332            [p[0] * scale, p[1] * scale],
333            p[2] * scale,
334            p[3] * scale,
335            Color(0, 0, 0, 255).opacity(p[4] * dp.min(1.0)),
336        );
337    }
338}
339/// Subtle 2dp resting shadow for AOSP `Widget.Material.Button` (`btn_default_material`).
340/// Scaled by `density` to match Android's ~2px top / ~3px bottom / <=4px side halo (~9-12% peak alpha)
341/// without overflowing the 4dp horizontal button inset.
342fn paint_material_button_shadow(f: &mut Frame<'_>, bounds: Rect, radius: f32, density: f32) {
343    let d = if density.is_finite() && density > 0.0 { density } else { 1.0 };
344    let black = Color(0, 0, 0, 255);
345    f.shadow(bounds, radius, [0.0, 0.25 * d], 2.8 * d, 0.0, black.opacity(0.07));
346    f.shadow(bounds, radius, [0.0, 1.0 * d], 2.0 * d, 0.0, black.opacity(0.07));
347}
348/// A ColorStateList entry: enabled, pressed, focused, selected, activated,
349/// hovered and checked are encoded in bits 0 through 6 respectively.
350#[derive(Clone, Copy)]
351pub struct TintState { pub required:u8, pub forbidden:u8, pub color:Color }
352/// One RelativeLayout rule; sibling anchors are Android XML IDs.
353#[derive(Clone, Copy)]
354pub struct RelativeRule { pub kind:u16, pub anchor:&'static str }
355/// RelativeRule kind for `android:elevation` in dp (e.g. `"4"`).
356pub const RULE_ELEVATION: u16 = 193;
357/// RelativeRule kind for `android:backgroundTint` as `"r,g,b,a"` (e.g. `"255,0,0,255"`).
358pub const RULE_BACKGROUND_TINT: u16 = 194;
359/// RelativeRule kind for `android:textAlignment` (`"start"`, `"center"`, `"end"`, `"left"`, `"right"`).
360pub const RULE_TEXT_ALIGNMENT: u16 = 195;
361/// ConstraintLayout `app:layout_constraintStart_toStartOf` (`"parent"` or sibling XML ID).
362pub const RULE_CONSTRAINT_START_TO_START: u16 = 196;
363/// ConstraintLayout `app:layout_constraintStart_toEndOf` (`"parent"` or sibling XML ID).
364pub const RULE_CONSTRAINT_START_TO_END: u16 = 197;
365/// ConstraintLayout `app:layout_constraintEnd_toEndOf` (`"parent"` or sibling XML ID).
366pub const RULE_CONSTRAINT_END_TO_END: u16 = 198;
367/// ConstraintLayout `app:layout_constraintEnd_toStartOf` (`"parent"` or sibling XML ID).
368pub const RULE_CONSTRAINT_END_TO_START: u16 = 199;
369/// ConstraintLayout `app:layout_constraintTop_toTopOf` (`"parent"` or sibling XML ID).
370pub const RULE_CONSTRAINT_TOP_TO_TOP: u16 = 200;
371/// ConstraintLayout `app:layout_constraintTop_toBottomOf` (`"parent"` or sibling XML ID).
372pub const RULE_CONSTRAINT_TOP_TO_BOTTOM: u16 = 201;
373/// ConstraintLayout `app:layout_constraintBottom_toBottomOf` (`"parent"` or sibling XML ID).
374pub const RULE_CONSTRAINT_BOTTOM_TO_BOTTOM: u16 = 202;
375/// ConstraintLayout `app:layout_constraintBottom_toTopOf` (`"parent"` or sibling XML ID).
376pub const RULE_CONSTRAINT_BOTTOM_TO_TOP: u16 = 203;
377/// ConstraintLayout `app:layout_constraintHorizontal_bias` (float in `0.0..=1.0`, default `0.5`).
378pub const RULE_CONSTRAINT_HORIZONTAL_BIAS: u16 = 204;
379/// ConstraintLayout `app:layout_constraintVertical_bias` (float in `0.0..=1.0`, default `0.5`).
380pub const RULE_CONSTRAINT_VERTICAL_BIAS: u16 = 205;
381/// Per-corner radii `"tl,tr,br,bl"` in dp for asymmetric rounded rectangles.
382pub const RULE_CORNER_RADII: u16 = 206;
383/// Gradient background (`linear` comma/pipe, `radial|<cx>,<cy>,<radius_dp>|<start>|<center>|<end>`, or `sweep|<cx>,<cy>|<start>|<center>|<end>`).
384pub const RULE_GRADIENT: u16 = 207;
385/// 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"`.
386pub const RULE_DRAWABLE_LAYER: u16 = 208;
387/// Custom ripple color and optional unbounded mask: `"r,g,b,a"` or `"r,g,b,a|unbounded"`.
388pub const RULE_RIPPLE_COLOR: u16 = 209;
389/// ConstraintLayout Guideline orientation (`"vertical"` or `"horizontal"`).
390pub const RULE_GUIDE_ORIENTATION: u16 = 210;
391/// ConstraintLayout Guideline begin offset in dp.
392pub const RULE_GUIDE_BEGIN: u16 = 211;
393/// ConstraintLayout Guideline end offset in dp.
394pub const RULE_GUIDE_END: u16 = 212;
395/// ConstraintLayout Guideline percent offset (`0.0..=1.0`).
396pub const RULE_GUIDE_PERCENT: u16 = 213;
397/// ConstraintLayout horizontal chain style (`"spread"`, `"spread_inside"`, `"packed"`).
398pub const RULE_CHAIN_STYLE_H: u16 = 214;
399/// ConstraintLayout vertical chain style (`"spread"`, `"spread_inside"`, `"packed"`).
400pub const RULE_CHAIN_STYLE_V: u16 = 215;
401/// ConstraintLayout horizontal chain weight (positive float).
402pub const RULE_CONSTRAINT_H_WEIGHT: u16 = 216;
403/// ConstraintLayout vertical chain weight (positive float).
404pub const RULE_CONSTRAINT_V_WEIGHT: u16 = 217;
405/// Explicit override for `android:textAllCaps` (`"true"` or `"false"`), allowing
406/// buttons under Material themes to opt out of default uppercase styling.
407pub const RULE_TEXT_ALL_CAPS: u16 = 218;
408/// ConstraintLayout `app:layout_constraintDimensionRatio` (`"16:9"`, `"H,16:9"`, `"W,4:3"`, `"1.5"`).
409pub const RULE_CONSTRAINT_DIMENSION_RATIO: u16 = 219;
410/// ConstraintLayout `app:layout_constraintWidth_percent` (`0.0..=1.0`).
411pub const RULE_CONSTRAINT_WIDTH_PERCENT: u16 = 220;
412/// ConstraintLayout `app:layout_constraintHeight_percent` (`0.0..=1.0`).
413pub const RULE_CONSTRAINT_HEIGHT_PERCENT: u16 = 221;
414/// ConstraintLayout `app:layout_constraintBaseline_toBaselineOf` (sibling XML ID).
415pub const RULE_CONSTRAINT_BASELINE_TO_BASELINE: u16 = 222;
416/// ConstraintLayout gone margins `"l,t,r,b,s,e"` (6-value), `"l,t,r,b,s,e,baseline"` (7-value),
417/// or `"s,t,e,b,baseline"` (5-value) in dp (`< 0.0` or empty means unset).
418pub const RULE_CONSTRAINT_GONE_MARGINS: u16 = 223;
419/// Alias for `RULE_CONSTRAINT_GONE_MARGINS` (`223`).
420pub const RULE_CONSTRAINT_GONE_MARGIN: u16 = RULE_CONSTRAINT_GONE_MARGINS;
421/// ConstraintLayout Barrier `"<dir>:<id1>,<id2>,..."` or `"<dir>|<id1>,<id2>,...|<margin_dp>|<allows_gone:0|1>"` (`start|end|left|right|top|bottom`).
422pub const RULE_BARRIER: u16 = 224;
423/// Alias for `RULE_BARRIER` (`224`).
424pub const RULE_CONSTRAINT_BARRIER: u16 = RULE_BARRIER;
425/// ConstraintLayout Group `"<id1>,<id2>,..."` (propagates `Gone`/`Invisible` to referenced siblings).
426pub const RULE_GROUP_REFS: u16 = 225;
427/// CoordinatorLayout scrolling view behavior (`app:layout_behavior` scrolling below top app bar).
428pub const RULE_COORDINATOR_SCROLL_BEHAVIOR: u16 = 226;
429/// CoordinatorLayout anchor placement `"<target_id>:<gravity_tokens>"` (e.g. `"appbar:bottom|end"`).
430pub const RULE_COORDINATOR_ANCHOR: u16 = 227;
431/// Material TextInputLayout box chrome `"<mode>|<corner_dp>|<stroke_rgba>|<hint>|<helper>|<error_enabled>|<end_icon>"`.
432pub const RULE_TEXT_INPUT_BOX: u16 = 228;
433/// MaterialButton / Button visual variant (`"filled"`, `"outlined"`, `"tonal"`, `"text"`, `"elevated"`).
434pub const RULE_BUTTON_VARIANT: u16 = 229;
435/// Material 3 Chip style `"<kind>|<close_visible>"` (e.g. `"filter|1"`).
436pub const RULE_CHIP_STYLE: u16 = 230;
437/// Stateful drawable layer (repeatable): `"<req_mask>,<forbid_mask>|<l,t,r,b>|<radius>|<fill_r,g,b,a>|<stroke_w,sr,sg,sb,sa>"`.
438pub const RULE_STATEFUL_DRAWABLE_LAYER: u16 = 231;
439/// ConstraintLayout Flow helper:
440/// - legacy: `"<orient:0|1>|<wrap:none|chain|aligned>|<h_gap_dp>|<v_gap_dp>|<max_wrap>|<id1>,<id2>,..."`
441/// - compact/extended: `"<orient:h|v>|<wrap:none|chain|aligned>|<hgap_dp>,<vgap_dp>|<id1>,<id2>,...[|<hstyle>,<vstyle>,<hbias>,<vbias>,<halign>,<valign>,<max_wrap>]"`.
442pub const RULE_FLOW: u16 = 232;
443/// ConstraintLayout circular positioning `"<target_id>,<radius_dp>,<angle_deg>"` (0 deg = 12 o'clock, clockwise).
444pub const RULE_CONSTRAINT_CIRCLE: u16 = 233;
445/// Clips child draw commands inside the view's rounded outline bounds (`"true"`).
446pub const RULE_CLIP_TO_OUTLINE: u16 = 234;
447/// Explicit text line height in dp/sp (positive float).
448pub const RULE_LINE_HEIGHT: u16 = 235;
449/// Android `includeFontPadding` override (`"true"` or `"false"`).
450pub const RULE_INCLUDE_FONT_PADDING: u16 = 236;
451/// Material 3 navigation container `"<kind:bar|rail|drawer>|<label_mode:auto|labeled|selected|unlabeled>"`.
452pub const RULE_NAV_BAR: u16 = 237;
453/// Material 3 navigation item (repeatable) `"<id>|<title>|<icon_name_or_empty>"`.
454pub const RULE_NAV_ITEM: u16 = 238;
455/// Material 3 SearchBar hint text `"<hint>"` on `Kind::SearchView`.
456pub const RULE_SEARCH_BAR: u16 = 239;
457/// MaterialButtonToggleGroup `"<single_selection:0|1>|<selection_required:0|1>|<checked_id>"`.
458pub const RULE_TOGGLE_GROUP: u16 = 240;
459/// Material 3 ExtendedFloatingActionButton `"<extended:0|1>"` on `Kind::Button`.
460pub const RULE_EXTENDED_FAB: u16 = 242;
461/// Material 3 BottomAppBar `"<fab_alignment:center|end>"` on `Kind::Toolbar`.
462pub const RULE_BOTTOM_APP_BAR: u16 = 243;
463/// Material 3 navigation destination badge (repeatable) `"<item_id>:<badge_text>"`.
464pub const RULE_NAV_BADGE: u16 = 244;
465/// Material 3 CollapsingToolbarLayout `"<title>|<expanded_h_dp>|<scrim_rgba>"` on `Kind::Frame`.
466pub const RULE_COLLAPSING_TOOLBAR: u16 = 245;
467/// AndroidX SwipeRefreshLayout container marker on `Kind::Frame`.
468pub const RULE_SWIPE_REFRESH: u16 = 246;
469/// AndroidX DrawerLayout container marker on `Kind::Frame`.
470pub const RULE_DRAWER_LAYOUT: u16 = 247;
471/// AndroidX ViewPager / ViewPager2 orientation `"<horizontal|vertical>"` on `Kind::ViewFlipper`.
472pub const RULE_VIEW_PAGER: u16 = 248;
473/// Material 3 RangeSlider initial two-thumb values `"<v0>,<v1>"` on `Kind::SeekBar`.
474pub const RULE_RANGE_SLIDER: u16 = 250;
475/// Static background bitmap/9-patch image `"<image_key>|<stretch_spec>"` (`stretch_spec` = `""` or `"sx0,sx1,...;sy0,sy1,..."`).
476pub const RULE_BACKGROUND_IMAGE: u16 = 251;
477/// Nine-patch stretch bands `"sx0,sx1,...;sy0,sy1,..."` (stripped image pixel coordinates, even count >= 2 per axis) on `ImageView`/`ImageButton`.
478pub const RULE_IMAGE_NINE_PATCH: u16 = 252;
479/// Stateful image `src` `<selector>` entry (repeatable in match order): `"<req_mask>,<forbid_mask>|<image_key>|<stretch_spec>"`.
480pub const RULE_STATEFUL_IMAGE_SRC: u16 = 253;
481/// Stateful background image `<selector>` entry (repeatable in match order): `"<req_mask>,<forbid_mask>|<image_key>|<stretch_spec>"`.
482pub const RULE_STATEFUL_BG_IMAGE: u16 = 254;
483/// RTL horizontal mirroring marker (`"true"`) from `android:autoMirrored="true"`.
484pub const RULE_AUTO_MIRRORED: u16 = 255;
485/// 2D view transform `"<tx_dp>,<ty_dp>,<sx>,<sy>,<rot_deg>,<px>,<py>"` (`px`/`py` `"center"`, `"<pct>%"`, or float dp).
486pub const RULE_VIEW_TRANSFORM: u16 = 256;
487/// Extended text styling `"<italic:0|1>|<family:sans|serif|mono>"`.
488pub const RULE_TEXT_STYLE_EXT: u16 = 257;
489/// Material tooltip text from `android:tooltipText`.
490pub const RULE_TOOLTIP_TEXT: u16 = 258;
491/// Material 3 BottomSheet behavior `"<peek_h_dp>|<hideable:0|1>|<fit_to_contents:0|1>|<half_ratio>|<skip_collapsed:0|1>"`.
492pub const RULE_BOTTOM_SHEET: u16 = 259;
493/// Material 3 BottomSheetDragHandleView pill marker (`""`).
494pub const RULE_DRAG_HANDLE: u16 = 260;
495/// Material 3 SideSheet behavior `"<edge:end|start>|<coplanar:0|1>"`.
496pub const RULE_SIDE_SHEET: u16 = 261;
497/// Material 3 Expressive LoadingIndicator `"<contained:0|1>"` on `Kind::ProgressBar`.
498pub const RULE_LOADING_INDICATOR: u16 = 262;
499/// Material 3 Expressive Wavy / flat-with-gap ProgressIndicator `"<wavelength_dp>|<amplitude_dp>|<wave_speed_dp>|<stop_size_dp>|<track_gap_dp>"` on `Kind::ProgressBar`.
500pub const RULE_WAVY_PROGRESS: u16 = 263;
501/// Material 3 AlertDialog container `"<icon_name_or_empty>"` on `Kind::Linear`.
502pub const RULE_ALERT_DIALOG: u16 = 264;
503/// Material 3 Snackbar container (`""`) on `Kind::Linear`.
504pub const RULE_SNACKBAR: u16 = 265;
505/// Material 3 TabLayout options `"<mode:fixed|scrollable>|<style:primary|secondary>|<indicator_rgba>"` on `Kind::TabWidget`.
506pub const RULE_TAB_OPTIONS: u16 = 266;
507/// Material 3 Slider / RangeSlider options `"<step_size>|<min_separation>|<label_behavior:floating|withinBounds|gone|visible>|<expressive:0|1>"` on `Kind::SeekBar`.
508pub const RULE_SLIDER_OPTIONS: u16 = 267;
509/// Material 3 TextInputLayout extensions `"<counter_enabled:0|1>|<counter_max>|<prefix>|<suffix>|<start_icon>"` on `Kind::Linear` with `RULE_TEXT_INPUT_BOX`.
510pub const RULE_TEXT_INPUT_EXT: u16 = 268;
511/// Material 3 ChipGroup wrap & selection `"<single_line:0|1>|<single_selection:0|1>|<h_spacing_dp>|<v_spacing_dp>"` on `Kind::Linear`.
512pub const RULE_CHIP_GROUP_WRAP: u16 = 269;
513/// Material 3 Expressive FloatingToolbar pill container (`""`) on `Kind::Linear`.
514pub const RULE_FLOATING_TOOLBAR: u16 = 270;
515/// Material 3 Expressive MaterialButtonGroup `"<spacing_dp>"` on `Kind::Linear`.
516pub const RULE_BUTTON_GROUP: u16 = 271;
517/// Material 3 Expressive MaterialSplitButton (`""`) on `Kind::Linear`.
518pub const RULE_SPLIT_BUTTON: u16 = 272;
519/// Material 3 Carousel MaskableFrameLayout item (`""`) on `Kind::Frame`.
520pub const RULE_CAROUSEL_ITEM: u16 = 273;
521/// Scale transition animation for incoming `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child:
522/// `"<from_sx>,<to_sx>,<from_sy>,<to_sy>|<px>,<py>|<duration_s>|<start_offset_s>|<linear:0|1>"`.
523pub const RULE_SCALE_IN: u16 = 274;
524/// Scale transition animation for outgoing `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child.
525pub const RULE_SCALE_OUT: u16 = 275;
526/// Rotate transition animation for incoming `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child:
527/// `"<from_deg>,<to_deg>|<px>,<py>|<duration_s>|<start_offset_s>|<linear:0|1>"`.
528pub const RULE_ROTATE_IN: u16 = 276;
529/// Rotate transition animation for outgoing `ViewAnimator`/`ViewSwitcher`/`ViewFlipper`/`AdapterViewFlipper` child.
530pub const RULE_ROTATE_OUT: u16 = 277;
531/// Per-corner family `"<tl>,<tr_>,<br>,<bl>"` where each token is `"r"` (rounded) or `"c"` (cut/chamfered).
532pub const RULE_CORNER_FAMILY: u16 = 278;
533/// AppBarLayout dynamic `liftOnScroll`: `"1"` (auto-detect sibling scroll) or `"1|<target_xml_id>"`.
534pub const RULE_APP_BAR_LIFT_ON_SCROLL: u16 = 279;
535/// ConstraintLayout constrained wrap and min/max bounds `"<cw:0|1>,<ch:0|1>|<wmin_dp>,<wmax_dp>,<hmin_dp>,<hmax_dp>"`.
536pub const RULE_CONSTRAINT_SIZE_BOUNDS: u16 = 280;
537/// ConstraintLayout Layer helper `"<id1>,<id2>,..."` applying shared background, elevation, transform, and alpha.
538pub const RULE_CONSTRAINT_LAYER: u16 = 281;
539/// ConstraintLayout Placeholder helper `"<content_id>|<empty_vis:gone|invisible|visible>"`.
540pub const RULE_CONSTRAINT_PLACEHOLDER: u16 = 282;
541/// AppBarLayout child `app:layout_scrollFlags` comma-separated flags (`scroll`, `enterAlways`, `enterAlwaysCollapsed`, `exitUntilCollapsed`, `snap`).
542pub const RULE_APP_BAR_SCROLL_FLAGS: u16 = 284;
543/// Animated `<animation-list>` frame playback `"<oneshot:0|1>|<img_key_0>:<dur_ms_0>,<img_key_1>:<dur_ms_1>,..."`.
544pub const RULE_ANIMATION_LIST: u16 = 285;
545/// Dynamic wrapper drawables (`level-list`, `clip`, `rotate`, `scale`, `transition`) with optional `bg:`/`src:` prefix:
546/// - `"level|<min0>:<max0>:<img_key0>,<min1>:<max1>:<img_key1>,..."`
547/// - `"clip|<h|v>|<start|end|center|top|bottom>|<img_key>"`
548/// - `"rotate|<from_deg>,<to_deg>|<px>,<py>|<img_key>"`
549/// - `"scale|<sw_frac>,<sh_frac>|<center|start|end|top|bottom>|<img_key>"`
550/// - `"transition|<dur_ms>|<img_key_0>,<img_key_1>"`
551pub const RULE_DRAWABLE_DYNAMIC: u16 = 286;
552/// ConstraintLayout physical vs. logical horizontal pinning bitmask `"<bitmask_u8>"`:
553/// bit 0 (`1`) = left-edge (`196`/`197`) physical `Left`; bit 1 (`2`) = right-edge (`198`/`199`) physical `Right`;
554/// bit 2 (`4`) = bias (`204`) and left/right margins physical when both anchors are physical.
555pub const RULE_CONSTRAINT_PHYS_FLAGS: u16 = 287;
556/// Incoming `elevation` / `translationZ` object animator transition on `ViewAnimator`/`ViewSwitcher`/
557/// `TextSwitcher`/`ImageSwitcher`/`ViewFlipper`/`AdapterViewFlipper`:
558/// `"<from_dp>,<to_dp>|<dur_ms>|<offset_ms>|<interp>"`.
559pub const RULE_ELEVATION_IN: u16 = 288;
560/// Outgoing `elevation` / `translationZ` object animator transition on `ViewAnimator`/`ViewSwitcher`/
561/// `TextSwitcher`/`ImageSwitcher`/`ViewFlipper`/`AdapterViewFlipper`.
562pub const RULE_ELEVATION_OUT: u16 = 289;
563/// AppBarLayout extended options:
564/// - on `AppBarLayout`: `"lift_color=<r>,<g>,<b>,<a>"` (custom `liftOnScrollColor`)
565/// - on `AppBarLayout` direct scrolling child: `"effect=compress"` (`app:layout_scrollEffect="compress"`)
566pub const RULE_APP_BAR_EXT: u16 = 290;
567/// DrawerLayout lock mode (`"unlocked"`/`"0"`, `"locked_closed"`/`"1"`, `"locked_open"`/`"2"`, `"undefined"`/`"3"`).
568pub const RULE_DRAWER_LOCK_MODE: u16 = 291;
569/// ConstraintLayout Flow per-first/last-line chain style & bias overrides:
570/// `"<first_hstyle>,<last_hstyle>,<first_hbias>,<last_hbias>,<first_vstyle>,<last_vstyle>,<first_vbias>,<last_vbias>"`.
571pub const RULE_CONSTRAINT_FLOW_EXT: u16 = 292;
572/// `<animated-selector>` transition frame playback (repeatable, one per `<transition>`):
573/// `"<ctx:src|bg>:<from_mask>:<to_mask>:<rev:0|1>|<img_key_0>:<dur_ms_0>,..."`.
574pub const RULE_ANIMATED_SELECTOR: u16 = 293;
575/// ConstraintLayout `app:layout_constraintWidth_default` / `app:layout_constraintHeight_default`:
576/// `"<w_def:spread|wrap|percent>,<h_def:spread|wrap|percent>"`.
577pub const RULE_CONSTRAINT_DEFAULT_SIZE: u16 = 294;
578/// Timed `<animation-list>` frame playback on compound drawables, checkable button drawables,
579/// `SeekBar` tick marks, and `ExpandableListView` group indicators (repeatable):
580/// `"<slot:start|top|end|bottom|left|right|button|tick|indicator>:<oneshot:0|1>|<img_key_0>:<dur_ms_0>,..."`.
581pub const RULE_COMPOUND_ANIMATION_LIST: u16 = 295;
582/// Extended `TextView`/`Button` text layout options:
583/// `"<break:simple|high_quality|balanced>|<hyphen:none|normal|full>|<just:none|inter_word>|<auto_min_sp>,<auto_max_sp>,<auto_step_sp>"`.
584pub const RULE_TEXT_LAYOUT_EXT: u16 = 296;
585/// Material `BadgeDrawable` extended options (repeatable):
586/// `"<item_index|-1|self>|<gravity:top_end|top_start|bottom_end|bottom_start>|<max_chars>|<hoff_dp>,<voff_dp>"`.
587pub const RULE_MATERIAL_BADGE_EXT: u16 = 297;
588/// CollapsingToolbarLayout extended options:
589/// - on `CollapsingToolbarLayout`: `"<mode:scale|fade>|<max_lines>|<scrim_dur_ms>|<subtitle>"`
590/// - on `CollapsingToolbarLayout` direct children: `"collapse:<none|pin|parallax>:<mult>"`.
591pub const RULE_COLLAPSING_TOOLBAR_EXT: u16 = 298;
592/// Material 3 ExtendedFloatingActionButton extended options:
593/// `"<extended:0|1>|<collapsed_size_dp>|<strategy:auto|wrap_content|match_parent>"`.
594pub const RULE_EXTENDED_FAB_EXT: u16 = 299;
595/// Material BottomAppBar extended options:
596/// `"<align:center|end>|<anchor:cradle|embed>|<cradle_margin_dp>,<cradle_rad_dp>,<cradle_voff_dp>|<hide_on_scroll:0|1>"`.
597pub const RULE_BOTTOM_APP_BAR_EXT: u16 = 300;
598/// RecyclerView layout manager extended options on `Kind::ListView` / `Kind::GridView`:
599/// `"<mgr:linear|grid|staggered>|<orient:v|h>|<span_count>|<reverse:0|1>|<stack_end:0|1>"`.
600pub const RULE_RECYCLER_LAYOUT_EXT: u16 = 301;
601/// Material `SearchView` fullscreen/modal search overlay coupled to `SearchBar` on `Kind::Frame` / `Kind::Linear`:
602/// `"<anchor_bar_id>|<hint>|<hide_nav:0|1>|<use_drawer_arrow:0|1>"`.
603pub const RULE_SEARCH_VIEW_EXT: u16 = 302;
604/// AndroidX `SwipeRefreshLayout` extended options (paired with `RULE_SWIPE_REFRESH` on `Kind::Frame`):
605/// `"<bg_rgba>|<scheme_rgba_list>|<size:default|large>|<start_off_dp>,<end_off_dp>"`.
606pub const RULE_SWIPE_REFRESH_EXT: u16 = 303;
607/// Material 3 `CarouselLayoutManager` keyline focal sizing & snap scrolling on `Kind::ListView`/`Kind::GridView`/`Kind::HorizontalScroll`/`Kind::Linear`:
608/// `"<strategy:multi_browse|hero|uncontained|full_screen>|<spacing_dp>|<align:start|center>"`.
609pub const RULE_CAROUSEL_LAYOUT: u16 = 304;
610/// AndroidX `ViewPager` / `ViewPager2` extended options (paired with `RULE_VIEW_PAGER` on `Kind::ViewFlipper`):
611/// `"<orient:h|v>|<user_input:0|1>|<page_margin_dp>|<transformer:none|zoom_out|depth>"`.
612pub const RULE_VIEW_PAGER_EXT: u16 = 305;
613/// Extended `TextView` / `EditText` auto-link detection & styling:
614/// `"<mask:all|web|email|phone|none>|<link_rgba>|<clickable:0|1>"`.
615pub const RULE_TEXT_LINKS_SPANS: u16 = 306;
616/// Sampled `<animated-vector>` frame sequence playback (repeatable, one per `src` / `bg`):
617/// `"<ctx:src|bg>:<repeat:0|1>:<dur_ms>|<img_key_0>,<img_key_1>,..."`.
618pub const RULE_ANIMATED_VECTOR: u16 = 309;
619/// DrawerLayout lock mode: unlocked (normal open/close, edge swipe, scrim dismiss).
620pub const DRAWER_LOCK_MODE_UNLOCKED: u8 = 0;
621/// DrawerLayout lock mode: locked closed (forces panel closed, blocks edge swipe-to-open).
622pub const DRAWER_LOCK_MODE_LOCKED_CLOSED: u8 = 1;
623/// DrawerLayout lock mode: locked open (forces panel open, blocks drag-to-close and scrim dismissal).
624pub const DRAWER_LOCK_MODE_LOCKED_OPEN: u8 = 2;
625/// DrawerLayout lock mode: undefined (behaves as unlocked).
626pub const DRAWER_LOCK_MODE_UNDEFINED: u8 = 3;
627/// Material BottomSheet/SideSheet expanded state (`BottomSheetBehavior.STATE_EXPANDED`).
628pub const SHEET_STATE_EXPANDED: u8 = 3;
629/// Material BottomSheet collapsed/peeking state (`BottomSheetBehavior.STATE_COLLAPSED`).
630pub const SHEET_STATE_COLLAPSED: u8 = 4;
631/// Material BottomSheet/SideSheet hidden state (`BottomSheetBehavior.STATE_HIDDEN`).
632pub const SHEET_STATE_HIDDEN: u8 = 5;
633/// Material BottomSheet half-expanded state (`BottomSheetBehavior.STATE_HALF_EXPANDED`).
634pub const SHEET_STATE_HALF_EXPANDED: u8 = 6;
635#[derive(Clone)]
636struct TilDropdownAnchor {
637    key: String,
638    til_key: String,
639    id: u64,
640    xml_id: &'static str,
641    bounds: Rect,
642    rtl: bool,
643}
644#[derive(Clone, Copy)]
645pub struct AnimationDelta { pub value: f32, pub mode: u8 }
646impl AnimationDelta { fn resolve(self, own:f32, parent:f32) -> f32 { self.value * match self.mode { 1 => own, 2 => parent, _ => 1.0 } } }
647#[derive(Clone, Copy)]
648pub struct TranslateAnimation { pub deltas: [AnimationDelta; 4], pub duration:f64, pub start_offset:f64, pub linear:bool, pub y_timing:Option<(f64,bool,f64)> }
649#[derive(Clone)]
650struct 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] }
651impl TranslateAnimation {
652    fn sample(self, elapsed:f64, child:Rect, parent:Rect, object:bool) -> [f32;2] {
653        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} };
654        let tx=progress(self.duration,self.linear,self.start_offset);
655        let (yd,yl,yo)=self.y_timing.unwrap_or((self.duration,self.linear,self.start_offset));
656        let ty=progress(yd,yl,yo);
657        let [a,b,c,d] = self.deltas;
658        let mix = |x:f32,y:f32,t:f32| x+(y-x)*t;
659        [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)}]
660    }
661    fn total_duration(self)->f64 { (self.start_offset+self.duration).max(self.y_timing.map_or(0.0,|timing|timing.0+timing.2)) }
662}
663#[derive(Clone, Copy)]
664pub struct AlphaAnimation { pub from: f32, pub to: f32, pub duration: f64, pub start_offset: f64, pub linear: bool }
665impl AlphaAnimation {
666    fn total_duration(self) -> f64 { self.start_offset + self.duration }
667    fn sample(self, elapsed: f64, object:bool) -> f32 {
668        if object && elapsed<self.start_offset {return 1.0;}
669        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 };
670        let t = if self.linear { t } else { (1.0 - (std::f32::consts::PI * t).cos()) * 0.5 };
671        self.from + (self.to - self.from) * t
672    }
673}
674#[derive(Clone, Copy)]
675pub struct ViewTransition { current: usize, previous: usize, started: f64, active: bool }
676#[derive(Clone, Copy)]
677pub struct FlipperClock { running: bool, next: f64, epoch:u64, pause_generation:u64, visible:bool }
678#[derive(Clone, Copy)]
679pub struct ChronometerState { pub base:f64, pub running:bool }
680#[derive(Clone, Copy)]
681pub struct WallClock { pub unix_seconds:f64, pub offset_seconds:i32, pub is_24_hour:bool }
682#[derive(Clone, Copy, Debug)]
683pub struct ZoomControlsFade { from:f32, target_visible:bool, start:f64 }
684impl ZoomControlsFade {
685    fn value(self, now:f64) -> f32 {
686        let t=((now-self.start)/0.5).clamp(0.0,1.0) as f32;
687        let eased=(1.0-(std::f32::consts::PI*t).cos())*0.5;
688        self.from+(f32::from(self.target_visible)-self.from)*eased
689    }
690}
691#[derive(Clone, Copy)]
692pub struct Node {
693    pub kind: Kind,
694    pub id: &'static str,
695    pub width: Size,
696    pub height: Size,
697    pub min_width: f32,
698    pub min_height: f32,
699    pub horizontal: bool,
700    pub measure_all_children: bool,
701    /// 0 inherits, 1 is left-to-right, and 2 is right-to-left.
702    pub layout_direction: u8,
703    pub fill_viewport: bool,
704    /// Android ViewGroup clips children to its padding by default.
705    pub clip_to_padding_disabled: bool,
706    /// Android ViewGroup clips each child to its bounds by default.
707    pub clip_children_disabled: bool,
708    pub weight: f32,
709    /// Zero uses the sum of the visible child weights.
710    pub weight_sum: f32,
711    pub divider_color: Option<Color>,
712    pub divider_thickness: f32,
713    pub divider_flags: u8,
714    pub divider_padding: f32,
715    /// Physical left, top, right and bottom padding and optional relative overrides.
716    pub padding_edges: [f32; 4],
717    pub padding_explicit: [bool; 4],
718    pub background_padding: Option<[f32; 4]>,
719    pub background_min_size: [f32; 2],
720    pub padding_relative: [Option<f32>; 2],
721    /// Physical left, top, right and bottom margins.
722    pub margin: [f32; 4],
723    /// Optional start and end margins override the physical side in the current direction.
724    pub margin_relative: [Option<f32>; 2],
725    /// FrameLayout gravity: horizontal start/center/end/left/right, vertical top/center/bottom.
726    pub layout_gravity: [u8; 2],
727    /// Physical coordinates for children of deprecated AbsoluteLayout.
728    pub absolute_position: [f32; 2],
729    pub relative_rules: &'static [RelativeRule],
730    pub layout_gravity_explicit: bool,
731    pub content_gravity: [u8; 2],
732    pub text: &'static str,
733    pub hint: &'static str,
734    pub chrono_format: &'static str,
735    pub count_down: bool,
736    pub clock_12: &'static str,
737    pub clock_24: &'static str,
738    /// 0 text, 1 email, 2 telephone, 3 numeric, 4 password, 5 decimal.
739    pub input_type: u8,
740    pub text_on: &'static str,
741    pub text_off: &'static str,
742    pub text_size: f32,
743    /// Android letter spacing in em units.
744    pub letter_spacing_em: f32,
745    pub line_spacing_extra: f32,
746    pub line_spacing_multiplier: f32,
747    pub text_bold: bool,
748    pub text_all_caps: bool,
749    /// Zero means no explicit line limit.
750    pub max_lines: usize,
751    pub min_lines: usize,
752    pub ellipsize_end: bool,
753    /// 1 truncates at the start, 2 in the middle.
754    pub ellipsize_side: u8,
755    pub single_line: bool,
756    pub align: u8,
757    pub color: Option<Color>,
758    pub text_color_states: &'static [TintState],
759    pub background: Option<Color>,
760    /// Solid foreground painted over this view and its descendants.
761    pub foreground: Option<Color>,
762    /// Negative radius represents an oval foreground.
763    pub foreground_radius: f32,
764    pub foreground_size: [f32; 2],
765    pub foreground_padding: Option<[f32; 4]>,
766    /// Horizontal/vertical foreground gravity; 5 means fill.
767    pub foreground_gravity: [u8; 2],
768    pub foreground_excludes_padding: bool,
769    pub background_stroke: Option<Color>,
770    pub background_stroke_width: f32,
771    pub foreground_stroke: Option<Color>,
772    pub foreground_stroke_width: f32,
773    pub radius: f32,
774    pub clickable: bool,
775    pub icon: MaterialIcon,
776    pub image_src: &'static str,
777    /// Image scale mode encoded by the Android XML importer.
778    pub image_scale: u8,
779    /// Preserve drawable aspect ratio when a view dimension can wrap.
780    pub image_adjust_bounds: bool,
781    pub image_max_width: Option<f32>,
782    pub image_max_height: Option<f32>,
783    pub image_tint: Option<Color>,
784    pub image_tint_states: &'static [TintState],
785    /// 0 SRC_ATOP (XML default), 1 SRC_IN, 2 SRC_OVER, 3 MULTIPLY,
786    /// 4 SCREEN, 5 ADD.
787    pub image_tint_mode: u8,
788    /// Drawable opacity in the Android imageAlpha range.
789    pub image_alpha: u8,
790    /// Opacity applied to the view and its children.
791    pub view_alpha: f32,
792    pub image_builtin: bool,
793    pub enabled: bool,
794    pub checked: bool,
795    pub checked_button: &'static str,
796    pub min: f32,
797    pub max: f32,
798    pub progress: f32,
799    pub secondary_progress: f32,
800    pub indeterminate: bool,
801    pub num_stars: usize,
802    pub rating: f32,
803    pub step_size: f32,
804    pub indicator: bool,
805    pub mirror_for_rtl: bool,
806    pub animation_in: Option<AlphaAnimation>,
807    pub animation_out: Option<AlphaAnimation>,
808    pub translate_in: Option<TranslateAnimation>,
809    pub translate_out: Option<TranslateAnimation>,
810    pub auto_start: bool,
811    pub flip_interval: f64,
812    pub visibility: Visibility,
813    pub children: &'static [Node],
814}
815/// A vector drawable tint resolved against the current theme when painted.
816#[derive(Clone,Copy,Debug,PartialEq,Eq)]
817pub enum AndroidDrawableTint {Fixed(Color),ControlNormal}
818/// Contact information supplied by the embedding application.
819#[derive(Clone,Debug,PartialEq,Eq)]
820pub enum QuickContactTarget { Uri(String), Email(String), Phone(String) }
821/// A contact lookup delegated to the host. Resolve using its token.
822#[derive(Clone,Debug,PartialEq,Eq)]
823pub struct QuickContactLookup { pub token:u64,pub target:QuickContactTarget,pub open_after_lookup:bool }
824#[derive(Clone,Debug,PartialEq,Eq)]
825pub enum QuickContactAction { Show(String), Create(QuickContactTarget) }
826/// Host player state shown by an XML MediaController.
827#[derive(Clone,Copy,Debug,Default,PartialEq,Eq)]
828pub struct MediaPlayerSnapshot {pub position_ms:u64,pub duration_ms:u64,pub buffered_percent:u8,pub playing:bool}
829/// Player capabilities and whether previous/next listeners are installed.
830#[derive(Clone,Copy,Debug,PartialEq,Eq)]
831pub struct MediaControllerCapabilities {pub can_pause:bool,pub can_seek_backward:bool,pub can_seek_forward:bool,pub has_previous:bool,pub has_next:bool}
832impl Default for MediaControllerCapabilities {fn default()->Self{Self{can_pause:true,can_seek_backward:true,can_seek_forward:true,has_previous:false,has_next:false}}}
833#[derive(Clone,Copy,Debug,PartialEq,Eq)]
834pub enum MediaControllerAction {Play,Pause,SeekTo(u64),Previous,Next}
835#[derive(Clone,Copy,Debug,PartialEq,Eq)]
836pub enum VideoMeasureSpec {Exactly(u32),AtMost(u32),Unspecified}
837/// Android VideoView.onMeasure, using integer pixel dimensions.
838pub fn measure_video_view(video:(u32,u32),width:VideoMeasureSpec,height:VideoMeasureSpec)->(u32,u32) {
839    use VideoMeasureSpec::*;
840    let default=|natural,spec|match spec {Exactly(size)|AtMost(size)=>size,Unspecified=>natural};
841    let (vw,vh)=video;let (mut w,mut h)=(default(vw,width),default(vh,height));
842    if vw==0||vh==0{return (w,h);}
843    let ratio=|size:u32,numerator:u32,denominator:u32|((size as u64*numerator as u64/denominator as u64).min(u32::MAX as u64)) as u32;
844    match (width,height) {
845        (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);}},
846        (Exactly(sw),other)=>{w=sw;h=ratio(w,vh,vw);if let AtMost(limit)=other{h=h.min(limit);}},
847        (other,Exactly(sh))=>{h=sh;w=ratio(h,vw,vh);if let AtMost(limit)=other{w=w.min(limit);}},
848        (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);}},
849    }
850    (w,h)
851}
852#[derive(Clone,Copy,Debug,Default)]
853struct MediaControllerFloating {visible:bool,deadline:Option<f64>,dragging:bool}
854/// Android menu item action placement policy.
855#[derive(Clone,Copy,Debug,PartialEq,Eq)]
856pub enum AndroidShowAsAction {Never,IfRoom,Always}
857/// Host-provided Android Toolbar menu item.
858#[derive(Clone,Debug)]
859pub 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}
860/// Allocate fixed-width actions using Android's group promotion and demotion rules.
861/// Slot widths remain an approximation of ActionMenuPresenter's view measurement.
862pub fn allocate_android_toolbar_actions(items:&[AndroidToolbarMenuItem],slots:usize)->(Vec<usize>,Vec<usize>) {
863    let required=items.iter().filter(|x|x.visible&&x.show_as_action==AndroidShowAsAction::Always).count();
864    let requested=items.iter().filter(|x|x.visible&&x.show_as_action==AndroidShowAsAction::IfRoom).count();
865    let never=items.iter().any(|x|x.visible&&x.show_as_action==AndroidShowAsAction::Never);
866    let reserve=usize::from(never||required+requested>slots);
867    let mut remaining=slots as isize-reserve as isize-required as isize;
868    let mut width=slots.saturating_sub(reserve) as isize;
869    let mut groups=std::collections::HashSet::new();let mut selected=vec![false;items.len()];
870    for (i,item) in items.iter().enumerate() {if !item.visible{continue;}match item.show_as_action {
871        AndroidShowAsAction::Always=>{selected[i]=true;width-=1;if item.group_id!=0 {groups.insert(item.group_id);}},
872        AndroidShowAsAction::IfRoom=>{
873            let grouped=item.group_id!=0&&groups.contains(&item.group_id);
874            if (remaining>0||grouped)&&width>0 {selected[i]=true;width-=1;remaining-=1;if item.group_id!=0 {groups.insert(item.group_id);}}
875            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;}}}
876        },
877        AndroidShowAsAction::Never=>{},
878    }}
879    let mut visible=Vec::new();let mut overflow=Vec::new();
880    for (i,item) in items.iter().enumerate() {if item.visible {if selected[i] {visible.push(i)}else{overflow.push(i)}}}
881    (visible,overflow)
882}
883// ActionMenuView text items need at least two cells; icon items need one.
884fn allocate_action_menu_items(items:&[AndroidToolbarMenuItem],costs:&[usize],slots:usize)->(Vec<usize>,Vec<usize>) {
885    if slots==0 {return (Vec::new(),items.iter().enumerate().filter_map(|(i,item)|item.visible.then_some(i)).collect());}
886    let requested=items.iter().enumerate().filter(|(_,item)|item.visible&&item.show_as_action!=AndroidShowAsAction::Never).map(|(i,_)|costs[i]).sum::<usize>();
887    let reserve=usize::from(requested>slots||items.iter().any(|item|item.visible&&item.show_as_action==AndroidShowAsAction::Never));
888    let required=items.iter().enumerate().filter(|(_,item)|item.visible&&item.show_as_action==AndroidShowAsAction::Always).map(|(i,_)|costs[i]).sum::<usize>();
889    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();
890    for (i,item) in items.iter().enumerate().filter(|(_,item)|item.visible) {
891        if item.show_as_action==AndroidShowAsAction::Always {selected[i]=true;if item.group_id!=0{groups.insert(item.group_id);}continue;}
892        if item.show_as_action!=AndroidShowAsAction::IfRoom {continue;}
893        let grouped=item.group_id!=0&&groups.contains(&item.group_id);
894        if remaining>=costs[i] as isize {selected[i]=true;remaining-=costs[i] as isize;if item.group_id!=0{groups.insert(item.group_id);}}
895        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;}}}
896    }
897    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)
898}
899/// Static, noninteractive XML views used to display a Spinner adapter item.
900#[derive(Clone,Copy)]
901pub struct SpinnerItemTemplates {
902    pub selected: &'static Node,
903    pub dropdown: &'static Node,
904    /// XML TextView ID receiving the item's text in both templates.
905    pub text_id: &'static str,
906}
907/// Static noninteractive XML view used for each ListView adapter row.
908#[derive(Clone,Copy)]
909pub struct ListItemTemplate {
910    pub row: &'static Node,
911    pub text_id: &'static str,
912}
913/// Additional text and drawable bindings for one ListView or GridView item.
914#[derive(Clone,Default)]
915pub struct AdapterItemBinding {
916    /// Optional XML layout override for this item; otherwise the adapter default is used.
917    pub template:Option<ListItemTemplate>,
918    pub text:HashMap<String,String>,
919    pub images:HashMap<String,String>,
920}
921fn adapter_item_template(default:Option<ListItemTemplate>,binding:Option<&AdapterItemBinding>)->Option<ListItemTemplate> {
922    binding.and_then(|binding|binding.template).or(default)
923}
924fn hash_item_binding<H:std::hash::Hasher>(hash:&mut H,binding:Option<&AdapterItemBinding>) {
925    use std::hash::{Hash,Hasher};
926    if let Some(binding)=binding {
927        binding.template.map(|template|(template.row as *const Node as usize,template.text_id)).hash(hash);
928        for map in [&binding.text,&binding.images] {
929            let mut combined=0u64;
930            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();}
931            map.len().hash(hash);combined.hash(hash);
932        }
933    } else {Option::<(usize,&str)>::None.hash(hash);0usize.hash(hash);0usize.hash(hash);}
934}
935fn with_adapter_binding<T>(state:&mut LayoutState,text_id:&str,label:&str,binding:Option<&AdapterItemBinding>,run:impl FnOnce(&mut LayoutState)->T)->T {
936    state.text.clear();let mut saved=Vec::new();
937    if let Some(binding)=binding {
938        state.text.extend(binding.text.iter().map(|(key,value)|(key.clone(),value.clone())));
939        for (key,value) in &binding.images {saved.push((key.clone(),state.image_sources.insert(key.clone(),value.clone())));}
940    }
941    state.text.insert(text_id.to_owned(),label.to_owned());
942    let result=run(state);
943    for (key,old) in saved {if let Some(value)=old {state.image_sources.insert(key,value);}else{state.image_sources.remove(&key);}}
944    result
945}
946/// An XML view placed before or after ListView adapter rows.
947#[derive(Clone,Copy)]
948pub struct ListFixedView { pub view:&'static Node, pub selectable:bool, pub label:&'static str }
949fn inspect_expandable_template(node:&Node,text_id:&str)->(bool,bool,bool) {
950    let allowed=matches!(node.kind,Kind::Text|Kind::Image|Kind::Space|Kind::View|Kind::Linear|Kind::Frame|Kind::CheckBox|Kind::Switch|Kind::Button);
951    let interactive=matches!(node.kind,Kind::CheckBox|Kind::Switch|Kind::Button);
952    let safe=allowed && (!node.clickable||interactive) && (!interactive||!node.id.is_empty());
953    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)})
954}
955fn inspect_adapter_template(node:&Node,text_id:&str)->(bool,bool) {
956    let safe=!node.clickable && matches!(node.kind,Kind::Text|Kind::Image|Kind::Space|Kind::View|Kind::Linear|Kind::Frame);
957    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)})
958}
959// Estimated row heights are refined only when rows become visible. The Fenwick
960// tree keeps scroll position lookup and individual height updates logarithmic.
961#[derive(Clone)]
962struct ListTextGeometry { signature:u64, heights:Vec<f32>, fingerprints:Vec<Option<u64>>, tree:Vec<f32>, divider:f32 }
963impl ListTextGeometry {
964    fn new(signature:u64,count:usize,divider:f32)->Self {
965        let step=48.0+divider;let mut tree=vec![0.0;count+1];
966        for i in 1..=count {tree[i]=step*(i & i.wrapping_neg()) as f32;}
967        Self {signature,heights:vec![48.0;count],fingerprints:vec![None;count],tree,divider}
968    }
969    fn prefix(&self,mut i:usize)->f32 {let mut sum=0.0;while i>0 {sum+=self.tree[i];i&=i-1;}sum}
970    fn index_at(&self,target:f32)->usize {
971        let n=self.heights.len();if n==0{return 0;}
972        let mut bit=1usize;while bit<=n/2 {bit*=2;}
973        let (mut index,mut sum)=(0usize,0.0f32);
974        while bit>0 {let next=index+bit;if next<=n && sum+self.tree[next]<=target {index=next;sum+=self.tree[next];}bit/=2;}
975        index
976    }
977    fn measure(&mut self,index:usize,label:&str,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:&mut Option<LayoutState>,id:u64,binding:Option<&AdapterItemBinding>)->bool {
978        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();
979        if self.fingerprints[index]==Some(fingerprint) {return false;}
980        self.fingerprints[index]=Some(fingerprint);
981        let template=adapter_item_template(template,binding);
982        let height=if let (Some(template),Some(row_state))=(template,row_state.as_mut()) {
983            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))})
984        } else {let lines=wrapped_text_lines(label,(width-32.0).max(1.0),TextStyle::default(),metrics,|_|{}).max(1);24.0*lines as f32};
985        let height=if height.is_finite() {height.clamp(if template.is_some(){1.0}else{48.0},4096.0)}else{48.0};
986        let delta=height-self.heights[index];self.heights[index]=height;
987        if delta.abs()<0.01 {return false;}
988        let mut pos=index+1;while pos<self.tree.len(){self.tree[pos]+=delta;pos+=pos & pos.wrapping_neg();}true
989    }
990    fn measure_grid_row(&mut self,row:usize,entries:&[String],columns:usize,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:&mut Option<LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>)->bool {
991        use std::hash::{Hash,Hasher};let start=row*columns;let end=(start+columns).min(entries.len());
992        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();
993        if self.fingerprints[row]==Some(fingerprint) {return false;}self.fingerprints[row]=Some(fingerprint);
994        let mut height=0.0_f32;
995        for (offset,label) in entries[start..end].iter().enumerate() {
996            let (_,measured)=grid_item_size(template,row_state,label,width,metrics,anonymous_child_id(id,1024+start+offset),bindings.and_then(|items|items.get(&(start+offset))));
997            height=height.max(measured);
998        }
999        let delta=height-self.heights[row];self.heights[row]=height;if delta.abs()<0.01{return false;}
1000        let mut pos=row+1;while pos<self.tree.len(){self.tree[pos]+=delta;pos+=pos & pos.wrapping_neg();}true
1001    }
1002    fn measure_grid_window(&mut self,entries:&[String],columns:usize,scroll:f32,height:f32,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:&mut Option<LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>)->bool {
1003        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;
1004        while row<self.heights.len() && y<scroll+height {changed|=self.measure_grid_row(row,entries,columns,width,metrics,template,row_state,id,bindings);y+=self.heights[row]+self.divider;row+=1;}changed
1005    }
1006    fn measure_window(&mut self,entries:&[String],scroll:f32,height:f32,width:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:&mut Option<LayoutState>,id:u64,bindings:Option<&HashMap<usize,AdapterItemBinding>>)->bool {
1007        if scroll+height<=0.0 {return false;}
1008        let mut index=self.index_at(scroll.max(0.0));let mut y=self.prefix(index);let mut changed=false;
1009        while index<entries.len() && y<scroll+height {changed|=self.measure(index,&entries[index],width,metrics,template,row_state,id,bindings.and_then(|items|items.get(&index)));y+=self.heights[index]+self.divider;index+=1;}
1010        changed
1011    }
1012}
1013fn list_text_signature(entries:&[String],width:f32,divider:f32,metrics:TextMetrics,template:Option<ListItemTemplate>,row_state:Option<&LayoutState>)->u64 {
1014    use std::hash::{Hash,Hasher};let mut hash=std::collections::hash_map::DefaultHasher::new();
1015    (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);
1016    for advance in metrics.normal.iter().chain(metrics.medium.iter()) {advance.to_bits().hash(&mut hash);}
1017    template.map(|t|(t.row as *const Node as usize,t.text_id)).hash(&mut hash);
1018    if let Some(state)=row_state {hash_adapter_environment(&mut hash,state);}
1019    hash.finish()
1020}
1021#[derive(Clone)]
1022struct 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}
1023#[derive(Clone)]
1024struct AutoMatches {query:Option<String>,indices:Vec<usize>}
1025#[derive(Clone,Copy)]
1026struct ListHold { item_id:u64, origin:[f32;2], deadline:f64, fired:bool }
1027#[derive(Clone,Default)]
1028struct 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>}
1029#[derive(Clone,Default)]
1030struct 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)> }
1031#[derive(Clone, Default)]
1032struct ViewPagerGesture {
1033    origin: Option<[f32; 2]>,
1034    offset: f32,
1035    dragging: bool,
1036    settle: Option<(f64, f32, f64)>,
1037    last_page: usize,
1038    from_page: Option<usize>,
1039    last_time: f64,
1040    initialized: bool,
1041    samples: Vec<(f64, f32)>,
1042}
1043#[derive(Clone, Copy, Default)]
1044struct SwipeRefreshMotion {
1045    initialized: bool,
1046    last_refreshing: bool,
1047    last_time: f64,
1048    origin: Option<[f32; 2]>,
1049    dragging: bool,
1050    pull_px: f32,
1051    offset_px: f32,
1052    settle: Option<(f64, f32, f32, f64)>,
1053}
1054#[derive(Clone, Default)]
1055struct CarouselMotion {
1056    origin: Option<[f32; 2]>,
1057    drag_base: f32,
1058    dragging: bool,
1059    was_touch_dragging: bool,
1060    snap: Option<(f64, f32, f32, f64)>,
1061    samples: Vec<(f64, f32)>,
1062}
1063#[derive(Clone, Default)]
1064struct XmlSheetMotion {
1065    origin: Option<[f32; 2]>,
1066    drag_base: f32,
1067    drag_offset: f32,
1068    current_h: Option<f32>,
1069    dragging: bool,
1070    settle: Option<(f64, f32, f32, f64)>,
1071    last_state: u8,
1072    samples: Vec<(f64, f32)>,
1073}
1074#[derive(Clone, Default)]
1075struct XmlDrawerMotion {
1076    initialized: bool,
1077    last_open: bool,
1078    last_time: f64,
1079    progress: f32,
1080    anim: Option<(f64, f32, f32, f64)>,
1081    origin: Option<[f32; 2]>,
1082    drag_base_progress: f32,
1083    drag_align_right: bool,
1084    drag_panel_w: f32,
1085    dragging: bool,
1086    edge_opening: bool,
1087    samples: Vec<(f64, f32)>,
1088}
1089#[derive(Clone, Copy, Default)]
1090struct AppBarScrollState {
1091    initialized: bool,
1092    last_scroll: f32,
1093    collapse_px: f32,
1094    last_scroll_time: f64,
1095    last_time: f64,
1096    was_dragging: bool,
1097    snap_anim: Option<(f64, f32, f32, f64)>,
1098}
1099#[derive(Clone, Copy, Default)]
1100struct AnimatedSelectorState {
1101    initialized: bool,
1102    last_mask: u8,
1103    active: Option<(f64, bool, usize)>,
1104}
1105#[derive(Clone, Copy, Default)]
1106struct XmlLiftMotion {
1107    initialized: bool,
1108    last_lifted: bool,
1109    last_time: f64,
1110    progress: f32,
1111    anim: Option<(f64, f32, f32, f64)>,
1112}
1113#[derive(Clone, Copy, Default)]
1114struct DrawableTransitionMotion {
1115    initialized: bool,
1116    last_active: bool,
1117    progress: f32,
1118    anim: Option<(f64, f32, f32, f64)>,
1119}
1120#[derive(Clone, Copy, Default)]
1121struct BottomAppBarHideState {
1122    initialized: bool,
1123    last_scroll: f32,
1124    hidden: bool,
1125    last_time: f64,
1126    progress: f32,
1127    anim: Option<(f64, f32, f32, f64)>,
1128}
1129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1130struct BottomAppBarCradleCacheKey {
1131    w: u16,
1132    h: u16,
1133    cx_q: u16,
1134    voff_q: i16,
1135    cradle_r_q: u16,
1136    fillet_r_q: u16,
1137    color: [u8; 4],
1138}
1139#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1140struct GradientCacheKey {
1141    kind_tag: u8,
1142    w: u16,
1143    h: u16,
1144    p0: i32,
1145    p1: i32,
1146    p2: i32,
1147    start: [u8; 4],
1148    center: Option<([u8; 4], u16)>,
1149    end: [u8; 4],
1150    tint: Option<[u8; 4]>,
1151    mask_tag: u8,
1152    mask_radii: [u16; 4],
1153    mask_cut: [bool; 4],
1154}
1155#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1156struct CutShapeCacheKey {
1157    w: u16,
1158    h: u16,
1159    radii_q: [u16; 4],
1160    cut: [bool; 4],
1161    color: [u8; 4],
1162}
1163fn pointer_velocity(samples: &[(f64, f32)], now: f64) -> f32 {
1164    samples
1165        .last()
1166        .and_then(|&(last_t, last_v)| {
1167            if now - last_t < 0.12 {
1168                samples
1169                    .iter()
1170                    .rev()
1171                    .find(|(t, _)| last_t - *t >= 0.005)
1172                    .map(|&(first_t, first_v)| (last_v - first_v) / (last_t - first_t) as f32)
1173            } else {
1174                None
1175            }
1176        })
1177        .unwrap_or(0.0)
1178}
1179// Android Scroller samples its fling spline at 100 intervals and linearly
1180// interpolates between those samples. The binary search solves its Bezier x.
1181fn gallery_spline_sample(index:usize)->f32 {
1182    if index==0{return 0.0;}if index>=100{return 1.0;}
1183    let target=index as f32/100.0;let(mut lo,mut hi)=(0.0,1.0);
1184    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;}}
1185    let x=(lo+hi)*0.5;let c=3.0*x*(1.0-x);c*((1.0-x)*0.5+x)+x*x*x
1186}
1187fn gallery_spline_position(progress:f32)->f32 {
1188    let scaled=progress.clamp(0.0,1.0)*100.0;let index=scaled as usize;if index>=100{return 1.0;}
1189    let a=gallery_spline_sample(index);let b=gallery_spline_sample(index+1);a+(b-a)*(scaled-index as f32)
1190}
1191/// View-ID based tabs configured by a host for Android TabHost.
1192#[derive(Clone,Default)]
1193pub 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>>}
1194/// Content of a TabHost tab: an existing XML view or a lazy XML factory.
1195#[derive(Clone)]
1196pub enum TabHostContent { View(String), Factory(fn(&str)-> &'static Node) }
1197fn tab_host_find<'a>(node:&'a Node,id:&str)->Option<&'a Node> {
1198    if node.id==id {return Some(node);}node.children.iter().find_map(|child|tab_host_find(child,id))
1199}
1200fn radio_descendant_by_id(node:&Node,id:u64)->Option<&Node> {
1201    if !node.id.is_empty() && view_id(node.id)==id {return Some(node);}
1202    node.children.iter().find_map(|child|radio_descendant_by_id(child,id))
1203}
1204/// SlidingDrawer notifications corresponding to Android's listeners.
1205#[derive(Clone,Copy,Debug,PartialEq,Eq)]
1206pub enum SlidingDrawerEvent { ScrollStarted, ScrollEnded, Opened, Closed }
1207#[derive(Clone,Default)]
1208pub 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>}
1209impl SlidingDrawerState {
1210    fn record(&mut self,event:SlidingDrawerEvent) {
1211        if self.events.len()==32 {self.events.remove(0);}
1212        self.events.push(event);
1213    }
1214    fn complete(&mut self,open:bool) {
1215        if self.open!=open {
1216            self.open=open;
1217            self.record(if open{SlidingDrawerEvent::Opened}else{SlidingDrawerEvent::Closed});
1218        }
1219    }
1220}
1221#[derive(Clone)]
1222pub struct LayoutState {
1223    /// Active Android Material / Material 3 theme preset; defaults to `AndroidTheme::Bhoo`.
1224    pub theme_style: AndroidTheme,
1225    /// Runtime display density multiplier (`dp` -> logical px). Defaults to `1.0`.
1226    pub density: f32,
1227    /// Runtime font scale multiplier (`sp` = `dp * font_scale`). Defaults to `1.0`.
1228    pub font_scale: f32,
1229    pub dialer_filters: HashMap<String,crate::android_dialer_filter::DialerFilterState>,
1230    pub tab_widget_clicked: HashMap<String,usize>,
1231    pub tab_hosts: HashMap<String,TabHostState>,
1232    tab_host_factory_cache: HashMap<(String,usize),&'static Node>,
1233    active_tab_host: Option<String>,
1234    gallery_gestures: HashMap<String,GalleryGesture>,
1235    gallery_rendered_generation: HashMap<String,u64>,
1236    pub gallery_clicked: HashMap<String,usize>,
1237    /// State for Android SlidingDrawer views, keyed by XML ID.
1238    pub sliding_drawers: HashMap<String,SlidingDrawerState>,
1239    /// Most recently clicked adapter position in a StackView.
1240    pub stack_clicked: HashMap<String,usize>,
1241    /// Runtime loop policy for each StackView. XML defaults to non-looping.
1242    pub stack_looping: HashMap<String,bool>,
1243    stack_gestures: HashMap<String,StackGesture>,
1244    stack_pending_step: HashMap<String,(usize,isize)>,
1245    stack_rendered_generation: HashMap<String,u64>,
1246    /// Override the Android screen-configuration policy for labels beside action icons.
1247    pub menu_allow_text_with_icon: Option<bool>,
1248    /// Host theme's GridLayout default gap in logical pixels. None uses Android's 8dp default.
1249    pub grid_default_gap: Option<f32>,
1250    /// Decoded frames supplied by the host; VideoView does not decode media itself.
1251    pub video_frames: HashMap<String,Image>,
1252    /// Original source dimensions when different from the decoded frame size.
1253    pub video_dimensions: HashMap<String,(u32,u32)>,
1254    /// IDs of videos whose host player is prepared for interaction.
1255    pub video_ready: std::collections::HashSet<String>,
1256    /// Video ID to floating controller ID and height in logical pixels.
1257    pub video_controllers: HashMap<String,(String,f32)>,
1258    pub media_players: HashMap<String,MediaPlayerSnapshot>,
1259    pub media_controller_actions: HashMap<String,MediaControllerAction>,
1260    pub media_controller_capabilities: HashMap<String,MediaControllerCapabilities>,
1261    media_active_capabilities: Option<MediaControllerCapabilities>,
1262    media_seek_progress: HashMap<String,f32>,
1263    media_floating: HashMap<String,MediaControllerFloating>,
1264    /// Host-provided contact targets; no Android contacts provider is accessed.
1265    pub quick_contact_targets: HashMap<String,QuickContactTarget>,
1266    /// Last activated target for each QuickContactBadge.
1267    pub quick_contact_clicked: HashMap<String,QuickContactTarget>,
1268    quick_contact_pressed: HashMap<String,QuickContactTarget>,
1269    pub quick_contact_lookups: HashMap<String,QuickContactLookup>,
1270    pub quick_contact_actions: HashMap<String,QuickContactAction>,
1271    quick_contact_generation: u64,
1272    /// Layout direction for relative FrameLayout start/end gravity.
1273    pub rtl: bool,
1274    /// Per-table overrides for Android TableLayout.setColumnCollapsed.
1275    pub table_collapsed: HashMap<(u64,usize),bool>,
1276    pub text: HashMap<String, String>,
1277    pub input_types: HashMap<String, u8>,
1278    /// Calendar widget state keyed by Android view ID.
1279    pub calendars: HashMap<String,crate::android_calendar::CalendarState>,
1280    /// NumberPicker values and displayed labels supplied by the host.
1281    pub number_pickers: HashMap<String,crate::android_number_picker::NumberPickerState>,
1282    pub date_spinners: HashMap<String,crate::android_date_spinner::DateSpinnerState>,
1283    pub time_spinners: HashMap<String,crate::android_time_spinner::TimeSpinnerState>,
1284    /// Expanded state, submit-button policy and last submitted query per SearchView ID.
1285    /// Caller-supplied groups and most recent user event for each expandable list.
1286    pub expandable_lists: HashMap<String,crate::android_expandable_list::ExpandableListState>,
1287    pub expandable_events: HashMap<String,crate::android_expandable_list::ExpandableEvent>,
1288    /// Most recent Toolbar navigation action, keyed by XML view ID.
1289    pub toolbar_navigation_clicked: std::collections::HashSet<String>,
1290    pub toolbar_title_colors: HashMap<String,Color>,
1291    pub toolbar_subtitle_colors: HashMap<String,Color>,
1292    /// Toolbar menu entries supplied by the host, in display order.
1293    pub toolbar_menu_items: HashMap<String,Vec<AndroidToolbarMenuItem>>,
1294    /// The ID of the last activated menu item for each toolbar.
1295    pub toolbar_menu_clicked: HashMap<String,u64>,
1296    toolbar_menu_overlays: HashMap<String,OverlayState>,
1297    /// Group IDs whose clicks are handled by the host before expansion.
1298    pub expandable_intercepted_groups: HashMap<String,std::collections::HashSet<u64>>,
1299    /// Most recent group position clicked, including intercepted clicks.
1300    pub expandable_group_clicked: HashMap<String,usize>,
1301    expandable_templates: HashMap<String,(Option<ListItemTemplate>,Option<ListItemTemplate>)>,
1302    expandable_bindings: HashMap<String,HashMap<(u64,Option<u64>),AdapterItemBinding>>,
1303    expandable_control_states: HashMap<(String,u64,Option<u64>),HashMap<String,bool>>,
1304    adapter_namespace: Option<u64>,
1305    /// Last XML control activated within an expandable row.
1306    pub expandable_control_events: HashMap<String,(crate::android_expandable_list::FlatPosition,&'static str)>,
1307    pub search_open: HashMap<String,bool>,
1308    pub search_submit_enabled: std::collections::HashSet<String>,
1309    pub search_submitted: HashMap<String,String>,
1310    /// Last activated local suggestion index for each SearchView.
1311    pub search_suggestion_clicked: HashMap<String,usize>,
1312    /// Minimum query length before showing local suggestions; defaults to one.
1313    pub search_suggestion_threshold: HashMap<String,usize>,
1314    // Keep the original filter while keyboard selection previews suggestion text.
1315    search_suggestion_preview: HashMap<String,(String,String)>,
1316    search_pending: std::collections::HashSet<String>,
1317    search_focus_requested: std::collections::HashSet<String>,
1318    pub time_clocks: HashMap<String,crate::android_time_clock::TimeClockState>,
1319    time_clock_dragging: std::collections::HashSet<String>,
1320    time_clock_transition: HashMap<String,TimeClockTransition>,
1321    pub time_clock_text_mode: std::collections::HashSet<String>,
1322    time_clock_field_owner: HashMap<String,(String,crate::android_time_clock::DialPart)>,
1323    time_clock_invalid: std::collections::HashSet<String>,
1324    time_clock_changed: std::collections::HashSet<String>,
1325    number_picker_motion: HashMap<String,NumberPickerMotion>,
1326    /// Fields currently showing the host text editor.
1327    pub number_picker_editing: std::collections::HashSet<String>,
1328    number_picker_committed: std::collections::HashSet<String>,
1329    /// Localized Gregorian labels and default week start, supplied by the host.
1330    pub calendar_locale: crate::android_calendar::CalendarLocale,
1331    calendar_motion: HashMap<String,CalendarMotion>,
1332    datepicker_year_open: std::collections::HashSet<String>,
1333    datepicker_year_scroll: HashMap<String,f32>,
1334    datepicker_fades: HashMap<String,DatePickerFade>,
1335    autocomplete_items: HashMap<String,Vec<String>>,
1336    /// UTF-16 selection end supplied by the host text editor.
1337    pub text_selection_end: HashMap<String,usize>,
1338    /// Fields configured by the host with Android’s comma tokenizer.
1339    pub comma_tokenizers: std::collections::HashSet<String>,
1340    autocomplete_matches: HashMap<String,AutoMatches>,
1341    autocomplete_anchor: Option<AutoAnchor>,
1342    autocomplete_open: Option<String>,
1343    autocomplete_panel: Option<Rect>,
1344    autocomplete_dismissed: HashMap<String,String>,
1345    autocomplete_highlight: HashMap<String,usize>,
1346    autocomplete_scroll: HashMap<String,f32>,
1347    /// Most recently selected suggestion index, keyed by field ID.
1348    pub autocomplete_selected: HashMap<String,usize>,
1349    /// Decoded drawable images supplied by the application, keyed by resource name.
1350    pub images: HashMap<String, crate::Image>,
1351    /// Source pixel size in density-independent units per drawable.
1352    pub image_scales: HashMap<String, f32>,
1353    /// Axis-aligned matrix scale and translation (sx, sy, tx, ty), keyed by view ID.
1354    pub image_matrices: HashMap<String, [f32; 4]>,
1355    pub drawable_tints: HashMap<String,AndroidDrawableTint>,
1356    /// Runtime drawable-name overrides by ImageView ID.
1357    pub image_sources: HashMap<String, String>,
1358    /// Application-owned selected and activated state for Android views.
1359    pub view_selected: HashMap<String,bool>,
1360    pub view_activated: HashMap<String,bool>,
1361    /// Caller-owned MaterialCardView dragged states, keyed by XML ID.
1362    pub view_dragged: HashMap<String,bool>,
1363    #[doc(hidden)] pub tinted_images: HashMap<(u32,[u8;4],u8),Image>,
1364    #[doc(hidden)] pub tinted_image_bytes: usize,
1365    /// Per-view long-press repeat deadline and whether repetition started.
1366    pub zoom_holds: HashMap<u64,(f64,bool,bool)>,
1367    /// ZoomButton repeat intervals in milliseconds, keyed by XML view ID.
1368    /// The default is 1000 ms; zero is limited to 1 ms to avoid a busy loop.
1369    pub zoom_speed_ms: HashMap<String,u64>,
1370    /// Per-control enabled state for the zoom-out and zoom-in buttons.
1371    pub zoom_controls_enabled: HashMap<String,[bool;2]>,
1372    /// Most recent action for a rendered ZoomControls: -1 out or 1 in.
1373    pub zoom_controls_actions: HashMap<String,i8>,
1374    pub zoom_controls_fades: HashMap<String,ZoomControlsFade>,
1375    pub checked: HashMap<String, bool>,
1376    /// Adapter entries and selected index for Android Spinner views.
1377    pub spinner_items: HashMap<String,Vec<String>>,
1378    pub spinner_selected: HashMap<String,usize>,
1379    /// Optional stable IDs supplied alongside adapter entries.
1380    pub spinner_item_ids: HashMap<String,Vec<i64>>,
1381    /// Optional per-item enabled flags; missing positions are enabled.
1382    pub spinner_enabled: HashMap<String,Vec<bool>>,
1383    /// Host-supplied ListView adapter labels, checked indices, and last click.
1384    pub list_items: HashMap<String,Vec<String>>,
1385    /// Optional unique stable IDs corresponding to ListView adapter items.
1386    pub list_item_ids: HashMap<String,Vec<i64>>,
1387    pub list_checked: HashMap<String,Vec<usize>>,
1388    list_control_states: HashMap<(String,i64),HashMap<String,bool>>,
1389    /// Most recent ListView child-control activation, as adapter position and XML view ID.
1390    pub list_control_clicked: HashMap<String,(usize,&'static str)>,
1391    pub list_clicked: HashMap<String,usize>,
1392    list_item_bindings: HashMap<String,HashMap<usize,AdapterItemBinding>>,
1393    /// Enable and retrieve handled item long presses by ListView ID.
1394    pub list_long_click_enabled: HashMap<String,bool>,
1395    pub list_long_clicked: HashMap<String,usize>,
1396    list_holds: HashMap<String,Option<ListHold>>,
1397    /// Missing item enabled flags default to true.
1398    pub list_enabled: HashMap<String,Vec<bool>>,
1399    /// Most recent selectable fixed-view click: (is_footer, index within that group).
1400    pub list_fixed_clicked: HashMap<String,(bool,usize)>,
1401    /// Most recent control activation in a fixed view: footer flag, view index, XML ID.
1402    pub list_fixed_control_clicked: HashMap<String,(bool,usize,&'static str)>,
1403    list_fixed_control_states: HashMap<(String,bool,usize),HashMap<String,bool>>,
1404    list_fixed_views: HashMap<String,(Vec<ListFixedView>,Vec<ListFixedView>)>,
1405    adapter_root_response: Option<(u64,Response)>,
1406    list_templates: HashMap<String,ListItemTemplate>,
1407    list_text_geometry: HashMap<String,std::sync::Arc<ListTextGeometry>>,
1408    list_pending_focus: HashMap<String,usize>,
1409    spinner_templates: HashMap<String,SpinnerItemTemplates>,
1410    spinner_row_cache: HashMap<String,(u64,std::sync::Arc<Vec<f32>>)>,
1411    spinner_highlight: HashMap<String,usize>,
1412    spinner_scroll: HashMap<String,crate::scroll::ScrollPhysics>,
1413    pub spinner_open: Option<String>,
1414    spinner_anchor: Option<SpinnerAnchor>,
1415    spinner_dialogs: HashMap<String,OverlayState>,
1416    spinner_closing: Option<String>,
1417    pub radio_groups: HashMap<u64, Option<u64>>,
1418    radio_group_requests: HashMap<String, Option<String>>,
1419    radio_group_events: HashMap<String, Vec<Option<u64>>>,
1420    pub progress: HashMap<String, f32>,
1421    pub secondary_progress: HashMap<String, f32>,
1422    pub ratings: HashMap<String, f32>,
1423    pub offsets: HashMap<String, f32>,
1424    expandable_scrolls: HashMap<String, crate::android_expandable_list::ExpansionScroll>,
1425    expandable_pending_scroll: HashMap<String,u64>,
1426    expandable_geometry: HashMap<String,std::sync::Arc<ListTextGeometry>>,
1427    /// Displayed child index for ViewAnimator and ViewSwitcher, keyed by view ID.
1428    pub displayed_children: HashMap<String, usize>,
1429    pub transitions: HashMap<u64, ViewTransition>,
1430    pub flipper_running: HashMap<String, bool>,
1431    /// Most recent clicked adapter position for an AdapterViewFlipper.
1432    pub adapter_flipper_clicked: HashMap<String,usize>,
1433    /// Flippers advanced by their host rather than by their own timer.
1434    pub adapter_flipper_host_advanced: std::collections::HashSet<String>,
1435    adapter_flipper_data_generation: HashMap<String,u64>,
1436    adapter_flipper_rendered_generation: HashMap<String,u64>,
1437    adapter_flipper_animated: std::collections::HashSet<String>,
1438    pub flipper_clocks: HashMap<u64, FlipperClock>,
1439    pub chronometers: HashMap<String, ChronometerState>,
1440    /// Wall-clock snapshot supplied by the host, including local UTC offset.
1441    pub wall_clock: Option<WallClock>,
1442    /// Runtime overrides for views with Android IDs.
1443    pub visibility: HashMap<String, Visibility>,
1444    /// Per-field password visibility toggle state for TextInputLayout password_toggle end icon.
1445    text_input_password_visible: HashMap<String, bool>,
1446    /// Active TextInputLayout box context while rendering its EditText child.
1447    text_input_active_box: Option<TextInputChildBox>,
1448    /// Selected destination index for `RULE_NAV_BAR` containers (`bar`/`rail`/`drawer`), keyed by XML ID.
1449    pub selected_index: HashMap<String, usize>,
1450    /// Runtime badges for `RULE_NAV_BAR` destinations (`bar`/`rail`), keyed by nav item XML ID.
1451    /// Empty string `""` renders a 6dp circular dot badge; non-empty text renders a 16dp pill badge.
1452    pub nav_badges: HashMap<String, String>,
1453    /// Refreshing state for `RULE_SWIPE_REFRESH` (`SwipeRefreshLayout`) containers, keyed by XML ID.
1454    pub refreshing: HashMap<String, bool>,
1455    /// Open state for `RULE_DRAWER_LAYOUT` (`DrawerLayout`) containers, keyed by XML ID.
1456    pub drawer_open: HashMap<String, bool>,
1457    /// Lock mode for `RULE_DRAWER_LAYOUT` (`DrawerLayout`) drawers, keyed by `"{id}"` (start) and `"{id}:end"` (end).
1458    /// Values: `0 = UNLOCKED`, `1 = LOCKED_CLOSED`, `2 = LOCKED_OPEN`, `3 = UNDEFINED`.
1459    pub drawer_lock_mode: HashMap<String, u8>,
1460    /// Active DrawerLayout drawer panel context while rendering a drawer child.
1461    drawer_panel_active: bool,
1462    /// Active MaterialButtonToggleGroup segment context while rendering a child button.
1463    toggle_group_segment: Option<ToggleGroupSegment>,
1464    /// Toggle groups whose initial `checked_id` / child `checked` flags have been seeded into `state.checked`.
1465    toggle_groups_initialized: std::collections::HashSet<u64>,
1466    /// Two-thumb values `[start, end]` for `RULE_RANGE_SLIDER` (`RangeSlider`) views, keyed by XML ID.
1467    pub range_values: HashMap<String, [f32; 2]>,
1468    /// Active dragged thumb index (`0` or `1`) for `RULE_RANGE_SLIDER`, keyed by view ID.
1469    range_slider_active_thumb: HashMap<u64, usize>,
1470    /// Interactive swipe/settle gesture state for `RULE_VIEW_PAGER` views, keyed by XML ID.
1471    view_pager_gestures: HashMap<String, ViewPagerGesture>,
1472    /// Scroll offset from sibling scrolling view propagated to `RULE_COLLAPSING_TOOLBAR`.
1473    collapsing_scroll_offset: Option<f32>,
1474    /// Active CollapsingToolbarLayout context while rendering a child Toolbar.
1475    collapsing_toolbar_child: bool,
1476    /// Sheet state for `RULE_BOTTOM_SHEET` / `RULE_SIDE_SHEET` views, keyed by XML ID
1477    /// (`SHEET_STATE_EXPANDED=3`, `SHEET_STATE_COLLAPSED=4`, `SHEET_STATE_HIDDEN=5`, `SHEET_STATE_HALF_EXPANDED=6`).
1478    pub sheet_state: HashMap<String, u8>,
1479    /// Exposed dropdown menu entries for `TextInputLayout` (`end_icon == "dropdown_menu"`), keyed by child Edit ID.
1480    pub entries: HashMap<String, Vec<String>>,
1481    /// Per-node morph state for `RULE_LOADING_INDICATOR` (`LoadingIndicator`) views.
1482    loading_states: HashMap<u64, crate::loading::LoadingState>,
1483    /// Currently open `TextInputLayout` exposed dropdown key.
1484    til_dropdown_open: Option<String>,
1485    /// Anchor metadata for open `TextInputLayout` exposed dropdown popup.
1486    til_dropdown_anchor: Option<TilDropdownAnchor>,
1487    /// Rendered popup bounds for open `TextInputLayout` exposed dropdown.
1488    til_dropdown_panel: Option<Rect>,
1489    /// Horizontal scroll offsets for scrollable `RULE_TAB_OPTIONS` tab strips, keyed by XML ID.
1490    tab_scroll_offsets: HashMap<String, f32>,
1491    /// Active `RULE_SNACKBAR` context while rendering Snackbar children.
1492    snackbar_active: bool,
1493    /// Active `RULE_SPLIT_BUTTON` segment role while rendering split button child buttons.
1494    split_button_role: Option<SplitButtonRole>,
1495    /// `RULE_CHIP_GROUP_WRAP` groups whose initial single-selection exclusion has been seeded.
1496    chip_groups_initialized: std::collections::HashSet<u64>,
1497    /// Two-way synchronization links between `TabWidget` (`TabLayout`) and `RULE_VIEW_PAGER` (`ViewPager2`) XML IDs.
1498    pub tab_pager_links: HashMap<String, String>,
1499    /// Interactive drag and settle motion state for `RULE_BOTTOM_SHEET` and modal `RULE_SIDE_SHEET` views.
1500    sheet_motion: HashMap<String, XmlSheetMotion>,
1501    /// Animated slide-in/out and drag-to-close motion state for `RULE_DRAWER_LAYOUT` containers.
1502    drawer_motion: HashMap<String, XmlDrawerMotion>,
1503    /// Active `RULE_BOTTOM_SHEET` key while rendering its children (for `RULE_DRAG_HANDLE` click toggle).
1504    active_bottom_sheet: Option<String>,
1505    /// Set when a `RULE_DRAG_HANDLE` child inside an active bottom sheet is clicked without dragging.
1506    drag_handle_toggled: bool,
1507    /// Last observed tab selection per `TabWidget` key to synchronize `selected_index` and `displayed_children`.
1508    tab_last_index: HashMap<String, usize>,
1509    /// Runtime alpha multiplier overrides (`0.0..=1.0`, matching Android `View.setAlpha`), keyed by XML ID.
1510    pub view_alpha: HashMap<String, f32>,
1511    /// Runtime scale overrides `[sx, sy]` (matching Android `View.setScaleX`/`setScaleY`), keyed by XML ID.
1512    pub view_scale: HashMap<String, [f32; 2]>,
1513    /// Runtime translation overrides `[tx_dp, ty_dp]` (matching Android `View.setTranslationX`/`setTranslationY`), keyed by XML ID.
1514    pub view_translation: HashMap<String, [f32; 2]>,
1515    /// Bounded cache of rasterized radial/sweep (and cut-corner linear) gradient images.
1516    gradient_images: HashMap<GradientCacheKey, Image>,
1517    gradient_image_bytes: usize,
1518    /// Bounded cache of rasterized chamfered cut-corner shape fills.
1519    cut_shape_images: HashMap<CutShapeCacheKey, Image>,
1520    cut_shape_image_bytes: usize,
1521    /// Smooth liftOnScroll transition progress per AppBarLayout / Toolbar XML ID.
1522    app_bar_lift_motion: HashMap<String, XmlLiftMotion>,
1523    /// Active lifted AppBarLayout context while rendering its child Toolbar.
1524    lifted_appbar_active: bool,
1525    /// Dynamic target sibling XML ID override for `RULE_CONSTRAINT_PLACEHOLDER` views, keyed by placeholder XML ID.
1526    pub placeholder_content: HashMap<String, String>,
1527    /// Scroll-delta collapse tracking for `RULE_APP_BAR_SCROLL_FLAGS` (`enterAlways`) children, keyed by view key.
1528    app_bar_scroll_motion: HashMap<String, AppBarScrollState>,
1529    /// Runtime drawable level (`0..=10000`, Android `Drawable.setLevel`) for `RULE_DRAWABLE_DYNAMIC`, keyed by XML ID.
1530    pub drawable_level: HashMap<String, u32>,
1531    /// Runtime transition state (`false` = layer 0, `true` = layer 1) for `RULE_DRAWABLE_DYNAMIC` `"transition|..."`, keyed by XML ID.
1532    pub drawable_transition_active: HashMap<String, bool>,
1533    /// Internal crossfade animation state for `RULE_DRAWABLE_DYNAMIC` `"transition|..."` drawables.
1534    drawable_transition_motion: HashMap<String, DrawableTransitionMotion>,
1535    /// Suppresses direct-child static `RULE_ELEVATION` when parent `ViewAnimator`/`AdapterViewFlipper` renders an elevation transition.
1536    suppress_next_elevation: bool,
1537    /// Bounded internal state tracking previous 7-bit state masks and active `<animated-selector>` transitions.
1538    animated_selector_states: HashMap<String, AnimatedSelectorState>,
1539    /// Runtime extended/collapsed override for `ExtendedFloatingActionButton`, keyed by node `id`.
1540    pub fab_extended: HashMap<String, bool>,
1541    /// Bounded internal scrim alpha fade motion for `RULE_COLLAPSING_TOOLBAR_EXT`.
1542    collapsing_scrim_motion: HashMap<String, XmlLiftMotion>,
1543    /// Bounded internal expand/collapse width motion for `ExtendedFloatingActionButton`.
1544    extended_fab_motion: HashMap<String, XmlLiftMotion>,
1545    /// Bounded internal hide-on-scroll slide motion for `RULE_BOTTOM_APP_BAR_EXT`.
1546    bottom_app_bar_hide_motion: HashMap<String, BottomAppBarHideState>,
1547    /// Bounded cache of rasterized `BottomAppBar` cradle-cutout surfaces.
1548    bottom_app_bar_images: HashMap<BottomAppBarCradleCacheKey, Image>,
1549    bottom_app_bar_image_bytes: usize,
1550    /// True while entering top-level `Node::render_inner` root `draw` (before descending into children).
1551    at_root_draw: bool,
1552    /// Suppresses double-applying `hide_on_scroll` offset when CoordinatorLayout already shifted `BottomAppBar`.
1553    bab_hide_applied_by_parent: bool,
1554    /// Current frame clock & motion/scroll snapshot for pure layout evaluation (AppBarLayout snap settle).
1555    frame_time: f64,
1556    frame_reduced_motion: bool,
1557    frame_scroll_dragging: bool,
1558    /// Bounded open/close ease-out animation state for `RULE_SEARCH_VIEW_EXT` overlays.
1559    search_view_motion: HashMap<String, XmlLiftMotion>,
1560    /// Transient per-frame `(anchor_bar_id, search_view_key)` coupling table populated at root render.
1561    search_bar_links: Vec<(String, String)>,
1562    /// Bounded pull-to-refresh drag/retract physics state for `RULE_SWIPE_REFRESH` / `RULE_SWIPE_REFRESH_EXT`.
1563    swipe_refresh_motion: HashMap<String, SwipeRefreshMotion>,
1564    /// Bounded drag & focal snap settle state for `RULE_CAROUSEL_LAYOUT` containers.
1565    carousel_motion: HashMap<String, CarouselMotion>,
1566    /// Most recently clicked auto-link span text from `RULE_TEXT_LINKS_SPANS`, overwritten on each link click.
1567    pub last_clicked_link: Option<String>,
1568}
1569
1570mod constraint_layout;
1571mod draw;
1572mod draw_adapter_views;
1573mod draw_containers;
1574mod draw_widgets;
1575mod drawables;
1576mod helpers;
1577mod measure;
1578mod render;
1579mod specs;
1580mod state;
1581mod text;
1582
1583use constraint_layout::*;
1584use drawables::*;
1585use helpers::*;
1586use specs::*;
1587use text::*;
1588pub use helpers::{quick_contact_default_avatar, view_id};
1589
1590#[cfg(test)]
1591mod object_animation_offset_tests {
1592    use super::*;
1593    #[test]
1594    fn object_delays_leave_properties_at_identity_and_each_axis_has_own_timing() {
1595        let a=AlphaAnimation{from:0.0,to:1.0,duration:0.4,start_offset:0.2,linear:true};
1596        assert_eq!(a.sample(0.1,true),1.0);
1597        assert_eq!(a.sample(0.1,false),0.0);
1598        assert!((a.sample(0.4,true)-0.5).abs()<0.001);
1599        let zero=AnimationDelta{value:0.0,mode:0};
1600        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))};
1601        let b=Rect{x:0.,y:0.,width:100.,height:100.};
1602        assert_eq!(t.sample(0.1,b,b,true),[0.0,0.0]);
1603        assert_eq!(t.sample(0.1,b,b,false),[40.0,20.0]);
1604        let v=t.sample(0.4,b,b,true);assert!((v[0]-20.0).abs()<0.001);assert_eq!(v[1],0.0);
1605        let v=t.sample(0.7,b,b,true);assert_eq!(v[0],0.0);assert!((v[1]-10.0).abs()<0.001);
1606        assert!((t.total_duration()-0.9).abs()<0.001);
1607    }
1608}