1use 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
56pub type FallbackBuilder = Rc<dyn Fn(&str) -> WidgetNode>;
62
63pub 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 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 }
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 }
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
151pub struct ErrorBoundaryWidget {
165 pub child: WidgetNode,
166 fallback: FallbackBuilder,
167 pub reset_key: u64,
169 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 pub fn new(child: impl Widget) -> Self {
186 Self::new_node(WidgetNode::new(child))
187 }
188
189 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 pub fn fallback(mut self, f: impl Fn(&str) -> WidgetNode + 'static) -> Self {
197 self.fallback = Rc::new(f);
198 self
199 }
200
201 pub fn with_reset_key(mut self, key: u64) -> Self {
203 self.reset_key = key;
204 self
205 }
206
207 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 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
241pub 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 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 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 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 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 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#[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#[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 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#[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
484pub(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