Skip to main content

velox_engine/pod/
layout_cache.rs

1//! `PodPool` 子视图布局缓存(Pass 1/2/3 重排边界)与递归 `SubView` 渲染展开。
2
3use crate::arena::ScratchArena;
4use crate::element::Element;
5
6use super::pool::{
7    PodPool, ReadersMask, LAYOUT_FLAG_CLAIMED, LAYOUT_FLAG_DIRTY_DESCENDANT,
8    LAYOUT_FLAG_HAS_SUBVIEWS, LAYOUT_FLAG_MULTI_MOUNTED, LAYOUT_FLAG_PARENT_NON_AUTO_H,
9    LAYOUT_FLAG_PARENT_NON_AUTO_W, LAYOUT_FLAG_SUBTREE_CLEAN,
10};
11use super::{FrameScope, PodId};
12
13impl PodPool {
14    #[inline]
15    pub(crate) fn record_relayout_boundary_hit(&self) {
16        self.relayout_boundary_hits
17            .set(self.relayout_boundary_hits.get().wrapping_add(1));
18    }
19
20    #[inline]
21    pub(crate) fn begin_layout_pass(&self) {
22        for slot in self.slots.iter() {
23            if slot.occupied() {
24                slot.layout_flags.set(
25                    slot.layout_flags.get() & !(LAYOUT_FLAG_CLAIMED | LAYOUT_FLAG_MULTI_MOUNTED),
26                );
27            }
28        }
29    }
30
31    #[inline]
32    pub(crate) fn try_claim_subview_layout(
33        &self,
34        id: PodId,
35        parent_non_auto_w: bool,
36        parent_non_auto_h: bool,
37    ) -> bool {
38        let Some(slot) = self.slots.get(id.0 as usize) else {
39            return false;
40        };
41        let mut flags = slot.layout_flags.get();
42        if (flags & LAYOUT_FLAG_CLAIMED) == 0 {
43            flags |= LAYOUT_FLAG_CLAIMED;
44            flags &= !(LAYOUT_FLAG_MULTI_MOUNTED
45                | LAYOUT_FLAG_PARENT_NON_AUTO_W
46                | LAYOUT_FLAG_PARENT_NON_AUTO_H);
47            if parent_non_auto_w {
48                flags |= LAYOUT_FLAG_PARENT_NON_AUTO_W;
49            }
50            if parent_non_auto_h {
51                flags |= LAYOUT_FLAG_PARENT_NON_AUTO_H;
52            }
53            slot.layout_flags.set(flags);
54            true
55        } else {
56            flags |= LAYOUT_FLAG_MULTI_MOUNTED;
57            flags &= !LAYOUT_FLAG_SUBTREE_CLEAN;
58            slot.layout_flags.set(flags);
59            slot.cached_layout.set(core::ptr::null_mut());
60            false
61        }
62    }
63
64    #[inline]
65    pub(crate) fn get_clean_subview_layout(
66        &self,
67        id: PodId,
68        arena: &ScratchArena,
69    ) -> Option<(*mut u8, i16, i16)> {
70        let slot = self.slots.get(id.0 as usize)?;
71        let flags = slot.layout_flags.get();
72        if (flags & (LAYOUT_FLAG_SUBTREE_CLEAN | LAYOUT_FLAG_MULTI_MOUNTED))
73            != LAYOUT_FLAG_SUBTREE_CLEAN
74        {
75            return None;
76        }
77        let ptr = slot.cached_layout.get();
78        if ptr.is_null() || !arena.contains_temp_ptr(ptr as *const u8) {
79            return None;
80        }
81        Some((ptr, slot.pass1_min_w.get(), slot.pass1_pref_w.get()))
82    }
83
84    #[inline]
85    pub(crate) fn get_subview_pass1(&self, id: PodId) -> (i16, i16) {
86        self.slots
87            .get(id.0 as usize)
88            .map(|s| (s.pass1_min_w.get(), s.pass1_pref_w.get()))
89            .unwrap_or((0, 0))
90    }
91
92    #[inline]
93    pub(crate) fn save_subview_pass1(&self, id: PodId, min_w: i16, pref_w: i16) {
94        if let Some(slot) = self.slots.get(id.0 as usize) {
95            slot.pass1_min_w.set(min_w);
96            slot.pass1_pref_w.set(pref_w);
97        }
98    }
99
100    #[inline]
101    pub(crate) fn get_subview_solved_xw(&self, id: PodId) -> (i16, i16) {
102        self.slots
103            .get(id.0 as usize)
104            .map(|s| {
105                let b = s.cached_bounds.get();
106                (b.x, b.w)
107            })
108            .unwrap_or((0, 0))
109    }
110
111    #[inline]
112    pub(crate) fn save_subview_solved_xw(&self, id: PodId, x: i16, w: i16) {
113        if let Some(slot) = self.slots.get(id.0 as usize) {
114            let mut b = slot.cached_bounds.get();
115            b.x = x;
116            b.w = w;
117            slot.cached_bounds.set(b);
118        }
119    }
120
121    #[inline]
122    pub(crate) fn get_subview_pass3(&self, id: PodId) -> (i16, i16) {
123        self.slots
124            .get(id.0 as usize)
125            .map(|s| (s.pass3_min_h.get(), s.pass3_pref_h.get()))
126            .unwrap_or((0, 0))
127    }
128
129    #[inline]
130    pub(crate) fn save_subview_pass3_and_node(
131        &self,
132        id: PodId,
133        min_h: i16,
134        pref_h: i16,
135        node_ptr: *mut u8,
136    ) {
137        if let Some(slot) = self.slots.get(id.0 as usize) {
138            slot.pass3_min_h.set(min_h);
139            slot.pass3_pref_h.set(pref_h);
140            slot.cached_layout.set(node_ptr);
141        }
142    }
143
144    #[inline]
145    pub(crate) fn update_subview_node_ptr(&self, id: PodId, node_ptr: *mut u8) {
146        if let Some(slot) = self.slots.get(id.0 as usize) {
147            slot.cached_layout.set(node_ptr);
148        }
149    }
150
151    #[inline]
152    pub(crate) fn get_subview_cached_element(
153        &self,
154        id: PodId,
155        arena: &ScratchArena,
156    ) -> Option<&'static Element<'static>> {
157        let slot = self.slots.get(id.0 as usize)?;
158        let ptr = slot.cached_element.get();
159        if ptr.is_null() || !arena.contains_temp_ptr(ptr as *const u8) {
160            return None;
161        }
162        Some(unsafe { &*ptr })
163    }
164
165    #[inline]
166    pub(crate) fn can_relayout_subview_in_place(
167        &self,
168        id: PodId,
169        arena: &ScratchArena,
170    ) -> Option<*mut u8> {
171        let slot = self.slots.get(id.0 as usize)?;
172        if !slot.occupied() {
173            return None;
174        }
175        let flags = slot.layout_flags.get();
176        if (flags & (LAYOUT_FLAG_DIRTY_DESCENDANT | LAYOUT_FLAG_MULTI_MOUNTED)) != 0 {
177            return None;
178        }
179        let layout_ptr = slot.cached_layout.get();
180        if layout_ptr.is_null() || !arena.contains_temp_ptr(layout_ptr as *const u8) {
181            return None;
182        }
183        let elem_ptr = slot.cached_element.get();
184        if elem_ptr.is_null() || !arena.contains_temp_ptr(elem_ptr as *const u8) {
185            return None;
186        }
187        Some(layout_ptr)
188    }
189
190    #[inline]
191    pub(crate) fn mark_subview_subtree_clean(&self, id: PodId) {
192        if let Some(slot) = self.slots.get(id.0 as usize) {
193            slot.layout_flags.set(
194                (slot.layout_flags.get() | LAYOUT_FLAG_SUBTREE_CLEAN)
195                    & !LAYOUT_FLAG_DIRTY_DESCENDANT,
196            );
197        }
198    }
199
200    #[inline]
201    pub(crate) fn subview_parent_non_auto_w(&self, id: PodId) -> bool {
202        self.slots
203            .get(id.0 as usize)
204            .map(|s| (s.layout_flags.get() & LAYOUT_FLAG_PARENT_NON_AUTO_W) != 0)
205            .unwrap_or(false)
206    }
207
208    #[inline]
209    pub(crate) fn subview_parent_non_auto_h(&self, id: PodId) -> bool {
210        self.slots
211            .get(id.0 as usize)
212            .map(|s| (s.layout_flags.get() & LAYOUT_FLAG_PARENT_NON_AUTO_H) != 0)
213            .unwrap_or(false)
214    }
215
216    /// 调用指定 `PodId` 的 `View::render` 生成瞬态 `Element<'a>` 树(自动递归展开所有嵌套 `SubView(PodId)`),并返回根引用与 `ScratchArena`。
217    ///
218    /// 注意:接收 `&self` 而非 `&mut self`,配合 `UnsafeCell` 与 `Cell<bool>` 借用锁,确保渲染期间 `frame.pool_ptr` 与方法调用严格满足 Stacked Borrows 共享只读起源规则。
219    pub fn render_pod_in_arena<'a>(
220        &self,
221        id: PodId,
222        frame: &'a mut FrameScope,
223    ) -> Option<(&'a Element<'a>, &'a ScratchArena)> {
224        frame.pool_ptr = self as *const PodPool;
225        let frame_ptr = frame as *mut FrameScope;
226        let root_opt = unsafe { self.render_single_pod_raw(id, None, frame_ptr) };
227        frame.pool_ptr = core::ptr::null();
228        let root_static = root_opt?;
229        let arena = frame.arena();
230        let root_ref: &'a Element<'a> =
231            unsafe { &*(root_static as *const Element<'static> as *const Element<'a>) };
232        Some((root_ref, arena))
233    }
234
235    unsafe fn render_single_pod_raw(
236        &self,
237        id: PodId,
238        expected_gen: Option<u16>,
239        frame_ptr: *mut FrameScope,
240    ) -> Option<&'static Element<'static>> {
241        let slot = self.slots.get(id.0 as usize)?;
242        if slot.is_borrowed() || slot.is_expanding() || slot.active_readers.get() > 0 {
243            return None;
244        }
245        if let Some(g) = expected_gen {
246            if slot.generation != g {
247                return None;
248            }
249        }
250        let vt = slot.vtable?;
251
252        // Retained SubView 快径:若当前视图未脏且其缓存的 Element 仍驻留在当前 ScratchArena 的有效临时区内,
253        // 则直接跳过 View::render() 调用;若该视图不包含嵌套 SubView,则连同子树遍历一并跳过。
254        if !slot.dirty {
255            let cached_ptr = slot.cached_element.get();
256            if !cached_ptr.is_null() {
257                let valid_in_arena = unsafe {
258                    (*frame_ptr)
259                        .arena()
260                        .contains_temp_ptr(cached_ptr as *const u8)
261                };
262                if valid_in_arena {
263                    self.skipped_renders
264                        .set(self.skipped_renders.get().wrapping_add(1));
265                    let alloc_ref: &'static Element<'static> = unsafe { &*cached_ptr };
266                    let flags = slot.layout_flags.get();
267                    if (flags & LAYOUT_FLAG_HAS_SUBVIEWS) == 0 {
268                        slot.layout_flags.set(
269                            (flags | LAYOUT_FLAG_SUBTREE_CLEAN) & !LAYOUT_FLAG_DIRTY_DESCENDANT,
270                        );
271                        return Some(alloc_ref);
272                    }
273                    slot.set_borrowed(true);
274                    slot.set_expanding(true);
275                    let (_has_sub, any_desc_dirty) =
276                        unsafe { self.expand_subviews_ref(alloc_ref, frame_ptr) };
277                    slot.set_expanding(false);
278                    slot.set_borrowed(false);
279                    let mut new_flags = slot.layout_flags.get();
280                    if any_desc_dirty {
281                        new_flags =
282                            (new_flags | LAYOUT_FLAG_DIRTY_DESCENDANT) & !LAYOUT_FLAG_SUBTREE_CLEAN;
283                    } else {
284                        new_flags =
285                            (new_flags | LAYOUT_FLAG_SUBTREE_CLEAN) & !LAYOUT_FLAG_DIRTY_DESCENDANT;
286                    }
287                    slot.layout_flags.set(new_flags);
288                    return Some(alloc_ref);
289                }
290            }
291        }
292
293        let mask_bits = (size_of::<ReadersMask>() * 8) as u16;
294        if id.0 < mask_bits {
295            let bit_mask: ReadersMask = !(1 << id.0);
296            for s in self.slots.iter() {
297                s.readers_mask.set(s.readers_mask.get() & bit_mask);
298            }
299        }
300
301        slot.set_borrowed(true);
302        slot.set_expanding(true);
303        unsafe {
304            let prev_pod = (*frame_ptr).current_pod;
305            let prev_pod_gen = (*frame_ptr).current_pod_gen;
306            (*frame_ptr).current_pod = id;
307            (*frame_ptr).current_pod_gen = Some(slot.generation);
308            let prev_frame_req = (*frame_ptr).frame_requested.replace(false);
309            let prev_tracking = crate::signal::begin_pod_tracking(self.ensure_pool_id(), id);
310            let storage_ptr = self.slot_storage_ptr(slot);
311            let el_static = (vt.render_fn)(storage_ptr, frame_ptr);
312            crate::signal::end_pod_tracking(prev_tracking);
313            let this_frame_req = (*frame_ptr).frame_requested.get();
314            (*frame_ptr)
315                .frame_requested
316                .set(prev_frame_req || this_frame_req);
317            slot.set_needs_next_frame(this_frame_req);
318            slot.render_count
319                .set(slot.render_count.get().wrapping_add(1));
320            slot.set_borrowed(false);
321            let alloc_ref: &'static Element<'static> =
322                &*(*frame_ptr).arena().alloc_temp(el_static);
323            slot.cached_element
324                .set(alloc_ref as *const Element<'static>);
325            let (has_sub, any_desc_dirty) = self.expand_subviews_ref(alloc_ref, frame_ptr);
326            let mut new_flags = slot.layout_flags.get()
327                & !(LAYOUT_FLAG_SUBTREE_CLEAN
328                    | LAYOUT_FLAG_HAS_SUBVIEWS
329                    | LAYOUT_FLAG_DIRTY_DESCENDANT);
330            if has_sub {
331                new_flags |= LAYOUT_FLAG_HAS_SUBVIEWS;
332            }
333            if any_desc_dirty {
334                new_flags |= LAYOUT_FLAG_DIRTY_DESCENDANT;
335            }
336            slot.layout_flags.set(new_flags);
337            slot.set_expanding(false);
338            (*frame_ptr).current_pod = prev_pod;
339            (*frame_ptr).current_pod_gen = prev_pod_gen;
340            Some(alloc_ref)
341        }
342    }
343
344    unsafe fn expand_subviews_ref(
345        &self,
346        elem: &'static Element<'static>,
347        frame_ptr: *mut FrameScope,
348    ) -> (bool, bool) {
349        match elem {
350            Element::Div(div) => {
351                let mut has_sub = false;
352                let mut any_dirty = false;
353                let mut cur = div.first_child;
354                while let Some(node) = cur {
355                    let (child_sub, child_dirty) =
356                        unsafe { self.expand_subviews_ref(&node.element, frame_ptr) };
357                    has_sub |= child_sub;
358                    any_dirty |= child_dirty;
359                    cur = node.next_sibling.get();
360                }
361                (has_sub, any_dirty)
362            }
363            Element::SubView {
364                id,
365                generation,
366                resolved,
367            } => {
368                let sub_id = *id;
369                let sub_gen = *generation;
370                let sub_was_dirty = self
371                    .slots
372                    .get(sub_id.0 as usize)
373                    .map(|s| s.dirty)
374                    .unwrap_or(true);
375                let sub_ref =
376                    unsafe { self.render_single_pod_raw(sub_id, Some(sub_gen), frame_ptr) };
377                resolved.set(sub_ref);
378                let sub_desc_dirty = self
379                    .slots
380                    .get(sub_id.0 as usize)
381                    .map(|s| (s.layout_flags.get() & LAYOUT_FLAG_DIRTY_DESCENDANT) != 0)
382                    .unwrap_or(true);
383                (true, sub_was_dirty || sub_desc_dirty || sub_ref.is_none())
384            }
385            _ => (false, false),
386        }
387    }
388}
389