1use std::any::Any;
14use std::rc::Rc;
15
16use crate::component::ComponentId;
17use crate::event::EventArgs;
18use crate::ui::Ui;
19
20#[derive(Clone, Debug, PartialEq)]
22pub struct Exception {
23 pub message: String,
25 pub path: String,
27 pub event: String,
29}
30
31impl std::fmt::Display for Exception {
32 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33 match (self.path.is_empty(), self.event.is_empty()) {
34 (false, false) => write!(f, "{} ({}.{})", self.message, self.path, self.event),
35 (false, true) => write!(f, "{} ({})", self.message, self.path),
36 _ => f.write_str(&self.message),
37 }
38 }
39}
40
41pub type ExceptionHandlerFn = dyn Fn(&mut Ui, &Exception) -> bool;
43pub type ExceptionDisplayFn = dyn Fn(&mut Ui, &Exception);
45
46pub fn panic_message(payload: &(dyn Any + Send)) -> String {
48 if let Some(s) = payload.downcast_ref::<&str>() {
49 s.to_string()
50 } else if let Some(s) = payload.downcast_ref::<String>() {
51 s.clone()
52 } else {
53 "erro desconhecido".to_string()
54 }
55}
56
57impl Ui {
58 pub fn on_exception(&mut self, f: impl Fn(&mut Ui, &Exception) -> bool + 'static) {
62 self.exceptions.handler = Some(Rc::new(f));
63 }
64
65 pub fn set_exception_display(&mut self, f: impl Fn(&mut Ui, &Exception) + 'static) {
68 self.exceptions.display = Some(Rc::new(f));
69 }
70
71 pub fn raise_exception(&mut self, exception: Exception) {
74 let text = exception.to_string();
75 self.report(&crate::activity::Activity::Error { message: &text });
76 if self.exceptions.handling {
78 crate::stderr_line!("aylis: erro ao tratar um erro: {text}");
79 return;
80 }
81 self.exceptions.handling = true;
82 let mut handled = match self.exceptions.handler.clone() {
83 Some(handler) => self.guard_call(|ui| handler(ui, &exception)).unwrap_or(false),
84 None => false,
85 };
86 if !handled {
88 let args = EventArgs::Text(format!(
89 "{{\"message\":{},\"path\":{},\"event\":{}}}",
90 json_string(&exception.message),
91 json_string(&exception.path),
92 json_string(&exception.event)
93 ));
94 for app in self.application_events() {
95 if self.has_handler(app, "on_exception") {
96 self.fire(app, "on_exception", &args);
97 handled = true;
98 }
99 }
100 }
101 if !handled {
102 match self.exceptions.display.clone() {
103 Some(display) => {
104 let _ = self.guard_call(|ui| display(ui, &exception));
105 }
106 None => crate::stderr_line!("aylis: {text}"),
107 }
108 }
109 self.exceptions.handling = false;
110 }
111
112 fn guard_call<R>(&mut self, f: impl FnOnce(&mut Ui) -> R) -> Option<R> {
114 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))).ok()
115 }
116
117 pub(crate) fn guarded<R>(&mut self, id: ComponentId, event: &str, f: impl FnOnce(&mut Ui) -> R) -> Option<R> {
120 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))) {
121 Ok(r) => Some(r),
122 Err(payload) => {
123 let exception = Exception { message: panic_message(payload.as_ref()), path: self.path_of(id), event: event.to_string() };
124 self.raise_exception(exception);
125 None
126 }
127 }
128 }
129
130 pub fn paint_failed(&self, id: ComponentId) -> bool {
133 self.exceptions.paint_failures.borrow().contains(&id)
134 }
135
136 pub(crate) fn note_paint_failure(&self, id: ComponentId, payload: &(dyn Any + Send)) {
138 if self.exceptions.paint_failures.borrow_mut().insert(id) {
139 let exception = Exception { message: panic_message(payload), path: self.path_of(id), event: "paint".into() };
140 crate::stderr_line!("aylis: {exception}");
141 self.exceptions.paint_reports.borrow_mut().push(exception);
142 }
143 }
144
145 pub(crate) fn flush_paint_failures(&mut self) {
147 let reports = std::mem::take(&mut *self.exceptions.paint_reports.borrow_mut());
148 for exception in reports {
149 let text = exception.to_string();
150 self.report(&crate::activity::Activity::Error { message: &text });
151 }
152 }
153}
154
155#[derive(Default)]
157pub(crate) struct Exceptions {
158 handler: Option<Rc<ExceptionHandlerFn>>,
159 display: Option<Rc<ExceptionDisplayFn>>,
160 handling: bool,
162 paint_failures: std::cell::RefCell<std::collections::HashSet<ComponentId>>,
164 paint_reports: std::cell::RefCell<Vec<Exception>>,
165}
166
167fn json_string(text: &str) -> String {
169 let mut out = String::with_capacity(text.len() + 2);
170 out.push('"');
171 for c in text.chars() {
172 match c {
173 '"' => out.push_str("\\\""),
174 '\\' => out.push_str("\\\\"),
175 '\n' => out.push_str("\\n"),
176 '\r' => out.push_str("\\r"),
177 '\t' => out.push_str("\\t"),
178 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
179 c => out.push(c),
180 }
181 }
182 out.push('"');
183 out
184}