Skip to main content

repose_ui/layout/
types.rs

1#![allow(non_snake_case)]
2
3use std::collections::HashMap;
4use std::rc::Rc;
5use std::sync::Arc;
6
7use repose_core::*;
8use repose_tree::{NodeId, TreeStats, ViewTree};
9
10use crate::hit_testing::HitRegionMetadata;
11use rustc_hash::FxHashMap;
12use taffy::TaffyTree;
13
14/// Measured text geometry feeding baseline alignment, by ViewTree NodeId.
15/// `first`/`last` are real baselines (px from the text block top);
16/// `content_h` is the un-stretched content height. Content height matters
17/// because `Row` children default to `stretch`: layout height follows the
18/// row, content height does not, and the grow pass must fit content rather
19/// than stretch slack.
20#[derive(Clone, Copy, Debug, Default)]
21pub(crate) struct TextBaselines {
22    pub(crate) first: f32,
23    pub(crate) last: f32,
24    pub(crate) content_h: f32,
25}
26
27pub(crate) struct ScopeLayoutTree {
28    pub(crate) taffy: TaffyTree<NodeContext>,
29    pub(crate) taffy_map: FxHashMap<NodeId, taffy::NodeId>,
30    pub(crate) reverse_map: FxHashMap<taffy::NodeId, NodeId>,
31    pub(crate) root_taffy_id: Option<taffy::NodeId>,
32    pub(crate) last_constraints:
33        Option<(taffy::Size<Option<f32>>, taffy::Size<taffy::AvailableSpace>)>,
34    pub(crate) cached_size: Option<taffy::Size<f32>>,
35    pub(crate) text_cache: FxHashMap<NodeId, TextLayout>,
36    pub(crate) valid: bool,
37    /// Measured text geometry by ViewTree NodeId, filled during measure.
38    /// Consumed by the baseline-alignment post-pass (and grow pass).
39    pub(crate) baseline_map: FxHashMap<NodeId, TextBaselines>,
40    /// Vertical px shifts from baseline alignment, applied in
41    /// `layout_for_node`. Overwritten every layout of this tree.
42    pub(crate) baseline_shifts: FxHashMap<NodeId, f32>,
43}
44
45impl ScopeLayoutTree {
46    pub(crate) fn new() -> Self {
47        Self {
48            taffy: TaffyTree::new(),
49            taffy_map: FxHashMap::default(),
50            reverse_map: FxHashMap::default(),
51            root_taffy_id: None,
52            last_constraints: None,
53            cached_size: None,
54            text_cache: FxHashMap::default(),
55            valid: false,
56            baseline_map: FxHashMap::default(),
57            baseline_shifts: FxHashMap::default(),
58        }
59    }
60}
61
62pub struct LayoutEngine {
63    pub(crate) tree: ViewTree,
64
65    /// Root Taffy layout tree (inter-scope layout + non-scope nodes).
66    pub(crate) taffy: TaffyTree<NodeContext>,
67
68    pub(crate) taffy_map: FxHashMap<NodeId, taffy::NodeId>,
69
70    /// Reverse map: root Taffy NodeId to ViewTree NodeId.
71    pub(crate) reverse_map: FxHashMap<taffy::NodeId, NodeId>,
72
73    /// Per-scope TaffyTrees for scope! macro isolation.
74    pub(crate) scope_trees: HashMap<String, ScopeLayoutTree>,
75
76    /// ViewTree NodeId -> scope key for scope boundary root nodes.
77    pub(crate) scope_root_map: FxHashMap<NodeId, String>,
78
79    /// ViewTree NodeId -> scope key for ALL nodes belonging to a scope.
80    pub(crate) node_to_scope: FxHashMap<NodeId, String>,
81
82    pub(crate) scope_root_ids: FxHashMap<String, Vec<NodeId>>,
83    pub(crate) scope_maps_valid: bool,
84    pub(crate) scroll_node_ids: Vec<NodeId>,
85    pub(crate) deferred_z_cache: FxHashMap<NodeId, bool>,
86    pub(crate) transform_layer_cache: FxHashMap<NodeId, bool>,
87    pub(crate) shared_element_cache: FxHashMap<NodeId, bool>,
88    pub(crate) shared_element_bundles: Vec<SharedElementBundle>,
89    pub(crate) shared_element_depth: usize,
90
91    /// Cached text layouts for non-scope nodes (persists across frames).
92    pub(crate) text_cache: FxHashMap<NodeId, TextLayout>,
93
94    /// Measured text geometry by ViewTree NodeId, filled during measure.
95    /// Consumed by the baseline-alignment post-pass (and grow pass).
96    pub(crate) baseline_map: FxHashMap<NodeId, TextBaselines>,
97    /// Vertical px shifts from baseline alignment, applied in
98    /// `layout_for_node`. Overwritten every root layout.
99    pub(crate) baseline_shifts: FxHashMap<NodeId, f32>,
100
101    /// Last window size used for layout.
102    pub(crate) last_size_px: Option<(u32, u32)>,
103
104    /// Whether root Taffy has a valid computed layout for `last_size_px`.
105    pub(crate) layout_valid: bool,
106
107    /// Repaint-boundary cache (SceneNodes + hits + semantics).
108    pub(crate) paint_cache: FxHashMap<NodeId, PaintCacheEntry>,
109
110    /// Statistics from the last frame.
111    pub stats: LayoutStats,
112
113    /// Tracks the previously focused view ID to detect focus changes.
114    pub(crate) prev_focused: Option<u64>,
115
116    /// Callbacks registered via `on_focus_changed` modifier, keyed by view ID.
117    pub(crate) focus_callbacks: FxHashMap<u64, Rc<dyn Fn(bool)>>,
118
119    /// Last "locals" stamp used for layout decisions (density/text scale/dir).
120    pub(crate) last_locals_stamp: Option<u64>,
121
122    /// Stable, unique ViewId per ViewTree NodeId.
123    pub(crate) view_ids: FxHashMap<NodeId, u64>,
124    pub(crate) next_view_id: u64,
125
126    /// Monotonic counter for graphics layer ids, assigned during paint.
127    pub(crate) layer_id_counter: u32,
128
129    pub(crate) paint_generation: u64,
130
131    pub(crate) graphics_scope_epoch: u64,
132
133    /// Previous absolute rects for `on_globally_positioned` / `on_size_changed` callbacks.
134    pub(crate) prev_observed_rects: FxHashMap<u64, repose_core::Rect>,
135
136    /// Stack of active focus group IDs. When non-empty, newly created hit regions
137    /// get `focus_group_id` set to the top of this stack. A focus group is entered
138    /// when a node with `modifier.focus_group == true` is traversed.
139    pub(crate) focus_group_stack: Vec<u64>,
140
141    /// InteractionSources that should receive Focus/Unfocus for the current paint tree,
142    /// keyed by view ID.
143    pub(crate) focus_interaction_sources: FxHashMap<u64, InteractionSource>,
144}
145
146/// Statistics about layout performance.
147#[derive(Clone, Debug, Default)]
148pub struct LayoutStats {
149    pub tree: TreeStats,
150
151    /// Taffy nodes created this frame.
152    pub taffy_created: usize,
153
154    /// Taffy nodes reused this frame.
155    pub taffy_reused: usize,
156
157    /// Layout cache hits.
158    pub layout_hits: usize,
159
160    /// Layout cache misses.
161    pub layout_misses: usize,
162
163    /// Paint cache hits (repaint boundaries).
164    pub paint_cache_hits: usize,
165
166    /// Paint cache misses (repaint boundaries).
167    pub paint_cache_misses: usize,
168
169    /// Nodes skipped due to clip/viewport culling.
170    pub paint_culled: usize,
171
172    /// Total time for layout+paint (ms).
173    pub layout_time_ms: f32,
174
175    /// Total time spent in the paint pass only (ms).
176    pub paint_time_ms: f32,
177}
178
179pub(crate) struct SharedElementBundle {
180    pub(crate) state: SharedElementState,
181    pub(crate) world_rect: Rect,
182    pub(crate) local_to_world: [f64; 9],
183    pub(crate) scene_index: usize,
184    pub(crate) hit_index: usize,
185    pub(crate) sem_index: usize,
186    pub(crate) scene: Vec<SceneNode>,
187    pub(crate) hits: Vec<HitRegion>,
188    pub(crate) sems: Vec<SemNode>,
189}
190
191#[derive(Clone)]
192pub(crate) struct PaintCacheEntry {
193    pub(crate) subtree_hash: u64,
194    pub(crate) stamp: u64,
195    pub(crate) rect: repose_core::Rect,
196    pub(crate) parent_offset_px: (f32, f32),
197    pub(crate) sem_parent: Option<u64>,
198    pub(crate) alpha_q: u8,
199    pub(crate) hit_context_key: u64,
200    pub(crate) paint_generation: u64,
201    pub(crate) nodes: Rc<Vec<SceneNode>>,
202    pub(crate) hits: Rc<Vec<HitRegion>>,
203    pub(crate) hit_metadata: Rc<Vec<Option<Arc<HitRegionMetadata>>>>,
204    pub(crate) sems: Rc<Vec<SemNode>>,
205}
206
207/// Selects the intrinsic sizing mode for [`LayoutEngine::intrinsic_size`].
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209pub enum IntrinsicSizeMode {
210    /// Smallest size at which the view's content does not overflow.
211    MinContent,
212    /// Largest size the view's content would take if unconstrained.
213    MaxContent,
214}
215
216/// Context stored with each Taffy node.
217/// Text sizes are [`Sp`](repose_core::Sp) (authoring units); converted to px
218/// by the `font_px` closure at the measure boundary.
219#[derive(Clone)]
220pub(crate) enum NodeContext {
221    Text {
222        text: String,
223        font_sp: Sp,
224        soft_wrap: bool,
225        max_lines: Option<usize>,
226        overflow: TextOverflow,
227        font_family: Option<&'static str>,
228        font_weight: FontWeight,
229        font_style: FontStyle,
230        letter_spacing: Sp,
231        line_height: Sp,
232        font_variation_settings: Option<Arc<str>>,
233        annotations: Option<Arc<[TextSpan]>>,
234    },
235    Container,
236    ScrollContainer,
237    TextInput {
238        multiline: bool,
239    },
240    /// An image leaf, carrying its natural pixel size so an unsized view can
241    /// report an intrinsic size. `w`/`h` are `0.0` while the size is unknown
242    /// (encoded uploads are decoded by the renderer), which measures to zero
243    /// exactly like a Compose `Painter` with an unspecified `intrinsicSize`.
244    Image {
245        w: f32,
246        h: f32,
247        fit: ImageFit,
248    },
249}
250
251#[derive(Clone)]
252pub(crate) struct TextLayout {
253    pub(crate) lines: Vec<String>,
254    /// Byte ranges into the original text for each line (used for annotation splitting).
255    pub(crate) line_ranges: Vec<(usize, usize)>,
256    pub(crate) size_px: f32,
257    pub(crate) line_h_px: f32,
258    /// Pre-measured width per line, in the same order as `lines`.
259    pub(crate) line_widths: Vec<f32>,
260    /// Per-line height in px (accounts for larger annotated font sizes, baseline shifts, stroke).
261    /// Uniform fallback is `line_h_px` when empty.
262    pub(crate) line_heights: Vec<f32>,
263}