mgui-core 0.7.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
//! RenderObject 子系统
//!
//! RenderObject 是 GUI 框架的渲染节点,负责布局(layout)和绘制(paint)。
//! 每个 RenderObject 是一棵树上的节点,父节点向子节点传递 `BoxConstraints`,
//! 子节点返回自身 `Size`,然后父节点确定子节点位置。
//!
//! 阶段 1 提供:
//! - `RenderObject` trait
//! - 叶子: `RRectRenderObject`(圆角矩形)
//! - 容器: `ColumnRenderObject`(垂直堆叠)、`PaddingRenderObject`(四边等值内边距)
//! - 绝对定位: `PositionedRenderObject`(在父容器内按 offset 摆放)
//! - 多子叠加: `StackRenderObject`(多个子节点按各自 offset 叠加,适合 root)

use crate::id::ElementId;
use crate::paint::PaintList;
use crate::reactive::Signal;
use crate::{Color, Point, Rect, Size};
use std::any::Any;
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::rc::Rc;

/// state → RO 就地更新的结果(P0-1 API,见架构审查 §11)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StateApply {
    /// 当前 RO 不支持由 state 就地更新(默认;框架回退 create_render_object)
    Unsupported,
    /// 已读取 state,但 layout/paint 的输入没有变化(无需标脏)
    Unchanged,
    /// 已就地更新,现有 layout/paint 需要重跑
    Updated,
}

/// 共享 RO 的内部单元:RO 本体 + 跨帧布局缓存。
struct RoCell {
    ro: RefCell<Box<dyn RenderObject>>,
    /// 子树内有影响布局的变化,下一次 layout_cached 必须真正执行。
    layout_dirty: Cell<bool>,
    /// 上次 layout 的约束与结果(约束相同且 clean 时直接复用)。
    layout_cache: Cell<Option<(BoxConstraints, Size)>>,
}

/// 共享 RO —— `Rc<RoCell>`
///
/// 除 RO 本体的 `RefCell` 外,还携带布局 dirty/约束缓存,供容器在
/// `layout_cached` 中跳过 clean 子树(容器级脏子树裁剪)。
#[derive(Clone)]
pub struct SharedRO(Rc<RoCell>);

impl SharedRO {
    pub fn borrow(&self) -> Ref<'_, Box<dyn RenderObject>> {
        self.0.ro.borrow()
    }

    pub fn borrow_mut(&self) -> RefMut<'_, Box<dyn RenderObject>> {
        self.0.ro.borrow_mut()
    }

    pub fn ptr_eq(&self, other: &SharedRO) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }

    pub fn mark_layout_dirty(&self) {
        self.0.layout_dirty.set(true);
    }

    pub fn is_layout_dirty(&self) -> bool {
        self.0.layout_dirty.get()
    }

    /// 只读快照:上一次 `layout_cached` 使用的约束与返回尺寸(从未布局过时为 None)。
    ///
    /// 供 Inspector 的布局 overlay 展示「这个元素被告知可用多大」;
    /// 纯读取,不改 dirty/cache,因此不影响渲染路径。
    pub fn layout_snapshot(&self) -> Option<(BoxConstraints, Size)> {
        self.0.layout_cache.get()
    }

    /// 带缓存的 layout:clean 且约束与上次相同时直接返回上次 size。
    pub fn layout_cached(&self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        if !self.0.layout_dirty.get() {
            if let Some((cached_constraints, size)) = self.0.layout_cache.get() {
                if cached_constraints == constraints {
                    return size;
                }
            }
        }
        let size = self.0.ro.borrow_mut().layout(constraints, ctx);
        self.0.layout_dirty.set(false);
        self.0.layout_cache.set(Some((constraints, size)));
        size
    }
}

/// 便捷构造:`Box<dyn RO>` → SharedRO
/// 避免到处写 `Rc::new(RefCell::new(ro))`
pub fn make_ro_shared(ro: Box<dyn RenderObject>) -> SharedRO {
    SharedRO(Rc::new(RoCell { ro: RefCell::new(ro), layout_dirty: Cell::new(true), layout_cache: Cell::new(None) }))
}

/// 布局约束(Flutter 范式:父→子 min/max,子→父 size)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxConstraints {
    pub min_width: f32,
    pub max_width: f32,
    pub min_height: f32,
    pub max_height: f32,
}

impl BoxConstraints {
    /// 无约束(子节点可以无限大)
    pub const UNBOUNDED: Self =
        Self { min_width: 0.0, max_width: f32::INFINITY, min_height: 0.0, max_height: f32::INFINITY };

    /// 强制子节点等于给定尺寸
    pub fn tight(size: Size) -> Self {
        Self { min_width: size.width, max_width: size.width, min_height: size.height, max_height: size.height }
    }

    /// 松约束(子节点可在 0..size 内自由决定)
    pub fn loose(size: Size) -> Self {
        Self { min_width: 0.0, max_width: size.width, min_height: 0.0, max_height: size.height }
    }

    /// 把一个尺寸夹紧到约束范围内
    pub fn constrain(&self, size: Size) -> Size {
        Size::new(size.width.clamp(self.min_width, self.max_width), size.height.clamp(self.min_height, self.max_height))
    }

    /// 四边均匀内缩(用于带边框/焦点环的容器给 child 的约束)。
    /// min 归 0(child 可以任意小),max 减去两侧 inset 并 clamp ≥0
    /// (防 max < min)。∞ 减有限值仍为 ∞。
    pub fn inset_uniform(&self, inset: f32) -> Self {
        Self {
            min_width: 0.0,
            max_width: (self.max_width - inset * 2.0).max(0.0),
            min_height: 0.0,
            max_height: (self.max_height - inset * 2.0).max(0.0),
        }
    }

    /// 约束是否在每个轴上都强制为唯一值(上下界相等)
    pub fn is_tight(&self) -> bool {
        self.min_width == self.max_width && self.min_height == self.max_height
    }

    /// 宽度轴是否被限制为有限值
    pub fn is_bounded_width(&self) -> bool {
        self.max_width.is_finite()
    }

    /// 高度轴是否被限制为有限值
    pub fn is_bounded_height(&self) -> bool {
        self.max_height.is_finite()
    }

    /// 收紧约束到指定的 width/height(等价于 tight + constrain)
    pub fn tighten(&self, width: f32, height: f32) -> Self {
        let w = width.clamp(self.min_width, self.max_width);
        let h = height.clamp(self.min_height, self.max_height);
        Self::tight(Size::new(w, h))
    }

    /// 把最小尺寸放宽为 0(返回只保留上限的松约束)
    pub fn loosen(&self) -> Self {
        Self { min_width: 0.0, max_width: self.max_width, min_height: 0.0, max_height: self.max_height }
    }
}

impl Default for BoxConstraints {
    fn default() -> Self {
        Self::UNBOUNDED
    }
}

/// 布局上下文(阶段 1 留空,后续可加 baseline、文字方向等)
#[derive(Default)]
pub struct LayoutContext;

/// RenderObject 核心 trait
///
/// 负责:
/// - `layout`:在给定约束下确定自身和子节点尺寸,返回自身最终尺寸
/// - `paint`:在 `offset` 偏移处把绘制命令追加到 `PaintList`
/// - `hit_test`:在 `position` 处做命中测试,返回命中的 `ElementId`
/// - `set_element_id`:Element 树 mount 时注入自身 id,默认 noop
/// - `propagate_element_ids`:容器 RO 把子 element_id 注入到内部子 RO(默认 noop)
#[deny(missing_docs)]
pub trait RenderObject {
    /// 在给定约束下计算并缓存自身尺寸,返回最终 content size。
    ///
    /// 容器应在此递归布局子节点(优先走 `SharedRO::layout_cached`),并把
    /// 子节点相对本 RO 的偏移记录下来供 `child_slots` / `for_each_child` 使用。
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size;

    /// 把自身内容追加到 `painter`;`offset` 是本 RO 原点在目标坐标系中的位置。
    fn paint(&self, offset: Point, painter: &mut PaintList);

    /// 命中测试:`position` 为目标坐标系,`offset` 为本 RO 原点;返回命中的 element id。
    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        let _ = (position, offset);
        None
    }
    /// 本 RO 的**滚动条车道**是否覆盖这个本地坐标点(`local` = 相对本 RO 原点)。
    ///
    /// 用途:滚动条画在内容之上,命中测试又是"子树优先"(为了让嵌套容器的滚动条
    /// 不被外层抢走)。于是一颗**按下即生效**的控件(NavigationMenu / TabBar 等)
    /// 躺在滚动条下面时,抓滚动条会顺带把它点一下。派发 `PointerDown` 时框架沿命中
    /// 元素的祖先链向上问这个方法,**最近的那个声明者**接管这颗粒按下(`ElementTree`)。
    ///
    /// 只有自带滚动条的容器需要 override(ScrollView / ListView / DataGrid / TreeView);
    /// 判定范围应当与自己的 `hit_test` / 拖拽判定同源,否则"能拖但下面还是被点了"。
    /// 默认 `false`(普通控件没有车道概念)。
    fn scrollbar_lane_hit(&self, _local: Point) -> bool {
        false
    }
    /// Element 树 mount 时调用,让 RO 记录自己归属哪个 Element。
    /// 阶段 2 仅 `RRectRenderObject` 有 element_id 字段,其他 RO 默认 noop。
    fn set_element_id(&mut self, _id: ElementId) {}
    /// 把子 element_id 注入到 RO 内部的子 RO。
    ///
    /// 阶段 2 协议:父 RO 在 mount 时调用此方法,把子 Element 的 id 传给自己的子 RO。
    /// 容器 RO(Stack/Column/Positioned/Padding)override 此方法,叶子 RRect 已经有 element_id 不再需要。
    ///
    /// 阶段 3 扩展:`stateful_ros[i] = Some(ro)` 时,父 RO 把第 i 个 child slot 的 RO
    /// 替换为这个 state-driven RO(覆盖 `widget.create_render_object()` 创建的 widget-driven RO)。
    /// 这是 state 上提到 Element 层后的关键同步:state 持有 pressed/hover 等可变状态,
    /// state.create_render_object() 返回的 RO 反映当前状态;但 Element 树的 root RO
    /// 是从 `widget.create_render_object()` 递归构建的,默认是 widget-driven(不变),
    /// 所以必须显式把 stateful child slot 替换成 state-driven RO,才能让 paint 反映 state。
    fn propagate_element_ids(&mut self, _child_ids: &[ElementId], _stateful_ros: &mut [SharedRO]) {}

    /// 阶段 4-D(候选 2):返回 RO 的内容 size(已 layout 后)。
    ///
    /// 用于 paint_frame 时把 layer 自己的 size 写到 `Layer.size`,
    /// Renderer 据此创建对应大小的 GPU texture(小 layer 用小 texture,省 fillrate)。
    ///
    /// 默认 ZERO(让 Renderer fallback 全屏 texture 兼容)。叶子 RO + LayerProxy RO
    /// override 返回真实 size;容器 RO(Stack/Column/Padding)布局复杂,默认 ZERO 即可
    /// (这些一般不被包在 RepaintBoundary 里,直接走 root layer 全屏 paint)。
    fn content_size(&self) -> Size {
        Size::ZERO
    }

    /// P1-7:显式的有效内容尺寸(finite 且 > 0)。
    ///
    /// 默认由 `content_size()` 推导;容器/自定义 RO 可 override 以区分
    /// “尚未布局”与“真实 ZERO”。layer sizing 不再依赖 ZERO 哨兵。
    fn content_size_opt(&self) -> Option<Size> {
        let size = self.content_size();
        (size.width.is_finite() && size.height.is_finite() && size.width > 0.0 && size.height > 0.0).then_some(size)
    }

    /// P1-7:layer texture 的尺寸提示:优先真实内容尺寸,其次边界盒子尺寸。
    ///
    /// `content_size` 对 FittedBox/RotatedBox 是未缩放/未旋转的纹理尺寸,
    /// `layer_layout_size` 是父布局中的盒子尺寸;两者都未知时由调用方回退
    /// layout 返回值/视口,并记录日志。
    fn layer_size_hint(&self) -> Option<Size> {
        self.content_size_opt().or_else(|| {
            self.layer_layout_size()
                .filter(|s| s.width.is_finite() && s.height.is_finite() && s.width > 0.0 && s.height > 0.0)
        })
    }

    /// 边界 RO 在父布局中实际占用的尺寸(供嵌套 layer 局部重排)。
    ///
    /// 与 `content_size()` 的区别:FittedBox/RotatedBox 的 content_size 是
    /// **未缩放/未旋转的纹理尺寸**,而父布局尺寸才是子层再次 layout 时的盒子。
    /// 默认 None = 未知(调用方保持原 UNBOUNDED 行为)。
    fn layer_layout_size(&self) -> Option<Size> {
        None
    }

    /// 嵌套 layer 局部重排时对该边界根使用的约束(默认 loose:允许内容收缩)。
    ///
    /// 变换类边界(FittedBox/RotatedBox)的盒子尺寸由 `constrain(child)` 推导,
    /// 用 loose(已知盒子) 重排会把它收缩到 child 自然尺寸、把 transform 算错;
    /// 它们覆盖为 tight(已知盒子),保证重排幂等。
    fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
        BoxConstraints::loose(layout_size)
    }

    /// bugfix(showcase effect 色块不显示):作为 **layer root** 收集本层内容时调用
    /// (paint_layer_recursive 专用)。
    ///
    /// 边界 RO(RepaintBoundary / Transform / Opacity / ClipRRect)的 `paint` 是
    /// noop —— 语义是"父层的 paint 走到这里必须跳过子树,内容由子 layer 的 GPU
    /// texture 合成"。但这要求 effect 容器的 child 自己也是一个 boundary(有自己的
    /// layer),否则**没有任何人把 child 内容画进 effect layer** → cmds=0 → 整层
    /// 不可见(fx 区 effect layer 回归 fx_zone_effect_layers_paint_all_rects 实锤)。
    ///
    /// 默认实现 = `self.paint`(普通容器 RO 就是本层内容本身);边界 RO override
    /// 为 `child.paint`(透传内容)。透传递归中若再遇到边界 RO(嵌套 layer),
    /// 其 `paint` 仍是 noop,自动排除 —— 不会与子 layer 的 texture 重复。
    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
        self.paint(offset, painter);
    }

    /// 阶段 4-D:容器 RO 暴露 push_child 让 Element 层在 mount 时填 children RO。
    /// 默认 noop(叶子 RO)。容器 RO(Stack/Column/ListView)override 实现 push 语义。
    ///
    /// **可扩展**:加 Padding/Positioned/ClipRRect 等容器时,override 此方法实现各自 push 语义。
    /// leaf RO 不需要 override。
    fn push_child(&mut self, _offset: Point, _child: SharedRO) {
        // 叶子 RO 默认 noop
    }

    /// 阶段 4-D:容器 RO 的 children 数量(让 Element 层知道 RO 是否还有空 slot)
    /// 默认 0(叶子 RO 没有 children)
    fn children_count(&self) -> usize {
        0
    }

    /// 阶段 5:返回此 RO 携带的 layer 视觉效果(Transform / Opacity / ClipRRect...)
    ///
    /// Element 层 mount RepaintBoundary 子类时调 `ro.layer_effect()` 把 effect
    /// 写到 `Layer.effect`,Renderer Pass 2 blit 走 shader 对应分支。
    ///
    /// 默认 `None`(无效果 — 90% 的 layer 不需要 effect,shader 走快速路径)。
    /// - RRect / Text / Image 等叶子 RO:None(自己直接画,没 layer 概念)
    /// - RepaintBoundary 叶子 RO:None(只是个 layer 边界,不带 effect)
    /// - **TransformRenderObject** / **OpacityRenderObject** / **ClipRRectRenderObject**:
    ///   override 返回对应 effect
    fn layer_effect(&self) -> crate::paint::LayerEffect {
        crate::paint::LayerEffect::None
    }

    /// 阶段 2-E:RO 持有的 element_id(未设置 = None)
    ///
    /// 用于 `ElementTree::element_origin` 等 RO 树遍历(IME 光标定位:
    /// 焦点 element 的窗口坐标)。叶子 RO override 返回自己的 element_id。
    fn element_id(&self) -> Option<ElementId> {
        None
    }

    /// 阶段 5-G:由 ElementTree 在 mount/update 时调用,把 element 的
    /// `SubscriberId` 注入 RO。**只在 paint/hit_test 期间作为 signal 的
    /// subscriber 用**——PositionedRenderObject 之类持 Signal 的 RO override 此钩子;
    /// 其他 RO 默认 noop。
    fn set_subscriber_id(&mut self, _id: crate::reactive::SubscriberId) {}

    /// 阶段 2-E:子 (offset, RO) 槽位 — layout 后的最终位置(相对本 RO 原点)
    ///
    /// `element_origin` 沿 RO 树 DFS 时用。容器 RO override。
    /// **局限**:嵌套 layer(RepaintBoundary)内的子树,其 layer 相对父 layer
    /// 的 blit offset 不在此遍历内(阶段 2-E 简化;TextField 演示不包 RB)。
    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        Vec::new()
    }

    /// P1-7:无分配遍历直接子槽(offset 相对本 RO 原点)。
    ///
    /// 默认委托 `child_slots()`(会分配 Vec);容器 RO 应 override 为直接迭代。
    /// origin / a11y bounds / 协议审计等 DFS 热路径使用此入口。
    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
        for (offset, child) in self.child_slots() {
            f(offset, &child);
        }
    }

    /// P0-1:由具体 RO 从 state 读取可变量并**就地**写回自身。
    ///
    /// 默认 `Unsupported` = 框架回退 `State::create_render_object`(行为不变)。
    /// 实现约定(详见架构审查 §11):
    /// - 只能修改自身字段;不得替换自身、child slot 或任何子 RO;
    /// - 修改了几何输入必须失效自身布局缓存;
    /// - 结构/类型变化,或实现不确定时返回 `Unsupported`;
    /// - 必须可重复调用,不得依赖调用次数。
    fn apply_state(&mut self, _state: &mut dyn Any) -> StateApply {
        StateApply::Unsupported
    }
}

/// 让 `Box<T>` 自动转发 `RenderObject` 方法,
/// 这样 `ColumnRenderObject::push(Box<dyn RenderObject>)` 等能直接通过。
///
/// orphan rule:`RenderObject` 是本 crate 的 trait,所以即使 `Box` 来自 std,
/// 给 `Box<T: RenderObject + ?Sized>` impl 也是允许的。
impl<T: RenderObject + ?Sized> RenderObject for Box<T> {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        (**self).layout(constraints, ctx)
    }
    fn paint(&self, offset: Point, painter: &mut PaintList) {
        (**self).paint(offset, painter);
    }
    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        (**self).hit_test(position, offset)
    }
    fn scrollbar_lane_hit(&self, local: Point) -> bool {
        (**self).scrollbar_lane_hit(local)
    }
    fn set_element_id(&mut self, id: ElementId) {
        (**self).set_element_id(id);
    }
    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        (**self).propagate_element_ids(child_ids, stateful_ros);
    }
    /// 阶段 4-D:Box 必须转发 content_size,否则 `Box<dyn RenderObject>` 调 content_size
    /// 会走 RenderObject trait 默认实现(返回 ZERO),丢失真正的 size。
    fn content_size(&self) -> Size {
        (**self).content_size()
    }
    fn content_size_opt(&self) -> Option<Size> {
        (**self).content_size_opt()
    }
    fn layer_size_hint(&self) -> Option<Size> {
        (**self).layer_size_hint()
    }
    fn layer_layout_size(&self) -> Option<Size> {
        (**self).layer_layout_size()
    }
    fn layer_relayout_constraints(&self, layout_size: Size) -> BoxConstraints {
        (**self).layer_relayout_constraints(layout_size)
    }
    /// bugfix:Box 转发 paint_as_layer_root 到内层(否则边界 RO 被包在 Box 里时
    /// 会走默认 self.paint,丢失透传语义)。
    fn paint_as_layer_root(&self, offset: Point, painter: &mut PaintList) {
        (**self).paint_as_layer_root(offset, painter)
    }
    /// 阶段 5:Box 转发 layer_effect 到内层
    fn layer_effect(&self) -> crate::paint::LayerEffect {
        (**self).layer_effect()
    }
    /// 阶段 5-G:Box 转发 set_subscriber_id 到内层(否则 Box 默认 noop 会吞掉
    /// PositionedRenderObject 等 override 的钩子调用,导致 Signal 订阅链路断裂)
    fn set_subscriber_id(&mut self, id: crate::reactive::SubscriberId) {
        (**self).set_subscriber_id(id);
    }
    /// 阶段 2-E:Box 转发 element_id
    fn element_id(&self) -> Option<ElementId> {
        (**self).element_id()
    }
    /// 阶段 2-E:Box 转发 child_slots
    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        (**self).child_slots()
    }
    /// 阶段 4-D:Box 必须转发 push_child,否则 `Box<dyn RenderObject>` 走默认 noop,
    /// Element 层 mount 时填不进子 RO。
    fn push_child(&mut self, offset: Point, child: SharedRO) {
        (**self).push_child(offset, child);
    }
    /// 阶段 4-D:Box 必须转发 children_count,否则默认 0 会让 slot 计数失真。
    fn children_count(&self) -> usize {
        (**self).children_count()
    }
    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
        (**self).for_each_child(f)
    }
    /// P0-1:Box 必须转发 apply_state,否则 `Box<dyn RenderObject>` 会走默认
    /// `Unsupported`,所有就地更新都被静默跳过。
    fn apply_state(&mut self, state: &mut dyn Any) -> StateApply {
        (**self).apply_state(state)
    }
}

// =================================================================
// 阶段 5:effect 几何辅助函数
// =================================================================

/// 阶段 5:点是否在圆角矩形内(几何等价于 shader 的 RRect alpha mask)
pub fn point_in_rrect(p: Point, rect_origin: Point, size: Size, radius: f32) -> bool {
    if size.width <= 0.0 || size.height <= 0.0 {
        return false;
    }
    let r = radius.max(0.0);
    let left = rect_origin.x;
    let top = rect_origin.y;
    let right = left + size.width;
    let bottom = top + size.height;
    if p.x < left || p.x > right || p.y < top || p.y > bottom {
        return false;
    }
    // 4 个角区域:以 corner center 为圆心,半径 r,点在圆外则不在 rrect 内
    let r = r.min(size.width * 0.5).min(size.height * 0.5);
    if r <= 0.0 {
        return true; // 直角矩形,前面 bounds 判定通过即可
    }
    // 4 个 corner center
    let c_tl = Point::new(left + r, top + r);
    let c_tr = Point::new(right - r, top + r);
    let c_bl = Point::new(left + r, bottom - r);
    let c_br = Point::new(right - r, bottom - r);
    // 左上角
    if p.x < c_tl.x && p.y < c_tl.y {
        return dist_sq(p, c_tl) <= r * r;
    }
    // 右上角
    if p.x > c_tr.x && p.y < c_tr.y {
        return dist_sq(p, c_tr) <= r * r;
    }
    // 左下角
    if p.x < c_bl.x && p.y > c_bl.y {
        return dist_sq(p, c_bl) <= r * r;
    }
    // 右下角
    if p.x > c_br.x && p.y > c_br.y {
        return dist_sq(p, c_br) <= r * r;
    }
    // 不在 corner 区域,前面 bounds 判定通过即可
    true
}

fn dist_sq(a: Point, b: Point) -> f32 {
    let dx = a.x - b.x;
    let dy = a.y - b.y;
    dx * dx + dy * dy
}

/// 阶段 5:把世界坐标 `p` 通过 Transform2D 反向变换到 layer 局部坐标
///
/// `forward(world_p) = R(rot) * S(sx, sy) * (local_p - center) + center + translate`
/// 反向:
///   `local_p = S(1/sx, 1/sy) * R(-rot) * (world_p - center - translate) + center`
pub fn inverse_apply_transform(world_p: Point, t: crate::Transform2D, cx: f32, cy: f32) -> Point {
    // 正向 = c + t + R(θ)·S·(p-c);逆变换必须按 S⁻¹·R⁻¹ 的顺序:
    // 先反旋转,再反缩放。非均匀缩放时 R⁻¹·S⁻¹ 与 S⁻¹·R⁻¹ 不相等,
    // 先除缩放会导致旋转+拉伸组合的命中坐标偏移。
    let px = world_p.x - cx - t.translate.x;
    let py = world_p.y - cy - t.translate.y;
    let c = (-t.rotation).cos();
    let sn = (-t.rotation).sin();
    let rx = px * c - py * sn;
    let ry = px * sn + py * c;
    // 反向缩放(两轴独立;退化值兜底为 1.0 避免除零)
    let sx = if t.scale_x.abs() < 1e-6 { 1.0 } else { t.scale_x };
    let sy = if t.scale_y.abs() < 1e-6 { 1.0 } else { t.scale_y };
    Point::new(rx / sx + cx, ry / sy + cy)
}

// =================================================================
// 容器节点共享 slot
// =================================================================

struct ChildSlot {
    child: SharedRO,
    cached_size: Size,
}

// =================================================================
// Submodule declarations
// =================================================================

pub mod border;
pub mod clip_rrect;
pub mod column;
pub mod layer_proxy;
pub mod margin;
pub mod opacity;
pub mod padding;
pub mod positioned;
pub mod proxy;
pub mod row;
pub mod rrect;
pub mod stack;
pub mod transform;

// 组件专属 RO 已迁到 mgui-components/src/render_object/ (button/checkbox/slider/switch_ro/progress/focus_scope/scroll_view)

// #[cfg(test)]
// pub mod tests; // 已迁到 crates/mgui-test/tests/render_object.rs

// =================================================================
// Re-exports (保持全部原始 pub 名)
// =================================================================

pub use border::{Border, BorderRenderObject};
pub use clip_rrect::ClipRRectRenderObject;
pub use column::ColumnRenderObject;
pub use layer_proxy::LayerProxyRenderObject;
pub use margin::MarginRenderObject;
pub use opacity::OpacityRenderObject;
pub use padding::EdgeInsets;
pub use padding::PaddingRenderObject;
pub use positioned::PositionedRenderObject;
pub use proxy::ProxyRenderObject;
pub use row::RowRenderObject;
pub use rrect::RRectRenderObject;
pub use stack::StackRenderObject;
pub use transform::TransformRenderObject;