Skip to main content

bhoo/systems/android/xml/
measure.rs

1use super::*;
2
3impl Node {
4    // Offset of the first rendered text baseline from the view's top edge.
5    pub(super) fn relative_baseline(
6        &self,
7        width: f32,
8        height: f32,
9        state: &LayoutState,
10        metrics: TextMetrics,
11        id: u64,
12    ) -> Option<f32> {
13        let padding = self.resolved_padding(state);
14        let inner_height = (height - padding[1] - padding[3]).max(0.0);
15        if matches!(
16            self.kind,
17            Kind::Image | Kind::QuickContactBadge | Kind::Icon | Kind::Zoom
18        ) {
19            if self.relative_rules.iter().any(|r| r.kind == 190) {
20                return Some(height);
21            }
22            return self
23                .relative_rules
24                .iter()
25                .find(|r| r.kind == 189)
26                .and_then(|r| r.anchor.parse::<f32>().ok())
27                .filter(|v| v.is_finite() && *v >= 0.0)
28                .map(|v| state.dp(v));
29        }
30        if matches!(self.kind, Kind::Linear | Kind::RadioGroup | Kind::TableRow) {
31            // LinearLayout.getBaseline() delegates to the explicitly selected child.
32            // Android rejects a weighted child before that index in a vertical layout.
33            let index = self
34                .relative_rules
35                .iter()
36                .find(|r| r.kind == 148)?
37                .anchor
38                .parse::<usize>()
39                .ok()?;
40            let child = self.children.get(index)?;
41            let horizontal = self.horizontal || matches!(self.kind, Kind::TableRow);
42            if child.effective_visibility(state) == Visibility::Gone
43                || (!horizontal
44                    && self.children[..index].iter().any(|n| {
45                        n.effective_visibility(state) != Visibility::Gone && n.weight > 0.0
46                    }))
47            {
48                return None;
49            }
50            let inner_width = (width - padding[0] - padding[2]).max(0.0);
51            let size = if horizontal {
52                inner_width
53            } else {
54                inner_height
55            };
56            let mut lengths = Vec::with_capacity(self.children.len());
57            let divider_thickness = state.dp(self.divider_thickness);
58            let mut fixed = self.divider_count(state) as f32 * divider_thickness;
59            let mut weight = 0.0;
60            for (i, n) in self.children.iter().enumerate() {
61                if n.effective_visibility(state) == Visibility::Gone {
62                    lengths.push(0.0);
63                    continue;
64                }
65                let m = n.resolved_margin(state);
66                let available = (inner_width - m[0] - m[2]).max(0.0);
67                let value = n.layout_intrinsic(
68                    horizontal,
69                    state,
70                    available,
71                    metrics,
72                    child_view_id(id, i, n),
73                );
74                fixed += value + n.margin_for_axis(horizontal, state);
75                weight += n.weight;
76                lengths.push(value);
77            }
78            let mut excess = size - fixed;
79            let mut remaining = if self.weight_sum > 0.0 {
80                self.weight_sum
81            } else {
82                weight
83            };
84            for (i, n) in self.children.iter().enumerate() {
85                if n.effective_visibility(state) == Visibility::Gone {
86                    continue;
87                }
88                let share = if n.weight > 0.0 && remaining.abs() > f32::EPSILON {
89                    excess * n.weight / remaining
90                } else {
91                    0.0
92                };
93                if n.weight > 0.0 {
94                    excess -= share;
95                    remaining -= n.weight;
96                }
97                lengths[i] = (lengths[i] + share).max(0.0);
98            }
99            let margin = child.resolved_margin(state);
100            let available_width = (inner_width - margin[0] - margin[2]).max(0.0);
101            let child_width = if horizontal {
102                lengths[index]
103            } else {
104                match child.width {
105                    Size::Dp(v) => state.dp(v).min(available_width),
106                    Size::Wrap => child
107                        .intrinsic(true, state, child_view_id(id, index, child))
108                        .min(available_width),
109                    Size::Match => available_width,
110                }
111            };
112            let available_height = (inner_height - margin[1] - margin[3]).max(0.0);
113            let child_height = if !horizontal {
114                lengths[index]
115            } else {
116                match child.height {
117                    Size::Dp(v) => state.dp(v).min(available_height),
118                    Size::Wrap => child
119                        .layout_intrinsic(
120                            false,
121                            state,
122                            child_width,
123                            metrics,
124                            child_view_id(id, index, child),
125                        )
126                        .min(available_height),
127                    Size::Match => available_height,
128                }
129            };
130            let baseline = child.relative_baseline(
131                child_width,
132                child_height,
133                state,
134                metrics,
135                child_view_id(id, index, child),
136            )?;
137            let mut child_top = 0.0;
138            if !horizontal {
139                let mut visible = 0usize;
140                for (i, n) in self.children.iter().enumerate().take(index) {
141                    if n.effective_visibility(state) == Visibility::Gone {
142                        continue;
143                    }
144                    if self.divider_color.is_some()
145                        && (if visible == 0 {
146                            self.divider_flags & 1 != 0
147                        } else {
148                            self.divider_flags & 2 != 0
149                        })
150                    {
151                        child_top += divider_thickness;
152                    }
153                    visible += 1;
154                    child_top += lengths[i] + n.margin_for_axis(false, state);
155                }
156                let total = lengths
157                    .iter()
158                    .enumerate()
159                    .filter(|(i, _)| {
160                        self.children[*i].effective_visibility(state) != Visibility::Gone
161                    })
162                    .map(|(i, length)| *length + self.children[i].margin_for_axis(false, state))
163                    .sum::<f32>()
164                    + self.divider_count(state) as f32 * divider_thickness
165                    + padding[1]
166                    + padding[3];
167                match self.content_gravity[1] {
168                    1 => child_top += ((height - padding[1] - padding[3]) - total) / 2.0,
169                    2 => child_top = height - padding[3] - total,
170                    _ => {}
171                }
172            }
173            return Some(child_top + margin[1] + baseline);
174        }
175        let (effective_size, effective_weight, italic, family) = self.effective_text_font(state);
176        let offset = if effective_weight >= 500 {
177            metrics.medium_baseline_offset
178        } else {
179            metrics.normal_baseline_offset
180        };
181        if matches!(self.kind, Kind::Button) {
182            let rtl = match self.layout_direction {
183                1 => false,
184                2 => true,
185                _ => state.rtl,
186            };
187            let compound = self.compound_extents(state, rtl);
188            let text_height = (inner_height - compound[1] - compound[3]).max(0.0);
189            let text_width = (width - padding[0] - padding[2] - compound[0] - compound[2]).max(0.0);
190            let key = if self.id.is_empty() {
191                format!("#{id}")
192            } else {
193                self.id.to_owned()
194            };
195            let text = self.display_text_for(
196                state.text.get(&key).map_or(self.text, String::as_str),
197                state,
198            );
199            let layout_ext = self.text_layout_ext();
200            let base_style = TextStyle {
201                size: effective_size,
202                weight: effective_weight,
203                letter_spacing: self.letter_spacing_em * effective_size,
204                italic,
205                family,
206                ..TextStyle::default()
207            };
208            let effective_size = if let Some(ext) = layout_ext
209                && ext.has_auto_size()
210            {
211                self.resolve_auto_text_size(
212                    &text,
213                    text_width,
214                    text_height,
215                    base_style,
216                    ext,
217                    state,
218                    metrics,
219                )
220            } else {
221                effective_size
222            };
223            let style = TextStyle {
224                size: effective_size,
225                weight: effective_weight,
226                letter_spacing: self.letter_spacing_em * effective_size,
227                italic,
228                family,
229                ..TextStyle::default()
230            };
231            let simple = layout_ext.is_none()
232                && !text.contains([
233                    '\n', '\r', '\u{000b}', '\u{000c}', '\u{0085}', '\u{2028}', '\u{2029}',
234                ])
235                && metrics.width(&text, style) <= text_width + 0.01
236                && self.min_lines <= 1
237                && self.ellipsize_side == 0
238                && !self.ellipsize_end;
239            if simple {
240                return Some(
241                    padding[1] + compound[1] + text_height * 0.5 + effective_size * offset,
242                );
243            }
244            let line_height = self.resolved_line_height(effective_size, state);
245            let advance = (line_height * self.line_spacing_multiplier
246                + state.dp(self.line_spacing_extra))
247            .max(1.0);
248            let single = self.single_line
249                || (self.max_lines == 1 && (self.ellipsize_side != 0 || self.ellipsize_end));
250            let total = if single {
251                1
252            } else if let Some(ext) = layout_ext {
253                wrap_text_lines_ext(&text, text_width + 0.01, style, metrics, ext)
254                    .len()
255                    .max(1)
256            } else {
257                wrapped_text_lines(&text, text_width + 0.01, style, metrics, |_| {}).max(1)
258            };
259            let height_limit = if text_height <= 0.0 {
260                0
261            } else {
262                ((text_height - line_height).max(0.0) / advance).ceil() as usize + 1
263            };
264            let limit = if self.max_lines == 0 {
265                height_limit
266            } else {
267                height_limit.min(self.max_lines)
268            };
269            let shown = total.min(limit);
270            let used = if shown == 0 {
271                0.0
272            } else {
273                (line_height + (shown - 1) as f32 * advance).min(text_height)
274            };
275            let extra = (text_height - used).max(0.0);
276            let gravity = if self.relative_rules.iter().any(|rule| rule.kind == 168) {
277                self.content_gravity[1]
278            } else {
279                1
280            };
281            let shift = match gravity {
282                0 => 0.0,
283                2 => extra,
284                _ => extra * 0.5,
285            };
286            return Some(
287                padding[1] + compound[1] + shift + line_height * 0.5 + effective_size * offset,
288            );
289        }
290        let scaled_text = self.scaled_text_size(state);
291        if matches!(self.kind, Kind::ToggleButton) {
292            return Some(padding[1] + inner_height * 0.5 + scaled_text * offset);
293        }
294        if matches!(
295            self.kind,
296            Kind::Edit | Kind::AutoComplete | Kind::MultiAutoComplete
297        ) {
298            // Editable text is painted in the lower portion of Bhoo's 48 dp field.
299            let field_height = inner_height.min(state.dp(48.0));
300            let top_offset = state.dp(16.0);
301            return Some(
302                padding[1]
303                    + top_offset
304                    + (field_height - top_offset).max(0.0) * 0.5
305                    + state.sp(TextStyle::default().size) * metrics.normal_baseline_offset,
306            );
307        }
308        if matches!(self.kind, Kind::CheckBox | Kind::RadioButton | Kind::Switch) {
309            // These controls render their label in their allocated 40/36 dp row,
310            // clipped to the inner height, before applying the XML text style.
311            let row_height = state.dp(if matches!(self.kind, Kind::Switch) {
312                36.0_f32
313            } else {
314                40.0_f32
315            });
316            return Some(padding[1] + inner_height.min(row_height) * 0.5 + scaled_text * offset);
317        }
318        if !matches!(
319            self.kind,
320            Kind::Text | Kind::CheckedText | Kind::Chronometer | Kind::TextClock
321        ) {
322            return None;
323        }
324        let rtl = match self.layout_direction {
325            1 => false,
326            2 => true,
327            _ => state.rtl,
328        };
329        let compound = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
330            self.compound_extents(state, rtl)
331        } else {
332            [0.0; 4]
333        };
334        let inner_height = (inner_height - compound[1] - compound[3]).max(0.0);
335        let inner_width = (width
336            - padding[0]
337            - padding[2]
338            - compound[0]
339            - compound[2]
340            - if matches!(self.kind, Kind::CheckedText) {
341                self.check_mark_width(state)
342            } else {
343                0.0
344            })
345        .max(0.0);
346        let key = if self.id.is_empty() {
347            format!("#{id}")
348        } else {
349            self.id.to_string()
350        };
351        let text = self.display_text_for(
352            state.text.get(&key).map_or(self.text, String::as_str),
353            state,
354        );
355        let layout_ext = self.text_layout_ext();
356        let base_style = TextStyle {
357            size: scaled_text,
358            weight: if self.text_bold { 700 } else { 400 },
359            letter_spacing: self.letter_spacing_em * scaled_text,
360            italic,
361            family,
362            ..TextStyle::default()
363        };
364        let scaled_text = if let Some(ext) = layout_ext
365            && ext.has_auto_size()
366        {
367            self.resolve_auto_text_size(
368                &text,
369                inner_width,
370                inner_height,
371                base_style,
372                ext,
373                state,
374                metrics,
375            )
376        } else {
377            scaled_text
378        };
379        let line_height = self.resolved_line_height(scaled_text, state);
380        let advance = (line_height * self.line_spacing_multiplier
381            + state.dp(self.line_spacing_extra))
382        .max(1.0);
383        let style = TextStyle {
384            size: scaled_text,
385            weight: if self.text_bold { 700 } else { 400 },
386            letter_spacing: self.letter_spacing_em * scaled_text,
387            italic,
388            family,
389            ..TextStyle::default()
390        };
391        let used = if self.single_line || (self.max_lines == 1 && self.ellipsize_side != 0) {
392            line_height
393        } else {
394            let total = if let Some(ext) = layout_ext {
395                wrap_text_lines_ext(&text, inner_width, style, metrics, ext)
396                    .len()
397                    .max(1)
398            } else {
399                wrapped_text_lines(&text, inner_width, style, metrics, |_| {})
400            };
401            let height_limit = if inner_height <= 0.0 {
402                0
403            } else {
404                ((inner_height - line_height).max(0.0) / advance).ceil() as usize + 1
405            };
406            let shown = total.min(if self.max_lines == 0 {
407                height_limit
408            } else {
409                height_limit.min(self.max_lines)
410            });
411            if shown == 0 {
412                0.0
413            } else {
414                (line_height + (shown - 1) as f32 * advance).min(inner_height)
415            }
416        };
417        let extra = (inner_height - used).max(0.0);
418        let shift = match self.content_gravity[1] {
419            1 => extra * 0.5,
420            2 => extra,
421            _ => 0.0,
422        };
423        Some(padding[1] + compound[1] + shift + line_height * 0.5 + scaled_text * offset)
424    }
425    pub(super) fn resolved_state_color(
426        &self,
427        rules: &[TintState],
428        fallback: Option<Color>,
429        state: &LayoutState,
430        key: &str,
431        response: Response,
432    ) -> Option<Color> {
433        if rules.is_empty() {
434            return fallback;
435        }
436        let checkable = matches!(
437            self.kind,
438            Kind::CheckedText
439                | Kind::CheckBox
440                | Kind::RadioButton
441                | Kind::Switch
442                | Kind::ToggleButton
443        ) || self.chip_style().is_some()
444            || state.toggle_group_segment.is_some();
445        let bits = (u8::from(response.enabled))
446            | (u8::from(response.pressed) << 1)
447            | (u8::from(response.focused) << 2)
448            | (u8::from(state.view_selected.get(key).copied().unwrap_or(false)) << 3)
449            | (u8::from(state.view_activated.get(key).copied().unwrap_or(false)) << 4)
450            | (u8::from(response.hovered) << 5)
451            | (u8::from(checkable && state.checked.get(key).copied().unwrap_or(self.checked)) << 6);
452        rules
453            .iter()
454            .find(|rule| bits & rule.required == rule.required && bits & rule.forbidden == 0)
455            .or_else(|| {
456                rules
457                    .iter()
458                    .rev()
459                    .find(|rule| rule.required == 0 && rule.forbidden == 0)
460            })
461            .or_else(|| rules.first())
462            .map(|rule| rule.color)
463    }
464    pub(super) fn live_state_mask(&self, state: &LayoutState, key: &str, response: Response) -> u8 {
465        u8::from(response.enabled)
466            | (u8::from(response.pressed) << 1)
467            | (u8::from(response.focused) << 2)
468            | (u8::from(state.view_selected.get(key).copied().unwrap_or(false)) << 3)
469            | (u8::from(state.view_activated.get(key).copied().unwrap_or(false)) << 4)
470            | (u8::from(response.hovered) << 5)
471            | (u8::from(state.checked.get(key).copied().unwrap_or(self.checked)) << 6)
472    }
473    pub(super) fn button_variant(&self) -> Option<XmlButtonVariant> {
474        if !matches!(self.kind, Kind::Button) {
475            return None;
476        }
477        self.relative_rules
478            .iter()
479            .find(|r| r.kind == RULE_BUTTON_VARIANT)
480            .and_then(|r| parse_button_variant(r.anchor))
481    }
482    pub(super) fn chip_style(&self) -> Option<XmlChipSpec> {
483        if !matches!(self.kind, Kind::Button) {
484            return None;
485        }
486        self.relative_rules
487            .iter()
488            .find(|r| r.kind == RULE_CHIP_STYLE)
489            .map(|r| parse_chip_style(r.anchor))
490    }
491    pub(super) fn text_input_box(&self) -> Option<TextInputBoxSpec<'static>> {
492        if !matches!(self.kind, Kind::Linear) {
493            return None;
494        }
495        self.relative_rules
496            .iter()
497            .find(|r| r.kind == RULE_TEXT_INPUT_BOX)
498            .map(|r| parse_text_input_box(r.anchor))
499    }
500    pub(super) fn clip_to_outline(&self) -> bool {
501        self.relative_rules.iter().any(|r| {
502            r.kind == RULE_CLIP_TO_OUTLINE
503                && matches!(r.anchor.trim().to_ascii_lowercase().as_str(), "true" | "1")
504        })
505    }
506    pub(super) fn resolved_line_height(&self, text_size: f32, state: &LayoutState) -> f32 {
507        if let Some(val) = self
508            .relative_rules
509            .iter()
510            .find(|r| r.kind == RULE_LINE_HEIGHT)
511            .and_then(|r| r.anchor.trim().parse::<f32>().ok())
512            .filter(|v| v.is_finite() && *v > 0.0)
513        {
514            return (val * state.effective_density() * state.effective_font_scale())
515                .max(text_size)
516                .max(1.0);
517        }
518        let include_font_padding = self
519            .relative_rules
520            .iter()
521            .find(|r| r.kind == RULE_INCLUDE_FONT_PADDING)
522            .map(|r| !matches!(r.anchor.trim().to_ascii_lowercase().as_str(), "false" | "0"))
523            .unwrap_or(true);
524        let factor = if include_font_padding {
525            state.theme_style.text_line_height_factor()
526        } else {
527            1.18
528        };
529        (text_size * factor).max(1.0)
530    }
531    pub(super) fn nav_bar_spec(&self) -> Option<NavBarSpec> {
532        if !matches!(self.kind, Kind::Linear) {
533            return None;
534        }
535        if !self.relative_rules.iter().any(|r| r.kind == RULE_NAV_ITEM) {
536            return None;
537        }
538        self.relative_rules
539            .iter()
540            .find(|r| r.kind == RULE_NAV_BAR)
541            .map(|r| parse_nav_bar(r.anchor))
542    }
543    pub(super) fn nav_items(&self) -> Vec<NavItemSpec> {
544        self.relative_rules
545            .iter()
546            .filter(|r| r.kind == RULE_NAV_ITEM)
547            .map(|r| parse_nav_item(r.anchor))
548            .collect()
549    }
550    pub(super) fn search_bar_hint(&self) -> Option<&'static str> {
551        if !matches!(self.kind, Kind::SearchView) {
552            return None;
553        }
554        self.relative_rules
555            .iter()
556            .find(|r| r.kind == RULE_SEARCH_BAR)
557            .map(|r| r.anchor)
558    }
559    pub(super) fn search_view_ext(&self) -> Option<SearchViewExtSpec<'static>> {
560        if !matches!(self.kind, Kind::Frame | Kind::Linear) {
561            return None;
562        }
563        self.relative_rules
564            .iter()
565            .rev()
566            .find(|r| r.kind == RULE_SEARCH_VIEW_EXT)
567            .map(|r| parse_search_view_ext(r.anchor))
568    }
569    pub(super) fn is_search_view_closed(&self, state: &LayoutState, id: u64) -> bool {
570        if self.search_view_ext().is_none() {
571            return false;
572        }
573        let key = if self.id.is_empty() {
574            format!("#{id}")
575        } else {
576            self.id.to_owned()
577        };
578        if state.search_open.get(&key).copied().unwrap_or(false) {
579            return false;
580        }
581        state
582            .search_view_motion
583            .get(&key)
584            .map_or(0.0, |m| m.progress)
585            <= 0.001
586    }
587    pub(super) fn toggle_group_spec(&self) -> Option<ToggleGroupSpec> {
588        if !matches!(self.kind, Kind::Linear) {
589            return None;
590        }
591        self.relative_rules
592            .iter()
593            .find(|r| r.kind == RULE_TOGGLE_GROUP)
594            .map(|r| parse_toggle_group(r.anchor))
595    }
596    pub(super) fn extended_fab_spec(&self) -> Option<ExtendedFabSpec> {
597        if !matches!(self.kind, Kind::Button) {
598            return None;
599        }
600        let legacy = self
601            .relative_rules
602            .iter()
603            .find(|r| r.kind == RULE_EXTENDED_FAB)
604            .map(|r| !matches!(r.anchor.trim().to_ascii_lowercase().as_str(), "0" | "false"));
605        if let Some(ext_rule) = self
606            .relative_rules
607            .iter()
608            .rev()
609            .find(|r| r.kind == RULE_EXTENDED_FAB_EXT)
610        {
611            return Some(parse_extended_fab_ext(ext_rule.anchor, legacy));
612        }
613        legacy.map(|static_extended| ExtendedFabSpec {
614            static_extended,
615            collapsed_size_dp: 56.0,
616            strategy: ExtendedFabStrategy::Auto,
617            has_ext: false,
618        })
619    }
620    pub(super) fn extended_fab_extended(&self) -> Option<bool> {
621        self.extended_fab_spec().map(|s| s.static_extended)
622    }
623    pub(super) fn extended_fab_progress(
624        &self,
625        state: &LayoutState,
626        id: u64,
627    ) -> Option<(ExtendedFabSpec, XmlLiftMotion, bool)> {
628        let spec = self.extended_fab_spec()?;
629        let key = if self.id.is_empty() {
630            format!("#{id}")
631        } else {
632            self.id.to_owned()
633        };
634        let target = state
635            .fab_extended
636            .get(&key)
637            .copied()
638            .unwrap_or(spec.static_extended);
639        let prev = state
640            .extended_fab_motion
641            .get(&key)
642            .copied()
643            .unwrap_or_default();
644        let now = if state.frame_time.is_finite() {
645            state.frame_time.max(0.0)
646        } else {
647            0.0
648        };
649        let (next, anim) =
650            eval_binary_ease_out_motion(prev, target, 0.22, now, state.frame_reduced_motion);
651        Some((spec, next, anim))
652    }
653    pub(super) fn extended_fab_intrinsic_extended_width(
654        &self,
655        state: &LayoutState,
656        metrics: TextMetrics,
657        id: u64,
658        spec: ExtendedFabSpec,
659    ) -> f32 {
660        let key = if self.id.is_empty() {
661            format!("#{id}")
662        } else {
663            self.id.to_owned()
664        };
665        let label = self.display_text_for(
666            state.text.get(&key).map_or(self.text, String::as_str),
667            state,
668        );
669        let (text_size, weight, italic, family) = self.effective_text_font(state);
670        let style = TextStyle {
671            size: text_size,
672            weight,
673            letter_spacing: self.letter_spacing_em * text_size,
674            italic,
675            family,
676            ..TextStyle::default()
677        };
678        let text_w = label
679            .split([
680                '\n', '\r', '\u{000b}', '\u{000c}', '\u{0085}', '\u{2028}', '\u{2029}',
681            ])
682            .map(|line| metrics.width(line, style))
683            .fold(0.0_f32, f32::max);
684        let rtl = match self.layout_direction {
685            1 => false,
686            2 => true,
687            _ => state.rtl,
688        };
689        let ext_def_pad = if rtl {
690            [20.0, 0.0, 16.0, 0.0]
691        } else {
692            [16.0, 0.0, 20.0, 0.0]
693        };
694        let raw_pad = self.resolved_padding(state);
695        let pad_l = if self.padding_explicit[0]
696            || self.padding_edges[0] != 0.0
697            || self.padding_relative[if rtl { 1 } else { 0 }].is_some()
698        {
699            raw_pad[0]
700        } else {
701            state.dp(ext_def_pad[0])
702        };
703        let pad_r = if self.padding_explicit[2]
704            || self.padding_edges[2] != 0.0
705            || self.padding_relative[if rtl { 0 } else { 1 }].is_some()
706        {
707            raw_pad[2]
708        } else {
709            state.dp(ext_def_pad[2])
710        };
711        let shapes = self.compound_sizes(state, rtl);
712        let extent = self.compound_extents(state, rtl);
713        let has_compound = shapes.iter().any(Option::is_some);
714        let icon_w = if !has_compound && !self.image_src.is_empty() {
715            state.dp(24.0)
716                + if label.is_empty() {
717                    0.0
718                } else {
719                    state.dp(12.0)
720                }
721        } else {
722            0.0
723        };
724        let min_w = state.dp(self.min_width);
725        let bg_min_w = state.dp(self.background_min_size[0]);
726        let min_ext = state.dp(80.0).max(state.dp(spec.collapsed_size_dp));
727        ((text_w + icon_w + extent[0] + extent[2])
728            .max(shapes[1].map_or(0.0, |s| s.0))
729            .max(shapes[3].map_or(0.0, |s| s.0))
730            + pad_l
731            + pad_r)
732            .max(min_ext)
733            .max(min_w)
734            .max(bg_min_w)
735    }
736    pub(super) fn bottom_app_bar_spec(&self) -> Option<BottomAppBarSpec> {
737        if !matches!(self.kind, Kind::Toolbar) {
738            return None;
739        }
740        let legacy = self
741            .relative_rules
742            .iter()
743            .find(|r| r.kind == RULE_BOTTOM_APP_BAR)
744            .map(|r| match r.anchor.trim().to_ascii_lowercase().as_str() {
745                "end" => BottomAppBarFabAlignment::End,
746                _ => BottomAppBarFabAlignment::Center,
747            });
748        if let Some(ext_rule) = self
749            .relative_rules
750            .iter()
751            .rev()
752            .find(|r| r.kind == RULE_BOTTOM_APP_BAR_EXT)
753        {
754            return Some(parse_bottom_app_bar_ext(ext_rule.anchor, legacy));
755        }
756        legacy.map(|alignment| BottomAppBarSpec {
757            alignment,
758            anchor_mode: BottomAppBarAnchorMode::Cradle,
759            cradle_margin_dp: 5.0,
760            cradle_rad_dp: 8.0,
761            cradle_voff_dp: 0.0,
762            hide_on_scroll: false,
763            has_ext: false,
764        })
765    }
766    pub(super) fn contains_hide_on_scroll_bar(&self) -> bool {
767        if self.bottom_app_bar_spec().is_some_and(|s| s.hide_on_scroll) {
768            return true;
769        }
770        matches!(self.kind, Kind::Linear | Kind::Frame)
771            && self
772                .children
773                .iter()
774                .any(|c| c.bottom_app_bar_spec().is_some_and(|s| s.hide_on_scroll))
775    }
776    pub(super) fn collapsing_toolbar_ext(&self) -> Option<CollapsingToolbarExt<'_>> {
777        if !matches!(self.kind, Kind::Frame) {
778            return None;
779        }
780        self.relative_rules
781            .iter()
782            .rev()
783            .filter(|r| r.kind == RULE_COLLAPSING_TOOLBAR_EXT)
784            .find_map(|r| parse_collapsing_toolbar_ext(r.anchor))
785    }
786    pub(super) fn collapsing_child_mode(&self) -> Option<CollapsingChildMode> {
787        self.relative_rules
788            .iter()
789            .rev()
790            .filter(|r| r.kind == RULE_COLLAPSING_TOOLBAR_EXT)
791            .find_map(|r| parse_collapsing_child_mode(r.anchor))
792    }
793    pub(super) fn recycler_layout_ext(&self) -> Option<RecyclerLayoutExt> {
794        if !matches!(self.kind, Kind::ListView | Kind::GridView) {
795            return None;
796        }
797        self.relative_rules
798            .iter()
799            .rev()
800            .find(|r| r.kind == RULE_RECYCLER_LAYOUT_EXT)
801            .map(|r| parse_recycler_layout_ext(r.anchor, matches!(self.kind, Kind::GridView)))
802    }
803    pub(super) fn nav_badge_for<'a>(
804        &'a self,
805        item_id: &str,
806        state: &'a LayoutState,
807    ) -> Option<&'a str> {
808        if item_id.is_empty() {
809            return None;
810        }
811        if let Some(runtime_text) = state.nav_badges.get(item_id) {
812            return Some(runtime_text.as_str());
813        }
814        self.relative_rules
815            .iter()
816            .rev()
817            .filter(|r| r.kind == RULE_NAV_BADGE)
818            .find_map(|r| {
819                let (bid, btext) = r.anchor.split_once(':')?;
820                (bid.trim() == item_id).then_some(btext)
821            })
822    }
823    pub(super) fn nav_badge_for_item<'a>(
824        &'a self,
825        item_index: usize,
826        item_id: &str,
827        state: &'a LayoutState,
828    ) -> Option<&'a str> {
829        if let Some(b) = self.nav_badge_for(item_id, state) {
830            return Some(b);
831        }
832        self.relative_rules
833            .iter()
834            .rev()
835            .filter(|r| r.kind == RULE_NAV_BADGE)
836            .find_map(|r| {
837                let (bid, btext) = r.anchor.split_once(':')?;
838                (bid.trim().parse::<usize>().ok() == Some(item_index)).then_some(btext)
839            })
840    }
841    pub(super) fn material_badge_ext(
842        &self,
843        item_index: Option<usize>,
844        item_id: &str,
845    ) -> Option<MaterialBadgeExt> {
846        self.relative_rules
847            .iter()
848            .rev()
849            .filter(|r| r.kind == RULE_MATERIAL_BADGE_EXT)
850            .find_map(|r| {
851                let (target, ext) = parse_material_badge_ext(r.anchor)?;
852                let matched = match item_index {
853                    Some(idx) => match target {
854                        BadgeTarget::Index(i) => i == idx,
855                        BadgeTarget::Id(id) => !item_id.is_empty() && id == item_id,
856                        BadgeTarget::SelfView => false,
857                    },
858                    None => matches!(target, BadgeTarget::SelfView),
859                };
860                matched.then_some(ext)
861            })
862    }
863    pub(super) fn standalone_badge<'a>(&'a self, state: &'a LayoutState) -> Option<&'a str> {
864        let from_rule = self
865            .relative_rules
866            .iter()
867            .rev()
868            .filter(|r| r.kind == RULE_NAV_BADGE)
869            .find_map(|r| {
870                let (bid, btext) = r.anchor.split_once(':')?;
871                let bid = bid.trim();
872                let is_self = bid == "-1"
873                    || bid.eq_ignore_ascii_case("self")
874                    || (!self.id.is_empty() && bid == self.id);
875                is_self.then_some(btext)
876            });
877        if from_rule.is_some() {
878            return from_rule;
879        }
880        if !self.id.is_empty()
881            && self.material_badge_ext(None, self.id).is_some()
882            && let Some(rt) = state.nav_badges.get(self.id)
883        {
884            return Some(rt.as_str());
885        }
886        None
887    }
888    pub(super) fn text_layout_ext(&self) -> Option<TextLayoutExt> {
889        if !matches!(self.kind, Kind::Text | Kind::Button) {
890            return None;
891        }
892        self.relative_rules
893            .iter()
894            .rev()
895            .find(|r| r.kind == RULE_TEXT_LAYOUT_EXT)
896            .map(|r| parse_text_layout_ext(r.anchor))
897            .filter(TextLayoutExt::has_custom_layout)
898    }
899    #[allow(clippy::too_many_arguments)]
900    pub(super) fn resolve_auto_text_size(
901        &self,
902        text: &str,
903        avail_w: f32,
904        avail_h: f32,
905        base_style: TextStyle,
906        ext: TextLayoutExt,
907        state: &LayoutState,
908        metrics: TextMetrics,
909    ) -> f32 {
910        let min_sp = ext.auto_min_sp;
911        let max_sp = ext.auto_max_sp.max(min_sp);
912        let step = if ext.auto_step_sp > 0.0 {
913            ext.auto_step_sp
914        } else {
915            1.0
916        };
917        let max_k = ((max_sp - min_sp + 1e-4) / step).floor().max(0.0) as usize;
918        if avail_w <= 0.0 || avail_h <= 0.0 || max_k == 0 {
919            return state.sp(min_sp);
920        }
921        let single = self.single_line || self.max_lines == 1;
922        let visible_single = if single {
923            text.replace('\u{00ad}', "")
924        } else {
925            String::new()
926        };
927        let fits = |sp: f32| -> bool {
928            let px = state.sp(sp);
929            let style = TextStyle {
930                size: px,
931                letter_spacing: self.letter_spacing_em * px,
932                ..base_style
933            };
934            let lh = self.resolved_line_height(px, state);
935            if lh > avail_h + 0.01 {
936                return false;
937            }
938            if single {
939                return metrics.width(&visible_single, style) <= avail_w + 0.01;
940            }
941            if ext.hyphenation == TextHyphenationFrequency::None {
942                for word in text.split(breakable_space).filter(|w| !w.is_empty()) {
943                    let clean = word.replace('\u{00ad}', "");
944                    if metrics.width(&clean, style) > avail_w + 0.01 {
945                        return false;
946                    }
947                }
948            }
949            let lines = wrap_text_lines_ext(text, avail_w, style, metrics, ext);
950            let count = lines.len().max(1);
951            if self.max_lines > 0 && count > self.max_lines {
952                return false;
953            }
954            let adv =
955                (lh * self.line_spacing_multiplier + state.dp(self.line_spacing_extra)).max(1.0);
956            let used_h = lh + (count - 1) as f32 * adv;
957            if used_h > avail_h + 0.01 {
958                return false;
959            }
960            lines
961                .iter()
962                .all(|l| metrics.width(&l.text, style) <= avail_w + 0.01)
963        };
964        if !fits(min_sp) {
965            return state.sp(min_sp);
966        }
967        let mut lo = 0usize;
968        let mut hi = max_k;
969        while lo < hi {
970            let mid = lo + (hi - lo + 1) / 2;
971            let cand = (min_sp + mid as f32 * step).min(max_sp);
972            if fits(cand) {
973                lo = mid;
974            } else {
975                hi = mid - 1;
976            }
977        }
978        let chosen_sp = (min_sp + lo as f32 * step).min(max_sp);
979        state.sp(chosen_sp)
980    }
981    pub(super) fn swipe_refresh_ext(&self) -> Option<SwipeRefreshExtSpec> {
982        if !matches!(self.kind, Kind::Frame) {
983            return None;
984        }
985        self.relative_rules
986            .iter()
987            .rev()
988            .find(|r| r.kind == RULE_SWIPE_REFRESH_EXT)
989            .map(|r| parse_swipe_refresh_ext(r.anchor))
990    }
991    pub(super) fn is_swipe_refresh(&self) -> bool {
992        matches!(self.kind, Kind::Frame)
993            && self
994                .relative_rules
995                .iter()
996                .any(|r| r.kind == RULE_SWIPE_REFRESH || r.kind == RULE_SWIPE_REFRESH_EXT)
997    }
998    pub(super) fn carousel_layout_spec(&self) -> Option<CarouselLayoutSpec> {
999        if !matches!(
1000            self.kind,
1001            Kind::ListView | Kind::GridView | Kind::HorizontalScroll | Kind::Linear
1002        ) {
1003            return None;
1004        }
1005        self.relative_rules
1006            .iter()
1007            .rev()
1008            .find(|r| r.kind == RULE_CAROUSEL_LAYOUT)
1009            .map(|r| parse_carousel_layout(r.anchor))
1010    }
1011    pub(super) fn blocks_pointer_for_lower_siblings_in(
1012        &self,
1013        state: &LayoutState,
1014        id: u64,
1015    ) -> bool {
1016        if self.search_view_ext().is_some() {
1017            return !self.is_search_view_closed(state, id);
1018        }
1019        self.blocks_pointer_for_lower_siblings()
1020    }
1021    pub(super) fn is_drawer_layout(&self) -> bool {
1022        matches!(self.kind, Kind::Frame)
1023            && self
1024                .relative_rules
1025                .iter()
1026                .any(|r| r.kind == RULE_DRAWER_LAYOUT)
1027    }
1028    pub(super) fn blocks_pointer_for_lower_siblings(&self) -> bool {
1029        self.clickable
1030            || matches!(
1031                self.kind,
1032                Kind::Button
1033                    | Kind::Icon
1034                    | Kind::Zoom
1035                    | Kind::ZoomControls
1036                    | Kind::CheckBox
1037                    | Kind::RadioButton
1038                    | Kind::Switch
1039                    | Kind::SeekBar
1040                    | Kind::RatingBar
1041                    | Kind::ToggleButton
1042                    | Kind::Edit
1043                    | Kind::AutoComplete
1044                    | Kind::MultiAutoComplete
1045                    | Kind::MaterialCard
1046                    | Kind::Spinner
1047                    | Kind::ListView
1048                    | Kind::GridView
1049                    | Kind::QuickContactBadge
1050                    | Kind::VideoView
1051                    | Kind::CalendarView
1052                    | Kind::DatePicker
1053                    | Kind::NumberPicker
1054                    | Kind::TimePicker
1055                    | Kind::SearchView
1056                    | Kind::ExpandableListView
1057                    | Kind::Toolbar
1058                    | Kind::ActionMenuView
1059                    | Kind::TabWidget
1060            )
1061            || self.bottom_sheet_spec().is_some()
1062            || self.side_sheet_spec().is_some()
1063            || self.is_snackbar()
1064            || self.is_floating_toolbar()
1065            || self.alert_dialog_icon().is_some()
1066            || self.nav_bar_spec().is_some()
1067            || self.search_bar_hint().is_some()
1068    }
1069    pub(super) fn collapsing_toolbar_spec(&self) -> Option<CollapsingToolbarSpec<'_>> {
1070        if !matches!(self.kind, Kind::Frame) {
1071            return None;
1072        }
1073        self.relative_rules
1074            .iter()
1075            .find(|r| r.kind == RULE_COLLAPSING_TOOLBAR)
1076            .map(|r| parse_collapsing_toolbar(r.anchor, self.height))
1077    }
1078    pub(super) fn collapsing_toolbar_scroll_px(&self, state: &LayoutState, id: u64) -> f32 {
1079        let sib = state
1080            .collapsing_scroll_offset
1081            .filter(|v| v.is_finite())
1082            .unwrap_or(0.0)
1083            .max(0.0);
1084        let key = if self.id.is_empty() {
1085            format!("#{id}")
1086        } else {
1087            self.id.to_owned()
1088        };
1089        let own = state
1090            .offsets
1091            .get(&key)
1092            .copied()
1093            .filter(|v| v.is_finite())
1094            .unwrap_or(0.0)
1095            .max(0.0);
1096        sib.max(own)
1097    }
1098    pub(super) fn collapsing_toolbar_height(&self, state: &LayoutState, id: u64) -> Option<f32> {
1099        let spec = self.collapsing_toolbar_spec()?;
1100        let expanded_px = state.dp(spec.expanded_h_dp);
1101        let collapsed_px = state.dp(64.0).min(expanded_px);
1102        let scroll_px = self.collapsing_toolbar_scroll_px(state, id);
1103        Some((expanded_px - scroll_px).clamp(collapsed_px, expanded_px))
1104    }
1105    pub(super) fn contains_collapsing_toolbar(&self) -> bool {
1106        if self.collapsing_toolbar_spec().is_some() {
1107            return true;
1108        }
1109        matches!(self.kind, Kind::Linear | Kind::Frame)
1110            && self
1111                .children
1112                .iter()
1113                .any(|c| c.collapsing_toolbar_spec().is_some())
1114    }
1115    pub(super) fn lift_on_scroll_spec(&self) -> Option<Option<&'static str>> {
1116        if !matches!(self.kind, Kind::Linear | Kind::Frame | Kind::Toolbar) {
1117            return None;
1118        }
1119        self.relative_rules
1120            .iter()
1121            .find(|r| r.kind == RULE_APP_BAR_LIFT_ON_SCROLL)
1122            .and_then(|r| {
1123                let trimmed = r.anchor.trim();
1124                let (flag, target) = match trimmed.split_once('|') {
1125                    Some((a, b)) => (a.trim(), Some(b.trim())),
1126                    None => (trimmed, None),
1127                };
1128                if !matches!(flag.to_ascii_lowercase().as_str(), "1" | "true") {
1129                    return None;
1130                }
1131                Some(target.filter(|s| !s.is_empty()))
1132            })
1133    }
1134    pub(super) fn contains_lift_on_scroll(&self) -> bool {
1135        if self.lift_on_scroll_spec().is_some() {
1136            return true;
1137        }
1138        matches!(self.kind, Kind::Linear | Kind::Frame)
1139            && self
1140                .children
1141                .iter()
1142                .any(|c| c.lift_on_scroll_spec().is_some())
1143    }
1144    pub(super) fn app_bar_scroll_flags(&self) -> Option<AppBarScrollFlags> {
1145        self.relative_rules
1146            .iter()
1147            .find(|r| r.kind == RULE_APP_BAR_SCROLL_FLAGS)
1148            .map(|r| parse_app_bar_scroll_flags(r.anchor))
1149            .filter(|f| f.scroll)
1150    }
1151    pub(super) fn app_bar_lift_color(&self) -> Option<Color> {
1152        self.relative_rules
1153            .iter()
1154            .filter(|r| r.kind == RULE_APP_BAR_EXT)
1155            .find_map(|r| parse_app_bar_ext_lift_color(r.anchor))
1156    }
1157    pub(super) fn app_bar_scroll_effect_compress(&self) -> bool {
1158        self.relative_rules
1159            .iter()
1160            .any(|r| r.kind == RULE_APP_BAR_EXT && parse_app_bar_ext_compress(r.anchor))
1161    }
1162    pub(super) fn static_drawer_lock_mode(&self) -> Option<u8> {
1163        self.relative_rules
1164            .iter()
1165            .find(|r| r.kind == RULE_DRAWER_LOCK_MODE)
1166            .and_then(|r| parse_drawer_lock_mode(r.anchor))
1167    }
1168    pub(super) fn contains_app_bar_scroll_flags(&self) -> bool {
1169        if self.app_bar_scroll_flags().is_some() {
1170            return true;
1171        }
1172        matches!(self.kind, Kind::Linear | Kind::Frame)
1173            && self
1174                .children
1175                .iter()
1176                .any(|c| c.app_bar_scroll_flags().is_some())
1177    }
1178    pub(super) fn app_bar_scroll_px(&self, state: &LayoutState, id: u64) -> f32 {
1179        if let Some(sib) = state.collapsing_scroll_offset.filter(|v| v.is_finite()) {
1180            return sib.max(0.0);
1181        }
1182        let key = if self.id.is_empty() {
1183            format!("#{id}")
1184        } else {
1185            self.id.to_owned()
1186        };
1187        state
1188            .offsets
1189            .get(&key)
1190            .copied()
1191            .filter(|v| v.is_finite())
1192            .unwrap_or(0.0)
1193            .max(0.0)
1194    }
1195    pub(super) fn app_bar_child_scroll_px(
1196        &self,
1197        parent_scroll: f32,
1198        state: &LayoutState,
1199        child_id: u64,
1200    ) -> f32 {
1201        if state.collapsing_scroll_offset.is_some() || parent_scroll > 0.0 {
1202            return parent_scroll;
1203        }
1204        let key = if self.id.is_empty() {
1205            format!("#{child_id}")
1206        } else {
1207            self.id.to_owned()
1208        };
1209        state
1210            .offsets
1211            .get(&key)
1212            .copied()
1213            .filter(|v| v.is_finite())
1214            .unwrap_or(0.0)
1215            .max(0.0)
1216    }
1217    pub(super) fn app_bar_children_collapse_total(
1218        &self,
1219        state: &LayoutState,
1220        inner_width: f32,
1221        metrics: TextMetrics,
1222        id: u64,
1223    ) -> f32 {
1224        if !matches!(self.kind, Kind::Linear) || self.horizontal {
1225            return 0.0;
1226        }
1227        let parent_scroll = self.app_bar_scroll_px(state, id);
1228        let mut total = 0.0_f32;
1229        for (i, n) in self.children.iter().enumerate() {
1230            if n.effective_visibility(state) == Visibility::Gone
1231                || n.app_bar_scroll_flags().is_none()
1232                || n.collapsing_toolbar_spec().is_some()
1233            {
1234                continue;
1235            }
1236            let cid = child_view_id(id, i, n);
1237            let m = n.resolved_margin(state);
1238            let avail_w = (inner_width - m[0] - m[2]).max(0.0);
1239            let natural_h = n.layout_intrinsic(false, state, avail_w, metrics, cid);
1240            let scroll_px = n.app_bar_child_scroll_px(parent_scroll, state, cid);
1241            total +=
1242                preview_app_bar_child_collapse(n, cid, natural_h, m[1] + m[3], scroll_px, state);
1243        }
1244        total
1245    }
1246    pub(super) fn drawer_header_intrinsic_height(&self, state: &LayoutState, id: u64) -> f32 {
1247        let mut h = 0.0_f32;
1248        let mut any = false;
1249        for (i, child) in self.children.iter().enumerate() {
1250            if child.effective_visibility(state) == Visibility::Gone {
1251                continue;
1252            }
1253            any = true;
1254            let m = child.resolved_margin(state);
1255            h += child.intrinsic(false, state, child_view_id(id, i, child)) + m[1] + m[3];
1256        }
1257        if any { h + state.dp(1.0) } else { 0.0 }
1258    }
1259    pub(super) fn sibling_scroll_offset(&self, state: &LayoutState, id: u64) -> Option<f32> {
1260        for (i, sib) in self.children.iter().enumerate() {
1261            if sib.effective_visibility(state) == Visibility::Gone
1262                || sib.contains_collapsing_toolbar()
1263                || sib.contains_lift_on_scroll()
1264                || sib.contains_app_bar_scroll_flags()
1265                || sib.contains_hide_on_scroll_bar()
1266            {
1267                continue;
1268            }
1269            if sib
1270                .relative_rules
1271                .iter()
1272                .any(|r| r.kind == RULE_COORDINATOR_SCROLL_BEHAVIOR)
1273                && let Some(off) = find_scroll_view_offset(sib, state, child_view_id(id, i, sib))
1274            {
1275                return Some(off);
1276            }
1277        }
1278        for (i, sib) in self.children.iter().enumerate() {
1279            if sib.effective_visibility(state) == Visibility::Gone
1280                || sib.contains_collapsing_toolbar()
1281                || sib.contains_lift_on_scroll()
1282                || sib.contains_app_bar_scroll_flags()
1283                || sib.contains_hide_on_scroll_bar()
1284            {
1285                continue;
1286            }
1287            if let Some(off) = find_scroll_view_offset(sib, state, child_view_id(id, i, sib)) {
1288                return Some(off);
1289            }
1290        }
1291        None
1292    }
1293    pub(super) fn view_pager_spec(&self) -> Option<ViewPagerSpec> {
1294        if !matches!(self.kind, Kind::ViewFlipper) {
1295            return None;
1296        }
1297        let legacy = self
1298            .relative_rules
1299            .iter()
1300            .find(|r| r.kind == RULE_VIEW_PAGER)
1301            .map(|r| parse_view_pager_orientation(r.anchor));
1302        if let Some(ext) = self
1303            .relative_rules
1304            .iter()
1305            .rev()
1306            .find(|r| r.kind == RULE_VIEW_PAGER_EXT)
1307        {
1308            return Some(parse_view_pager_ext(ext.anchor, legacy));
1309        }
1310        legacy.map(|orient| ViewPagerSpec {
1311            orient,
1312            user_input_enabled: true,
1313            page_margin_dp: 0.0,
1314            transformer: ViewPagerTransformer::None,
1315            has_ext: false,
1316        })
1317    }
1318    pub(super) fn range_slider_initial(&self) -> Option<[f32; 2]> {
1319        if !matches!(self.kind, Kind::SeekBar) {
1320            return None;
1321        }
1322        let rule = self
1323            .relative_rules
1324            .iter()
1325            .find(|r| r.kind == RULE_RANGE_SLIDER)?;
1326        let max = if self.max > self.min {
1327            self.max
1328        } else {
1329            self.min + 100.0
1330        };
1331        Some(parse_range_slider_values(rule.anchor, self.min, max))
1332    }
1333    pub(super) fn is_drawer_panel_child(&self) -> bool {
1334        let has_drawer_nav = self
1335            .relative_rules
1336            .iter()
1337            .any(|r| r.kind == RULE_NAV_BAR && parse_nav_bar(r.anchor).kind == NavBarKind::Drawer);
1338        if has_drawer_nav {
1339            return true;
1340        }
1341        self.layout_gravity_explicit
1342            && matches!(self.layout_gravity[0], 0 | 2 | 3 | 4)
1343            && !matches!(self.width, Size::Match)
1344    }
1345    pub(super) fn drawer_panel_is_logical_end(&self, rtl: bool) -> bool {
1346        match self.layout_gravity[0] {
1347            2 => true,
1348            3 => rtl,
1349            4 => !rtl,
1350            _ => false,
1351        }
1352    }
1353    pub(super) fn resolved_drawer_lock_mode(
1354        &self,
1355        is_end: bool,
1356        has_start: bool,
1357        child_lock: Option<u8>,
1358        state: &LayoutState,
1359        key: &str,
1360        end_key: &str,
1361    ) -> u8 {
1362        let rt_lock = if is_end {
1363            if has_start {
1364                state.drawer_lock_mode.get(end_key).copied()
1365            } else {
1366                state
1367                    .drawer_lock_mode
1368                    .get(end_key)
1369                    .copied()
1370                    .or_else(|| state.drawer_lock_mode.get(key).copied())
1371            }
1372        } else {
1373            state.drawer_lock_mode.get(key).copied()
1374        };
1375        rt_lock
1376            .or(child_lock)
1377            .or_else(|| self.static_drawer_lock_mode())
1378            .unwrap_or(DRAWER_LOCK_MODE_UNLOCKED)
1379    }
1380    pub(super) fn drawer_panel_is_closed(
1381        &self,
1382        child: &Node,
1383        state: &LayoutState,
1384        id: u64,
1385    ) -> bool {
1386        if !self.is_drawer_layout() || !child.is_drawer_panel_child() {
1387            return false;
1388        }
1389        let key = if self.id.is_empty() {
1390            format!("#{id}")
1391        } else {
1392            self.id.to_owned()
1393        };
1394        let end_key = format!("{key}:end");
1395        let has_start = self.children.iter().any(|c| {
1396            c.effective_visibility(state) != Visibility::Gone
1397                && c.is_drawer_panel_child()
1398                && !c.drawer_panel_is_logical_end(state.rtl)
1399        });
1400        let is_end = child.drawer_panel_is_logical_end(state.rtl);
1401        let lock_mode = self.resolved_drawer_lock_mode(
1402            is_end,
1403            has_start,
1404            child.static_drawer_lock_mode(),
1405            state,
1406            &key,
1407            &end_key,
1408        );
1409        if lock_mode == DRAWER_LOCK_MODE_LOCKED_CLOSED {
1410            return true;
1411        }
1412        if lock_mode == DRAWER_LOCK_MODE_LOCKED_OPEN {
1413            return false;
1414        }
1415        if is_end && has_start {
1416            !state.drawer_open.get(&end_key).copied().unwrap_or(false)
1417        } else if is_end {
1418            !(state.drawer_open.get(&end_key).copied().unwrap_or(false)
1419                || state.drawer_open.get(&key).copied().unwrap_or(false))
1420        } else {
1421            !state.drawer_open.get(&key).copied().unwrap_or(false)
1422        }
1423    }
1424    pub(super) fn has_animated_selector(&self, is_src: bool) -> bool {
1425        self.relative_rules.iter().any(|r| {
1426            r.kind == RULE_ANIMATED_SELECTOR
1427                && parse_animated_selector_transition(r.anchor).is_some_and(|t| t.is_src == is_src)
1428        })
1429    }
1430    pub(super) fn sample_animated_selector(
1431        &self,
1432        f: &mut Frame<'_>,
1433        b: Rect,
1434        state: &mut LayoutState,
1435        view_key: &str,
1436        response: Response,
1437        is_src: bool,
1438    ) -> Option<&'static str> {
1439        let transitions: Vec<AnimatedSelectorTransition<'static>> = self
1440            .relative_rules
1441            .iter()
1442            .filter(|r| r.kind == RULE_ANIMATED_SELECTOR)
1443            .filter_map(|r| parse_animated_selector_transition(r.anchor))
1444            .filter(|t| t.is_src == is_src)
1445            .collect();
1446        if transitions.is_empty() {
1447            return None;
1448        }
1449        let map_key = format!("{}:{view_key}", if is_src { "src" } else { "bg" });
1450        let new_mask = self.live_state_mask(state, view_key, response) & 0x7F;
1451        let now = if f.time().is_finite() {
1452            f.time().max(0.0)
1453        } else {
1454            0.0
1455        };
1456        let reduced = f.reduced_motion();
1457
1458        let mut st = state
1459            .animated_selector_states
1460            .get(&map_key)
1461            .copied()
1462            .unwrap_or_default();
1463
1464        let mut chosen_frame: Option<&'static str> = None;
1465        if !st.initialized {
1466            st.initialized = true;
1467            st.last_mask = new_mask;
1468            st.active = None;
1469        } else if reduced {
1470            st.last_mask = new_mask;
1471            st.active = None;
1472        } else {
1473            if new_mask != st.last_mask {
1474                let old_mask = st.last_mask;
1475                st.last_mask = new_mask;
1476                let matched = transitions
1477                    .iter()
1478                    .enumerate()
1479                    .find_map(|(idx, tr)| {
1480                        matches_animated_selector_transition(
1481                            old_mask,
1482                            new_mask,
1483                            tr.from_mask,
1484                            tr.to_mask,
1485                        )
1486                        .then_some((idx, false))
1487                    })
1488                    .or_else(|| {
1489                        transitions.iter().enumerate().find_map(|(idx, tr)| {
1490                            (tr.reversible
1491                                && matches_animated_selector_transition(
1492                                    old_mask,
1493                                    new_mask,
1494                                    tr.to_mask,
1495                                    tr.from_mask,
1496                                ))
1497                            .then_some((idx, true))
1498                        })
1499                    });
1500                if let Some((rule_idx, reversed)) = matched {
1501                    st.active = Some((now, reversed, rule_idx));
1502                } else if let Some((_, rev, r_idx)) = st.active {
1503                    if let Some(tr) = transitions.get(r_idx) {
1504                        let (eff_from, eff_to) = if rev {
1505                            (tr.to_mask, tr.from_mask)
1506                        } else {
1507                            (tr.from_mask, tr.to_mask)
1508                        };
1509                        let still_at_dest = if eff_to == 0 {
1510                            (new_mask & eff_from) != eff_from
1511                        } else {
1512                            (new_mask & eff_to) == eff_to
1513                        };
1514                        if !still_at_dest {
1515                            st.active = None;
1516                        }
1517                    } else {
1518                        st.active = None;
1519                    }
1520                }
1521            }
1522            if let Some((start_time, reversed, rule_idx)) = st.active {
1523                if let Some(tr) = transitions.get(rule_idx) {
1524                    let elapsed_sec = (now - start_time).max(0.0);
1525                    let elapsed_ms = (elapsed_sec * 1000.0 + 1e-6).floor() as u64;
1526                    if elapsed_ms >= tr.total_ms {
1527                        st.active = None;
1528                    } else {
1529                        let mut acc = 0u64;
1530                        let count = tr.frames.len();
1531                        for step in 0..count {
1532                            let frame = if reversed {
1533                                &tr.frames[count - 1 - step]
1534                            } else {
1535                                &tr.frames[step]
1536                            };
1537                            acc = acc.saturating_add(frame.duration_ms);
1538                            if elapsed_ms < acc {
1539                                chosen_frame = Some(frame.img_key);
1540                                let next_wake = (start_time + acc as f64 / 1000.0).max(now + 0.001);
1541                                let vis_rect = b.intersect(f.clip);
1542                                if vis_rect.width > 0.0 && vis_rect.height > 0.0 {
1543                                    f.wake_at(next_wake);
1544                                }
1545                                break;
1546                            }
1547                        }
1548                    }
1549                } else {
1550                    st.active = None;
1551                }
1552            }
1553        }
1554
1555        if state.animated_selector_states.len() >= 256
1556            && !state.animated_selector_states.contains_key(&map_key)
1557        {
1558            state
1559                .animated_selector_states
1560                .retain(|_, v| v.active.is_some());
1561            if state.animated_selector_states.len() >= 256 {
1562                state.animated_selector_states.clear();
1563            }
1564        }
1565        state.animated_selector_states.insert(map_key, st);
1566        chosen_frame
1567    }
1568    pub(super) fn is_image_src_kind(&self) -> bool {
1569        matches!(
1570            self.kind,
1571            Kind::Image | Kind::QuickContactBadge | Kind::Icon | Kind::Zoom
1572        )
1573    }
1574    pub(super) fn animation_list_spec(&self) -> Option<AnimationListSpec<'_>> {
1575        self.relative_rules
1576            .iter()
1577            .find(|r| r.kind == RULE_ANIMATION_LIST)
1578            .and_then(|r| parse_animation_list(r.anchor))
1579    }
1580    pub(super) fn animated_vector_spec(&self, is_src: bool) -> Option<AnimatedVectorSpec<'_>> {
1581        self.relative_rules
1582            .iter()
1583            .filter(|r| r.kind == RULE_ANIMATED_VECTOR)
1584            .filter_map(|r| parse_animated_vector(r.anchor))
1585            .find(|spec| spec.is_src == is_src)
1586    }
1587    pub(super) fn has_animated_vector(&self, is_src: bool) -> bool {
1588        self.animated_vector_spec(is_src).is_some()
1589    }
1590    pub(super) fn text_links_spans(&self) -> Option<TextLinksSpec> {
1591        self.relative_rules
1592            .iter()
1593            .find(|r| r.kind == RULE_TEXT_LINKS_SPANS)
1594            .map(|r| parse_text_links_spans(r.anchor))
1595    }
1596    pub(super) fn has_clickable_text_links(&self) -> bool {
1597        matches!(self.kind, Kind::Text | Kind::CheckedText)
1598            && self
1599                .text_links_spans()
1600                .is_some_and(|spec| spec.mask != 0 && spec.clickable)
1601    }
1602    pub(super) fn dynamic_drawable_for(
1603        &self,
1604        wanted: DynamicDrawableTarget,
1605    ) -> Option<DynamicDrawableSpec<'_>> {
1606        let default_target = if self.is_image_src_kind() {
1607            DynamicDrawableTarget::Src
1608        } else {
1609            DynamicDrawableTarget::Bg
1610        };
1611        self.relative_rules
1612            .iter()
1613            .filter(|r| r.kind == RULE_DRAWABLE_DYNAMIC)
1614            .filter_map(|r| parse_dynamic_drawable(r.anchor, default_target))
1615            .find_map(|(target, spec)| (target == wanted).then_some(spec))
1616    }
1617    pub(super) fn dynamic_drawable_bg(&self) -> Option<DynamicDrawableSpec<'_>> {
1618        self.dynamic_drawable_for(DynamicDrawableTarget::Bg)
1619    }
1620    pub(super) fn dynamic_drawable_src(&self) -> Option<DynamicDrawableSpec<'_>> {
1621        self.dynamic_drawable_for(DynamicDrawableTarget::Src)
1622    }
1623    pub(super) fn placeholder_spec(&self) -> Option<PlaceholderSpec<'_>> {
1624        self.relative_rules
1625            .iter()
1626            .find(|r| r.kind == RULE_CONSTRAINT_PLACEHOLDER)
1627            .map(|r| parse_placeholder_spec(r.anchor))
1628    }
1629    pub(super) fn has_explicit_custom_background(&self) -> bool {
1630        self.background.is_some()
1631            || self.dynamic_drawable_bg().is_some()
1632            || self.has_animated_vector(false)
1633            || self.has_animated_selector(false)
1634            || self.relative_rules.iter().any(|r| {
1635                r.kind == 96
1636                    || r.kind == RULE_DRAWABLE_LAYER
1637                    || r.kind == RULE_STATEFUL_DRAWABLE_LAYER
1638                    || r.kind == RULE_BACKGROUND_IMAGE
1639                    || r.kind == RULE_STATEFUL_BG_IMAGE
1640                    || (!self.is_image_src_kind()
1641                        && r.kind == RULE_ANIMATION_LIST
1642                        && parse_animation_list(r.anchor).is_some())
1643                    || (r.kind == RULE_GRADIENT && parse_gradient(r.anchor).is_some())
1644            })
1645    }
1646    pub(super) fn text_style_ext(&self) -> (bool, FontFamily) {
1647        let Some(rule) = self
1648            .relative_rules
1649            .iter()
1650            .find(|r| r.kind == RULE_TEXT_STYLE_EXT)
1651        else {
1652            return (false, FontFamily::System);
1653        };
1654        let (italic_part, family_part) =
1655            rule.anchor.split_once('|').unwrap_or((rule.anchor, "sans"));
1656        let italic = matches!(
1657            italic_part.trim().to_ascii_lowercase().as_str(),
1658            "1" | "true" | "italic"
1659        );
1660        let family = match family_part.trim().to_ascii_lowercase().as_str() {
1661            "serif" => FontFamily::Serif,
1662            "mono" | "monospace" => FontFamily::Monospace,
1663            _ => FontFamily::System,
1664        };
1665        (italic, family)
1666    }
1667    pub(super) fn is_auto_mirrored(&self) -> bool {
1668        self.relative_rules.iter().any(|r| {
1669            r.kind == RULE_AUTO_MIRRORED
1670                && matches!(r.anchor.trim().to_ascii_lowercase().as_str(), "true" | "1")
1671        })
1672    }
1673    pub(super) fn view_transform(&self) -> Option<ViewTransformSpec> {
1674        let spec = self
1675            .relative_rules
1676            .iter()
1677            .find(|r| r.kind == RULE_VIEW_TRANSFORM)
1678            .and_then(|r| parse_view_transform(r.anchor))?;
1679        let is_identity = spec.tx_dp == 0.0
1680            && spec.ty_dp == 0.0
1681            && (spec.sx - 1.0).abs() < 1e-6
1682            && (spec.sy - 1.0).abs() < 1e-6
1683            && spec.rot_deg == 0.0
1684            && spec.rot_x_deg == 0.0
1685            && spec.rot_y_deg == 0.0;
1686        (!is_identity).then_some(spec)
1687    }
1688    pub(super) fn tooltip_text(&self) -> Option<&'static str> {
1689        self.relative_rules
1690            .iter()
1691            .find(|r| r.kind == RULE_TOOLTIP_TEXT)
1692            .map(|r| r.anchor)
1693            .filter(|s| !s.is_empty())
1694    }
1695    pub(super) fn bottom_sheet_spec(&self) -> Option<BottomSheetSpec> {
1696        self.relative_rules
1697            .iter()
1698            .find(|r| r.kind == RULE_BOTTOM_SHEET)
1699            .map(|r| parse_bottom_sheet(r.anchor))
1700    }
1701    pub(super) fn is_drag_handle(&self) -> bool {
1702        self.relative_rules
1703            .iter()
1704            .any(|r| r.kind == RULE_DRAG_HANDLE)
1705    }
1706    pub(super) fn side_sheet_spec(&self) -> Option<SideSheetSpec> {
1707        self.relative_rules
1708            .iter()
1709            .find(|r| r.kind == RULE_SIDE_SHEET)
1710            .map(|r| parse_side_sheet(r.anchor))
1711    }
1712    pub(super) fn loading_indicator_contained(&self) -> Option<bool> {
1713        if !matches!(self.kind, Kind::ProgressBar) {
1714            return None;
1715        }
1716        self.relative_rules
1717            .iter()
1718            .find(|r| r.kind == RULE_LOADING_INDICATOR)
1719            .map(|r| matches!(r.anchor.trim().to_ascii_lowercase().as_str(), "1" | "true"))
1720    }
1721    pub(super) fn wavy_progress_spec(&self) -> Option<WavyProgressSpec> {
1722        if !matches!(self.kind, Kind::ProgressBar) {
1723            return None;
1724        }
1725        self.relative_rules
1726            .iter()
1727            .find(|r| r.kind == RULE_WAVY_PROGRESS)
1728            .map(|r| parse_wavy_progress(r.anchor))
1729    }
1730    pub(super) fn alert_dialog_icon(&self) -> Option<&'static str> {
1731        if !matches!(self.kind, Kind::Linear) {
1732            return None;
1733        }
1734        self.relative_rules
1735            .iter()
1736            .find(|r| r.kind == RULE_ALERT_DIALOG)
1737            .map(|r| r.anchor.trim())
1738    }
1739    pub(super) fn is_snackbar(&self) -> bool {
1740        matches!(self.kind, Kind::Linear)
1741            && self.relative_rules.iter().any(|r| r.kind == RULE_SNACKBAR)
1742    }
1743    pub(super) fn tab_options(&self) -> Option<XmlTabOptionsSpec> {
1744        if !matches!(self.kind, Kind::TabWidget) {
1745            return None;
1746        }
1747        self.relative_rules
1748            .iter()
1749            .find(|r| r.kind == RULE_TAB_OPTIONS)
1750            .map(|r| parse_tab_options(r.anchor))
1751    }
1752    pub(super) fn slider_options(&self) -> Option<SliderOptionsSpec> {
1753        if !matches!(self.kind, Kind::SeekBar) {
1754            return None;
1755        }
1756        self.relative_rules
1757            .iter()
1758            .find(|r| r.kind == RULE_SLIDER_OPTIONS)
1759            .map(|r| parse_slider_options(r.anchor))
1760    }
1761    pub(super) fn text_input_ext(&self) -> Option<TextInputExtSpec<'static>> {
1762        if !matches!(self.kind, Kind::Linear) {
1763            return None;
1764        }
1765        self.relative_rules
1766            .iter()
1767            .find(|r| r.kind == RULE_TEXT_INPUT_EXT)
1768            .map(|r| parse_text_input_ext(r.anchor))
1769    }
1770    pub(super) fn chip_group_wrap_spec(&self) -> Option<ChipGroupWrapSpec> {
1771        if !matches!(self.kind, Kind::Linear) {
1772            return None;
1773        }
1774        self.relative_rules
1775            .iter()
1776            .find(|r| r.kind == RULE_CHIP_GROUP_WRAP)
1777            .map(|r| parse_chip_group_wrap(r.anchor))
1778    }
1779    pub(super) fn is_floating_toolbar(&self) -> bool {
1780        matches!(self.kind, Kind::Linear)
1781            && self
1782                .relative_rules
1783                .iter()
1784                .any(|r| r.kind == RULE_FLOATING_TOOLBAR)
1785    }
1786    pub(super) fn button_group_spacing(&self) -> Option<f32> {
1787        if !matches!(self.kind, Kind::Linear) {
1788            return None;
1789        }
1790        self.relative_rules
1791            .iter()
1792            .find(|r| r.kind == RULE_BUTTON_GROUP)
1793            .map(|r| {
1794                r.anchor
1795                    .trim()
1796                    .parse::<f32>()
1797                    .ok()
1798                    .filter(|v| v.is_finite() && *v >= 0.0)
1799                    .unwrap_or(12.0)
1800            })
1801    }
1802    pub(super) fn is_split_button(&self) -> bool {
1803        matches!(self.kind, Kind::Linear)
1804            && self
1805                .relative_rules
1806                .iter()
1807                .any(|r| r.kind == RULE_SPLIT_BUTTON)
1808    }
1809    pub(super) fn is_carousel_item(&self) -> bool {
1810        matches!(self.kind, Kind::Frame)
1811            && self
1812                .relative_rules
1813                .iter()
1814                .any(|r| r.kind == RULE_CAROUSEL_ITEM)
1815    }
1816    pub(super) fn linear_extra_gap(&self, state: &LayoutState) -> f32 {
1817        if self.is_split_button() {
1818            state.dp(2.0)
1819        } else if let Some(sp) = self.button_group_spacing() {
1820            state.dp(sp)
1821        } else {
1822            0.0
1823        }
1824    }
1825    pub(super) fn alert_dialog_top_icon_extra(&self, state: &LayoutState) -> f32 {
1826        if let Some(icon_name) = self.alert_dialog_icon()
1827            && !icon_name.is_empty()
1828            && (state.images.contains_key(icon_name) || parse_material_icon(icon_name).is_some())
1829        {
1830            state.dp(40.0)
1831        } else {
1832            0.0
1833        }
1834    }
1835    pub(super) fn scale_anim(&self, kind: u16) -> Option<ScaleAnimationSpec> {
1836        self.relative_rules
1837            .iter()
1838            .find(|r| r.kind == kind)
1839            .and_then(|r| parse_scale_animation(r.anchor))
1840    }
1841    pub(super) fn rotate_anim(&self, kind: u16) -> Option<RotateAnimationSpec> {
1842        self.relative_rules
1843            .iter()
1844            .find(|r| r.kind == kind)
1845            .and_then(|r| parse_rotate_animation(r.anchor))
1846    }
1847    pub(super) fn elevation_anim(&self, kind: u16) -> Option<ElevationAnimationSpec> {
1848        self.relative_rules
1849            .iter()
1850            .find(|r| r.kind == kind)
1851            .and_then(|r| parse_elevation_animation(r.anchor))
1852    }
1853    pub(super) fn is_sheet_hidden(&self, state: &LayoutState, id: u64) -> bool {
1854        let key = if self.id.is_empty() {
1855            format!("#{id}")
1856        } else {
1857            self.id.to_owned()
1858        };
1859        let active_motion = state
1860            .sheet_motion
1861            .get(&key)
1862            .is_some_and(|m| m.settle.is_some() || m.dragging);
1863        if let Some(bs) = self.bottom_sheet_spec() {
1864            return bs.hideable
1865                && state.sheet_state.get(&key) == Some(&SHEET_STATE_HIDDEN)
1866                && !active_motion;
1867        }
1868        if self.side_sheet_spec().is_some() {
1869            return state.sheet_state.get(&key) == Some(&SHEET_STATE_HIDDEN) && !active_motion;
1870        }
1871        false
1872    }
1873    pub(super) fn resolve_bottom_sheet_height(
1874        &self,
1875        spec: BottomSheetSpec,
1876        parent_h: f32,
1877        max_h: f32,
1878        natural_h: f32,
1879        state: &LayoutState,
1880        id: u64,
1881    ) -> f32 {
1882        let key = if self.id.is_empty() {
1883            format!("#{id}")
1884        } else {
1885            self.id.to_owned()
1886        };
1887        if let Some(cur_h) = state.sheet_motion.get(&key).and_then(|m| m.current_h) {
1888            return cur_h.clamp(0.0, max_h);
1889        }
1890        let st = state.sheet_state.get(&key).copied();
1891        let peek_px = if spec.peek_h_dp > 0.0 {
1892            Some(state.dp(spec.peek_h_dp))
1893        } else {
1894            None
1895        };
1896        let target = match st {
1897            Some(SHEET_STATE_HIDDEN) if spec.hideable => 0.0,
1898            Some(SHEET_STATE_EXPANDED) => {
1899                if spec.fit_to_contents {
1900                    natural_h
1901                } else {
1902                    max_h
1903                }
1904            }
1905            Some(SHEET_STATE_HALF_EXPANDED) => parent_h * spec.half_ratio,
1906            Some(SHEET_STATE_COLLAPSED) => peek_px.unwrap_or(natural_h),
1907            _ => {
1908                if !spec.skip_collapsed {
1909                    peek_px.unwrap_or(natural_h)
1910                } else if spec.fit_to_contents {
1911                    natural_h
1912                } else {
1913                    max_h
1914                }
1915            }
1916        };
1917        target.clamp(0.0, max_h)
1918    }
1919    pub(super) fn chip_group_wrap_rects(
1920        &self,
1921        inner: Rect,
1922        spec: ChipGroupWrapSpec,
1923        state: &LayoutState,
1924        metrics: TextMetrics,
1925        id: u64,
1926    ) -> (Vec<Option<Rect>>, f32, f32) {
1927        let h_gap = state.dp(spec.h_spacing_dp.max(0.0));
1928        let v_gap = state.dp(spec.v_spacing_dp.max(0.0));
1929        let mut rects: Vec<Option<Rect>> = vec![None; self.children.len()];
1930        let mut rows: Vec<(f32, f32, Vec<(usize, f32, f32, f32, [f32; 4])>)> = Vec::new();
1931        let mut cur_x = 0.0_f32;
1932        let mut cur_h = 0.0_f32;
1933        let mut cur_row: Vec<(usize, f32, f32, f32, [f32; 4])> = Vec::new();
1934        let mut max_row_w = 0.0_f32;
1935        for (i, n) in self.children.iter().enumerate() {
1936            if n.effective_visibility(state) == Visibility::Gone {
1937                continue;
1938            }
1939            let cid = child_view_id(id, i, n);
1940            let m = n.resolved_margin(state);
1941            let avail_w = (inner.width - m[0] - m[2]).max(0.0);
1942            let cw = match n.width {
1943                Size::Dp(w) => state.dp(w).min(avail_w.max(state.dp(w))),
1944                Size::Match => avail_w,
1945                Size::Wrap => n
1946                    .layout_intrinsic(true, state, avail_w, metrics, cid)
1947                    .min(avail_w),
1948            };
1949            let ch = match n.height {
1950                Size::Dp(h) => state.dp(h),
1951                Size::Match => n.layout_intrinsic(false, state, cw, metrics, cid),
1952                Size::Wrap => n.layout_intrinsic(false, state, cw, metrics, cid),
1953            };
1954            let total_w = cw + m[0] + m[2];
1955            let total_h = ch + m[1] + m[3];
1956            if !spec.single_line
1957                && !cur_row.is_empty()
1958                && cur_x + h_gap + total_w > inner.width + 0.01
1959            {
1960                max_row_w = max_row_w.max(cur_x);
1961                rows.push((cur_x, cur_h, std::mem::take(&mut cur_row)));
1962                cur_x = 0.0;
1963                cur_h = 0.0;
1964            }
1965            let x_in_row = if cur_row.is_empty() {
1966                0.0
1967            } else {
1968                cur_x + h_gap
1969            };
1970            cur_x = x_in_row + total_w;
1971            cur_h = cur_h.max(total_h);
1972            cur_row.push((i, x_in_row, cw, ch, m));
1973        }
1974        if !cur_row.is_empty() {
1975            max_row_w = max_row_w.max(cur_x);
1976            rows.push((cur_x, cur_h, cur_row));
1977        }
1978        let mut cursor_y = 0.0_f32;
1979        for (row_idx, (_rw, row_h, items)) in rows.into_iter().enumerate() {
1980            if row_idx > 0 {
1981                cursor_y += v_gap;
1982            }
1983            for (i, x_in_row, cw, ch, m) in items {
1984                let total_h = ch + m[1] + m[3];
1985                let rx = if state.rtl {
1986                    inner.x + inner.width - (x_in_row + m[0] + cw)
1987                } else {
1988                    inner.x + x_in_row + m[0]
1989                };
1990                let ry = inner.y + cursor_y + (row_h - total_h) * 0.5 + m[1];
1991                rects[i] = Some(Rect {
1992                    x: rx,
1993                    y: ry,
1994                    width: cw,
1995                    height: ch,
1996                });
1997            }
1998            cursor_y += row_h;
1999        }
2000        (rects, max_row_w, cursor_y)
2001    }
2002    pub(super) fn resolved_bg_image<'a>(
2003        &'a self,
2004        state: &LayoutState,
2005        key: &str,
2006        response: Response,
2007    ) -> Option<(&'a str, Option<NinePatchBands>)> {
2008        let bits = self.live_state_mask(state, key, response);
2009        for rule in self
2010            .relative_rules
2011            .iter()
2012            .filter(|r| r.kind == RULE_STATEFUL_BG_IMAGE)
2013        {
2014            if let Some((required, forbidden, img_key, stretch_str)) =
2015                parse_stateful_image_rule(rule.anchor)
2016            {
2017                if (bits & required) == required && (bits & forbidden) == 0 {
2018                    if img_key.is_empty() {
2019                        return None;
2020                    }
2021                    return Some((img_key, parse_nine_patch_stretch(stretch_str)));
2022                }
2023            }
2024        }
2025        if let Some((img_key, stretch_str)) = self
2026            .relative_rules
2027            .iter()
2028            .find(|r| r.kind == RULE_BACKGROUND_IMAGE)
2029            .and_then(|r| parse_bg_image_rule(r.anchor))
2030        {
2031            return Some((img_key, parse_nine_patch_stretch(stretch_str)));
2032        }
2033        None
2034    }
2035    pub(super) fn resolved_image_src<'a>(
2036        &'a self,
2037        state: &'a LayoutState,
2038        key: &str,
2039        response: Response,
2040    ) -> (&'a str, Option<NinePatchBands>, bool) {
2041        if let Some(override_src) = state.image_sources.get(key) {
2042            let stretch = if override_src.as_str() == self.image_src {
2043                self.relative_rules
2044                    .iter()
2045                    .find(|r| r.kind == RULE_IMAGE_NINE_PATCH)
2046                    .and_then(|r| parse_nine_patch_stretch(r.anchor))
2047            } else {
2048                None
2049            };
2050            return (override_src.as_str(), stretch, true);
2051        }
2052        let bits = self.live_state_mask(state, key, response);
2053        for rule in self
2054            .relative_rules
2055            .iter()
2056            .filter(|r| r.kind == RULE_STATEFUL_IMAGE_SRC)
2057        {
2058            if let Some((required, forbidden, img_key, stretch_str)) =
2059                parse_stateful_image_rule(rule.anchor)
2060            {
2061                if (bits & required) == required && (bits & forbidden) == 0 {
2062                    return (img_key, parse_nine_patch_stretch(stretch_str), false);
2063                }
2064            }
2065        }
2066        let stretch = self
2067            .relative_rules
2068            .iter()
2069            .find(|r| r.kind == RULE_IMAGE_NINE_PATCH)
2070            .and_then(|r| parse_nine_patch_stretch(r.anchor));
2071        (self.image_src, stretch, false)
2072    }
2073    pub(super) fn resolved_intrinsic_image_src<'a>(
2074        &'a self,
2075        state: &'a LayoutState,
2076        key: &str,
2077    ) -> &'a str {
2078        if let Some(override_src) = state.image_sources.get(key) {
2079            return override_src.as_str();
2080        }
2081        if let Some(spec) = self.dynamic_drawable_src() {
2082            return match spec {
2083                DynamicDrawableSpec::Level(items) => {
2084                    let level = state.drawable_level.get(key).copied().unwrap_or(0);
2085                    select_level_drawable_key(&items, level)
2086                }
2087                DynamicDrawableSpec::Clip { img_key, .. }
2088                | DynamicDrawableSpec::Rotate { img_key, .. }
2089                | DynamicDrawableSpec::Scale { img_key, .. } => img_key,
2090                DynamicDrawableSpec::Transition {
2091                    img_key_0,
2092                    img_key_1,
2093                    ..
2094                } => {
2095                    let active = state
2096                        .drawable_transition_active
2097                        .get(key)
2098                        .copied()
2099                        .unwrap_or(false);
2100                    if active && !img_key_1.is_empty() {
2101                        img_key_1
2102                    } else if !img_key_0.is_empty() {
2103                        img_key_0
2104                    } else {
2105                        img_key_1
2106                    }
2107                }
2108            };
2109        }
2110        if let Some(spec) = self.animation_list_spec() {
2111            return spec.frames[0].img_key;
2112        }
2113        if let Some(spec) = self.animated_vector_spec(true) {
2114            return if !spec.repeat && state.frame_reduced_motion {
2115                spec.frames[spec.frames.len() - 1]
2116            } else {
2117                spec.frames[0]
2118            };
2119        }
2120        if !self.image_src.is_empty() {
2121            return self.image_src;
2122        }
2123        self.relative_rules
2124            .iter()
2125            .filter(|r| r.kind == RULE_STATEFUL_IMAGE_SRC)
2126            .filter_map(|r| parse_stateful_image_rule(r.anchor))
2127            .find_map(|(_, _, img_key, _)| (!img_key.is_empty()).then_some(img_key))
2128            .or_else(|| {
2129                self.relative_rules
2130                    .iter()
2131                    .filter(|r| r.kind == RULE_ANIMATED_SELECTOR)
2132                    .filter_map(|r| parse_animated_selector_transition(r.anchor))
2133                    .find_map(|t| (t.is_src && !t.frames.is_empty()).then_some(t.frames[0].img_key))
2134            })
2135            .unwrap_or("")
2136    }
2137    pub(super) fn paint_constraint_layer_chrome(
2138        &self,
2139        f: &mut Frame<'_>,
2140        b: Rect,
2141        state: &mut LayoutState,
2142    ) {
2143        if b.width <= 0.0 || b.height <= 0.0 {
2144            return;
2145        }
2146        let background_tint = self
2147            .relative_rules
2148            .iter()
2149            .find(|r| r.kind == RULE_BACKGROUND_TINT)
2150            .and_then(|r| {
2151                let mut parts = r
2152                    .anchor
2153                    .split(',')
2154                    .filter_map(|p| p.trim().parse::<u8>().ok());
2155                Some(Color(
2156                    parts.next()?,
2157                    parts.next()?,
2158                    parts.next()?,
2159                    parts.next()?,
2160                ))
2161            });
2162        let scaled_radius = if self.radius < 0.0 {
2163            self.radius
2164        } else {
2165            state.dp(self.radius)
2166        };
2167        let corner_radii = self.resolved_corner_radii(state);
2168        let corner_family = self.resolved_corner_family();
2169        let gradient = self
2170            .relative_rules
2171            .iter()
2172            .find(|r| r.kind == RULE_GRADIENT)
2173            .and_then(|r| parse_gradient(r.anchor));
2174        let explicit_elevation = self
2175            .relative_rules
2176            .iter()
2177            .find(|r| r.kind == RULE_ELEVATION)
2178            .and_then(|r| r.anchor.trim().parse::<f32>().ok())
2179            .filter(|v| v.is_finite() && *v > 0.0);
2180        if let Some(dp) = explicit_elevation {
2181            let elev_radius = if self.radius < 0.0 {
2182                b.width.min(b.height) * 0.5
2183            } else if scaled_radius > 0.0 {
2184                scaled_radius
2185            } else if let Some([tl, tr, br, bl]) = corner_radii {
2186                tl.max(tr).max(br).max(bl)
2187            } else {
2188                0.0
2189            };
2190            paint_elevation_level(
2191                f,
2192                b,
2193                elev_radius,
2194                elevation_level_from_dp(dp),
2195                state.effective_density(),
2196            );
2197        }
2198        let is_oval = self.radius < 0.0 && corner_radii.is_none();
2199        if let Some(spec) = gradient {
2200            let radii = corner_radii.unwrap_or([scaled_radius.max(0.0); 4]);
2201            paint_gradient(
2202                f,
2203                state,
2204                b,
2205                spec,
2206                is_oval,
2207                radii,
2208                corner_family,
2209                background_tint,
2210            );
2211        } else if let Some(color) = background_tint.or(self.background) {
2212            paint_shape_fill_with_family(
2213                f,
2214                state,
2215                b,
2216                is_oval,
2217                corner_radii,
2218                scaled_radius,
2219                corner_family,
2220                color,
2221            );
2222        }
2223        if let Some((img_key, stretch)) = self
2224            .relative_rules
2225            .iter()
2226            .find(|r| r.kind == RULE_BACKGROUND_IMAGE)
2227            .and_then(|r| parse_bg_image_rule(r.anchor))
2228            .map(|(k, s)| (k, parse_nine_patch_stretch(s)))
2229            && let Some(img) = state.images.get(img_key).cloned()
2230        {
2231            let bg_img_start = f.commands.len();
2232            let density =
2233                state.image_scales.get(img_key).copied().unwrap_or(1.0) * state.effective_density();
2234            if let Some(ref bands) = stretch {
2235                paint_nine_patch_image(f, state, b, &img, bands, background_tint, 1, 255, density);
2236            } else {
2237                let tinted = tint_image(state, &img, background_tint, 1);
2238                f.commands.push(DrawCommand::Image {
2239                    bounds: b,
2240                    uv: [0.0, 0.0, 1.0, 1.0],
2241                    radius: 0.0,
2242                    color: Color(255, 255, 255, 255),
2243                    image: tinted,
2244                });
2245            }
2246            let outline_radii = corner_radii.unwrap_or([scaled_radius.max(0.0); 4]);
2247            clip_commands_to_rounded_outline(f, bg_img_start, b, is_oval, outline_radii);
2248        }
2249        let d = state.effective_density();
2250        for rule in self
2251            .relative_rules
2252            .iter()
2253            .filter(|r| r.kind == RULE_DRAWABLE_LAYER)
2254        {
2255            if let Some(layer) = parse_drawable_layer(rule.anchor) {
2256                paint_drawable_layer(f, b, layer, background_tint, d);
2257            }
2258        }
2259        if let Some(color) = self.background_stroke {
2260            let sw = state.dp(self.background_stroke_width);
2261            paint_shape_outline_with_family(
2262                f,
2263                b,
2264                is_oval,
2265                corner_radii,
2266                scaled_radius,
2267                corner_family,
2268                sw,
2269                color,
2270            );
2271        }
2272    }
2273    pub(super) fn paint_stateful_drawable_layers(
2274        &self,
2275        f: &mut Frame<'_>,
2276        b: Rect,
2277        state: &LayoutState,
2278        key: &str,
2279        response: Response,
2280        tint: Option<Color>,
2281    ) {
2282        let bits = self.live_state_mask(state, key, response);
2283        let specs: Vec<StatefulDrawableLayerSpec> = self
2284            .relative_rules
2285            .iter()
2286            .filter(|r| r.kind == RULE_STATEFUL_DRAWABLE_LAYER)
2287            .filter_map(|r| parse_stateful_drawable_layer(r.anchor))
2288            .collect();
2289        if specs.is_empty() {
2290            return;
2291        }
2292        if let Some(first_idx) = specs
2293            .iter()
2294            .position(|s| (bits & s.required) == s.required && (bits & s.forbidden) == 0)
2295        {
2296            let (req, forbid) = (specs[first_idx].required, specs[first_idx].forbidden);
2297            let d = state.effective_density();
2298            for spec in &specs[first_idx..] {
2299                if spec.required != req || spec.forbidden != forbid {
2300                    break;
2301                }
2302                paint_drawable_layer(f, b, spec.layer, tint, d);
2303            }
2304        }
2305    }
2306    pub(super) fn text_input_extra_height(
2307        &self,
2308        spec: &TextInputBoxSpec<'_>,
2309        state: &LayoutState,
2310        id: u64,
2311    ) -> (f32, f32) {
2312        let key = if self.id.is_empty() {
2313            format!("#{id}")
2314        } else {
2315            self.id.to_owned()
2316        };
2317        let effective_hint = if !spec.hint.is_empty() {
2318            spec.hint
2319        } else if !self.hint.is_empty() {
2320            self.hint
2321        } else {
2322            find_text_input_edit(self, id).map_or("", |(n, _, _)| n.hint)
2323        };
2324        let label_size = state.sp(12.0);
2325        let label_h = label_size.max(state.dp(12.0)) + state.dp(2.0);
2326        let top_inset = if spec.mode == TextInputBoxMode::Outline && !effective_hint.is_empty() {
2327            label_h * 0.5
2328        } else {
2329            0.0
2330        };
2331        let has_error = spec.error_enabled
2332            && state
2333                .text
2334                .get(&format!("{key}:error"))
2335                .is_some_and(|s| !s.is_empty());
2336        let has_counter = self.text_input_ext().is_some_and(|e| e.counter_enabled);
2337        let supporting_h = if has_error || !spec.helper.is_empty() || has_counter {
2338            state.dp(4.0) + (label_size * 1.3333).max(state.dp(16.0))
2339        } else {
2340            0.0
2341        };
2342        (top_inset, supporting_h)
2343    }
2344    pub(super) fn compute_coordinator_rects(
2345        &self,
2346        inner: Rect,
2347        state: &LayoutState,
2348        metrics: TextMetrics,
2349        id: u64,
2350    ) -> Vec<Option<Rect>> {
2351        let measure_frame_child = |i: usize, n: &Node, max_w: f32, max_h: f32| -> (f32, f32) {
2352            let mut w = max_w;
2353            let mut h = max_h;
2354            if let Size::Dp(dw) = n.width {
2355                w = state.dp(dw);
2356            }
2357            if let Size::Dp(dh) = n.height {
2358                h = state.dp(dh);
2359            }
2360            if matches!(n.kind, Kind::VideoView) {
2361                let name = if n.id.is_empty() {
2362                    format!("#{}", child_view_id(id, i, n))
2363                } else {
2364                    n.id.to_owned()
2365                };
2366                let size = state
2367                    .video_dimensions
2368                    .get(&name)
2369                    .copied()
2370                    .or_else(|| {
2371                        state
2372                            .video_frames
2373                            .get(&name)
2374                            .map(|frame| (frame.width(), frame.height()))
2375                    })
2376                    .unwrap_or((0, 0));
2377                let spec = |dimension: Size, available: f32| {
2378                    if matches!(dimension, Size::Wrap) {
2379                        VideoMeasureSpec::AtMost(available.max(0.0) as u32)
2380                    } else {
2381                        VideoMeasureSpec::Exactly(available.max(0.0) as u32)
2382                    }
2383                };
2384                let (vw, vh) = measure_video_view(size, spec(n.width, w), spec(n.height, h));
2385                return (vw as f32, vh as f32);
2386            }
2387            let cid = child_view_id(id, i, n);
2388            if let Some(ch) = n.collapsing_toolbar_height(state, cid) {
2389                h = ch.min(max_h);
2390            } else if matches!(n.kind, Kind::Linear)
2391                && let Size::Dp(dp_h) = n.height
2392                && let Some((ci, cc)) = n
2393                    .children
2394                    .iter()
2395                    .enumerate()
2396                    .find(|(_, c)| c.collapsing_toolbar_spec().is_some())
2397            {
2398                let cc_id = child_view_id(cid, ci, cc);
2399                if let (Some(spec), Some(ch)) = (
2400                    cc.collapsing_toolbar_spec(),
2401                    cc.collapsing_toolbar_height(state, cc_id),
2402                ) {
2403                    let delta = (state.dp(spec.expanded_h_dp) - ch).max(0.0);
2404                    h = (state.dp(dp_h) - delta)
2405                        .max(state.dp(64.0).min(state.dp(dp_h)))
2406                        .min(max_h);
2407                }
2408            } else if matches!(n.kind, Kind::Linear)
2409                && !n.horizontal
2410                && let Size::Dp(dp_h) = n.height
2411                && n.children
2412                    .iter()
2413                    .any(|c| c.app_bar_scroll_flags().is_some())
2414            {
2415                let pad = n.resolved_padding(state);
2416                let inner_w = (w - pad[0] - pad[2]).max(0.0);
2417                let delta = n.app_bar_children_collapse_total(state, inner_w, metrics, cid);
2418                h = (state.dp(dp_h) - delta).max(0.0).min(max_h);
2419            }
2420            if matches!(n.width, Size::Wrap) {
2421                w = n.layout_intrinsic(true, state, w, metrics, cid).min(w);
2422            }
2423            if matches!(n.height, Size::Wrap) && n.collapsing_toolbar_spec().is_none() {
2424                h = n.layout_intrinsic(false, state, w, metrics, cid).min(h);
2425            }
2426            (w, h)
2427        };
2428        let place_gravity = |n: &Node, area: Rect, margin: [f32; 4], w: f32, h: f32| -> Rect {
2429            let right = match n.layout_gravity[0] {
2430                0 => state.rtl,
2431                2 => !state.rtl,
2432                4 => true,
2433                _ => false,
2434            };
2435            let x = if n.layout_gravity[0] == 1 {
2436                area.x + (area.width - w) * 0.5 + margin[0] - margin[2]
2437            } else if right {
2438                area.x + area.width - w - margin[2]
2439            } else {
2440                area.x + margin[0]
2441            };
2442            let y = match n.layout_gravity[1] {
2443                1 => area.y + (area.height - h) * 0.5 + margin[1] - margin[3],
2444                2 => area.y + area.height - h - margin[3],
2445                _ => area.y + margin[1],
2446            };
2447            Rect {
2448                x,
2449                y,
2450                width: w,
2451                height: h,
2452            }
2453        };
2454        let mut rects: Vec<Option<Rect>> = vec![None; self.children.len()];
2455        let mut content_inner = inner;
2456        for (i, n) in self.children.iter().enumerate() {
2457            if n.effective_visibility(state) == Visibility::Gone {
2458                continue;
2459            }
2460            let cid = child_view_id(id, i, n);
2461            if let Some(ss) = n.side_sheet_spec()
2462                && ss.coplanar
2463                && !n.is_sheet_hidden(state, cid)
2464            {
2465                let margin = n.resolved_margin(state);
2466                let default_w = state.dp(320.0).min((inner.width * 0.8).max(0.0));
2467                let sw = match n.width {
2468                    Size::Dp(w) => state.dp(w).min(inner.width),
2469                    Size::Wrap => {
2470                        let iw = n.layout_intrinsic(true, state, inner.width, metrics, cid);
2471                        (if iw > 0.0 { iw } else { default_w }).min(inner.width)
2472                    }
2473                    Size::Match => default_w,
2474                };
2475                let phys_right = if ss.edge_start { state.rtl } else { !state.rtl };
2476                let total_sw = (sw + margin[0] + margin[2]).min(content_inner.width);
2477                if phys_right {
2478                    content_inner.width = (content_inner.width - total_sw).max(0.0);
2479                } else {
2480                    content_inner.x += total_sw;
2481                    content_inner.width = (content_inner.width - total_sw).max(0.0);
2482                }
2483            }
2484        }
2485        // Pass 1: layout all non-anchored visible children (including scroll behavior below appbar, bottom/side sheets).
2486        for (i, n) in self.children.iter().enumerate() {
2487            if n.effective_visibility(state) == Visibility::Gone
2488                || n.relative_rules
2489                    .iter()
2490                    .any(|r| r.kind == RULE_COORDINATOR_ANCHOR)
2491            {
2492                continue;
2493            }
2494            let cid = child_view_id(id, i, n);
2495            if n.is_sheet_hidden(state, cid) {
2496                continue;
2497            }
2498            let margin = n.resolved_margin(state);
2499            if let Some(bs) = n.bottom_sheet_spec() {
2500                let max_w = (content_inner.width - margin[0] - margin[2]).max(0.0);
2501                let max_h = (content_inner.height - margin[1] - margin[3]).max(0.0);
2502                let (w, natural_h) = measure_frame_child(i, n, max_w, max_h);
2503                let h = n.resolve_bottom_sheet_height(
2504                    bs,
2505                    content_inner.height,
2506                    max_h,
2507                    natural_h,
2508                    state,
2509                    cid,
2510                );
2511                let x = if n.layout_gravity_explicit {
2512                    place_gravity(n, content_inner, margin, w, h).x
2513                } else if w < max_w {
2514                    content_inner.x + (content_inner.width - w) * 0.5 + margin[0] - margin[2]
2515                } else {
2516                    content_inner.x + margin[0]
2517                };
2518                let y = content_inner.y + content_inner.height - h - margin[3];
2519                rects[i] = Some(Rect {
2520                    x,
2521                    y,
2522                    width: w,
2523                    height: h,
2524                });
2525                continue;
2526            }
2527            if let Some(ss) = n.side_sheet_spec() {
2528                let default_w = state.dp(320.0).min((inner.width * 0.8).max(0.0));
2529                let sw = match n.width {
2530                    Size::Dp(w) => state.dp(w).min(inner.width),
2531                    Size::Wrap => {
2532                        let iw = n.layout_intrinsic(true, state, inner.width, metrics, cid);
2533                        (if iw > 0.0 { iw } else { default_w }).min(inner.width)
2534                    }
2535                    Size::Match => default_w,
2536                };
2537                let sh = match n.height {
2538                    Size::Dp(h) => state.dp(h).min(inner.height),
2539                    Size::Wrap | Size::Match => (inner.height - margin[1] - margin[3]).max(0.0),
2540                };
2541                let phys_right = if ss.edge_start { state.rtl } else { !state.rtl };
2542                let x = if phys_right {
2543                    inner.x + inner.width - sw - margin[2]
2544                } else {
2545                    inner.x + margin[0]
2546                };
2547                let y = inner.y + margin[1];
2548                rects[i] = Some(Rect {
2549                    x,
2550                    y,
2551                    width: sw,
2552                    height: sh,
2553                });
2554                continue;
2555            }
2556            let has_scroll = n
2557                .relative_rules
2558                .iter()
2559                .any(|r| r.kind == RULE_COORDINATOR_SCROLL_BEHAVIOR);
2560            let area = if has_scroll {
2561                let appbar_h = (0..i)
2562                    .find_map(|j| {
2563                        let sib = &self.children[j];
2564                        if sib.effective_visibility(state) == Visibility::Gone
2565                            || (!matches!(sib.kind, Kind::Linear | Kind::Toolbar)
2566                                && sib.collapsing_toolbar_spec().is_none())
2567                            || sib.bottom_app_bar_spec().is_some()
2568                            || sib.layout_gravity[1] == 2
2569                            || sib.bottom_sheet_spec().is_some()
2570                            || sib.side_sheet_spec().is_some()
2571                            || sib.relative_rules.iter().any(|r| {
2572                                matches!(
2573                                    r.kind,
2574                                    RULE_COORDINATOR_SCROLL_BEHAVIOR | RULE_COORDINATOR_ANCHOR
2575                                )
2576                            })
2577                        {
2578                            return None;
2579                        }
2580                        let ab_rect = rects[j]?;
2581                        let ab_margin = sib.resolved_margin(state);
2582                        Some((ab_rect.y + ab_rect.height + ab_margin[3] - content_inner.y).max(0.0))
2583                    })
2584                    .unwrap_or(0.0);
2585                Rect {
2586                    x: content_inner.x,
2587                    y: content_inner.y + appbar_h,
2588                    width: content_inner.width,
2589                    height: (content_inner.height - appbar_h).max(0.0),
2590                }
2591            } else {
2592                content_inner
2593            };
2594            let max_w = (area.width - margin[0] - margin[2]).max(0.0);
2595            let max_h = (area.height - margin[1] - margin[3]).max(0.0);
2596            let (w, h) = measure_frame_child(i, n, max_w, max_h);
2597            let mut placed = place_gravity(n, area, margin, w, h);
2598            if n.bottom_app_bar_spec().is_some_and(|s| s.hide_on_scroll) {
2599                let bab_key = if n.id.is_empty() {
2600                    format!("#{cid}")
2601                } else {
2602                    n.id.to_owned()
2603                };
2604                let scroll_px = n.app_bar_scroll_px(state, cid);
2605                let (hs, _) = eval_bottom_app_bar_hide(&bab_key, scroll_px, state);
2606                placed.y += placed.height * hs.progress;
2607            }
2608            rects[i] = Some(placed);
2609        }
2610        // Pass 2: layout anchored children centered on their target sibling's edge/corner.
2611        for (i, n) in self.children.iter().enumerate() {
2612            if n.effective_visibility(state) == Visibility::Gone {
2613                continue;
2614            }
2615            let Some(anchor_rule) = n
2616                .relative_rules
2617                .iter()
2618                .find(|r| r.kind == RULE_COORDINATOR_ANCHOR)
2619            else {
2620                continue;
2621            };
2622            let margin = n.resolved_margin(state);
2623            let max_w = (inner.width - margin[0] - margin[2]).max(0.0);
2624            let max_h = (inner.height - margin[1] - margin[3]).max(0.0);
2625            let (w, h) = measure_frame_child(i, n, max_w, max_h);
2626            let target_id = anchor_rule
2627                .anchor
2628                .split_once(':')
2629                .map_or(anchor_rule.anchor, |(lhs, _)| lhs)
2630                .trim();
2631            let target_hit = if target_id.is_empty() {
2632                None
2633            } else {
2634                self.children
2635                    .iter()
2636                    .enumerate()
2637                    .find(|(j, sib)| *j != i && !sib.id.is_empty() && sib.id == target_id)
2638                    .and_then(|(j, sib)| rects[j].map(|r| (sib, r)))
2639            };
2640            rects[i] = Some(if let Some((target_sib, target)) = target_hit {
2641                if let Some(bab) = target_sib.bottom_app_bar_spec() {
2642                    let (fab_cx, fab_cy) = bottom_app_bar_fab_center(target, bab, w, state);
2643                    let min_x = inner.x + margin[0];
2644                    let max_x = (inner.x + inner.width - w - margin[2]).max(min_x);
2645                    let x = (fab_cx - w * 0.5).clamp(min_x, max_x);
2646                    let y = (fab_cy - h * 0.5).max(inner.y + margin[1]);
2647                    Rect {
2648                        x,
2649                        y,
2650                        width: w,
2651                        height: h,
2652                    }
2653                } else {
2654                    resolve_coordinator_anchor_rect(
2655                        anchor_rule.anchor,
2656                        target,
2657                        (w, h),
2658                        inner,
2659                        margin,
2660                        state.rtl,
2661                    )
2662                }
2663            } else {
2664                place_gravity(n, inner, margin, w, h)
2665            });
2666        }
2667        // Pass 3: Snackbar-aware FAB dodge — shift bottom-aligned FAB / ExtendedFAB siblings
2668        // upward by the visible bottom-docked Snackbar's height + margin + 8dp gap so they never overlap.
2669        let mut snackbar_dodge: Option<(f32, f32)> = None;
2670        for (si, sn) in self.children.iter().enumerate() {
2671            if sn.effective_visibility(state) != Visibility::Visible || !sn.is_snackbar() {
2672                continue;
2673            }
2674            let Some(sr) = rects[si] else { continue };
2675            let docked_bottom =
2676                sn.layout_gravity[1] == 2 || sr.y + sr.height >= inner.y + inner.height * 0.5;
2677            if !docked_bottom {
2678                continue;
2679            }
2680            let sm = sn.resolved_margin(state);
2681            let shift = sr.height + sm[1] + sm[3] + state.dp(8.0);
2682            snackbar_dodge = Some(match snackbar_dodge {
2683                Some((prev_top, prev_shift)) => (prev_top.min(sr.y), prev_shift.max(shift)),
2684                None => (sr.y, shift),
2685            });
2686        }
2687        if let Some((snack_top_y, shift)) = snackbar_dodge {
2688            let gap = state.dp(8.0);
2689            let is_m3 = matches!(
2690                state.theme_style,
2691                AndroidTheme::Material3Light | AndroidTheme::Material3Dark
2692            );
2693            for (i, n) in self.children.iter().enumerate() {
2694                if n.effective_visibility(state) == Visibility::Gone || n.is_snackbar() {
2695                    continue;
2696                }
2697                let elev_dp = n
2698                    .relative_rules
2699                    .iter()
2700                    .find(|r| r.kind == RULE_ELEVATION)
2701                    .and_then(|r| r.anchor.trim().parse::<f32>().ok())
2702                    .filter(|v| v.is_finite())
2703                    .unwrap_or(0.0);
2704                let is_fab = n.extended_fab_extended().is_some()
2705                    || (matches!(n.kind, Kind::Button | Kind::Icon)
2706                        && n.layout_gravity[1] == 2
2707                        && (elev_dp >= 4.0
2708                            || (matches!(n.kind, Kind::Icon) && n.radius < 0.0 && is_m3)));
2709                if !is_fab {
2710                    continue;
2711                }
2712                let is_bottom_aligned = n.layout_gravity[1] == 2
2713                    || rects[i].is_some_and(|r| r.y + r.height >= inner.y + inner.height * 0.5);
2714                if !is_bottom_aligned {
2715                    continue;
2716                }
2717                if let Some(ref mut r) = rects[i] {
2718                    let shifted_y = (r.y - shift).min(snack_top_y - gap - r.height);
2719                    r.y = shifted_y.max(inner.y);
2720                }
2721            }
2722        }
2723        rects
2724    }
2725    pub(super) fn resolved_text_alignment(&self, rtl: bool) -> Option<u8> {
2726        let rule = self
2727            .relative_rules
2728            .iter()
2729            .find(|r| r.kind == RULE_TEXT_ALIGNMENT)?;
2730        match rule.anchor.trim() {
2731            "start" | "textStart" | "viewStart" => Some(if rtl { 2 } else { 0 }),
2732            "center" | "1" => Some(1),
2733            "end" | "textEnd" | "viewEnd" => Some(if rtl { 0 } else { 2 }),
2734            "left" | "0" => Some(0),
2735            "right" | "2" => Some(2),
2736            _ => None,
2737        }
2738    }
2739    pub(super) fn resolved_corner_radii(&self, state: &LayoutState) -> Option<[f32; 4]> {
2740        let rule = self
2741            .relative_rules
2742            .iter()
2743            .find(|r| r.kind == RULE_CORNER_RADII)?;
2744        let d = state.effective_density();
2745        parse_corner_radii(rule.anchor).map(|r| r.map(|v| v * d))
2746    }
2747    pub(super) fn resolved_corner_family(&self) -> [bool; 4] {
2748        self.relative_rules
2749            .iter()
2750            .find(|r| r.kind == RULE_CORNER_FAMILY)
2751            .and_then(|r| parse_corner_family(r.anchor))
2752            .unwrap_or([false; 4])
2753    }
2754    pub(super) fn resolved_state_radius(&self, state: &LayoutState) -> f32 {
2755        if self.radius > 0.0 {
2756            state.dp(self.radius)
2757        } else if let Some([tl, tr, br, bl]) = self.resolved_corner_radii(state) {
2758            (tl + tr + br + bl) * 0.25
2759        } else {
2760            0.0
2761        }
2762    }
2763    pub(super) fn resolved_ripple(&self) -> Option<(Color, bool)> {
2764        let rule = self
2765            .relative_rules
2766            .iter()
2767            .find(|r| r.kind == RULE_RIPPLE_COLOR)?;
2768        let mut parts = rule.anchor.split('|');
2769        let color_str = parts.next()?.trim();
2770        let mut rgba = color_str.split(',').map(|p| p.trim().parse::<u8>().ok());
2771        let color = Color(rgba.next()??, rgba.next()??, rgba.next()??, rgba.next()??);
2772        if rgba.next().is_some() {
2773            return None;
2774        }
2775        let unbounded = parts
2776            .next()
2777            .is_some_and(|m| m.trim().eq_ignore_ascii_case("unbounded"));
2778        Some((color, unbounded))
2779    }
2780    pub(super) fn paint_state_layer(
2781        &self,
2782        f: &mut Frame<'_>,
2783        response: Response,
2784        default_radius: f32,
2785        corner_radii: Option<[f32; 4]>,
2786        default_color: Color,
2787    ) {
2788        let (color, unbounded) = match self.resolved_ripple() {
2789            Some((c, u)) => (c, u),
2790            None => (default_color, false),
2791        };
2792        if color.3 == 0 {
2793            return;
2794        }
2795        if unbounded {
2796            let b = response.bounds;
2797            let side = b.width.hypot(b.height);
2798            let ripple_bounds = Rect {
2799                x: b.x + (b.width - side) * 0.5,
2800                y: b.y + (b.height - side) * 0.5,
2801                width: side,
2802                height: side,
2803            };
2804            f.state_layer(
2805                Response {
2806                    bounds: ripple_bounds,
2807                    ..response
2808                },
2809                side * 0.5,
2810                color,
2811            );
2812        } else if let Some(radii) = corner_radii {
2813            let r = normalize_corner_radii(response.bounds, radii);
2814            if (r[0] - r[1]).abs() < 0.01
2815                && (r[1] - r[2]).abs() < 0.01
2816                && (r[2] - r[3]).abs() < 0.01
2817            {
2818                f.state_layer(response, r[0], color);
2819            } else {
2820                let max_r = r.into_iter().fold(0.0_f32, f32::max);
2821                let start = f.commands.len();
2822                f.state_layer(response, max_r, color);
2823                if f.commands.len() > start {
2824                    let emitted: Vec<DrawCommand> = f.commands.drain(start..).collect();
2825                    for cmd in emitted {
2826                        match cmd {
2827                            DrawCommand::RoundedRect {
2828                                bounds: cb,
2829                                color: c,
2830                                ..
2831                            } => {
2832                                paint_rounded_rect_radii(f, cb, r, c);
2833                            }
2834                            DrawCommand::Ripple {
2835                                bounds: rb,
2836                                center,
2837                                radius: ink_r,
2838                                color: c,
2839                                soft,
2840                                ..
2841                            } => {
2842                                paint_ripple_radii(f, rb, r, center, ink_r, c, soft);
2843                            }
2844                            other => f.commands.push(other),
2845                        }
2846                    }
2847                }
2848            }
2849        } else {
2850            f.state_layer(response, default_radius, color);
2851        }
2852    }
2853    pub(super) fn resolved_background(
2854        &self,
2855        state: &LayoutState,
2856        key: &str,
2857        response: Response,
2858    ) -> Option<Color> {
2859        let bits = u8::from(response.enabled)
2860            | (u8::from(response.pressed) << 1)
2861            | (u8::from(response.focused) << 2)
2862            | (u8::from(state.view_selected.get(key).copied().unwrap_or(false)) << 3)
2863            | (u8::from(state.view_activated.get(key).copied().unwrap_or(false)) << 4)
2864            | (u8::from(response.hovered) << 5)
2865            | (u8::from(
2866                matches!(
2867                    self.kind,
2868                    Kind::CheckedText
2869                        | Kind::CheckBox
2870                        | Kind::RadioButton
2871                        | Kind::Switch
2872                        | Kind::ToggleButton
2873                ) && state.checked.get(key).copied().unwrap_or(self.checked),
2874            ) << 6);
2875        let mut first = None;
2876        let mut fallback = None;
2877        for rule in self.relative_rules.iter().filter(|rule| rule.kind == 96) {
2878            let mut p = rule.anchor.split(',');
2879            let parsed = (|| {
2880                Some((
2881                    p.next()?.parse::<u8>().ok()?,
2882                    p.next()?.parse::<u8>().ok()?,
2883                    Color(
2884                        p.next()?.parse().ok()?,
2885                        p.next()?.parse().ok()?,
2886                        p.next()?.parse().ok()?,
2887                        p.next()?.parse().ok()?,
2888                    ),
2889                ))
2890            })();
2891            if let Some((required, forbidden, color)) = parsed {
2892                if first.is_none() {
2893                    first = Some(color);
2894                }
2895                if required == 0 && forbidden == 0 {
2896                    fallback = Some(color);
2897                }
2898                if bits & required == required && bits & forbidden == 0 {
2899                    return Some(color);
2900                }
2901            }
2902        }
2903        fallback.or(first).or(self.background)
2904    }
2905    pub(super) fn resolved_progress_tint(
2906        &self,
2907        kind: u16,
2908        state: &LayoutState,
2909        key: &str,
2910        response: Response,
2911    ) -> Option<Color> {
2912        self.resolved_tint_with_checked(kind, state, key, response, None)
2913    }
2914    pub(super) fn check_mark_width(&self, state: &LayoutState) -> f32 {
2915        let mut custom = false;
2916        let mut width = 0.0_f32;
2917        for rule in self.relative_rules.iter().filter(|r| r.kind == 164) {
2918            custom = true;
2919            if let Some(w) = rule
2920                .anchor
2921                .split(',')
2922                .nth(2)
2923                .and_then(|s| s.parse::<f32>().ok())
2924            {
2925                width = width.max(w);
2926            }
2927        }
2928        state.dp(if custom {
2929            if width > 0.0 { width + 8.0 } else { 0.0 }
2930        } else {
2931            32.0
2932        })
2933    }
2934    pub(super) fn compound_anim_spec(
2935        &self,
2936        slot: CompoundAnimSlot,
2937    ) -> Option<AnimationListSpec<'static>> {
2938        self.relative_rules
2939            .iter()
2940            .rev()
2941            .filter(|r| r.kind == RULE_COMPOUND_ANIMATION_LIST)
2942            .find_map(|r| {
2943                let (s, spec) = parse_compound_animation_list(r.anchor)?;
2944                (s == slot).then_some(spec)
2945            })
2946    }
2947    pub(super) fn compound_anim_slots(&self, rtl: bool) -> [Option<CompoundAnimSlot>; 4] {
2948        let has_start = self.compound_anim_spec(CompoundAnimSlot::Start).is_some();
2949        let has_end = self.compound_anim_spec(CompoundAnimSlot::End).is_some();
2950        let (left, right) = if has_start || has_end {
2951            if rtl {
2952                (
2953                    has_end.then_some(CompoundAnimSlot::End),
2954                    has_start.then_some(CompoundAnimSlot::Start),
2955                )
2956            } else {
2957                (
2958                    has_start.then_some(CompoundAnimSlot::Start),
2959                    has_end.then_some(CompoundAnimSlot::End),
2960                )
2961            }
2962        } else {
2963            (
2964                self.compound_anim_spec(CompoundAnimSlot::Left)
2965                    .is_some()
2966                    .then_some(CompoundAnimSlot::Left),
2967                self.compound_anim_spec(CompoundAnimSlot::Right)
2968                    .is_some()
2969                    .then_some(CompoundAnimSlot::Right),
2970            )
2971        };
2972        let top = self
2973            .compound_anim_spec(CompoundAnimSlot::Top)
2974            .is_some()
2975            .then_some(CompoundAnimSlot::Top);
2976        let bottom = self
2977            .compound_anim_spec(CompoundAnimSlot::Bottom)
2978            .is_some()
2979            .then_some(CompoundAnimSlot::Bottom);
2980        [left, top, right, bottom]
2981    }
2982    pub(super) fn compound_anim_intrinsic_size(
2983        &self,
2984        slot: CompoundAnimSlot,
2985        state: &LayoutState,
2986    ) -> Option<(f32, f32)> {
2987        let spec = self.compound_anim_spec(slot)?;
2988        let first_key = spec.frames.first()?.img_key;
2989        let img = state.images.get(first_key)?;
2990        let scale =
2991            state.image_scales.get(first_key).copied().unwrap_or(1.0) * state.effective_density();
2992        Some((img.width() as f32 * scale, img.height() as f32 * scale))
2993    }
2994    pub(super) fn compound_drawables(
2995        &self,
2996        state: &LayoutState,
2997        rtl: bool,
2998    ) -> [Option<(f32, f32, f32, Color)>; 4] {
2999        let d = state.effective_density();
3000        let get = |kind| {
3001            self.relative_rules
3002                .iter()
3003                .find(|r| r.kind == kind)
3004                .map(|rule| {
3005                    let mut p = rule.anchor.split(',');
3006                    (|| {
3007                        Some((
3008                            p.next()?.parse::<f32>().ok()?,
3009                            p.next()?.parse::<f32>().ok()?,
3010                            p.next()?.parse::<f32>().ok()?,
3011                            Color(
3012                                p.next()?.parse().ok()?,
3013                                p.next()?.parse().ok()?,
3014                                p.next()?.parse().ok()?,
3015                                p.next()?.parse().ok()?,
3016                            ),
3017                        ))
3018                    })()
3019                    .filter(|(w, h, _, _)| *w > 0.0 && *h > 0.0)
3020                    .map(|(w, h, r, c)| (w * d, h * d, if r < 0.0 { r } else { r * d }, c))
3021                })
3022        };
3023        let start = get(173);
3024        let end = get(174);
3025        let (left, right) = if start.flatten().is_some() || end.flatten().is_some() {
3026            if rtl {
3027                (end.flatten(), start.flatten())
3028            } else {
3029                (start.flatten(), end.flatten())
3030            }
3031        } else {
3032            (get(169).flatten(), get(171).flatten())
3033        };
3034        [left, get(170).flatten(), right, get(172).flatten()]
3035    }
3036    pub(super) fn compound_sizes(&self, state: &LayoutState, rtl: bool) -> [Option<(f32, f32)>; 4] {
3037        let shapes = self.compound_drawables(state, rtl);
3038        let anims = self.compound_anim_slots(rtl);
3039        std::array::from_fn(|i| {
3040            anims[i]
3041                .and_then(|slot| self.compound_anim_intrinsic_size(slot, state))
3042                .or_else(|| shapes[i].map(|(w, h, _, _)| (w, h)))
3043        })
3044    }
3045    pub(super) fn compound_extents(&self, state: &LayoutState, rtl: bool) -> [f32; 4] {
3046        let sizes = self.compound_sizes(state, rtl);
3047        let pad = state.dp(self
3048            .relative_rules
3049            .iter()
3050            .find(|r| r.kind == 175)
3051            .and_then(|r| r.anchor.parse::<f32>().ok())
3052            .unwrap_or(0.0)
3053            .max(0.0));
3054        [
3055            sizes[0].map_or(0.0, |(w, _)| w + pad),
3056            sizes[1].map_or(0.0, |(_, h)| h + pad),
3057            sizes[2].map_or(0.0, |(w, _)| w + pad),
3058            sizes[3].map_or(0.0, |(_, h)| h + pad),
3059        ]
3060    }
3061    pub(super) fn paint_compound_drawables(
3062        &self,
3063        f: &mut Frame<'_>,
3064        inner: Rect,
3065        text_area: Rect,
3066        state: &mut LayoutState,
3067        key: &str,
3068        response: Response,
3069    ) {
3070        let shapes = self.compound_drawables(state, state.rtl);
3071        let anim_slots = self.compound_anim_slots(state.rtl);
3072        if shapes.iter().all(Option::is_none) && anim_slots.iter().all(Option::is_none) {
3073            return;
3074        }
3075        let tint = self.resolved_progress_tint(176, state, key, response);
3076        let tint_mode = self
3077            .relative_rules
3078            .iter()
3079            .find(|r| r.kind == 177)
3080            .and_then(|r| r.anchor.parse::<u8>().ok())
3081            .unwrap_or(1);
3082        let has_relative = self.relative_rules.iter().any(|r| {
3083            (r.kind == 173 || r.kind == 174)
3084                && r.anchor
3085                    .split(',')
3086                    .next()
3087                    .and_then(|n| n.parse::<f32>().ok())
3088                    .is_some_and(|w| w > 0.0)
3089        });
3090        let sides = if has_relative {
3091            if state.rtl {
3092                [174, 170, 173, 172]
3093            } else {
3094                [173, 170, 174, 172]
3095            }
3096        } else {
3097            [169, 170, 171, 172]
3098        };
3099        let mirror = self.is_auto_mirrored() && state.rtl;
3100        let alpha = if response.enabled { 1.0 } else { 0.38 };
3101        f.within(inner, |f| {
3102            for i in 0..4 {
3103                if let Some(slot) = anim_slots[i]
3104                    && let Some(spec) = self.compound_anim_spec(slot)
3105                {
3106                    let (frame_key, next_wake) =
3107                        select_animation_list_frame(&spec, f.time(), f.reduced_motion());
3108                    if let Some(img) = state.images.get(frame_key).cloned() {
3109                        let scale = state.image_scales.get(frame_key).copied().unwrap_or(1.0)
3110                            * state.effective_density();
3111                        let (w, h) = (img.width() as f32 * scale, img.height() as f32 * scale);
3112                        let rect = match i {
3113                            0 => Rect {
3114                                x: inner.x,
3115                                y: text_area.y + (text_area.height - h) * 0.5,
3116                                width: w,
3117                                height: h,
3118                            },
3119                            1 => Rect {
3120                                x: text_area.x + (text_area.width - w) * 0.5,
3121                                y: inner.y,
3122                                width: w,
3123                                height: h,
3124                            },
3125                            2 => Rect {
3126                                x: inner.x + inner.width - w,
3127                                y: text_area.y + (text_area.height - h) * 0.5,
3128                                width: w,
3129                                height: h,
3130                            },
3131                            _ => Rect {
3132                                x: text_area.x + (text_area.width - w) * 0.5,
3133                                y: inner.y + inner.height - h,
3134                                width: w,
3135                                height: h,
3136                            },
3137                        };
3138                        if let Some(wake) = next_wake {
3139                            let vis = rect.intersect(f.clip);
3140                            if vis.width > 0.0 && vis.height > 0.0 {
3141                                f.wake_at(wake);
3142                            }
3143                        }
3144                        let tinted = tint_image(state, &img, tint, tint_mode);
3145                        if mirror {
3146                            f.push_transform(
3147                                [rect.x + rect.width * 0.5, rect.y + rect.height * 0.5],
3148                                [0.0, 0.0],
3149                                [-1.0, 1.0],
3150                                0.0,
3151                            );
3152                        }
3153                        f.commands.push(DrawCommand::Image {
3154                            bounds: rect,
3155                            uv: [0.0, 0.0, 1.0, 1.0],
3156                            radius: 0.0,
3157                            color: Color(255, 255, 255, 255).opacity(alpha),
3158                            image: tinted,
3159                        });
3160                        if mirror {
3161                            f.pop_transform();
3162                        }
3163                        continue;
3164                    }
3165                }
3166                let shape = shapes[i];
3167                let selected = self
3168                    .custom_check_mark(sides[i] + 9, state, key, response)
3169                    .unwrap_or(shape);
3170                if let (Some((w, h, _, _)), Some((source_w, source_h, r, original))) =
3171                    (shape, selected)
3172                {
3173                    let r = if r < 0.0 {
3174                        r
3175                    } else {
3176                        r * (w / source_w).min(h / source_h)
3177                    };
3178                    let color =
3179                        tint.map_or(original, |value| tint_pixel(original, value, tint_mode));
3180                    let rect = match i {
3181                        0 => Rect {
3182                            x: inner.x,
3183                            y: text_area.y + (text_area.height - h) * 0.5,
3184                            width: w,
3185                            height: h,
3186                        },
3187                        1 => Rect {
3188                            x: text_area.x + (text_area.width - w) * 0.5,
3189                            y: inner.y,
3190                            width: w,
3191                            height: h,
3192                        },
3193                        2 => Rect {
3194                            x: inner.x + inner.width - w,
3195                            y: text_area.y + (text_area.height - h) * 0.5,
3196                            width: w,
3197                            height: h,
3198                        },
3199                        _ => Rect {
3200                            x: text_area.x + (text_area.width - w) * 0.5,
3201                            y: inner.y + inner.height - h,
3202                            width: w,
3203                            height: h,
3204                        },
3205                    };
3206                    if r < 0.0 {
3207                        paint_oval(f, rect, color);
3208                    } else {
3209                        f.paint_rect(rect, r, color);
3210                    }
3211                }
3212            }
3213        });
3214    }
3215    pub(super) fn custom_check_mark(
3216        &self,
3217        kind: u16,
3218        state: &LayoutState,
3219        key: &str,
3220        response: Response,
3221    ) -> Option<Option<(f32, f32, f32, Color)>> {
3222        let d = state.effective_density();
3223        let bits = u8::from(response.enabled)
3224            | (u8::from(response.pressed) << 1)
3225            | (u8::from(response.focused) << 2)
3226            | (u8::from(state.view_selected.get(key).copied().unwrap_or(false)) << 3)
3227            | (u8::from(state.view_activated.get(key).copied().unwrap_or(false)) << 4)
3228            | (u8::from(response.hovered) << 5)
3229            | (u8::from(state.checked.get(key).copied().unwrap_or(self.checked)) << 6);
3230        let mut first = None;
3231        let mut fallback = None;
3232        for rule in self.relative_rules.iter().filter(|r| r.kind == kind) {
3233            let mut p = rule.anchor.split(',');
3234            let parsed = (|| {
3235                Some((
3236                    p.next()?.parse::<u8>().ok()?,
3237                    p.next()?.parse::<u8>().ok()?,
3238                    p.next()?.parse::<f32>().ok()?,
3239                    p.next()?.parse::<f32>().ok()?,
3240                    p.next()?.parse::<f32>().ok()?,
3241                    Color(
3242                        p.next()?.parse().ok()?,
3243                        p.next()?.parse().ok()?,
3244                        p.next()?.parse().ok()?,
3245                        p.next()?.parse().ok()?,
3246                    ),
3247                ))
3248            })();
3249            if let Some((required, forbidden, w, h, r, color)) = parsed {
3250                let mark = if w > 0.0 && h > 0.0 {
3251                    Some((w * d, h * d, if r < 0.0 { r } else { r * d }, color))
3252                } else {
3253                    None
3254                };
3255                if first.is_none() {
3256                    first = Some(mark);
3257                }
3258                if required == 0 && forbidden == 0 {
3259                    fallback = Some(mark);
3260                }
3261                if bits & required == required && bits & forbidden == 0 {
3262                    return Some(mark);
3263                }
3264            }
3265        }
3266        fallback.or_else(|| first.map(|_| None))
3267    }
3268    pub(super) fn resolved_tint_with_checked(
3269        &self,
3270        kind: u16,
3271        state: &LayoutState,
3272        key: &str,
3273        response: Response,
3274        checked: Option<bool>,
3275    ) -> Option<Color> {
3276        let bits = u8::from(response.enabled)
3277            | (u8::from(response.pressed) << 1)
3278            | (u8::from(response.focused) << 2)
3279            | (u8::from(state.view_selected.get(key).copied().unwrap_or(false)) << 3)
3280            | (u8::from(state.view_activated.get(key).copied().unwrap_or(false)) << 4)
3281            | (u8::from(response.hovered) << 5)
3282            | (u8::from(
3283                matches!(
3284                    self.kind,
3285                    Kind::CheckedText
3286                        | Kind::CheckBox
3287                        | Kind::RadioButton
3288                        | Kind::Switch
3289                        | Kind::ToggleButton
3290                ) && checked
3291                    .unwrap_or_else(|| state.checked.get(key).copied().unwrap_or(self.checked)),
3292            ) << 6);
3293        let mut first = None;
3294        let mut fallback = None;
3295        for rule in self.relative_rules.iter().filter(|rule| rule.kind == kind) {
3296            let mut p = rule.anchor.split(',');
3297            let parsed = (|| {
3298                Some((
3299                    p.next()?.parse::<u8>().ok()?,
3300                    p.next()?.parse::<u8>().ok()?,
3301                    Color(
3302                        p.next()?.parse().ok()?,
3303                        p.next()?.parse().ok()?,
3304                        p.next()?.parse().ok()?,
3305                        p.next()?.parse().ok()?,
3306                    ),
3307                ))
3308            })();
3309            if let Some((required, forbidden, color)) = parsed {
3310                if first.is_none() {
3311                    first = Some(color);
3312                }
3313                if required == 0 && forbidden == 0 {
3314                    fallback = Some(color);
3315                }
3316                if bits & required == required && bits & forbidden == 0 {
3317                    return Some(color);
3318                }
3319            }
3320        }
3321        fallback.or(first)
3322    }
3323    pub(super) fn resolved_image_tint(
3324        &self,
3325        state: &LayoutState,
3326        key: &str,
3327        response: Response,
3328    ) -> Option<Color> {
3329        self.resolved_state_color(
3330            self.image_tint_states,
3331            self.image_tint,
3332            state,
3333            key,
3334            response,
3335        )
3336    }
3337    pub(super) fn effective_visibility(&self, state: &LayoutState) -> Visibility {
3338        if state.motion_collision_probe_visible.contains(&(self as *const Node as usize)) {
3339            return Visibility::Visible;
3340        }
3341        if let Some((_, visual)) = state.motion_child_visual
3342            && !self.id.is_empty() && visual.node_id == self.id
3343        {
3344            return visual.visibility;
3345        }
3346        if self.id.is_empty() {
3347            return self.visibility;
3348        }
3349        state
3350            .visibility
3351            .get(self.id)
3352            .copied()
3353            .unwrap_or(self.visibility)
3354    }
3355    pub(super) fn resolved_view_padding(&self, state: &LayoutState) -> [f32; 4] {
3356        let d = state.effective_density();
3357        if matches!(self.kind, Kind::MaterialCard) {
3358            // CardView ignores setPadding/setPaddingRelative and uses physical
3359            // contentPadding values instead (AndroidX CardView.java).
3360            let (h, v) = self.card_compat_insets(state);
3361            return std::array::from_fn(|i| {
3362                self.relative_rules
3363                    .iter()
3364                    .find(|r| r.kind == 67 + i as u16)
3365                    .and_then(|r| r.anchor.parse::<f32>().ok())
3366                    .unwrap_or(0.0)
3367                    * d
3368                    + if i % 2 == 0 { h } else { v }
3369            });
3370        }
3371        let rtl = match self.layout_direction {
3372            1 => false,
3373            2 => true,
3374            _ => state.rtl,
3375        };
3376        let mut padding = self
3377            .background_padding
3378            .unwrap_or_else(|| self.default_theme_padding(state));
3379        if rtl && self.background_padding.is_some() {
3380            padding.swap(0, 2);
3381        }
3382        for (i, value) in padding.iter_mut().enumerate() {
3383            if self.padding_explicit[i] || self.padding_edges[i] != 0.0 {
3384                *value = self.padding_edges[i];
3385            }
3386        }
3387        let start = if rtl { 2 } else { 0 };
3388        let end = if rtl { 0 } else { 2 };
3389        if let Some(value) = self.padding_relative[0] {
3390            padding[start] = value;
3391        }
3392        if let Some(value) = self.padding_relative[1] {
3393            padding[end] = value;
3394        }
3395        padding.map(|v| v * d)
3396    }
3397    pub(super) fn card_compat_insets(&self, state: &LayoutState) -> (f32, f32) {
3398        let rule = |kind| {
3399            self.relative_rules
3400                .iter()
3401                .find(|r| r.kind == kind)
3402                .map(|r| r.anchor)
3403        };
3404        if rule(73) != Some("true") {
3405            return (0.0, 0.0);
3406        }
3407        let default_elevation = if rule(57) == Some("Elevated") {
3408            1.0
3409        } else {
3410            0.0
3411        };
3412        let elevation = rule(71)
3413            .and_then(|s| s.parse::<f32>().ok())
3414            .unwrap_or(default_elevation)
3415            .max(0.0);
3416        let max_elevation = rule(72)
3417            .and_then(|s| s.parse::<f32>().ok())
3418            .unwrap_or(0.0)
3419            .max(elevation);
3420        let radius = rule(66)
3421            .and_then(|s| s.parse::<f32>().ok())
3422            .unwrap_or(12.0)
3423            .max(0.0);
3424        let corner = if rule(74) == Some("false") {
3425            0.0
3426        } else {
3427            (1.0 - std::f32::consts::FRAC_1_SQRT_2) * radius
3428        };
3429        let d = state.effective_density();
3430        (
3431            (max_elevation + corner).ceil() * d,
3432            (1.5 * max_elevation + corner).ceil() * d,
3433        )
3434    }
3435    pub(super) fn resolved_padding(&self, state: &LayoutState) -> [f32; 4] {
3436        let mut padding = self.resolved_view_padding(state);
3437        if matches!(
3438            self.kind,
3439            Kind::Frame
3440                | Kind::MediaController
3441                | Kind::MaterialCard
3442                | Kind::ViewAnimator
3443                | Kind::ViewSwitcher
3444                | Kind::TextSwitcher
3445                | Kind::ImageSwitcher
3446                | Kind::ViewFlipper
3447        ) && self.foreground_gravity == [5, 5]
3448            && let Some(foreground) = self.foreground_padding
3449        {
3450            let d = state.effective_density();
3451            for i in 0..4 {
3452                let fg = foreground[i] * d;
3453                padding[i] = if self.foreground_excludes_padding {
3454                    padding[i] + fg
3455                } else {
3456                    padding[i].max(fg)
3457                };
3458            }
3459        }
3460        padding
3461    }
3462    pub(super) fn resolved_margin(&self, state: &LayoutState) -> [f32; 4] {
3463        let mut margin = self.margin;
3464        let start = if state.rtl { 2 } else { 0 };
3465        let end = if state.rtl { 0 } else { 2 };
3466        if let Some(value) = self.margin_relative[0] {
3467            margin[start] = value;
3468        }
3469        if let Some(value) = self.margin_relative[1] {
3470            margin[end] = value;
3471        }
3472        let d = state.effective_density();
3473        margin.map(|v| v * d)
3474    }
3475    pub(super) fn margin_for_axis(&self, horizontal: bool, state: &LayoutState) -> f32 {
3476        let margin = self.resolved_margin(state);
3477        if horizontal {
3478            margin[0] + margin[2]
3479        } else {
3480            margin[1] + margin[3]
3481        }
3482    }
3483    pub(super) fn divider_count(&self, state: &LayoutState) -> usize {
3484        if self.divider_color.is_none() {
3485            return 0;
3486        }
3487        let visible = self
3488            .children
3489            .iter()
3490            .filter(|n| n.effective_visibility(state) != Visibility::Gone)
3491            .count();
3492        if visible == 0 {
3493            return 0;
3494        }
3495        usize::from(self.divider_flags & 1 != 0)
3496            + if self.divider_flags & 2 != 0 {
3497                visible.saturating_sub(1)
3498            } else {
3499                0
3500            }
3501            + usize::from(self.divider_flags & 4 != 0)
3502    }
3503    pub(super) fn intrinsic(&self, horizontal: bool, state: &LayoutState, id: u64) -> f32 {
3504        let rtl = match self.layout_direction {
3505            1 => false,
3506            2 => true,
3507            _ => state.rtl,
3508        };
3509        if rtl != state.rtl {
3510            let mut scoped = state.clone();
3511            scoped.rtl = rtl;
3512            return self.intrinsic(horizontal, &scoped, id);
3513        }
3514        if self.is_search_view_closed(state, id)
3515            && matches!(
3516                if horizontal { self.width } else { self.height },
3517                Size::Wrap
3518            )
3519        {
3520            return 0.0;
3521        }
3522        if !horizontal && let Some(ch) = self.collapsing_toolbar_height(state, id) {
3523            return ch.max(state.dp(self.min_height));
3524        }
3525        let d = state.effective_density();
3526        match if horizontal { self.width } else { self.height } {
3527            Size::Dp(v) => v * d,
3528            _ => {
3529                let inner = match self.kind {
3530                    Kind::Linear | Kind::RadioGroup => {
3531                        if let Some(nav) = self.nav_bar_spec() {
3532                            let count = self.nav_items().len().max(1);
3533                            match nav.kind {
3534                                NavBarKind::Bar => {
3535                                    if horizontal {
3536                                        count as f32 * state.dp(80.0)
3537                                    } else {
3538                                        state.dp(80.0)
3539                                    }
3540                                }
3541                                NavBarKind::Rail => {
3542                                    if horizontal {
3543                                        state.dp(80.0)
3544                                    } else {
3545                                        let item_h = if nav.label_mode == NavLabelMode::Unlabeled {
3546                                            48.0
3547                                        } else {
3548                                            56.0
3549                                        };
3550                                        count as f32 * state.dp(item_h)
3551                                            + count.saturating_sub(1) as f32 * state.dp(12.0)
3552                                            + state.dp(24.0)
3553                                    }
3554                                }
3555                                NavBarKind::Drawer => {
3556                                    if horizontal {
3557                                        state.dp(300.0)
3558                                    } else {
3559                                        self.drawer_header_intrinsic_height(state, id)
3560                                            + count as f32 * state.dp(56.0)
3561                                            + state.dp(24.0)
3562                                    }
3563                                }
3564                            }
3565                        } else {
3566                            let visible_count = self
3567                                .children
3568                                .iter()
3569                                .filter(|n| n.effective_visibility(state) != Visibility::Gone)
3570                                .count();
3571                            let extra_gap_total = if self.horizontal == horizontal {
3572                                let gap = if let Some(cg) = self.chip_group_wrap_spec() {
3573                                    state.dp(cg.h_spacing_dp.max(0.0))
3574                                } else {
3575                                    self.linear_extra_gap(state)
3576                                };
3577                                visible_count.saturating_sub(1) as f32 * gap
3578                            } else {
3579                                0.0
3580                            };
3581                            let appbar_parent_scroll = if !horizontal
3582                                && !self.horizontal
3583                                && matches!(self.kind, Kind::Linear)
3584                                && self
3585                                    .children
3586                                    .iter()
3587                                    .any(|c| c.app_bar_scroll_flags().is_some())
3588                            {
3589                                Some(self.app_bar_scroll_px(state, id))
3590                            } else {
3591                                None
3592                            };
3593                            let base = if self.horizontal == horizontal {
3594                                self.children
3595                                    .iter()
3596                                    .enumerate()
3597                                    .map(|(i, n)| {
3598                                        if n.effective_visibility(state) == Visibility::Gone {
3599                                            0.0
3600                                        } else {
3601                                            let cid = child_view_id(id, i, n);
3602                                            let h = n.intrinsic(horizontal, state, cid);
3603                                            let m_axis = n.margin_for_axis(horizontal, state);
3604                                            if let Some(parent_scroll) = appbar_parent_scroll
3605                                                && n.app_bar_scroll_flags().is_some()
3606                                            {
3607                                                let sp = n.app_bar_child_scroll_px(
3608                                                    parent_scroll,
3609                                                    state,
3610                                                    cid,
3611                                                );
3612                                                let collapse = preview_app_bar_child_collapse(
3613                                                    n, cid, h, m_axis, sp, state,
3614                                                );
3615                                                (h + m_axis - collapse).max(0.0)
3616                                            } else {
3617                                                h + m_axis
3618                                            }
3619                                        }
3620                                    })
3621                                    .sum::<f32>()
3622                                    + extra_gap_total
3623                            } else {
3624                                self.children
3625                                    .iter()
3626                                    .enumerate()
3627                                    .map(|(i, n)| {
3628                                        if n.effective_visibility(state) == Visibility::Gone {
3629                                            0.0
3630                                        } else {
3631                                            n.intrinsic(horizontal, state, child_view_id(id, i, n))
3632                                                + n.margin_for_axis(horizontal, state)
3633                                        }
3634                                    })
3635                                    .fold(0., f32::max)
3636                            };
3637                            if !horizontal && let Some(spec) = self.text_input_box() {
3638                                let (top_inset, supporting_h) =
3639                                    self.text_input_extra_height(&spec, state, id);
3640                                base.max(state.dp(56.0)) + top_inset + supporting_h
3641                            } else if !horizontal && self.alert_dialog_icon().is_some() {
3642                                base + self.alert_dialog_top_icon_extra(state)
3643                            } else {
3644                                base
3645                            }
3646                        }
3647                    }
3648                    Kind::Grid => {
3649                        let (widths, heights, _, _, _) = self.grid_tracks(
3650                            state,
3651                            TextMetrics::default(),
3652                            id,
3653                            1000000.0,
3654                            false,
3655                            None,
3656                        );
3657                        if horizontal {
3658                            widths.iter().sum()
3659                        } else {
3660                            heights.iter().sum()
3661                        }
3662                    }
3663                    Kind::Table => {
3664                        if horizontal {
3665                            self.table_columns(state, TextMetrics::default(), id)
3666                                .iter()
3667                                .sum()
3668                        } else {
3669                            self.children
3670                                .iter()
3671                                .enumerate()
3672                                .filter(|(_, n)| n.effective_visibility(state) != Visibility::Gone)
3673                                .map(|(i, n)| {
3674                                    n.intrinsic(false, state, child_view_id(id, i, n))
3675                                        + n.margin_for_axis(false, state)
3676                                })
3677                                .sum()
3678                        }
3679                    }
3680                    Kind::TableRow => self
3681                        .children
3682                        .iter()
3683                        .enumerate()
3684                        .filter(|(_, n)| n.effective_visibility(state) != Visibility::Gone)
3685                        .map(|(i, n)| {
3686                            n.intrinsic(horizontal, state, child_view_id(id, i, n))
3687                                + n.margin_for_axis(horizontal, state)
3688                        })
3689                        .reduce(|a, b| if horizontal { a + b } else { a.max(b) })
3690                        .unwrap_or(0.0),
3691                    Kind::Relative | Kind::DialerFilter | Kind::ConstraintLayout => {
3692                        let bounds = Rect {
3693                            x: 0.0,
3694                            y: 0.0,
3695                            width: 1000000.0,
3696                            height: 1000000.0,
3697                        };
3698                        let is_cl = matches!(self.kind, Kind::ConstraintLayout);
3699                        let ph_claimed = if is_cl {
3700                            Some(resolve_constraint_placeholders(self.children, state).1)
3701                        } else {
3702                            None
3703                        };
3704                        let visibilities = if is_cl {
3705                            Some(constraint_group_visibilities(self.children, state))
3706                        } else {
3707                            None
3708                        };
3709                        let positions = if is_cl {
3710                            constraint_layout_positions(
3711                                self,
3712                                id,
3713                                bounds,
3714                                state,
3715                                TextMetrics::default(),
3716                                true,
3717                                true,
3718                            )
3719                        } else {
3720                            relative_layout::layout(
3721                                self,
3722                                id,
3723                                bounds,
3724                                state,
3725                                TextMetrics::default(),
3726                                true,
3727                                true,
3728                            )
3729                        };
3730                        let extent = positions
3731                            .iter()
3732                            .enumerate()
3733                            .filter(|(i, _)| {
3734                                let vis = visibilities.as_ref().map_or_else(
3735                                    || self.children[*i].effective_visibility(state),
3736                                    |v| v[*i],
3737                                );
3738                                vis != Visibility::Gone
3739                                    && !(is_cl && is_constraint_helper(&self.children[*i]))
3740                                    && !ph_claimed.as_ref().is_some_and(|m| m[*i].is_some())
3741                            })
3742                            .map(|(i, r)| {
3743                                let m = self.children[i].resolved_margin(state);
3744                                if horizontal {
3745                                    if state.rtl {
3746                                        (bounds.x + bounds.width) - (r.x - m[0])
3747                                    } else {
3748                                        r.x + r.width + m[2]
3749                                    }
3750                                } else {
3751                                    r.y + r.height + m[3]
3752                                }
3753                            })
3754                            .fold(0.0_f32, f32::max);
3755                        extent
3756                    }
3757                    Kind::MaterialDivider => {
3758                        if horizontal {
3759                            0.0
3760                        } else {
3761                            state.dp(self.divider_thickness.max(0.0))
3762                        }
3763                    }
3764                    Kind::Spinner => state.dp(if horizontal { 160.0 } else { 48.0 }),
3765                    Kind::GridView if self.carousel_layout_spec().is_some() => {
3766                        state.dp(if horizontal { 240.0 } else { 180.0 })
3767                    }
3768                    Kind::GridView => state.dp(if horizontal { 160.0 } else { 48.0 }),
3769                    Kind::ListView if self.carousel_layout_spec().is_some() => {
3770                        state.dp(if horizontal { 240.0 } else { 180.0 })
3771                    }
3772                    Kind::ListView => {
3773                        if horizontal {
3774                            state.dp(160.0)
3775                        } else {
3776                            let key = if self.id.is_empty() {
3777                                format!("#{id}")
3778                            } else {
3779                                self.id.to_owned()
3780                            };
3781                            let count = state.list_items.get(&key).map_or_else(
3782                                || self.relative_rules.iter().filter(|r| r.kind == 82).count(),
3783                                Vec::len,
3784                            );
3785                            count as f32 * state.dp(48.0)
3786                                + count.saturating_sub(1) as f32 * state.dp(self.divider_thickness)
3787                        }
3788                    }
3789                    Kind::Text | Kind::CheckedText | Kind::Chronometer | Kind::TextClock => {
3790                        let shapes = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
3791                            self.compound_sizes(state, state.rtl)
3792                        } else {
3793                            [None; 4]
3794                        };
3795                        let ext = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
3796                            self.compound_extents(state, state.rtl)
3797                        } else {
3798                            [0.0; 4]
3799                        };
3800                        let text_size = self.scaled_text_size(state);
3801                        if horizontal {
3802                            let key = if self.id.is_empty() {
3803                                format!("#{id}")
3804                            } else {
3805                                self.id.to_string()
3806                            };
3807                            let text = self.display_text_for(
3808                                state.text.get(&key).map_or(self.text, String::as_str),
3809                                state,
3810                            );
3811                            let count = text.chars().filter(|c| !c.is_control()).count();
3812                            let text = (count as f32 * text_size * 0.55
3813                                + count.saturating_sub(1) as f32
3814                                    * text_size
3815                                    * self.letter_spacing_em)
3816                                .max(0.0)
3817                                + if matches!(self.kind, Kind::CheckedText) {
3818                                    self.check_mark_width(state)
3819                                } else {
3820                                    0.0
3821                                };
3822                            (text + ext[0] + ext[2])
3823                                .max(shapes[1].map_or(0.0, |s| s.0))
3824                                .max(shapes[3].map_or(0.0, |s| s.0))
3825                        } else {
3826                            let lh = self.resolved_line_height(text_size, state);
3827                            let text = lh
3828                                + (self.min_lines.max(1) - 1) as f32
3829                                    * (lh * self.line_spacing_multiplier
3830                                        + state.dp(self.line_spacing_extra))
3831                                    .max(1.0);
3832                            text.max(shapes[0].map_or(0.0, |s| s.1))
3833                                .max(shapes[2].map_or(0.0, |s| s.1))
3834                                + ext[1]
3835                                + ext[3]
3836                        }
3837                    }
3838                    Kind::CheckBox | Kind::RadioButton | Kind::Switch => {
3839                        if horizontal {
3840                            state.dp(48.)
3841                                + self.text.chars().count() as f32
3842                                    * self.scaled_text_size(state)
3843                                    * 0.55
3844                        } else {
3845                            state.dp(48.)
3846                        }
3847                    }
3848                    Kind::ExpandableListView => state.dp(240.0),
3849                    Kind::SearchView => {
3850                        if self.search_bar_hint().is_some() {
3851                            state.dp(if horizontal { 240.0 } else { 56.0 })
3852                        } else {
3853                            state.dp(48.0)
3854                        }
3855                    }
3856                    Kind::Toolbar | Kind::ActionMenuView => {
3857                        if self.bottom_app_bar_spec().is_some() {
3858                            state.dp(if horizontal { 240.0 } else { 80.0 })
3859                        } else {
3860                            state.dp(if horizontal { 240.0 } else { 56.0 })
3861                        }
3862                    }
3863                    Kind::TabWidget if self.tab_options().is_some() => {
3864                        state.dp(if horizontal { 240.0 } else { 48.0 })
3865                    }
3866                    Kind::AdapterViewFlipper
3867                    | Kind::StackView
3868                    | Kind::Gallery
3869                    | Kind::TabWidget
3870                    | Kind::SlidingDrawer => state.dp(if horizontal { 240.0 } else { 160.0 }),
3871                    Kind::NumberPicker => state.dp(if horizontal { 80.0 } else { 144.0 }),
3872                    Kind::TimePicker
3873                        if self
3874                            .relative_rules
3875                            .iter()
3876                            .any(|r| r.kind == 105 && r.anchor == "clock") =>
3877                    {
3878                        state.dp(if horizontal { 328.0 } else { 476.0 })
3879                    }
3880                    Kind::TimePicker => state.dp(if horizontal { 280.0 } else { 144.0 }),
3881                    Kind::CalendarView => state.dp(if horizontal { 348.0 } else { 338.0 }),
3882                    Kind::DatePicker
3883                        if self
3884                            .relative_rules
3885                            .iter()
3886                            .any(|r| r.kind == 102 && r.anchor == "spinner") =>
3887                    {
3888                        let wheels = self
3889                            .relative_rules
3890                            .iter()
3891                            .all(|r| r.kind != 103 || r.anchor != "false");
3892                        let calendar = self
3893                            .relative_rules
3894                            .iter()
3895                            .all(|r| r.kind != 104 || r.anchor != "false");
3896                        state.dp(if horizontal {
3897                            if wheels && calendar { 540.0 } else { 348.0 }
3898                        } else if calendar {
3899                            338.0
3900                        } else {
3901                            144.0
3902                        })
3903                    }
3904                    Kind::DatePicker => state.dp(if horizontal { 348.0 } else { 454.0 }),
3905                    Kind::AnalogClock => state.dp(160.0),
3906                    Kind::RatingBar => state.dp(if horizontal {
3907                        self.num_stars as f32 * 48.0
3908                    } else {
3909                        48.0
3910                    }),
3911                    Kind::SeekBar => state.dp(if horizontal { 160. } else { 48. }),
3912                    Kind::ProgressBar if self.loading_indicator_contained().is_some() => {
3913                        state.dp(48.0)
3914                    }
3915                    Kind::ProgressBar if self.horizontal && self.wavy_progress_spec().is_some() => {
3916                        let spec = self.wavy_progress_spec().unwrap();
3917                        if horizontal {
3918                            state.dp(160.0)
3919                        } else {
3920                            state.dp((4.0 + spec.amplitude_dp * 2.0).max(12.0))
3921                        }
3922                    }
3923                    Kind::ProgressBar => state.dp(if self.horizontal && horizontal {
3924                        160.
3925                    } else if self.horizontal {
3926                        8.
3927                    } else {
3928                        48.
3929                    }),
3930                    Kind::View if self.is_drag_handle() => state.dp(48.0),
3931                    Kind::Image | Kind::QuickContactBadge | Kind::Icon | Kind::Zoom
3932                        if self.image_adjust_bounds
3933                            && horizontal
3934                            && matches!(self.width, Size::Wrap)
3935                            && matches!(self.height, Size::Dp(_)) =>
3936                    {
3937                        let key = if self.id.is_empty() {
3938                            format!("#{id}")
3939                        } else {
3940                            self.id.to_string()
3941                        };
3942                        let source = self.resolved_intrinsic_image_src(state, &key);
3943                        let padding = self.resolved_padding(state);
3944                        state.images.get(source).map_or(
3945                            if matches!(self.kind, Kind::Icon | Kind::Zoom) {
3946                                state.dp(48.0)
3947                            } else {
3948                                0.0
3949                            },
3950                            |image| {
3951                                let height = if let Size::Dp(h) = self.height {
3952                                    state.dp(h)
3953                                } else {
3954                                    0.0
3955                                };
3956                                (height - padding[1] - padding[3]).max(0.0) * image.width() as f32
3957                                    / image.height() as f32
3958                            },
3959                        )
3960                    }
3961                    Kind::Icon | Kind::Zoom if self.image_adjust_bounds => {
3962                        let key = if self.id.is_empty() {
3963                            format!("#{id}")
3964                        } else {
3965                            self.id.to_string()
3966                        };
3967                        let source = self.resolved_intrinsic_image_src(state, &key);
3968                        state.images.get(source).map_or(state.dp(48.0), |image| {
3969                            let scale = state.image_scales.get(source).copied().unwrap_or(1.0) * d;
3970                            (if horizontal {
3971                                image.width() as f32
3972                            } else {
3973                                image.height() as f32
3974                            }) * scale
3975                        })
3976                    }
3977                    Kind::Image | Kind::QuickContactBadge => {
3978                        let key = if self.id.is_empty() {
3979                            format!("#{id}")
3980                        } else {
3981                            self.id.to_string()
3982                        };
3983                        let source = self.resolved_intrinsic_image_src(state, &key);
3984                        state.images.get(source).map_or(0.0, |image| {
3985                            let scale = state.image_scales.get(source).copied().unwrap_or(1.0) * d;
3986                            (if horizontal {
3987                                image.width() as f32
3988                            } else {
3989                                image.height() as f32
3990                            }) * scale
3991                        })
3992                    }
3993                    Kind::VideoView => {
3994                        let key = if self.id.is_empty() {
3995                            format!("#{id}")
3996                        } else {
3997                            self.id.to_owned()
3998                        };
3999                        let dimensions = state
4000                            .video_dimensions
4001                            .get(&key)
4002                            .copied()
4003                            .or_else(|| {
4004                                state
4005                                    .video_frames
4006                                    .get(&key)
4007                                    .map(|frame| (frame.width(), frame.height()))
4008                            })
4009                            .unwrap_or((0, 0));
4010                        if horizontal {
4011                            dimensions.0 as f32
4012                        } else {
4013                            dimensions.1 as f32
4014                        }
4015                    }
4016                    Kind::ZoomControls => state.dp(if horizontal { 158. } else { 48. }),
4017                    Kind::Button if self.extended_fab_spec().is_some() => {
4018                        let (spec, m, _) = self.extended_fab_progress(state, id).unwrap();
4019                        let col = state.dp(spec.collapsed_size_dp);
4020                        if horizontal {
4021                            let ext_base = state.dp(44.0).max(col);
4022                            col + (ext_base - col) * m.progress
4023                        } else {
4024                            let ext_h = state.dp(56.0);
4025                            col + (ext_h - col) * m.progress
4026                        }
4027                    }
4028                    Kind::Button
4029                    | Kind::ToggleButton
4030                    | Kind::Icon
4031                    | Kind::Zoom
4032                    | Kind::Edit
4033                    | Kind::AutoComplete
4034                    | Kind::MultiAutoComplete => state.dp(48.),
4035                    _ => self
4036                        .children
4037                        .iter()
4038                        .enumerate()
4039                        .map(|(i, n)| {
4040                            if n.effective_visibility(state) == Visibility::Gone
4041                                && !self.measure_all_children
4042                            {
4043                                return 0.0;
4044                            }
4045                            if self.drawer_panel_is_closed(n, state, id) {
4046                                return 0.0;
4047                            }
4048                            n.intrinsic(horizontal, state, child_view_id(id, i, n))
4049                                + if matches!(self.kind, Kind::Absolute) {
4050                                    state.dp(n.absolute_position[if horizontal { 0 } else { 1 }])
4051                                } else {
4052                                    n.margin_for_axis(horizontal, state)
4053                                }
4054                        })
4055                        .fold(0., f32::max),
4056                };
4057                let inner = inner
4058                    + if matches!(self.kind, Kind::Linear | Kind::RadioGroup | Kind::TableRow)
4059                        && self.horizontal == horizontal
4060                    {
4061                        self.divider_count(state) as f32 * state.dp(self.divider_thickness)
4062                    } else {
4063                        0.0
4064                    };
4065                let mut minimum = state.dp(if horizontal {
4066                    self.min_width
4067                } else {
4068                    self.min_height
4069                });
4070                if !horizontal && self.is_snackbar() {
4071                    minimum = minimum.max(state.dp(48.0));
4072                } else if !horizontal && self.is_floating_toolbar() {
4073                    minimum = minimum.max(state.dp(64.0));
4074                }
4075                let bg_min = state.dp(self.background_min_size[usize::from(!horizontal)]);
4076                if matches!(self.kind, Kind::Space) {
4077                    return minimum.max(bg_min);
4078                }
4079                let padding = self.resolved_padding(state);
4080                let mut measured = (inner
4081                    + if horizontal {
4082                        padding[0] + padding[2]
4083                    } else {
4084                        padding[1] + padding[3]
4085                    })
4086                .max(minimum)
4087                .max(bg_min)
4088                .max(
4089                    if matches!(
4090                        self.kind,
4091                        Kind::Frame
4092                            | Kind::MediaController
4093                            | Kind::MaterialCard
4094                            | Kind::ViewAnimator
4095                            | Kind::ViewSwitcher
4096                            | Kind::TextSwitcher
4097                            | Kind::ImageSwitcher
4098                            | Kind::ViewFlipper
4099                    ) {
4100                        state.dp(self.foreground_size[usize::from(!horizontal)])
4101                    } else {
4102                        0.0
4103                    },
4104                );
4105                if horizontal
4106                    && self.image_adjust_bounds
4107                    && matches!(
4108                        self.kind,
4109                        Kind::Image | Kind::QuickContactBadge | Kind::Icon | Kind::Zoom
4110                    )
4111                    && matches!(self.width, Size::Wrap)
4112                {
4113                    if matches!(self.height, Size::Wrap)
4114                        && let Some(max_height) = self.image_max_height
4115                    {
4116                        let key = if self.id.is_empty() {
4117                            format!("#{id}")
4118                        } else {
4119                            self.id.to_string()
4120                        };
4121                        let source = state
4122                            .image_sources
4123                            .get(&key)
4124                            .map_or(self.image_src, String::as_str);
4125                        if let Some(image) = state.images.get(source) {
4126                            let max_content =
4127                                (state.dp(max_height) - padding[1] - padding[3]).max(0.0);
4128                            measured = measured.min(
4129                                max_content * image.width() as f32 / image.height() as f32
4130                                    + padding[0]
4131                                    + padding[2],
4132                            );
4133                        }
4134                    }
4135                    if let Some(max_width) = self.image_max_width {
4136                        measured = measured.min(state.dp(max_width));
4137                    }
4138                }
4139                measured
4140            }
4141        }
4142    }
4143    pub(super) fn grid_weight(&self, kind: u16) -> f32 {
4144        self.relative_rules
4145            .iter()
4146            .find(|r| r.kind == kind)
4147            .and_then(|r| r.anchor.parse::<f32>().ok())
4148            .filter(|v| v.is_finite() && *v > 0.0)
4149            .unwrap_or(0.0)
4150    }
4151    pub(super) fn grid_weighted_fill(&self, horizontal: bool) -> bool {
4152        let (weight, explicit) = if horizontal { (46, 48) } else { (47, 49) };
4153        self.grid_weight(weight) > 0.0 && !self.relative_rules.iter().any(|r| r.kind == explicit)
4154    }
4155    pub(super) fn grid_margin(&self, child: &Node, state: &LayoutState) -> [f32; 4] {
4156        let mut margin = child.resolved_margin(state);
4157        if !self.relative_rules.iter().any(|r| r.kind == 53) || matches!(child.kind, Kind::Space) {
4158            return margin;
4159        }
4160        let mut mask = child
4161            .relative_rules
4162            .iter()
4163            .find(|r| r.kind == 50)
4164            .and_then(|r| r.anchor.parse::<u8>().ok())
4165            .unwrap_or(0);
4166        if child.margin_relative[0].is_some() {
4167            mask |= if state.rtl { 4 } else { 1 };
4168        }
4169        if child.margin_relative[1].is_some() {
4170            mask |= if state.rtl { 1 } else { 4 };
4171        }
4172        // Each undefined side receives half the host theme's default gap.
4173        let gap = state
4174            .grid_default_gap
4175            .filter(|gap| gap.is_finite() && *gap >= 0.0)
4176            .unwrap_or_else(|| state.dp(8.0));
4177        for (i, value) in margin.iter_mut().enumerate() {
4178            if mask & (1 << i) == 0 {
4179                *value = gap / 2.0;
4180            }
4181        }
4182        margin
4183    }
4184    pub(super) fn grid_uses_baseline(&self) -> bool {
4185        self.layout_gravity[1] == 6
4186            || (self.layout_gravity[1] == 0
4187                && !self.relative_rules.iter().any(|r| r.kind == 49)
4188                && self.grid_weight(47) == 0.0)
4189    }
4190    // Initial GridLayout uses automatic placement and intrinsic span constraints.
4191    pub(super) fn grid_tracks(
4192        &self,
4193        state: &LayoutState,
4194        metrics: TextMetrics,
4195        id: u64,
4196        available_width: f32,
4197        expand_width: bool,
4198        available_height: Option<f32>,
4199    ) -> (
4200        Vec<f32>,
4201        Vec<f32>,
4202        Vec<(usize, usize, usize, usize)>,
4203        Vec<(usize, usize, f32)>,
4204        Vec<[f32; 4]>,
4205    ) {
4206        let count = self.children.len();
4207        let read = |kind| {
4208            self.relative_rules
4209                .iter()
4210                .find(|r| r.kind == kind)
4211                .and_then(|r| r.anchor.parse::<usize>().ok())
4212        };
4213        let minor_count =
4214            (if self.horizontal { read(40) } else { read(41) }).map(|count| count.clamp(1, 128));
4215        let mut occupied = vec![0usize; minor_count.unwrap_or(0)];
4216        let mut major = 0usize;
4217        let mut minor = 0usize;
4218        let mut positions = Vec::with_capacity(count);
4219        let mut cols = 0;
4220        let mut rows = 0;
4221        for child in self.children.iter() {
4222            let get = |kind| {
4223                child
4224                    .relative_rules
4225                    .iter()
4226                    .find(|r| r.kind == kind)
4227                    .and_then(|r| r.anchor.parse::<usize>().ok())
4228            };
4229            let explicit_major = if self.horizontal { get(43) } else { get(42) };
4230            let explicit_minor = if self.horizontal { get(42) } else { get(43) };
4231            let row_span = get(45).unwrap_or(1).clamp(1, 128);
4232            let col_span = get(44).unwrap_or(1).clamp(1, 128);
4233            let major_span = if self.horizontal { row_span } else { col_span };
4234            let mut minor_span = if self.horizontal { col_span } else { row_span };
4235            if let Some(value) = explicit_major {
4236                major = value;
4237            }
4238            if let Some(value) = explicit_minor {
4239                minor = value;
4240            }
4241            if let Some(limit) = minor_count {
4242                if explicit_minor.is_some() && minor >= limit {
4243                    minor = limit - 1;
4244                }
4245                minor_span = minor_span.min(if explicit_minor.is_some() {
4246                    limit - minor
4247                } else {
4248                    limit
4249                });
4250                if explicit_major.is_none() || explicit_minor.is_none() {
4251                    while minor + minor_span > limit
4252                        || occupied[minor..(minor + minor_span).min(limit)]
4253                            .iter()
4254                            .any(|&value| value > major)
4255                    {
4256                        if explicit_minor.is_some() {
4257                            major += 1;
4258                        } else if minor + minor_span <= limit {
4259                            minor += 1;
4260                        } else {
4261                            minor = 0;
4262                            major += 1;
4263                        }
4264                    }
4265                }
4266                for value in &mut occupied[minor..(minor + minor_span).min(limit)] {
4267                    *value = major + major_span;
4268                }
4269            }
4270            let (row, col, rs, cs) = if self.horizontal {
4271                (major, minor, major_span, minor_span)
4272            } else {
4273                (minor, major, minor_span, major_span)
4274            };
4275            positions.push((row, col, rs, cs));
4276            rows = rows.max(row + rs);
4277            cols = cols.max(col + cs);
4278            minor += minor_span;
4279        }
4280        let mut margins: Vec<[f32; 4]> = self
4281            .children
4282            .iter()
4283            .map(|n| self.grid_margin(n, state))
4284            .collect();
4285        if self.relative_rules.iter().any(|r| r.kind == 54) {
4286            let mut left = vec![0.0_f32; cols + 1];
4287            let mut right = vec![0.0_f32; cols + 1];
4288            let mut top = vec![0.0_f32; rows + 1];
4289            let mut bottom = vec![0.0_f32; rows + 1];
4290            for (i, n) in self.children.iter().enumerate() {
4291                if n.effective_visibility(state) == Visibility::Gone {
4292                    continue;
4293                }
4294                let (r, c, rs, cs) = positions[i];
4295                let m = margins[i];
4296                left[c] = left[c].max(m[0]);
4297                right[c + cs] = right[c + cs].max(m[2]);
4298                top[r] = top[r].max(m[1]);
4299                bottom[r + rs] = bottom[r + rs].max(m[3]);
4300            }
4301            for (i, m) in margins.iter_mut().enumerate() {
4302                let (r, c, rs, cs) = positions[i];
4303                *m = [left[c], top[r], right[c + cs], bottom[r + rs]];
4304            }
4305        }
4306        let mut width_constraints = Vec::new();
4307        // Single-track children establish track minima; spanning children add any deficit.
4308        for spanning in [false, true] {
4309            for (i, n) in self.children.iter().enumerate() {
4310                if n.effective_visibility(state) == Visibility::Gone {
4311                    continue;
4312                }
4313                let (_, col, _, span) = positions[i];
4314                if (span > 1) != spanning {
4315                    continue;
4316                }
4317                let margin = margins[i];
4318                let available = (available_width - margin[0] - margin[2]).max(0.0);
4319                let wanted = n
4320                    .layout_intrinsic(true, state, available, metrics, child_view_id(id, i, n))
4321                    .min(available)
4322                    + margin[0]
4323                    + margin[2];
4324                width_constraints.push((col, span, wanted, n.grid_weight(46)));
4325            }
4326        }
4327        let mut widths = grid_solve_constraints(cols, &width_constraints, 0.0, 0.0);
4328        if expand_width {
4329            grid_distribute(&mut widths, &width_constraints, available_width);
4330        }
4331        let mut height_constraints = Vec::new();
4332        for spanning in [false, true] {
4333            for (i, n) in self.children.iter().enumerate() {
4334                if n.effective_visibility(state) == Visibility::Gone {
4335                    continue;
4336                }
4337                let (row, col, span, cs) = positions[i];
4338                if (span > 1) != spanning {
4339                    continue;
4340                }
4341                let margin = margins[i];
4342                let available =
4343                    (widths[col..col + cs].iter().sum::<f32>() - margin[0] - margin[2]).max(0.0);
4344                let key = child_view_id(id, i, n);
4345                let width = if matches!(n.width, Size::Match)
4346                    || (n.layout_gravity_explicit && n.layout_gravity[0] == 5)
4347                    || n.grid_weighted_fill(true)
4348                {
4349                    available
4350                } else {
4351                    n.layout_intrinsic(true, state, available, metrics, key)
4352                        .min(available)
4353                };
4354                let wanted =
4355                    n.layout_intrinsic(false, state, width, metrics, key) + margin[1] + margin[3];
4356                height_constraints.push((row, span, wanted, n.grid_weight(47)));
4357            }
4358        }
4359        // Baseline groups are shared by children with the same row interval.
4360        let mut groups: Vec<(usize, usize, f32, f32)> = Vec::new();
4361        for (i, n) in self.children.iter().enumerate() {
4362            if n.effective_visibility(state) == Visibility::Gone
4363                || !n.grid_uses_baseline()
4364                || matches!(n.height, Size::Match)
4365            {
4366                continue;
4367            }
4368            let (row, col, rs, cs) = positions[i];
4369            let m = margins[i];
4370            let key = child_view_id(id, i, n);
4371            let available = (widths[col..col + cs].iter().sum::<f32>() - m[0] - m[2]).max(0.0);
4372            let width = if matches!(n.width, Size::Match)
4373                || (n.layout_gravity_explicit && n.layout_gravity[0] == 5)
4374                || n.grid_weighted_fill(true)
4375            {
4376                available
4377            } else {
4378                n.layout_intrinsic(true, state, available, metrics, key)
4379                    .min(available)
4380            };
4381            let height = n.layout_intrinsic(false, state, width, metrics, key);
4382            if let Some(base) = n.relative_baseline(width, height, state, metrics, key) {
4383                let above = base + m[1];
4384                let below = height - base + m[3];
4385                if let Some(group) = groups.iter_mut().find(|g| g.0 == row && g.1 == rs) {
4386                    group.2 = group.2.max(above);
4387                    group.3 = group.3.max(below);
4388                } else {
4389                    groups.push((row, rs, above, below));
4390                }
4391            }
4392        }
4393        for &(row, span, above, below) in &groups {
4394            height_constraints.push((row, span, above + below, 0.0));
4395        }
4396        let mut heights = grid_solve_constraints(rows, &height_constraints, 0.0, 0.0);
4397        if let Some(available) = available_height {
4398            grid_distribute(&mut heights, &height_constraints, available);
4399        }
4400        (
4401            widths,
4402            heights,
4403            positions,
4404            groups
4405                .into_iter()
4406                .map(|(row, span, above, _)| (row, span, above))
4407                .collect(),
4408            margins,
4409        )
4410    }
4411    // TableRow's virtual columns include explicit gaps and repeated columns for spans.
4412    pub(super) fn table_cells(&self) -> Vec<(usize, usize, usize)> {
4413        let mut result = Vec::with_capacity(self.children.len());
4414        let mut next = 0usize;
4415        for (index, cell) in self.children.iter().enumerate() {
4416            let read = |kind| {
4417                cell.relative_rules
4418                    .iter()
4419                    .find(|r| r.kind == kind)
4420                    .and_then(|r| r.anchor.parse::<usize>().ok())
4421            };
4422            let column = read(30).unwrap_or(next).max(next);
4423            let span = read(31).unwrap_or(1).clamp(1, 128);
4424            result.push((index, column, span));
4425            next = column.saturating_add(span);
4426        }
4427        result
4428    }
4429    pub(super) fn table_cell_collapsed(
4430        &self,
4431        state: &LayoutState,
4432        id: u64,
4433        column: usize,
4434        span: usize,
4435    ) -> bool {
4436        let initial = self
4437            .relative_rules
4438            .iter()
4439            .find(|r| r.kind == 34)
4440            .map(|r| r.anchor);
4441        (column..column + span).any(|index| {
4442            state
4443                .table_collapsed
4444                .get(&(id, index))
4445                .copied()
4446                .unwrap_or_else(|| {
4447                    initial.is_some_and(|list| {
4448                        list.split(',')
4449                            .any(|v| v.parse::<usize>().ok() == Some(index))
4450                    })
4451                })
4452        })
4453    }
4454    /// Override a named table column's collapsed state. Returns false for unnamed/non-table nodes.
4455    pub fn set_table_column_collapsed(
4456        &self,
4457        state: &mut LayoutState,
4458        column: usize,
4459        collapsed: bool,
4460    ) -> bool {
4461        if !matches!(self.kind, Kind::Table) || self.id.is_empty() {
4462            return false;
4463        }
4464        state
4465            .table_collapsed
4466            .insert((view_id(self.id), column), collapsed);
4467        true
4468    }
4469    pub(super) fn table_columns(
4470        &self,
4471        state: &LayoutState,
4472        metrics: TextMetrics,
4473        id: u64,
4474    ) -> Vec<f32> {
4475        let mut columns = Vec::<f32>::new();
4476        for (i, row) in self.children.iter().enumerate() {
4477            if !matches!(row.kind, Kind::TableRow)
4478                || row.effective_visibility(state) == Visibility::Gone
4479            {
4480                continue;
4481            }
4482            let row_rtl = match row.layout_direction {
4483                1 => false,
4484                2 => true,
4485                _ => state.rtl,
4486            };
4487            let scoped;
4488            let state = if row_rtl != state.rtl {
4489                scoped = {
4490                    let mut copy = state.clone();
4491                    copy.rtl = row_rtl;
4492                    copy
4493                };
4494                &scoped
4495            } else {
4496                state
4497            };
4498            for (j, column, span) in row.table_cells() {
4499                if columns.len() < column + span {
4500                    columns.resize(column + span, 0.0);
4501                }
4502                let cell = &row.children[j];
4503                if span == 1
4504                    && !self.table_cell_collapsed(state, id, column, span)
4505                    && cell.effective_visibility(state) != Visibility::Gone
4506                {
4507                    let key = child_view_id(child_view_id(id, i, row), j, cell);
4508                    columns[column] = columns[column].max(
4509                        cell.layout_intrinsic(true, state, 1_000_000.0, metrics, key)
4510                            + cell.margin_for_axis(true, state),
4511                    );
4512                }
4513            }
4514        }
4515        columns
4516    }
4517    pub(super) fn table_columns_for_width(
4518        &self,
4519        state: &LayoutState,
4520        metrics: TextMetrics,
4521        id: u64,
4522        width: f32,
4523    ) -> Vec<f32> {
4524        let mut columns = self.table_columns(state, metrics, id);
4525        let total = columns.iter().sum::<f32>();
4526        let kind = if total > width {
4527            33
4528        } else if total < width {
4529            32
4530        } else {
4531            return columns;
4532        };
4533        if let Some(rule) = self.relative_rules.iter().find(|r| r.kind == kind) {
4534            let selected: Vec<usize> = if rule.anchor == "*" {
4535                (0..columns.len()).collect()
4536            } else {
4537                rule.anchor
4538                    .split(',')
4539                    .filter_map(|part| part.parse::<usize>().ok())
4540                    .filter(|&index| index < columns.len())
4541                    .collect()
4542            };
4543            if !selected.is_empty() {
4544                // Android uses integer pixel deltas and truncates division toward zero.
4545                let extra = ((width - total) / selected.len() as f32).trunc();
4546                for index in selected {
4547                    columns[index] = (columns[index] + extra).max(0.0);
4548                }
4549            }
4550        }
4551        columns
4552    }
4553    // Baselines use the same font metrics as the renderer. Android tracks ascent
4554    // and descent separately for top, centre and bottom gravity groups.
4555    pub(super) fn table_row_metrics(
4556        &self,
4557        row: &Node,
4558        columns: &[f32],
4559        state: &LayoutState,
4560        metrics: TextMetrics,
4561        id: u64,
4562        table_id: u64,
4563    ) -> (f32, [f32; 3], [f32; 3]) {
4564        let row_rtl = match row.layout_direction {
4565            1 => false,
4566            2 => true,
4567            _ => state.rtl,
4568        };
4569        let scoped;
4570        let state = if row_rtl != state.rtl {
4571            scoped = {
4572                let mut copy = state.clone();
4573                copy.rtl = row_rtl;
4574                copy
4575            };
4576            &scoped
4577        } else {
4578            state
4579        };
4580        let padding = row.resolved_padding(state);
4581        let mut max_height = 0.0_f32;
4582        let mut ascent = [-1.0_f32; 3];
4583        let mut descent = [-1.0_f32; 3];
4584        let baseline_aligned = !row.relative_rules.iter().any(|r| r.kind == 36);
4585        for (j, column, span) in row.table_cells() {
4586            let n = &row.children[j];
4587            if n.effective_visibility(state) == Visibility::Gone
4588                || self.table_cell_collapsed(state, table_id, column, span)
4589            {
4590                continue;
4591            }
4592            let available = (columns.iter().skip(column).take(span).sum::<f32>()
4593                - n.margin_for_axis(true, state))
4594            .max(0.0);
4595            let child_id = child_view_id(id, j, n);
4596            let width = if n.relative_rules.iter().any(|r| r.kind == 35) {
4597                n.layout_intrinsic(true, state, available, metrics, child_id)
4598                    .min(available)
4599            } else {
4600                available
4601            };
4602            let height = n.layout_intrinsic(false, state, width, metrics, child_id);
4603            let margin = n.resolved_margin(state);
4604            max_height = max_height.max(height + margin[1] + margin[3]);
4605            if baseline_aligned
4606                && let Some(baseline) = n.relative_baseline(width, height, state, metrics, child_id)
4607            {
4608                let gravity = if n.layout_gravity_explicit {
4609                    n.layout_gravity[1]
4610                } else {
4611                    row.content_gravity[1]
4612                }
4613                .min(2) as usize;
4614                ascent[gravity] = ascent[gravity].max(baseline);
4615                descent[gravity] = descent[gravity].max(height + margin[1] + margin[3] - baseline);
4616            }
4617        }
4618        let max_ascent = ascent.iter().copied().fold(-1.0_f32, f32::max);
4619        let max_descent = descent.iter().copied().fold(-1.0_f32, f32::max);
4620        if max_ascent >= 0.0 && max_descent >= 0.0 {
4621            max_height = max_height.max(max_ascent + max_descent);
4622        }
4623        (max_height + padding[1] + padding[3], ascent, descent)
4624    }
4625    pub(super) fn standalone_row_metrics(
4626        &self,
4627        state: &LayoutState,
4628        metrics: TextMetrics,
4629        id: u64,
4630        widths: &[f32],
4631    ) -> (f32, [f32; 3], [f32; 3]) {
4632        let padding = self.resolved_padding(state);
4633        let mut max_height = 0.0_f32;
4634        let mut ascent = [-1.0_f32; 3];
4635        let mut descent = [-1.0_f32; 3];
4636        for (i, n) in self.children.iter().enumerate() {
4637            if n.effective_visibility(state) == Visibility::Gone {
4638                continue;
4639            }
4640            let key = child_view_id(id, i, n);
4641            let width = widths.get(i).copied().unwrap_or(0.0);
4642            let height =
4643                n.layout_intrinsic_for_width(false, state, width, n.weight > 0.0, metrics, key);
4644            let margin = n.resolved_margin(state);
4645            max_height = max_height.max(height + margin[1] + margin[3]);
4646            if !self.relative_rules.iter().any(|r| r.kind == 36)
4647                && let Some(base) = n.relative_baseline(width, height, state, metrics, key)
4648            {
4649                let gravity = if n.layout_gravity_explicit {
4650                    n.layout_gravity[1]
4651                } else {
4652                    self.content_gravity[1]
4653                }
4654                .min(2) as usize;
4655                ascent[gravity] = ascent[gravity].max(base);
4656                descent[gravity] = descent[gravity].max(height + margin[1] + margin[3] - base);
4657            }
4658        }
4659        let a = ascent.iter().copied().fold(-1.0_f32, f32::max);
4660        let d = descent.iter().copied().fold(-1.0_f32, f32::max);
4661        if a >= 0.0 && d >= 0.0 {
4662            max_height = max_height.max(a + d);
4663        }
4664        (max_height + padding[1] + padding[3], ascent, descent)
4665    }
4666    pub(super) fn linear_main_lengths(
4667        &self,
4668        horizontal: bool,
4669        state: &LayoutState,
4670        size: f32,
4671        inner_width: f32,
4672        metrics: TextMetrics,
4673        id: u64,
4674    ) -> Vec<f32> {
4675        let appbar_parent_scroll = if !horizontal
4676            && matches!(self.kind, Kind::Linear)
4677            && self
4678                .children
4679                .iter()
4680                .any(|c| c.app_bar_scroll_flags().is_some())
4681        {
4682            Some(self.app_bar_scroll_px(state, id))
4683        } else {
4684            None
4685        };
4686        let measure_child_len = |i: usize, n: &Node| -> (f32, f32) {
4687            let margins = n.resolved_margin(state);
4688            let cid = child_view_id(id, i, n);
4689            let len = n.layout_intrinsic(
4690                horizontal,
4691                state,
4692                (inner_width - margins[0] - margins[2]).max(0.0),
4693                metrics,
4694                cid,
4695            );
4696            let m_axis = n.margin_for_axis(horizontal, state);
4697            if let Some(parent_scroll) = appbar_parent_scroll
4698                && let Some(flags) = n.app_bar_scroll_flags()
4699            {
4700                let sp = n.app_bar_child_scroll_px(parent_scroll, state, cid);
4701                let collapse = preview_app_bar_child_collapse(n, cid, len, m_axis, sp, state);
4702                let (eff_top, vis_h, eff_bot, _) = app_bar_child_collapsed_layout(
4703                    len,
4704                    margins[1],
4705                    margins[3],
4706                    collapse,
4707                    flags.snap_margins,
4708                );
4709                return (vis_h, eff_top + eff_bot);
4710            }
4711            (len, m_axis)
4712        };
4713        let mut lengths = Vec::with_capacity(self.children.len());
4714        let mut fixed = 0.0_f32;
4715        let mut weight = 0.0_f32;
4716        let mut visible_children = 0usize;
4717        for (i, n) in self.children.iter().enumerate() {
4718            if n.effective_visibility(state) == Visibility::Gone {
4719                lengths.push(0.0);
4720                continue;
4721            }
4722            visible_children += 1;
4723            let (len, m_axis) = measure_child_len(i, n);
4724            lengths.push(len);
4725            fixed += len + m_axis;
4726            weight += n.weight;
4727        }
4728        let extra_gap = self.linear_extra_gap(state);
4729        fixed += if matches!(self.kind, Kind::Linear | Kind::RadioGroup | Kind::TableRow) {
4730            self.divider_count(state) as f32 * state.dp(self.divider_thickness)
4731                + visible_children.saturating_sub(1) as f32 * extra_gap
4732        } else {
4733            0.0
4734        };
4735        let mut excess = size - fixed;
4736        let mut remaining_weight = if self.weight_sum > 0.0 {
4737            self.weight_sum
4738        } else {
4739            weight
4740        };
4741        for (i, n) in self.children.iter().enumerate() {
4742            if n.effective_visibility(state) == Visibility::Gone {
4743                continue;
4744            }
4745            let share = if n.weight > 0.0 && remaining_weight.abs() > f32::EPSILON {
4746                excess * n.weight / remaining_weight
4747            } else {
4748                0.0
4749            };
4750            if n.weight > 0.0 {
4751                excess -= share;
4752                remaining_weight -= n.weight;
4753            }
4754            lengths[i] = (lengths[i] + share).max(0.0);
4755        }
4756        lengths
4757    }
4758    pub(super) fn table_row_height(
4759        &self,
4760        row: &Node,
4761        columns: &[f32],
4762        state: &LayoutState,
4763        metrics: TextMetrics,
4764        id: u64,
4765        table_id: u64,
4766    ) -> f32 {
4767        self.table_row_metrics(row, columns, state, metrics, id, table_id)
4768            .0
4769    }
4770    pub(super) fn effective_text_all_caps(&self, state: &LayoutState) -> bool {
4771        if let Some(rule) = self
4772            .relative_rules
4773            .iter()
4774            .find(|r| r.kind == RULE_TEXT_ALL_CAPS)
4775        {
4776            return rule.anchor.trim().eq_ignore_ascii_case("true");
4777        }
4778        if self.chip_style().is_some()
4779            || self.button_variant().is_some()
4780            || self.extended_fab_extended().is_some()
4781        {
4782            return self.text_all_caps;
4783        }
4784        self.text_all_caps
4785            || (matches!(self.kind, Kind::Button)
4786                && matches!(
4787                    state.theme_style,
4788                    AndroidTheme::MaterialLight | AndroidTheme::MaterialDark
4789                ))
4790    }
4791    pub(super) fn display_text_for<'a>(
4792        &self,
4793        text: &'a str,
4794        state: &LayoutState,
4795    ) -> std::borrow::Cow<'a, str> {
4796        let text = if self.effective_text_all_caps(state) {
4797            std::borrow::Cow::Owned(text.to_uppercase())
4798        } else {
4799            std::borrow::Cow::Borrowed(text)
4800        };
4801        if self.single_line && (text.contains('\n') || text.contains('\r')) {
4802            std::borrow::Cow::Owned(text.replace(['\n', '\r'], " "))
4803        } else {
4804            text
4805        }
4806    }
4807    pub(super) fn scaled_text_size(&self, state: &LayoutState) -> f32 {
4808        state.sp(self.text_size)
4809    }
4810    pub(super) fn effective_text_font(&self, state: &LayoutState) -> (f32, u16, bool, FontFamily) {
4811        let (italic, family) = self.text_style_ext();
4812        if matches!(self.kind, Kind::Button)
4813            && (state.theme_style != AndroidTheme::Bhoo
4814                || self.button_variant().is_some()
4815                || self.chip_style().is_some()
4816                || self.extended_fab_extended().is_some())
4817        {
4818            let size = if (self.text_size - 16.0).abs() < 0.001 {
4819                14.0
4820            } else {
4821                self.text_size
4822            };
4823            let weight = if self.text_bold { 700 } else { 500 };
4824            (state.sp(size), weight, italic, family)
4825        } else {
4826            (
4827                state.sp(self.text_size),
4828                if self.text_bold { 700 } else { 400 },
4829                italic,
4830                family,
4831            )
4832        }
4833    }
4834    pub(super) fn uses_default_button_chrome(&self, state: &LayoutState) -> bool {
4835        matches!(self.kind, Kind::Button)
4836            && state.theme_style != AndroidTheme::Bhoo
4837            && self.chip_style().is_none()
4838            && self.extended_fab_extended().is_none()
4839            && self.button_variant().is_none()
4840            && self.background_stroke.is_none()
4841            && !self.has_explicit_custom_background()
4842    }
4843    pub(super) fn active_button_variant(&self) -> Option<XmlButtonVariant> {
4844        if self.chip_style().is_some()
4845            || self.extended_fab_extended().is_some()
4846            || self.has_explicit_custom_background()
4847        {
4848            return None;
4849        }
4850        self.button_variant()
4851    }
4852    pub(super) fn default_button_visual_bounds(&self, b: Rect, state: &LayoutState) -> Rect {
4853        let inset_4 = state.dp(4.0);
4854        if self.active_button_variant().is_some() {
4855            let inset_y = inset_4.min(b.height * 0.25);
4856            return Rect {
4857                x: b.x,
4858                y: b.y + inset_y,
4859                width: b.width,
4860                height: (b.height - inset_y * 2.0).max(0.0),
4861            };
4862        }
4863        match state.theme_style {
4864            AndroidTheme::MaterialLight | AndroidTheme::MaterialDark => {
4865                // AOSP dimens_material.xml: button_inset_horizontal_material=4dp, button_inset_vertical_material=6dp.
4866                let inset_x = inset_4.min(b.width * 0.25);
4867                let inset_y = state.dp(6.0).min(b.height * 0.25);
4868                Rect {
4869                    x: b.x + inset_x,
4870                    y: b.y + inset_y,
4871                    width: (b.width - inset_x * 2.0).max(0.0),
4872                    height: (b.height - inset_y * 2.0).max(0.0),
4873                }
4874            }
4875            AndroidTheme::Material3Light | AndroidTheme::Material3Dark => {
4876                let inset_y = inset_4.min(b.height * 0.25);
4877                Rect {
4878                    x: b.x,
4879                    y: b.y + inset_y,
4880                    width: b.width,
4881                    height: (b.height - inset_y * 2.0).max(0.0),
4882                }
4883            }
4884            AndroidTheme::Bhoo => b,
4885        }
4886    }
4887    pub(super) fn default_theme_padding(&self, state: &LayoutState) -> [f32; 4] {
4888        if self.alert_dialog_icon().is_some() {
4889            return [24.0; 4];
4890        }
4891        if self.is_floating_toolbar() {
4892            return [8.0; 4];
4893        }
4894        if self.is_snackbar() {
4895            let rtl = match self.layout_direction {
4896                1 => false,
4897                2 => true,
4898                _ => state.rtl,
4899            };
4900            return if rtl {
4901                [8.0, 6.0, 16.0, 6.0]
4902            } else {
4903                [16.0, 6.0, 8.0, 6.0]
4904            };
4905        }
4906        if self.chip_style().is_some() {
4907            return [0.0; 4];
4908        }
4909        if state.snackbar_active && matches!(self.kind, Kind::Button) {
4910            return [12.0, 8.0, 12.0, 8.0];
4911        }
4912        if let Some(spec) = self.extended_fab_spec() {
4913            let extended = if !self.id.is_empty() {
4914                state
4915                    .fab_extended
4916                    .get(self.id)
4917                    .copied()
4918                    .unwrap_or(spec.static_extended)
4919            } else {
4920                spec.static_extended
4921            };
4922            if !extended {
4923                return [0.0; 4];
4924            }
4925            let rtl = match self.layout_direction {
4926                1 => false,
4927                2 => true,
4928                _ => state.rtl,
4929            };
4930            return if rtl {
4931                [20.0, 0.0, 16.0, 0.0]
4932            } else {
4933                [16.0, 0.0, 20.0, 0.0]
4934            };
4935        }
4936        if let Some(variant) = self.active_button_variant() {
4937            return match variant {
4938                XmlButtonVariant::Text => [12.0, 10.0, 12.0, 10.0],
4939                _ => [24.0, 10.0, 24.0, 10.0],
4940            };
4941        }
4942        if !self.uses_default_button_chrome(state) {
4943            return [0.0; 4];
4944        }
4945        match state.theme_style {
4946            // AOSP btn_default_material: 4dp H / 6dp V inset + 8dp H / 4dp V padding.
4947            AndroidTheme::MaterialLight | AndroidTheme::MaterialDark => [12.0, 10.0, 12.0, 10.0],
4948            // Material 3 filled button: 24dp horizontal padding, 4dp inset + 6dp vertical padding.
4949            AndroidTheme::Material3Light | AndroidTheme::Material3Dark => [24.0, 10.0, 24.0, 10.0],
4950            AndroidTheme::Bhoo => [0.0; 4],
4951        }
4952    }
4953    pub(super) fn default_button_min_width(&self, state: &LayoutState) -> f32 {
4954        if self.chip_style().is_some() {
4955            return state.dp(48.0);
4956        }
4957        if state.snackbar_active {
4958            return state.dp(48.0);
4959        }
4960        if let Some(spec) = self.extended_fab_spec() {
4961            let extended = if !self.id.is_empty() {
4962                state
4963                    .fab_extended
4964                    .get(self.id)
4965                    .copied()
4966                    .unwrap_or(spec.static_extended)
4967            } else {
4968                spec.static_extended
4969            };
4970            return state.dp(if extended {
4971                80.0_f32.max(spec.collapsed_size_dp)
4972            } else {
4973                spec.collapsed_size_dp
4974            });
4975        }
4976        if let Some(variant) = self.active_button_variant() {
4977            return state.dp(match variant {
4978                XmlButtonVariant::Text => 48.0,
4979                _ => 64.0,
4980            });
4981        }
4982        let raw = if !self.uses_default_button_chrome(state) {
4983            48.0
4984        } else {
4985            match state.theme_style {
4986                AndroidTheme::MaterialLight | AndroidTheme::MaterialDark => 88.0,
4987                AndroidTheme::Material3Light | AndroidTheme::Material3Dark => 64.0,
4988                AndroidTheme::Bhoo => 48.0,
4989            }
4990        };
4991        state.dp(raw)
4992    }
4993    pub(super) fn switch_layout(
4994        &self,
4995        state: &LayoutState,
4996    ) -> crate::systems::material::SwitchLayout {
4997        let value = |kind, default| {
4998            self.relative_rules
4999                .iter()
5000                .find(|r| r.kind == kind)
5001                .and_then(|r| r.anchor.parse::<f32>().ok())
5002                .filter(|v| v.is_finite() && *v >= 0.0)
5003                .unwrap_or(default)
5004        };
5005        crate::systems::material::SwitchLayout {
5006            min_width: state.dp(value(193, 52.0)),
5007            padding: state.dp(value(194, 4.0)),
5008            thumb_text_padding: state.dp(value(195, 4.0)),
5009        }
5010    }
5011    #[allow(clippy::too_many_arguments)]
5012    #[allow(clippy::too_many_arguments)]
5013    pub(super) fn paint_edit_text(
5014        &self,
5015        f: &mut Frame<'_>,
5016        state: &LayoutState,
5017        text_rect: Rect,
5018        content: &str,
5019        color: Color,
5020        style: TextStyle,
5021        pad_x: f32,
5022        v_pad_top: f32,
5023        v_pad_bottom: f32,
5024        multiline: bool,
5025        links: Option<(TextLinksSpec, Color, bool, u64, &mut Option<String>, bool)>,
5026    ) {
5027        let inner_w = (text_rect.width - pad_x * 2.0).max(0.0);
5028        if inner_w <= 0.0 || text_rect.height <= 0.0 || content.is_empty() {
5029            return;
5030        }
5031        let mut links = links;
5032        let mut link_counter = 0usize;
5033        let underline_h = state.dp(1.0);
5034        let line_h = self.resolved_line_height(style.size, state);
5035        let line_advance =
5036            (line_h * self.line_spacing_multiplier + state.dp(self.line_spacing_extra)).max(1.0);
5037        let clip_pad_x = (pad_x - state.dp(2.0)).max(0.0);
5038        if multiline {
5039            let top_pad = if self.padding_explicit[1] {
5040                0.0
5041            } else {
5042                v_pad_top.min(text_rect.height * 0.25)
5043            };
5044            let bottom_pad = if self.padding_explicit[3] {
5045                0.0
5046            } else {
5047                v_pad_bottom.min(text_rect.height * 0.25)
5048            };
5049            let area = Rect {
5050                x: text_rect.x + pad_x,
5051                y: text_rect.y + top_pad,
5052                width: inner_w,
5053                height: (text_rect.height - top_pad - bottom_pad).max(0.0),
5054            };
5055            if area.height <= 0.0 {
5056                return;
5057            }
5058            let clip = Rect {
5059                x: text_rect.x + clip_pad_x,
5060                y: area.y,
5061                width: (text_rect.width - clip_pad_x * 2.0).max(0.0),
5062                height: area.height,
5063            }
5064            .intersect(f.clip);
5065            if clip.width <= 0.0 || clip.height <= 0.0 {
5066                return;
5067            }
5068            let metrics = f.ui.text_metrics;
5069            let line_style = TextStyle {
5070                padding: 0.0,
5071                ..style
5072            };
5073            let total = wrapped_text_lines(content, area.width, line_style, metrics, |_| {});
5074            let height_limit = ((area.height - line_h).max(0.0) / line_advance).ceil() as usize + 1;
5075            let limit = if self.max_lines == 0 {
5076                height_limit
5077            } else {
5078                height_limit.min(self.max_lines)
5079            };
5080            let shown = total.min(limit);
5081            let used_height = if shown == 0 {
5082                0.0
5083            } else {
5084                (line_h + (shown - 1) as f32 * line_advance).min(area.height)
5085            };
5086            let extra = (area.height - used_height).max(0.0);
5087            let top_align = self.content_gravity[1] == 0
5088                || self.min_lines > 1
5089                || text_rect.height >= line_h * 2.2;
5090            let start_y = if self.content_gravity[1] == 2 {
5091                area.y + extra
5092            } else if top_align {
5093                area.y
5094            } else {
5095                area.y + extra * 0.5
5096            };
5097            f.commands.push(DrawCommand::PushClip(clip));
5098            let mut line_index = 0usize;
5099            wrapped_text_lines(content, area.width, line_style, metrics, |line| {
5100                if line_index < limit {
5101                    let line_bounds = Rect {
5102                        x: area.x,
5103                        y: start_y + line_index as f32 * line_advance,
5104                        width: area.width,
5105                        height: line_h,
5106                    };
5107                    if !line.text.is_empty() {
5108                        if let Some((lspec, lcol, lenabled, lid, clicked_out, field_clicked)) =
5109                            links.as_mut()
5110                        {
5111                            paint_text_line_with_links(
5112                                f,
5113                                line_bounds,
5114                                &line.text,
5115                                color,
5116                                *lcol,
5117                                line_style,
5118                                metrics,
5119                                lspec.mask,
5120                                lspec.clickable,
5121                                *lenabled,
5122                                *lid,
5123                                &mut link_counter,
5124                                clicked_out,
5125                                underline_h,
5126                                *field_clicked,
5127                            );
5128                        } else {
5129                            f.styled_text(line_bounds, &line.text, color, line_style);
5130                        }
5131                    }
5132                }
5133                line_index += 1;
5134            });
5135            f.commands.push(DrawCommand::PopClip);
5136        } else {
5137            let clip = Rect {
5138                x: text_rect.x + clip_pad_x,
5139                y: text_rect.y,
5140                width: (text_rect.width - clip_pad_x * 2.0).max(0.0),
5141                height: text_rect.height,
5142            }
5143            .intersect(f.clip);
5144            if clip.width <= 0.0 || clip.height <= 0.0 {
5145                return;
5146            }
5147            let single = if content.contains(['\n', '\r']) {
5148                std::borrow::Cow::Owned(content.replace(['\n', '\r'], " "))
5149            } else {
5150                std::borrow::Cow::Borrowed(content)
5151            };
5152            let metrics = f.ui.text_metrics;
5153            f.commands.push(DrawCommand::PushClip(clip));
5154            if let Some((lspec, lcol, lenabled, lid, clicked_out, field_clicked)) = links.as_mut() {
5155                paint_text_line_with_links(
5156                    f,
5157                    text_rect,
5158                    &single,
5159                    color,
5160                    *lcol,
5161                    style,
5162                    metrics,
5163                    lspec.mask,
5164                    lspec.clickable,
5165                    *lenabled,
5166                    *lid,
5167                    &mut link_counter,
5168                    clicked_out,
5169                    underline_h,
5170                    *field_clicked,
5171                );
5172            } else {
5173                f.styled_text(text_rect, &single, color, style);
5174            }
5175            f.commands.push(DrawCommand::PopClip);
5176        }
5177    }
5178    pub(super) fn layout_intrinsic(
5179        &self,
5180        horizontal: bool,
5181        state: &LayoutState,
5182        available_width: f32,
5183        metrics: TextMetrics,
5184        id: u64,
5185    ) -> f32 {
5186        self.layout_intrinsic_for_width(horizontal, state, available_width, false, metrics, id)
5187    }
5188    pub(super) fn layout_intrinsic_for_width(
5189        &self,
5190        horizontal: bool,
5191        state: &LayoutState,
5192        available_width: f32,
5193        exact_width: bool,
5194        metrics: TextMetrics,
5195        id: u64,
5196    ) -> f32 {
5197        let rtl = match self.layout_direction {
5198            1 => false,
5199            2 => true,
5200            _ => state.rtl,
5201        };
5202        if rtl != state.rtl {
5203            let mut scoped = state.clone();
5204            scoped.rtl = rtl;
5205            let result = self.layout_intrinsic_for_width(
5206                horizontal,
5207                &scoped,
5208                available_width,
5209                exact_width,
5210                metrics,
5211                id,
5212            );
5213            // Measurement records MotionLayout constraint changes through
5214            // interior state. Preserve those updates across the RTL scope.
5215            *state.motion_wrap_available.borrow_mut() = scoped.motion_wrap_available.borrow().clone();
5216            return result;
5217        }
5218        if !horizontal && let Some(ch) = self.collapsing_toolbar_height(state, id) {
5219            return ch.max(state.dp(self.min_height));
5220        }
5221        let d = state.effective_density();
5222        let min_w = state.dp(self.min_width);
5223        let min_h = state.dp(self.min_height);
5224        let bg_min_w = state.dp(self.background_min_size[0]);
5225        let bg_min_h = state.dp(self.background_min_size[1]);
5226        if horizontal
5227            && matches!(self.width, Size::Wrap)
5228            && matches!(self.kind, Kind::Linear | Kind::RadioGroup | Kind::TableRow)
5229        {
5230            if self.nav_bar_spec().is_some() {
5231                return self.intrinsic(horizontal, state, id);
5232            }
5233            let padding = self.resolved_padding(state);
5234            let inner = (available_width - padding[0] - padding[2]).max(0.0);
5235            if let Some(cg) = self.chip_group_wrap_spec() {
5236                let (_, max_row_w, _) = self.chip_group_wrap_rects(
5237                    Rect {
5238                        x: 0.0,
5239                        y: 0.0,
5240                        width: inner,
5241                        height: 100_000.0,
5242                    },
5243                    cg,
5244                    state,
5245                    metrics,
5246                    id,
5247                );
5248                return (max_row_w + padding[0] + padding[2])
5249                    .max(min_w)
5250                    .max(bg_min_w);
5251            }
5252            let flow = self.horizontal || matches!(self.kind, Kind::TableRow);
5253            let visible_count = self
5254                .children
5255                .iter()
5256                .filter(|n| n.effective_visibility(state) != Visibility::Gone)
5257                .count();
5258            let extra_gap = if flow {
5259                visible_count.saturating_sub(1) as f32 * self.linear_extra_gap(state)
5260            } else {
5261                0.0
5262            };
5263            let sizes = self
5264                .children
5265                .iter()
5266                .enumerate()
5267                .filter(|(_, n)| n.effective_visibility(state) != Visibility::Gone)
5268                .map(|(i, n)| {
5269                    let m = n.resolved_margin(state);
5270                    let available = (inner - m[0] - m[2]).max(0.0);
5271                    n.layout_intrinsic(true, state, available, metrics, child_view_id(id, i, n))
5272                        .min(available)
5273                        + m[0]
5274                        + m[2]
5275                });
5276            let content = if flow {
5277                sizes.sum::<f32>()
5278                    + extra_gap
5279                    + self.divider_count(state) as f32 * state.dp(self.divider_thickness)
5280            } else {
5281                sizes.fold(0.0_f32, f32::max)
5282            };
5283            (content + padding[0] + padding[2]).max(min_w).max(bg_min_w)
5284        } else if horizontal && matches!(self.width, Size::Wrap) && matches!(self.kind, Kind::Table)
5285        {
5286            let padding = self.resolved_padding(state);
5287            let inner = (available_width - padding[0] - padding[2]).max(0.0);
5288            let columns = self.table_columns(state, metrics, id).iter().sum::<f32>();
5289            let other = self
5290                .children
5291                .iter()
5292                .enumerate()
5293                .filter(|(_, n)| {
5294                    !matches!(n.kind, Kind::TableRow)
5295                        && n.effective_visibility(state) != Visibility::Gone
5296                })
5297                .map(|(i, n)| {
5298                    let m = n.resolved_margin(state);
5299                    let available = (inner - m[0] - m[2]).max(0.0);
5300                    n.layout_intrinsic(true, state, available, metrics, child_view_id(id, i, n))
5301                        .min(available)
5302                        + m[0]
5303                        + m[2]
5304                })
5305                .fold(0.0_f32, f32::max);
5306            (columns.max(other) + padding[0] + padding[2])
5307                .max(min_w)
5308                .max(bg_min_w)
5309        } else if horizontal && matches!(self.width, Size::Wrap) && matches!(self.kind, Kind::Grid)
5310        {
5311            let padding = self.resolved_padding(state);
5312            let inner = (available_width - padding[0] - padding[2]).max(0.0);
5313            let (widths, _, _, _, _) = self.grid_tracks(state, metrics, id, inner, false, None);
5314            (widths.iter().sum::<f32>() + padding[0] + padding[2])
5315                .max(min_w)
5316                .max(bg_min_w)
5317        } else if horizontal
5318            && matches!(self.width, Size::Wrap)
5319            && matches!(
5320                self.kind,
5321                Kind::Relative | Kind::DialerFilter | Kind::ConstraintLayout
5322            )
5323        {
5324            let padding = self.resolved_padding(state);
5325            let inner = Rect {
5326                x: 0.0,
5327                y: 0.0,
5328                width: (available_width - padding[0] - padding[2]).max(0.0),
5329                height: 1_000_000.0,
5330            };
5331            let is_cl = matches!(self.kind, Kind::ConstraintLayout);
5332            let ph_claimed = if is_cl {
5333                Some(resolve_constraint_placeholders(self.children, state).1)
5334            } else {
5335                None
5336            };
5337            let visibilities = if is_cl {
5338                Some(constraint_group_visibilities(self.children, state))
5339            } else {
5340                None
5341            };
5342            let positions = if is_cl {
5343                constraint_layout_positions(self, id, inner, state, metrics, true, true)
5344            } else {
5345                relative_layout::layout(self, id, inner, state, metrics, true, true)
5346            };
5347            let content = positions
5348                .iter()
5349                .enumerate()
5350                .filter(|(i, _)| {
5351                    let vis = visibilities
5352                        .as_ref()
5353                        .map_or_else(|| self.children[*i].effective_visibility(state), |v| v[*i]);
5354                    vis != Visibility::Gone
5355                        && !(is_cl && is_constraint_helper(&self.children[*i]))
5356                        && !ph_claimed.as_ref().is_some_and(|m| m[*i].is_some())
5357                })
5358                .map(|(i, r)| {
5359                    let m = self.children[i].resolved_margin(state);
5360                    if state.rtl {
5361                        (inner.x + inner.width) - (r.x - m[0])
5362                    } else {
5363                        r.x + r.width + m[2]
5364                    }
5365                })
5366                .fold(0.0_f32, f32::max);
5367            let content = if is_cl {
5368                motion_layout::motion_wrap_content_extent(self, id, inner, state, metrics, true, true, true).unwrap_or(content)
5369            } else { content };
5370            (content + padding[0] + padding[2]).max(min_w).max(bg_min_w)
5371        } else if horizontal
5372            && matches!(self.width, Size::Wrap)
5373            && matches!(
5374                self.kind,
5375                Kind::Frame
5376                    | Kind::MediaController
5377                    | Kind::MaterialCard
5378                    | Kind::ViewAnimator
5379                    | Kind::ViewSwitcher
5380                    | Kind::TextSwitcher
5381                    | Kind::ImageSwitcher
5382                    | Kind::ViewFlipper
5383            )
5384        {
5385            let padding = self.resolved_padding(state);
5386            let inner = (available_width - padding[0] - padding[2]).max(0.0);
5387            let content = self
5388                .children
5389                .iter()
5390                .enumerate()
5391                .filter(|(_, n)| {
5392                    (self.measure_all_children || n.effective_visibility(state) != Visibility::Gone)
5393                        && !self.drawer_panel_is_closed(n, state, id)
5394                })
5395                .map(|(i, n)| {
5396                    let m = n.resolved_margin(state);
5397                    let available = (inner - m[0] - m[2]).max(0.0);
5398                    n.layout_intrinsic(true, state, available, metrics, child_view_id(id, i, n))
5399                        .min(available)
5400                        + m[0]
5401                        + m[2]
5402                })
5403                .fold(0.0_f32, f32::max);
5404            (content + padding[0] + padding[2])
5405                .max(min_w)
5406                .max(bg_min_w)
5407                .max(state.dp(self.foreground_size[0]))
5408        } else if horizontal
5409            && matches!(self.width, Size::Wrap)
5410            && matches!(self.kind, Kind::Switch)
5411        {
5412            let layout = self.switch_layout(state);
5413            let texts = if self.relative_rules.iter().any(|r| r.kind == 161) {
5414                Some((self.text_on, self.text_off))
5415            } else {
5416                None
5417            };
5418            let (_, track) = crate::systems::material::switch_widths(texts, metrics, layout);
5419            let key = if self.id.is_empty() {
5420                format!("#{id}")
5421            } else {
5422                self.id.to_owned()
5423            };
5424            let label = self.display_text_for(
5425                state.text.get(&key).map_or(self.text, String::as_str),
5426                state,
5427            );
5428            let text_size = self.scaled_text_size(state);
5429            let (italic, family) = self.text_style_ext();
5430            let style = TextStyle {
5431                size: text_size,
5432                weight: if self.text_bold { 700 } else { 400 },
5433                letter_spacing: self.letter_spacing_em * text_size,
5434                italic,
5435                family,
5436                ..TextStyle::default()
5437            };
5438            let padding = self.resolved_padding(state);
5439            (track
5440                + (if label.is_empty() {
5441                    0.0
5442                } else {
5443                    layout.padding + metrics.width(&label, style)
5444                })
5445                + padding[0]
5446                + padding[2])
5447                .max(min_w)
5448                .max(bg_min_w)
5449        } else if horizontal
5450            && matches!(self.width, Size::Wrap)
5451            && matches!(self.kind, Kind::Button)
5452        {
5453            if let Some((spec, m, _)) = self.extended_fab_progress(state, id) {
5454                let collapsed_w = state.dp(spec.collapsed_size_dp).max(min_w).max(bg_min_w);
5455                let extended_w = if spec.strategy == ExtendedFabStrategy::MatchParent
5456                    && available_width.is_finite()
5457                    && available_width > 0.0
5458                {
5459                    available_width.max(collapsed_w)
5460                } else {
5461                    self.extended_fab_intrinsic_extended_width(state, metrics, id, spec)
5462                        .max(collapsed_w)
5463                };
5464                return collapsed_w + (extended_w - collapsed_w) * m.progress;
5465            }
5466            let key = if self.id.is_empty() {
5467                format!("#{id}")
5468            } else {
5469                self.id.to_owned()
5470            };
5471            let label = self.display_text_for(
5472                state.text.get(&key).map_or(self.text, String::as_str),
5473                state,
5474            );
5475            let (text_size, weight, italic, family) = self.effective_text_font(state);
5476            let style = TextStyle {
5477                size: text_size,
5478                weight,
5479                letter_spacing: self.letter_spacing_em * text_size,
5480                italic,
5481                family,
5482                ..TextStyle::default()
5483            };
5484            let width = label
5485                .split([
5486                    '\n', '\r', '\u{000b}', '\u{000c}', '\u{0085}', '\u{2028}', '\u{2029}',
5487                ])
5488                .map(|line| metrics.width(line, style))
5489                .fold(0.0_f32, f32::max);
5490            let padding = self.resolved_padding(state);
5491            if let Some(chip) = self.chip_style() {
5492                let selected = state.checked.get(&key).copied().unwrap_or(self.checked)
5493                    || state.view_selected.get(&key).copied().unwrap_or(false);
5494                let lead = if selected && chip.kind == XmlChipKind::Filter {
5495                    state.dp(34.0)
5496                } else {
5497                    state.dp(16.0)
5498                };
5499                let trail = if chip.close_visible {
5500                    state.dp(34.0)
5501                } else {
5502                    state.dp(16.0)
5503                };
5504                (width + lead + trail + padding[0] + padding[2])
5505                    .max(self.default_button_min_width(state))
5506                    .max(min_w)
5507                    .max(bg_min_w)
5508            } else {
5509                let shapes = self.compound_sizes(state, state.rtl);
5510                let extent = self.compound_extents(state, state.rtl);
5511                ((width + extent[0] + extent[2])
5512                    .max(shapes[1].map_or(0.0, |s| s.0))
5513                    .max(shapes[3].map_or(0.0, |s| s.0))
5514                    + padding[0]
5515                    + padding[2])
5516                    .max(self.default_button_min_width(state))
5517                    .max(min_w)
5518                    .max(bg_min_w)
5519            }
5520        } else if horizontal
5521            && matches!(self.width, Size::Wrap)
5522            && matches!(self.kind, Kind::ToggleButton)
5523        {
5524            let key = if self.id.is_empty() {
5525                format!("#{id}")
5526            } else {
5527                self.id.to_owned()
5528            };
5529            let checked = state.checked.get(&key).copied().unwrap_or(self.checked);
5530            let label =
5531                self.display_text_for(if checked { self.text_on } else { self.text_off }, state);
5532            let text_size = self.scaled_text_size(state);
5533            let (italic, family) = self.text_style_ext();
5534            let style = TextStyle {
5535                size: text_size,
5536                weight: if self.text_bold { 700 } else { 400 },
5537                letter_spacing: self.letter_spacing_em * text_size,
5538                italic,
5539                family,
5540                ..TextStyle::default()
5541            };
5542            let padding = self.resolved_padding(state);
5543            (metrics.width(&label, style) + padding[0] + padding[2])
5544                .max(state.dp(48.0))
5545                .max(min_w)
5546                .max(bg_min_w)
5547        } else if horizontal
5548            && matches!(self.width, Size::Wrap)
5549            && matches!(self.kind, Kind::CheckBox | Kind::RadioButton)
5550        {
5551            let key = if self.id.is_empty() {
5552                format!("#{id}")
5553            } else {
5554                self.id.to_owned()
5555            };
5556            let label = self.display_text_for(
5557                state.text.get(&key).map_or(self.text, String::as_str),
5558                state,
5559            );
5560            let text_size = self.scaled_text_size(state);
5561            let (italic, family) = self.text_style_ext();
5562            let style = TextStyle {
5563                size: text_size,
5564                weight: if self.text_bold { 700 } else { 400 },
5565                letter_spacing: self.letter_spacing_em * text_size,
5566                italic,
5567                family,
5568                ..TextStyle::default()
5569            };
5570            let padding = self.resolved_padding(state);
5571            (state.dp(48.0) + metrics.width(&label, style) + padding[0] + padding[2])
5572                .max(min_w)
5573                .max(bg_min_w)
5574        } else if horizontal
5575            && matches!(self.width, Size::Wrap)
5576            && matches!(
5577                self.kind,
5578                Kind::Text | Kind::CheckedText | Kind::Chronometer | Kind::TextClock
5579            )
5580        {
5581            let key = if self.id.is_empty() {
5582                format!("#{id}")
5583            } else {
5584                self.id.to_owned()
5585            };
5586            let text = self.display_text_for(
5587                state.text.get(&key).map_or(self.text, String::as_str),
5588                state,
5589            );
5590            let text_size = self.scaled_text_size(state);
5591            let (italic, family) = self.text_style_ext();
5592            let style = TextStyle {
5593                size: text_size,
5594                weight: if self.text_bold { 700 } else { 400 },
5595                letter_spacing: self.letter_spacing_em * text_size,
5596                italic,
5597                family,
5598                ..TextStyle::default()
5599            };
5600            let width = text
5601                .split([
5602                    '\n', '\r', '\u{000b}', '\u{000c}', '\u{0085}', '\u{2028}', '\u{2029}',
5603                ])
5604                .map(|line| metrics.width(line, style))
5605                .fold(0.0_f32, f32::max);
5606            let shapes = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
5607                self.compound_sizes(state, state.rtl)
5608            } else {
5609                [None; 4]
5610            };
5611            let ext = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
5612                self.compound_extents(state, state.rtl)
5613            } else {
5614                [0.0; 4]
5615            };
5616            let mark = if matches!(self.kind, Kind::CheckedText) {
5617                self.check_mark_width(state)
5618            } else {
5619                0.0
5620            };
5621            let padding = self.resolved_padding(state);
5622            ((width + mark + ext[0] + ext[2])
5623                .max(shapes[1].map_or(0.0, |shape| shape.0))
5624                .max(shapes[3].map_or(0.0, |shape| shape.0))
5625                + padding[0]
5626                + padding[2])
5627                .max(min_w)
5628                .max(bg_min_w)
5629        } else if matches!(self.kind, Kind::VideoView)
5630            && (horizontal || !matches!(self.height, Size::Match))
5631        {
5632            let key = if self.id.is_empty() {
5633                format!("#{id}")
5634            } else {
5635                self.id.to_owned()
5636            };
5637            let size = state
5638                .video_dimensions
5639                .get(&key)
5640                .copied()
5641                .or_else(|| {
5642                    state
5643                        .video_frames
5644                        .get(&key)
5645                        .map(|frame| (frame.width(), frame.height()))
5646                })
5647                .unwrap_or((0, 0));
5648            let width = if exact_width {
5649                VideoMeasureSpec::Exactly(available_width.max(0.0) as u32)
5650            } else {
5651                match self.width {
5652                    Size::Dp(value) => VideoMeasureSpec::Exactly(state.dp(value).max(0.0) as u32),
5653                    Size::Match => VideoMeasureSpec::Exactly(available_width.max(0.0) as u32),
5654                    Size::Wrap => VideoMeasureSpec::AtMost(available_width.max(0.0) as u32),
5655                }
5656            };
5657            let height = match self.height {
5658                Size::Dp(value) => VideoMeasureSpec::Exactly(state.dp(value).max(0.0) as u32),
5659                _ => VideoMeasureSpec::Unspecified,
5660            };
5661            let measured = measure_video_view(size, width, height);
5662            if horizontal {
5663                measured.0 as f32
5664            } else {
5665                measured.1 as f32
5666            }
5667        } else if !horizontal
5668            && matches!(self.kind, Kind::GridView)
5669            && matches!(self.height, Size::Wrap)
5670        {
5671            if let Some(ext) = self.recycler_layout_ext() {
5672                let padding = self.resolved_view_padding(state);
5673                let v_gap = self
5674                    .relative_rules
5675                    .iter()
5676                    .find(|r| r.kind == 94)
5677                    .and_then(|r| r.anchor.parse::<f32>().ok())
5678                    .unwrap_or(0.0)
5679                    .max(0.0)
5680                    * d;
5681                if ext.horizontal {
5682                    let span = ext.span_count.max(1);
5683                    let total =
5684                        span as f32 * state.dp(48.0) + span.saturating_sub(1) as f32 * v_gap;
5685                    return (total + padding[1] + padding[3]).max(min_h).max(bg_min_h);
5686                }
5687            }
5688            let key = if self.id.is_empty() {
5689                format!("#{id}")
5690            } else {
5691                self.id.to_owned()
5692            };
5693            let padding = self.resolved_view_padding(state);
5694            let width = (available_width - padding[0] - padding[2]).max(0.0);
5695            let (columns, column_width, _, _) = grid_view_columns(self, width, d);
5696            let spacing = state.dp(self
5697                .relative_rules
5698                .iter()
5699                .find(|r| r.kind == 94)
5700                .and_then(|r| r.anchor.parse::<f32>().ok())
5701                .unwrap_or(0.0)
5702                .max(0.0));
5703            let entries = state.list_items.get(&key).map(Vec::as_slice).unwrap_or(&[]);
5704            let template = state.list_templates.get(&key).copied();
5705            let mut row_state = if template.is_some() || state.list_item_bindings.contains_key(&key)
5706            {
5707                Some(spinner_template_state(state, rtl))
5708            } else {
5709                None
5710            };
5711            let mut total = 0.0;
5712            for (row, items) in entries.chunks(columns).enumerate() {
5713                let mut height = 0.0_f32;
5714                for (column, label) in items.iter().enumerate() {
5715                    let (_, h) = grid_item_size(
5716                        template,
5717                        row_state.as_mut(),
5718                        label,
5719                        column_width,
5720                        metrics,
5721                        anonymous_child_id(id, 1024 + row * columns + column),
5722                        state
5723                            .list_item_bindings
5724                            .get(&key)
5725                            .and_then(|items| items.get(&(row * columns + column))),
5726                    );
5727                    height = height.max(h);
5728                }
5729                if row > 0 {
5730                    total += spacing;
5731                }
5732                total += height;
5733            }
5734            (total + padding[1] + padding[3]).max(min_h).max(bg_min_h)
5735        } else if !horizontal
5736            && matches!(self.kind, Kind::ListView)
5737            && matches!(self.height, Size::Wrap)
5738        {
5739            if let Some(ext) = self.recycler_layout_ext()
5740                && ext.horizontal
5741            {
5742                let padding = self.resolved_view_padding(state);
5743                let v_gap = self
5744                    .relative_rules
5745                    .iter()
5746                    .find(|r| r.kind == 94)
5747                    .and_then(|r| r.anchor.parse::<f32>().ok())
5748                    .unwrap_or(0.0)
5749                    .max(0.0)
5750                    * d;
5751                let span = ext.span_count.max(1);
5752                let total = span as f32 * state.dp(48.0) + span.saturating_sub(1) as f32 * v_gap;
5753                return (total + padding[1] + padding[3]).max(min_h).max(bg_min_h);
5754            }
5755            let key = if self.id.is_empty() {
5756                format!("#{id}")
5757            } else {
5758                self.id.to_owned()
5759            };
5760            let template = state.list_templates.get(&key).copied();
5761            let mut row_state = spinner_template_state(state, rtl);
5762            let entries: Vec<&str> = match state.list_items.get(&key) {
5763                Some(items) => items.iter().map(String::as_str).collect(),
5764                None => self
5765                    .relative_rules
5766                    .iter()
5767                    .filter(|rule| rule.kind == 82)
5768                    .map(|rule| rule.anchor)
5769                    .collect(),
5770            };
5771            let padding = self.resolved_view_padding(state);
5772            let width = (available_width - padding[0] - padding[2]).max(0.0);
5773            let divider = state.dp(self.divider_thickness.max(0.0));
5774            let (headers, footers) = state
5775                .list_fixed_views
5776                .get(&key)
5777                .cloned()
5778                .unwrap_or_default();
5779            let header_dividers = !self
5780                .relative_rules
5781                .iter()
5782                .any(|r| r.kind == 89 && r.anchor == "false");
5783            let footer_dividers = !self
5784                .relative_rules
5785                .iter()
5786                .any(|r| r.kind == 90 && r.anchor == "false");
5787            let mut total = 0.0;
5788            for (i, fixed) in headers.iter().enumerate() {
5789                total += list_fixed_height(
5790                    fixed.view,
5791                    state,
5792                    width,
5793                    metrics,
5794                    anonymous_child_id(id, 2048 + i),
5795                );
5796                if header_dividers
5797                    && (i + 1 < headers.len() || !entries.is_empty() || !footers.is_empty())
5798                {
5799                    total += divider;
5800                }
5801            }
5802            for (i, label) in entries.iter().enumerate() {
5803                let binding = state
5804                    .list_item_bindings
5805                    .get(&key)
5806                    .and_then(|items| items.get(&i));
5807                let height = if let Some(template) = adapter_item_template(template, binding) {
5808                    with_adapter_binding(
5809                        &mut row_state,
5810                        template.text_id,
5811                        label,
5812                        binding,
5813                        |row_state| match template.row.height {
5814                            Size::Match => state.dp(48.0),
5815                            _ => template.row.layout_intrinsic(
5816                                false,
5817                                row_state,
5818                                width,
5819                                metrics,
5820                                anonymous_child_id(id, 1024 + i),
5821                            ),
5822                        },
5823                    )
5824                } else {
5825                    (wrapped_text_lines(
5826                        label,
5827                        (width - 32.0).max(1.0),
5828                        TextStyle::default(),
5829                        metrics,
5830                        |_| {},
5831                    )
5832                    .max(1) as f32
5833                        * 24.0)
5834                        .max(48.0)
5835                };
5836                total += if height.is_finite() {
5837                    height.clamp(1.0, 4096.0)
5838                } else {
5839                    state.dp(48.0)
5840                };
5841                if i + 1 < entries.len() || (!footers.is_empty() && footer_dividers) {
5842                    total += divider;
5843                }
5844            }
5845            for (i, fixed) in footers.iter().enumerate() {
5846                total += list_fixed_height(
5847                    fixed.view,
5848                    state,
5849                    width,
5850                    metrics,
5851                    anonymous_child_id(id, 3072 + i),
5852                );
5853                if footer_dividers && i + 1 < footers.len() {
5854                    total += divider;
5855                }
5856            }
5857            (total + padding[1] + padding[3]).max(min_h).max(bg_min_h)
5858        } else if !horizontal
5859            && matches!(self.kind, Kind::Spinner)
5860            && matches!(self.height, Size::Wrap)
5861        {
5862            let key = if self.id.is_empty() {
5863                format!("#{id}")
5864            } else {
5865                self.id.to_owned()
5866            };
5867            let selected = state.spinner_selected.get(&key).copied().unwrap_or(0);
5868            let label = match state.spinner_items.get(&key) {
5869                Some(items) => items
5870                    .get(selected.min(items.len().saturating_sub(1)))
5871                    .map(String::as_str),
5872                None => self
5873                    .relative_rules
5874                    .iter()
5875                    .filter(|rule| rule.kind == 82)
5876                    .nth(selected)
5877                    .or_else(|| {
5878                        self.relative_rules
5879                            .iter()
5880                            .filter(|rule| rule.kind == 82)
5881                            .last()
5882                    })
5883                    .map(|rule| rule.anchor),
5884            };
5885            if let (Some(template), Some(label)) = (state.spinner_templates.get(&key), label) {
5886                let mut row_state = spinner_template_state(state, rtl);
5887                row_state
5888                    .text
5889                    .insert(template.text_id.to_owned(), label.to_owned());
5890                let height = match template.selected.height {
5891                    Size::Match => state.dp(48.0),
5892                    _ => template.selected.layout_intrinsic(
5893                        false,
5894                        &row_state,
5895                        (available_width - state.dp(40.0)).max(0.0),
5896                        metrics,
5897                        anonymous_child_id(id, 1023),
5898                    ),
5899                };
5900                let padding = self.resolved_view_padding(state);
5901                (height + padding[1] + padding[3]).max(min_h).max(bg_min_h)
5902            } else {
5903                self.intrinsic(horizontal, state, id)
5904            }
5905        } else if !horizontal
5906            && matches!(self.kind, Kind::Button)
5907            && matches!(self.height, Size::Wrap)
5908        {
5909            if let Some((spec, m, _)) = self.extended_fab_progress(state, id) {
5910                let collapsed_h = state.dp(spec.collapsed_size_dp).max(min_h).max(bg_min_h);
5911                if m.progress <= 0.001 {
5912                    return collapsed_h;
5913                }
5914                let ext_h = state.dp(56.0).max(min_h).max(bg_min_h);
5915                return collapsed_h + (ext_h - collapsed_h) * m.progress;
5916            }
5917            let shapes = self.compound_sizes(state, state.rtl);
5918            let extent = self.compound_extents(state, state.rtl);
5919            let padding = self.resolved_padding(state);
5920            let key = if self.id.is_empty() {
5921                format!("#{id}")
5922            } else {
5923                self.id.to_owned()
5924            };
5925            let label = self.display_text_for(
5926                state.text.get(&key).map_or(self.text, String::as_str),
5927                state,
5928            );
5929            let (base_text_size, weight, italic, family) = self.effective_text_font(state);
5930            let width = if exact_width {
5931                available_width
5932            } else {
5933                match self.width {
5934                    Size::Dp(value) => state.dp(value).min(available_width),
5935                    _ => available_width,
5936                }
5937            };
5938            let text_width = (width - padding[0] - padding[2] - extent[0] - extent[2]).max(1.0);
5939            let layout_ext = self.text_layout_ext();
5940            let base_style = TextStyle {
5941                size: base_text_size,
5942                weight,
5943                letter_spacing: self.letter_spacing_em * base_text_size,
5944                italic,
5945                family,
5946                ..TextStyle::default()
5947            };
5948            let text_size = if let Some(ext) = layout_ext
5949                && ext.has_auto_size()
5950            {
5951                self.resolve_auto_text_size(
5952                    &label,
5953                    text_width,
5954                    f32::INFINITY,
5955                    base_style,
5956                    ext,
5957                    state,
5958                    metrics,
5959                )
5960            } else {
5961                base_text_size
5962            };
5963            let style = TextStyle {
5964                size: text_size,
5965                weight,
5966                letter_spacing: self.letter_spacing_em * text_size,
5967                italic,
5968                family,
5969                ..TextStyle::default()
5970            };
5971            let single = self.single_line
5972                || (self.max_lines == 1 && (self.ellipsize_side != 0 || self.ellipsize_end));
5973            let lines = if single {
5974                1
5975            } else if let Some(ext) = layout_ext {
5976                wrap_text_lines_ext(&label, text_width + 0.01, style, metrics, ext)
5977                    .len()
5978                    .max(1)
5979            } else {
5980                wrapped_text_lines(&label, text_width + 0.01, style, metrics, |_| {}).max(1)
5981            };
5982            let lines = if self.max_lines == 0 {
5983                lines
5984            } else {
5985                lines.min(self.max_lines)
5986            }
5987            .max(self.min_lines.max(1));
5988            let line_height = self.resolved_line_height(text_size, state);
5989            let advance = (line_height * self.line_spacing_multiplier
5990                + state.dp(self.line_spacing_extra))
5991            .max(1.0);
5992            let content = (line_height + (lines - 1) as f32 * advance)
5993                .max(shapes[0].map_or(0.0, |s| s.1))
5994                .max(shapes[2].map_or(0.0, |s| s.1));
5995            let min_btn_h = if self.extended_fab_extended().is_some() {
5996                state.dp(56.0)
5997            } else {
5998                state.dp(48.0)
5999            };
6000            (content + extent[1] + extent[3] + padding[1] + padding[3])
6001                .max(min_btn_h)
6002                .max(min_h)
6003                .max(bg_min_h)
6004        } else if !horizontal
6005            && matches!(self.kind, Kind::Grid)
6006            && matches!(self.height, Size::Wrap)
6007        {
6008            let padding = self.resolved_padding(state);
6009            let width = if exact_width {
6010                available_width
6011            } else {
6012                match self.width {
6013                    Size::Dp(w) => state.dp(w).min(available_width),
6014                    _ => available_width,
6015                }
6016            };
6017            let (_, heights, _, _, _) = self.grid_tracks(
6018                state,
6019                metrics,
6020                id,
6021                (width - padding[0] - padding[2]).max(0.0),
6022                exact_width || !matches!(self.width, Size::Wrap),
6023                None,
6024            );
6025            (heights.iter().sum::<f32>() + padding[1] + padding[3])
6026                .max(min_h)
6027                .max(bg_min_h)
6028        } else if !horizontal
6029            && matches!(self.kind, Kind::TableRow)
6030            && matches!(self.height, Size::Wrap)
6031        {
6032            let widths: Vec<f32> = self
6033                .children
6034                .iter()
6035                .enumerate()
6036                .map(|(i, n)| n.intrinsic(true, state, child_view_id(id, i, n)))
6037                .collect();
6038            self.standalone_row_metrics(state, metrics, id, &widths)
6039                .0
6040                .max(min_h)
6041                .max(bg_min_h)
6042        } else if !horizontal
6043            && matches!(self.kind, Kind::Table)
6044            && matches!(self.height, Size::Wrap)
6045        {
6046            let padding = self.resolved_padding(state);
6047            let columns = self.table_columns_for_width(
6048                state,
6049                metrics,
6050                id,
6051                (available_width - padding[0] - padding[2]).max(0.0),
6052            );
6053            let height = self
6054                .children
6055                .iter()
6056                .enumerate()
6057                .filter(|(_, n)| n.effective_visibility(state) != Visibility::Gone)
6058                .map(|(i, n)| {
6059                    let child = child_view_id(id, i, n);
6060                    (if matches!(n.kind, Kind::TableRow) {
6061                        self.table_row_height(n, &columns, state, metrics, child, id)
6062                    } else {
6063                        n.layout_intrinsic(false, state, available_width, metrics, child)
6064                    }) + n.margin_for_axis(false, state)
6065                })
6066                .sum::<f32>();
6067            (height + padding[1] + padding[3]).max(min_h).max(bg_min_h)
6068        } else if !horizontal
6069            && matches!(
6070                self.kind,
6071                Kind::Relative | Kind::DialerFilter | Kind::ConstraintLayout
6072            )
6073            && matches!(self.height, Size::Wrap)
6074        {
6075            let padding = self.resolved_padding(state);
6076            let wrap_w = !exact_width && matches!(self.width, Size::Wrap);
6077            let width = if exact_width {
6078                available_width
6079            } else {
6080                match self.width {
6081                    Size::Dp(w) => state.dp(w).min(available_width),
6082                    _ => available_width,
6083                }
6084            };
6085            let inner = Rect {
6086                x: 0.0,
6087                y: 0.0,
6088                width: (width - padding[0] - padding[2]).max(0.0),
6089                height: 1000000.0,
6090            };
6091            let is_cl = matches!(self.kind, Kind::ConstraintLayout);
6092            let ph_claimed = if is_cl {
6093                Some(resolve_constraint_placeholders(self.children, state).1)
6094            } else {
6095                None
6096            };
6097            let visibilities = if is_cl {
6098                Some(constraint_group_visibilities(self.children, state))
6099            } else {
6100                None
6101            };
6102            let positions = if is_cl {
6103                constraint_layout_positions(self, id, inner, state, metrics, wrap_w, true)
6104            } else {
6105                relative_layout::layout(self, id, inner, state, metrics, wrap_w, true)
6106            };
6107            let height = positions
6108                .iter()
6109                .enumerate()
6110                .filter(|(i, _)| {
6111                    let vis = visibilities
6112                        .as_ref()
6113                        .map_or_else(|| self.children[*i].effective_visibility(state), |v| v[*i]);
6114                    vis != Visibility::Gone
6115                        && !(is_cl && is_constraint_helper(&self.children[*i]))
6116                        && !ph_claimed.as_ref().is_some_and(|m| m[*i].is_some())
6117                })
6118                .map(|(i, r)| r.y + r.height + self.children[i].resolved_margin(state)[3])
6119                .fold(0.0_f32, f32::max);
6120            let height = if is_cl {
6121                motion_layout::motion_wrap_content_extent(self, id, inner, state, metrics, false, wrap_w, true).unwrap_or(height)
6122            } else { height };
6123            (height + padding[1] + padding[3]).max(min_h).max(bg_min_h)
6124        } else if !horizontal
6125            && self.image_adjust_bounds
6126            && matches!(
6127                self.kind,
6128                Kind::Image | Kind::QuickContactBadge | Kind::Icon | Kind::Zoom
6129            )
6130            && matches!(self.height, Size::Wrap)
6131        {
6132            let key = if self.id.is_empty() {
6133                format!("#{id}")
6134            } else {
6135                self.id.to_string()
6136            };
6137            let source = self.resolved_intrinsic_image_src(state, &key);
6138            if let Some(image) = state.images.get(source) {
6139                let padding = self.resolved_padding(state);
6140                let width = if exact_width {
6141                    available_width
6142                } else {
6143                    match self.width {
6144                        Size::Dp(w) => state.dp(w).min(available_width),
6145                        Size::Wrap => self.intrinsic(true, state, id).min(available_width),
6146                        Size::Match => available_width,
6147                    }
6148                };
6149                let height = (width - padding[0] - padding[2]).max(0.0) * image.height() as f32
6150                    / image.width() as f32
6151                    + padding[1]
6152                    + padding[3];
6153                let height = height.max(min_h).max(bg_min_h);
6154                return self
6155                    .image_max_height
6156                    .map_or(height, |maximum| height.min(state.dp(maximum)));
6157            }
6158            self.intrinsic(horizontal, state, id)
6159        } else if !horizontal
6160            && matches!(
6161                self.kind,
6162                Kind::Text | Kind::CheckedText | Kind::Chronometer | Kind::TextClock
6163            )
6164            && matches!(self.height, Size::Wrap)
6165        {
6166            let width = if exact_width {
6167                available_width
6168            } else {
6169                match self.width {
6170                    Size::Dp(width) => state.dp(width).min(available_width),
6171                    _ => available_width,
6172                }
6173            };
6174            let key = if self.id.is_empty() {
6175                format!("#{id}")
6176            } else {
6177                self.id.to_string()
6178            };
6179            let text = self.display_text_for(
6180                state.text.get(&key).map_or(self.text, String::as_str),
6181                state,
6182            );
6183            let base_text_size = self.scaled_text_size(state);
6184            let (italic, family) = self.text_style_ext();
6185            let padding = self.resolved_padding(state);
6186            let mark_width = if matches!(self.kind, Kind::CheckedText) {
6187                self.check_mark_width(state)
6188            } else {
6189                0.0
6190            };
6191            let ext = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
6192                self.compound_extents(state, state.rtl)
6193            } else {
6194                [0.0; 4]
6195            };
6196            let shapes = if matches!(self.kind, Kind::Text | Kind::CheckedText) {
6197                self.compound_sizes(state, state.rtl)
6198            } else {
6199                [None; 4]
6200            };
6201            let text_width =
6202                (width - padding[0] - padding[2] - mark_width - ext[0] - ext[2]).max(1.0);
6203            let layout_ext = self.text_layout_ext();
6204            let base_style = TextStyle {
6205                size: base_text_size,
6206                weight: if self.text_bold { 700 } else { 400 },
6207                align: self.align,
6208                letter_spacing: self.letter_spacing_em * base_text_size,
6209                italic,
6210                family,
6211                ..TextStyle::default()
6212            };
6213            let text_size = if let Some(lext) = layout_ext
6214                && lext.has_auto_size()
6215            {
6216                self.resolve_auto_text_size(
6217                    &text,
6218                    text_width,
6219                    f32::INFINITY,
6220                    base_style,
6221                    lext,
6222                    state,
6223                    metrics,
6224                )
6225            } else {
6226                base_text_size
6227            };
6228            let style = TextStyle {
6229                size: text_size,
6230                weight: if self.text_bold { 700 } else { 400 },
6231                align: self.align,
6232                letter_spacing: self.letter_spacing_em * text_size,
6233                italic,
6234                family,
6235                ..TextStyle::default()
6236            };
6237            let lines = if self.single_line {
6238                1
6239            } else if let Some(lext) = layout_ext {
6240                wrap_text_lines_ext(&text, text_width, style, metrics, lext)
6241                    .len()
6242                    .max(1)
6243            } else {
6244                wrapped_text_lines(&text, text_width, style, metrics, |_| {})
6245            };
6246            let lines = if self.max_lines == 0 {
6247                lines
6248            } else {
6249                lines.min(self.max_lines)
6250            };
6251            let lines = lines.max(self.min_lines.max(1));
6252            let lh = self.resolved_line_height(text_size, state);
6253            ((lh + (lines - 1) as f32
6254                * (lh * self.line_spacing_multiplier + state.dp(self.line_spacing_extra)).max(1.0))
6255            .max(shapes[0].map_or(0.0, |s| s.1))
6256            .max(shapes[2].map_or(0.0, |s| s.1))
6257                + ext[1]
6258                + ext[3]
6259                + padding[1]
6260                + padding[3])
6261                .max(min_h)
6262                .max(bg_min_h)
6263        } else if !horizontal
6264            && matches!(self.height, Size::Wrap)
6265            && matches!(
6266                self.kind,
6267                Kind::Linear
6268                    | Kind::RadioGroup
6269                    | Kind::TableRow
6270                    | Kind::Frame
6271                    | Kind::MediaController
6272                    | Kind::MaterialCard
6273                    | Kind::Absolute
6274                    | Kind::ViewAnimator
6275                    | Kind::ViewSwitcher
6276                    | Kind::TextSwitcher
6277                    | Kind::ImageSwitcher
6278                    | Kind::ViewFlipper
6279            )
6280        {
6281            if let Some(nav) = self.nav_bar_spec() {
6282                if nav.kind == NavBarKind::Drawer && !self.children.is_empty() {
6283                    let width = if exact_width {
6284                        available_width
6285                    } else {
6286                        match self.width {
6287                            Size::Dp(w) => state.dp(w).min(available_width),
6288                            _ => available_width,
6289                        }
6290                    };
6291                    let padding = self.resolved_padding(state);
6292                    let inner_w = (width - padding[0] - padding[2]).max(0.0);
6293                    let mut header_h = 0.0_f32;
6294                    let mut has_header = false;
6295                    for (i, child) in self.children.iter().enumerate() {
6296                        if child.effective_visibility(state) == Visibility::Gone {
6297                            continue;
6298                        }
6299                        has_header = true;
6300                        let m = child.resolved_margin(state);
6301                        let avail_w = (inner_w - m[0] - m[2]).max(0.0);
6302                        let cid = child_view_id(id, i, child);
6303                        let ch = match child.height {
6304                            Size::Dp(h) => state.dp(h),
6305                            _ => child.layout_intrinsic(false, state, avail_w, metrics, cid),
6306                        };
6307                        header_h += ch + m[1] + m[3];
6308                    }
6309                    if has_header {
6310                        header_h += state.dp(1.0);
6311                    }
6312                    let count = self.nav_items().len().max(1);
6313                    return (header_h
6314                        + count as f32 * state.dp(56.0)
6315                        + state.dp(24.0)
6316                        + padding[1]
6317                        + padding[3])
6318                        .max(min_h)
6319                        .max(bg_min_h);
6320                }
6321                return self.intrinsic(horizontal, state, id);
6322            }
6323            let width = if exact_width {
6324                available_width
6325            } else {
6326                match self.width {
6327                    Size::Dp(width) => state.dp(width).min(available_width),
6328                    _ => available_width,
6329                }
6330            };
6331            let padding = self.resolved_padding(state);
6332            let inner_width = (width - padding[0] - padding[2]).max(0.0);
6333            let min_h = if self.is_snackbar() {
6334                min_h.max(state.dp(48.0))
6335            } else if self.is_floating_toolbar() {
6336                min_h.max(state.dp(64.0))
6337            } else {
6338                min_h
6339            };
6340            if let Some(cg) = self.chip_group_wrap_spec() {
6341                let (_, _, total_h) = self.chip_group_wrap_rects(
6342                    Rect {
6343                        x: 0.0,
6344                        y: 0.0,
6345                        width: inner_width,
6346                        height: 100_000.0,
6347                    },
6348                    cg,
6349                    state,
6350                    metrics,
6351                    id,
6352                );
6353                return (total_h + padding[1] + padding[3]).max(min_h).max(bg_min_h);
6354            }
6355            let appbar_parent_scroll = if !self.horizontal
6356                && matches!(self.kind, Kind::Linear)
6357                && self
6358                    .children
6359                    .iter()
6360                    .any(|c| c.app_bar_scroll_flags().is_some())
6361            {
6362                Some(self.app_bar_scroll_px(state, id))
6363            } else {
6364                None
6365            };
6366            let horizontal_weights = if self.horizontal
6367                && matches!(self.kind, Kind::Linear | Kind::RadioGroup)
6368                && inner_width > 0.0
6369                && self
6370                    .children
6371                    .iter()
6372                    .any(|n| n.effective_visibility(state) != Visibility::Gone && n.weight > 0.0)
6373            {
6374                Some(self.linear_main_lengths(true, state, inner_width, inner_width, metrics, id))
6375            } else {
6376                None
6377            };
6378            let inline_baselines = self.horizontal
6379                && matches!(self.kind, Kind::Linear | Kind::RadioGroup)
6380                && !self.relative_rules.iter().any(|r| r.kind == 36)
6381                && horizontal_weights.is_some();
6382            let mut inline_ascent = [-1.0_f32; 3];
6383            let mut inline_descent = [-1.0_f32; 3];
6384            let dimensions = self
6385                .children
6386                .iter()
6387                .enumerate()
6388                .filter(|(_, n)| {
6389                    (self.measure_all_children || n.effective_visibility(state) != Visibility::Gone)
6390                        && !self.drawer_panel_is_closed(n, state, id)
6391                })
6392                .map(|(i, n)| {
6393                    let margin = if matches!(self.kind, Kind::Absolute) {
6394                        [0.0; 4]
6395                    } else {
6396                        n.resolved_margin(state)
6397                    };
6398                    let vis = n.effective_visibility(state) != Visibility::Gone;
6399                    let (child_avail_w, child_exact_w) = if vis
6400                        && let Some(ref widths) = horizontal_weights
6401                    {
6402                        (widths[i], n.weight > 0.0)
6403                    } else {
6404                        ((inner_width - margin[0] - margin[2]).max(0.0), false)
6405                    };
6406                    let cid = child_view_id(id, i, n);
6407                    let child_h = n.layout_intrinsic_for_width(
6408                        false,
6409                        state,
6410                        child_avail_w,
6411                        child_exact_w,
6412                        metrics,
6413                        cid,
6414                    );
6415                    if inline_baselines
6416                        && vis
6417                        && let Some(base) = n.relative_baseline(child_avail_w, child_h, state, metrics, cid)
6418                    {
6419                        let gravity = if n.layout_gravity_explicit {
6420                            n.layout_gravity[1]
6421                        } else {
6422                            self.content_gravity[1]
6423                        }
6424                        .min(2) as usize;
6425                        inline_ascent[gravity] = inline_ascent[gravity].max(base);
6426                        inline_descent[gravity] =
6427                            inline_descent[gravity].max(child_h + margin[1] + margin[3] - base);
6428                    }
6429                    let v_margin = if matches!(self.kind, Kind::Absolute) {
6430                        state.dp(n.absolute_position[1])
6431                    } else {
6432                        margin[1] + margin[3]
6433                    };
6434                    if let Some(parent_scroll) = appbar_parent_scroll
6435                        && n.app_bar_scroll_flags().is_some()
6436                    {
6437                        let sp = n.app_bar_child_scroll_px(parent_scroll, state, cid);
6438                        let collapse =
6439                            preview_app_bar_child_collapse(n, cid, child_h, v_margin, sp, state);
6440                        (child_h + v_margin - collapse).max(0.0)
6441                    } else {
6442                        child_h + v_margin
6443                    }
6444                });
6445            let content = if matches!(
6446                self.kind,
6447                Kind::Frame
6448                    | Kind::MediaController
6449                    | Kind::MaterialCard
6450                    | Kind::Absolute
6451                    | Kind::ViewAnimator
6452                    | Kind::ViewSwitcher
6453                    | Kind::TextSwitcher
6454                    | Kind::ImageSwitcher
6455                    | Kind::ViewFlipper
6456            ) || self.horizontal
6457                || matches!(self.kind, Kind::TableRow)
6458            {
6459                dimensions.fold(0.0_f32, f32::max)
6460            } else {
6461                dimensions.sum()
6462            };
6463            let content = if matches!(self.kind, Kind::Frame)
6464                && self.children.iter().any(|n| {
6465                    n.relative_rules
6466                        .iter()
6467                        .any(|r| r.kind == RULE_COORDINATOR_SCROLL_BEHAVIOR)
6468                }) {
6469                let mut combined = content;
6470                for (i, n) in self.children.iter().enumerate() {
6471                    if n.effective_visibility(state) == Visibility::Gone
6472                        || !n
6473                            .relative_rules
6474                            .iter()
6475                            .any(|r| r.kind == RULE_COORDINATOR_SCROLL_BEHAVIOR)
6476                    {
6477                        continue;
6478                    }
6479                    let appbar_h = (0..i)
6480                        .find_map(|j| {
6481                            let sib = &self.children[j];
6482                            if sib.effective_visibility(state) == Visibility::Gone
6483                                || (!matches!(sib.kind, Kind::Linear | Kind::Toolbar)
6484                                    && sib.collapsing_toolbar_spec().is_none())
6485                                || sib.layout_gravity[1] == 2
6486                                || sib.relative_rules.iter().any(|r| {
6487                                    matches!(
6488                                        r.kind,
6489                                        RULE_COORDINATOR_SCROLL_BEHAVIOR | RULE_COORDINATOR_ANCHOR
6490                                    )
6491                                })
6492                            {
6493                                return None;
6494                            }
6495                            let m = sib.resolved_margin(state);
6496                            Some(
6497                                sib.layout_intrinsic(
6498                                    false,
6499                                    state,
6500                                    (inner_width - m[0] - m[2]).max(0.0),
6501                                    metrics,
6502                                    child_view_id(id, j, sib),
6503                                ) + m[1]
6504                                    + m[3],
6505                            )
6506                        })
6507                        .unwrap_or(0.0);
6508                    let m = n.resolved_margin(state);
6509                    let child_h = n.layout_intrinsic(
6510                        false,
6511                        state,
6512                        (inner_width - m[0] - m[2]).max(0.0),
6513                        metrics,
6514                        child_view_id(id, i, n),
6515                    ) + m[1]
6516                        + m[3];
6517                    combined = combined.max(appbar_h + child_h);
6518                }
6519                combined
6520            } else {
6521                content
6522            };
6523            let content = if let Some(spec) = self.text_input_box() {
6524                let (top_inset, supporting_h) = self.text_input_extra_height(&spec, state, id);
6525                content.max(state.dp(56.0)) + top_inset + supporting_h
6526            } else if self.alert_dialog_icon().is_some() {
6527                content + self.alert_dialog_top_icon_extra(state)
6528            } else {
6529                content
6530            };
6531            let vertical_extra_gap = if !self.horizontal && matches!(self.kind, Kind::Linear) {
6532                let vis = self
6533                    .children
6534                    .iter()
6535                    .filter(|n| n.effective_visibility(state) != Visibility::Gone)
6536                    .count();
6537                vis.saturating_sub(1) as f32 * self.linear_extra_gap(state)
6538            } else {
6539                0.0
6540            };
6541            let content = content + vertical_extra_gap;
6542            let content = if inline_baselines {
6543                let a = inline_ascent.iter().copied().fold(-1.0_f32, f32::max);
6544                let d = inline_descent.iter().copied().fold(-1.0_f32, f32::max);
6545                if a >= 0.0 && d >= 0.0 {
6546                    content.max(a + d)
6547                } else {
6548                    content
6549                }
6550            } else if self.horizontal
6551                && matches!(self.kind, Kind::Linear | Kind::RadioGroup)
6552                && !self.relative_rules.iter().any(|r| r.kind == 36)
6553            {
6554                let widths: Vec<f32> = self
6555                    .children
6556                    .iter()
6557                    .enumerate()
6558                    .map(|(i, n)| {
6559                        let margins = n.resolved_margin(state);
6560                        let available = (inner_width - margins[0] - margins[2]).max(0.0);
6561                        n.layout_intrinsic(
6562                            true,
6563                            state,
6564                            available,
6565                            metrics,
6566                            child_view_id(id, i, n),
6567                        )
6568                        .min(available)
6569                    })
6570                    .collect();
6571                let (height, _, _) = self.standalone_row_metrics(state, metrics, id, &widths);
6572                content.max((height - padding[1] - padding[3]).max(0.0))
6573            } else {
6574                content
6575            };
6576            let dividers = if matches!(self.kind, Kind::Linear | Kind::RadioGroup | Kind::TableRow)
6577                && !self.horizontal
6578            {
6579                self.divider_count(state) as f32 * state.dp(self.divider_thickness)
6580            } else {
6581                0.0
6582            };
6583            (content + dividers + padding[1] + padding[3])
6584                .max(min_h)
6585                .max(bg_min_h)
6586                .max(
6587                    if matches!(
6588                        self.kind,
6589                        Kind::Frame
6590                            | Kind::MediaController
6591                            | Kind::MaterialCard
6592                            | Kind::ViewAnimator
6593                            | Kind::ViewSwitcher
6594                            | Kind::TextSwitcher
6595                            | Kind::ImageSwitcher
6596                            | Kind::ViewFlipper
6597                    ) {
6598                        state.dp(self.foreground_size[1])
6599                    } else {
6600                        0.0
6601                    },
6602                )
6603        } else {
6604            self.intrinsic(horizontal, state, id)
6605        }
6606    }
6607}