1use std::any::{Any, TypeId};
17use std::collections::HashMap;
18use std::rc::Rc;
19
20use crate::component::ComponentId;
21use crate::event::EventArgs;
22use crate::ui::Ui;
23
24pub type Binder = Rc<dyn Fn(&mut Ui, ComponentId) -> Result<Box<dyn Any>, String>>;
26
27type Deferred = Box<dyn FnOnce(&mut Ui)>;
29
30enum State {
33 Here(Box<dyn Any>),
34 Busy(Vec<Deferred>),
35}
36
37struct Slot {
38 kind: TypeId,
39 class: String,
42 state: State,
43}
44
45#[derive(Default)]
46pub(crate) struct Instances {
47 binders: HashMap<String, Binder>,
48 slots: HashMap<ComponentId, Slot>,
49 components: HashMap<ComponentId, Box<dyn Any>>,
52 renamed: HashMap<ComponentId, String>,
55}
56
57impl Ui {
58 pub fn register_form_class(&mut self, name: &str, bind: impl Fn(&mut Ui, ComponentId) -> Result<Box<dyn Any>, String> + 'static) {
61 self.instances.binders.insert(name.to_ascii_lowercase(), Rc::new(bind));
62 let existing: Vec<ComponentId> =
66 self.components().filter(|&c| self.form_of(c) == c && self.name(c).is_some_and(|n| n.eq_ignore_ascii_case(name)) && !self.instances.slots.contains_key(&c)).collect();
67 for form in existing {
68 if let Err(message) = self.bind_form(form) {
69 self.raise_exception(crate::exception::Exception { message, path: self.path_of(form), event: String::new() });
70 }
71 }
72 }
73
74 pub fn bind_form(&mut self, form: ComponentId) -> Result<(), String> {
78 let Some(class) = self.name(form).map(str::to_string) else { return Ok(()) };
79 let Some(bind) = self.instances.binders.get(&class.to_ascii_lowercase()).cloned() else { return Ok(()) };
80 let instance = bind(self, form)?;
81 let kind = (*instance).type_id();
82 self.instances.slots.insert(form, Slot { kind, class, state: State::Here(instance) });
83 Ok(())
84 }
85
86 pub fn form_class(&self, form: ComponentId) -> Option<&str> {
89 match self.instances.slots.get(&form) {
90 Some(slot) => Some(slot.class.as_str()),
91 None => self.instances.renamed.get(&form).map(String::as_str),
92 }
93 }
94
95 pub(crate) fn remember_form_class(&mut self, form: ComponentId, class: &str) {
98 if !self.instances.slots.contains_key(&form) {
99 self.instances.renamed.insert(form, class.to_string());
100 }
101 }
102
103 pub fn form_instance<T: 'static>(&self, form: ComponentId) -> Option<&T> {
108 match &self.instances.slots.get(&form)?.state {
109 State::Here(b) => b.downcast_ref(),
110 State::Busy(_) => {
111 self.warn_busy_instance(form);
112 None
113 }
114 }
115 }
116
117 pub fn form_instance_mut<T: 'static>(&mut self, form: ComponentId) -> Option<&mut T> {
118 let busy = matches!(self.instances.slots.get(&form)?.state, State::Busy(_));
119 if busy {
120 self.warn_busy_instance(form);
121 return None;
122 }
123 match &mut self.instances.slots.get_mut(&form)?.state {
124 State::Here(b) => b.downcast_mut(),
125 State::Busy(_) => None,
126 }
127 }
128
129 fn warn_busy_instance(&self, form: ComponentId) {
132 if cfg!(debug_assertions) {
133 thread_local! {
134 static WARNED: std::cell::RefCell<std::collections::HashSet<ComponentId>> = Default::default();
135 }
136 if WARNED.with(|w| w.borrow_mut().insert(form)) {
137 let name = self.form_class(form).map(str::to_string).or_else(|| self.name(form).map(str::to_string)).unwrap_or_default();
138 crate::stderr_line!(
139 "aylis: a instância do form {name} está com um handler que roda agora, e o get/get_mut dela dá None. \
140 Dentro de um handler do próprio form, use o self; no código chamado por ele, os componentes pelo components(ui) gerado."
141 );
142 }
143 }
144 }
145
146 pub fn set_form_components(&mut self, form: ComponentId, components: Box<dyn Any>) {
150 self.instances.components.insert(form, components);
151 }
152
153 pub fn form_components<T: Copy + 'static>(&self, form: ComponentId) -> Option<T> {
155 self.instances.components.get(&form)?.downcast_ref().copied()
156 }
157
158 fn instance_of<T: 'static>(&self, id: ComponentId) -> Option<ComponentId> {
161 let kind = TypeId::of::<T>();
162 let mut current = Some(self.form_of(id));
163 while let Some(form) = current {
164 if self.instances.slots.get(&form).is_some_and(|s| s.kind == kind) {
165 return Some(form);
166 }
167 current = self.parent(form).map(|p| self.form_of(p));
168 }
169 None
170 }
171
172 pub fn with_form<T: 'static>(&mut self, sender: ComponentId, f: impl FnOnce(&mut T, &mut Ui) + 'static) -> bool {
175 let Some(form) = self.instance_of::<T>(sender) else { return false };
176 let claims = self.claim_question();
178 let busy = matches!(self.instances.slots.get(&form).map(|s| &s.state), Some(State::Busy(_)));
179 let path = if busy && cfg!(debug_assertions) { self.path_of(sender) } else { String::new() };
180 let slot = self.instances.slots.get_mut(&form).expect("achado acima");
181 let instance = match std::mem::replace(&mut slot.state, State::Busy(Vec::new())) {
182 State::Here(b) => b,
183 State::Busy(mut waiting) => {
184 let automatic = self.running_events.last().is_some_and(|e| crate::question::COALESCED_EVENTS.contains(&e.as_str()));
188 if cfg!(debug_assertions) && !automatic {
189 crate::stderr_line!("aylis: evento de {path} adiado: um handler do mesmo form está rodando");
190 }
191 slot.state = State::Busy(Vec::new());
192 let token = if claims { self.defer_question() } else { 0 };
195 waiting.push(Box::new(move |ui: &mut Ui| {
196 if token == 0 {
197 ui.with_form::<T>(sender, f);
198 } else {
199 ui.answering(token, |ui| {
200 ui.with_form::<T>(sender, f);
201 });
202 }
203 }));
204 if let Some(slot) = self.instances.slots.get_mut(&form) {
205 slot.state = State::Busy(waiting);
206 }
207 return true;
208 }
209 };
210 let mut instance = instance;
211 let panicked = {
216 let (typed, ui) = (instance.downcast_mut::<T>(), &mut *self);
217 std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
218 if let Some(typed) = typed {
219 f(typed, ui);
220 }
221 }))
222 .err()
223 };
224 let waiting = match self.instances.slots.get_mut(&form) {
226 Some(slot) => match std::mem::replace(&mut slot.state, State::Here(instance)) {
227 State::Busy(w) => w,
228 State::Here(_) => Vec::new(),
229 },
230 None => Vec::new(),
231 };
232 for deferred in waiting {
233 deferred(self);
234 }
235 if let Some(payload) = panicked {
236 std::panic::resume_unwind(payload);
237 }
238 true
239 }
240
241 pub(crate) fn forget_instances(&mut self, doomed: &[ComponentId]) {
243 if !self.instances.components.is_empty() {
244 self.instances.components.retain(|form, _| !doomed.contains(form));
245 }
246 if !self.instances.slots.is_empty() {
247 self.instances.slots.retain(|form, _| !doomed.contains(form));
248 }
249 if !self.instances.renamed.is_empty() {
250 self.instances.renamed.retain(|form, _| !doomed.contains(form));
251 }
252 }
253}
254
255pub fn form_handler<T: 'static, M, H: FormMethod<T, M>>(method: H) -> impl Fn(&mut Ui, ComponentId, &EventArgs) + 'static {
262 let method = Rc::new(method);
263 move |ui, sender, args| {
264 let args = args.clone();
265 let method = method.clone();
266 if !ui.with_form::<T>(sender, move |instance, ui| method.call(instance, ui, sender, &args)) && cfg!(debug_assertions) {
267 crate::stderr_line!("aylis: {} não tem a instância do form ({}): o form foi criado sem a classe registrada", ui.path_of(sender), std::any::type_name::<T>());
268 }
269 }
270}
271
272pub trait FormMethod<T, M>: 'static {
275 fn call(&self, instance: &mut T, ui: &mut Ui, sender: ComponentId, args: &EventArgs);
276}
277
278pub struct Untyped;
280
281impl<T, R: HandlerResult, F: Fn(&mut T, &mut Ui, ComponentId, &EventArgs) -> R + 'static> FormMethod<T, Untyped> for F {
282 fn call(&self, instance: &mut T, ui: &mut Ui, sender: ComponentId, args: &EventArgs) {
283 self(instance, ui, sender, args).finish(ui)
284 }
285}
286
287impl<T, S: crate::FromSender, R: HandlerResult, F: Fn(&mut T, &mut Ui, S) -> R + 'static> FormMethod<T, (S,)> for F {
288 fn call(&self, instance: &mut T, ui: &mut Ui, sender: ComponentId, _args: &EventArgs) {
289 let Some(s) = typed_sender::<S>(ui, sender) else { return };
290 self(instance, ui, s).finish(ui)
291 }
292}
293
294impl<T, S: crate::FromSender, A: crate::EventValue, R: HandlerResult, F: Fn(&mut T, &mut Ui, S, A) -> R + 'static> FormMethod<T, (S, A)> for F {
295 fn call(&self, instance: &mut T, ui: &mut Ui, sender: ComponentId, args: &EventArgs) {
296 let Some(s) = typed_sender::<S>(ui, sender) else { return };
297 let Some(value) = A::from_args(args) else {
298 let message = format!("o evento de {} chegou com {args:?}, e o handler espera {}", ui.path_of(sender), std::any::type_name::<A>());
299 if cfg!(debug_assertions) {
300 crate::stderr_line!("aylis: {message}");
301 }
302 ui.report(&crate::activity::Activity::Error { message: &message });
303 return;
304 };
305 self(instance, ui, s, value).finish(ui)
306 }
307}
308
309fn typed_sender<S: crate::FromSender>(ui: &mut Ui, sender: ComponentId) -> Option<S> {
312 let s = S::from_sender(ui, sender);
313 if s.is_none() {
314 let message = format!("{} disparou um handler que espera {}", ui.path_of(sender), std::any::type_name::<S>());
315 if cfg!(debug_assertions) {
316 crate::stderr_line!("aylis: {message}");
317 }
318 ui.report(&crate::activity::Activity::Error { message: &message });
319 }
320 s
321}
322
323pub trait HandlerResult {
327 fn finish(self, ui: &mut Ui);
328}
329
330impl HandlerResult for () {
331 fn finish(self, _ui: &mut Ui) {}
332}
333
334impl HandlerResult for Result<(), String> {
335 fn finish(self, ui: &mut Ui) {
336 if let Err(message) = self {
337 if ui.asking() {
338 ui.refuse(message);
339 } else {
340 ui.raise_exception(crate::Exception { message, path: String::new(), event: String::new() });
342 }
343 }
344 }
345}