Skip to main content

repose_ui/layout/
engine.rs

1#![allow(non_snake_case)]
2
3use std::cell::RefCell;
4use std::collections::HashMap;
5use std::hash::{Hash, Hasher};
6use std::rc::Rc;
7
8use repose_core::*;
9use repose_tree::{LayoutConstraints, NodeId, ViewTree};
10use rustc_hash::{FxHashMap, FxHasher};
11use taffy::TaffyTree;
12use taffy::prelude::*;
13
14use crate::Interactions;
15use crate::textfield::TextFieldState;
16
17use super::*;
18impl Default for LayoutEngine {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl LayoutEngine {
25    pub fn layout_frame(
26        &mut self,
27        root: &View,
28        size_px: (u32, u32),
29        textfield_states: &HashMap<u64, Rc<RefCell<TextFieldState>>>,
30        interactions: &Interactions,
31        focused: Option<u64>,
32    ) -> (Scene, Vec<HitRegion>, Vec<SemNode>) {
33        let start = web_time::Instant::now();
34        repose_text::begin_frame();
35        self.stats = LayoutStats::default();
36        self.graphics_scope_epoch = self.graphics_scope_epoch.wrapping_add(1);
37
38        // 0a. Reset per-frame state
39        self.focus_group_stack.clear();
40
41        // 0b. Check global invalidation
42        let locals_stamp = Self::locals_stamp();
43        let locals_changed = self.last_locals_stamp != Some(locals_stamp);
44        if locals_changed {
45            self.layout_valid = false;
46            self.paint_cache.clear();
47            self.text_cache.clear();
48        }
49
50        let density_scale = locals::effective_density_scale();
51        let mut max_w_dp = size_px.0 as f32 / density_scale;
52        let mut max_h_dp = size_px.1 as f32 / density_scale;
53        if !max_w_dp.is_finite() || max_w_dp < 10.0 {
54            max_w_dp = 1280.0;
55        }
56        if !max_h_dp.is_finite() || max_h_dp < 10.0 {
57            max_h_dp = 800.0;
58        }
59        self.tree
60            .set_subcompose_scope(repose_core::SubcomposeScope::new(
61                Dp::ZERO,
62                Dp(max_w_dp),
63                Dp::ZERO,
64                Dp(max_h_dp),
65            ));
66        let root_node_id = self.tree.update(root);
67        self.stats.tree = self.tree.stats.clone();
68        let has_paint_mutation = !self.tree.paint_dirty_nodes().is_empty();
69        let size_changed = self.last_size_px != Some(size_px);
70        if has_paint_mutation || size_changed {
71            self.paint_generation = self.paint_generation.wrapping_add(1);
72        }
73        let has_tree_mutation =
74            !self.tree.dirty_nodes().is_empty() || !self.tree.removed_ids.is_empty();
75        if !self.scope_maps_valid || has_tree_mutation {
76            self.build_scope_maps();
77        }
78        if has_tree_mutation {
79            let mut scroll_node_ids = Vec::new();
80            let mut stack = vec![root_node_id];
81            while let Some(id) = stack.pop() {
82                let Some(node) = self.tree.get(id) else {
83                    continue;
84                };
85                if node.modifier.scroll.is_some() {
86                    scroll_node_ids.push(id);
87                }
88                stack.extend(node.children.iter().copied());
89            }
90            self.scroll_node_ids = scroll_node_ids;
91        }
92        if has_tree_mutation || has_paint_mutation {
93            self.deferred_z_cache.clear();
94            self.transform_layer_cache.clear();
95            self.shared_element_cache.clear();
96        }
97
98        // 2. Determine layout need
99        // 2a. Publish the current window size class as a default local so that
100        let class = locals::calculate_window_size_class(
101            (max_w_dp * density_scale) as u32,
102            (max_h_dp * density_scale) as u32,
103            density_scale,
104        );
105        if class != locals::window_size_class() {
106            locals::set_window_size_class_default(class);
107        }
108        locals::set_window_container_size(max_w_dp, max_h_dp);
109        let mut need_layout =
110            size_changed || !self.layout_valid || has_tree_mutation || locals_changed;
111
112        // Must force a style refresh for all nodes to keep physical sizes in sync with the new scale.
113        if locals_changed {
114            let all_ids: Vec<NodeId> = self.tree.iter_with_ids().map(|(id, _)| id).collect();
115            for id in all_ids {
116                self.tree.mark_dirty(id);
117            }
118            for st in self.scope_trees.values_mut() {
119                st.valid = false;
120            }
121            need_layout = true;
122        }
123
124        // NOTE: Needed to ensure that text is always re-measured with the new available width
125        if size_changed {
126            // Root tree text cache
127            for &node_id in self.text_cache.keys() {
128                if let Some(&taffy_id) = self.taffy_map.get(&node_id) {
129                    let _ = self.taffy.mark_dirty(taffy_id);
130                }
131            }
132            self.text_cache.clear();
133            // Scope tree text caches
134            for st in self.scope_trees.values_mut() {
135                for &node_id in st.text_cache.keys() {
136                    if let Some(&tid) = st.taffy_map.get(&node_id) {
137                        let _ = st.taffy.mark_dirty(tid);
138                    }
139                }
140                st.text_cache.clear();
141            }
142        }
143        if locals_changed {
144            for st in self.scope_trees.values_mut() {
145                st.text_cache.clear();
146            }
147        }
148
149        if has_tree_mutation {
150            let dirty: Vec<NodeId> = self.tree.dirty_nodes().iter().copied().collect();
151            for nid in dirty {
152                if self.text_cache.contains_key(&nid) {
153                    if let Some(&tid) = self.taffy_map.get(&nid) {
154                        let _ = self.taffy.mark_dirty(tid);
155                    }
156                    self.text_cache.remove(&nid);
157                }
158                for st in self.scope_trees.values_mut() {
159                    if st.text_cache.contains_key(&nid) {
160                        if let Some(&tid) = st.taffy_map.get(&nid) {
161                            let _ = st.taffy.mark_dirty(tid);
162                        }
163                        st.text_cache.remove(&nid);
164                    }
165                }
166                if let Some(&tid) = self.taffy_map.get(&nid) {
167                    let _ = self.taffy.mark_dirty(tid);
168                }
169                for st in self.scope_trees.values_mut() {
170                    if let Some(&tid) = st.taffy_map.get(&nid) {
171                        let _ = st.taffy.mark_dirty(tid);
172                    }
173                }
174                self.paint_cache.remove(&nid);
175            }
176        }
177
178        // Helpers: Dp/Sp authoring units -> px floats for Taffy.
179        // (Sp includes TextScale, like Compose `TextUnit.toPx`.)
180        let px = |v: Dp| v.to_px().0;
181        let font_px = |s: Sp| s.to_px().0;
182
183        // 3. Sync Taffy
184        // 3a. Sync scope-internal TaffyTrees first
185        self.sync_scope_trees(&font_px);
186        // 3b. Sync root TaffyTree (non-scope nodes + scope root markers)
187        self.sync_taffy_tree(root_node_id, &font_px);
188
189        // 4. Compute Layout
190        let taffy_root = self.taffy_map.get(&root_node_id).copied();
191        if let Some(taffy_root) = taffy_root {
192            if need_layout {
193                if let Ok(mut style) = self.taffy.style(taffy_root).cloned() {
194                    style.size.width = length(size_px.0 as f32);
195                    style.size.height = length(size_px.1 as f32);
196                    if let Err(e) = self.taffy.set_style(taffy_root, style) {
197                        log::error!("taffy set_style failed for root: {e:?}");
198                    }
199                } else {
200                    log::error!("taffy root style missing for {:?}", taffy_root);
201                }
202
203                let available = taffy::geometry::Size {
204                    width: AvailableSpace::Definite(size_px.0 as f32),
205                    height: AvailableSpace::Definite(size_px.1 as f32),
206                };
207
208                Self::run_measure_pass(
209                    &mut self.taffy,
210                    taffy_root,
211                    available,
212                    &self.tree,
213                    &mut self.text_cache,
214                    &self.reverse_map,
215                    &self.scope_root_map,
216                    &self.node_to_scope,
217                    &mut self.scope_trees,
218                    &font_px,
219                    &px,
220                    &mut self.baseline_map,
221                    &self.taffy_map,
222                    &mut self.baseline_shifts,
223                );
224
225                // 4a. Store Taffy-computed sizes for non-scope + scope-root nodes
226                for (&node_id, &taffy_id) in &self.taffy_map {
227                    if let Ok(layout) = self.taffy.layout(taffy_id) {
228                        let dp_w = layout.size.width / density_scale;
229                        let dp_h = layout.size.height / density_scale;
230                        let rect = repose_core::Rect {
231                            x: 0.0,
232                            y: 0.0,
233                            w: dp_w,
234                            h: dp_h,
235                        };
236                        self.tree
237                            .set_layout(node_id, rect, rect, LayoutConstraints::default());
238                    }
239                }
240
241                self.last_locals_stamp = Some(locals_stamp);
242
243                self.layout_valid = true;
244                self.last_size_px = Some(size_px);
245                self.stats.layout_misses += 1;
246            } else {
247                self.stats.layout_hits += 1;
248            }
249        }
250        self.stats.layout_time_ms = (web_time::Instant::now() - start).as_secs_f32() * 1000.0;
251
252        // 4.5. Advance scroll physics (pre-paint, so paint only reads offset)
253        self.walk_tick(root_node_id);
254
255        // 5. Paint
256        let t_paint = web_time::Instant::now();
257        self.focus_interaction_sources.clear();
258        let (scene, hits, sems) = self.paint(
259            root_node_id,
260            textfield_states,
261            interactions,
262            focused,
263            &font_px,
264        );
265        self.stats.paint_time_ms = (web_time::Instant::now() - t_paint).as_secs_f32() * 1000.0;
266
267        // Fire focus change callbacks.
268        if self.prev_focused != focused {
269            if let Some(old_id) = self.prev_focused {
270                if let Some(cb) = self.focus_callbacks.get(&old_id) {
271                    (cb)(false);
272                }
273                if let Some(src) = self.focus_interaction_sources.get(&old_id) {
274                    src.to_mutable().emit(Interaction::Unfocus);
275                }
276            }
277            if let Some(new_id) = focused {
278                if let Some(cb) = self.focus_callbacks.get(&new_id) {
279                    (cb)(true);
280                }
281                if let Some(src) = self.focus_interaction_sources.get(&new_id) {
282                    src.to_mutable().emit(Interaction::Focus);
283                }
284            }
285            self.prev_focused = focused;
286        }
287
288        // Clean up callbacks for removed nodes
289        for &node_id in &self.tree.removed_ids {
290            if let Some(&vid) = self.view_ids.get(&node_id) {
291                self.focus_callbacks.remove(&vid);
292                self.focus_interaction_sources.remove(&vid);
293            }
294        }
295
296        self.tree.clear_dirty();
297        (scene, hits, sems)
298    }
299
300    pub fn intrinsic_size(&mut self, view: &View, mode: IntrinsicSizeMode) -> (f32, f32) {
301        let px_closure = |v: Dp| v.to_px().0;
302        let font_px_closure = |s: Sp| s.to_px().0;
303
304        let mut temp_taffy = taffy::TaffyTree::new();
305        let root_tid = self.build_taffy_subtree(view, &mut temp_taffy, &font_px_closure);
306
307        let avail = match mode {
308            IntrinsicSizeMode::MinContent => taffy::geometry::Size {
309                width: taffy::style::AvailableSpace::MinContent,
310                height: taffy::style::AvailableSpace::MinContent,
311            },
312            IntrinsicSizeMode::MaxContent => taffy::geometry::Size {
313                width: taffy::style::AvailableSpace::MaxContent,
314                height: taffy::style::AvailableSpace::MaxContent,
315            },
316        };
317
318        let mut text_cache: FxHashMap<NodeId, TextLayout> = FxHashMap::default();
319        let reverse_map: FxHashMap<taffy::NodeId, NodeId> = FxHashMap::default();
320        let mut baseline_map: FxHashMap<NodeId, TextBaselines> = FxHashMap::default();
321        // Intrinsic queries don't consume shifts; the growth loop needs maps
322        // matching `temp_taffy`, so pass throwaways (no-ops, as today).
323        let empty_map: FxHashMap<NodeId, taffy::NodeId> = FxHashMap::default();
324        let mut dropped_shifts: FxHashMap<NodeId, f32> = FxHashMap::default();
325
326        Self::run_measure_pass(
327            &mut temp_taffy,
328            root_tid,
329            avail,
330            &self.tree,
331            &mut text_cache,
332            &reverse_map,
333            &self.scope_root_map,
334            &self.node_to_scope,
335            &mut self.scope_trees,
336            &font_px_closure,
337            &px_closure,
338            &mut baseline_map,
339            &empty_map,
340            &mut dropped_shifts,
341        );
342
343        let layout = temp_taffy.layout(root_tid).ok();
344        match layout {
345            Some(l) => (l.size.width, l.size.height),
346            None => (0.0, 0.0),
347        }
348    }
349
350    pub fn new() -> Self {
351        Self {
352            tree: ViewTree::new(),
353            taffy: TaffyTree::new(),
354            taffy_map: FxHashMap::default(),
355            reverse_map: FxHashMap::default(),
356            scope_trees: HashMap::new(),
357            scope_root_map: FxHashMap::default(),
358            node_to_scope: FxHashMap::default(),
359            scope_root_ids: FxHashMap::default(),
360            scope_maps_valid: false,
361            scroll_node_ids: Vec::new(),
362            deferred_z_cache: FxHashMap::default(),
363            transform_layer_cache: FxHashMap::default(),
364            shared_element_cache: FxHashMap::default(),
365            shared_element_bundles: Vec::new(),
366            shared_element_depth: 0,
367            text_cache: FxHashMap::default(),
368            baseline_map: FxHashMap::default(),
369            baseline_shifts: FxHashMap::default(),
370            last_size_px: None,
371            layout_valid: false,
372            paint_cache: FxHashMap::default(),
373            stats: LayoutStats::default(),
374            last_locals_stamp: None,
375            view_ids: FxHashMap::default(),
376            next_view_id: 1,
377            layer_id_counter: 0,
378            paint_generation: 0,
379            graphics_scope_epoch: 0,
380            prev_focused: None,
381            focus_callbacks: FxHashMap::default(),
382            focus_interaction_sources: FxHashMap::default(),
383            prev_observed_rects: FxHashMap::default(),
384            focus_group_stack: Vec::new(),
385        }
386    }
387
388    pub(crate) fn layout_for_node(&self, node_id: NodeId) -> taffy::prelude::Layout {
389        let mut l = self.raw_layout_for_node(node_id);
390        // RowScope baseline-alignment shifts (no-op when absent).
391        if let Some(s) = self.baseline_shift_for(node_id) {
392            l.location.y += s;
393        }
394        // Compose-style post-layout offsets. Only the returned copy is moved so
395        // the parent's Taffy measurement stays untouched. The paint walk uses
396        // this same layout, so geometry, children and hit regions shift together.
397        if let Some(node) = self.tree.get(node_id) {
398            let m = &node.modifier;
399            if let Some((x, y)) = m.layout_offset {
400                let x_px = x.to_px().0;
401                l.location.x += if locals::text_direction() == locals::TextDirection::Rtl {
402                    -x_px
403                } else {
404                    x_px
405                };
406                l.location.y += y.to_px().0;
407            }
408            if let Some((x, y)) = m.absolute_layout_offset {
409                l.location.x += x.to_px().0;
410                l.location.y += y.to_px().0;
411            }
412            if let Some(p) = m.padding_from_baseline
413                && m.baseline_align.is_none()
414            {
415                l.location.y += p.to_px().0;
416            }
417        }
418        l
419    }
420
421    /// Baseline shift for `node_id`, mirroring `raw_layout_for_node`'s
422    /// tree resolution so shifts come from the tree that laid the node out.
423    fn baseline_shift_for(&self, node_id: NodeId) -> Option<f32> {
424        if self.scope_root_map.contains_key(&node_id)
425            && let Some(&s) = self.baseline_shifts.get(&node_id)
426        {
427            return Some(s);
428        }
429        if let Some(parent_id) = self.tree.get(node_id).and_then(|n| n.parent)
430            && let Some(outer_key) = self.node_to_scope.get(&parent_id)
431            && let Some(st) = self.scope_trees.get(outer_key)
432            && let Some(&s) = st.baseline_shifts.get(&node_id)
433        {
434            return Some(s);
435        }
436        if let Some(key) = self.node_to_scope.get(&node_id)
437            && let Some(st) = self.scope_trees.get(key)
438            && let Some(&s) = st.baseline_shifts.get(&node_id)
439        {
440            return Some(s);
441        }
442        self.baseline_shifts.get(&node_id).copied()
443    }
444
445    fn raw_layout_for_node(&self, node_id: NodeId) -> taffy::prelude::Layout {
446        fn fallback() -> taffy::prelude::Layout {
447            log::error!("layout_for_node: missing taffy layout, returning zero rect");
448            taffy::prelude::Layout {
449                size: taffy::geometry::Size {
450                    width: 0.0,
451                    height: 0.0,
452                },
453                location: taffy::geometry::Point { x: 0.0, y: 0.0 },
454                ..Default::default()
455            }
456        }
457        if self.scope_root_map.contains_key(&node_id) {
458            if let Some(&tid) = self.taffy_map.get(&node_id) {
459                if let Ok(l) = self.taffy.layout(tid) {
460                    return *l;
461                }
462                log::error!(
463                    "layout_for_node: taffy layout missing for scope root {:?}",
464                    node_id
465                );
466                return fallback();
467            }
468            if let Some(parent_id) = self.tree.get(node_id).and_then(|n| n.parent)
469                && let Some(outer_key) = self.node_to_scope.get(&parent_id)
470                && let Some(st) = self.scope_trees.get(outer_key)
471                && let Some(&tid) = st.taffy_map.get(&node_id)
472                && let Ok(l) = st.taffy.layout(tid)
473            {
474                return *l;
475            }
476            if let Some(key) = self.node_to_scope.get(&node_id)
477                && let Some(st) = self.scope_trees.get(key)
478                && let Some(&tid) = st.taffy_map.get(&node_id)
479                && let Ok(l) = st.taffy.layout(tid)
480            {
481                return *l;
482            }
483            return fallback();
484        }
485        if let Some(key) = self.node_to_scope.get(&node_id)
486            && let Some(st) = self.scope_trees.get(key)
487        {
488            if let Some(&tid) = st.taffy_map.get(&node_id) {
489                if let Ok(l) = st.taffy.layout(tid) {
490                    return *l;
491                }
492                log::error!(
493                    "layout_for_node: scope taffy layout missing for {:?}",
494                    node_id
495                );
496                return fallback();
497            }
498            log::error!("layout_for_node: scope taffy_map missing for {:?}", node_id);
499            return fallback();
500        }
501        if let Some(&tid) = self.taffy_map.get(&node_id) {
502            if let Ok(l) = self.taffy.layout(tid) {
503                return *l;
504            }
505            log::error!("layout_for_node: taffy layout missing for {:?}", node_id);
506        } else {
507            log::error!("layout_for_node: taffy_map missing for {:?}", node_id);
508        }
509        fallback()
510    }
511
512    pub(crate) fn ensure_view_id(&mut self, node_id: NodeId) -> u64 {
513        if let Some(&id) = self.view_ids.get(&node_id) {
514            return id;
515        }
516        let id = self.next_view_id;
517        self.next_view_id += 1;
518        self.view_ids.insert(node_id, id);
519        id
520    }
521
522    /// Debug dump of the taffy subtree rooted at `node_id` (styles +
523    /// computed layout), for the devtools inspector. Empty string when the
524    /// node has no taffy node. Backed by taffy's `write_tree`.
525    pub fn debug_taffy_subtree(&self, node_id: NodeId) -> String {
526        let trees: Vec<(&taffy::TaffyTree<NodeContext>, taffy::NodeId)> = if let Some(key) =
527            self.node_to_scope.get(&node_id)
528            && let Some(st) = self.scope_trees.get(key)
529            && let Some(&tid) = st.taffy_map.get(&node_id)
530        {
531            vec![(&st.taffy, tid)]
532        } else if let Some(&tid) = self.taffy_map.get(&node_id) {
533            vec![(&self.taffy, tid)]
534        } else {
535            Vec::new()
536        };
537        let mut out = String::new();
538        for (tree, tid) in trees {
539            let mut buf = Vec::new();
540            if taffy::util::write_tree(&mut buf, tree, tid).is_ok() {
541                out.push_str(&String::from_utf8_lossy(&buf));
542            }
543        }
544        out
545    }
546
547    /// One-line grid summary (track counts, line positions, resolved
548    /// templates) for a grid container, for the devtools inspector.
549    /// `None` when the node is not a grid container with detailed info.
550    /// Requires taffy's `detailed_layout_info` feature (default-on).
551    pub fn debug_grid_summary(&self, node_id: NodeId) -> Option<String> {
552        let tid = if let Some(key) = self.node_to_scope.get(&node_id)
553            && let Some(st) = self.scope_trees.get(key)
554            && let Some(&tid) = st.taffy_map.get(&node_id)
555        {
556            return Self::grid_summary_for(&st.taffy, tid);
557        } else {
558            self.taffy_map.get(&node_id).copied()?
559        };
560        Self::grid_summary_for(&self.taffy, tid)
561    }
562
563    fn grid_summary_for(
564        tree: &taffy::TaffyTree<NodeContext>,
565        tid: taffy::NodeId,
566    ) -> Option<String> {
567        let taffy::tree::DetailedLayoutInfo::Grid(grid) = tree.detailed_layout_info(tid) else {
568            return None;
569        };
570        Some(format!(
571            "grid rows=({} explicit of {} tracks) cols=({} explicit of {} tracks) rows=[{}] cols=[{}] items={}",
572            grid.rows.explicit_tracks,
573            grid.rows.explicit_tracks
574                + grid.rows.negative_implicit_tracks
575                + grid.rows.positive_implicit_tracks,
576            grid.columns.explicit_tracks,
577            grid.columns.explicit_tracks
578                + grid.columns.negative_implicit_tracks
579                + grid.columns.positive_implicit_tracks,
580            grid.grid_template_rows(),
581            grid.grid_template_columns(),
582            grid.items.len(),
583        ))
584    }
585
586    pub(crate) fn locals_stamp() -> u64 {
587        let mut h = FxHasher::default();
588
589        // These affect layout measurement and/or flex direction decisions.
590        locals::density().scale.to_bits().hash(&mut h);
591        locals::ui_scale().0.to_bits().hash(&mut h);
592        locals::text_scale().0.to_bits().hash(&mut h);
593
594        let dir_u8 = match locals::text_direction() {
595            locals::TextDirection::Ltr => 0u8,
596            locals::TextDirection::Rtl => 1u8,
597        };
598        dir_u8.hash(&mut h);
599        // For font fallback generation (ex: emoji loaded dynamically)
600        repose_text::font_generation().hash(&mut h);
601
602        h.finish()
603    }
604}