mgui-core 0.1.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
//! 阶段 4-A4:ErrorBoundary — 子树 build panic 隔离
//!
//! # 动机
//!
//! 框架正处快速迭代期,任何 widget 的 `build`/`children()` panic 都会击穿整棵
//! element 树让 app 直接挂掉。ErrorBoundary 提供声明式的故障隔离:坏 widget
//! 只损失自己所在的子树,外层 UI 继续存活(等价 Flutter `ErrorWidget`/React
//! Error Boundary 的定位,见设计文档第二十一章)。
//!
//! # 架构(与设计文档的差异说明)
//!
//! 设计文档初稿是"ErrorBoundaryState.build 里 catch_unwind 包 child.build()"。
//! 实际本框架的子树构建由 ElementTree 驱动(`children_with_positions_of` →
//! 递归 mount/update),state.build 只返回**一层的** child 列表,子树的深递归
//! 发生在 state.build 返回之后。因此在 ErrorBoundaryState.build 里包
//! catch_unwind 拦不到后代 build 的 panic。
//!
//! 实际方案:**catch_unwind 放在 ElementTree::children_with_positions_of 的
//! 两个调用点**(state.build / widget.children_with_positions)。panic 发生时:
//! 1. 沿 element 父链向上找最近一个 `handles_build_error() == true` 的 state
//!    (即 ErrorBoundaryState),调 `on_build_error(msg)` 写入错误;
//! 2. panic 的 element 本轮 children 视为空(旧 children 被 diff 卸载);
//! 3. 下一帧 `ErrorBoundaryState::build` 读到 `error = Some(msg)`,
//!    输出 fallback widget → 显示错误 UI(一帧空白后 fallback 出现,runtime
//!    每帧都调 `tree.update`,延迟恒定);
//! 4. 找不到任何 ErrorBoundary → `resume_unwind`,保持原语义(app 挂)。
//!
//! # 用法
//!
//! ```
//! use mgui_core::error_boundary::{ErrorBoundaryWidget, PanicWidget};
//! use mgui_core::widget::{RRectWidget, WidgetNode};
//! use mgui_core::{Color, Size};
//!
//! let boundary = ErrorBoundaryWidget::new(PanicWidget::boom("boom"))
//!     .fallback(|msg| {
//!         WidgetNode::new(RRectWidget::new(
//!             Size::new(120.0, 40.0),
//!             Color::rgba(0.8, 0.2, 0.2, 1.0),
//!             6.0,
//!         ))
//!     });
//! ```

use std::any::Any;
use std::fmt;
use std::rc::Rc;

use crate::id::ElementId;
use crate::inherited::BuildContext;
use crate::paint::LayerEffect;
use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
use crate::widget::{State, Widget, WidgetNode};
use crate::{Color, Point, Size};

// ============================================================
// fallback 构造器类型
// ============================================================

/// 由错误消息构造 fallback widget 的闭包类型
pub type FallbackBuilder = Rc<dyn Fn(&str) -> WidgetNode>;

// ============================================================
// RenderObject
// ============================================================

/// ErrorBoundary 的 RO:单 child 透传容器。
///
/// 结构与 OpacityRenderObject 同构(child slot + set_element_id 透传 +
/// child_slots 透传),只是没有 layer effect — ErrorBoundary 不改视觉,
/// 只是切换"显示 child 还是 fallback"。
pub struct ErrorBoundaryRenderObject {
    pub child: Option<SharedRO>,
    pub element_id: Option<ElementId>,
    pub size: Size,
}

impl ErrorBoundaryRenderObject {
    pub fn new(child: Box<dyn RenderObject>) -> Self {
        Self { child: Some(make_ro_shared(child)), element_id: None, size: Size::ZERO }
    }
}

impl fmt::Debug for ErrorBoundaryRenderObject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorBoundaryRenderObject")
            .field("element_id", &self.element_id)
            .field("has_child", &self.child.is_some())
            .field("size", &self.size)
            .finish()
    }
}

impl RenderObject for ErrorBoundaryRenderObject {
    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
        self.size = self.child.as_mut().map(|c| c.layout_cached(constraints, ctx)).unwrap_or(Size::ZERO);
        self.size
    }
    fn paint(&self, offset: Point, painter: &mut crate::paint::PaintList) {
        if let Some(c) = &self.child {
            c.borrow().paint(offset, painter);
        }
    }
    fn paint_as_layer_root(&self, offset: Point, painter: &mut crate::paint::PaintList) {
        // 防御:即使被误标为 layer root 也不丢内容
        if let Some(c) = &self.child {
            c.borrow().paint(offset, painter);
        }
    }
    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
        self.child.as_ref()?.borrow().hit_test(position, offset)
    }
    fn set_element_id(&mut self, _id: ElementId) {
        // noop(与 Opacity 一致)
    }
    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
    }

    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
        if let Some(c) = &self.child {
            f(Point::ZERO, c);
        }
    }
    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
        if let (Some(child_ro), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
            if let Some(new_ro) = stateful_ros.first_mut() {
                *child_ro = new_ro.clone();
            }
            child_ro.borrow_mut().set_element_id(cid);
        }
    }
    fn content_size(&self) -> Size {
        self.size
    }
    fn push_child(&mut self, _offset: Point, _child: SharedRO) {
        // noop
    }
    fn children_count(&self) -> usize {
        if self.child.is_some() {
            1
        } else {
            0
        }
    }
    fn layer_effect(&self) -> LayerEffect {
        LayerEffect::None
    }
}

// ============================================================
// ErrorBoundaryWidget
// ============================================================

/// 错误边界 widget:child 构建时 panic → 显示 fallback(并把错误消息传给
/// fallback 闭包),同子树之外的 UI 不受影响。
///
/// # 恢复
///
/// 一旦进入 fallback 状态,**不会自动恢复**(error 状态持久,防止每帧重试
/// panic 的 build 死循环)。想恢复:rebuild 时改 `reset_key`(did_update_widget
/// 检测到 key 变化 → 清 error → 下一轮 build 重试 child)。
/// 调用方需保证重试时 child 已经不会 panic(例如翻转信号驱动的开关)。
pub struct ErrorBoundaryWidget {
    pub child: WidgetNode,
    fallback: FallbackBuilder,
    /// 变化时清除 error 状态、重试 child(恢复机制)
    pub reset_key: u64,
    /// 可选 key(阶段 3-C,ListView 复用 Element)
    key: Option<u64>,
}

impl fmt::Debug for ErrorBoundaryWidget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorBoundaryWidget")
            .field("child", &self.child)
            .field("has_fallback", &true)
            .field("reset_key", &self.reset_key)
            .finish()
    }
}

impl ErrorBoundaryWidget {
    /// 包裹 `child`;fallback 默认为红色块(`ErrorFallbackWidget`)
    pub fn new(child: impl Widget) -> Self {
        Self::new_node(WidgetNode::new(child))
    }

    /// 同 [`ErrorBoundaryWidget::new`],但 child 已是 WidgetNode
    /// (嵌套组装树时的常用形态)
    pub fn new_node(child: WidgetNode) -> Self {
        Self { child, fallback: Rc::new(|_msg| WidgetNode::new(ErrorFallbackWidget)), reset_key: 0, key: None }
    }

    /// 设置 fallback 构造器(收到错误消息)
    pub fn fallback(mut self, f: impl Fn(&str) -> WidgetNode + 'static) -> Self {
        self.fallback = Rc::new(f);
        self
    }

    /// 设置 reset_key(下次 update 时 key 变化 → 清 error 重试 child)
    pub fn with_reset_key(mut self, key: u64) -> Self {
        self.reset_key = key;
        self
    }

    /// 设置 key(阶段 3-C:ListView 中按 key 配对,保留 state)
    pub fn with_key(mut self, key: u64) -> Self {
        self.key = Some(key);
        self
    }
}

impl Widget for ErrorBoundaryWidget {
    fn is_stateful(&self) -> bool {
        true
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(ErrorBoundaryState::new()))
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        // 纯 widget 路径兜底(stateful,Element 实际走 state.create_render_object)
        Box::new(ErrorBoundaryRenderObject::new(self.child.0.create_render_object()))
    }

    fn children(&self) -> Vec<WidgetNode> {
        vec![self.child.clone()]
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn key(&self) -> Option<u64> {
        self.key
    }
}

// ============================================================
// ErrorBoundaryState
// ============================================================

/// ErrorBoundary 的 element state。
///
/// 字段:
/// - `error`:最近一次 descendant build panic 的消息;`Some` → build 输出 fallback
/// - `last_reset_key`:上次见过的 reset_key(变化 → 清 error)
pub struct ErrorBoundaryState {
    current: Option<WidgetNode>,
    error: Option<String>,
    last_reset_key: u64,
}

impl fmt::Debug for ErrorBoundaryState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorBoundaryState")
            .field("error", &self.error)
            .field("last_reset_key", &self.last_reset_key)
            .finish()
    }
}

impl ErrorBoundaryState {
    pub fn new() -> Self {
        Self { current: None, error: None, last_reset_key: 0 }
    }

    /// 从当前 widget 取 (child, fallback)
    fn child_and_fallback(&self) -> (WidgetNode, FallbackBuilder) {
        let w = self.widget();
        let eb = w.0.as_any().downcast_ref::<ErrorBoundaryWidget>().expect("widget must be ErrorBoundaryWidget");
        (eb.child.clone(), Rc::clone(&eb.fallback))
    }

    /// 当前错误消息(None = 正常显示 child)
    pub fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }
}

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

impl State for ErrorBoundaryState {
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
    fn build(&self, _ctx: &mut BuildContext<'_>) -> Vec<WidgetNode> {
        let (child, fallback) = self.child_and_fallback();
        match &self.error {
            Some(msg) => vec![fallback(msg)],
            None => vec![child],
        }
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        // 按 error 状态构建对应内容的 RO(architecture 规则 1:state → RO 同步)
        let (child, fallback) = self.child_and_fallback();
        let content = match &self.error {
            Some(msg) => fallback(msg),
            None => child,
        };
        Box::new(ErrorBoundaryRenderObject::new(content.0.create_render_object()))
    }

    fn did_update_widget(&mut self) {
        // reset_key 变化 → 清 error,下一轮 build 重试 child
        let key = self
            .widget()
            .0
            .as_any()
            .downcast_ref::<ErrorBoundaryWidget>()
            .map(|w| w.reset_key)
            .unwrap_or(self.last_reset_key);
        if key != self.last_reset_key && self.error.is_some() {
            self.error = None;
        }
        self.last_reset_key = key;
    }

    fn handles_build_error(&self) -> bool {
        true
    }

    fn on_build_error(&mut self, msg: &str) {
        // 保留第一次的错误(嵌套 panic 时不被覆盖)
        if self.error.is_none() {
            self.error = Some(msg.to_string());
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("ErrorBoundaryState: widget not set (init_state 之前?)")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }
}

// ============================================================
// 默认 fallback
// ============================================================

/// 默认 fallback:红色圆角块(本 crate 不依赖 runtime 的 TextWidget,
/// 需要显示错误文字时用 `.fallback(|msg| TextWidget::new(msg))` 自定义)
#[derive(Debug, Clone, Copy, Default)]
pub struct ErrorFallbackWidget;

impl Widget for ErrorFallbackWidget {
    fn create_render_object(&self) -> Box<dyn RenderObject> {
        Box::new(RRectRenderObject::new(Size::new(80.0, 28.0), Color::rgba(0.82, 0.22, 0.22, 1.0), 4.0))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

// ============================================================
// 测试/演示用:panic widget
// ============================================================

/// build(`children()`)时 panic 的 widget — A4 测试与 showcase 演示用
#[derive(Debug, Clone)]
pub struct PanicWidget {
    pub message: String,
    pub panic_on: bool,
}

impl PanicWidget {
    pub fn boom(message: impl Into<String>) -> Self {
        Self { message: message.into(), panic_on: true }
    }

    /// 同型 widget 但不 panic(恢复测试用:同 type 才能复用 element)
    pub fn calm(message: impl Into<String>) -> Self {
        Self { message: message.into(), panic_on: false }
    }
}

impl Widget for PanicWidget {
    fn create_render_object(&self) -> Box<dyn RenderObject> {
        Box::new(RRectRenderObject::new(Size::new(100.0, 40.0), Color::rgba(0.9, 0.75, 0.2, 1.0), 4.0))
    }

    fn children(&self) -> Vec<WidgetNode> {
        if self.panic_on {
            panic!("{}", self.message);
        }
        Vec::new()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// state.build panic 的 stateful 版本(覆盖 catch_unwind 的 state 路径)
#[derive(Debug, Clone)]
pub struct PanicStateWidget {
    pub message: String,
    pub panic_on: bool,
}

impl PanicStateWidget {
    pub fn boom(message: impl Into<String>) -> Self {
        Self { message: message.into(), panic_on: true }
    }

    pub fn calm(message: impl Into<String>) -> Self {
        Self { message: message.into(), panic_on: false }
    }
}

impl Widget for PanicStateWidget {
    fn is_stateful(&self) -> bool {
        true
    }

    fn create_state(&self) -> Option<Box<dyn State>> {
        Some(Box::new(PanicStateWidgetState::new()))
    }

    fn create_render_object(&self) -> Box<dyn RenderObject> {
        Box::new(RRectRenderObject::new(Size::new(100.0, 40.0), Color::rgba(0.9, 0.6, 0.2, 1.0), 4.0))
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

#[derive(Debug, Default)]
pub struct PanicStateWidgetState {
    current: Option<WidgetNode>,
}

impl PanicStateWidgetState {
    pub fn new() -> Self {
        Self::default()
    }
}

impl State for PanicStateWidgetState {
    fn as_any(&self) -> &dyn Any {
        self
    }
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
    fn build(&self, _ctx: &mut BuildContext<'_>) -> Vec<WidgetNode> {
        let msg = self
            .widget()
            .0
            .as_any()
            .downcast_ref::<PanicStateWidget>()
            .map(|w| (w.message.clone(), w.panic_on))
            .unwrap_or_default();
        if msg.1 {
            panic!("{}", msg.0);
        }
        Vec::new()
    }

    fn widget(&self) -> &WidgetNode {
        self.current.as_ref().expect("PanicStateWidgetState: widget not set")
    }

    fn set_widget(&mut self, widget: WidgetNode) {
        self.current = Some(widget);
    }
}

// ============================================================
// panic message 提取(element.rs 的 catch 处理用)
// ============================================================

/// 从 `catch_unwind` payload 提取可读消息
pub(crate) fn extract_panic_message(payload: &(dyn Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic payload".to_string()
    }
}

// ============================================================
// 测试
// ============================================================

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