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