mgui-core 0.3.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! 简化版 Element 树 — 阶段 3
//!
//! 设计文档 § 3.3 扩展(阶段 3-A):
//! - 同 type 同 key 的 Element 节点**原地复用**,只更新 widget 引用 + 重建 RO
//! - 不同 type 或不同 key 的 Element **替换**(旧 element 暂存到 Inactive 池,新挂载)
//! - `subscriber_id` 跨 update 保留,Signal 订阅关系自然延续
//! - children 列表按 index 对齐(3-C 引入 ListView 后支持 key 配对)
//!
//! 设计文档 § 3.3 扩展(阶段 3-B):
//! - `Inactive 池`:卸载的 Element 按 `(type_id, key)` 暂存,后续 mount 优先复用
//!
//! 阶段 3 重构:State 上提到 Element 层
//! - Element 持有 `Option<Box<dyn State>>` 字段
//! - StatefulWidget mount 时,Element 调 `widget.create_state()` + `set_widget` + `init_state`
//! - 同 type widget 复用时,Element 调 `set_widget(new)` + `did_update_widget`
//! - Element 卸载时调 `dispose()`
//! - 渲染、子节点、事件都优先走 state,fallback 到 widget

use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};

use crate::arena::Arena;
use crate::id::{ElementId, LayerId};
use crate::paint::{LayerEffect, PaintList};
use crate::reactive::SubscriberId;
pub use crate::render_object::{make_ro_shared, SharedRO};
use crate::render_object::{BoxConstraints, LayoutContext, RRectRenderObject, RenderObject};
use crate::widget::{State, Widget, WidgetNode};
use crate::{Color, GestureState, KeyCode, Point, Rect, Size, WidgetEvent};

/// Element — 树上的一个节点
///
/// 字段仅在 crate 内可写;外部通过只读 accessor([`Element::id`] /
/// [`Element::children`] / [`Element::render_object`] 等)查询,避免绕过
/// Element/RO 双树不变量直接改树。
pub struct Element {
    pub(crate) id: ElementId,
    pub(crate) parent: Option<ElementId>,
    pub(crate) children: Vec<ElementId>,
    /// 当前关联的 widget
    pub(crate) widget: WidgetNode,
    /// 缓存的 RO(由 widget 或 state.create_render_object() 生成)
    ///
    /// 根治 clone_box 分叉问题:用 SharedRO(`Rc<RefCell<Box<dyn RO>>>`) 持有,
    /// 与 RO 树 ChildSlot 里的 RO 共享同一实例。
    /// 之前每次 collect_stateful_ros → clone_box() → RO 树分叉,layout 本体
    /// 不影响副本,现在同一份 RO,layout/refresh 天然同步。
    pub(crate) render_object: SharedRO,
    /// 响应式订阅者 id
    pub(crate) subscriber_id: SubscriberId,
    /// 是否需要重建
    pub(crate) dirty: bool,
    /// state 是否可能已变化、需要在下一次 refresh 时重建 RO。
    /// 与 `dirty` 分离:update/mount 直接创建了 fresh RO 的元素不必再重建;
    /// 事件/Signal/tick 改变的 state 才置位,`refresh_layer_subtree` 只处理这些元素。
    pub(crate) needs_ro_sync: bool,
    /// 本子树(含自身)是否存在待同步的 state。用于 refresh 剪枝:
    /// 干净分支直接跳过,不再逐节点遍历整个 dirty layer。
    pub(crate) subtree_ro_dirty: bool,
    /// `reuse_element` 是否刚把本元素的 RO 换成了新的 Rc。
    /// refresh 必须返回 changed 让父层重新注入 child slot——否则父 RO 仍指向
    /// 旧实例,后续 state 更新写在新实例上而无法显示。
    pub(crate) ro_replaced: bool,
    /// 是否在树中(active=false 表示已卸载,暂存于 Inactive 池)
    pub(crate) active: bool,
    /// 状态(仅 StatefulWidget 才有)— 阶段 3 重构
    pub(crate) state: Option<Box<dyn State>>,
    /// 所属 layer(阶段 4:RepaintBoundary 引入的合成单元)
    /// None = 处于 root layer(默认整个屏幕)
    pub(crate) layer: Option<LayerId>,
    /// 阶段 4-D:此 element 在所属 layer 内的 logical offset
    /// (从 layer.offset 累计到自己的位置)。
    /// 用于:
    /// - hit_test 时计算 element 的实际 rect(避免跨层坐标错误)
    /// - 调试/未来 layout 重构时的位置信息
    pub(crate) layout_offset: Point,
    /// 父容器 `visible_children()` 对本节点的可见性判定。
    /// mount/update 更新 children 时同步刷新;layer/焦点/语义遍历直接读缓存,
    /// 避免每个 layer 都线性扫描父 children(O(L²))。
    pub(crate) visible_in_parent: bool,
    /// 阶段 4-A:本 element 被哪些子 element `depend_on` 引用。
    /// 当本 element 的 InheritedWidget 数据变化时,遍历此集合标 dirty + rebuild。
    dependents: HashSet<ElementId>,
    /// 阶段 4-A:本 element 是 InheritedElement(其 widget 实现了 InheritedWidget)时为 true。
    /// **不存 `Box<dyn InheritedWidget>`**:借用 widget 字段即可,widget 跟 element 共生命周期。
    pub(crate) is_inherited: bool,
    /// 阶段 4-A:祖先 InheritedWidget(主题/方向/Locale)的数据变了,但本 element 的
    /// RenderObject 还没按新数据同步过。
    ///
    /// `reuse_element` 在 RO 同步处读它:为 true 时**强制重建 RO**而不走 `apply_state`
    /// 就地写回。`apply_state` 是逐字段比较,组件漏掉某个主题派生字段就会留下旧色,
    /// 表现为「切深色/浅色后部分区域不变色,鼠标滑过才刷新」。
    pub(crate) inherited_stale: bool,
}

impl Element {
    /// Element 在树中的稳定 id。
    pub fn id(&self) -> ElementId {
        self.id
    }

    /// 父 element(root 为 None)。
    pub fn parent(&self) -> Option<ElementId> {
        self.parent
    }

    /// 直接子 element id 列表(顺序 = widget children 顺序)。
    pub fn children(&self) -> &[ElementId] {
        &self.children
    }

    /// 当前关联的 widget 配置。
    pub fn widget(&self) -> &WidgetNode {
        &self.widget
    }

    /// Element 持有的共享 RenderObject。
    pub fn render_object(&self) -> &SharedRO {
        &self.render_object
    }

    /// 是否在活动树中(false = 已停放到 Inactive 池)。
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// 是否被标记为需要重画。
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// State(仅 StatefulWidget 才有)。
    pub fn state(&self) -> Option<&dyn State> {
        self.state.as_deref()
    }

    /// 可变 State(仅供 devtools / 测试模拟状态变更;框架内部走 State 生命周期)。
    pub fn state_mut(&mut self) -> Option<&mut dyn State> {
        self.state.as_deref_mut()
    }

    /// 可变 State Box(兼容测试直接 downcast_mut 的用法)。
    pub fn state_box_mut(&mut self) -> Option<&mut Box<dyn State>> {
        self.state.as_mut()
    }

    /// 所属 layer(None = root layer)。
    pub fn layer(&self) -> Option<LayerId> {
        self.layer
    }

    /// 本 element 在所属 layer 内的布局偏移。
    pub fn layout_offset(&self) -> Point {
        self.layout_offset
    }

    /// 是否是 InheritedWidget 节点。
    pub fn is_inherited(&self) -> bool {
        self.is_inherited
    }

    /// 响应式订阅者 id。
    pub fn subscriber_id(&self) -> SubscriberId {
        self.subscriber_id
    }
}

/// 阶段 2-E:在 RO 树里 DFS 找到持有 `id` 的 RO,
/// 返回 (累计全局原点, 该 RO 的 content_size) —— 二者取自同一个克隆 RO,
/// 避免"本体未被 layout 导致 content_size=ZERO"的问题。
pub fn locate_element_in_ro_tree(ro: &dyn RenderObject, id: ElementId, origin: Point) -> Option<(Point, Size)> {
    if ro.element_id() == Some(id) {
        return Some((origin, ro.content_size()));
    }
    let mut found = None;
    ro.for_each_child(&mut |off, child| {
        if found.is_some() {
            return;
        }
        let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
        if let Some(pair) = locate_element_in_ro_tree(child.borrow().as_ref(), id, child_origin) {
            found = Some(pair);
        }
    });
    found
}

/// bugfix(layer offset 同步):**element 树与 RO 树平行下降**定位 element 的布局位置。
///
/// 与 `locate_element_in_ro_tree` 的区别:后者按 `ro.element_id()` 匹配,但容器 RO 的
/// `propagate_element_ids` 只设置**直接 child** 的 id,深层 RO 的 id 缺失(locate 返回
/// None)。这里按 element 树的 children 顺序与 RO 的 child_slots 顺序配对下降
/// (mount/update 时两者同构,均按 widget children 顺序构建),不依赖深层 id。
pub fn locate_element_via_tree_pair(
    tree: &ElementTree,
    ro: &dyn RenderObject,
    target: ElementId,
    cur_el: ElementId,
    origin: Point,
) -> Option<Point> {
    if cur_el == target {
        return Some(origin);
    }
    let child_ids: Vec<ElementId> = tree.elements.get(cur_el).map(|el| el.children.clone()).unwrap_or_default();
    let mut index = 0usize;
    let mut found = None;
    ro.for_each_child(&mut |off, child_ro| {
        if found.is_some() {
            return;
        }
        if let Some(&cid) = child_ids.get(index) {
            let child_origin = Point::new(origin.x + off.x, origin.y + off.y);
            if let Some(p) = locate_element_via_tree_pair(tree, child_ro.borrow().as_ref(), target, cid, child_origin) {
                found = Some(p);
            }
        }
        index += 1;
    });
    found
}

/// 文字测量回调:(文本, 字号, 最大宽度) → (宽度, 高度)
pub type TextMeasurer = fn(&str, f32, Option<f32>) -> (f32, f32);

/// Element 树
///
/// 外部只读查询走 accessor([`ElementTree::element`] / [`ElementTree::root_id`] /
/// [`ElementTree::elements`] / [`ElementTree::layer_tree`]);字段在 crate 内可写,
/// 防止宿主/devtools 绕过树不变量直接改树。
pub struct ElementTree {
    pub(crate) elements: Arena<ElementId, Element>,
    pub(crate) root: Option<ElementId>,
    /// Inactive 池:按 `(type_id, key)` 暂存已卸载的 Element,后续 mount 优先复用。
    /// 每个 key 允许多个元素(同类型无 key 兄弟会落到同一个 key);
    /// 总量走 `inactive_total` 上限,超限的元素直接从 Arena 释放。
    inactive: HashMap<InactiveKey, Vec<ElementId>>,
    /// 池内元素总数(与 vec 总和同步,避免每次统计 O(keys))
    inactive_total: usize,
    /// 阶段 2:当前持有键盘焦点的 element(None = 无焦点)
    focused: Option<ElementId>,
    /// 焦点环是否该显示(等价 CSS `:focus-visible`):键盘导航 = true,鼠标点击 = false。
    /// 只对"当前焦点"有意义,控件通过 `WidgetEvent::FocusVisibleChanged` 收到变化。
    focus_visible: bool,
    /// 已收到 FocusWithin(true) 的祖先集合(用于结构变化时增量重算)
    focus_within_ancestors: Vec<ElementId>,
    /// 阶段 2 手势:指针捕获目标(PointerDown 命中者,Move/Up 独占,Up 释放)
    pointer_capture: Option<ElementId>,
    /// 阶段 2 手势:竞技场胜出 element(持续型手势独占指针,Up 释放)
    gesture_winner: Option<ElementId>,
    /// 本次 PointerDown 实际投递过的链(命中者 + 有 state 的祖先),
    /// 用于竞技场胜出/捕获失效时给其余控件发 PointerCancel。
    pointer_down_chain: Vec<ElementId>,
    /// 阶段 3-13:Overlay 层(后入=上层,自顶向下 hit/事件)
    ///
    /// 每个 overlay 是一条独立 element 子树 + 自己的 layer(z_order 高于主树);
    /// 用途:菜单、对话框、tooltip — 不参与主树布局但显示在主树之上。
    /// 焦点:显示时转移到 overlay 内首个 focusable;关闭时恢复 `focused_before`。
    overlays: Vec<OverlayEntry>,
    /// 下一个 overlay handle id
    next_overlay_handle: u32,
    /// 阶段 5-G:subscriber_id → element_id 反查表(让 Signal::set 标 element dirty)
    subscriber_to_element: HashMap<crate::reactive::SubscriberId, ElementId>,
    /// 阶段 4:Layer 树(与 element 树平行,RepaintBoundary 处建立分支)
    pub(crate) layer_tree: LayerTree,
    /// 分配时给 layer 一个临时递增序;paint_frame 每帧会按 element 树
    /// 重算 `Layer.z_order`(分配时序不能代表 keyed 重排/overlay 置顶)。
    z_order_counter: u32,
    /// P0 补全:上一次 PointerMove 命中的 element — 用于自动派发 PointerLeave
    last_hit_target: Option<ElementId>,
    /// State 请求重建 children 的队列(handle_event 里 take_needs_build()=true 时入队,
    /// 下一帧 paint_frame 开头由 process_build_requests 统一处理)
    build_requests: Vec<ElementId>,
    /// 事件冒泡/手势仲裁链的复用缓冲(避免每次 PointerMove 分配 Vec)。
    event_chain: Vec<ElementId>,
    /// 按 z_order 槽位收集 LayerPaint 的复用缓冲;paint_frame 每帧 clear 后
    /// 按 rank 写入,最后压缩输出,避免每帧对全部 layer 排序。
    paint_slots: Vec<Option<LayerPaint>>,
    /// 顶层 layer id 的复用缓冲(避免每帧 clone root.children)。
    top_layers_scratch: Vec<LayerId>,
    /// 最近一帧 paint_frame 的 layout/paint 分段时间(纳秒,Inspector/stress 用)。
    last_layout_ns: u64,
    last_paint_ns: u64,
    /// 可选的文字测量函数 —— runtime 层注入,core 层 tooltip 用它算真实文字尺寸
    /// 签名:`fn(text: &str, font_size: f32, max_width: Option<f32>) -> (f32, f32)`
    pub(crate) text_measurer: Option<TextMeasurer>,
    /// 有状态元素注册表(create_state_for 挂载时登记,tick_all_states 只遍历此表,
    /// 复杂度从 O(全树) 降到 O(有状态数)。过期项在 tick 前惰性压缩剔除。
    stateful_registry: Vec<ElementId>,
    /// 与 registry 同步的集合,挂载去重 O(1)。
    stateful_set: HashSet<ElementId>,
    /// 具备 OverlayAware 能力的 state 注册表(挂载时探测一次)。
    /// process_overlay_intents 只遍历此表,避免每帧扫描全树 + 对所有 state 做
    /// `as_overlay_aware()` 动态探测。过期项在消费前惰性剔除。
    overlay_aware_registry: Vec<ElementId>,
    /// 上次消费的资源重绘 generation(字形 atlas 扩容/清空等)
    repaint_generation: u64,
    /// 当前 surface 逻辑尺寸(overlay 边界 clamp / 自动翻转用;None = 未知)
    viewport_size: Option<Size>,
    /// 语义树版本:mount/update/dirty/overlay/focus 变化时自增。
    /// Host 据此跳过无变化帧的 a11y 快照构建与推送。
    semantics_revision: u64,
    /// 本树的 reactive scope(多窗口 dirty 隔离)。
    reactive_scope: u64,
    /// layer 合成顺序是否需要重算(结构变化时置位;paint_frame 只在置位时 DFS)。
    layer_order_dirty: bool,
    /// 下一次 paint 前是否需要整棵 RO 树重新 layout(update/mount/resize)。
    /// 事件帧仍走 per-layer layout,避免 hover 全树重排。
    full_layout_needed: bool,
    /// 本轮 Signal dirty 命中的 element,供 `rebuild_signal_dirty` 选择性重建。
    signal_dirty_elements: Vec<ElementId>,
    /// 已消费的 peek 信号全局 epoch(多窗口各自消费,不漏全树 rebuild)。
    last_any_signal_epoch: u64,
    /// 最近一次布局后的 element 绝对 origin(相对 root layer)+ 深度。
    /// None = 缓存失效;首次查询 O(N),同一帧后续查询 O(1)。
    /// 结构变化/布局/overlay 移动时失效,由 `element_origin` 惰性重建。
    origin_cache: RefCell<Option<HashMap<ElementId, (Point, usize)>>>,
    /// P2:focus 链缓存 `(semantics_revision, chain)`;Tab 连续遍历不重复 DFS。
    focus_chain_cache: RefCell<Option<(u64, Vec<ElementId>)>>,
}

/// 资源 epoch:运行时在「已缓存的 PaintList 全部失效」时递增,例如
/// glyph atlas 扩容后所有旧 UV 都指向错误位置。下一帧 paint_frame 会
/// 把所有 layer 标脏强制重画。
static RESOURCE_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// 每棵 ElementTree 独占的 reactive scope(0 保留给 Memo/Effect 等全局订阅者)。
static NEXT_REACTIVE_SCOPE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

fn next_reactive_scope() -> u64 {
    NEXT_REACTIVE_SCOPE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// 请求下一帧全量重绘(运行时资源不连续变化时调用)
pub fn request_full_repaint() {
    RESOURCE_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}

pub(crate) fn resource_epoch() -> u64 {
    RESOURCE_EPOCH.load(std::sync::atomic::Ordering::Relaxed)
}

// =================================================================
// 阶段 4:Layer 树(图层与合成)

// 阶段 B5(roadmap 4-I):element.rs 拆分为子模块 — 原单文件按职责拆 4 块,
// API 路径完全不变: crate::element::{Element, ElementTree, Layer, LayerTree, ...}。
mod dirty;
mod event;
mod layer;
mod overlay;
mod overlay_host;

pub use layer::{paint_frame, FramePaint, Layer, LayerPaint, LayerTree};
use overlay::OverlayEntry;
pub use overlay::OverlayHandle;

/// Inactive 池的 key
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct InactiveKey {
    type_id: TypeId,
    key: Option<u64>, // 用 &str 哈希后的 u64,避免借用问题
}

/// 计算 inactive 池的 key
///
/// `key` 字段用 `&str` 的指针地址作为 u64(避免借用问题)。
/// 这是一种简化:同一个 widget key 字符串常量会得到相同的 u64(因为字符串常量 intern),
/// 但运行时构造的 String 即使内容相同也会得到不同 hash—这对阶段 3-B 是足够的。
fn inactive_key(widget: &WidgetNode) -> InactiveKey {
    // 取内层 widget 的 TypeId(WidgetNode 自身的 Any::type_id 永远是 WidgetNode)
    let type_id = widget.type_id();
    // 阶段 3-C:用 element_key(u64)作为 Inactive 池的 secondary key
    let key_hash = widget.0.key();
    InactiveKey { type_id, key: key_hash }
}

impl Default for ElementTree {
    fn default() -> Self {
        Self::new()
    }
}

// 阶段 B5(roadmap 4-II):进一步拆分 element.rs 的 impl block 为子模块
pub mod inherited_methods;
pub mod mount;
pub mod state;

impl ElementTree {
    /// 当前 root element id(空树为 None)。
    pub fn root_id(&self) -> Option<ElementId> {
        self.root
    }

    /// 按 id 查询活动/池中的 element(只读)。
    pub fn element(&self, id: ElementId) -> Option<&Element> {
        self.elements.get(id)
    }

    /// 遍历所有 element(含 Inactive 池;用 [`Element::is_active`] 过滤)。
    pub fn elements(&self) -> impl Iterator<Item = (ElementId, &Element)> + '_ {
        self.elements.iter()
    }

    /// element 总数(含 Inactive 池)。
    pub fn element_count(&self) -> usize {
        self.elements.len()
    }

    /// Layer 树(只读)。
    pub fn layer_tree(&self) -> &LayerTree {
        &self.layer_tree
    }

    /// 当前注入的文字测量回调。
    pub fn text_measurer(&self) -> Option<TextMeasurer> {
        self.text_measurer
    }

    /// 注入文字测量回调(core 不依赖字体实现)。
    pub fn set_text_measurer(&mut self, measurer: Option<TextMeasurer>) {
        self.text_measurer = measurer;
    }

    /// P1-7 诊断:检查 element 树与 RO 树的直接 child 对应关系。
    ///
    /// 对每个 active element 检查两件事:
    /// 1. 其直接 child 的 `SharedRO` 是否在自身 RO 子树中**恰好出现一次**;
    /// 2. 自身 RO 的**直接子 RO 数**是否超过 element 树的直接 child 数
    ///    (多出来的就是 widget/state 在 `create_render_object` 里自造的“影子 RO”:
    ///    element 树不知道它 → 永远不 mount → 该子树不渲染、不收事件、state 失效。
    ///    `State::build()` 必须返回这些 children,让框架挂 element 后再由
    ///    `propagate_element_ids` 把 slot 换成 element 自己的 RO —— ScrollView/
    ///    SplitPane 都踩过这条)。
    ///
    /// 直接子 RO 数取 `for_each_child`(所有容器 RO 都必须实现,比 `children_count`
    /// 可靠),返回问题列表(空 = 一致);复杂度 O(元素数 × RO 子树),
    /// 只应在 debug / 测试 / Inspector 中调用。
    pub fn audit_render_protocol(&self) -> Vec<String> {
        fn collect(ro: &dyn RenderObject, out: &mut Vec<*const ()>) {
            out.push(ro as *const dyn RenderObject as *const ());
            ro.for_each_child(&mut |_, child| {
                collect(child.borrow().as_ref(), out);
            });
        }

        let mut problems = Vec::new();
        for (id, el) in self.elements.iter() {
            if !el.active {
                continue;
            }
            let mut slots = 0usize;
            el.render_object.borrow().for_each_child(&mut |_, _| slots += 1);
            if slots > el.children.len() {
                problems.push(format!(
                    "element {id:?} ({}) 的 RO 有 {slots} 个直接子 RO,element 树只挂了 {} 个子节点;多出来的是 create_render_object 自造的影子 RO(不 mount ⇒ 不渲染、不收事件),State::build() 应返回这些 children",
                    el.widget.0.type_name(),
                    el.children.len()
                ));
            }
            if el.children.is_empty() {
                continue;
            }
            let mut ptrs = Vec::new();
            collect(el.render_object.borrow().as_ref(), &mut ptrs);
            for &cid in &el.children {
                let Some(child) = self.elements.get(cid) else { continue };
                let ptr = child.render_object.borrow().as_ref() as *const dyn RenderObject as *const ();
                let count = ptrs.iter().filter(|&&p| p == ptr).count();
                if count != 1 {
                    problems.push(format!(
                        "element {id:?} ({}) 的 child {cid:?} ({}) 在其 RO 子树出现 {count} 次(期望 1)",
                        el.widget.0.type_name(),
                        child.widget.0.type_name()
                    ));
                }
            }
        }
        problems
    }

    /// 可见性判定:沿 element 祖先链上溯,若某个祖先通过 `visible_children()`
    /// 把「当前分支」列为不可见,则整棵子树(含其内部 RepaintBoundary layer)不可见。
    ///
    /// 默认所有组件 `visible_children()` 返回 `None`(全部可见),故此函数对
    /// 既有组件恒返回 `true` —— 零行为变化。`IndexedStack`/`Offstage` 等按需 override。
    pub(crate) fn element_subtree_visible(&self, eid: ElementId) -> bool {
        let Some(start) = self.elements.get(eid) else { return true };
        if !start.visible_in_parent {
            return false;
        }
        let mut cursor = start.parent;
        while let Some(pid) = cursor {
            let Some(pel) = self.elements.get(pid) else { break };
            if !pel.visible_in_parent {
                return false;
            }
            cursor = pel.parent;
        }
        true
    }

    /// 语义树版本(mount/update/dirty/overlay/focus 变化时自增)。
    ///
    /// Host 仅在版本变化时重建 a11y 快照,避免动画/角标帧每帧全量遍历。
    pub fn semantics_revision(&self) -> u64 {
        self.semantics_revision
    }

    /// 最近一帧 `paint_frame` 的布局耗时(纳秒,供 profile/Inspector)。
    pub fn last_layout_ns(&self) -> u64 {
        self.last_layout_ns
    }

    /// 最近一帧 `paint_frame` 的绘制收集/合批耗时(纳秒)。
    pub fn last_paint_ns(&self) -> u64 {
        self.last_paint_ns
    }

    pub(crate) fn bump_semantics_revision(&mut self) {
        self.semantics_revision = self.semantics_revision.wrapping_add(1);
    }

    /// 一次性收集所有 active element 的 root-layer 原点与深度。
    ///
    /// 滚轮目标搜索等“按位置找某个 element”的路径以前对每个候选调用
    /// `element_origin`(每次从 RO 根 DFS),整体 O(N²);这里一次 O(N) 得到
    /// 全表。overlay 子树的根 origin = layer 偏移。
    pub(crate) fn layout_origins(&self) -> HashMap<ElementId, (Point, usize)> {
        let mut out = HashMap::new();
        if let Some(root) = self.root {
            self.collect_layout_origins(root, Point::ZERO, 0, &mut out);
        }
        for entry in &self.overlays {
            let origin = entry.layer_offset(self);
            self.collect_layout_origins(entry.root_element, origin, 0, &mut out);
        }
        out
    }

    /// 失效 origin 缓存(结构变化 / 布局 / layer 移动后调用)。
    pub(crate) fn invalidate_origin_cache(&self) {
        *self.origin_cache.borrow_mut() = None;
    }

    /// 惰性构建 origin 缓存:本帧首次查询 O(N),之后 O(1)。
    fn origin_map(&self) -> std::cell::Ref<'_, HashMap<ElementId, (Point, usize)>> {
        if self.origin_cache.borrow().is_none() {
            let origins = self.layout_origins();
            *self.origin_cache.borrow_mut() = Some(origins);
        }
        std::cell::Ref::map(self.origin_cache.borrow(), |cache| cache.as_ref().expect("origin cache initialised"))
    }

    fn collect_layout_origins(
        &self,
        id: ElementId,
        origin: Point,
        depth: usize,
        out: &mut HashMap<ElementId, (Point, usize)>,
    ) {
        let Some(el) = self.elements.get(id) else { return };
        if !el.active {
            return;
        }
        out.insert(id, (origin, depth));
        let offsets: Vec<Point> = {
            let mut offsets = Vec::with_capacity(el.children.len());
            el.render_object.borrow().for_each_child(&mut |off, _| offsets.push(off));
            offsets
        };
        for (index, &child) in el.children.iter().enumerate() {
            let off = offsets.get(index).copied().unwrap_or(Point::ZERO);
            self.collect_layout_origins(child, Point::new(origin.x + off.x, origin.y + off.y), depth + 1, out);
        }
    }
}
// 模块内测试已迁到 crates/mgui-test/tests/
// #[cfg(test)]
// mod tests;