Skip to main content

mgui_core/element/
mod.rs

1//! 简化版 Element 树 — 阶段 3
2//!
3//! 设计文档 § 3.3 扩展(阶段 3-A):
4//! - 同 type 同 key 的 Element 节点**原地复用**,只更新 widget 引用 + 重建 RO
5//! - 不同 type 或不同 key 的 Element **替换**(旧 element 暂存到 Inactive 池,新挂载)
6//! - `subscriber_id` 跨 update 保留,Signal 订阅关系自然延续
7//! - children 列表按 index 对齐(3-C 引入 ListView 后支持 key 配对)
8//!
9//! 设计文档 § 3.3 扩展(阶段 3-B):
10//! - `Inactive 池`:卸载的 Element 按 `(type_id, key)` 暂存,后续 mount 优先复用
11//!
12//! 阶段 3 重构:State 上提到 Element 层
13//! - Element 持有 `Option<Box<dyn State>>` 字段
14//! - StatefulWidget mount 时,Element 调 `widget.create_state()` + `set_widget` + `init_state`
15//! - 同 type widget 复用时,Element 调 `set_widget(new)` + `did_update_widget`
16//! - Element 卸载时调 `dispose()`
17//! - 渲染、子节点、事件都优先走 state,fallback 到 widget
18
19use std::any::{Any, TypeId};
20use std::cell::RefCell;
21use std::collections::{HashMap, HashSet};
22
23use crate::arena::Arena;
24use crate::id::{ElementId, LayerId};
25use crate::paint::{LayerEffect, PaintList};
26use crate::reactive::SubscriberId;
27pub use crate::render_object::{make_ro_shared, SharedRO};
28use crate::render_object::{BoxConstraints, LayoutContext, RRectRenderObject, RenderObject};
29use crate::widget::{State, Widget, WidgetNode};
30use crate::{Color, GestureState, KeyCode, Point, Rect, Size, WidgetEvent};
31
32/// Element — 树上的一个节点
33///
34/// 字段仅在 crate 内可写;外部通过只读 accessor([`Element::id`] /
35/// [`Element::children`] / [`Element::render_object`] 等)查询,避免绕过
36/// Element/RO 双树不变量直接改树。
37pub struct Element {
38    pub(crate) id: ElementId,
39    pub(crate) parent: Option<ElementId>,
40    pub(crate) children: Vec<ElementId>,
41    /// 当前关联的 widget
42    pub(crate) widget: WidgetNode,
43    /// 缓存的 RO(由 widget 或 state.create_render_object() 生成)
44    ///
45    /// 根治 clone_box 分叉问题:用 SharedRO(`Rc<RefCell<Box<dyn RO>>>`) 持有,
46    /// 与 RO 树 ChildSlot 里的 RO 共享同一实例。
47    /// 之前每次 collect_stateful_ros → clone_box() → RO 树分叉,layout 本体
48    /// 不影响副本,现在同一份 RO,layout/refresh 天然同步。
49    pub(crate) render_object: SharedRO,
50    /// 响应式订阅者 id
51    pub(crate) subscriber_id: SubscriberId,
52    /// 是否需要重建
53    pub(crate) dirty: bool,
54    /// state 是否可能已变化、需要在下一次 refresh 时重建 RO。
55    /// 与 `dirty` 分离:update/mount 直接创建了 fresh RO 的元素不必再重建;
56    /// 事件/Signal/tick 改变的 state 才置位,`refresh_layer_subtree` 只处理这些元素。
57    pub(crate) needs_ro_sync: bool,
58    /// 本子树(含自身)是否存在待同步的 state。用于 refresh 剪枝:
59    /// 干净分支直接跳过,不再逐节点遍历整个 dirty layer。
60    pub(crate) subtree_ro_dirty: bool,
61    /// `reuse_element` 是否刚把本元素的 RO 换成了新的 Rc。
62    /// refresh 必须返回 changed 让父层重新注入 child slot——否则父 RO 仍指向
63    /// 旧实例,后续 state 更新写在新实例上而无法显示。
64    pub(crate) ro_replaced: bool,
65    /// 是否在树中(active=false 表示已卸载,暂存于 Inactive 池)
66    pub(crate) active: bool,
67    /// 状态(仅 StatefulWidget 才有)— 阶段 3 重构
68    pub(crate) state: Option<Box<dyn State>>,
69    /// 所属 layer(阶段 4:RepaintBoundary 引入的合成单元)
70    /// None = 处于 root layer(默认整个屏幕)
71    pub(crate) layer: Option<LayerId>,
72    /// 阶段 4-D:此 element 在所属 layer 内的 logical offset
73    /// (从 layer.offset 累计到自己的位置)。
74    /// 用于:
75    /// - hit_test 时计算 element 的实际 rect(避免跨层坐标错误)
76    /// - 调试/未来 layout 重构时的位置信息
77    pub(crate) layout_offset: Point,
78    /// 父容器 `visible_children()` 对本节点的可见性判定。
79    /// mount/update 更新 children 时同步刷新;layer/焦点/语义遍历直接读缓存,
80    /// 避免每个 layer 都线性扫描父 children(O(L²))。
81    pub(crate) visible_in_parent: bool,
82    /// 阶段 4-A:本 element 被哪些子 element `depend_on` 引用。
83    /// 当本 element 的 InheritedWidget 数据变化时,遍历此集合标 dirty + rebuild。
84    dependents: HashSet<ElementId>,
85    /// 阶段 4-A:本 element 是 InheritedElement(其 widget 实现了 InheritedWidget)时为 true。
86    /// **不存 `Box<dyn InheritedWidget>`**:借用 widget 字段即可,widget 跟 element 共生命周期。
87    pub(crate) is_inherited: bool,
88}
89
90impl Element {
91    /// Element 在树中的稳定 id。
92    pub fn id(&self) -> ElementId {
93        self.id
94    }
95
96    /// 父 element(root 为 None)。
97    pub fn parent(&self) -> Option<ElementId> {
98        self.parent
99    }
100
101    /// 直接子 element id 列表(顺序 = widget children 顺序)。
102    pub fn children(&self) -> &[ElementId] {
103        &self.children
104    }
105
106    /// 当前关联的 widget 配置。
107    pub fn widget(&self) -> &WidgetNode {
108        &self.widget
109    }
110
111    /// Element 持有的共享 RenderObject。
112    pub fn render_object(&self) -> &SharedRO {
113        &self.render_object
114    }
115
116    /// 是否在活动树中(false = 已停放到 Inactive 池)。
117    pub fn is_active(&self) -> bool {
118        self.active
119    }
120
121    /// 是否被标记为需要重画。
122    pub fn is_dirty(&self) -> bool {
123        self.dirty
124    }
125
126    /// State(仅 StatefulWidget 才有)。
127    pub fn state(&self) -> Option<&dyn State> {
128        self.state.as_deref()
129    }
130
131    /// 可变 State(仅供 devtools / 测试模拟状态变更;框架内部走 State 生命周期)。
132    pub fn state_mut(&mut self) -> Option<&mut dyn State> {
133        self.state.as_deref_mut()
134    }
135
136    /// 可变 State Box(兼容测试直接 downcast_mut 的用法)。
137    pub fn state_box_mut(&mut self) -> Option<&mut Box<dyn State>> {
138        self.state.as_mut()
139    }
140
141    /// 所属 layer(None = root layer)。
142    pub fn layer(&self) -> Option<LayerId> {
143        self.layer
144    }
145
146    /// 本 element 在所属 layer 内的布局偏移。
147    pub fn layout_offset(&self) -> Point {
148        self.layout_offset
149    }
150
151    /// 是否是 InheritedWidget 节点。
152    pub fn is_inherited(&self) -> bool {
153        self.is_inherited
154    }
155
156    /// 响应式订阅者 id。
157    pub fn subscriber_id(&self) -> SubscriberId {
158        self.subscriber_id
159    }
160}
161
162/// 阶段 2-E:在 RO 树里 DFS 找到持有 `id` 的 RO,
163/// 返回 (累计全局原点, 该 RO 的 content_size) —— 二者取自同一个克隆 RO,
164/// 避免"本体未被 layout 导致 content_size=ZERO"的问题。
165pub fn locate_element_in_ro_tree(ro: &dyn RenderObject, id: ElementId, origin: Point) -> Option<(Point, Size)> {
166    if ro.element_id() == Some(id) {
167        return Some((origin, ro.content_size()));
168    }
169    let mut found = None;
170    ro.for_each_child(&mut |off, child| {
171        if found.is_some() {
172            return;
173        }
174        let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
175        if let Some(pair) = locate_element_in_ro_tree(child.borrow().as_ref(), id, child_origin) {
176            found = Some(pair);
177        }
178    });
179    found
180}
181
182/// bugfix(layer offset 同步):**element 树与 RO 树平行下降**定位 element 的布局位置。
183///
184/// 与 `locate_element_in_ro_tree` 的区别:后者按 `ro.element_id()` 匹配,但容器 RO 的
185/// `propagate_element_ids` 只设置**直接 child** 的 id,深层 RO 的 id 缺失(locate 返回
186/// None)。这里按 element 树的 children 顺序与 RO 的 child_slots 顺序配对下降
187/// (mount/update 时两者同构,均按 widget children 顺序构建),不依赖深层 id。
188pub fn locate_element_via_tree_pair(
189    tree: &ElementTree,
190    ro: &dyn RenderObject,
191    target: ElementId,
192    cur_el: ElementId,
193    origin: Point,
194) -> Option<Point> {
195    if cur_el == target {
196        return Some(origin);
197    }
198    let child_ids: Vec<ElementId> = tree.elements.get(cur_el).map(|el| el.children.clone()).unwrap_or_default();
199    let mut index = 0usize;
200    let mut found = None;
201    ro.for_each_child(&mut |off, child_ro| {
202        if found.is_some() {
203            return;
204        }
205        if let Some(&cid) = child_ids.get(index) {
206            let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
207            if let Some(p) = locate_element_via_tree_pair(tree, child_ro.borrow().as_ref(), target, cid, child_origin) {
208                found = Some(p);
209            }
210        }
211        index += 1;
212    });
213    found
214}
215
216/// 文字测量回调:(文本, 字号, 最大宽度) → (宽度, 高度)
217pub type TextMeasurer = fn(&str, f32, Option<f32>) -> (f32, f32);
218
219/// Element 树
220///
221/// 外部只读查询走 accessor([`ElementTree::element`] / [`ElementTree::root_id`] /
222/// [`ElementTree::elements`] / [`ElementTree::layer_tree`]);字段在 crate 内可写,
223/// 防止宿主/devtools 绕过树不变量直接改树。
224pub struct ElementTree {
225    pub(crate) elements: Arena<ElementId, Element>,
226    pub(crate) root: Option<ElementId>,
227    /// Inactive 池:按 `(type_id, key)` 暂存已卸载的 Element,后续 mount 优先复用。
228    /// 每个 key 允许多个元素(同类型无 key 兄弟会落到同一个 key);
229    /// 总量走 `inactive_total` 上限,超限的元素直接从 Arena 释放。
230    inactive: HashMap<InactiveKey, Vec<ElementId>>,
231    /// 池内元素总数(与 vec 总和同步,避免每次统计 O(keys))
232    inactive_total: usize,
233    /// 阶段 2:当前持有键盘焦点的 element(None = 无焦点)
234    focused: Option<ElementId>,
235    /// 已收到 FocusWithin(true) 的祖先集合(用于结构变化时增量重算)
236    focus_within_ancestors: Vec<ElementId>,
237    /// 阶段 2 手势:指针捕获目标(PointerDown 命中者,Move/Up 独占,Up 释放)
238    pointer_capture: Option<ElementId>,
239    /// 阶段 2 手势:竞技场胜出 element(持续型手势独占指针,Up 释放)
240    gesture_winner: Option<ElementId>,
241    /// 本次 PointerDown 实际投递过的链(命中者 + 有 state 的祖先),
242    /// 用于竞技场胜出/捕获失效时给其余控件发 PointerCancel。
243    pointer_down_chain: Vec<ElementId>,
244    /// 阶段 3-13:Overlay 层(后入=上层,自顶向下 hit/事件)
245    ///
246    /// 每个 overlay 是一条独立 element 子树 + 自己的 layer(z_order 高于主树);
247    /// 用途:菜单、对话框、tooltip — 不参与主树布局但显示在主树之上。
248    /// 焦点:显示时转移到 overlay 内首个 focusable;关闭时恢复 `focused_before`。
249    overlays: Vec<OverlayEntry>,
250    /// 下一个 overlay handle id
251    next_overlay_handle: u32,
252    /// 阶段 5-G:subscriber_id → element_id 反查表(让 Signal::set 标 element dirty)
253    subscriber_to_element: HashMap<crate::reactive::SubscriberId, ElementId>,
254    /// 阶段 4:Layer 树(与 element 树平行,RepaintBoundary 处建立分支)
255    pub(crate) layer_tree: LayerTree,
256    /// 分配时给 layer 一个临时递增序;paint_frame 每帧会按 element 树
257    /// 重算 `Layer.z_order`(分配时序不能代表 keyed 重排/overlay 置顶)。
258    z_order_counter: u32,
259    /// P0 补全:上一次 PointerMove 命中的 element — 用于自动派发 PointerLeave
260    last_hit_target: Option<ElementId>,
261    /// State 请求重建 children 的队列(handle_event 里 take_needs_build()=true 时入队,
262    /// 下一帧 paint_frame 开头由 process_build_requests 统一处理)
263    build_requests: Vec<ElementId>,
264    /// 事件冒泡/手势仲裁链的复用缓冲(避免每次 PointerMove 分配 Vec)。
265    event_chain: Vec<ElementId>,
266    /// 按 z_order 槽位收集 LayerPaint 的复用缓冲;paint_frame 每帧 clear 后
267    /// 按 rank 写入,最后压缩输出,避免每帧对全部 layer 排序。
268    paint_slots: Vec<Option<LayerPaint>>,
269    /// 顶层 layer id 的复用缓冲(避免每帧 clone root.children)。
270    top_layers_scratch: Vec<LayerId>,
271    /// 最近一帧 paint_frame 的 layout/paint 分段时间(纳秒,Inspector/stress 用)。
272    last_layout_ns: u64,
273    last_paint_ns: u64,
274    /// 可选的文字测量函数 —— runtime 层注入,core 层 tooltip 用它算真实文字尺寸
275    /// 签名:`fn(text: &str, font_size: f32, max_width: Option<f32>) -> (f32, f32)`
276    pub(crate) text_measurer: Option<TextMeasurer>,
277    /// 有状态元素注册表(create_state_for 挂载时登记,tick_all_states 只遍历此表,
278    /// 复杂度从 O(全树) 降到 O(有状态数)。过期项在 tick 前惰性压缩剔除。
279    stateful_registry: Vec<ElementId>,
280    /// 与 registry 同步的集合,挂载去重 O(1)。
281    stateful_set: HashSet<ElementId>,
282    /// 具备 OverlayAware 能力的 state 注册表(挂载时探测一次)。
283    /// process_overlay_intents 只遍历此表,避免每帧扫描全树 + 对所有 state 做
284    /// `as_overlay_aware()` 动态探测。过期项在消费前惰性剔除。
285    overlay_aware_registry: Vec<ElementId>,
286    /// 上次消费的资源重绘 generation(字形 atlas 扩容/清空等)
287    repaint_generation: u64,
288    /// 当前 surface 逻辑尺寸(overlay 边界 clamp / 自动翻转用;None = 未知)
289    viewport_size: Option<Size>,
290    /// 语义树版本:mount/update/dirty/overlay/focus 变化时自增。
291    /// Host 据此跳过无变化帧的 a11y 快照构建与推送。
292    semantics_revision: u64,
293    /// 本树的 reactive scope(多窗口 dirty 隔离)。
294    reactive_scope: u64,
295    /// layer 合成顺序是否需要重算(结构变化时置位;paint_frame 只在置位时 DFS)。
296    layer_order_dirty: bool,
297    /// 下一次 paint 前是否需要整棵 RO 树重新 layout(update/mount/resize)。
298    /// 事件帧仍走 per-layer layout,避免 hover 全树重排。
299    full_layout_needed: bool,
300    /// 本轮 Signal dirty 命中的 element,供 `rebuild_signal_dirty` 选择性重建。
301    signal_dirty_elements: Vec<ElementId>,
302    /// 已消费的 peek 信号全局 epoch(多窗口各自消费,不漏全树 rebuild)。
303    last_any_signal_epoch: u64,
304    /// 最近一次布局后的 element 绝对 origin(相对 root layer)+ 深度。
305    /// None = 缓存失效;首次查询 O(N),同一帧后续查询 O(1)。
306    /// 结构变化/布局/overlay 移动时失效,由 `element_origin` 惰性重建。
307    origin_cache: RefCell<Option<HashMap<ElementId, (Point, usize)>>>,
308    /// P2:focus 链缓存 `(semantics_revision, chain)`;Tab 连续遍历不重复 DFS。
309    focus_chain_cache: RefCell<Option<(u64, Vec<ElementId>)>>,
310}
311
312/// 资源 epoch:运行时在「已缓存的 PaintList 全部失效」时递增,例如
313/// glyph atlas 扩容后所有旧 UV 都指向错误位置。下一帧 paint_frame 会
314/// 把所有 layer 标脏强制重画。
315static RESOURCE_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
316
317/// 每棵 ElementTree 独占的 reactive scope(0 保留给 Memo/Effect 等全局订阅者)。
318static NEXT_REACTIVE_SCOPE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
319
320fn next_reactive_scope() -> u64 {
321    NEXT_REACTIVE_SCOPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
322}
323
324/// 请求下一帧全量重绘(运行时资源不连续变化时调用)
325pub fn request_full_repaint() {
326    RESOURCE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
327}
328
329pub(crate) fn resource_epoch() -> u64 {
330    RESOURCE_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
331}
332
333// =================================================================
334// 阶段 4:Layer 树(图层与合成)
335
336// 阶段 B5(roadmap 4-I):element.rs 拆分为子模块 — 原单文件按职责拆 4 块,
337// API 路径完全不变: crate::element::{Element, ElementTree, Layer, LayerTree, ...}。
338mod dirty;
339mod event;
340mod layer;
341mod overlay;
342mod overlay_host;
343
344pub use layer::{paint_frame, FramePaint, Layer, LayerPaint, LayerTree};
345use overlay::OverlayEntry;
346pub use overlay::OverlayHandle;
347
348/// Inactive 池的 key
349#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
350struct InactiveKey {
351    type_id: TypeId,
352    key: Option<u64>, // 用 &str 哈希后的 u64,避免借用问题
353}
354
355/// 计算 inactive 池的 key
356///
357/// `key` 字段用 `&str` 的指针地址作为 u64(避免借用问题)。
358/// 这是一种简化:同一个 widget key 字符串常量会得到相同的 u64(因为字符串常量 intern),
359/// 但运行时构造的 String 即使内容相同也会得到不同 hash—这对阶段 3-B 是足够的。
360fn inactive_key(widget: &WidgetNode) -> InactiveKey {
361    // 取内层 widget 的 TypeId(WidgetNode 自身的 Any::type_id 永远是 WidgetNode)
362    let type_id = widget.type_id();
363    // 阶段 3-C:用 element_key(u64)作为 Inactive 池的 secondary key
364    let key_hash = widget.0.key();
365    InactiveKey { type_id, key: key_hash }
366}
367
368impl Default for ElementTree {
369    fn default() -> Self {
370        Self::new()
371    }
372}
373
374// 阶段 B5(roadmap 4-II):进一步拆分 element.rs 的 impl block 为子模块
375pub mod inherited_methods;
376pub mod mount;
377pub mod state;
378
379impl ElementTree {
380    /// 当前 root element id(空树为 None)。
381    pub fn root_id(&self) -> Option<ElementId> {
382        self.root
383    }
384
385    /// 按 id 查询活动/池中的 element(只读)。
386    pub fn element(&self, id: ElementId) -> Option<&Element> {
387        self.elements.get(id)
388    }
389
390    /// 遍历所有 element(含 Inactive 池;用 [`Element::is_active`] 过滤)。
391    pub fn elements(&self) -> impl Iterator<Item = (ElementId, &Element)> + '_ {
392        self.elements.iter()
393    }
394
395    /// element 总数(含 Inactive 池)。
396    pub fn element_count(&self) -> usize {
397        self.elements.len()
398    }
399
400    /// Layer 树(只读)。
401    pub fn layer_tree(&self) -> &LayerTree {
402        &self.layer_tree
403    }
404
405    /// 当前注入的文字测量回调。
406    pub fn text_measurer(&self) -> Option<TextMeasurer> {
407        self.text_measurer
408    }
409
410    /// 注入文字测量回调(core 不依赖字体实现)。
411    pub fn set_text_measurer(&mut self, measurer: Option<TextMeasurer>) {
412        self.text_measurer = measurer;
413    }
414
415    /// P1-7 诊断:检查 element 树与 RO 树的直接 child 对应关系。
416    ///
417    /// 对每个 active element 检查其直接 child 的 `SharedRO` 是否在自身 RO 子树中
418    /// **恰好出现一次**。返回问题列表(空 = 一致);复杂度 O(元素数 × RO 子树),
419    /// 只应在 debug / 测试 / Inspector 中调用。
420    pub fn audit_render_protocol(&self) -> Vec<String> {
421        fn collect(ro: &dyn RenderObject, out: &mut Vec<*const ()>) {
422            out.push(ro as *const dyn RenderObject as *const ());
423            ro.for_each_child(&mut |_, child| {
424                collect(child.borrow().as_ref(), out);
425            });
426        }
427
428        let mut problems = Vec::new();
429        for (id, el) in self.elements.iter() {
430            if !el.active || el.children.is_empty() {
431                continue;
432            }
433            let mut ptrs = Vec::new();
434            collect(el.render_object.borrow().as_ref(), &mut ptrs);
435            for &cid in &el.children {
436                let Some(child) = self.elements.get(cid) else { continue };
437                let ptr = child.render_object.borrow().as_ref() as *const dyn RenderObject as *const ();
438                let count = ptrs.iter().filter(|&&p| p == ptr).count();
439                if count != 1 {
440                    problems.push(format!(
441                        "element {id:?} ({}) 的 child {cid:?} ({}) 在其 RO 子树出现 {count} 次(期望 1)",
442                        el.widget.0.type_name(),
443                        child.widget.0.type_name()
444                    ));
445                }
446            }
447        }
448        problems
449    }
450
451    /// 可见性判定:沿 element 祖先链上溯,若某个祖先通过 `visible_children()`
452    /// 把「当前分支」列为不可见,则整棵子树(含其内部 RepaintBoundary layer)不可见。
453    ///
454    /// 默认所有组件 `visible_children()` 返回 `None`(全部可见),故此函数对
455    /// 既有组件恒返回 `true` —— 零行为变化。`IndexedStack`/`Offstage` 等按需 override。
456    pub(crate) fn element_subtree_visible(&self, eid: ElementId) -> bool {
457        let Some(start) = self.elements.get(eid) else { return true };
458        if !start.visible_in_parent {
459            return false;
460        }
461        let mut cursor = start.parent;
462        while let Some(pid) = cursor {
463            let Some(pel) = self.elements.get(pid) else { break };
464            if !pel.visible_in_parent {
465                return false;
466            }
467            cursor = pel.parent;
468        }
469        true
470    }
471
472    /// 语义树版本(mount/update/dirty/overlay/focus 变化时自增)。
473    ///
474    /// Host 仅在版本变化时重建 a11y 快照,避免动画/角标帧每帧全量遍历。
475    pub fn semantics_revision(&self) -> u64 {
476        self.semantics_revision
477    }
478
479    /// 最近一帧 `paint_frame` 的布局耗时(纳秒,供 profile/Inspector)。
480    pub fn last_layout_ns(&self) -> u64 {
481        self.last_layout_ns
482    }
483
484    /// 最近一帧 `paint_frame` 的绘制收集/合批耗时(纳秒)。
485    pub fn last_paint_ns(&self) -> u64 {
486        self.last_paint_ns
487    }
488
489    pub(crate) fn bump_semantics_revision(&mut self) {
490        self.semantics_revision = self.semantics_revision.wrapping_add(1);
491    }
492
493    /// 一次性收集所有 active element 的 root-layer 原点与深度。
494    ///
495    /// 滚轮目标搜索等“按位置找某个 element”的路径以前对每个候选调用
496    /// `element_origin`(每次从 RO 根 DFS),整体 O(N²);这里一次 O(N) 得到
497    /// 全表。overlay 子树的根 origin = layer 偏移。
498    pub(crate) fn layout_origins(&self) -> HashMap<ElementId, (Point, usize)> {
499        let mut out = HashMap::new();
500        if let Some(root) = self.root {
501            self.collect_layout_origins(root, Point::ZERO, 0, &mut out);
502        }
503        for entry in &self.overlays {
504            let origin = entry.layer_offset(self);
505            self.collect_layout_origins(entry.root_element, origin, 0, &mut out);
506        }
507        out
508    }
509
510    /// 失效 origin 缓存(结构变化 / 布局 / layer 移动后调用)。
511    pub(crate) fn invalidate_origin_cache(&self) {
512        *self.origin_cache.borrow_mut() = None;
513    }
514
515    /// 惰性构建 origin 缓存:本帧首次查询 O(N),之后 O(1)。
516    fn origin_map(&self) -> std::cell::Ref<'_, HashMap<ElementId, (Point, usize)>> {
517        if self.origin_cache.borrow().is_none() {
518            let origins = self.layout_origins();
519            *self.origin_cache.borrow_mut() = Some(origins);
520        }
521        std::cell::Ref::map(self.origin_cache.borrow(), |cache| cache.as_ref().expect("origin cache initialised"))
522    }
523
524    fn collect_layout_origins(
525        &self,
526        id: ElementId,
527        origin: Point,
528        depth: usize,
529        out: &mut HashMap<ElementId, (Point, usize)>,
530    ) {
531        let Some(el) = self.elements.get(id) else { return };
532        if !el.active {
533            return;
534        }
535        out.insert(id, (origin, depth));
536        let offsets: Vec<Point> = {
537            let mut offsets = Vec::with_capacity(el.children.len());
538            el.render_object.borrow().for_each_child(&mut |off, _| offsets.push(off));
539            offsets
540        };
541        for (index, &child) in el.children.iter().enumerate() {
542            let off = offsets.get(index).copied().unwrap_or(Point::ZERO);
543            self.collect_layout_origins(child, Point::new(origin.x + off.x, origin.y + off.y), depth + 1, out);
544        }
545    }
546}
547// 模块内测试已迁到 crates/mgui-test/tests/
548// #[cfg(test)]
549// mod tests;