1mod button;
3mod calendar;
4mod choice;
5mod clip;
6mod delay_button;
7mod drag;
8mod edit;
9mod file_drop;
10mod flow;
11mod focus_observers;
12mod focus_scope;
13mod geometry;
14mod grid;
15mod group_box;
16mod history;
17mod hover_observers;
18mod image;
19mod input;
20mod keyboard;
21mod label;
22mod linear;
23mod list_anchor;
24mod menu;
25mod modal;
26mod overscroll;
27mod page;
28mod page_indicator;
29mod password;
30mod path_view;
31mod pointer_events;
32mod popup;
33mod range;
34mod row_layout;
35mod scale_rotate;
36#[doc(hidden)]
37pub mod scale_rotate_gestures;
38mod scroll_bar;
39mod scroll_gesture;
40mod search;
41mod selection;
42mod shortcut;
43mod spin;
44mod split;
45mod stack_transition;
46mod styled_text;
47mod swipe_delegate;
48mod swipe_gesture;
49mod tab_move;
50mod table;
51mod table_drag_selection;
52mod text_area;
53mod tooltip;
54mod transform;
55mod tree;
56mod tumbler;
57mod view_cells;
58mod viewport;
59mod visual_text;
60mod window_chrome;
61pub use button::{ButtonContent, ButtonPlacement};
62pub use calendar::{CalendarDay, CalendarGeometry, CalendarWeek};
63pub use choice::{ChoiceKey, ChoiceMenu, ComboCompletion, ComboGeometry};
64use clip::ClipChain;
65pub use clip::{RoundedClip, corner_radii, normalize_radii};
66pub use delay_button::ButtonHoldEvent;
67pub use drag::{DragDispatch, DragUpdate};
68#[doc(hidden)]
69pub use edit::selection_drag_axis;
70pub use edit::{EditAction, TextEdit, TextEditContext, TextPosition};
71pub use file_drop::{FileDragInput, FileDropScope, TextDrop};
72pub use focus_observers::{FocusDelivery, FocusObservers};
73pub use geometry::{Point, Rect, Size};
74pub use group_box::group_header;
75pub use history::EditSource;
76pub use hover_observers::{HoverDelivery, HoverObservers};
77pub use image::{ImagePlacement, ImagePresentation, ImageRegion, fitted_rect, tile_extent};
78pub use input::{
79 ActivationKey, ControlInput, Interaction, NavigationKey, RangeInput, ScrollBarUpdate,
80 SliderKey, SplitResize, TableEditCommit, TableEditTarget, TablePasteDestination,
81 TableSelectionKey, Target, TextLinkTarget, WheelAdjustment, WheelRoute, swipe_view_selection,
82};
83pub use keyboard::KeyRoute;
84pub use label::{
85 LabelLayout, LabelLine, LabelPlan, PlannedLabelLine, TextAlignment, elide_to_width,
86 uses_label_layout,
87};
88pub use menu::{MenuEntry, MenuKey, MenuPanel, MenuRow, NativeTextMenu};
89pub use modal::{dialog_title_height, drawer_grip};
90pub use overscroll::OverscrollFrame;
91pub use page_indicator::{PageIndicatorGeometry, PageMarker};
92pub use password::PasswordMask;
93pub use pointer_events::{ButtonClick, PointerDelivery, PointerSequence, pointer_click_follows};
94pub use range::{ColorPlaneGeometry, DialGeometry, SliderGeometry, progress_fill_bounds};
95#[doc(hidden)]
96pub use row_layout::{RowLayoutCache, RowLayoutStats};
97pub use scale_rotate::{ScaleRotateTarget, TouchTransform, touch_centroid};
98pub use scroll_bar::ScrollBarGeometry;
99pub use scroll_gesture::{ScrollGestureEnd, ScrollGestureKind};
100pub use search::SearchGeometry;
101pub use selection::{TAB_LABEL_SIZE, tab_content_rect, tab_font_size};
102pub use shortcut::{MenuShortcut, ShortcutKey, ShortcutModifiers, ShortcutOutcome};
103pub use spin::SpinGeometry;
104pub use split::{SplitGeometry, SplitHandle, SplitHandleRange};
105pub use stack_transition::{StackSlide, StackTransitions};
106use std::{collections::BTreeMap, rc::Rc, sync::Arc};
107pub use styled_text::{StyledFragment, StyledTextLayout};
108pub use swipe_delegate::SwipeDelegateGeometry;
109pub use swipe_gesture::SwipeDelivery;
110pub use table::{TableGeometry, table_heading_font_size};
111pub use text_area::{
112 TextAreaLayout, TextAreaMotion, text_editor_line_bounds, text_editor_viewport,
113};
114pub use tooltip::{TooltipPopup, TouchTooltip, layout_tooltip, tooltip_text};
115pub use transform::Affine;
116use transform::TransformSpace;
117pub use tree::TreeRowGeometry;
118pub use tumbler::{TumblerGeometry, TumblerRow, TumblerScroll};
119pub use view_cells::ListSectionHeader;
120use view_cells::ViewCells;
121pub use viewport::{LayoutObservers, ScrollDelivery, ViewportObservers};
122pub use visual_text::{VisualGrapheme, VisualTextLine};
123pub use window_chrome::WindowResizeEdge;
124use xrack_runtime::{
125 Component, LayoutDirection, ListMetrics, Node, Orientation, RowKey, SelectionTarget,
126 group_index, is_font_family_choice, is_modal_overlay, is_window_overlay,
127 set_font_family_choices,
128};
129
130#[cfg(test)]
131mod tests;
132
133pub const DEFAULT_FONT_SIZE: f32 = 16.0;
134
135pub trait TextMeasurer {
136 fn measure(&mut self, text: &str, font_size: f32, max_width: f32) -> Size;
137
138 fn begin_window(&mut self, _scene: &Node) {}
139
140 fn font_families(&self) -> &[String] {
142 &[]
143 }
144
145 fn default_font_size(&self) -> Option<f32> {
146 None
147 }
148
149 #[doc(hidden)]
151 fn text_scale(&self) -> f32 {
152 1.0
153 }
154
155 fn font_size(&self, node: &Node) -> f32 {
156 node.font_size()
157 .or_else(|| self.default_font_size())
158 .unwrap_or(DEFAULT_FONT_SIZE)
159 .clamp(1.0, 512.0)
160 }
161
162 fn measure_node(&mut self, node: &Node, text: &str, max_width: f32) -> Size {
163 self.measure(text, self.font_size(node), max_width)
164 }
165
166 #[doc(hidden)]
167 fn measure_node_at_size(
168 &mut self,
169 _node: &Node,
170 text: &str,
171 size: f32,
172 max_width: f32,
173 ) -> Size {
174 self.measure(text, size, max_width)
175 }
176
177 fn layout_styled_text(&mut self, node: &Node, available: Size) -> Option<StyledTextLayout> {
178 let document = node.styled_text("text")?;
179 let size = self.font_size(node);
180 Some(StyledTextLayout::new(
181 node,
182 document,
183 available,
184 size,
185 |text, _| self.measure_node(node, text, f32::MAX).width,
186 ))
187 }
188
189 fn measure_label(&mut self, node: &Node, max_width: f32) -> Size {
190 if let Some(plan) = self.layout_styled_text(node, Size::new(max_width, f32::INFINITY)) {
191 return plan.size;
192 }
193 LabelLayout::with_font_size(
194 node,
195 Size::new(max_width, f32::INFINITY),
196 self.font_size(node),
197 |value| self.measure_node(node, value, f32::MAX).width,
198 )
199 .size
200 }
201}
202
203#[derive(Clone, Debug, PartialEq)]
204struct TransformPlacement {
205 local: Affine,
206 parent_clip: Rect,
207 parent_space: Option<Arc<TransformSpace>>,
208}
209
210#[derive(Clone, Debug, PartialEq)]
211pub struct LayoutNode {
212 pub bounds: Rect,
213 pub clip: Rect,
215 pub visible: bool,
216 pub enabled: bool,
217 pub layout_direction: LayoutDirection,
218 direction_override: Option<LayoutDirection>,
219 pub(crate) content_bounds: Option<Box<Rect>>,
220 pub scroll: Option<ScrollLayout>,
221 list_section_headers: Option<Box<[ListSectionHeader]>>,
222 horizontal_scroll: Option<ScrollLayout>,
223 horizontal_scroll_reversed: bool,
224 viewport_handle: Option<xrack_runtime::ViewportHandle>,
225 nested_list: Option<xrack_runtime::ListRowRenderer>,
226 missing_list_rows: bool,
227 missing_descendant_list_rows: bool,
228 attached_scroll_bar: Option<Box<scroll_bar::AttachedScrollBar>>,
229 mouse_drag_pan: bool,
230 middle_mouse_pan: bool,
231 pan_axes: [bool; 2],
232 elastic: Option<overscroll::ElasticOptions>,
233 pull_to_refresh: bool,
234 pub table: Option<Box<TableGeometry>>,
235 pub split: Option<Box<SplitGeometry>>,
236 pub tab_header: Option<Rect>,
238 pub tab_close: Option<Rect>,
240 tab_strip: Option<Rect>,
241 pub tumbler: Option<Box<TumblerGeometry>>,
242 pub switch_position: Option<f32>,
244 pub swipe_delegate: Option<Box<SwipeDelegateGeometry>>,
245 #[doc(hidden)]
246 pub swipe_preview: Option<Box<LayoutNode>>,
247 pub styled_text: Option<Box<StyledTextLayout>>,
248 modal_title: Option<Box<label::TitleLayout>>,
249 group_title: Option<Box<label::TitleLayout>>,
250 font_size: f32,
251 overlays: Option<Box<modal::OverlayIndex>>,
252 paint_order: Option<xrack_runtime::ScenePlanSlice<usize>>,
253 overflow: bool,
254 child_shape: Option<RoundedClip>,
255 ancestor_shapes: Option<Arc<ClipChain>>,
256 space: Option<Arc<TransformSpace>>,
257 transform: Option<Box<TransformPlacement>>,
258 table_pane: Option<Box<(Rect, Affine)>>,
259 table_column_window: xrack_runtime::TableColumnWindow,
260 pub children: Vec<LayoutNode>,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq)]
264pub struct ScrollLayout {
265 pub offset: f32,
266 pub max_offset: f32,
267}
268
269impl ScrollLayout {
270 pub(crate) fn new(requested: f32, max_offset: f32) -> Self {
271 let max_offset = max_offset.max(0.0);
272 Self {
273 offset: requested.clamp(0.0, max_offset),
274 max_offset,
275 }
276 }
277
278 pub(crate) fn revealing(self, top: f32, height: f32, viewport: f32) -> Self {
279 let offset = if top < self.offset {
280 top
281 } else {
282 self.offset.max(top + height - viewport)
283 };
284 Self::new(offset, self.max_offset)
285 }
286}
287
288#[doc(hidden)]
290#[derive(Default)]
291pub struct WindowEffects<'a> {
292 pub button_animations: Vec<&'a xrack_runtime::ButtonPressHandle>,
293 pub timers: Vec<&'a xrack_runtime::TimerRegistration>,
294 pub dialogs: Vec<&'a xrack_runtime::NativeDialogRegistration>,
295 pub media: Vec<&'a xrack_runtime::MediaRegistration>,
296 pub playback: Vec<(&'a Rc<xrack_runtime::ImagePlaybackRegistration>, bool)>,
297}
298
299impl<'a> WindowEffects<'a> {
300 pub fn collect(node: &'a Node, layout: &LayoutNode) -> Self {
301 let mut effects = Self::default();
302 effects.extend(node, layout);
303 effects
304 }
305
306 fn extend(&mut self, node: &'a Node, layout: &LayoutNode) {
307 if node.expander_collapsed() {
308 return;
309 }
310 if let Some(handle) = node
311 .button_press_handle
312 .as_ref()
313 .filter(|handle| handle.supports_animation())
314 {
315 self.button_animations.push(handle);
316 }
317 self.timers.extend(layout.timer_registrations(node));
318 if layout.visible && layout.enabled {
319 self.dialogs.extend(&node.native_dialogs);
320 }
321 self.playback.extend(layout.image_playback(node));
322 if layout.visible {
323 self.media.extend(node.media.as_ref());
324 }
325 self.media.extend(&node.sound_effects);
326 for (child, item) in node.children.iter().zip(&layout.children) {
327 self.extend(child, item);
328 }
329 }
330}
331
332impl LayoutNode {
333 pub(crate) fn popup_typography(&self) -> popup::PopupTypography {
334 self.overlays
335 .as_ref()
336 .map_or_else(popup::PopupTypography::default, |index| {
337 index.popup_typography
338 })
339 }
340
341 pub(crate) fn floating_keyboard(&self) -> Option<Rect> {
342 self.overlays
343 .as_ref()
344 .and_then(|index| index.floating_keyboard)
345 }
346
347 #[doc(hidden)]
349 pub fn grid_view_columns(&self, node: &Node) -> usize {
350 ViewCells::new(node, self.bounds.width).columns
351 }
352
353 pub fn list_section_headers(&self) -> &[ListSectionHeader] {
354 self.list_section_headers.as_deref().unwrap_or_default()
355 }
356
357 pub fn layout_direction_override(&self) -> Option<LayoutDirection> {
359 self.direction_override
360 }
361
362 #[doc(hidden)]
363 pub fn has_missing_list_rows(&self) -> bool {
364 self.missing_list_rows || self.missing_descendant_list_rows
365 }
366
367 #[doc(hidden)]
368 pub fn timer_registrations<'a>(
369 &self,
370 node: &'a Node,
371 ) -> &'a [xrack_runtime::TimerRegistration] {
372 if self.visible { &node.timers } else { &[] }
373 }
374
375 pub fn image_playback<'a>(
376 &self,
377 node: &'a Node,
378 ) -> Option<(&'a Rc<xrack_runtime::ImagePlaybackRegistration>, bool)> {
379 let registration = node.image_playback.as_ref()?;
380 let clip = self.clip_rect(self.bounds);
381 Some((
382 registration,
383 self.visible && clip.width > 0.0 && clip.height > 0.0,
384 ))
385 }
386
387 pub fn allows_overflow(&self) -> bool {
388 self.overflow
389 }
390
391 pub fn child_clip_shape(&self) -> Option<RoundedClip> {
392 self.child_shape
393 }
394
395 pub fn local_transform(&self) -> Affine {
396 self.transform
397 .as_deref()
398 .map_or(Affine::IDENTITY, |transform| transform.local)
399 }
400
401 pub fn table_pane_clip(&self) -> Option<(Rect, Affine)> {
403 self.table_pane.as_deref().copied()
404 }
405
406 pub fn world_transform(&self) -> Affine {
407 self.space
408 .as_deref()
409 .map_or(Affine::IDENTITY, |space| space.world)
410 }
411
412 fn inverse_transform(&self) -> Option<Affine> {
413 self.space
414 .as_deref()
415 .map_or(Some(Affine::IDENTITY), |space| space.inverse)
416 }
417
418 pub fn map_from_window(&self, point: Point) -> Option<Point> {
420 Some(self.inverse_transform()?.map_point(point))
421 }
422
423 pub fn map_delta_from_window(&self, delta: Point) -> Option<Point> {
424 Some(self.inverse_transform()?.map_vector(delta))
425 }
426
427 pub fn map_to_window(&self, point: Point) -> Point {
428 self.world_transform().map_point(point)
429 }
430
431 pub fn window_bounds(&self, rect: Rect) -> Rect {
432 self.world_transform().map_rect(rect)
433 }
434
435 pub fn clip_rect(&self, rect: Rect) -> Rect {
437 let rect = self.clip.intersect(rect);
438 let Some(inverse) = self.inverse_transform() else {
439 return Rect::default();
440 };
441 self.ancestor_shapes.as_deref().map_or(rect, |chain| {
442 chain.clip_rect(rect, self.world_transform(), inverse)
443 })
444 }
445
446 pub fn visible_window_bounds(&self, rect: Rect) -> Rect {
447 let rect = self.window_bounds(self.clip_rect(rect));
448 self.ancestor_shapes.as_deref().map_or(rect, |chain| {
451 chain.clip_rect(rect, Affine::IDENTITY, Affine::IDENTITY)
452 })
453 }
454
455 pub fn contains_clip_point(&self, point: Point) -> bool {
456 self.map_from_window(point)
457 .is_some_and(|local| self.clip.contains(local))
458 && self
459 .ancestor_shapes
460 .as_deref()
461 .is_none_or(|chain| chain.contains(point))
462 }
463
464 pub(crate) fn contains_subtree_point(&self, point: Point) -> bool {
465 self.visible
466 && self.contains_clip_point(point)
467 && (self.overflow
468 || self
469 .map_from_window(point)
470 .is_some_and(|local| self.bounds.contains(local)))
471 }
472
473 pub fn child_paint_order(&self) -> impl DoubleEndedIterator<Item = usize> + '_ {
475 (0..self.children.len()).map(|index| {
476 let dense = self
477 .paint_order
478 .as_deref()
479 .map_or(index, |order| order[index]);
480 self.table_column_window.logical_index(dense)
481 })
482 }
483
484 pub fn children_in_paint_order<'a>(
485 &'a self,
486 node: &'a Node,
487 ) -> impl DoubleEndedIterator<Item = (usize, &'a Node, &'a LayoutNode)> + 'a {
488 self.child_paint_order()
489 .filter_map(move |index| Some((index, node.child_at(index)?, self.child_at(index)?)))
490 }
491
492 pub(crate) fn children_in_scene_order<'a, 'b>(
493 &'b self,
494 node: &'a Node,
495 ) -> impl Iterator<Item = (usize, &'a Node, &'b LayoutNode)> {
496 node.materialized_children()
497 .zip(&self.children)
498 .map(|((index, child), layout)| (index, child, layout))
499 }
500
501 pub fn text_link_regions(&self) -> impl Iterator<Item = (usize, Rect)> + '_ {
502 self.styled_text
503 .iter()
504 .flat_map(|plan| &plan.fragments)
505 .filter_map(|fragment| {
506 let link = fragment.link()?;
507 let rect = fragment.bounds;
508 let visible = self.clip_rect(
509 Rect::new(
510 self.bounds.x + rect.x,
511 self.bounds.y + rect.y,
512 rect.width,
513 rect.height,
514 )
515 .intersect(self.bounds),
516 );
517 (self.visible && visible.width > 0.0 && visible.height > 0.0)
518 .then_some((link, visible))
519 })
520 }
521
522 pub fn dialog_title_height(&self, _node: &Node) -> f32 {
524 self.modal_title.as_ref().map_or(0.0, |title| title.height)
525 }
526
527 #[doc(hidden)]
528 pub fn dialog_title_lines(&self) -> &[label::PlannedLabelLine] {
529 self.modal_title
530 .as_ref()
531 .map_or(&[], |title| title.lines.as_slice())
532 }
533
534 #[doc(hidden)]
535 pub fn dialog_title_font_size(&self) -> Option<f32> {
536 self.modal_title.as_ref().map(|title| title.font_size)
537 }
538
539 pub fn group_header(&self, node: &Node) -> Rect {
540 if let Some(title) = &self.group_title {
541 group_box::header_bounds(node, self.bounds, title.height)
542 } else {
543 group_box::header_with_font_size(node, self.bounds, self.font_size)
544 }
545 }
546
547 #[doc(hidden)]
548 pub fn group_title(&self) -> Option<(f32, &[PlannedLabelLine])> {
549 self.group_title
550 .as_ref()
551 .map(|title| (title.font_size, title.lines.as_slice()))
552 }
553
554 pub(crate) fn tab_viewport(&self) -> Rect {
555 self.tab_strip.unwrap_or(self.bounds)
556 }
557
558 pub(crate) fn tab_item_rect(&self, index: usize) -> Option<Rect> {
559 let child = self.child_at(index)?;
560 if self.tab_strip.is_some() {
561 child.tab_header
562 } else {
563 child.visible.then_some(child.bounds)
564 }
565 }
566
567 pub fn scroll_on(&self, orientation: Orientation) -> Option<ScrollLayout> {
568 match orientation {
569 Orientation::Horizontal => self
570 .table
571 .as_ref()
572 .map(|table| table.horizontal)
573 .or(self.horizontal_scroll),
574 Orientation::Vertical => self.scroll,
575 }
576 }
577
578 fn accepts_pan(&self, axis: Orientation, device: scroll_gesture::PanDevice) -> bool {
579 use scroll_gesture::PanDevice;
580 self.pan_axes[usize::from(axis == Orientation::Vertical)]
581 && match device {
582 PanDevice::Touch => true,
583 PanDevice::LeftMouse => self.mouse_drag_pan,
584 PanDevice::MiddleMouse => self.middle_mouse_pan,
585 }
586 }
587
588 pub fn dialog_paths(&self) -> &[Vec<usize>] {
590 self.overlays
591 .as_ref()
592 .map_or(&[], |overlays| overlays.modal.as_slice())
593 }
594
595 pub fn overlay_paths(&self) -> &[Vec<usize>] {
597 self.overlays
598 .as_ref()
599 .map_or(&[], |overlays| overlays.open.as_slice())
600 }
601
602 pub(crate) fn drawer_paths(&self) -> &[Vec<usize>] {
603 self.overlays
604 .as_ref()
605 .map_or(&[], |overlays| overlays.drawers.as_slice())
606 }
607
608 #[doc(hidden)]
610 pub fn has_leading_edge_drawer(&self, scene: &Node) -> bool {
611 let leading = match self.layout_direction {
612 LayoutDirection::LeftToRight => xrack_runtime::DrawerEdge::Left,
613 LayoutDirection::RightToLeft => xrack_runtime::DrawerEdge::Right,
614 };
615 let viewport = window_safe_area(scene, self.bounds);
616 self.drawer_paths().iter().any(|path| {
617 scene
618 .control_target(path, xrack_runtime::ControlAction::Drawer(true))
619 .is_some_and(|node| {
620 !node.boolean("open", false)
621 && node.drawer_edge() == leading
622 && modal::drawer_margin(node, modal::drawer_bounds(node, viewport)) > 0.0
623 })
624 })
625 }
626
627 pub fn child_at(&self, index: usize) -> Option<&Self> {
629 self.children
630 .get(self.table_column_window.dense_index(index)?)
631 }
632
633 pub(crate) fn child_at_mut(&mut self, index: usize) -> Option<&mut Self> {
634 let dense = self.table_column_window.dense_index(index)?;
635 self.children.get_mut(dense)
636 }
637
638 pub fn at_path(&self, path: &[usize]) -> Option<&Self> {
639 let mut item = self;
640 for &index in path {
641 item = item.child_at(index)?;
642 }
643 Some(item)
644 }
645}
646
647fn sibling_paint_order(node: &Node, count: usize) -> Option<xrack_runtime::ScenePlanSlice<usize>> {
648 use xrack_runtime::ScenePlanSlice;
649
650 if node.has_natural_paint_order() {
651 return None;
652 }
653 if let Some(order) = node.paint_order_plan().filter(|order| order.len() == count) {
654 return Some(order.clone());
655 }
656 let children = &node.children[..count];
657 if !children.windows(2).any(|pair| pair[0].z() > pair[1].z()) {
659 return None;
660 }
661 let mut order: Vec<_> = (0..children.len()).collect();
662 order.sort_by(|&left, &right| children[left].z().total_cmp(&children[right].z()));
663 Some(ScenePlanSlice::Owned(order))
664}
665
666pub fn font_size(node: &Node) -> f32 {
667 node.font_size()
668 .unwrap_or(DEFAULT_FONT_SIZE)
669 .clamp(1.0, 512.0)
670}
671
672fn dimension(node: &Node, name: &str) -> Option<f32> {
673 node.length(name).map(|n| n.max(0.0))
674}
675
676fn default_toggle_indicator_size(node: &Node) -> Size {
677 match node.kind {
678 "Switch" => Size::new(36.0, 18.0),
679 "RadioButton" => Size::new(16.0, 16.0),
680 _ => Size::new(18.0, 18.0),
681 }
682}
683
684fn toggle_indicator_size(node: &Node) -> Option<Size> {
685 let indicator = node.control_part("ToggleIndicator")?;
686 let default = default_toggle_indicator_size(node);
687 Some(Size::new(
688 dimension(indicator, "width").unwrap_or(default.width),
689 dimension(indicator, "height").unwrap_or(default.height),
690 ))
691}
692
693#[doc(hidden)]
695pub struct ToggleGeometry {
696 pub indicator: Rect,
697 pub label: Rect,
698 direction: LayoutDirection,
699 thumb_size: Size,
700}
701
702impl ToggleGeometry {
703 pub fn new(node: &Node, bounds: Rect, direction: LayoutDirection) -> Self {
704 let replacement = toggle_indicator_size(node);
705 let size = replacement.unwrap_or_else(|| {
706 let preferred = default_toggle_indicator_size(node);
707 let scale = (bounds.height / preferred.height).clamp(0.0, 1.0);
708 Size::new(preferred.width * scale, preferred.height * scale)
709 });
710 let delegate = node.is_item_delegate();
711 let inset = (if delegate { 12.0_f32 } else { 6.0 }).min(bounds.width);
712 let width = size.width.min((bounds.width - inset).max(0.0));
713 let height = size.height.min(bounds.height);
714 let x = if delegate {
715 bounds.x + bounds.width - inset - width
716 } else {
717 bounds.x + inset
718 };
719 let indicator = Rect::new(x, bounds.y + (bounds.height - height) * 0.5, width, height);
720 let (left, right) = if delegate {
721 (bounds.x + 12.0, x - 10.0)
722 } else if node.kind == "RadioButton" && replacement.is_none() {
723 (bounds.x + 28.0, bounds.x + bounds.width)
724 } else {
725 (x + width + 7.0, bounds.x + bounds.width)
726 };
727 let label = Rect::new(left, bounds.y, (right - left).max(0.0), bounds.height);
728 let thumb = node.control_part("SwitchThumb");
729 let diameter = (width.min(height) - 4.0).max(0.0);
730 let dimension = |name, available| {
731 thumb
732 .and_then(|thumb| thumb.relative_length(name, available))
733 .unwrap_or(diameter)
734 .clamp(0.0, available)
735 };
736 Self {
737 indicator: place_in_direction(indicator, bounds, direction),
738 label: place_in_direction(label, bounds, direction),
739 direction,
740 thumb_size: Size::new(dimension("width", width), dimension("height", height)),
741 }
742 }
743
744 pub fn switch_travel(&self) -> f32 {
745 (self.indicator.width - self.indicator.height.max(self.thumb_size.width)).max(0.0)
746 }
747
748 pub fn switch_thumb(&self, checked: bool, preview: Option<f32>) -> Rect {
749 let logical = preview.unwrap_or(if checked { 1.0 } else { 0.0 });
750 let visual = if self.direction == LayoutDirection::RightToLeft {
751 1.0 - logical
752 } else {
753 logical
754 };
755 let travel = self.switch_travel();
756 let bounds = self.indicator;
757 Rect::new(
758 bounds.x + (bounds.width - travel - self.thumb_size.width) * 0.5 + travel * visual,
759 bounds.y + (bounds.height - self.thumb_size.height) * 0.5,
760 self.thumb_size.width,
761 self.thumb_size.height,
762 )
763 }
764}
765
766#[doc(hidden)]
768pub fn toggle_indicator_rect(node: &Node, bounds: Rect) -> Option<Rect> {
769 node.control_part("ToggleIndicator")?;
770 Some(ToggleGeometry::new(node, bounds, node.layout_direction().unwrap_or_default()).indicator)
771}
772
773fn place_in_direction(mut rect: Rect, content: Rect, direction: LayoutDirection) -> Rect {
774 if direction == LayoutDirection::RightToLeft {
775 rect.x = content.x + content.width - (rect.x - content.x) - rect.width;
776 }
777 rect
778}
779
780fn participates_in_flow(node: &Node) -> bool {
781 !is_window_overlay(node.kind)
782 && !matches!(node.kind, "Menu" | "Tooltip" | "Shortcut")
783 && node.is_visible()
784}
785
786pub fn is_layout(kind: &str) -> bool {
787 matches!(
788 kind,
789 "GridLayout"
790 | "FlowLayout"
791 | "FlexboxLayout"
792 | "ToolBar"
793 | "Row"
794 | "RadioGroup"
795 | "SplitView"
796 ) || linear::Axis::for_layout(kind).is_some()
797}
798
799pub fn child_reading_order(node: &Node) -> impl Iterator<Item = usize> {
801 let slots @ [menu, header, footer] = page::slots(node);
802 let count = node.table_column_window.logical_len(node.children.len());
803 let (ordered, len) =
804 if node.kind == "TableRow" && node.table_column_order.as_slice(count).is_some() {
805 let mut ordered: Vec<_> = node
806 .materialized_children()
807 .map(|(column, _)| column)
808 .collect();
809 ordered.sort_by_key(|&column| node.table_column_order.visual_index(count, column));
810 (ordered, 0)
811 } else if node.kind == "SplitView" {
812 let count = node.split_pane_count();
813 let ordered = (0..count)
814 .flat_map(|slot| [slot, count + slot])
815 .filter(|&slot| slot < node.children.len())
816 .collect();
817 (ordered, 0)
818 } else if matches!(node.kind, "DialogButtonBox" | "FlexboxLayout") {
819 let mut ordered = (0..node.children.len()).collect::<Vec<_>>();
820 ordered.sort_by_key(|&index| linear::item_order(node, &node.children[index]));
821 (ordered, 0)
822 } else {
823 (Vec::new(), node.children.len())
824 };
825 ordered
826 .into_iter()
827 .chain(menu)
828 .chain(header)
829 .chain(
830 (0..len)
831 .map(move |index| node.table_column_window.logical_index(index))
832 .filter(move |&index| !slots.contains(&Some(index))),
833 )
834 .chain(footer)
835}
836
837pub fn layout(scene: &Node, viewport: Size, text: &mut impl TextMeasurer) -> LayoutNode {
839 layout_with_scroll(scene, viewport, text, &BTreeMap::new())
840}
841
842pub fn layout_with_scroll(
843 scene: &Node,
844 viewport: Size,
845 text: &mut impl TextMeasurer,
846 offsets: &BTreeMap<Vec<usize>, f32>,
847) -> LayoutNode {
848 let mut layout = layout_with_offsets(scene, viewport, text, offsets, None);
849 scroll_bar::attach(scene, &mut layout, text);
850 layout
851}
852
853pub fn layout_with_input(
854 scene: &Node,
855 viewport: Size,
856 text: &mut impl TextMeasurer,
857 input: &Interaction,
858) -> LayoutNode {
859 let mut layout =
860 layout_with_offsets(scene, viewport, text, input.scroll_offsets(), Some(input));
861 scroll_bar::attach(scene, &mut layout, text);
862 layout
863}
864
865fn layout_with_offsets(
866 scene: &Node,
867 viewport: Size,
868 text: &mut impl TextMeasurer,
869 offsets: &BTreeMap<Vec<usize>, f32>,
870 input: Option<&Interaction>,
871) -> LayoutNode {
872 text.begin_window(scene);
873 layout_current_window(scene, viewport, text, offsets, input)
874}
875
876fn layout_current_window(
877 scene: &Node,
878 viewport: Size,
879 text: &mut impl TextMeasurer,
880 offsets: &BTreeMap<Vec<usize>, f32>,
881 input: Option<&Interaction>,
882) -> LayoutNode {
883 let bounds = Rect::new(0.0, 0.0, viewport.width.max(0.0), viewport.height.max(0.0));
884 let safe_viewport = window_safe_area(scene, bounds);
885 let mut layout = LayoutContext {
886 text,
887 layout_direction: None,
888 offsets,
889 input,
890 path: Vec::new(),
891 row_key: None,
892 anchor: None,
893 resolved_list_scroll: None,
894 row_layouts: None,
895 ancestor_shapes: None,
896 space: None,
897 viewport: safe_viewport,
898 }
899 .place(scene, bounds, bounds, true, true, None);
900 modal::index_overlays(
901 scene,
902 &mut layout,
903 popup::PopupTypography::from_text(text),
904 input.and_then(Interaction::floating_keyboard),
905 );
906 layout
907}
908
909const WINDOW_SAFE_AREA: [&str; 4] = [
910 "__safe-area-left",
911 "__safe-area-top",
912 "__safe-area-right",
913 "__safe-area-bottom",
914];
915
916#[doc(hidden)]
918pub fn set_window_safe_area(scene: &mut Node, insets: [f64; 4]) {
919 for (edge, value) in WINDOW_SAFE_AREA.into_iter().zip(insets) {
920 if value > 0.0 && value.is_finite() {
921 scene
922 .properties
923 .insert(edge, xrack_runtime::Length(value).into());
924 } else {
925 scene.properties.remove(edge);
926 }
927 }
928}
929
930#[doc(hidden)]
932pub fn apply_system_layout_direction(mut scene: Rc<Node>, direction: LayoutDirection) -> Rc<Node> {
933 if direction == LayoutDirection::RightToLeft && scene.layout_direction().is_none() {
934 Rc::make_mut(&mut scene).properties.insert(
935 "layout-direction",
936 xrack_runtime::Value::LayoutDirection(direction),
937 );
938 }
939 scene
940}
941
942fn window_safe_area(node: &Node, bounds: Rect) -> Rect {
943 if node.kind != "Window" {
944 return bounds;
945 }
946 let [left, top, right, bottom] =
947 WINDOW_SAFE_AREA.map(|edge| node.length(edge).unwrap_or(0.0).max(0.0));
948 Rect::new(
949 bounds.x + left.min(bounds.width),
950 bounds.y + top.min(bounds.height),
951 (bounds.width - left - right).max(0.0),
952 (bounds.height - top - bottom).max(0.0),
953 )
954}
955
956#[doc(hidden)]
958pub fn layout_choice_option(
959 node: &Node,
960 bounds: Rect,
961 direction: LayoutDirection,
962 enabled: bool,
963 text: &mut impl TextMeasurer,
964) -> LayoutNode {
965 LayoutContext {
966 text,
967 layout_direction: Some(direction),
968 offsets: &BTreeMap::new(),
969 input: None,
970 path: Vec::new(),
971 row_key: None,
972 anchor: None,
973 resolved_list_scroll: None,
974 row_layouts: None,
975 ancestor_shapes: None,
976 space: None,
977 viewport: bounds,
978 }
979 .place(node, bounds, bounds, true, enabled, None)
980}
981
982#[doc(hidden)]
984pub fn layout_drawer_opening(
985 node: &Node,
986 viewport: Rect,
987 reveal: f32,
988 text: &mut impl TextMeasurer,
989) -> (Node, LayoutNode, Point) {
990 let mut shell = node.clone();
991 shell.properties.insert("open", true.into());
992 shell.children.clear();
993 let item = layout_choice_option(
994 &shell,
995 viewport,
996 node.layout_direction().unwrap_or_default(),
997 true,
998 text,
999 );
1000 let shown = modal::drawer_revealed_bounds(node.drawer_edge(), item.bounds, reveal);
1001 let displacement = Point {
1002 x: shown.x - item.bounds.x,
1003 y: shown.y - item.bounds.y,
1004 };
1005 (shell, item, displacement)
1006}
1007
1008pub fn prepare_scene(
1011 component: &impl Component,
1012 scene: Rc<Node>,
1013 viewport: Size,
1014 text: &mut impl TextMeasurer,
1015 offsets: &BTreeMap<Vec<usize>, f32>,
1016) -> (Rc<Node>, LayoutNode) {
1017 prepare_scene_with_offsets(component, scene, viewport, text, offsets, None, None)
1018}
1019
1020pub fn prepare_scene_with_input(
1021 component: &impl Component,
1022 scene: Rc<Node>,
1023 viewport: Size,
1024 text: &mut impl TextMeasurer,
1025 input: &Interaction,
1026) -> (Rc<Node>, LayoutNode) {
1027 prepare_scene_with_offsets(
1028 component,
1029 scene,
1030 viewport,
1031 text,
1032 input.scroll_offsets(),
1033 Some(input),
1034 None,
1035 )
1036}
1037
1038#[doc(hidden)]
1039pub fn prepare_scene_with_row_cache(
1040 component: &impl Component,
1041 scene: Rc<Node>,
1042 viewport: Size,
1043 text: &mut impl TextMeasurer,
1044 input: &Interaction,
1045 cache: &mut RowLayoutCache,
1046) -> (Rc<Node>, LayoutNode) {
1047 cache.begin_frame(&scene);
1048 let result = prepare_scene_with_offsets(
1049 component,
1050 scene,
1051 viewport,
1052 text,
1053 input.scroll_offsets(),
1054 Some(input),
1055 Some(cache),
1056 );
1057 cache.finish_frame();
1058 result
1059}
1060
1061fn prepare_scene_with_offsets(
1062 component: &impl Component,
1063 mut scene: Rc<Node>,
1064 viewport: Size,
1065 text: &mut impl TextMeasurer,
1066 offsets: &BTreeMap<Vec<usize>, f32>,
1067 input: Option<&Interaction>,
1068 row_layouts: Option<&mut RowLayoutCache>,
1069) -> (Rc<Node>, LayoutNode) {
1070 fn has_lists(node: &Node) -> bool {
1071 node.list.is_some()
1072 || node.children.iter().any(has_lists)
1073 || node
1074 .swipe_preview
1075 .as_ref()
1076 .and_then(|preview| preview.page.as_ref())
1077 .is_some_and(|(_, page)| has_lists(page))
1078 }
1079
1080 text.begin_window(&scene);
1081 let families = text.font_families();
1082 if !families.is_empty()
1083 && let Some(populated) = populate_font_choices(&scene, families)
1084 {
1085 scene = Rc::new(populated);
1086 }
1087 let mut layout = layout_current_window(&scene, viewport, text, offsets, input);
1088 if has_lists(&scene) {
1089 let viewport = Rect::new(0.0, 0.0, viewport.width.max(0.0), viewport.height.max(0.0));
1090 LayoutContext {
1091 text,
1092 layout_direction: None,
1093 offsets,
1094 input,
1095 path: Vec::new(),
1096 row_key: None,
1097 anchor: None,
1098 resolved_list_scroll: None,
1099 row_layouts,
1100 ancestor_shapes: None,
1101 space: None,
1102 viewport,
1103 }
1104 .populate_lists(component, Rc::make_mut(&mut scene), &mut layout);
1105 modal::index_overlays(
1106 &scene,
1107 &mut layout,
1108 popup::PopupTypography::from_text(text),
1109 input.and_then(Interaction::floating_keyboard),
1110 );
1111 }
1112 scroll_bar::attach(&scene, &mut layout, text);
1113 (scene, layout)
1114}
1115
1116fn populate_font_choices(node: &Node, families: &[String]) -> Option<Node> {
1117 if is_font_family_choice(node) {
1118 let mut populated = node.clone();
1119 set_font_family_choices(&mut populated, families);
1120 return Some(populated);
1121 }
1122 let mut populated = None;
1123 for (index, child) in node.children.iter().enumerate() {
1124 if let Some(child) = populate_font_choices(child, families) {
1125 populated.get_or_insert_with(|| node.clone()).children[index] = child;
1126 }
1127 }
1128 populated
1129}
1130
1131struct ScrollContent {
1132 extent: Size,
1133 children: Vec<Option<(f32, f32, f32, linear::AxisInfo)>>,
1134}
1135
1136struct LayoutContext<'a, T> {
1137 text: &'a mut T,
1138 layout_direction: Option<LayoutDirection>,
1139 offsets: &'a BTreeMap<Vec<usize>, f32>,
1140 input: Option<&'a Interaction>,
1141 path: Vec<usize>,
1142 row_key: Option<RowKey>,
1143 anchor: Option<Rect>,
1144 resolved_list_scroll: Option<ScrollLayout>,
1145 row_layouts: Option<&'a mut RowLayoutCache>,
1146 ancestor_shapes: Option<Arc<ClipChain>>,
1147 space: Option<Arc<TransformSpace>>,
1148 viewport: Rect,
1149}
1150
1151impl<T: TextMeasurer> LayoutContext<'_, T> {
1152 fn requested_scroll(&self, node: &Node, orientation: Orientation) -> f32 {
1153 self.scroll_request(node, orientation).unwrap_or_default()
1154 }
1155
1156 fn scroll_request(&self, node: &Node, orientation: Orientation) -> Option<f32> {
1157 if let Some(offset) = node
1158 .viewport_handle
1159 .as_ref()
1160 .and_then(|handle| handle.bound_offset(orientation))
1161 {
1162 return Some(offset);
1163 }
1164 if orientation == Orientation::Vertical && self.tree_root_changed(node) {
1165 return Some(0.0);
1166 }
1167 if self.row_key.is_some()
1168 && let Some(renderer) = &node.list_row_renderer
1169 {
1170 return renderer.offset(orientation);
1171 }
1172 let offsets = match orientation {
1173 Orientation::Horizontal => self.input.map(Interaction::horizontal_scroll_offsets),
1174 Orientation::Vertical => Some(self.offsets),
1175 };
1176 offsets.and_then(|offsets| offsets.get(&self.path)).copied()
1177 }
1178
1179 fn tree_root_changed(&self, node: &Node) -> bool {
1180 if self.row_key.is_some()
1181 && let Some(renderer) = &node.list_row_renderer
1182 {
1183 node.tree
1184 .as_ref()
1185 .is_some_and(|tree| renderer.tree_root_changed(tree.root_identity()))
1186 } else {
1187 self.input
1188 .is_some_and(|input| input.tree_root_changed(&self.path, node))
1189 }
1190 }
1191
1192 fn populate_lists(
1193 &mut self,
1194 component: &impl Component,
1195 node: &mut Node,
1196 layout: &mut LayoutNode,
1197 ) {
1198 if node.list.is_none() && node.children.is_empty() {
1199 return;
1200 }
1201 let previous_row = self.row_key;
1202 let previous_direction = self.layout_direction;
1203 self.row_key = node.routing_row_key().or(previous_row);
1204 self.layout_direction = layout.direction_override;
1205 if let Some(mut list) = node.list
1206 && !(list.row_count == 0
1207 && node
1208 .children
1209 .first()
1210 .is_some_and(|child| child.kind == "EmptyState"))
1211 {
1212 let viewport = layout
1213 .table
1214 .as_ref()
1215 .map_or(layout.bounds, |table| table.body);
1216 let clipped = layout.clip_rect(
1217 layout
1218 .table
1219 .as_ref()
1220 .map_or(viewport, |table| table.rows_area()),
1221 );
1222 let clipped = view_cells::list_body_clip(clipped, layout.list_section_headers());
1223 let range = if let Some(scroll) = layout.scroll
1224 && clipped.width > 0.0
1225 && clipped.height > 0.0
1226 {
1227 let top = f64::from(scroll.offset) + f64::from(clipped.y - viewport.y);
1228 let bottom = top + f64::from(clipped.height);
1229 ViewCells::new(node, viewport.width).visible(top, bottom, list.row_count)
1230 } else {
1231 0..0
1232 };
1233 list.first_row = range.start;
1234 let selected = ListMetrics::selection(node);
1235 let selection = node.table_selection.as_ref();
1236 let tree = node.tree.as_ref();
1237 let tree_selection = node.tree_selection.as_ref();
1238 let row_headers = layout
1239 .table
1240 .as_ref()
1241 .is_some_and(|table| table.row_header.width > 0.0);
1242 let indentation = node.length("indentation").unwrap_or(16.0).clamp(0.0, 64.0);
1243 let renderer = node.list_row_renderer.as_ref();
1244 let scope = renderer
1245 .filter(|_| self.row_key.is_some())
1246 .map_or(0, xrack_runtime::ListRowRenderer::scope);
1247 let expects_rows = !range.is_empty();
1248 let delegates = if let Some(renderer) = renderer {
1249 let columns = layout
1250 .table
1251 .as_ref()
1252 .map_or_else(xrack_runtime::TableColumnWindow::default, |table| {
1253 table.column_window(layout.clip_rect(table.body))
1254 });
1255 renderer.render_in_scene(node, range, &columns)
1256 } else {
1257 component.list_rows(&self.path, range)
1258 };
1259 xrack_runtime::update_profile::rows(node.element_id(), delegates.len());
1260 let missing_list_rows = expects_rows && delegates.is_empty();
1261 node.children = delegates
1262 .into_iter()
1263 .enumerate()
1264 .map(|(slot, mut delegate)| {
1265 let families = self.text.font_families();
1266 if !families.is_empty()
1267 && let Some(populated) = populate_font_choices(&delegate, families)
1268 {
1269 delegate = populated;
1270 }
1271 let mut row = Node::new("ListRow", None);
1272 row.row_key = delegate.row_key.take();
1273 row.row_scope = scope;
1274 if delegate.kind == "TableRow" {
1275 delegate.table_column_order = node.table_column_order.clone();
1276 if row_headers {
1277 let title = delegate.text("row-header-text").map_or_else(
1278 || (list.first_row + slot + 1).to_string(),
1279 str::to_owned,
1280 );
1281 row.properties.insert("row-header-text", title.into());
1282 }
1283 }
1284 let tree_item = tree.and_then(|tree| tree.rows().get(list.first_row + slot));
1285 if let Some(item) = tree_item {
1286 row.properties
1287 .insert("tree-depth", (item.depth as i64).into());
1288 row.properties
1289 .insert("tree-has-children", item.has_children.into());
1290 row.properties.insert("tree-expanded", item.expanded.into());
1291 row.properties.insert(
1292 "tree-indentation",
1293 xrack_runtime::Length(f64::from(indentation)).into(),
1294 );
1295 }
1296 let current = selected == Some((list.first_row + slot) as i64);
1297 let grid = selection.filter(|view| view.target() != SelectionTarget::Rows);
1298 if let (Some(view), Some(key)) = (grid, row.row_key) {
1299 let columns = delegate.table_column_window.clone();
1300 for (index, cell) in delegate.children.iter_mut().enumerate() {
1301 let column = columns.logical_index(index);
1302 if !cell.is_visible() {
1303 continue;
1304 }
1305 if view.contains_cell(key, column) {
1306 cell.properties.insert("table-selected", true.into());
1307 }
1308 if current && view.current_column() == Some(column) {
1309 cell.properties.insert("table-current", true.into());
1310 }
1311 }
1312 }
1313 let is_selected = if let Some(keys) = tree_selection {
1314 tree_item.is_some_and(|item| {
1315 row.row_key == Some(item.row) && keys.get(&item.key) == Some(&item.row)
1316 })
1317 } else {
1318 selection.map_or(current, |view| {
1319 row.row_key.is_some_and(|key| view.keys().contains(&key))
1320 })
1321 };
1322 if matches!(node.kind, "ListView" | "GridView") && delegate.is_item_delegate() {
1323 delegate
1324 .properties
1325 .entry("highlighted")
1326 .or_insert(xrack_runtime::Value::Bool(is_selected));
1327 if delegate.kind == "RadioButton" {
1328 delegate
1329 .properties
1330 .insert("checked", xrack_runtime::Value::Bool(current));
1331 }
1332 }
1333 row.properties
1334 .insert("selected", xrack_runtime::Value::Bool(is_selected));
1335 if (node.kind == "GridView"
1336 || tree_selection.is_some()
1337 || selection.is_some() && grid.is_none())
1338 && current
1339 {
1340 row.properties
1341 .insert("current", xrack_runtime::Value::Bool(true));
1342 }
1343 row.children.push(delegate);
1344 row
1345 })
1346 .collect();
1347 node.list = Some(list);
1348 let (incoming_clip, incoming_shapes, incoming_space) =
1349 if let Some(placement) = &layout.transform {
1350 (
1351 placement.parent_clip,
1352 layout
1353 .ancestor_shapes
1354 .as_ref()
1355 .and_then(|shape| shape.parent.clone()),
1356 placement.parent_space.clone(),
1357 )
1358 } else {
1359 (
1360 layout.clip,
1361 layout.ancestor_shapes.clone(),
1362 layout.space.clone(),
1363 )
1364 };
1365 let shapes = std::mem::replace(&mut self.ancestor_shapes, incoming_shapes);
1366 let space = std::mem::replace(&mut self.space, incoming_space);
1367 self.resolved_list_scroll = layout.scroll;
1369 let pane = layout.table_pane.take();
1370 *layout = self.place(
1371 node,
1372 layout.bounds,
1373 incoming_clip,
1374 layout.visible,
1375 layout.enabled,
1376 None,
1377 );
1378 layout.table_pane = pane;
1379 layout.missing_list_rows = missing_list_rows;
1380 self.ancestor_shapes = shapes;
1381 self.space = space;
1382 }
1383 self.populate_section_headers(node, layout);
1384 let columns = node.table_column_window.clone();
1385 for (index, (child, item)) in node
1386 .children
1387 .iter_mut()
1388 .zip(&mut layout.children)
1389 .enumerate()
1390 {
1391 self.path.push(columns.logical_index(index));
1392 self.populate_lists(component, child, item);
1393 layout.missing_descendant_list_rows |= item.has_missing_list_rows();
1394 self.path.pop();
1395 }
1396 if let Some((index, page)) = node
1397 .swipe_preview
1398 .as_mut()
1399 .and_then(|preview| preview.page.as_mut())
1400 && let Some(item) = &mut layout.swipe_preview
1401 {
1402 self.path.push(*index);
1403 self.populate_lists(component, page, item);
1404 self.path.pop();
1405 scroll_bar::attach(page, item, self.text);
1406 }
1407 self.row_key = previous_row;
1408 self.layout_direction = previous_direction;
1409 }
1410
1411 fn populate_section_headers(&mut self, node: &Node, layout: &mut LayoutNode) {
1412 let Some(renderer) = node
1413 .list_section_renderer
1414 .as_ref()
1415 .filter(|_| layout.visible)
1416 else {
1417 return;
1418 };
1419 let clip = layout.clip_rect(layout.bounds);
1420 let Some(headers) = layout.list_section_headers.as_deref_mut() else {
1421 return;
1422 };
1423 let previous_space = std::mem::replace(&mut self.space, layout.space.clone());
1424 let previous_shapes =
1425 std::mem::replace(&mut self.ancestor_shapes, layout.ancestor_shapes.clone());
1426 for header in headers {
1427 let visible = clip.intersect(header.bounds);
1428 if visible.width <= 0.0 || visible.height <= 0.0 {
1429 continue;
1430 }
1431 let Some(node) = renderer.render(xrack_runtime::ListSectionInput {
1432 label: header.label.clone(),
1433 first_index: header.first_row as i64,
1434 count: header.row_count as i64,
1435 pinned: header.pinned,
1436 }) else {
1437 continue;
1438 };
1439 let item = self.place(&node, header.bounds, visible, true, layout.enabled, None);
1440 header.content = Some(Box::new((node, item)));
1441 }
1442 self.space = previous_space;
1443 self.ancestor_shapes = previous_shapes;
1444 }
1445
1446 fn place(
1447 &mut self,
1448 node: &Node,
1449 bounds: Rect,
1450 clip: Rect,
1451 parent_visible: bool,
1452 parent_enabled: bool,
1453 row_children: Option<grid::RowPlacements>,
1454 ) -> LayoutNode {
1455 let outer_key = self.row_key;
1456 let outer_direction = self.layout_direction;
1457 let outer_anchor = self.anchor;
1458 let outer_shapes = self.ancestor_shapes.clone();
1459 let outer_space = self.space.clone();
1460 self.row_key = node.routing_row_key().or(outer_key);
1461 self.layout_direction = node.layout_direction().or(outer_direction);
1462 let row_cache = node.kind == "ListRow"
1463 && row_children.is_none()
1464 && self.space.is_none()
1465 && self.ancestor_shapes.is_none()
1466 && self.row_layouts.is_some();
1467 let layout = if row_cache && let Some(row) = node.routing_row_key() {
1468 let slot = row_layout::Slot { row, column: None };
1469 let inputs = row_layout::RowInputs {
1470 size: Size::new(bounds.width, bounds.height),
1471 visible: parent_visible,
1472 enabled: parent_enabled,
1473 layout_direction: self.layout_direction,
1474 };
1475 self.place_cached_content(node, bounds, clip, inputs, slot)
1476 } else {
1477 self.place_node(
1478 node,
1479 bounds,
1480 clip,
1481 parent_visible,
1482 parent_enabled,
1483 row_children,
1484 )
1485 };
1486 self.row_key = outer_key;
1487 self.layout_direction = outer_direction;
1488 self.anchor = outer_anchor;
1489 self.ancestor_shapes = outer_shapes;
1490 self.space = outer_space;
1491 layout
1492 }
1493
1494 fn place_cached_content(
1495 &mut self,
1496 node: &Node,
1497 bounds: Rect,
1498 clip: Rect,
1499 inputs: row_layout::RowInputs,
1500 slot: row_layout::Slot,
1501 ) -> LayoutNode {
1502 if self
1503 .input
1504 .is_some_and(|input| input.contains_switch_preview(&self.path))
1505 {
1506 return self.place_node(node, bounds, clip, inputs.visible, inputs.enabled, None);
1507 }
1508 let depth = if slot.column.is_some() { 3 } else { 1 };
1509 let path_len = self.path.len().saturating_sub(depth);
1510 let path = &self.path[..path_len];
1511 if let Some(mut layout) = self
1512 .row_layouts
1513 .as_deref_mut()
1514 .and_then(|cache| cache.get(path, slot, node, inputs))
1515 {
1516 row_layout::place_in_view(&mut layout, bounds, clip);
1517 return layout;
1518 }
1519 if !row_layout::cacheable(node) {
1520 return self.place_node(node, bounds, clip, inputs.visible, inputs.enabled, None);
1521 }
1522 let local = Rect::new(0.0, 0.0, inputs.size.width, inputs.size.height);
1523 let mut layout = self.place_node(node, local, local, inputs.visible, inputs.enabled, None);
1524 let path = &self.path[..path_len];
1525 if let Some(cache) = self.row_layouts.as_deref_mut() {
1526 cache.insert(path, slot, node, inputs, &layout);
1527 }
1528 row_layout::place_in_view(&mut layout, bounds, clip);
1529 layout
1530 }
1531
1532 fn place_node(
1533 &mut self,
1534 node: &Node,
1535 bounds: Rect,
1536 clip: Rect,
1537 parent_visible: bool,
1538 parent_enabled: bool,
1539 row_children: Option<grid::RowPlacements>,
1540 ) -> LayoutNode {
1541 let resolved_list_scroll = self.resolved_list_scroll.take();
1542 let tree_parts = match &row_children {
1543 Some(grid::RowPlacements::Tree {
1544 geometry,
1545 has_children,
1546 }) => Some((*geometry, *has_children)),
1547 _ => None,
1548 };
1549 let font_size = self.text.font_size(node);
1550 let children_enabled = parent_enabled && node.enables_children();
1551 let enabled =
1552 children_enabled && (node.kind != "TouchArea" || node.boolean("enabled", true));
1553 let mut visible = parent_visible
1554 && node.is_visible()
1555 && (node.kind != "PopupWindow" || enabled && self.anchor.is_some())
1556 && xrack_runtime::indicator_state(node) != Some(xrack_runtime::IndicatorState::Hidden);
1557 let (bounds, clip) = if node.kind == "Shortcut" {
1558 (Rect::new(bounds.x, bounds.y, 0.0, 0.0), clip)
1559 } else if visible
1560 && node.kind == "PopupWindow"
1561 && let Some(anchor) = self.anchor
1562 {
1563 (
1564 popup::bounds(node, anchor, self.viewport, self.text),
1565 self.viewport,
1566 )
1567 } else if visible && is_modal_overlay(node.kind) {
1568 let panel = modal::bounds(node, self.viewport, self.text);
1569 let reveal = (node.kind == "Drawer")
1570 .then(|| {
1571 self.input?.closing_drawer_reveal(
1572 node,
1573 &self.path,
1574 self.row_key,
1575 self.viewport,
1576 panel,
1577 )
1578 })
1579 .flatten();
1580 let panel = reveal.map_or(panel, |reveal| {
1581 modal::drawer_revealed_bounds(node.drawer_edge(), panel, reveal)
1582 });
1583 (panel, self.viewport)
1584 } else {
1585 (bounds, clip)
1586 };
1587 if is_window_overlay(node.kind) {
1588 self.ancestor_shapes = None;
1589 self.space = None;
1590 }
1591 let local = Affine::for_node(node, bounds);
1592 let mut clip = clip;
1593 let transform = if local != Affine::IDENTITY {
1594 let parent_space = self.space.clone();
1595 let parent_clip = clip;
1596 self.ancestor_shapes = Some(Arc::new(ClipChain {
1597 shape: RoundedClip {
1598 bounds: clip,
1599 radii: [0.0; 4],
1600 },
1601 parent: self.ancestor_shapes.clone(),
1602 space: parent_space.clone(),
1603 }));
1604 let world = local.then(
1605 parent_space
1606 .as_deref()
1607 .map_or(Affine::IDENTITY, |space| space.world),
1608 );
1609 self.space = Some(Arc::new(TransformSpace {
1610 world,
1611 inverse: world.inverse(),
1612 }));
1613 clip = local
1614 .inverse()
1615 .map_or(Rect::default(), |inverse| inverse.map_rect(clip));
1616 Some(Box::new(TransformPlacement {
1617 local,
1618 parent_clip,
1619 parent_space,
1620 }))
1621 } else {
1622 None
1623 };
1624 let space = self.space.clone();
1625 let world = space
1626 .as_deref()
1627 .map_or(Affine::IDENTITY, |space| space.world);
1628 let inverse = space
1629 .as_deref()
1630 .map_or(Some(Affine::IDENTITY), |space| space.inverse);
1631 visible &= inverse.is_some();
1632 let ancestor_shapes = self.ancestor_shapes.clone();
1633 let clipped = world.map_rect(bounds.intersect(clip));
1634 let clipped = ancestor_shapes.as_deref().map_or(clipped, |chain| {
1635 chain.clip_rect(clipped, Affine::IDENTITY, Affine::IDENTITY)
1636 });
1637 if node.kind != "Shortcut" {
1638 self.anchor =
1639 (visible && clipped.width > 0.0 && clipped.height > 0.0).then_some(clipped);
1640 }
1641 if matches!(node.kind, "Menu" | "Tooltip" | "Shortcut") {
1642 return LayoutNode {
1644 bounds,
1645 clip,
1646 visible: visible && node.kind != "Tooltip",
1647 enabled,
1648 layout_direction: self.layout_direction.unwrap_or_default(),
1649 direction_override: self.layout_direction,
1650 content_bounds: None,
1651 scroll: None,
1652 list_section_headers: None,
1653 horizontal_scroll: None,
1654 horizontal_scroll_reversed: false,
1655 viewport_handle: None,
1656 nested_list: None,
1657 missing_list_rows: false,
1658 missing_descendant_list_rows: false,
1659 attached_scroll_bar: None,
1660 mouse_drag_pan: false,
1661 middle_mouse_pan: false,
1662 pan_axes: [false; 2],
1663 elastic: None,
1664 pull_to_refresh: false,
1665 table: None,
1666 split: None,
1667 tab_header: None,
1668 tab_close: None,
1669 tab_strip: None,
1670 tumbler: None,
1671 switch_position: None,
1672 swipe_delegate: None,
1673 swipe_preview: None,
1674 styled_text: None,
1675 modal_title: None,
1676 group_title: None,
1677 font_size,
1678 overlays: None,
1679 paint_order: None,
1680 overflow: false,
1681 child_shape: None,
1682 ancestor_shapes,
1683 space,
1684 transform,
1685 table_pane: None,
1686 table_column_window: node.table_column_window.clone(),
1687 children: Vec::new(),
1688 };
1689 }
1690 let table = if visible && node.table_header.is_some() {
1691 let preferred_header = if self.text.text_scale() > 1.0 {
1692 (table_heading_font_size(self.text) * 1.4 + 8.0).max(34.0)
1693 } else {
1694 34.0
1695 };
1696 TableGeometry::with_offset(
1697 node,
1698 bounds,
1699 clip,
1700 self.requested_scroll(node, Orientation::Horizontal),
1701 self.layout_direction.unwrap_or_default(),
1702 table::header_height(node, bounds.height, preferred_header),
1703 )
1704 .map(Box::new)
1705 } else {
1706 None
1707 };
1708 let pane = xrack_runtime::is_pane(node.kind);
1709 let overflow =
1710 (matches!(node.kind, "Rectangle" | "Flickable") || pane) && !node.boolean("clip", true);
1711 let clipping = ((node.kind == "Rectangle" || pane) && node.boolean("clip", false))
1712 .then(|| RoundedClip::content_box(node, bounds));
1713 let child_shape = clipping.filter(|shape| shape.radii.iter().any(|radius| *radius > 0.0));
1714 if let Some(shape) = child_shape {
1715 self.ancestor_shapes = Some(Arc::new(ClipChain {
1716 shape,
1717 parent: ancestor_shapes.clone(),
1718 space: space.clone(),
1719 }));
1720 }
1721 let viewport = table.as_ref().map_or(bounds, |table| table.rows_area());
1722 let child_clip = if overflow {
1723 clip
1724 } else {
1725 clip.intersect(clipping.map_or(viewport, |shape| shape.bounds))
1726 };
1727 if matches!(
1728 node.kind,
1729 "TabWidget" | "SwipeView" | "StackView" | "StackLayout"
1730 ) && visible
1731 {
1732 let tabs = (node.kind == "TabWidget").then(|| {
1733 selection::TabGeometry::new(
1734 node,
1735 bounds,
1736 self.layout_direction.unwrap_or_default(),
1737 self.text,
1738 )
1739 });
1740 let stack_layout = node.kind == "StackLayout";
1741 let page_bounds = if stack_layout {
1742 linear::Padding::read(node).inner_rect(bounds)
1743 } else {
1744 tabs.as_ref().map_or(bounds, |geometry| geometry.content)
1745 };
1746 let selected = if node.kind == "StackView" {
1747 node.stack_page_index()
1748 } else {
1749 group_index(node)
1750 };
1751 let orientation = node.orientation();
1752 let direction = self.layout_direction.unwrap_or_default();
1753 let headers = tabs.as_ref().map(|geometry| {
1754 let requested = self.scroll_request(node, orientation);
1755 let reveal = requested.is_none()
1756 || self.input.is_some_and(|input| {
1757 input.scroll_selection_changed(
1758 node,
1759 &self.path,
1760 1,
1761 direction,
1762 self.text.text_scale(),
1763 )
1764 });
1765 selection::tab_bar(node, geometry.bar, self.text, direction, requested, reveal)
1766 });
1767 let header_scroll = headers.as_ref().map(|(_, scroll)| *scroll);
1768 let children = node
1769 .children
1770 .iter()
1771 .enumerate()
1772 .map(|(index, tab)| {
1773 self.path.push(index);
1774 let active = selected == Some(index);
1775 let bounds = if stack_layout && active && tab.is_visible() {
1776 let size = Size::new(page_bounds.width, page_bounds.height);
1777 let metrics = linear::measure(tab, size, self.text);
1778 place_in_direction(
1779 Rect::new(
1780 page_bounds.x,
1781 page_bounds.y,
1782 metrics.x.clamp(size.width),
1783 metrics.y.clamp(size.height),
1784 ),
1785 page_bounds,
1786 direction,
1787 )
1788 } else {
1789 page_bounds
1790 };
1791 let clip = if stack_layout {
1792 child_clip.intersect(page_bounds)
1793 } else {
1794 child_clip
1795 };
1796 let mut page = self.place(tab, bounds, clip, active, enabled, None);
1797 self.path.pop();
1798 if let Some((rects, _)) = &headers
1799 && tab.is_visible()
1800 {
1801 page.tab_header = rects.get(index).copied();
1802 if xrack_runtime::tab_is_closable(node, tab) {
1803 page.tab_close = page.tab_header.and_then(|header| {
1804 selection::tab_close_rect(
1805 header,
1806 direction,
1807 self.text.text_scale() > 1.0,
1808 )
1809 });
1810 }
1811 }
1812 page
1813 })
1814 .collect();
1815 let swipe_preview = node
1816 .swipe_preview
1817 .as_ref()
1818 .and_then(|preview| preview.page.as_ref())
1819 .map(|(index, page)| {
1820 self.path.push(*index);
1821 let item = self.place(page, page_bounds, child_clip, true, enabled, None);
1822 self.path.pop();
1823 Box::new(item)
1824 });
1825 return LayoutNode {
1826 bounds,
1827 clip,
1828 visible,
1829 enabled,
1830 layout_direction: self.layout_direction.unwrap_or_default(),
1831 direction_override: self.layout_direction,
1832 content_bounds: None,
1833 scroll: header_scroll.filter(|_| orientation == Orientation::Vertical),
1834 list_section_headers: None,
1835 horizontal_scroll: header_scroll.filter(|_| orientation == Orientation::Horizontal),
1836 horizontal_scroll_reversed: false,
1837 viewport_handle: None,
1838 nested_list: None,
1839 missing_list_rows: false,
1840 missing_descendant_list_rows: false,
1841 attached_scroll_bar: None,
1842 mouse_drag_pan: false,
1843 middle_mouse_pan: tabs.is_some(),
1844 pan_axes: [tabs.is_some(); 2],
1845 elastic: None,
1846 pull_to_refresh: false,
1847 table: None,
1848 split: None,
1849 tab_header: None,
1850 tab_close: None,
1851 tab_strip: tabs.as_ref().map(|geometry| geometry.bar),
1852 tumbler: None,
1853 switch_position: None,
1854 swipe_delegate: None,
1855 swipe_preview,
1856 styled_text: None,
1857 modal_title: None,
1858 group_title: None,
1859 font_size,
1860 overlays: None,
1861 paint_order: None,
1862 overflow: false,
1863 child_shape: None,
1864 ancestor_shapes,
1865 space,
1866 transform,
1867 table_pane: None,
1868 table_column_window: node.table_column_window.clone(),
1869 children,
1870 };
1871 }
1872 let mut scroll = None;
1873 let mut horizontal_scroll = None;
1874 let mut list_section_headers = None;
1875 let mut scroll_area = None;
1876 let horizontal_scroll_reversed = matches!(node.kind, "ScrollView" | "Flickable")
1877 && self.layout_direction == Some(LayoutDirection::RightToLeft);
1878 let (split, split_rects) = if visible && node.kind == "SplitView" {
1879 let (geometry, rects) = SplitGeometry::new(
1880 node,
1881 bounds,
1882 self.layout_direction.unwrap_or_default(),
1883 self.text,
1884 );
1885 (Some(Box::new(geometry)), Some(rects))
1886 } else {
1887 (None, None)
1888 };
1889 let table_cells = node.kind == "TableRow" && row_children.is_some();
1890 let mut row_children = row_children;
1891 let content_bounds = window_safe_area(node, bounds);
1892 let page = (visible && (node.kind == "Page" || node.application_window))
1893 .then(|| page::Regions::new(node, content_bounds, self.text));
1894 let swipe_delegate = (visible && node.kind == "SwipeDelegate").then(|| {
1895 let mut geometry = SwipeDelegateGeometry::new(node, bounds, self.text);
1896 if enabled
1897 && let Some(offset) = self.input.and_then(|input| {
1898 input.swipe_preview_offset(&self.path, node, &geometry, self.row_key)
1899 })
1900 {
1901 geometry.set_preview(offset);
1902 }
1903 Box::new(geometry)
1904 });
1905 let switch_position = if enabled && visible && node.kind == "Switch" {
1906 self.input.and_then(|input| {
1907 input.switch_position(
1908 node,
1909 bounds,
1910 self.layout_direction.unwrap_or_default(),
1911 &self.path,
1912 self.row_key,
1913 )
1914 })
1915 } else {
1916 None
1917 };
1918 let custom_scroll = (visible && node.has_scroll_parts() && node.scroll_target.is_none())
1919 .then(|| {
1920 scroll_bar::standalone_geometry(
1921 node,
1922 bounds,
1923 self.layout_direction.unwrap_or_default(),
1924 )
1925 })
1926 .flatten();
1927 let modal_title = if visible && is_modal_overlay(node.kind) {
1928 modal::title_layout(
1929 node,
1930 Size::new(bounds.width, bounds.height),
1931 self.layout_direction.unwrap_or_default(),
1932 self.text,
1933 )
1934 .map(Box::new)
1935 } else {
1936 None
1937 };
1938 let group_title = if visible {
1939 group_box::title_layout(
1940 node,
1941 Size::new(bounds.width, bounds.height),
1942 self.layout_direction.unwrap_or_default(),
1943 self.text,
1944 )
1945 .map(Box::new)
1946 } else {
1947 None
1948 };
1949 let placements = if !visible {
1950 (0..node.children.len())
1951 .map(|_| grid::Placement::plain(Rect::new(bounds.x, bounds.y, 0.0, 0.0)))
1952 .collect()
1953 } else if node.has_scroll_parts() {
1954 node.children
1955 .iter()
1956 .map(|child| {
1957 let rect = custom_scroll.map_or_else(
1958 || Rect::new(bounds.x, bounds.y, 0.0, 0.0),
1959 |geometry| {
1960 if child.kind == "ScrollThumb" {
1961 geometry.thumb
1962 } else {
1963 geometry.track
1964 }
1965 },
1966 );
1967 grid::Placement::plain(rect)
1968 })
1969 .collect()
1970 } else if let Some(rects) = split_rects {
1971 rects.into_iter().map(grid::Placement::plain).collect()
1972 } else if node.kind == "MonthGrid" && node.calendar_cells().is_some() {
1973 node.children
1974 .iter()
1975 .map(|child| {
1976 grid::Placement::plain(if child.kind == "CalendarCells" {
1977 bounds
1978 } else {
1979 self.absolute_child(child, bounds)
1980 })
1981 })
1982 .collect()
1983 } else if node.has_progress_parts() {
1984 let fill = progress_fill_bounds(
1985 bounds,
1986 self.layout_direction.unwrap_or_default(),
1987 xrack_runtime::indicator_state(node)
1988 .unwrap_or(xrack_runtime::IndicatorState::Hidden),
1989 None,
1990 );
1991 node.children
1992 .iter()
1993 .map(|child| {
1994 grid::Placement::plain(match child.kind {
1995 "ProgressTrack" => bounds,
1996 "ProgressFill" => fill,
1997 _ => self.absolute_child(child, bounds),
1998 })
1999 })
2000 .collect()
2001 } else if node.control_part("SliderHandle").is_some() {
2002 let geometry = SliderGeometry::with_layout_direction(
2003 bounds,
2004 node,
2005 self.layout_direction.unwrap_or_default(),
2006 );
2007 let range = xrack_runtime::SliderRange::from_node(node);
2008 let fraction = self
2009 .input
2010 .and_then(|input| {
2011 (!node.boolean("live", true))
2012 .then(|| input.slider_preview(&self.path))
2013 .flatten()
2014 })
2015 .map_or_else(|| range.fraction(), |value| range.preview_fraction(value));
2016 node.children
2017 .iter()
2018 .map(|child| {
2019 let rect = if child.kind == "SliderHandle" {
2020 geometry.thumb_bounds(0, fraction)
2021 } else {
2022 self.absolute_child(child, bounds)
2023 };
2024 grid::Placement::plain(rect)
2025 })
2026 .collect()
2027 } else if node.kind == "ComboBox" && !node.children.is_empty() {
2028 let direction = self.layout_direction.unwrap_or_default();
2029 let geometry = ComboGeometry::for_control(node, bounds, direction);
2030 node.children
2031 .iter()
2032 .map(|child| match child.kind {
2033 "ComboIndicator" => grid::Placement::plain(geometry.indicator_bounds(child)),
2034 "ComboPopup" => grid::Placement::plain(Rect::new(bounds.x, bounds.y, 0.0, 0.0)),
2035 "ComboContent" => {
2036 let bounds = geometry.label_bounds(direction);
2037 grid::Placement {
2038 bounds,
2039 clip: Some(Arc::new(table::PaneClip {
2040 bounds,
2041 space: space.clone(),
2042 })),
2043 row_children: None,
2044 }
2045 }
2046 _ => grid::Placement::plain(self.absolute_child(child, bounds)),
2047 })
2048 .collect()
2049 } else if xrack_runtime::is_spin_box(node.kind) && !node.children.is_empty() {
2050 let geometry = SpinGeometry::with_layout_direction(
2051 bounds,
2052 node,
2053 self.layout_direction.unwrap_or_default(),
2054 );
2055 node.children
2056 .iter()
2057 .map(|child| {
2058 grid::Placement::plain(match child.kind {
2059 "SpinUpIndicator" => geometry.up,
2060 "SpinDownIndicator" => geometry.down,
2061 _ => self.absolute_child(child, bounds),
2062 })
2063 })
2064 .collect()
2065 } else if node.control_part("ToggleIndicator").is_some()
2066 || node.control_part("SwitchThumb").is_some()
2067 {
2068 let geometry =
2069 ToggleGeometry::new(node, bounds, self.layout_direction.unwrap_or_default());
2070 let checked = node.boolean("checked", false);
2071 node.children
2072 .iter()
2073 .map(|child| {
2074 grid::Placement::plain(match child.kind {
2075 "ToggleIndicator" => geometry.indicator,
2076 "SwitchThumb" => geometry.switch_thumb(checked, switch_position),
2077 _ => self.absolute_child(child, bounds),
2078 })
2079 })
2080 .collect()
2081 } else if node.control_part("ButtonContent").is_some() {
2082 let content = bounds.inset(ButtonContent::new(node).padding);
2083 node.children
2084 .iter()
2085 .map(|child| {
2086 grid::Placement::plain(if child.kind == "ButtonContent" {
2087 content
2088 } else {
2089 self.absolute_child(child, bounds)
2090 })
2091 })
2092 .collect()
2093 } else if node.kind == "SplitHandle" {
2094 node.children
2095 .iter()
2096 .map(|_| grid::Placement::plain(bounds))
2097 .collect()
2098 } else if node.kind == "CalendarCells" {
2099 (0..node.children.len())
2100 .map(|slot| {
2101 let bounds = calendar::month_cell(
2102 bounds,
2103 slot,
2104 self.layout_direction.unwrap_or_default(),
2105 );
2106 grid::Placement {
2107 bounds,
2108 clip: Some(Arc::new(table::PaneClip {
2109 bounds,
2110 space: space.clone(),
2111 })),
2112 row_children: None,
2113 }
2114 })
2115 .collect()
2116 } else if let Some(list) = node.list {
2117 let cells = ViewCells::new(node, viewport.width);
2118 let axis = resolved_list_scroll
2119 .unwrap_or_else(|| self.list_scroll(node, &cells, viewport.height, list.row_count));
2120 scroll = Some(axis);
2121 list_section_headers = cells.headers(viewport, axis.offset, list.row_count);
2122 let panes = table.as_ref().and_then(|table| {
2123 if table.row_header.width == 0.0 {
2124 table.frozen_boundary()?;
2125 }
2126 let pane = |bounds| {
2127 Arc::new(table::PaneClip {
2128 bounds,
2129 space: space.clone(),
2130 })
2131 };
2132 Some((pane(table.frozen_body()), pane(table.scrollable_body())))
2133 });
2134 node.children
2135 .iter()
2136 .enumerate()
2137 .map(|(slot, row)| {
2138 if list.row_count == 0 && row.kind == "EmptyState" {
2139 return grid::Placement::plain(viewport);
2140 }
2141 let bounds = cells.bounds(list.first_row + slot, viewport, axis.offset);
2142 let bounds = if node.kind == "GridView" {
2143 place_in_direction(
2144 bounds,
2145 viewport,
2146 self.layout_direction.unwrap_or_default(),
2147 )
2148 } else {
2149 bounds
2150 };
2151 let delegate = if row.kind == "ListRow" {
2152 row.children.first()
2153 } else {
2154 Some(row)
2155 };
2156 grid::Placement {
2157 bounds,
2158 clip: None,
2159 row_children: table.as_ref().zip(delegate).map(|(table, row)| {
2160 grid::RowPlacements::Cells(
2161 row.materialized_children()
2162 .filter_map(|(index, _)| {
2163 let column = table.columns.get(index)?;
2164 Some(grid::CellPlacement {
2165 bounds: Rect::new(
2166 column.x,
2167 bounds.y,
2168 column.width,
2169 bounds.height,
2170 ),
2171 clip: panes.as_ref().map(|(frozen, scrolling)| {
2172 if table.is_frozen(index) {
2173 frozen.clone()
2174 } else {
2175 scrolling.clone()
2176 }
2177 }),
2178 })
2179 })
2180 .collect(),
2181 )
2182 }),
2183 }
2184 })
2185 .collect()
2186 } else if node.kind == "RangeSlider" {
2187 let geometry = SliderGeometry::with_layout_direction(
2188 bounds,
2189 node,
2190 self.layout_direction.unwrap_or_default(),
2191 );
2192 let interval = xrack_runtime::SliderInterval::from_node(node);
2193 let preview = self
2194 .input
2195 .filter(|_| enabled)
2196 .and_then(|input| input.interval_preview(node, &self.path));
2197 let fractions = preview.map_or_else(
2198 || interval.fractions(),
2199 |(index, fraction)| interval.preview_fractions(index, fraction),
2200 );
2201 node.children
2202 .iter()
2203 .enumerate()
2204 .map(|(index, child)| {
2205 let index = if index < Node::RANGE_THUMBS {
2206 Some(index)
2207 } else {
2208 Node::RANGE_HANDLE_PARTS
2209 .iter()
2210 .position(|kind| *kind == child.kind)
2211 };
2212 let rect = index.map_or(Rect::default(), |index| {
2213 geometry.thumb_bounds(index, fractions[index])
2214 });
2215 grid::Placement::plain(rect)
2216 })
2217 .collect()
2218 } else if node.kind == "ListRow" {
2219 let direction = self.layout_direction.unwrap_or_default();
2220 let tree = TreeRowGeometry::with_layout_direction(node, bounds, direction);
2221 node.children
2222 .iter()
2223 .map(|child| {
2224 if let Some(geometry) = tree
2225 && child.kind == "TreeRow"
2226 && child.control_part("TreeDisclosure").is_some()
2227 {
2228 grid::Placement {
2229 bounds,
2230 clip: None,
2231 row_children: Some(grid::RowPlacements::Tree {
2232 geometry,
2233 has_children: node.boolean("tree-has-children", false),
2234 }),
2235 }
2236 } else {
2237 grid::Placement {
2238 bounds: tree.map_or(bounds, |tree| tree.content),
2239 clip: None,
2240 row_children: row_children.take(),
2241 }
2242 }
2243 })
2244 .collect()
2245 } else if node.kind == "GridLayout" {
2246 grid::children(
2247 node,
2248 bounds,
2249 self.layout_direction.unwrap_or_default(),
2250 self.text,
2251 )
2252 } else if node.kind == "TabBar" {
2253 let orientation = node.orientation();
2254 let direction = self.layout_direction.unwrap_or_default();
2255 let requested = self.scroll_request(node, orientation);
2256 let reveal = requested.is_none()
2257 || self.input.is_some_and(|input| {
2258 input.scroll_selection_changed(
2259 node,
2260 &self.path,
2261 1,
2262 direction,
2263 self.text.text_scale(),
2264 )
2265 });
2266 let (rects, axis) =
2267 selection::tab_bar(node, bounds, self.text, direction, requested, reveal);
2268 match orientation {
2269 Orientation::Horizontal => horizontal_scroll = Some(axis),
2270 Orientation::Vertical => scroll = Some(axis),
2271 }
2272 rects.into_iter().map(grid::Placement::plain).collect()
2273 } else if matches!(node.kind, "ScrollView" | "Flickable") {
2274 let (rects, x, y, area) =
2275 self.scroll_view_children(node, bounds, enabled, horizontal_scroll_reversed);
2276 scroll_area = (area != bounds).then_some(area);
2277 horizontal_scroll = Some(x);
2278 scroll = Some(y);
2279 rects.into_iter().map(grid::Placement::plain).collect()
2280 } else if let Some((tree, _)) = tree_parts {
2281 node.children
2282 .iter()
2283 .map(|child| {
2284 grid::Placement::plain(if child.kind == "TreeDisclosure" {
2285 tree.indicator
2286 } else {
2287 self.absolute_child(child, tree.content)
2288 })
2289 })
2290 .collect()
2291 } else if let Some(grid::RowPlacements::Cells(placements)) = row_children {
2292 placements
2293 .into_iter()
2294 .map(|cell| grid::Placement {
2295 bounds: cell.bounds,
2296 row_children: None,
2297 clip: cell.clip,
2298 })
2299 .collect()
2300 } else {
2301 let mut content = if pane || matches!(node.kind, "Loader" | "Window") {
2302 linear::Padding::read(node).inner_rect(content_bounds)
2303 } else {
2304 content_bounds
2305 };
2306 let title = (selection::radio_title_height(node, font_size)
2307 + modal_title.as_ref().map_or(0.0, |title| title.height)
2308 + group_title.as_ref().map_or_else(
2309 || group_box::title_height(node, font_size),
2310 |title| title.height,
2311 ))
2312 .min(bounds.height);
2313 content.y += title;
2314 content.height -= title;
2315 let rects = if matches!(node.kind, "Loader" | "LoaderCandidate") {
2316 node.children.iter().map(|_| content).collect()
2317 } else if let Some(geometry) = &swipe_delegate {
2318 node.children
2319 .iter()
2320 .map(|child| geometry.region(child.kind).bounds)
2321 .collect()
2322 } else if let Some(page) = &page {
2323 node.children
2324 .iter()
2325 .map(|child| {
2326 page.band(child)
2327 .unwrap_or_else(|| self.absolute_child(child, page.body))
2328 })
2329 .collect()
2330 } else if let Some(rects) = modal::picker_children(
2331 node,
2332 content,
2333 self.layout_direction.unwrap_or_default(),
2334 self.text,
2335 ) {
2336 rects
2337 } else if flow::uses_flow(node) {
2338 flow::children(
2339 node,
2340 content,
2341 self.layout_direction.unwrap_or_default(),
2342 self.text,
2343 )
2344 } else if let Some(axis) = linear::Axis::for_node(node) {
2345 linear::children(
2346 node,
2347 axis,
2348 content,
2349 self.layout_direction.unwrap_or_default(),
2350 self.text,
2351 )
2352 } else {
2353 self.absolute_children(node, content)
2354 };
2355 rects.into_iter().map(grid::Placement::plain).collect()
2356 };
2357 let child_clip = scroll_area.map_or(child_clip, |area| child_clip.intersect(area));
2358 let children: Vec<_> = node
2359 .materialized_children()
2360 .filter(|_| !node.expander_collapsed())
2361 .zip(placements)
2362 .map(|((index, child), placement)| {
2363 self.path.push(index);
2364 let is_handle = child.kind == "SplitHandle";
2365 let closable = xrack_runtime::tab_is_closable(node, child);
2366 let clip = page.as_ref().map_or(child_clip, |page| {
2367 child_clip.intersect(page.band(child).unwrap_or(page.body))
2368 });
2369 let region = swipe_delegate
2370 .as_ref()
2371 .map(|geometry| geometry.region(child.kind));
2372 let clip = region
2373 .as_ref()
2374 .map_or(clip, |region| clip.intersect(region.clip));
2375 let clip = view_cells::list_body_clip(
2376 clip,
2377 list_section_headers.as_deref().unwrap_or_default(),
2378 );
2379 let (clip, visible) = match tree_parts {
2380 Some((tree, has_children)) if child.kind == "TreeDisclosure" => {
2381 (clip.intersect(tree.indicator), visible && has_children)
2382 }
2383 Some((tree, _)) => (clip.intersect(tree.content), visible),
2384 None => (clip, visible),
2385 };
2386 let clip = if child.kind == "ProgressFill" {
2389 placement.bounds
2390 } else {
2391 clip
2392 };
2393 let scroll_part = Node::SCROLL_PARTS.contains(&child.kind);
2394 let clip = if scroll_part {
2395 clip.intersect(placement.bounds)
2396 } else {
2397 clip
2398 };
2399 let visible = visible
2400 && (!scroll_part || custom_scroll.is_some())
2401 && child.kind != "ComboPopup"
2402 && !(child.kind == "ComboContent" && xrack_runtime::combo_editable(node));
2403 let outer_shapes = placement
2404 .clip
2405 .as_ref()
2406 .map(|_| self.ancestor_shapes.clone());
2407 let pane = placement.clip.as_ref().map(|pane| {
2408 let table_world = pane
2409 .space
2410 .as_ref()
2411 .map_or(Affine::IDENTITY, |space| space.world);
2412 let to_parent = self
2413 .space
2414 .as_ref()
2415 .and_then(|space| space.inverse)
2416 .map_or(table_world, |inverse| table_world.then(inverse));
2417 if to_parent != Affine::IDENTITY {
2418 self.ancestor_shapes = Some(Arc::new(ClipChain {
2419 shape: RoundedClip {
2420 bounds: pane.bounds,
2421 radii: [0.0; 4],
2422 },
2423 parent: self.ancestor_shapes.clone(),
2424 space: pane.space.clone(),
2425 }));
2426 }
2427 (pane.bounds, to_parent)
2428 });
2429 let clip = pane.map_or(clip, |(bounds, to_parent)| {
2430 clip.intersect(to_parent.map_rect(bounds))
2431 });
2432 let visible = visible
2433 && region
2434 .as_ref()
2435 .is_none_or(|_| clip.width > 0.0 && clip.height > 0.0);
2436 let enabled = children_enabled
2437 && node.group_content_enabled()
2438 && region.is_none_or(|region| region.enabled);
2439 let mut child = if table_cells
2440 && !child.children.is_empty()
2441 && self.row_layouts.is_some()
2442 && self.space.is_none()
2443 && self.ancestor_shapes.is_none()
2444 && child.routing_row_key().is_none()
2445 && row_layout::cacheable(child)
2446 && let Some(row) = self.row_key
2447 {
2448 let outer_anchor = self.anchor;
2449 let outer_direction = self.layout_direction;
2450 self.layout_direction = child.layout_direction().or(outer_direction);
2451 let inputs = row_layout::RowInputs {
2452 size: Size::new(placement.bounds.width, placement.bounds.height),
2453 visible,
2454 enabled,
2455 layout_direction: self.layout_direction,
2456 };
2457 let slot = row_layout::Slot {
2458 row,
2459 column: Some(index),
2460 };
2461 let child =
2462 self.place_cached_content(child, placement.bounds, clip, inputs, slot);
2463 self.anchor = outer_anchor;
2464 self.layout_direction = outer_direction;
2465 child
2466 } else {
2467 self.place(
2468 child,
2469 placement.bounds,
2470 clip,
2471 visible,
2472 enabled,
2473 placement.row_children,
2474 )
2475 };
2476 if child.visible && closable {
2477 child.tab_close = selection::tab_close_rect(
2478 placement.bounds,
2479 self.layout_direction.unwrap_or_default(),
2480 self.text.text_scale() > 1.0,
2481 );
2482 }
2483 if let Some(shapes) = outer_shapes {
2484 self.ancestor_shapes = shapes;
2485 }
2486 if let Some((bounds, to_parent)) = pane
2487 && (to_parent != Affine::IDENTITY
2488 || child.local_transform() != Affine::IDENTITY)
2489 {
2490 child.table_pane = Some(Box::new((bounds, to_parent)));
2491 }
2492 if is_handle {
2493 child.enabled &= split
2494 .as_ref()
2495 .and_then(|geometry| geometry.handle(index))
2496 .is_some_and(SplitHandle::adjustable);
2497 }
2498 self.path.pop();
2499 child
2500 })
2501 .collect();
2502 let tumbler = (visible && matches!(node.kind, "Tumbler" | "PathView"))
2503 .then(|| {
2504 let wheel = xrack_runtime::Tumbler::from_node(node);
2505 let offset = self
2506 .input
2507 .map_or(0.0, |input| input.tumbler_offset(&wheel, &self.path));
2508 let mut geometry = if node.kind == "PathView" {
2509 TumblerGeometry::along_path(
2510 node,
2511 &wheel,
2512 bounds,
2513 offset,
2514 self.layout_direction.unwrap_or_default(),
2515 )?
2516 } else {
2517 TumblerGeometry::new(
2518 &wheel,
2519 bounds,
2520 offset,
2521 tumbler::scaled_row_height(node, self.text),
2522 )
2523 };
2524 if let Some(renderer) = &node.combo_option_renderer {
2525 let clip = clip.intersect(bounds);
2526 for row in &mut geometry.rows {
2527 let visible = clip.intersect(row.bounds);
2528 if visible.width <= 0.0 || visible.height <= 0.0 {
2529 continue;
2530 }
2531 let mut input = wheel.option_input(
2532 row.index,
2533 row.label.clone(),
2534 f64::from(row.displacement),
2535 enabled,
2536 );
2537 input.progress = f64::from(row.progress);
2538 if let Some(content) = renderer.render(input) {
2539 let layout =
2540 self.place(&content, row.bounds, visible, true, enabled, None);
2541 row.content = Some(Box::new((content, layout)));
2542 }
2543 }
2544 }
2545 Some(Box::new(geometry))
2546 })
2547 .flatten();
2548 LayoutNode {
2549 bounds,
2550 clip,
2551 visible,
2552 enabled,
2553 layout_direction: self.layout_direction.unwrap_or_default(),
2554 direction_override: self.layout_direction,
2555 content_bounds: scroll_area
2556 .or_else(|| {
2557 page.filter(|_| node.application_window)
2558 .map(|page| page.body)
2559 })
2560 .map(Box::new),
2561 scroll,
2562 list_section_headers,
2563 horizontal_scroll,
2564 horizontal_scroll_reversed,
2565 viewport_handle: node.viewport_handle.clone(),
2566 nested_list: node
2567 .list_row_renderer
2568 .clone()
2569 .filter(|_| self.row_key.is_some()),
2570 missing_list_rows: false,
2571 missing_descendant_list_rows: false,
2572 attached_scroll_bar: None,
2573 mouse_drag_pan: node.boolean("mouse-drag-pan-enabled", node.kind == "Flickable"),
2574 middle_mouse_pan: node.kind != "Flickable"
2575 || node.boolean("mouse-drag-pan-enabled", true),
2576 pan_axes: if node.kind == "Flickable" {
2577 let direction = match node.properties.get("flick-direction") {
2578 Some(xrack_runtime::Value::FlickDirection(direction)) => *direction,
2579 _ => xrack_runtime::FlickDirection::Both,
2580 };
2581 [Orientation::Horizontal, Orientation::Vertical]
2582 .map(|axis| node.boolean("interactive", true) && direction.allows(axis))
2583 } else {
2584 [true; 2]
2585 },
2586 elastic: overscroll::ElasticOptions::from_node(node),
2587 pull_to_refresh: node.boolean("pull-to-refresh", false),
2588 table,
2589 split,
2590 tab_header: None,
2591 tab_close: None,
2592 tab_strip: None,
2593 tumbler,
2594 switch_position,
2595 swipe_delegate,
2596 swipe_preview: None,
2597 styled_text: if visible && node.kind == "StyledText" {
2598 self.text
2599 .layout_styled_text(node, Size::new(bounds.width, bounds.height))
2600 .map(|mut plan| {
2601 if let Some(direction) = self.layout_direction {
2602 plan.align_in_direction(node, bounds.width, direction);
2603 }
2604 Box::new(plan)
2605 })
2606 } else {
2607 None
2608 },
2609 modal_title,
2610 group_title,
2611 font_size,
2612 overlays: None,
2613 paint_order: sibling_paint_order(node, children.len()),
2614 overflow,
2615 child_shape,
2616 ancestor_shapes,
2617 space,
2618 transform,
2619 table_pane: None,
2620 table_column_window: node.table_column_window.clone(),
2621 children,
2622 }
2623 }
2624
2625 fn list_scroll(
2626 &self,
2627 node: &Node,
2628 cells: &ViewCells,
2629 height: f32,
2630 rows: usize,
2631 ) -> ScrollLayout {
2632 let requested = self.scroll_request(node, Orientation::Vertical);
2633 let axis = ScrollLayout::new(requested.unwrap_or_default(), cells.extent(rows) - height);
2634 if node
2635 .viewport_handle
2636 .as_ref()
2637 .is_some_and(|handle| handle.has_bound_offset(Orientation::Vertical))
2638 {
2639 return axis;
2640 }
2641 let nested = node
2642 .list_row_renderer
2643 .as_ref()
2644 .filter(|_| self.row_key.is_some());
2645 let anchor = self
2646 .input
2647 .and_then(|input| {
2648 list_anchor::ListAnchor::find(
2649 &input.scroll_anchors,
2650 &self.path,
2651 nested.map(xrack_runtime::ListRowRenderer::scope),
2652 )
2653 })
2654 .filter(|_| {
2655 node.boolean("preserve-scroll-anchor", false) && !self.tree_root_changed(node)
2656 });
2657 if node.boolean(
2658 "follow-current",
2659 matches!(node.kind, "StandardListView" | "GridView"),
2660 ) && let Some(index) = input::scroll_selection(node)
2661 && anchor.map_or_else(
2662 || {
2663 requested.is_none()
2664 || if let Some(renderer) = nested {
2665 renderer.selection_changed(input::scroll_selection(node), cells.columns)
2666 } else {
2667 self.input.is_some_and(|input| {
2668 input.scroll_selection_changed(
2669 node,
2670 &self.path,
2671 cells.columns,
2672 self.layout_direction.unwrap_or_default(),
2673 self.text.text_scale(),
2674 )
2675 })
2676 }
2677 },
2678 |anchor| anchor.selection_changed(node),
2679 )
2680 {
2681 return cells.reveal(axis, index, height);
2682 }
2683 anchor
2684 .and_then(|anchor| anchor.restore(node, cells, requested.unwrap_or_default()))
2685 .map_or(axis, |offset| ScrollLayout::new(offset, axis.max_offset))
2686 }
2687
2688 fn scroll_view_children(
2689 &mut self,
2690 node: &Node,
2691 viewport: Rect,
2692 enabled: bool,
2693 horizontal_reversed: bool,
2694 ) -> (Vec<Rect>, ScrollLayout, ScrollLayout, Rect) {
2695 let (viewport, ScrollContent { extent, children }) =
2696 self.fit_scroll_content(node, viewport, horizontal_reversed);
2697 let horizontal = ScrollLayout::new(
2698 self.requested_scroll(node, Orientation::Horizontal),
2699 extent.width - viewport.width,
2700 );
2701 let vertical = ScrollLayout::new(
2702 self.requested_scroll(node, Orientation::Vertical),
2703 extent.height - viewport.height,
2704 );
2705 let elastic_offset = |axis| {
2706 if !enabled
2707 || !node.boolean("interactive", true)
2708 || matches!(node.properties.get("flick-direction"), Some(xrack_runtime::Value::FlickDirection(direction)) if !direction.allows(axis))
2709 || !overscroll::ElasticOptions::from_node(node)
2710 .is_some_and(overscroll::ElasticOptions::moves_contents)
2711 {
2712 return 0.0;
2713 }
2714 let offset = self
2715 .input
2716 .zip(node.viewport_handle.as_ref())
2717 .map_or(0.0, |(input, handle)| input.visual_overscroll(handle, axis));
2718 let (scroll, logical_offset) = if axis == Orientation::Horizontal {
2719 (
2720 horizontal,
2721 if horizontal_reversed { -offset } else { offset },
2722 )
2723 } else {
2724 (vertical, offset)
2725 };
2726 if scroll.max_offset > 0.0
2727 && ((logical_offset < 0.0 && scroll.offset == 0.0)
2728 || (logical_offset > 0.0 && scroll.offset == scroll.max_offset))
2729 {
2730 offset
2731 } else {
2732 0.0
2733 }
2734 };
2735 let physical_x = if horizontal_reversed {
2736 horizontal.max_offset - horizontal.offset
2737 } else {
2738 horizontal.offset
2739 };
2740 let keyboard_shift = self
2741 .input
2742 .and_then(Interaction::keyboard_avoidance)
2743 .filter(|(path, _)| *path == self.path)
2744 .map_or(0.0, |(_, shift)| shift);
2745 let origin = Point {
2746 x: viewport.x - physical_x - elastic_offset(Orientation::Horizontal),
2747 y: viewport.y - vertical.offset - elastic_offset(Orientation::Vertical)
2748 + keyboard_shift,
2749 };
2750 let rects = node
2751 .children
2752 .iter()
2753 .zip(children)
2754 .map(|(child, placement)| {
2755 let Some((x, y, width, height)) = placement else {
2756 return Rect::new(origin.x, origin.y, 0.0, 0.0);
2757 };
2758 let height = absolute_height(child, height, (extent.height - y.max(0.0)).max(0.0));
2759 Rect::new(origin.x + x, origin.y + y, width, height)
2760 })
2761 .collect();
2762 (rects, horizontal, vertical, viewport)
2763 }
2764
2765 fn measure_scroll_content(&mut self, node: &Node, viewport: Rect) -> ScrollContent {
2766 let explicit_width = node.relative_length("content-width", viewport.width);
2769 let explicit_height = node
2770 .relative_length("content-height", viewport.height)
2771 .or_else(|| node.length("viewport-height"));
2772 let reference = Size::new(
2773 viewport.width.max(explicit_width.unwrap_or(0.0)),
2774 viewport.height.max(explicit_height.unwrap_or(0.0)),
2775 );
2776 let mut extent = reference;
2777 let mut children = Vec::with_capacity(node.children.len());
2778 for child in &node.children {
2779 if !participates_in_flow(child) {
2780 children.push(None);
2781 continue;
2782 }
2783 let x = child.length("x").unwrap_or(0.0);
2784 let y = child.length("y").unwrap_or(0.0);
2785 let metrics = linear::measure(child, reference, self.text);
2786 let width = absolute_width(child, metrics.x, (reference.width - x.max(0.0)).max(0.0));
2787 let height = linear::measure_with_width(child, reference, Some(width), self.text).y;
2788 extent.width = extent.width.max(x + width);
2789 extent.height = extent.height.max(y + height.preferred);
2790 children.push(Some((x, y, width, height)));
2791 }
2792 if node.kind == "Flickable" {
2793 extent.width = explicit_width.unwrap_or(extent.width).max(0.0);
2794 extent.height = explicit_height.unwrap_or(extent.height).max(0.0);
2795 }
2796 ScrollContent { extent, children }
2797 }
2798
2799 fn fit_scroll_content(
2800 &mut self,
2801 node: &Node,
2802 bounds: Rect,
2803 mirrored: bool,
2804 ) -> (Rect, ScrollContent) {
2805 use xrack_runtime::ScrollBarPolicy;
2806
2807 if node.kind != "ScrollView" || !node.boolean("reserve-scroll-bar-space", false) {
2808 return (bounds, self.measure_scroll_content(node, bounds));
2809 }
2810 let thickness = scroll_bar::scroll_bar_thickness(bounds);
2811 if thickness < 1.0 {
2812 return (bounds, self.measure_scroll_content(node, bounds));
2813 }
2814 let policies = [Orientation::Horizontal, Orientation::Vertical]
2815 .map(|axis| node.scroll_bar_policy(axis));
2816 let mut fallback = None;
2817 for bars in [[false, false], [false, true], [true, false], [true, true]] {
2820 if !bars
2821 .iter()
2822 .zip(policies)
2823 .all(|(&shown, policy)| match policy {
2824 ScrollBarPolicy::AlwaysOn => shown,
2825 ScrollBarPolicy::AlwaysOff => !shown,
2826 ScrollBarPolicy::AsNeeded => true,
2827 })
2828 {
2829 continue;
2830 }
2831 let bottom = if bars[0] { thickness } else { 0.0 };
2832 let side = if bars[1] { thickness } else { 0.0 };
2833 let viewport = Rect::new(
2834 bounds.x + if mirrored { side } else { 0.0 },
2835 bounds.y,
2836 bounds.width - side,
2837 bounds.height - bottom,
2838 );
2839 let content = self.measure_scroll_content(node, viewport);
2840 let overflowing = [
2841 content.extent.width > viewport.width,
2842 content.extent.height > viewport.height,
2843 ];
2844 if bars
2845 .into_iter()
2846 .zip(policies)
2847 .zip(overflowing)
2848 .all(|((shown, policy), overflow)| {
2849 policy != ScrollBarPolicy::AsNeeded || shown == overflow
2850 })
2851 {
2852 return (viewport, content);
2853 }
2854 fallback = Some((viewport, content));
2855 }
2856 #[expect(
2859 clippy::expect_used,
2860 reason = "enumeration always includes the allowed combination of forced and optional scrollbars"
2861 )]
2862 fallback.expect("scrollbar policies allow a candidate")
2863 }
2864
2865 fn absolute_children(&mut self, node: &Node, content: Rect) -> Vec<Rect> {
2866 node.children
2867 .iter()
2868 .map(|child| self.absolute_child(child, content))
2869 .collect()
2870 }
2871
2872 fn absolute_child(&mut self, child: &Node, content: Rect) -> Rect {
2873 if !participates_in_flow(child) {
2874 return Rect::new(content.x, content.y, 0.0, 0.0);
2875 }
2876 let available = Size::new(content.width, content.height);
2877 let metrics = linear::measure(child, available, self.text);
2878 let width = absolute_width(child, metrics.x, content.width);
2879 let height = absolute_height(child, metrics.y, content.height);
2880 Rect::new(
2881 content.x + child.length("x").unwrap_or(0.0),
2882 content.y + child.length("y").unwrap_or(0.0),
2883 width,
2884 height,
2885 )
2886 }
2887}
2888
2889fn absolute_width(node: &Node, info: linear::AxisInfo, available: f32) -> f32 {
2890 if xrack_runtime::is_button(node.kind)
2891 || xrack_runtime::is_pane(node.kind)
2892 || matches!(
2893 node.kind,
2894 "Image" | "AnimatedImage" | "ToolSeparator" | "Loader"
2895 )
2896 || node.properties.contains_key("preferred-width")
2897 {
2898 info.preferred
2899 } else {
2900 info.clamp(available)
2901 }
2902}
2903
2904fn absolute_height(node: &Node, info: linear::AxisInfo, available: f32) -> f32 {
2905 if linear::intrinsic_item(node.kind)
2906 || matches!(node.kind, "ToolSeparator" | "Loader")
2907 || xrack_runtime::is_pane(node.kind)
2908 || node.properties.contains_key("preferred-height")
2909 {
2910 info.preferred
2911 } else {
2912 info.clamp(available)
2913 }
2914}