Skip to main content

mgui_core/
error_boundary.rs

1//! 阶段 4-A4:ErrorBoundary — 子树 build panic 隔离
2//!
3//! # 动机
4//!
5//! 框架正处快速迭代期,任何 widget 的 `build`/`children()` panic 都会击穿整棵
6//! element 树让 app 直接挂掉。ErrorBoundary 提供声明式的故障隔离:坏 widget
7//! 只损失自己所在的子树,外层 UI 继续存活(等价 Flutter `ErrorWidget`/React
8//! Error Boundary 的定位,见设计文档第二十一章)。
9//!
10//! # 架构(与设计文档的差异说明)
11//!
12//! 设计文档初稿是"ErrorBoundaryState.build 里 catch_unwind 包 child.build()"。
13//! 实际本框架的子树构建由 ElementTree 驱动(`children_with_positions_of` →
14//! 递归 mount/update),state.build 只返回**一层的** child 列表,子树的深递归
15//! 发生在 state.build 返回之后。因此在 ErrorBoundaryState.build 里包
16//! catch_unwind 拦不到后代 build 的 panic。
17//!
18//! 实际方案:**catch_unwind 放在 ElementTree::children_with_positions_of 的
19//! 两个调用点**(state.build / widget.children_with_positions)。panic 发生时:
20//! 1. 沿 element 父链向上找最近一个 `handles_build_error() == true` 的 state
21//!    (即 ErrorBoundaryState),调 `on_build_error(msg)` 写入错误;
22//! 2. panic 的 element 本轮 children 视为空(旧 children 被 diff 卸载);
23//! 3. 下一帧 `ErrorBoundaryState::build` 读到 `error = Some(msg)`,
24//!    输出 fallback widget → 显示错误 UI(一帧空白后 fallback 出现,runtime
25//!    每帧都调 `tree.update`,延迟恒定);
26//! 4. 找不到任何 ErrorBoundary → `resume_unwind`,保持原语义(app 挂)。
27//!
28//! # 用法
29//!
30//! ```
31//! use mgui_core::error_boundary::{ErrorBoundaryWidget, PanicWidget};
32//! use mgui_core::widget::{RRectWidget, WidgetNode};
33//! use mgui_core::{Color, Size};
34//!
35//! let boundary = ErrorBoundaryWidget::new(PanicWidget::boom("boom"))
36//!     .fallback(|msg| {
37//!         WidgetNode::new(RRectWidget::new(
38//!             Size::new(120.0, 40.0),
39//!             Color::rgba(0.8, 0.2, 0.2, 1.0),
40//!             6.0,
41//!         ))
42//!     });
43//! ```
44
45use std::any::Any;
46use std::fmt;
47use std::rc::Rc;
48
49use crate::id::ElementId;
50use crate::inherited::BuildContext;
51use crate::paint::LayerEffect;
52use crate::render_object::{make_ro_shared, BoxConstraints, LayoutContext, RRectRenderObject, RenderObject, SharedRO};
53use crate::widget::{State, Widget, WidgetNode};
54use crate::{Color, Point, Size};
55
56// ============================================================
57// fallback 构造器类型
58// ============================================================
59
60/// 由错误消息构造 fallback widget 的闭包类型
61pub type FallbackBuilder = Rc<dyn Fn(&str) -> WidgetNode>;
62
63// ============================================================
64// RenderObject
65// ============================================================
66
67/// ErrorBoundary 的 RO:单 child 透传容器。
68///
69/// 结构与 OpacityRenderObject 同构(child slot + set_element_id 透传 +
70/// child_slots 透传),只是没有 layer effect — ErrorBoundary 不改视觉,
71/// 只是切换"显示 child 还是 fallback"。
72pub struct ErrorBoundaryRenderObject {
73    pub child: Option<SharedRO>,
74    pub element_id: Option<ElementId>,
75    pub size: Size,
76}
77
78impl ErrorBoundaryRenderObject {
79    pub fn new(child: Box<dyn RenderObject>) -> Self {
80        Self { child: Some(make_ro_shared(child)), element_id: None, size: Size::ZERO }
81    }
82}
83
84impl fmt::Debug for ErrorBoundaryRenderObject {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        f.debug_struct("ErrorBoundaryRenderObject")
87            .field("element_id", &self.element_id)
88            .field("has_child", &self.child.is_some())
89            .field("size", &self.size)
90            .finish()
91    }
92}
93
94impl RenderObject for ErrorBoundaryRenderObject {
95    fn layout(&mut self, constraints: BoxConstraints, ctx: &mut LayoutContext) -> Size {
96        self.size = self.child.as_mut().map(|c| c.layout_cached(constraints, ctx)).unwrap_or(Size::ZERO);
97        self.size
98    }
99    fn paint(&self, offset: Point, painter: &mut crate::paint::PaintList) {
100        if let Some(c) = &self.child {
101            c.borrow().paint(offset, painter);
102        }
103    }
104    fn paint_as_layer_root(&self, offset: Point, painter: &mut crate::paint::PaintList) {
105        // 防御:即使被误标为 layer root 也不丢内容
106        if let Some(c) = &self.child {
107            c.borrow().paint(offset, painter);
108        }
109    }
110    fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
111        self.child.as_ref()?.borrow().hit_test(position, offset)
112    }
113    fn set_element_id(&mut self, _id: ElementId) {
114        // noop(与 Opacity 一致)
115    }
116    fn child_slots(&self) -> Vec<(Point, SharedRO)> {
117        self.child.as_ref().map(|c| vec![(Point::ZERO, c.clone())]).unwrap_or_default()
118    }
119
120    fn for_each_child(&self, f: &mut dyn FnMut(Point, &SharedRO)) {
121        if let Some(c) = &self.child {
122            f(Point::ZERO, c);
123        }
124    }
125    fn propagate_element_ids(&mut self, child_ids: &[ElementId], stateful_ros: &mut [SharedRO]) {
126        if let (Some(child_ro), Some(&cid)) = (self.child.as_mut(), child_ids.first()) {
127            if let Some(new_ro) = stateful_ros.first_mut() {
128                *child_ro = new_ro.clone();
129            }
130            child_ro.borrow_mut().set_element_id(cid);
131        }
132    }
133    fn content_size(&self) -> Size {
134        self.size
135    }
136    fn push_child(&mut self, _offset: Point, _child: SharedRO) {
137        // noop
138    }
139    fn children_count(&self) -> usize {
140        if self.child.is_some() {
141            1
142        } else {
143            0
144        }
145    }
146    fn layer_effect(&self) -> LayerEffect {
147        LayerEffect::None
148    }
149}
150
151// ============================================================
152// ErrorBoundaryWidget
153// ============================================================
154
155/// 错误边界 widget:child 构建时 panic → 显示 fallback(并把错误消息传给
156/// fallback 闭包),同子树之外的 UI 不受影响。
157///
158/// # 恢复
159///
160/// 一旦进入 fallback 状态,**不会自动恢复**(error 状态持久,防止每帧重试
161/// panic 的 build 死循环)。想恢复:rebuild 时改 `reset_key`(did_update_widget
162/// 检测到 key 变化 → 清 error → 下一轮 build 重试 child)。
163/// 调用方需保证重试时 child 已经不会 panic(例如翻转信号驱动的开关)。
164pub struct ErrorBoundaryWidget {
165    pub child: WidgetNode,
166    fallback: FallbackBuilder,
167    /// 变化时清除 error 状态、重试 child(恢复机制)
168    pub reset_key: u64,
169    /// 可选 key(阶段 3-C,ListView 复用 Element)
170    key: Option<u64>,
171}
172
173impl fmt::Debug for ErrorBoundaryWidget {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.debug_struct("ErrorBoundaryWidget")
176            .field("child", &self.child)
177            .field("has_fallback", &true)
178            .field("reset_key", &self.reset_key)
179            .finish()
180    }
181}
182
183impl ErrorBoundaryWidget {
184    /// 包裹 `child`;fallback 默认为红色块(`ErrorFallbackWidget`)
185    pub fn new(child: impl Widget) -> Self {
186        Self::new_node(WidgetNode::new(child))
187    }
188
189    /// 同 [`ErrorBoundaryWidget::new`],但 child 已是 WidgetNode
190    /// (嵌套组装树时的常用形态)
191    pub fn new_node(child: WidgetNode) -> Self {
192        Self { child, fallback: Rc::new(|_msg| WidgetNode::new(ErrorFallbackWidget)), reset_key: 0, key: None }
193    }
194
195    /// 设置 fallback 构造器(收到错误消息)
196    pub fn fallback(mut self, f: impl Fn(&str) -> WidgetNode + 'static) -> Self {
197        self.fallback = Rc::new(f);
198        self
199    }
200
201    /// 设置 reset_key(下次 update 时 key 变化 → 清 error 重试 child)
202    pub fn with_reset_key(mut self, key: u64) -> Self {
203        self.reset_key = key;
204        self
205    }
206
207    /// 设置 key(阶段 3-C:ListView 中按 key 配对,保留 state)
208    pub fn with_key(mut self, key: u64) -> Self {
209        self.key = Some(key);
210        self
211    }
212}
213
214impl Widget for ErrorBoundaryWidget {
215    fn is_stateful(&self) -> bool {
216        true
217    }
218
219    fn create_state(&self) -> Option<Box<dyn State>> {
220        Some(Box::new(ErrorBoundaryState::new()))
221    }
222
223    fn create_render_object(&self) -> Box<dyn RenderObject> {
224        // 纯 widget 路径兜底(stateful,Element 实际走 state.create_render_object)
225        Box::new(ErrorBoundaryRenderObject::new(self.child.0.create_render_object()))
226    }
227
228    fn children(&self) -> Vec<WidgetNode> {
229        vec![self.child.clone()]
230    }
231
232    fn as_any(&self) -> &dyn Any {
233        self
234    }
235
236    fn key(&self) -> Option<u64> {
237        self.key
238    }
239}
240
241// ============================================================
242// ErrorBoundaryState
243// ============================================================
244
245/// ErrorBoundary 的 element state。
246///
247/// 字段:
248/// - `error`:最近一次 descendant build panic 的消息;`Some` → build 输出 fallback
249/// - `last_reset_key`:上次见过的 reset_key(变化 → 清 error)
250pub struct ErrorBoundaryState {
251    current: Option<WidgetNode>,
252    error: Option<String>,
253    last_reset_key: u64,
254}
255
256impl fmt::Debug for ErrorBoundaryState {
257    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258        f.debug_struct("ErrorBoundaryState")
259            .field("error", &self.error)
260            .field("last_reset_key", &self.last_reset_key)
261            .finish()
262    }
263}
264
265impl ErrorBoundaryState {
266    pub fn new() -> Self {
267        Self { current: None, error: None, last_reset_key: 0 }
268    }
269
270    /// 从当前 widget 取 (child, fallback)
271    fn child_and_fallback(&self) -> (WidgetNode, FallbackBuilder) {
272        let w = self.widget();
273        let eb = w.0.as_any().downcast_ref::<ErrorBoundaryWidget>().expect("widget must be ErrorBoundaryWidget");
274        (eb.child.clone(), Rc::clone(&eb.fallback))
275    }
276
277    /// 当前错误消息(None = 正常显示 child)
278    pub fn error(&self) -> Option<&str> {
279        self.error.as_deref()
280    }
281}
282
283impl Default for ErrorBoundaryState {
284    fn default() -> Self {
285        Self::new()
286    }
287}
288
289impl State for ErrorBoundaryState {
290    fn as_any_mut(&mut self) -> &mut dyn Any {
291        self
292    }
293    fn build(&self, _ctx: &mut BuildContext<'_>) -> Vec<WidgetNode> {
294        let (child, fallback) = self.child_and_fallback();
295        match &self.error {
296            Some(msg) => vec![fallback(msg)],
297            None => vec![child],
298        }
299    }
300
301    fn create_render_object(&self) -> Box<dyn RenderObject> {
302        // 按 error 状态构建对应内容的 RO(architecture 规则 1:state → RO 同步)
303        let (child, fallback) = self.child_and_fallback();
304        let content = match &self.error {
305            Some(msg) => fallback(msg),
306            None => child,
307        };
308        Box::new(ErrorBoundaryRenderObject::new(content.0.create_render_object()))
309    }
310
311    fn did_update_widget(&mut self) {
312        // reset_key 变化 → 清 error,下一轮 build 重试 child
313        let key = self
314            .widget()
315            .0
316            .as_any()
317            .downcast_ref::<ErrorBoundaryWidget>()
318            .map(|w| w.reset_key)
319            .unwrap_or(self.last_reset_key);
320        if key != self.last_reset_key && self.error.is_some() {
321            self.error = None;
322        }
323        self.last_reset_key = key;
324    }
325
326    fn handles_build_error(&self) -> bool {
327        true
328    }
329
330    fn on_build_error(&mut self, msg: &str) {
331        // 保留第一次的错误(嵌套 panic 时不被覆盖)
332        if self.error.is_none() {
333            self.error = Some(msg.to_string());
334        }
335    }
336
337    fn as_any(&self) -> &dyn Any {
338        self
339    }
340
341    fn widget(&self) -> &WidgetNode {
342        self.current.as_ref().expect("ErrorBoundaryState: widget not set (init_state 之前?)")
343    }
344
345    fn set_widget(&mut self, widget: WidgetNode) {
346        self.current = Some(widget);
347    }
348}
349
350// ============================================================
351// 默认 fallback
352// ============================================================
353
354/// 默认 fallback:红色圆角块(本 crate 不依赖 runtime 的 TextWidget,
355/// 需要显示错误文字时用 `.fallback(|msg| TextWidget::new(msg))` 自定义)
356#[derive(Debug, Clone, Copy, Default)]
357pub struct ErrorFallbackWidget;
358
359impl Widget for ErrorFallbackWidget {
360    fn create_render_object(&self) -> Box<dyn RenderObject> {
361        Box::new(RRectRenderObject::new(Size::new(80.0, 28.0), Color::rgba(0.82, 0.22, 0.22, 1.0), 4.0))
362    }
363
364    fn as_any(&self) -> &dyn Any {
365        self
366    }
367}
368
369// ============================================================
370// 测试/演示用:panic widget
371// ============================================================
372
373/// build(`children()`)时 panic 的 widget — A4 测试与 showcase 演示用
374#[derive(Debug, Clone)]
375pub struct PanicWidget {
376    pub message: String,
377    pub panic_on: bool,
378}
379
380impl PanicWidget {
381    pub fn boom(message: impl Into<String>) -> Self {
382        Self { message: message.into(), panic_on: true }
383    }
384
385    /// 同型 widget 但不 panic(恢复测试用:同 type 才能复用 element)
386    pub fn calm(message: impl Into<String>) -> Self {
387        Self { message: message.into(), panic_on: false }
388    }
389}
390
391impl Widget for PanicWidget {
392    fn create_render_object(&self) -> Box<dyn RenderObject> {
393        Box::new(RRectRenderObject::new(Size::new(100.0, 40.0), Color::rgba(0.9, 0.75, 0.2, 1.0), 4.0))
394    }
395
396    fn children(&self) -> Vec<WidgetNode> {
397        if self.panic_on {
398            panic!("{}", self.message);
399        }
400        Vec::new()
401    }
402
403    fn as_any(&self) -> &dyn Any {
404        self
405    }
406}
407
408/// state.build panic 的 stateful 版本(覆盖 catch_unwind 的 state 路径)
409#[derive(Debug, Clone)]
410pub struct PanicStateWidget {
411    pub message: String,
412    pub panic_on: bool,
413}
414
415impl PanicStateWidget {
416    pub fn boom(message: impl Into<String>) -> Self {
417        Self { message: message.into(), panic_on: true }
418    }
419
420    pub fn calm(message: impl Into<String>) -> Self {
421        Self { message: message.into(), panic_on: false }
422    }
423}
424
425impl Widget for PanicStateWidget {
426    fn is_stateful(&self) -> bool {
427        true
428    }
429
430    fn create_state(&self) -> Option<Box<dyn State>> {
431        Some(Box::new(PanicStateWidgetState::new()))
432    }
433
434    fn create_render_object(&self) -> Box<dyn RenderObject> {
435        Box::new(RRectRenderObject::new(Size::new(100.0, 40.0), Color::rgba(0.9, 0.6, 0.2, 1.0), 4.0))
436    }
437
438    fn as_any(&self) -> &dyn Any {
439        self
440    }
441}
442
443#[derive(Debug, Default)]
444pub struct PanicStateWidgetState {
445    current: Option<WidgetNode>,
446}
447
448impl PanicStateWidgetState {
449    pub fn new() -> Self {
450        Self::default()
451    }
452}
453
454impl State for PanicStateWidgetState {
455    fn as_any(&self) -> &dyn Any {
456        self
457    }
458    fn as_any_mut(&mut self) -> &mut dyn Any {
459        self
460    }
461    fn build(&self, _ctx: &mut BuildContext<'_>) -> Vec<WidgetNode> {
462        let msg = self
463            .widget()
464            .0
465            .as_any()
466            .downcast_ref::<PanicStateWidget>()
467            .map(|w| (w.message.clone(), w.panic_on))
468            .unwrap_or_default();
469        if msg.1 {
470            panic!("{}", msg.0);
471        }
472        Vec::new()
473    }
474
475    fn widget(&self) -> &WidgetNode {
476        self.current.as_ref().expect("PanicStateWidgetState: widget not set")
477    }
478
479    fn set_widget(&mut self, widget: WidgetNode) {
480        self.current = Some(widget);
481    }
482}
483
484// ============================================================
485// panic message 提取(element.rs 的 catch 处理用)
486// ============================================================
487
488/// 从 `catch_unwind` payload 提取可读消息
489pub(crate) fn extract_panic_message(payload: &(dyn Any + Send)) -> String {
490    if let Some(s) = payload.downcast_ref::<&str>() {
491        (*s).to_string()
492    } else if let Some(s) = payload.downcast_ref::<String>() {
493        s.clone()
494    } else {
495        "unknown panic payload".to_string()
496    }
497}
498
499// ============================================================
500// 测试
501// ============================================================
502
503// #[cfg(test)] 已迁到 crates/mgui-test/tests/.rs