Skip to main content

bhoo/systems/android/xml/
render.rs

1use super::*;
2
3fn contains_motion_scene(node: &Node, state: &LayoutState) -> bool {
4    state.motion_scenes.contains_key(node.id)
5        || node.children.iter().any(|child| contains_motion_scene(child, state))
6}
7
8// Rendering normally skips the children of an invisible container, although
9// Android's layout retains them. Collect only ancestors of layout targets;
10// the special probe must never change the normal hit-test geometry.
11fn invisible_collision_ancestors(node: &'static Node, target: &str, state: &LayoutState, out: &mut Vec<usize>) -> bool {
12    if node.id == target { return true; }
13    let found = node.children.iter().any(|child| invisible_collision_ancestors(child, target, state, out));
14    if found && node.effective_visibility(state) == Visibility::Invisible {
15        out.push(node as *const Node as usize);
16    }
17    found
18}
19
20pub(super) fn refresh_motion_descendant_geometry(root: &'static Node, scene: &'static str, bounds: Rect, f: &mut Frame<'_>, state: &mut LayoutState) {
21        // Motion input is handled before normal drawing. If there is no usable
22        // descendant geometry yet, lay out a cloned state with input disabled so
23        // a first-frame press or a resize can still find nested swipe regions.
24        let nested_target = |target: &str| target != root.id && !root.children.iter().any(|child| child.id == target);
25        let nested_collision = state.motion_scenes.get(scene).is_some_and(|motion| motion.key_triggers.iter().any(|trigger|
26            trigger.collision.is_some_and(nested_target))) || state.motion_view_key_triggers.iter().any(|(&(owner, _), triggers)|
27                owner == scene && triggers.iter().any(|trigger| trigger.collision.is_some_and(nested_target)))
28            || state.motion_independent_views.iter().any(|(&(owner, target), animation)| owner == scene && nested_target(target)
29                && animation.has_collision_triggers());
30        if (f.input.pointer.is_some() || nested_collision) && state.motion_scenes.contains_key(scene)
31            && (state.motion_descendant_roots.get(scene) != Some(&bounds) || state.motion_descendant_signatures.get(scene) != Some(&state.motion_descendant_signature(scene, f.time())))
32            && root.children.iter().any(|child| !child.children.is_empty() || matches!(child.kind, Kind::ListView | Kind::GridView | Kind::ExpandableListView)) {
33            let mut probe_state = state.clone();
34            probe_state.motion_descendant_bounds.retain(|(owner, _), _| *owner != scene);
35            probe_state.motion_collision_bounds.retain(|(owner, _), _| *owner != scene);
36            probe_state.motion_anonymous_bounds.retain(|(owner, _), _| *owner != scene);
37            probe_state.motion_collect_anonymous_bounds = true;
38            probe_state.motion_parent_bounds.clear();
39            probe_state.motion_parent_scroll.clear();
40            probe_state.motion_descendant_clips.retain(|(owner, _), _| *owner != scene);
41            probe_state.motion_descendant_transforms.retain(|(owner, _), _| *owner != scene);
42            probe_state.motion_hit_stack.clear();
43            probe_state.motion_collect_scene = Some(scene);
44            let mut probe_ui = crate::Ui::default();
45            probe_ui.theme = f.ui.theme;
46            probe_ui.text_metrics = f.ui.text_metrics;
47            probe_ui.viewport = Some(f.viewport());
48            probe_ui.high_contrast = f.ui.high_contrast;
49            probe_ui.motion_preference = f.ui.motion_preference;
50            probe_ui.frame(crate::Input { time: f.time(), ..crate::Input::default() }, bounds, 0.0, |probe| {
51                root.render_inner(probe, bounds, &mut probe_state);
52            });
53            let mut hidden_ancestors = Vec::new();
54            if let Some(motion) = state.motion_scenes.get(scene) {
55                for target in motion.key_triggers.iter().filter_map(|trigger| trigger.collision) {
56                    invisible_collision_ancestors(root, target, state, &mut hidden_ancestors);
57                }
58                for target in motion.swipe.and_then(|swipe| swipe.rotation_center).into_iter().chain(
59                    state.motion_transitions.get(scene).into_iter().flat_map(|(edges, _)|
60                        edges.iter().filter_map(|edge| edge.scene.swipe.and_then(|swipe| swipe.rotation_center)))) {
61                    invisible_collision_ancestors(root, target, state, &mut hidden_ancestors);
62                }
63            }
64            for (&(owner, _), triggers) in &state.motion_view_key_triggers {
65                if owner == scene {
66                    for target in triggers.iter().filter_map(|trigger| trigger.collision) {
67                        invisible_collision_ancestors(root, target, state, &mut hidden_ancestors);
68                    }
69                }
70            }
71            for (&(owner, target), animation) in &state.motion_independent_views {
72                if owner == scene && animation.has_collision_triggers() {
73                    invisible_collision_ancestors(root, target, state, &mut hidden_ancestors);
74                }
75            }
76            if !hidden_ancestors.is_empty() {
77                let mut collision_probe = state.clone();
78                collision_probe.motion_collision_probe_visible.extend(hidden_ancestors);
79                collision_probe.motion_collision_bounds.retain(|(owner, _), _| *owner != scene);
80                collision_probe.motion_parent_bounds.clear();
81                collision_probe.motion_parent_scroll.clear();
82                collision_probe.motion_hit_stack.clear();
83                collision_probe.motion_collect_scene = Some(scene);
84                let mut collision_ui = crate::Ui::default();
85                collision_ui.theme = f.ui.theme;
86                collision_ui.text_metrics = f.ui.text_metrics;
87                collision_ui.viewport = Some(f.viewport());
88                collision_ui.high_contrast = f.ui.high_contrast;
89                collision_ui.motion_preference = f.ui.motion_preference;
90                collision_ui.frame(crate::Input { time: f.time(), ..crate::Input::default() }, bounds, 0.0, |probe| {
91                    root.render_inner(probe, bounds, &mut collision_probe);
92                });
93                probe_state.motion_collision_bounds.retain(|(owner, _), _| *owner != scene);
94                probe_state.motion_collision_bounds.extend(collision_probe.motion_collision_bounds.into_iter().filter(|((owner, _), _)| *owner == scene));
95            }
96            state.motion_descendant_scroll_limits.retain(|(owner, _), _| *owner != scene);
97            state.motion_descendant_scroll_limits.extend(probe_ui.scroll_limits.iter().map(|(&id, &limit)| ((scene, id), limit)));
98            state.motion_descendant_bounds.retain(|(owner, _), _| *owner != scene);
99            state.motion_descendant_bounds.extend(probe_state.motion_descendant_bounds.into_iter().filter(|((owner, _), _)| *owner == scene));
100            state.motion_collision_bounds.retain(|(owner, _), _| *owner != scene);
101            state.motion_collision_bounds.extend(probe_state.motion_collision_bounds.into_iter().filter(|((owner, _), _)| *owner == scene));
102            state.motion_anonymous_bounds.retain(|(owner, _), _| *owner != scene);
103            state.motion_anonymous_bounds.extend(probe_state.motion_anonymous_bounds.into_iter().filter(|((owner, _), _)| *owner == scene));
104            state.motion_descendant_clips.retain(|(owner, _), _| *owner != scene);
105            state.motion_descendant_clips.extend(probe_state.motion_descendant_clips.into_iter().filter(|((owner, _), _)| *owner == scene));
106            state.motion_descendant_transforms.retain(|(owner, _), _| *owner != scene);
107            state.motion_descendant_transforms.extend(probe_state.motion_descendant_transforms.into_iter().filter(|((owner, _), _)| *owner == scene));
108            state.motion_descendant_roots.insert(scene, bounds);
109            state.motion_descendant_signatures.insert(scene, state.motion_descendant_signature(scene, f.time()));
110        }
111}
112
113
114impl Node {
115    /// Set text in a TextSwitcher, optionally switching to its next child.
116    /// The switcher must have a stable XML ID when nested in another layout.
117    pub fn set_switcher_text(&self, state: &mut LayoutState, text: &str, advance: bool) -> bool {
118        if !matches!(self.kind, Kind::TextSwitcher) || self.children.is_empty() { return false; }
119        let key = if self.id.is_empty() { format!("#{}", view_id(self.id)) } else { self.id.to_string() };
120        let selected = state.displayed_children.entry(key).or_default();
121        if *selected >= self.children.len() { *selected = 0; }
122        if advance { *selected = (*selected + 1) % self.children.len(); }
123        let child = &self.children[*selected];
124        let child_key = if child.id.is_empty() { format!("#{}", anonymous_child_id(view_id(self.id), *selected)) } else { child.id.to_string() };
125        state.text.insert(child_key, text.to_owned());
126        true
127    }
128    /// Set the image of the next ImageSwitcher child and select it.
129    pub fn set_switcher_image(&self, state: &mut LayoutState, source: &str) -> bool {
130        if !matches!(self.kind, Kind::ImageSwitcher) || self.children.is_empty() || !state.images.contains_key(source) { return false; }
131        let key = if self.id.is_empty() { format!("#{}", view_id(self.id)) } else { self.id.to_string() };
132        let selected = state.displayed_children.entry(key).or_default();
133        if *selected >= self.children.len() { *selected = 0; }
134        *selected = (*selected + 1) % self.children.len();
135        let child = &self.children[*selected];
136        let child_key = if child.id.is_empty() { format!("#{}", anonymous_child_id(view_id(self.id), *selected)) } else { child.id.to_string() };
137        state.image_sources.insert(child_key, source.to_owned());
138        true
139    }
140    /// Paint an explicitly shown floating MediaController at the bottom of its anchor.
141    pub fn render_floating_media_controller(&'static self,f:&mut Frame<'_>,anchor:Rect,height:f32,state:&mut LayoutState)->Option<&'static str> {
142        if !matches!(self.kind,Kind::MediaController)||self.id.is_empty()||!height.is_finite(){return None;}
143        let key=self.id;let now=f.time();let slider_id=anonymous_child_id(view_id(key),view_id("mediacontroller_progress") as usize);
144        let mut floating=state.media_floating.remove(key)?;if !floating.visible{return None;}
145        let was_dragging=floating.dragging;let dragging_before=f.ui.active==Some(slider_id);
146        if !dragging_before&&!was_dragging&&floating.deadline.is_some_and(|deadline|now>=deadline){return None;}
147        let h=height.max(0.0).min(anchor.height);let bounds=Rect{x:anchor.x,y:anchor.y+anchor.height-h,width:anchor.width,height:h};
148        let start=f.commands.len();let action=self.render(f,bounds,state);f.ui.overlays.extend(f.commands.drain(start..));
149        let dragging=f.ui.active==Some(slider_id)&&!f.input.released&&!f.input.cancelled&&!f.input.blurred;floating.dragging=dragging;
150        if action.is_some()||was_dragging&&!dragging {floating.deadline=Some(now+3.0);}
151        if dragging {f.continuous(bounds);} else if let Some(deadline)=floating.deadline {f.wake_at(deadline);}
152        state.media_floating.insert(key.to_owned(),floating);action
153    }
154    pub fn render(
155        &'static self,
156        f: &mut Frame<'_>,
157        bounds: Rect,
158        state: &mut LayoutState,
159    ) -> Option<&'static str> {
160        if state.motion_measure_frame.is_none_or(|(time, _)| time != f.time()) {
161            state.motion_measure_swipe_fallback.borrow_mut().clear();
162        }
163        state.motion_measure_frame = Some((f.time(), f.reduced_motion()));
164        state.motion_measure_input = Some(f.input);
165        state.synchronize_motion_shared_values();
166        let previous_theme = state
167            .theme_style
168            .bhoo_theme()
169            .map(|theme| std::mem::replace(&mut f.ui.theme, theme));
170        if state.motion_scenes.contains_key(self.id) {
171            let viewport = f.viewport();
172            state.motion_root_viewports.insert(self.id, viewport);
173            state.motion_root_parent_origins.insert(self.id, [viewport.x, viewport.y]);
174        }
175        state.prepare_motion_frame(self.id, bounds, f);
176        state.resolve_motion_variants(self.id, bounds);
177        state.refresh_motion_position_patterns(self.id);
178        let root = state.motion_start_node(self.id).unwrap_or(self);
179        refresh_motion_descendant_geometry(root, self.id, bounds, f, state);
180        let nested_owns_gesture = state.motion_nested_child_owns_gesture(root, f);
181        if !nested_owns_gesture { state.select_motion_swipe_edge(root, bounds, f); }
182        state.resolve_motion_variants(self.id, bounds);
183        state.refresh_motion_position_patterns(self.id);
184        let root = state.motion_start_node(self.id).unwrap_or(self);
185        refresh_motion_descendant_geometry(root, self.id, bounds, f, state);
186        let original_scroll = f.input.scroll;
187        let swipe = !nested_owns_gesture && state.handle_motion_swipe(root, bounds, f);
188        // A swipe may have changed progress since the input geometry probe.
189        // Refresh nested collision targets for that same rendered frame.
190        refresh_motion_descendant_geometry(root, self.id, bounds, f, state);
191        let previous_scene = state.motion_collect_scene;
192        if state.motion_scenes.contains_key(self.id) {
193            state.motion_descendant_bounds.retain(|(scene, _), _| *scene != self.id);
194            state.motion_descendant_clips.retain(|(scene, _), _| *scene != self.id);
195            state.motion_descendant_transforms.retain(|(scene, _), _| *scene != self.id);
196            state.motion_descendant_roots.insert(self.id, bounds);
197            state.motion_collect_scene = Some(self.id);
198            motion_layout::prepare_root_independent_view(self.id, f, state);
199        }
200        let action = f.cancel_pointer_input(swipe, |f| root.render_inner(f, bounds, state));
201        state.motion_collect_scene = previous_scene;
202        if state.motion_scenes.contains_key(self.id) {
203            state.motion_descendant_scroll_limits.retain(|(scene, _), _| *scene != self.id);
204            state.motion_descendant_scroll_limits.extend(f.ui.scroll_limits.iter().map(|(&id, &limit)| ((self.id, id), limit)));
205            state.motion_descendant_signatures.insert(self.id, state.motion_descendant_signature(self.id, f.time()));
206        }
207        f.input.scroll = original_scroll;
208        state.wake_for_motion_frame(self.id, f);
209        if let Some(theme) = previous_theme {
210            f.ui.theme = theme;
211        }
212        action
213    }
214    pub(super) fn render_inner(
215        &'static self,
216        f: &mut Frame<'_>,
217        bounds: Rect,
218        state: &mut LayoutState,
219    ) -> Option<&'static str> {
220        state.frame_time = f.time();
221        state.frame_reduced_motion = f.reduced_motion();
222        state.frame_scroll_dragging = f.any_scroll_dragging();
223        state.spinner_anchor=None;state.autocomplete_anchor=None;state.til_dropdown_anchor=None;
224        state.search_bar_links.clear();
225        collect_search_view_links(self, view_id(self.id), &mut state.search_bar_links);
226        let mut action=None;
227        let blocked=state.spinner_open.is_some() || state.spinner_closing.is_some();
228        let popup_pointer=state.autocomplete_open.is_some() && state.autocomplete_panel.is_some_and(|panel|f.input.pointer.is_some_and(|point|panel.contains(point))) && (f.input.pressed || f.input.released);
229        let popup_key=state.autocomplete_open.is_some() && f.input.key.is_some_and(|key|matches!(key.key,Key::Up|Key::Down|Key::Enter|Key::Escape));
230        let til_popup_pointer = state.til_dropdown_open.is_some()
231            && state.til_dropdown_panel.is_some_and(|panel| f.input.pointer.is_some_and(|point| panel.contains(point)))
232            && (f.input.pressed || f.input.released);
233        let til_popup_key = state.til_dropdown_open.is_some()
234            && f.input.key.is_some_and(|key| matches!(key.key, Key::Escape));
235        if let Some(window_bg) = state.theme_style.window_background() {
236            let root_has_bg = self.background.is_some()
237                || self.dynamic_drawable_bg().is_some()
238                || self.has_animated_vector(false)
239                || self.has_animated_selector(false)
240                || self.relative_rules.iter().any(|r| {
241                    r.kind == 96
242                        || (!matches!(self.kind, Kind::Button) && r.kind == RULE_BACKGROUND_TINT)
243                        || r.kind == RULE_DRAWABLE_LAYER
244                        || r.kind == RULE_STATEFUL_DRAWABLE_LAYER
245                        || r.kind == RULE_BACKGROUND_IMAGE
246                        || r.kind == RULE_STATEFUL_BG_IMAGE
247                        || (!self.is_image_src_kind() && r.kind == RULE_ANIMATION_LIST && parse_animation_list(r.anchor).is_some())
248                        || (r.kind == RULE_GRADIENT && parse_gradient(r.anchor).is_some())
249                });
250            if !root_has_bg && bounds.width > 0.0 && bounds.height > 0.0 {
251                f.paint_rect(bounds, 0.0, window_bg);
252            }
253        }
254        state.at_root_draw = true;
255        f.without_input(blocked || popup_pointer || popup_key || til_popup_pointer || til_popup_key,|f| {action=self.draw(f,bounds,state,view_id(self.id));});
256        state.at_root_draw = false;
257        if let Some(chosen)=render_autocomplete_popup(f,state) {action=Some(chosen);}
258        if let Some(chosen)=render_til_dropdown_popup(f,state) {action=Some(chosen);}
259        if let Some(SpinnerAnchor {key,id,bounds:anchor,xml_id,dialog,prompt,rtl,width:requested_width,offset_x,offset_y,padding})=state.spinner_anchor.clone() && (state.spinner_open.as_deref()==Some(key.as_str()) || dialog && state.spinner_closing.as_deref()==Some(key.as_str())) {
260            let Some(entries)=state.spinner_items.get(&key) else {state.spinner_open=None;return action;};
261            if entries.is_empty() {state.spinner_open=None;return action;}
262            let flags=state.spinner_enabled.get(&key).cloned().unwrap_or_default();
263            let enabled_at=|i:usize|flags.get(i).copied().unwrap_or(true);
264            let templates=state.spinner_templates.get(&key).copied();
265            let mut template_state=templates.map(|_|spinner_template_state(state,rtl));
266            if dialog {
267                let viewport=f.viewport();let title_height=if prompt.is_empty(){0.0}else{56.0};
268                let width=(viewport.width-48.0).clamp(0.0,400.0);
269                let rows=spinner_row_offsets(&mut state.spinner_row_cache,&key,entries,templates,&mut template_state,(width-32.0).max(0.0),f.ui.text_metrics,id,0.0);
270                let list_height=rows[entries.len()].min((viewport.height-88.0-title_height).max(48.0));let height=(32.0+title_height+list_height).min(viewport.height);
271                let dialog_bounds=Rect{x:viewport.x+(viewport.width-width)*0.5,y:viewport.y+(viewport.height-height)*0.5,width,height};
272                let mut overlay=state.spinner_dialogs.remove(&key).unwrap_or_default();
273                let was_closing=state.spinner_closing.as_deref()==Some(key.as_str());
274                overlay.kind=OverlayKind::Dialog;overlay.open=state.spinner_open.as_deref()==Some(key.as_str());overlay.dismiss_policy=OverlayDismissPolicy::EscapeOrOutside;
275                let selected=state.spinner_selected.get(&key).copied().unwrap_or(0).min(entries.len()-1);
276                let highlighted=state.spinner_highlight.get(&key).copied().unwrap_or(selected).min(entries.len()-1);
277                let mut choice=None;
278                let scroll=state.spinner_scroll.entry(key.clone()).or_insert_with(|| {let mut physics=crate::scroll::ScrollPhysics::default();physics.offset=rows[highlighted].max(0.0);physics});
279                f.overlay(anonymous_child_id(id,511),&mut overlay,dialog_bounds,true,|f,open| {
280                    let content=f.available();
281                    if !prompt.is_empty() {f.styled_text(Rect{x:content.x,y:content.y,width:content.width,height:title_height},prompt,f.theme().text,TextStyle {size:20.0,..TextStyle::default()});}
282                    let list=Rect{x:content.x,y:content.y+title_height,width:content.width,height:(content.height-title_height).max(0.0)};
283                    let max_scroll=(rows[entries.len()]-list.height).max(0.0);
284                    if f.input.pressed && f.input.pointer_kind==PointerKind::Touch && f.pointer_in(list) && let Some(point)=f.input.pointer {scroll.begin(point[1],f.time());}
285                    if scroll.touching() && let Some(point)=f.input.pointer {scroll.drag(point[1],f.time(),max_scroll,list.height);}
286                    let scrolling=scroll.dragging;if scrolling {f.ui.active=None;}
287                    if f.input.released && scroll.touching() {scroll.release(f.time(),f.reduced_motion());}
288                    if f.pointer_in(list) && f.input.scroll[1]!=0.0 {scroll.wheel(f.input.scroll[1],max_scroll,f.reduced_motion());}
289                    if scroll.advance(f.time(),max_scroll,f.reduced_motion()) {f.ui.continuous=true;}
290                    let offset=scroll.offset.clamp(0.0,max_scroll);let (start,end)=spinner_visible_rows(&rows,offset,list.height);
291                    f.without_input(scrolling,|f| f.within(list,|f| for (i,label) in entries.iter().enumerate().skip(start).take(end.saturating_sub(start)) {
292                        let row=Rect{x:list.x,y:list.y+rows[i]-offset,width:list.width,height:rows[i+1]-rows[i]};
293                        if i==highlighted && highlighted!=selected {f.paint_rect(row,0.0,f.theme().primary_container);}
294                        let r=f.target(anonymous_child_id(id,i),row,label,enabled_at(i),Role::Button);f.state_layer(r,0.0,f.theme().text);
295                        if let (Some(templates),Some(row_state))=(templates,template_state.as_mut()) {
296                            paint_spinner_template(f,templates.dropdown,templates.text_id,label,row,row_state,anonymous_child_id(id,1024+i),r,i==selected,None);
297                        } else {
298                            let circle=Rect{x:row.x+8.0,y:row.y+14.0,width:20.0,height:20.0};let t=f.theme();
299                            let alpha=if r.enabled {1.0}else{0.38};
300                            f.paint_rect(circle,10.0,if i==selected {t.primary.opacity(alpha)}else{t.outline.opacity(alpha)});f.paint_rect(circle.inset(2.0),8.0,t.surface_high);
301                            if i==selected {f.paint_rect(circle.inset(5.0),5.0,t.primary.opacity(alpha));}
302                            f.styled_text(Rect{x:row.x+40.0,width:(row.width-40.0).max(0.0),..row},label,t.text.opacity(alpha),TextStyle::default());
303                        }
304                        if r.clicked {choice=Some(i);*open=false;}
305                    }));
306                    if blocked && (f.pressed_key(Key::Down)||f.pressed_key(Key::Up)) {
307                        let next=spinner_next_enabled(&flags,entries.len(),highlighted,f.pressed_key(Key::Down)).unwrap_or(highlighted);
308                        state.spinner_highlight.insert(key.clone(),next);let top=rows[next];let bottom=rows[next+1];
309                        if top<scroll.offset {scroll.offset=top;}else if bottom>scroll.offset+list.height {scroll.offset=(bottom-list.height).min(max_scroll);}f.ui.continuous=true;
310                    }
311                    if blocked && f.pressed_key(Key::Enter) && enabled_at(highlighted) {choice=Some(highlighted);*open=false;}
312                });
313                if let Some(index)=choice {state.spinner_selected.insert(key.clone(),index);action=Some(xml_id);}
314                if !overlay.open {
315                    state.spinner_open=None;
316                    if was_closing && !overlay.moving() {state.spinner_closing=None;} else {state.spinner_closing=Some(key.clone());}
317                }
318                state.spinner_dialogs.insert(key,overlay);
319                return action;
320            }
321            let viewport=f.viewport();
322            let inner_width=(anchor.width-padding[0]-padding[2]).max(0.0);
323            let selected_for_width=state.spinner_selected.get(&key).copied().unwrap_or(0).min(entries.len()-1);
324            let end=(selected_for_width+15).min(entries.len());let start=selected_for_width.saturating_sub(15-(end-selected_for_width));
325            // Android measures up to 15 adapter *selected* views, including their XML padding.
326            let measured=if requested_width=="wrap_content" {
327                if let (Some(template),Some(row_state))=(templates,template_state.as_mut()) {
328                    entries[start..end].iter().enumerate().map(|(i,label)| {
329                        row_state.text.insert(template.text_id.to_owned(),label.clone());
330                        template.selected.intrinsic(true,row_state,anonymous_child_id(id,1023+i))
331                    }).fold(0.0_f32,f32::max)
332                } else {entries[start..end].iter().map(|s|f.text_width(s,TextStyle::default())+32.0).fold(0.0_f32,f32::max)}
333            } else {0.0};
334            let wanted=match requested_width {"match_parent"=>inner_width,"wrap_content"=>inner_width.max(measured),v=>v.parse::<f32>().unwrap_or(inner_width)};
335            let width=wanted.clamp(0.0,viewport.width.max(0.0));
336            let rows=spinner_row_offsets(&mut state.spinner_row_cache,&key,entries,templates,&mut template_state,width,f.ui.text_metrics,id,0.0);
337            let desired=rows[entries.len()].min(viewport.height);
338            let below_start=(anchor.y+anchor.height+offset_y).clamp(viewport.y,viewport.y+viewport.height);
339            let above_end=(anchor.y+offset_y).clamp(viewport.y,viewport.y+viewport.height);
340            let below=(viewport.y+viewport.height-below_start).max(0.0);let above=(above_end-viewport.y).max(0.0);
341            let use_below=below>=desired || below>=above;
342            let height=desired.min(if use_below {below} else {above});let y=if use_below {below_start} else {above_end-height};
343            let raw_x=if rtl {anchor.x+anchor.width-padding[2]-width-offset_x} else {anchor.x+padding[0]+offset_x};
344            let panel=Rect{x:raw_x.clamp(viewport.x,viewport.x+(viewport.width-width).max(0.0)),y,width,height};
345            if f.input.cancelled || f.input.blurred || f.pressed_key(Key::Escape) || f.input.pressed && !f.pointer_in(panel) {state.spinner_open=None;return action;}
346            let selected=state.spinner_selected.get(&key).copied().unwrap_or(0).min(entries.len()-1);
347            let highlighted=state.spinner_highlight.get(&key).copied().unwrap_or(selected).min(entries.len()-1);
348            let max_scroll=(rows[entries.len()]-panel.height).max(0.0);
349            let scroll=state.spinner_scroll.entry(key.clone()).or_insert_with(|| {let mut physics=crate::scroll::ScrollPhysics::default();physics.offset=rows[highlighted].clamp(0.0,max_scroll);physics});
350            if f.input.pressed && f.input.pointer_kind==PointerKind::Touch && f.pointer_in(panel) && let Some(point)=f.input.pointer {scroll.begin(point[1],f.time());}
351            if scroll.touching() && let Some(point)=f.input.pointer {scroll.drag(point[1],f.time(),max_scroll,panel.height);}
352            let scrolling=scroll.dragging;
353            if scrolling {f.ui.active=None;}
354            if f.input.released && scroll.touching() {scroll.release(f.time(),f.reduced_motion());}
355            if f.pointer_in(panel) && f.input.scroll[1]!=0.0 {scroll.wheel(f.input.scroll[1],max_scroll,f.reduced_motion());}
356            if scroll.advance(f.time(),max_scroll,f.reduced_motion()) {f.ui.continuous=true;}
357            let offset=scroll.offset.clamp(0.0,max_scroll);
358            let (start,end)=spinner_visible_rows(&rows,offset,panel.height);
359            f.elevation(panel,4.0,2);f.paint_rect(panel,4.0,f.theme().surface_highest);
360            f.without_input(scrolling,|f|f.within(panel,|f| for (i,label) in entries.iter().enumerate().skip(start).take(end.saturating_sub(start)) {
361                let r=Rect{x:panel.x,y:panel.y+rows[i]-offset,width:panel.width,height:rows[i+1]-rows[i]};
362                let response=f.target(anonymous_child_id(id,i),r,label,enabled_at(i),Role::Button);
363                if i==highlighted {f.paint_rect(r,0.0,f.theme().primary_container);}
364                f.state_layer(response,0.0,f.theme().text);
365                if let (Some(templates),Some(row_state))=(templates,template_state.as_mut()) {
366                    paint_spinner_template(f,templates.dropdown,templates.text_id,label,r,row_state,anonymous_child_id(id,1024+i),response,i==selected,None);
367                } else {f.styled_text(r,label,f.theme().text.opacity(if response.enabled {1.0}else{0.38}),TextStyle {padding:16.0,..TextStyle::default()});}
368                if response.clicked {state.spinner_selected.insert(key.clone(),i);state.spinner_open=None;action=Some(xml_id);}
369            }));
370            if blocked && (f.pressed_key(Key::Down) || f.pressed_key(Key::Up)) {
371                let next=spinner_next_enabled(&flags,entries.len(),highlighted,f.pressed_key(Key::Down)).unwrap_or(highlighted);
372                state.spinner_highlight.insert(key.clone(),next);
373                let item_top=rows[next];let item_bottom=rows[next+1];
374                if item_top<scroll.offset {scroll.offset=item_top;} else if item_bottom>scroll.offset+panel.height {scroll.offset=(item_bottom-panel.height).min(max_scroll);}
375                f.ui.continuous=true;
376            }
377            if blocked && f.pressed_key(Key::Enter) && enabled_at(highlighted) {state.spinner_selected.insert(key.clone(),highlighted);state.spinner_open=None;action=Some(xml_id);}
378        } else if state.spinner_open.is_some() || state.spinner_closing.is_some() {state.spinner_open=None;state.spinner_closing=None;}
379        action
380    }
381    pub(super) fn draw(
382        &'static self,
383        f: &mut Frame<'_>,
384        b: Rect,
385        state: &mut LayoutState,
386        id: u64,
387    ) -> Option<&'static str> {
388        state.frame_time = f.time();
389        state.frame_reduced_motion = f.reduced_motion();
390        state.frame_scroll_dragging = f.any_scroll_dragging();
391        if !state.motion_child_visual.is_some_and(|(child, _)| child == id)
392            && let Some((scene, progress)) = motion_layout::nested_independent_progress(self, state)
393        {
394            state.motion_animated_view_progress.insert((scene, self.id), progress);
395            if state.motion_scenes.contains_key(self.id) {
396                state.seek_motion_progress(self.id, progress, true);
397            }
398        }
399        let b = if state.motion_child_visual.is_some_and(|(child, _)| child == id) { b }
400            else { motion_layout::nested_independent_position(self, b, state) };
401        let visible = self.effective_visibility(state) == Visibility::Visible
402            && !matches!(self.kind, Kind::Space);
403        let rt_scale = if visible && !self.id.is_empty() {
404            state.view_scale.get(self.id).copied()
405        } else {
406            None
407        };
408        let rt_trans = if visible && !self.id.is_empty() {
409            state.view_translation.get(self.id).copied()
410        } else {
411            None
412        };
413        let rt_alpha = if visible && !self.id.is_empty() {
414            state.view_alpha.get(self.id).copied().unwrap_or(1.0)
415        } else {
416            1.0
417        };
418        let motion_visual = state.motion_child_visual
419            .filter(|(child_id, _)| *child_id == id)
420            .map(|(_, visual)| visual);
421        let nested_visual = if motion_visual.is_none() {
422            motion_layout::nested_independent_visual(self, b, state)
423        } else { None };
424        let motion_transform = motion_visual.and_then(|visual| visual.transform)
425            .or_else(|| nested_visual.map(|(transform, pivot, _)| (transform, pivot)));
426        let xml_tr = if visible {
427            if motion_visual.is_some() || nested_visual.is_some() { motion_transform.map(|(tr, _)| tr) }
428            else { self.view_transform() }
429        } else {
430            None
431        };
432        let prior_pointer = f.input.pointer;
433        let prior_clip = f.clip;
434        let mut transformed_input = false;
435        let clip_motion_child = motion_visual.is_some_and(|visual| visual.clip_child)
436            && (motion_transform.is_some() || rt_scale.is_some() || rt_trans.is_some());
437        let pushed_transform = if visible && (xml_tr.is_some() || rt_scale.is_some() || rt_trans.is_some()) {
438            let (origin, xml_tx, xml_ty, xml_sx, xml_sy, rot_deg) = if let Some(tr) = xml_tr {
439                let [px, py] = motion_transform.map_or_else(
440                    || [tr.px.resolve(b.width, state), tr.py.resolve(b.height, state)],
441                    |(_, pivot)| pivot,
442                );
443                (
444                    [b.x + px, b.y + py],
445                    tr.tx_dp,
446                    tr.ty_dp,
447                    tr.sx,
448                    tr.sy,
449                    tr.rot_deg,
450                )
451            } else {
452                ([b.x + b.width * 0.5, b.y + b.height * 0.5], 0.0, 0.0, 1.0, 1.0, 0.0)
453            };
454            let [rtx, rty] = rt_trans.unwrap_or([0.0, 0.0]);
455            let [rsx, rsy] = rt_scale.unwrap_or([1.0, 1.0]);
456            let tx = xml_tx + rtx;
457            let ty = xml_ty + rty;
458            let sx = xml_sx * rsx;
459            let sy = xml_sy * rsy;
460            #[cfg(any(feature = "gles", target_arch = "wasm32"))]
461            let projective = xml_tr.and_then(|tr| {
462                if tr.rot_x_deg.abs() <= 1e-4 && tr.rot_y_deg.abs() <= 1e-4 { return None; }
463                crate::projective::ProjectiveTransform::camera_view(
464                    origin.map(f64::from), [state.dp(tx) as f64, state.dp(ty) as f64],
465                    [sx as f64, sy as f64], [tr.rot_x_deg as f64, tr.rot_y_deg as f64, rot_deg as f64], state.view_camera_projection_distance(self.id))
466            });
467            #[cfg(not(any(feature = "gles", target_arch = "wasm32")))]
468            let projective: Option<crate::projective::ProjectiveTransform> = None;
469            if tx.abs() > 1e-4
470                || ty.abs() > 1e-4
471                || (sx - 1.0).abs() > 1e-4
472                || (sy - 1.0).abs() > 1e-4
473                || rot_deg.abs() > 1e-4
474                || projective.is_some()
475            {
476                if motion_transform.is_some() || state.motion_collect_scene.is_some()
477                    || (!state.motion_scenes.is_empty() && self.children.iter().any(|child| contains_motion_scene(child, state)))
478                {
479                    transformed_input = true;
480                    if state.motion_collect_scene.is_some() {
481                        state.motion_hit_stack.push(motion_layout::MotionHitTransform {
482                            clip: prior_clip, origin, translate: [state.dp(tx), state.dp(ty)], scale: [sx,sy], angle: rot_deg.to_radians(), projective,
483                        });
484                    }
485                    f.input.pointer = prior_pointer
486                        .filter(|&point| prior_clip.contains(point))
487                        .and_then(|[x, y]| {
488                            if let Some(matrix) = projective {
489                                let mapped = matrix.inverse()?.map([x as f64, y as f64])?;
490                                return Some(mapped.map(|value| value as f32));
491                            }
492                            if sx.abs() <= f32::EPSILON || sy.abs() <= f32::EPSILON {
493                                return None;
494                            }
495                            let x = x - origin[0] - state.dp(tx);
496                            let y = y - origin[1] - state.dp(ty);
497                            let (sin, cos) = rot_deg.to_radians().sin_cos();
498                            Some([
499                                origin[0] + (cos * x + sin * y) / sx,
500                                origin[1] + (-sin * x + cos * y) / sy,
501                            ])
502                        });
503                }
504                #[cfg(any(feature = "gles", target_arch = "wasm32"))]
505                if let Some(matrix) = projective {
506                    f.push_projective(matrix.coefficients().map(|row| row.map(|value| value as f32)));
507                } else {
508                    f.push_transform(origin, [state.dp(tx), state.dp(ty)], [sx, sy], rot_deg.to_radians());
509                }
510                #[cfg(not(any(feature = "gles", target_arch = "wasm32")))]
511                f.push_transform(origin, [state.dp(tx), state.dp(ty)], [sx, sy], rot_deg.to_radians());
512                true
513            } else {
514                false
515            }
516        } else {
517            false
518        };
519        if clip_motion_child {
520            f.clip = if pushed_transform { b } else { prior_clip.intersect(b) };
521            f.commands.push(DrawCommand::PushClip(f.clip));
522        }
523        if self.id.is_empty() && visible && state.motion_collect_anonymous_bounds && let Some(scene) = state.motion_collect_scene {
524            state.motion_anonymous_bounds.insert((scene, id), b);
525        }
526        if !self.id.is_empty() && let Some(scene) = state.motion_collect_scene {
527            if visible {
528                state.motion_descendant_bounds.insert((scene, self.id), b);
529                state.motion_descendant_clips.insert((scene, self.id), b.intersect(f.clip));
530                state.motion_descendant_transforms.insert((scene, self.id), state.motion_hit_stack.clone());
531            }
532            let parent = state.motion_parent_bounds.last().copied()
533                .or_else(|| (self.id == scene).then(|| f.viewport()));
534            if let Some(parent) = parent {
535                let scroll = state.motion_parent_scroll.last().copied().unwrap_or([0.0; 2]);
536                let local = Rect { x: b.x - parent.x + scroll[0], y: b.y - parent.y + scroll[1], ..b };
537                let mut mapped = local;
538                let mut hit = local;
539                let xml = if motion_visual.is_some() || nested_visual.is_some() { motion_transform.map(|(tr, _)| tr) }
540                    else { self.view_transform() };
541                let runtime_scale = state.view_scale.get(self.id).copied().unwrap_or([1.0; 2]);
542                let runtime_translation = state.view_translation.get(self.id).copied().unwrap_or([0.0; 2]);
543                if xml.is_some() || runtime_scale != [1.0; 2] || runtime_translation != [0.0; 2] {
544                    let origin = xml.map_or([b.width * 0.5, b.height * 0.5], |tr| motion_transform.map_or_else(
545                        || [tr.px.resolve(b.width, state), tr.py.resolve(b.height, state)], |(_, pivot)| pivot));
546                    let scale = xml.map_or(runtime_scale, |tr| [tr.sx * runtime_scale[0], tr.sy * runtime_scale[1]]);
547                    let translation = xml.map_or(runtime_translation, |tr| [tr.tx_dp + runtime_translation[0], tr.ty_dp + runtime_translation[1]]).map(|v| state.dp(v));
548                    let (sin, cos) = xml.map_or(0.0, |tr| tr.rot_deg.to_radians()).sin_cos();
549                    let mut lo = [f32::INFINITY; 2];
550                    let mut hi = [f32::NEG_INFINITY; 2];
551                    for x in [local.x, local.x + local.width] {
552                        for y in [local.y, local.y + local.height] {
553                            let x = (x - origin[0]) * scale[0];
554                            let y = (y - origin[1]) * scale[1];
555                            let point = [origin[0] + cos*x - sin*y + translation[0], origin[1] + sin*x + cos*y + translation[1]];
556                            for axis in 0..2 { lo[axis] = lo[axis].min(point[axis]); hi[axis] = hi[axis].max(point[axis]); }
557                        }
558                    }
559                    mapped = Rect { x: lo[0], y: lo[1], width: hi[0]-lo[0], height: hi[1]-lo[1] };
560                    // getHitRect maps local view coordinates and then offsets by
561                    // its layout position; KeyTrigger instead maps the parent rect.
562                    hit = Rect { x: mapped.x + local.x - (cos * local.x * scale[0] - sin * local.y * scale[1]),
563                        y: mapped.y + local.y - (sin * local.x * scale[0] + cos * local.y * scale[1]), ..mapped };
564                    #[cfg(any(feature = "gles", target_arch = "wasm32"))]
565                    if let Some(tr) = xml.filter(|tr| tr.rot_x_deg.abs() > 1e-4 || tr.rot_y_deg.abs() > 1e-4)
566                        && let Some(camera) = crate::projective::ProjectiveTransform::camera_view(
567                            origin.map(f64::from), translation.map(f64::from), scale.map(f64::from),
568                            [tr.rot_x_deg as f64, tr.rot_y_deg as f64, tr.rot_deg as f64], state.view_camera_projection_distance(self.id))
569                        && let Some(m) = camera.map_rect([local.x as f64, local.y as f64, local.width as f64, local.height as f64])
570                        && let Some(h) = camera.map_rect([0.0, 0.0, local.width as f64, local.height as f64])
571                    {
572                        mapped = Rect { x: m[0] as f32, y: m[1] as f32, width: m[2] as f32, height: m[3] as f32 };
573                        hit = Rect { x: local.x + h[0] as f32, y: local.y + h[1] as f32, width: h[2] as f32, height: h[3] as f32 };
574                    }
575                }
576                // Android's getHitRect truncates transformed local edges before
577                // adding the integer layout position.
578                let left = local.x.trunc() + (hit.x - local.x).trunc();
579                let top = local.y.trunc() + (hit.y - local.y).trunc();
580                let right = local.x.trunc() + (hit.x + hit.width - local.x).trunc();
581                let bottom = local.y.trunc() + (hit.y + hit.height - local.y).trunc();
582                hit = Rect { x: left, y: top, width: right - left, height: bottom - top };
583                state.motion_collision_bounds.insert((scene, self.id), (local, mapped, hit));
584            }
585        }
586        let xml_alpha = motion_visual.map_or_else(|| nested_visual.map_or(self.view_alpha, |(_, _, alpha)| alpha), |visual| visual.alpha);
587        let effective_alpha = (xml_alpha * rt_alpha).clamp(0.0, 1.0);
588        let pushed_layer = if visible && effective_alpha < 1.0 {
589            let opacity = effective_alpha;
590            let has_elev = self.relative_rules.iter().any(|r| r.kind == RULE_ELEVATION);
591            let layer_bounds = if self.clip_children_disabled || self.clip_to_padding_disabled {
592                let min_x = b.x.min(f.clip.x);
593                let min_y = b.y.min(f.clip.y);
594                let max_x = (b.x + b.width).max(f.clip.x + f.clip.width);
595                let max_y = (b.y + b.height).max(f.clip.y + f.clip.height);
596                Rect {
597                    x: min_x,
598                    y: min_y,
599                    width: (max_x - min_x).max(0.0),
600                    height: (max_y - min_y).max(0.0),
601                }
602            } else if has_elev {
603                let pad = state.dp(24.0);
604                Rect {
605                    x: b.x - pad,
606                    y: b.y - pad,
607                    width: b.width + pad * 2.0,
608                    height: b.height + pad * 2.0,
609                }
610                .intersect(f.clip)
611            } else {
612                b
613            };
614            f.push_layer(layer_bounds, opacity);
615            true
616        } else {
617            false
618        };
619        let fade=if matches!(self.kind,Kind::ZoomControls) {
620            let key=if self.id.is_empty() { format!("#{id}") } else { self.id.to_owned() };
621            state.zoom_controls_fades.get(&key).copied().map(|fade|(key,fade))
622        } else { None };
623        let track_motion_parent = !state.motion_scenes.is_empty();
624        if track_motion_parent { state.motion_parent_bounds.push(b); state.motion_parent_scroll.push([0.0; 2]); }
625        let mut action=if let Some((key,fade))=fade {
626            let done=f.reduced_motion() || f.time()-fade.start>=0.5;
627            let opacity=if done { f32::from(fade.target_visible) } else { fade.value(f.time()) };
628            let mut action=None;
629            f.with_opacity(opacity,|f| f.without_input(!fade.target_visible,|f| { action=self.draw_contents(f,b,state,id,false); }));
630            if done {
631                state.zoom_controls_fades.remove(&key);
632                if !fade.target_visible {
633                    state.visibility.insert(key,Visibility::Gone);
634                    // One more frame removes the now-gone view from the parent's layout.
635                    f.wake_at(f.time()+0.001);
636                }
637            } else { f.continuous(b); }
638            action
639        } else { self.draw_contents(f,b,state,id,false) };
640        if self.id=="android:tabcontent"&&matches!(self.kind,Kind::Frame)&&self.effective_visibility(state)==Visibility::Visible {
641            if let Some(host_id)=state.active_tab_host.clone() {if let Some(host)=state.tab_hosts.get(&host_id).cloned() {if let Some(factory)=host.factories.get(host.selected).copied().flatten() {
642                let cache_key=(host_id,host.selected);let node=if let Some(node)=state.tab_host_factory_cache.get(&cache_key){*node}else{let node=factory(&host.tags[host.selected]);state.tab_host_factory_cache.insert(cache_key,node);node};
643                let mut child_action=None;f.within(b,|f|{child_action=node.draw(f,b,state,child_view_id(id,host.selected,node));});if child_action.is_some(){action=child_action;}
644            }}}
645        }
646        if track_motion_parent { state.motion_parent_bounds.pop(); state.motion_parent_scroll.pop(); }
647        if !self.is_search_view_closed(state, id) {
648            self.draw_post(f,b,state);
649        }
650        if pushed_layer {
651            f.pop_layer();
652        }
653        if clip_motion_child {
654            f.commands.push(DrawCommand::PopClip);
655            f.clip = prior_clip;
656        }
657        if transformed_input {
658            f.input.pointer = prior_pointer;
659        }
660        if pushed_transform {
661            f.pop_transform();
662            if transformed_input && state.motion_collect_scene.is_some() { state.motion_hit_stack.pop(); }
663        }
664        action
665    }
666    pub(super) fn draw_post(&self,f:&mut Frame<'_>,b:Rect,state:&LayoutState) {
667        if self.effective_visibility(state)==Visibility::Visible && !matches!(self.kind,Kind::Space) {
668            let padding=self.resolved_view_padding(state);
669            let area=if self.foreground_excludes_padding { Rect { x:b.x+padding[0],y:b.y+padding[1],width:(b.width-padding[0]-padding[2]).max(0.0),height:(b.height-padding[1]-padding[3]).max(0.0) } } else { b };
670            let rtl=match self.layout_direction { 1=>false,2=>true,_=>state.rtl };
671            let [h,v]=self.foreground_gravity;
672            let width=if h==5 { area.width } else { state.dp(self.foreground_size[0].max(0.0)) };
673            let height=if v==5 { area.height } else { state.dp(self.foreground_size[1].max(0.0)) };
674            let right=match h {0=>rtl,2=>!rtl,4=>true,_=>false};
675            let x=if h==1 { area.x+(area.width-width)*0.5 } else if right { area.x+area.width-width } else { area.x };
676            let y=match v {1=>area.y+(area.height-height)*0.5,2=>area.y+area.height-height,_=>area.y};
677            let foreground_bounds=Rect { x,y,width,height };
678            let fg_radii = (self.foreground_radius == 0.0)
679                .then(|| self.resolved_corner_radii(state))
680                .flatten();
681            let fg_radius=if self.foreground_radius<0.0 { self.foreground_radius } else { state.dp(self.foreground_radius) };
682            if let Some(color)=self.foreground {
683                if let Some(radii) = fg_radii {
684                    paint_rounded_rect_radii(f, foreground_bounds, radii, color);
685                } else if fg_radius<0.0 {
686                    paint_oval(f,foreground_bounds,color);
687                } else {
688                    f.paint_rect(foreground_bounds,fg_radius,color);
689                }
690            }
691            if let Some(color)=self.foreground_stroke {
692                let sw = state.dp(self.foreground_stroke_width);
693                if let Some(radii) = fg_radii {
694                    paint_outline_radii(f, foreground_bounds, radii, sw, color);
695                } else {
696                    f.commands.push(DrawCommand::Outline { bounds:foreground_bounds,radius:fg_radius,width:sw,color });
697                }
698            }
699        }
700    }
701    pub(super) fn draw_recycler_ext(
702        &'static self,
703        f: &mut Frame<'_>,
704        inner: Rect,
705        state: &mut LayoutState,
706        id: u64,
707        ext: RecyclerLayoutExt,
708        t: Theme,
709    ) -> Option<&'static str> {
710        let key = if self.id.is_empty() { format!("#{id}") } else { self.id.to_owned() };
711        state.list_perf.frames += 1;
712        let rtl = state.rtl;
713        let template = state.list_templates.get(&key).copied();
714        let default_interactive = template.is_some_and(|t| inspect_expandable_template(t.row, t.text_id).2);
715        let default_has_edit = template.is_some_and(|t| template_has_edit(t.row));
716        let mut row_state = (template.is_some() || state.list_item_bindings.contains_key(&key))
717            .then(|| state.take_row_scratch(rtl));
718        let d = state.effective_density();
719        let divider = state.dp(self.divider_thickness.max(0.0));
720        let h_gap = self
721            .relative_rules
722            .iter()
723            .find(|r| r.kind == 93)
724            .and_then(|r| r.anchor.parse::<f32>().ok())
725            .unwrap_or(0.0)
726            .max(0.0)
727            * d;
728        let v_gap = self
729            .relative_rules
730            .iter()
731            .find(|r| r.kind == 94)
732            .and_then(|r| r.anchor.parse::<f32>().ok())
733            .unwrap_or(0.0)
734            .max(0.0)
735            * d;
736        let main_gap = match ext.manager {
737            RecyclerLayoutManager::Linear => {
738                if divider > 0.0 {
739                    divider
740                } else if ext.horizontal {
741                    h_gap
742                } else {
743                    v_gap
744                }
745            }
746            RecyclerLayoutManager::Grid | RecyclerLayoutManager::Staggered => {
747                if ext.horizontal { h_gap.max(divider) } else { v_gap.max(divider) }
748            }
749        };
750        let cross_gap = if ext.horizontal { v_gap } else { h_gap };
751        let span = match ext.manager {
752            RecyclerLayoutManager::Linear => 1,
753            RecyclerLayoutManager::Grid | RecyclerLayoutManager::Staggered => ext.span_count.clamp(1, 256),
754        };
755        let entries = state.list_items.entry(key.clone()).or_insert_with(|| {
756            self.relative_rules
757                .iter()
758                .filter(|r| r.kind == 82)
759                .map(|r| r.anchor.to_owned())
760                .collect()
761        });
762        let entry_count = entries.len();
763        let checked = state.list_checked.entry(key.clone()).or_default();
764        checked.retain(|i| *i < entry_count);
765        let flags = state.list_enabled.get(&key);
766        let item_ids = state.list_item_ids.get(&key);
767        let bindings = state.list_item_bindings.get(&key);
768        let mode = self.relative_rules.iter().find(|r| r.kind == 88).map_or("none", |r| r.anchor);
769        let metrics = f.ui.text_metrics;
770        let cross_avail = if ext.horizontal { inner.height } else { inner.width };
771        let track_size = ((cross_avail - (span - 1) as f32 * cross_gap) / span as f32).max(1.0);
772        let viewport_main = if ext.horizontal { inner.width } else { inner.height };
773
774        let mut chosen = None;
775        let mut long_choice = None;
776        let mut control_choice = None;
777
778        if ext.manager == RecyclerLayoutManager::Linear {
779            let ext_salt = (u64::from(ext.horizontal) << 1)
780                ^ (u64::from(ext.reverse) << 2)
781                ^ (u64::from(ext.stack_end) << 3)
782                ^ if ext.horizontal { u64::from(inner.width.to_bits()).rotate_left(17) } else { 0 };
783            let signature = list_text_signature(entries, track_size, main_gap, metrics, template, row_state.as_deref())
784                ^ ext_salt.wrapping_mul(0x9e3779b97f4a7c15);
785            let list_perf = &mut state.list_perf;
786            let geometry = state.list_text_geometry.entry(key.clone()).or_insert_with(|| {
787                list_perf.geometry_rebuilds += 1;
788                std::sync::Arc::new(ListTextGeometry::new(signature, entry_count, main_gap))
789            });
790            if geometry.signature != signature {
791                list_perf.geometry_rebuilds += 1;
792                *geometry = std::sync::Arc::new(ListTextGeometry::new(signature, entry_count, main_gap));
793            }
794            let geometry = std::sync::Arc::make_mut(geometry);
795            let last_gap = if entry_count == 0 { 0.0 } else { main_gap };
796            let mut content_extent = (geometry.prefix(entry_count) - last_gap).max(0.0);
797            let mut max_scroll = (content_extent - viewport_main).max(0.0);
798            let offset = state.offsets.entry(key.clone()).or_default();
799            if !offset.is_finite() {
800                *offset = 0.0;
801            }
802            let dragging = if ext.horizontal {
803                f.scroll_viewport_horizontal_rtl(id, inner, offset, max_scroll, rtl)
804            } else {
805                f.scroll_viewport(id, inner, offset, max_scroll)
806            };
807            let anchor = if *offset > 0.0 && geometry.measured_count > 0 && entry_count > 0 {
808                let first_vis = geometry.index_at(*offset).min(entry_count);
809                let last_vis = geometry.index_at(*offset + viewport_main).saturating_add(1).min(entry_count);
810                let anchor_idx = (first_vis..last_vis)
811                    .find(|&idx| geometry.fingerprints[idx].is_some())
812                    .unwrap_or(first_vis)
813                    .min(entry_count.saturating_sub(1));
814                Some((anchor_idx, geometry.prefix(anchor_idx)))
815            } else {
816                None
817            };
818            if geometry.measure_recycler_linear_window(
819                entries,
820                ext.reverse,
821                ext.horizontal,
822                *offset,
823                viewport_main,
824                track_size,
825                inner.width,
826                metrics,
827                template,
828                row_state.as_deref_mut(),
829                id,
830                bindings,
831                list_perf,
832            ) {
833                content_extent = (geometry.prefix(entry_count) - last_gap).max(0.0);
834                max_scroll = (content_extent - viewport_main).max(0.0);
835                if let Some((anchor_idx, old_prefix)) = anchor {
836                    let shift = geometry.prefix(anchor_idx) - old_prefix;
837                    if shift.abs() > 0.01 {
838                        let new_offset = (*offset + shift).clamp(0.0, max_scroll);
839                        let applied = new_offset - *offset;
840                        *offset = new_offset;
841                        f.shift_scroll_offset(id, applied, new_offset);
842                    }
843                }
844                f.continuous(inner);
845            }
846            f.ui.scroll_limits.insert(id, max_scroll);
847            let scroll = *offset;
848            let pad_start = if ext.stack_end {
849                (viewport_main - content_extent).max(0.0)
850            } else {
851                0.0
852            };
853            let local_start = (scroll - pad_start).max(0.0);
854            let local_end = (scroll - pad_start + viewport_main).max(0.0);
855            let (start, end) = if entry_count == 0 || scroll - pad_start + viewport_main <= 0.0 {
856                (0, 0)
857            } else {
858                (
859                    geometry.index_at(local_start).min(entry_count),
860                    geometry.index_at(local_end).saturating_add(1).min(entry_count),
861                )
862            };
863            let long_enabled = state.list_long_click_enabled.get(&key).copied().unwrap_or(false);
864            let hold = state.list_holds.entry(key.clone()).or_default();
865            if !long_enabled
866                || dragging
867                || f.input.cancelled
868                || f.input.blurred
869                || f.input.released
870                || f.input.scroll != [0.0, 0.0]
871            {
872                *hold = None;
873            }
874            let control_states = &mut state.list_control_states;
875            let edit_states = &mut state.list_edit_states;
876            let kept_alive_focus = &mut state.list_kept_alive_focus;
877            let saved_focus = kept_alive_focus.get(&key).copied();
878            let mut saw_kept_alive_row = false;
879            let mut focused_visible_row: Option<(i64, u64, bool)> = None;
880            let mut ext_built: u64 = 0;
881            let (stretch_s, stretch_sign) = f.scroll_stretch(id);
882            let mut main_pos = geometry.prefix(start);
883            f.cancel_pointer_input(dragging, |f| {
884                f.within(inner, |f| {
885                    f.with_edge_stretch(inner, ext.horizontal, stretch_s, stretch_sign, |f| {
886                        for vis_pos in start..end {
887                            let index = if ext.reverse { entry_count - 1 - vis_pos } else { vis_pos };
888                            let main_len = geometry.heights[vis_pos];
889                            let cross_len = geometry.cross_sizes.get(vis_pos).copied().unwrap_or(track_size);
890                            let (item_w, item_h) = if ext.horizontal { (main_len, cross_len) } else { (cross_len, main_len) };
891                            let bounds = if ext.horizontal {
892                                let logical_x = pad_start + main_pos - scroll;
893                                let x = if rtl {
894                                    inner.x + inner.width - logical_x - item_w
895                                } else {
896                                    inner.x + logical_x
897                                };
898                                Rect { x, y: inner.y, width: item_w, height: item_h }
899                            } else {
900                                let x = if rtl {
901                                    inner.x + inner.width - item_w
902                                } else {
903                                    inner.x
904                                };
905                                Rect { x, y: inner.y + pad_start + main_pos - scroll, width: item_w, height: item_h }
906                            };
907                            main_pos += main_len + main_gap;
908                            let clip_vis = bounds.intersect(inner);
909                            if clip_vis.width <= 0.0 || clip_vis.height <= 0.0 {
910                                continue;
911                            }
912                            ext_built += 1;
913                            if checked.contains(&index) {
914                                f.paint_rect(bounds, 0.0, t.primary_container);
915                            }
916                            let item_key = item_ids
917                                .and_then(|ids| ids.get(index))
918                                .map_or(index as u64, |value| *value as u64);
919                            let identity = item_key as i64;
920                            let enabled = self.enabled && flags.and_then(|v| v.get(index)).copied().unwrap_or(true);
921                            let row_id = id.wrapping_mul(0x9e3779b97f4a7c15).wrapping_add(item_key);
922                            if let Some((saved_identity, saved_fid, saved_kb)) = saved_focus
923                                && saved_identity == identity
924                            {
925                                saw_kept_alive_row = true;
926                                if enabled && f.ui.focused.is_none() && f.ui.pending_focus.is_none() && !f.input.blurred {
927                                    f.ui.focused = Some(saved_fid);
928                                    f.ui.keyboard_focus = saved_kb;
929                                }
930                            }
931                            let focus_order_start = f.ui.next_focus_order.len();
932                            let binding = bindings.and_then(|items| items.get(&index));
933                            let item_template = adapter_item_template(template, binding);
934                            let (interactive, has_edit) = match binding.and_then(|b| b.template) {
935                                Some(tmpl) => (inspect_expandable_template(tmpl.row, tmpl.text_id).2, template_has_edit(tmpl.row)),
936                                None => (default_interactive, default_has_edit),
937                            };
938                            if interactive {
939                                let tmpl = item_template.unwrap();
940                                if let Some(scratch) = row_state.as_deref_mut() {
941                                    scratch.adapter_namespace = Some(row_id);
942                                    scratch.rtl = rtl;
943                                    load_row_control_overrides(control_states, &key, identity, &mut scratch.checked);
944                                    with_adapter_binding(scratch, tmpl.text_id, &entries[index], binding, |rs| {
945                                        if has_edit {
946                                            apply_row_edit_overrides(edit_states, &key, identity, &mut rs.text);
947                                        }
948                                        f.within(bounds, |f| {
949                                            f.with_enabled(enabled, |f| {
950                                                if let Some(view) = tmpl.row.draw(f, bounds, rs, anonymous_child_id(row_id, 0)) {
951                                                    control_choice = Some((index, view));
952                                                }
953                                            });
954                                        });
955                                        if has_edit {
956                                            commit_row_edit_overrides(edit_states, &key, identity, tmpl.row, binding, &rs.text);
957                                        }
958                                    });
959                                    commit_row_control_overrides(control_states, &key, identity, tmpl.row, &mut scratch.checked);
960                                    scratch.adapter_namespace = None;
961                                }
962                            }
963                            let r = f.target(row_id, bounds, &entries[index], enabled, Role::Button);
964                            if let Some(fid) = f.ui.pending_focus.or(f.ui.focused)
965                                && f.ui.next_focus_order[focus_order_start..].contains(&fid)
966                            {
967                                focused_visible_row = Some((identity, fid, f.ui.keyboard_focus));
968                            }
969                            if adapter_item_long_press(f, r, hold, long_enabled) {
970                                long_choice = Some(index);
971                            }
972                            f.state_layer(r, 0.0, t.text);
973                            if interactive {
974                            } else if let (Some(tmpl), Some(rs)) = (item_template, row_state.as_deref_mut()) {
975                                paint_spinner_template(
976                                    f,
977                                    tmpl.row,
978                                    tmpl.text_id,
979                                    &entries[index],
980                                    bounds,
981                                    rs,
982                                    anonymous_child_id(id, 1024 + index),
983                                    r,
984                                    checked.contains(&index),
985                                    binding,
986                                );
987                            } else {
988                                let style = TextStyle { align: if rtl { 2 } else { 0 }, ..TextStyle::default() };
989                                let text_w = (bounds.width - 32.0).max(1.0);
990                                let wrapped = wrap_text_lines_once(&entries[index], text_w, style, metrics);
991                                let mut line_y = bounds.y + (bounds.height - wrapped.len().max(1) as f32 * 24.0).max(0.0) * 0.5;
992                                for line in wrapped.as_slice() {
993                                    f.styled_text(
994                                        Rect { x: bounds.x + 16.0, y: line_y, width: text_w, height: 24.0 },
995                                        &line.text,
996                                        t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
997                                        style,
998                                    );
999                                    line_y += 24.0;
1000                                }
1001                            }
1002                            if r.clicked {
1003                                chosen = Some(index);
1004                            }
1005                            if vis_pos + 1 < entry_count
1006                                && divider > 0.0
1007                                && let Some(color) = self.divider_color
1008                            {
1009                                if ext.horizontal {
1010                                    let dx = if rtl { bounds.x - divider } else { bounds.x + bounds.width };
1011                                    f.paint_rect(Rect { x: dx, y: bounds.y, width: divider, height: bounds.height }, 0.0, color);
1012                                } else {
1013                                    f.paint_rect(
1014                                        Rect { x: bounds.x, y: bounds.y + bounds.height, width: bounds.width, height: divider },
1015                                        0.0,
1016                                        color,
1017                                    );
1018                                }
1019                            }
1020                        }
1021                    });
1022                });
1023            });
1024            if let Some(active_row) = focused_visible_row {
1025                kept_alive_focus.insert(key.clone(), active_row);
1026            } else if let Some((_, saved_fid, _)) = saved_focus {
1027                let focused_elsewhere = f.ui.focused.is_some_and(|fid| fid != saved_fid)
1028                    || f.ui.pending_focus.is_some_and(|fid| fid != saved_fid);
1029                if f.input.blurred || saw_kept_alive_row || focused_elsewhere {
1030                    kept_alive_focus.remove(&key);
1031                }
1032            }
1033            list_perf.rows_built += ext_built;
1034            let ext_ctrl = control_states.get(&key).map_or(0, HashMap::len)
1035                + edit_states.get(&key).map_or(0, HashMap::len);
1036            let ext_rows = geometry.measured_count.max(ext_ctrl);
1037            let ext_bytes = geometry.retained_bytes()
1038                + ext_ctrl * (std::mem::size_of::<(i64, HashMap<String, bool>)>() + 96)
1039                + usize::from(kept_alive_focus.contains_key(&key))
1040                    * std::mem::size_of::<(String, (i64, u64, bool))>();
1041            list_perf.peak_retained_rows = list_perf.peak_retained_rows.max(ext_rows);
1042            list_perf.peak_retained_control_rows = list_perf.peak_retained_control_rows.max(ext_ctrl);
1043            list_perf.peak_retained_bytes = list_perf.peak_retained_bytes.max(ext_bytes);
1044        } else {
1045        let visual_order: Vec<usize> = if ext.reverse {
1046            (0..entry_count).rev().collect()
1047        } else {
1048            (0..entry_count).collect()
1049        };
1050        let mut ext_measured: u64 = 0;
1051        let mut measure_item = |index: usize, row_state: Option<&mut LayoutState>| -> (f32, f32) {
1052            ext_measured += 1;
1053            let label = &entries[index];
1054            let binding = bindings.and_then(|items| items.get(&index));
1055            let item_tmpl = adapter_item_template(template, binding);
1056            let cid = anonymous_child_id(id, 1024 + index);
1057            if let (Some(tmpl), Some(rs)) = (item_tmpl, row_state) {
1058                with_adapter_binding(rs, tmpl.text_id, label, binding, |rs| {
1059                    if ext.horizontal {
1060                        let h = match tmpl.row.height {
1061                            Size::Match => track_size,
1062                            Size::Dp(v) => rs.dp(v).min(track_size),
1063                            Size::Wrap => tmpl.row.layout_intrinsic(false, rs, inner.width.max(48.0), metrics, cid).min(track_size),
1064                        }
1065                        .max(1.0);
1066                        let w = match tmpl.row.width {
1067                            Size::Match => rs.dp(120.0).min(inner.width.max(48.0)),
1068                            Size::Dp(v) => rs.dp(v),
1069                            Size::Wrap => tmpl.row.layout_intrinsic(true, rs, inner.width.max(48.0), metrics, cid),
1070                        };
1071                        (if w.is_finite() { w.clamp(1.0, 4096.0) } else { rs.dp(120.0) }, h)
1072                    } else {
1073                        let w = match tmpl.row.width {
1074                            Size::Match => track_size,
1075                            Size::Dp(v) => rs.dp(v).min(track_size),
1076                            Size::Wrap => tmpl.row.layout_intrinsic(true, rs, track_size, metrics, cid).min(track_size),
1077                        }
1078                        .max(1.0);
1079                        let h = match tmpl.row.height {
1080                            Size::Match => rs.dp(48.0),
1081                            Size::Dp(v) => rs.dp(v),
1082                            Size::Wrap => tmpl.row.layout_intrinsic(false, rs, w, metrics, cid),
1083                        };
1084                        (w, if h.is_finite() { h.clamp(1.0, 4096.0) } else { rs.dp(48.0) })
1085                    }
1086                })
1087            } else if ext.horizontal {
1088                let tw = metrics.width(label, TextStyle::default());
1089                let w = (tw.ceil() + 34.0).clamp(48.0, 4096.0);
1090                (w, track_size)
1091            } else {
1092                let lines = wrapped_text_lines(label, (track_size - 32.0).max(1.0), TextStyle::default(), metrics, |_| {}).max(1);
1093                (track_size, (24.0 * lines as f32).clamp(48.0, 4096.0))
1094            }
1095        };
1096        // Each tuple: (adapter_index, main_pos, cross_pos, item_w, item_h)
1097        let mut placed: Vec<(usize, f32, f32, f32, f32)> = Vec::with_capacity(entry_count);
1098        let content_extent = match ext.manager {
1099            RecyclerLayoutManager::Linear => unreachable!(),
1100            RecyclerLayoutManager::Grid => {
1101                let mut cursor = 0.0_f32;
1102                for chunk in visual_order.chunks(span) {
1103                    let mut chunk_max = 0.0_f32;
1104                    let mut sizes = Vec::with_capacity(chunk.len());
1105                    for &idx in chunk {
1106                        let (w, h) = measure_item(idx, row_state.as_deref_mut());
1107                        chunk_max = chunk_max.max(if ext.horizontal { w } else { h });
1108                        sizes.push((idx, w, h));
1109                    }
1110                    for (lane, (idx, w, h)) in sizes.into_iter().enumerate() {
1111                        let cross_pos = lane as f32 * (track_size + cross_gap);
1112                        placed.push((idx, cursor, cross_pos, w, h));
1113                    }
1114                    cursor += chunk_max + main_gap;
1115                }
1116                if entry_count == 0 { 0.0 } else { (cursor - main_gap).max(0.0) }
1117            }
1118            RecyclerLayoutManager::Staggered => {
1119                let mut track_ends = vec![0.0_f32; span];
1120                let mut track_counts = vec![0usize; span];
1121                for &idx in &visual_order {
1122                    let mut best = 0usize;
1123                    let mut best_end = track_ends[0];
1124                    for (lane, &end_val) in track_ends.iter().enumerate().skip(1) {
1125                        if end_val + 0.01 < best_end {
1126                            best = lane;
1127                            best_end = end_val;
1128                        }
1129                    }
1130                    let (w, h) = measure_item(idx, row_state.as_deref_mut());
1131                    let main_len = if ext.horizontal { w } else { h };
1132                    let main_pos = if track_counts[best] > 0 {
1133                        track_ends[best] + main_gap
1134                    } else {
1135                        0.0
1136                    };
1137                    let cross_pos = best as f32 * (track_size + cross_gap);
1138                    placed.push((idx, main_pos, cross_pos, w, h));
1139                    track_ends[best] = main_pos + main_len;
1140                    track_counts[best] += 1;
1141                }
1142                track_ends.into_iter().fold(0.0_f32, f32::max)
1143            }
1144        };
1145        let max_scroll = (content_extent - viewport_main).max(0.0);
1146        let offset = state.offsets.entry(key.clone()).or_default();
1147        if !offset.is_finite() {
1148            *offset = 0.0;
1149        }
1150        let dragging = if ext.horizontal {
1151            f.scroll_viewport_horizontal_rtl(id, inner, offset, max_scroll, rtl)
1152        } else {
1153            f.scroll_viewport(id, inner, offset, max_scroll)
1154        };
1155        f.ui.scroll_limits.insert(id, max_scroll);
1156        let scroll = *offset;
1157        let pad_start = if ext.stack_end {
1158            (viewport_main - content_extent).max(0.0)
1159        } else {
1160            0.0
1161        };
1162        let long_enabled = state.list_long_click_enabled.get(&key).copied().unwrap_or(false);
1163        let hold = state.list_holds.entry(key.clone()).or_default();
1164        if !long_enabled
1165            || dragging
1166            || f.input.cancelled
1167            || f.input.blurred
1168            || f.input.released
1169            || f.input.scroll != [0.0, 0.0]
1170        {
1171            *hold = None;
1172        }
1173        state.list_perf.rows_measured += ext_measured;
1174        let control_states = &mut state.list_control_states;
1175        let mut ext_built: u64 = 0;
1176        let (stretch_s, stretch_sign) = f.scroll_stretch(id);
1177        f.cancel_pointer_input(dragging, |f| {
1178            f.within(inner, |f| {
1179                f.with_edge_stretch(inner, ext.horizontal, stretch_s, stretch_sign, |f| {
1180                for &(index, main_pos, cross_pos, item_w, item_h) in &placed {
1181                    let bounds = if ext.horizontal {
1182                        let logical_x = pad_start + main_pos - scroll;
1183                        let x = if rtl {
1184                            inner.x + inner.width - logical_x - item_w
1185                        } else {
1186                            inner.x + logical_x
1187                        };
1188                        Rect { x, y: inner.y + cross_pos, width: item_w, height: item_h }
1189                    } else {
1190                        let x = if rtl {
1191                            inner.x + inner.width - cross_pos - item_w
1192                        } else {
1193                            inner.x + cross_pos
1194                        };
1195                        Rect { x, y: inner.y + pad_start + main_pos - scroll, width: item_w, height: item_h }
1196                    };
1197                    let clip_vis = bounds.intersect(inner);
1198                    if clip_vis.width <= 0.0 || clip_vis.height <= 0.0 {
1199                        continue;
1200                    }
1201                    ext_built += 1;
1202                    if checked.contains(&index) {
1203                        f.paint_rect(bounds, 0.0, t.primary_container);
1204                    }
1205                    let item_key = item_ids
1206                        .and_then(|ids| ids.get(index))
1207                        .map_or(index as u64, |value| *value as u64);
1208                    let enabled = self.enabled && flags.and_then(|v| v.get(index)).copied().unwrap_or(true);
1209                    let row_id = id.wrapping_mul(0x9e3779b97f4a7c15).wrapping_add(item_key);
1210                    let binding = bindings.and_then(|items| items.get(&index));
1211                    let item_template = adapter_item_template(template, binding);
1212                    let interactive = match binding.and_then(|b| b.template) {
1213                        Some(tmpl) => inspect_expandable_template(tmpl.row, tmpl.text_id).2,
1214                        None => default_interactive,
1215                    };
1216                    if interactive {
1217                        let tmpl = item_template.unwrap();
1218                        if let Some(scratch) = row_state.as_deref_mut() {
1219                            scratch.adapter_namespace = Some(row_id);
1220                            scratch.rtl = rtl;
1221                            load_row_control_overrides(control_states, &key, item_key as i64, &mut scratch.checked);
1222                            with_adapter_binding(scratch, tmpl.text_id, &entries[index], binding, |rs| {
1223                                f.within(bounds, |f| {
1224                                    f.with_enabled(enabled, |f| {
1225                                        if let Some(view) = tmpl.row.draw(f, bounds, rs, anonymous_child_id(row_id, 0)) {
1226                                            control_choice = Some((index, view));
1227                                        }
1228                                    });
1229                                });
1230                            });
1231                            commit_row_control_overrides(control_states, &key, item_key as i64, tmpl.row, &mut scratch.checked);
1232                            scratch.adapter_namespace = None;
1233                        }
1234                    }
1235                    let r = f.target(row_id, bounds, &entries[index], enabled, Role::Button);
1236                    if adapter_item_long_press(f, r, hold, long_enabled) {
1237                        long_choice = Some(index);
1238                    }
1239                    f.state_layer(r, 0.0, t.text);
1240                    if interactive {
1241                    } else if let (Some(tmpl), Some(rs)) = (item_template, row_state.as_deref_mut()) {
1242                        paint_spinner_template(
1243                            f,
1244                            tmpl.row,
1245                            tmpl.text_id,
1246                            &entries[index],
1247                            bounds,
1248                            rs,
1249                            anonymous_child_id(id, 1024 + index),
1250                            r,
1251                            checked.contains(&index),
1252                            binding,
1253                        );
1254                    } else {
1255                        let style = TextStyle { align: if rtl { 2 } else { 0 }, ..TextStyle::default() };
1256                        let text_w = (bounds.width - 32.0).max(1.0);
1257                        let wrapped = wrap_text_lines_once(&entries[index], text_w, style, metrics);
1258                        let mut line_y = bounds.y + (bounds.height - wrapped.len().max(1) as f32 * 24.0).max(0.0) * 0.5;
1259                        for line in wrapped.as_slice() {
1260                            f.styled_text(
1261                                Rect { x: bounds.x + 16.0, y: line_y, width: text_w, height: 24.0 },
1262                                &line.text,
1263                                t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
1264                                style,
1265                            );
1266                            line_y += 24.0;
1267                        }
1268                    }
1269                    if r.clicked {
1270                        chosen = Some(index);
1271                    }
1272                }
1273                });
1274            });
1275        });
1276        state.list_perf.rows_built += ext_built;
1277        let ext_ctrl = state.list_control_states.get(&key).map_or(0, HashMap::len);
1278        let ext_rows = placed.len().max(ext_ctrl);
1279        let ext_bytes = placed.capacity() * std::mem::size_of::<(usize, f32, f32, f32, f32)>()
1280            + ext_ctrl * (std::mem::size_of::<(i64, HashMap<String, bool>)>() + 96);
1281        state.list_perf.peak_retained_rows = state.list_perf.peak_retained_rows.max(ext_rows);
1282        state.list_perf.peak_retained_control_rows = state.list_perf.peak_retained_control_rows.max(ext_ctrl);
1283        state.list_perf.peak_retained_bytes = state.list_perf.peak_retained_bytes.max(ext_bytes);
1284        }
1285        let mut action = None;
1286        if let Some(control) = control_choice {
1287            state.list_control_clicked.insert(key.clone(), control);
1288            chosen = None;
1289            long_choice = None;
1290            action = Some(self.id);
1291        }
1292        if let Some(index) = long_choice {
1293            state.list_long_clicked.insert(key.clone(), index);
1294            action = Some(self.id);
1295        }
1296        if let Some(index) = chosen {
1297            match mode {
1298                "singleChoice" => {
1299                    checked.clear();
1300                    checked.push(index);
1301                }
1302                "multipleChoice" => {
1303                    if let Some(pos) = checked.iter().position(|v| *v == index) {
1304                        checked.remove(pos);
1305                    } else {
1306                        checked.push(index);
1307                    }
1308                }
1309                _ => {}
1310            }
1311            state.list_clicked.insert(key, index);
1312            action = Some(self.id);
1313        }
1314        if let Some(scratch) = row_state {
1315            state.restore_row_scratch(scratch);
1316        }
1317        action
1318    }
1319    #[allow(clippy::too_many_arguments)]
1320    pub(super) fn draw_search_view_ext(
1321        &'static self,
1322        f: &mut Frame<'_>,
1323        b: Rect,
1324        state: &mut LayoutState,
1325        id: u64,
1326        spec: SearchViewExtSpec<'static>,
1327        t: Theme,
1328        background_tint: Option<Color>,
1329        explicit_background: Option<Color>,
1330        scaled_radius: f32,
1331    ) -> Option<&'static str> {
1332        let view_key = if self.id.is_empty() {
1333            format!("#{id}")
1334        } else {
1335            self.id.to_owned()
1336        };
1337        let is_open = state.search_open.get(&view_key).copied().unwrap_or(false);
1338        let now = if f.time().is_finite() { f.time().max(0.0) } else { 0.0 };
1339        let prev = state.search_view_motion.get(&view_key).copied().unwrap_or_default();
1340        let (next_m, anim) =
1341            eval_binary_ease_out_motion(prev, is_open, 0.24, now, f.reduced_motion());
1342        if state.search_view_motion.len() >= 64
1343            && !state.search_view_motion.contains_key(&view_key)
1344        {
1345            state.search_view_motion.clear();
1346        }
1347        state.search_view_motion.insert(view_key.clone(), next_m);
1348        if anim {
1349            f.continuous(b);
1350        }
1351        let progress = next_m.progress;
1352        if !is_open && progress <= 0.001 {
1353            return None;
1354        }
1355        let enabled = self.enabled && f.enabled;
1356        let rtl = state.rtl;
1357        let mut action = None;
1358        state.text.entry(view_key.clone()).or_default();
1359        state.input_types.insert(view_key.clone(), 0);
1360        if state.search_pending.remove(&view_key) {
1361            action = Some(self.id);
1362        }
1363        let surface_color = background_tint
1364            .or(explicit_background)
1365            .unwrap_or(match state.theme_style {
1366                AndroidTheme::Material3Light => Color(0xEC, 0xE6, 0xF0, 255),
1367                AndroidTheme::Material3Dark => Color(0x2B, 0x29, 0x30, 255),
1368                _ => t.surface_high,
1369            });
1370        let pushed_layer = if progress < 0.999 {
1371            f.push_layer(b, progress);
1372            true
1373        } else {
1374            false
1375        };
1376        let block_input = !is_open || progress < 0.01;
1377        let mut closed_now = false;
1378        f.without_input(block_input, |f| {
1379            f.paint_rect(b, scaled_radius.max(0.0), surface_color);
1380            let header_h = state.dp(56.0).min(b.height);
1381            let header_rect = Rect {
1382                x: b.x,
1383                y: b.y,
1384                width: b.width,
1385                height: header_h,
1386            };
1387            let mut query = state.text.get(&view_key).cloned().unwrap_or_default();
1388            let mut show_clear = !query.is_empty();
1389            let btn_s = state.dp(48.0).min(header_h).min(header_rect.width);
1390            let edge_pad = state.dp(4.0);
1391            if !spec.hide_nav && btn_s > 0.0 {
1392                let back_x = if rtl {
1393                    header_rect.x + header_rect.width - edge_pad - btn_s
1394                } else {
1395                    header_rect.x + edge_pad
1396                };
1397                let back_rect = Rect {
1398                    x: back_x,
1399                    y: header_rect.y + (header_h - btn_s) * 0.5,
1400                    width: btn_s,
1401                    height: btn_s,
1402                };
1403                let back_hit = f.target(
1404                    anonymous_child_id(id, 9810),
1405                    back_rect,
1406                    "Back",
1407                    enabled,
1408                    Role::Button,
1409                );
1410                f.state_layer(back_hit, btn_s * 0.5, t.text);
1411                f.focus_ring(back_hit);
1412                let icon_s = state.dp(24.0).min(btn_s);
1413                let icon_rect = Rect {
1414                    x: back_rect.x + (back_rect.width - icon_s) * 0.5,
1415                    y: back_rect.y + (back_rect.height - icon_s) * 0.5,
1416                    width: icon_s,
1417                    height: icon_s,
1418                };
1419                let back_icon = if spec.use_drawer_arrow && progress < 0.5 {
1420                    MaterialIcon::Menu
1421                } else if rtl {
1422                    MaterialIcon::ArrowForward
1423                } else {
1424                    MaterialIcon::ArrowBack
1425                };
1426                f.paint_material_icon(
1427                    icon_rect,
1428                    back_icon,
1429                    t.text.opacity(if enabled { 1.0 } else { 0.38 }),
1430                );
1431                if back_hit.clicked {
1432                    closed_now = true;
1433                }
1434            }
1435            if enabled && is_open && f.pressed_key(Key::Escape) {
1436                closed_now = true;
1437            }
1438            if show_clear && btn_s > 0.0 {
1439                let clear_x = if rtl {
1440                    header_rect.x + edge_pad
1441                } else {
1442                    header_rect.x + header_rect.width - edge_pad - btn_s
1443                };
1444                let clear_rect = Rect {
1445                    x: clear_x,
1446                    y: header_rect.y + (header_h - btn_s) * 0.5,
1447                    width: btn_s,
1448                    height: btn_s,
1449                };
1450                let clear_hit = f.target(
1451                    anonymous_child_id(id, 9811),
1452                    clear_rect,
1453                    "Clear search",
1454                    enabled,
1455                    Role::Button,
1456                );
1457                f.state_layer(clear_hit, btn_s * 0.5, t.text);
1458                f.focus_ring(clear_hit);
1459                let icon_s = state.dp(24.0).min(btn_s);
1460                let icon_rect = Rect {
1461                    x: clear_rect.x + (clear_rect.width - icon_s) * 0.5,
1462                    y: clear_rect.y + (clear_rect.height - icon_s) * 0.5,
1463                    width: icon_s,
1464                    height: icon_s,
1465                };
1466                f.paint_material_icon(
1467                    icon_rect,
1468                    MaterialIcon::Close,
1469                    t.on_surface_variant.opacity(if enabled { 1.0 } else { 0.38 }),
1470                );
1471                if clear_hit.clicked {
1472                    query.clear();
1473                    show_clear = false;
1474                    state.text.insert(view_key.clone(), String::new());
1475                    state.search_focus_requested.insert(view_key.clone());
1476                    f.request_focus(id);
1477                    action = Some(self.id);
1478                    f.continuous(b);
1479                }
1480            }
1481            let lead = if spec.hide_nav {
1482                state.dp(16.0)
1483            } else {
1484                state.dp(56.0)
1485            };
1486            let trail = if show_clear {
1487                state.dp(56.0)
1488            } else {
1489                state.dp(16.0)
1490            };
1491            let field_x = header_rect.x + if rtl { trail } else { lead };
1492            let field_w = (header_rect.width - lead - trail).max(0.0);
1493            let field_rect = Rect {
1494                x: field_x,
1495                y: header_rect.y,
1496                width: field_w,
1497                height: header_h,
1498            };
1499            let hint = if !spec.hint.is_empty() {
1500                spec.hint
1501            } else if !self.hint.is_empty() {
1502                self.hint
1503            } else {
1504                "Search"
1505            };
1506            let field_resp = f.target(id, field_rect, hint, enabled, Role::TextField);
1507            f.focus_ring(field_resp);
1508            if field_resp.clicked {
1509                f.request_focus(id);
1510                state.search_focus_requested.insert(view_key.clone());
1511            }
1512            if field_resp.focused
1513                && f.pressed_key(Key::Enter)
1514                && state.submit_search(&view_key)
1515            {
1516                state.search_pending.remove(&view_key);
1517                action = Some(self.id);
1518            }
1519            let (display, text_color) = if query.is_empty() {
1520                (
1521                    hint,
1522                    t.on_surface_variant.opacity(if enabled { 1.0 } else { 0.38 }),
1523                )
1524            } else {
1525                (
1526                    query.as_str(),
1527                    self.color
1528                        .unwrap_or(t.text)
1529                        .opacity(if enabled { 1.0 } else { 0.38 }),
1530                )
1531            };
1532            let text_size = if (self.text_size - 16.0).abs() < 0.001 {
1533                state.sp(16.0)
1534            } else {
1535                self.scaled_text_size(state)
1536            };
1537            f.within(field_rect, |f| {
1538                f.styled_text(
1539                    field_rect,
1540                    display,
1541                    text_color,
1542                    TextStyle {
1543                        size: text_size,
1544                        weight: if self.text_bold { 700 } else { 400 },
1545                        align: if rtl { 2 } else { 0 },
1546                        letter_spacing: self.letter_spacing_em * text_size,
1547                        ..TextStyle::default()
1548                    },
1549                );
1550            });
1551            let div_h = state.dp(1.0).min((b.height - header_h).max(0.0));
1552            if div_h > 0.0 {
1553                f.paint_rect(
1554                    Rect {
1555                        x: b.x,
1556                        y: b.y + header_h,
1557                        width: b.width,
1558                        height: div_h,
1559                    },
1560                    0.0,
1561                    t.outline_variant,
1562                );
1563            }
1564            let body_clip = Rect {
1565                x: b.x,
1566                y: b.y + header_h + div_h,
1567                width: b.width,
1568                height: (b.height - header_h - div_h).max(0.0),
1569            };
1570            if body_clip.width > 0.0 && body_clip.height > 0.0 && !self.children.is_empty() {
1571                let padding = self.resolved_padding(state);
1572                let body_inner = Rect {
1573                    x: body_clip.x + padding[0],
1574                    y: body_clip.y + padding[1],
1575                    width: (body_clip.width - padding[0] - padding[2]).max(0.0),
1576                    height: (body_clip.height - padding[1] - padding[3]).max(0.0),
1577                };
1578                let metrics = f.ui.text_metrics;
1579                f.within(body_clip, |f| {
1580                    if matches!(self.kind, Kind::Linear) {
1581                        let horiz = self.horizontal;
1582                        let main_avail = if horiz { body_inner.width } else { body_inner.height };
1583                        let lengths = self.linear_main_lengths(
1584                            horiz,
1585                            state,
1586                            main_avail,
1587                            body_inner.width,
1588                            metrics,
1589                            id,
1590                        );
1591                        let mut cursor = if horiz && rtl {
1592                            body_inner.x + body_inner.width
1593                        } else if horiz {
1594                            body_inner.x
1595                        } else {
1596                            body_inner.y
1597                        };
1598                        for (i, n) in self.children.iter().enumerate() {
1599                            if n.effective_visibility(state) == Visibility::Gone {
1600                                continue;
1601                            }
1602                            let cid = child_view_id(id, i, n);
1603                            let m = n.resolved_margin(state);
1604                            let len = lengths[i];
1605                            let mut r = Rect {
1606                                x: body_inner.x + m[0],
1607                                y: body_inner.y + m[1],
1608                                width: (body_inner.width - m[0] - m[2]).max(0.0),
1609                                height: (body_inner.height - m[1] - m[3]).max(0.0),
1610                            };
1611                            if horiz {
1612                                r.x = if rtl { cursor - m[2] - len } else { cursor + m[0] };
1613                                r.width = len;
1614                                let ext = len + m[0] + m[2];
1615                                if rtl { cursor -= ext; } else { cursor += ext; }
1616                                if let Size::Dp(h) = n.height {
1617                                    r.height = state.dp(h).min(r.height);
1618                                } else if matches!(n.height, Size::Wrap) {
1619                                    r.height = n
1620                                        .layout_intrinsic(false, state, r.width, metrics, cid)
1621                                        .min(r.height);
1622                                }
1623                            } else {
1624                                r.y = cursor + m[1];
1625                                r.height = len;
1626                                cursor += len + m[1] + m[3];
1627                                if let Size::Dp(w) = n.width {
1628                                    r.width = state.dp(w).min(r.width);
1629                                } else if matches!(n.width, Size::Wrap) {
1630                                    r.width = n
1631                                        .layout_intrinsic(true, state, r.width, metrics, cid)
1632                                        .min(r.width);
1633                                }
1634                                let right = match n.layout_gravity[0] {
1635                                    0 => rtl,
1636                                    2 => !rtl,
1637                                    4 => true,
1638                                    _ => false,
1639                                };
1640                                r.x = if n.layout_gravity[0] == 1 {
1641                                    body_inner.x + (body_inner.width - r.width) * 0.5 + m[0] - m[2]
1642                                } else if right {
1643                                    body_inner.x + body_inner.width - r.width - m[2]
1644                                } else {
1645                                    body_inner.x + m[0]
1646                                };
1647                            }
1648                            let mut child_act = None;
1649                            if self.clip_children_disabled {
1650                                child_act = n.draw(f, r, state, cid);
1651                            } else {
1652                                f.within(r, |f| {
1653                                    child_act = n.draw(f, r, state, cid);
1654                                });
1655                            }
1656                            if child_act.is_some() {
1657                                action = child_act;
1658                            }
1659                        }
1660                    } else {
1661                        for (i, n) in self.children.iter().enumerate() {
1662                            if n.effective_visibility(state) == Visibility::Gone {
1663                                continue;
1664                            }
1665                            let cid = child_view_id(id, i, n);
1666                            let m = n.resolved_margin(state);
1667                            let mut r = Rect {
1668                                x: body_inner.x + m[0],
1669                                y: body_inner.y + m[1],
1670                                width: (body_inner.width - m[0] - m[2]).max(0.0),
1671                                height: (body_inner.height - m[1] - m[3]).max(0.0),
1672                            };
1673                            if let Size::Dp(w) = n.width {
1674                                r.width = state.dp(w);
1675                            } else if matches!(n.width, Size::Wrap) {
1676                                r.width = n
1677                                    .layout_intrinsic(true, state, r.width, metrics, cid)
1678                                    .min(r.width);
1679                            }
1680                            if let Size::Dp(h) = n.height {
1681                                r.height = state.dp(h);
1682                            } else if matches!(n.height, Size::Wrap) {
1683                                r.height = n
1684                                    .layout_intrinsic(false, state, r.width, metrics, cid)
1685                                    .min(r.height);
1686                            }
1687                            let right = match n.layout_gravity[0] {
1688                                0 => rtl,
1689                                2 => !rtl,
1690                                4 => true,
1691                                _ => false,
1692                            };
1693                            r.x = if n.layout_gravity[0] == 1 {
1694                                body_inner.x + (body_inner.width - r.width) * 0.5 + m[0] - m[2]
1695                            } else if right {
1696                                body_inner.x + body_inner.width - r.width - m[2]
1697                            } else {
1698                                body_inner.x + m[0]
1699                            };
1700                            r.y = match n.layout_gravity[1] {
1701                                1 => body_inner.y + (body_inner.height - r.height) * 0.5 + m[1] - m[3],
1702                                2 => body_inner.y + body_inner.height - r.height - m[3],
1703                                _ => body_inner.y + m[1],
1704                            };
1705                            let mut child_act = None;
1706                            if self.clip_children_disabled {
1707                                child_act = n.draw(f, r, state, cid);
1708                            } else {
1709                                f.within(r, |f| {
1710                                    child_act = n.draw(f, r, state, cid);
1711                                });
1712                            }
1713                            if child_act.is_some() {
1714                                action = child_act;
1715                            }
1716                        }
1717                    }
1718                });
1719            }
1720        });
1721        if closed_now {
1722            state.search_open.insert(view_key.clone(), false);
1723            let (closing_m, _closing_anim) =
1724                eval_binary_ease_out_motion(next_m, false, 0.24, now, f.reduced_motion());
1725            state.search_view_motion.insert(view_key, closing_m);
1726            f.continuous(b);
1727        }
1728        if pushed_layer {
1729            f.pop_layer();
1730        }
1731        action
1732    }
1733    pub(super) fn draw_carousel_layout(
1734        &'static self,
1735        f: &mut Frame<'_>,
1736        inner: Rect,
1737        state: &mut LayoutState,
1738        id: u64,
1739        spec: CarouselLayoutSpec,
1740        t: Theme,
1741    ) -> Option<&'static str> {
1742        let key = if self.id.is_empty() {
1743            format!("#{id}")
1744        } else {
1745            self.id.to_owned()
1746        };
1747        let (child_source, child_parent_id): (Option<&'static [Node]>, u64) =
1748            if matches!(self.kind, Kind::HorizontalScroll) {
1749                if self.children.len() == 1
1750                    && matches!(self.children[0].kind, Kind::Linear)
1751                    && !self.children[0].children.is_empty()
1752                    && !self.children[0].is_carousel_item()
1753                {
1754                    (
1755                        Some(self.children[0].children),
1756                        child_view_id(id, 0, &self.children[0]),
1757                    )
1758                } else {
1759                    (Some(self.children), id)
1760                }
1761            } else if matches!(self.kind, Kind::Linear) {
1762                (Some(self.children), id)
1763            } else if !self.children.is_empty() {
1764                (Some(self.children), id)
1765            } else {
1766                (None, id)
1767            };
1768
1769        let visible_children: Vec<(usize, &'static Node)> = if let Some(nodes) = child_source {
1770            nodes
1771                .iter()
1772                .enumerate()
1773                .filter(|(_, n)| n.effective_visibility(state) != Visibility::Gone)
1774                .collect()
1775        } else {
1776            Vec::new()
1777        };
1778        let adapter_entries: Vec<String> = if child_source.is_none() {
1779            state
1780                .list_items
1781                .entry(key.clone())
1782                .or_insert_with(|| {
1783                    self.relative_rules
1784                        .iter()
1785                        .filter(|r| r.kind == 82)
1786                        .map(|r| r.anchor.to_owned())
1787                        .collect()
1788                })
1789                .clone()
1790        } else {
1791            Vec::new()
1792        };
1793        let n = if child_source.is_some() {
1794            visible_children.len()
1795        } else {
1796            adapter_entries.len()
1797        };
1798        if n == 0 {
1799            return None;
1800        }
1801        let viewport_w = inner.width.max(1.0);
1802        let gap = state.dp(spec.spacing_dp.max(0.0));
1803        let (focal_w, step, max_scroll) = match spec.strategy {
1804            CarouselStrategy::FullScreen => {
1805                let fw = viewport_w;
1806                let st = fw + gap;
1807                (fw, st, ((n - 1) as f32 * st).max(0.0))
1808            }
1809            CarouselStrategy::Uncontained => {
1810                let fw = (viewport_w * 0.60).max(1.0);
1811                let st = fw + gap;
1812                let ms = if spec.align == CarouselAlign::Center {
1813                    ((n - 1) as f32 * st).max(0.0)
1814                } else {
1815                    (n as f32 * fw + (n - 1) as f32 * gap - viewport_w).max(0.0)
1816                };
1817                (fw, st, ms)
1818            }
1819            CarouselStrategy::Hero => {
1820                let fw = (viewport_w * 0.78).max(1.0);
1821                let st = fw + gap;
1822                (fw, st, ((n - 1) as f32 * st).max(0.0))
1823            }
1824            CarouselStrategy::MultiBrowse => {
1825                let fw = (viewport_w * 0.55).max(1.0);
1826                let st = fw + gap;
1827                (fw, st, ((n - 1) as f32 * st).max(0.0))
1828            }
1829        };
1830        let _ = focal_w;
1831        let now = if f.time().is_finite() { f.time().max(0.0) } else { 0.0 };
1832        let rtl = state.rtl;
1833        let enabled = self.enabled && f.enabled;
1834        let mut cm = state.carousel_motion.remove(&key).unwrap_or_default();
1835        let mut offset = state
1836            .offsets
1837            .get(&key)
1838            .copied()
1839            .filter(|v| v.is_finite())
1840            .unwrap_or(0.0)
1841            .clamp(0.0, max_scroll);
1842        if let Some((start, from, to, dur)) = cm.snap {
1843            if f.reduced_motion() || dur <= 0.0 {
1844                offset = to.clamp(0.0, max_scroll);
1845                cm.snap = None;
1846            } else {
1847                let p = ((now - start) / dur).clamp(0.0, 1.0) as f32;
1848                let ease = 1.0 - (1.0 - p) * (1.0 - p);
1849                offset = (from + (to - from) * ease).clamp(0.0, max_scroll);
1850                if p >= 1.0 {
1851                    offset = to.clamp(0.0, max_scroll);
1852                    cm.snap = None;
1853                } else {
1854                    f.continuous(inner);
1855                }
1856            }
1857        }
1858        let prev_input = f.input;
1859        let offset_before_sv = offset;
1860        let touch_dragging = f.scroll_viewport_horizontal_rtl(id, inner, &mut offset, max_scroll, rtl);
1861        let wheel_moved = (offset - offset_before_sv).abs() > 0.01 && !touch_dragging;
1862        if wheel_moved {
1863            cm.snap = None;
1864        }
1865        let compute_snap_target = |cur_scroll: f32, v_scroll: f32| -> f32 {
1866            if max_scroll <= 0.0 || n <= 1 {
1867                return 0.0;
1868            }
1869            let mut candidates: Vec<f32> = (0..n)
1870                .map(|k| (k as f32 * step).clamp(0.0, max_scroll))
1871                .collect();
1872            if !candidates.last().is_some_and(|&v| (v - max_scroll).abs() < 0.5) {
1873                candidates.push(max_scroll);
1874            }
1875            let flick_v = state.dp(400.0);
1876            let hint = if v_scroll > flick_v {
1877                (cur_scroll + step * 0.45).min(max_scroll)
1878            } else if v_scroll < -flick_v {
1879                (cur_scroll - step * 0.45).max(0.0)
1880            } else {
1881                cur_scroll
1882            };
1883            candidates
1884                .into_iter()
1885                .min_by(|a, b| {
1886                    (a - hint)
1887                        .abs()
1888                        .partial_cmp(&(b - hint).abs())
1889                        .unwrap_or(std::cmp::Ordering::Equal)
1890                })
1891                .unwrap_or(0.0)
1892        };
1893        if touch_dragging {
1894            cm.was_touch_dragging = true;
1895            cm.snap = None;
1896        }
1897        if cm.was_touch_dragging
1898            && (prev_input.released || prev_input.cancelled || prev_input.blurred)
1899        {
1900            cm.was_touch_dragging = false;
1901            f.cancel_scroll(id);
1902            let target = compute_snap_target(offset, 0.0);
1903            if f.reduced_motion() || (offset - target).abs() <= 0.5 {
1904                offset = target;
1905                cm.snap = None;
1906            } else {
1907                cm.snap = Some((now, offset, target, 0.24));
1908                f.continuous(inner);
1909            }
1910        }
1911        let mut mouse_was_dragging = false;
1912        if enabled && prev_input.pointer_kind != PointerKind::Touch {
1913            let inside = prev_input
1914                .pointer
1915                .is_some_and(|p| inner.intersect(f.clip).contains(p));
1916            if prev_input.pressed && inside {
1917                cm.origin = prev_input.pointer;
1918                cm.drag_base = offset;
1919                cm.dragging = false;
1920                cm.snap = None;
1921                cm.samples.clear();
1922                if let Some(p) = prev_input.pointer {
1923                    cm.samples.push((now, p[0]));
1924                }
1925            }
1926            if let (Some(origin), Some(ptr)) = (cm.origin, prev_input.pointer)
1927                && !prev_input.cancelled
1928                && !prev_input.blurred
1929            {
1930                if cm.samples.last().map_or(true, |&(_, x)| (x - ptr[0]).abs() > 0.01) {
1931                    cm.samples.push((now, ptr[0]));
1932                    if cm.samples.len() > 8 {
1933                        cm.samples.remove(0);
1934                    }
1935                }
1936                let dx = ptr[0] - origin[0];
1937                let dy = ptr[1] - origin[1];
1938                let slop = state.dp(8.0);
1939                if !cm.dragging && dx.abs() > slop && dx.abs() >= dy.abs() {
1940                    cm.dragging = true;
1941                    f.ui.active = None;
1942                }
1943                if cm.dragging {
1944                    let delta_scroll = if rtl { dx } else { -dx };
1945                    offset = (cm.drag_base + delta_scroll).clamp(0.0, max_scroll);
1946                    if !prev_input.released {
1947                        f.continuous(inner);
1948                    }
1949                }
1950            }
1951            mouse_was_dragging = cm.dragging;
1952            if cm.origin.is_some()
1953                && (prev_input.released || prev_input.cancelled || prev_input.blurred)
1954            {
1955                if cm.dragging {
1956                    let v_scroll = if !prev_input.cancelled && !prev_input.blurred {
1957                        let vx = pointer_velocity(&cm.samples, now);
1958                        if rtl { vx } else { -vx }
1959                    } else {
1960                        0.0
1961                    };
1962                    let target = compute_snap_target(offset, v_scroll);
1963                    if f.reduced_motion() || (offset - target).abs() <= 0.5 {
1964                        offset = target;
1965                        cm.snap = None;
1966                    } else {
1967                        cm.snap = Some((now, offset, target, 0.24));
1968                        f.continuous(inner);
1969                    }
1970                }
1971                cm.origin = None;
1972                cm.dragging = false;
1973                cm.samples.clear();
1974            }
1975        } else if !enabled {
1976            cm.origin = None;
1977            cm.dragging = false;
1978            cm.samples.clear();
1979        }
1980        offset = offset.clamp(0.0, max_scroll);
1981        state.offsets.insert(key.clone(), offset);
1982        let f_idx = if step > 0.0 {
1983            (offset / step).clamp(0.0, (n - 1) as f32)
1984        } else {
1985            0.0
1986        };
1987        state
1988            .selected_index
1989            .insert(key.clone(), (f_idx.round() as usize).min(n - 1));
1990        if state.carousel_motion.len() >= 64 && !state.carousel_motion.contains_key(&key) {
1991            state.carousel_motion.clear();
1992        }
1993        state.carousel_motion.insert(key.clone(), cm);
1994
1995        let widths: Vec<f32> = (0..n)
1996            .map(|i| match spec.strategy {
1997                CarouselStrategy::FullScreen => viewport_w,
1998                CarouselStrategy::Uncontained => (viewport_w * 0.60).max(1.0),
1999                CarouselStrategy::Hero => {
2000                    let large = viewport_w * 0.78;
2001                    let small = viewport_w * 0.18;
2002                    let d = (i as f32 - f_idx).abs();
2003                    if d <= 1.0 {
2004                        large + (small - large) * d
2005                    } else {
2006                        small
2007                    }
2008                }
2009                CarouselStrategy::MultiBrowse => {
2010                    let large = viewport_w * 0.55;
2011                    let med = viewport_w * 0.26;
2012                    let small = viewport_w * 0.12;
2013                    let d = (i as f32 - f_idx).abs();
2014                    if d <= 1.0 {
2015                        large + (med - large) * d
2016                    } else if d <= 2.0 {
2017                        med + (small - med) * (d - 1.0)
2018                    } else {
2019                        small
2020                    }
2021                }
2022            })
2023            .collect();
2024        let mut raw_x = Vec::with_capacity(n);
2025        let mut cursor_x = 0.0_f32;
2026        for &w in &widths {
2027            raw_x.push(cursor_x);
2028            cursor_x += w + gap;
2029        }
2030        let logical_x: Vec<f32> = match spec.strategy {
2031            CarouselStrategy::FullScreen => raw_x.iter().map(|&x| x - offset).collect(),
2032            CarouselStrategy::Uncontained if spec.align == CarouselAlign::Start => {
2033                raw_x.iter().map(|&x| x - offset).collect()
2034            }
2035            _ => {
2036                let k0 = (f_idx.floor() as usize).min(n - 1);
2037                let k1 = (k0 + 1).min(n - 1);
2038                let frac = (f_idx - k0 as f32).clamp(0.0, 1.0);
2039                let shift = if spec.align == CarouselAlign::Center {
2040                    let c0 = raw_x[k0] + widths[k0] * 0.5;
2041                    let c1 = raw_x[k1] + widths[k1] * 0.5;
2042                    viewport_w * 0.5 - (c0 + (c1 - c0) * frac)
2043                } else {
2044                    let s0 = raw_x[k0];
2045                    let s1 = raw_x[k1];
2046                    -(s0 + (s1 - s0) * frac)
2047                };
2048                raw_x.iter().map(|&x| x + shift).collect()
2049            }
2050        };
2051
2052        let any_dragging = touch_dragging || mouse_was_dragging;
2053        let mut action = None;
2054        let default_mask_r = state.dp(28.0);
2055        if child_source.is_some() {
2056            f.without_input(any_dragging, |f| {
2057                f.within(inner, |f| {
2058                    for (pos, &(orig_idx, child)) in visible_children.iter().enumerate() {
2059                        let w = widths[pos];
2060                        let phys_x = if rtl {
2061                            inner.x + inner.width - logical_x[pos] - w
2062                        } else {
2063                            inner.x + logical_x[pos]
2064                        };
2065                        let m = child.resolved_margin(state);
2066                        let avail_h = (inner.height - m[1] - m[3]).max(0.0);
2067                        let cid = child_view_id(child_parent_id, orig_idx, child);
2068                        let h = match child.height {
2069                            Size::Dp(v) => state.dp(v).min(avail_h),
2070                            Size::Wrap => child
2071                                .layout_intrinsic(false, state, w, f.ui.text_metrics, cid)
2072                                .min(avail_h)
2073                                .max(1.0),
2074                            Size::Match => avail_h,
2075                        };
2076                        let y = match child.layout_gravity[1] {
2077                            1 => inner.y + (inner.height - h) * 0.5 + m[1] - m[3],
2078                            2 => inner.y + inner.height - h - m[3],
2079                            _ => inner.y + m[1],
2080                        };
2081                        let item_rect = Rect { x: phys_x, y, width: w, height: h };
2082                        let vis = item_rect.intersect(inner);
2083                        if vis.width <= 0.0 || vis.height <= 0.0 {
2084                            continue;
2085                        }
2086                        let (is_oval, mask_radii) = if let Some(cr) = child.resolved_corner_radii(state) {
2087                            (false, cr)
2088                        } else if child.radius < 0.0 {
2089                            (true, [0.0; 4])
2090                        } else if child.radius > 0.0 {
2091                            (false, [state.dp(child.radius); 4])
2092                        } else {
2093                            (false, [default_mask_r; 4])
2094                        };
2095                        let cmd_start = f.commands.len();
2096                        let mut child_act = None;
2097                        f.within(item_rect, |f| {
2098                            child_act = child.draw(f, item_rect, state, cid);
2099                        });
2100                        clip_commands_to_rounded_outline(f, cmd_start, item_rect, is_oval, mask_radii);
2101                        if child_act.is_some() {
2102                            action = child_act;
2103                        }
2104                    }
2105                });
2106            });
2107        } else {
2108            let template = state.list_templates.get(&key).copied();
2109            let mut row_state = if template.is_some() || state.list_item_bindings.contains_key(&key)
2110            {
2111                Some(spinner_template_state(state, rtl))
2112            } else {
2113                None
2114            };
2115            let bindings = state.list_item_bindings.get(&key).cloned();
2116            let flags = state.list_enabled.get(&key).cloned();
2117            let item_ids = state.list_item_ids.get(&key).cloned();
2118            let checked = state.list_checked.get(&key).cloned().unwrap_or_default();
2119            let mut chosen = None;
2120            f.without_input(any_dragging, |f| {
2121                f.within(inner, |f| {
2122                    for (pos, label) in adapter_entries.iter().enumerate() {
2123                        let w = widths[pos];
2124                        let phys_x = if rtl {
2125                            inner.x + inner.width - logical_x[pos] - w
2126                        } else {
2127                            inner.x + logical_x[pos]
2128                        };
2129                        let item_rect = Rect {
2130                            x: phys_x,
2131                            y: inner.y,
2132                            width: w,
2133                            height: inner.height,
2134                        };
2135                        let vis = item_rect.intersect(inner);
2136                        if vis.width <= 0.0 || vis.height <= 0.0 {
2137                            continue;
2138                        }
2139                        let item_key = item_ids
2140                            .as_ref()
2141                            .and_then(|ids| ids.get(pos))
2142                            .map_or(pos as u64, |v| *v as u64);
2143                        let item_enabled =
2144                            enabled && flags.as_ref().and_then(|v| v.get(pos)).copied().unwrap_or(true);
2145                        let row_id = id.wrapping_mul(0x9e3779b97f4a7c15).wrapping_add(item_key);
2146                        let binding = bindings.as_ref().and_then(|items| items.get(&pos));
2147                        let item_template = adapter_item_template(template, binding);
2148                        let mask_r = item_template
2149                            .filter(|tmpl| tmpl.row.radius > 0.0)
2150                            .map_or(default_mask_r, |tmpl| state.dp(tmpl.row.radius));
2151                        let cmd_start = f.commands.len();
2152                        f.within(item_rect, |f| {
2153                            let r = f.target(row_id, item_rect, label, item_enabled, Role::Button);
2154                            if let (Some(tmpl), Some(rs)) = (item_template, row_state.as_mut()) {
2155                                paint_spinner_template(
2156                                    f,
2157                                    tmpl.row,
2158                                    tmpl.text_id,
2159                                    label,
2160                                    item_rect,
2161                                    rs,
2162                                    anonymous_child_id(id, 1024 + pos),
2163                                    r,
2164                                    checked.contains(&pos),
2165                                    binding,
2166                                );
2167                            } else {
2168                                let fill = if checked.contains(&pos) {
2169                                    t.primary_container
2170                                } else {
2171                                    t.surface_high
2172                                };
2173                                f.paint_rect(item_rect, mask_r, fill);
2174                                f.state_layer(r, mask_r, t.text);
2175                                let style = TextStyle {
2176                                    align: if rtl { 2 } else { 0 },
2177                                    padding: state.dp(12.0),
2178                                    ..TextStyle::default()
2179                                };
2180                                f.styled_text(
2181                                    item_rect,
2182                                    label,
2183                                    t.text.opacity(if r.enabled { 1.0 } else { 0.38 }),
2184                                    style,
2185                                );
2186                            }
2187                            if r.clicked {
2188                                chosen = Some(pos);
2189                            }
2190                        });
2191                        clip_commands_to_rounded_outline(f, cmd_start, item_rect, false, [mask_r; 4]);
2192                    }
2193                });
2194            });
2195            if let Some(idx) = chosen {
2196                state.list_clicked.insert(key, idx);
2197                action = Some(self.id);
2198            }
2199        }
2200        f.input = prev_input;
2201        action
2202    }
2203}