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};
pub type FallbackBuilder = Rc<dyn Fn(&str) -> WidgetNode>;
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) {
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) {
}
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) {
}
fn children_count(&self) -> usize {
if self.child.is_some() {
1
} else {
0
}
}
fn layer_effect(&self) -> LayerEffect {
LayerEffect::None
}
}
pub struct ErrorBoundaryWidget {
pub child: WidgetNode,
fallback: FallbackBuilder,
pub reset_key: u64,
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 {
pub fn new(child: impl Widget) -> Self {
Self::new_node(WidgetNode::new(child))
}
pub fn new_node(child: WidgetNode) -> Self {
Self { child, fallback: Rc::new(|_msg| WidgetNode::new(ErrorFallbackWidget)), reset_key: 0, key: None }
}
pub fn fallback(mut self, f: impl Fn(&str) -> WidgetNode + 'static) -> Self {
self.fallback = Rc::new(f);
self
}
pub fn with_reset_key(mut self, key: u64) -> Self {
self.reset_key = key;
self
}
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> {
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
}
}
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 }
}
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))
}
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> {
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) {
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) {
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);
}
}
#[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
}
}
#[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 }
}
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
}
}
#[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);
}
}
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()
}
}