1use std::any::Any;
5use std::cell::{Cell, RefCell};
6use std::collections::HashMap;
7use std::fmt::Write as _;
8
9use crate::anim::Running;
10use crate::canvas::{Canvas, TextStyle};
11use crate::component::{ColorOverride, Component, ComponentId, ControlBase};
12use crate::error::{Error, Result};
13use crate::event::{EventArgs, EventCtx};
14use crate::component::ControlState;
15use crate::geometry::{Bounds, RectF, SizeF};
16use crate::input::InputState;
17use crate::paint::{PaintCtx, Visual};
18use crate::platform::Services;
19use crate::prop::{PropInfo, PropKind, PropValue};
20use crate::registry::{ClassInfo, ClassRegistry, create_default};
21use crate::theme::Theme;
22
23const PAINT_ONLY: [&str; 9] = ["opacity", "rotation", "translate_x", "translate_y", "cursor", "hint", "shadow", "hit_test", "cache_layer"];
27
28pub const EVENTS_PER_ROUND: usize = 10_000;
30pub const LOOP_WARNING: usize = 1_000;
32pub const MAX_TREE_DEPTH: usize = 256;
36
37pub const MAX_EVENT_NESTING: usize = 64;
40
41pub const SAFE_TREE_DEPTH: usize = 1024;
43pub const SAFE_EVENT_NESTING: usize = 256;
44
45pub type HandlerFn = dyn Fn(&mut Ui, ComponentId, &EventArgs);
48
49pub type EventSinkFn = dyn Fn(&mut Ui, ComponentId, &str, &str, &EventArgs);
53
54pub type PaintHookFn = dyn Fn(&mut dyn Canvas, &PaintCtx<'_>, &dyn Fn(&mut dyn Canvas, &PaintCtx<'_>));
57
58#[derive(Clone)]
59pub(crate) enum Handler {
60 Closure(std::rc::Rc<HandlerFn>),
61 Named(String),
62}
63
64pub(crate) struct Entry {
65 pub(crate) component: Option<Box<dyn Component>>,
67 pub(crate) name: String,
68 pub(crate) scope: bool,
71 pub(crate) parent: Option<ComponentId>,
72 pub(crate) children: Vec<ComponentId>,
73 pub(crate) events: Vec<(String, Handler)>,
74 pub(crate) paint_hook: Option<Box<PaintHookFn>>,
75 pub(crate) visual: RefCell<Visual>,
77 pub(crate) bindings: Vec<crate::bindings::Binding>,
79}
80
81struct Slot {
82 generation: u32,
83 entry: Option<Entry>,
84}
85
86pub type TraceFn = dyn Fn(&Ui, ComponentId, &str, &str);
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91pub enum ThemeSource {
92 App,
94 Own,
96 Inherited(ComponentId),
98 Class(String),
100}
101
102pub struct DesignChanged;
104
105pub struct Ui {
131 slots: Vec<Slot>,
132 free_slots: Vec<u32>,
133 roots: Vec<ComponentId>,
134 registry: ClassRegistry,
135 handlers: HashMap<String, HashMap<String, std::rc::Rc<HandlerFn>>>,
138 event_sink: Option<std::rc::Rc<EventSinkFn>>,
139 event_depth: usize,
141 quiet_changes: u32,
144 pub(crate) running_events: Vec<String>,
147 trace: Option<std::rc::Rc<TraceFn>>,
149 observers: crate::activity::Observers,
151 pub(crate) binding_sink: Option<crate::bindings::BindingSink>,
153 pub(crate) binding_refresh: Option<crate::bindings::BindingSink>,
154 pub(crate) views: HashMap<ComponentId, crate::views::ViewState>,
156 pending: Vec<(ComponentId, String, EventArgs, Option<(ComponentId, crate::ClickPointer)>)>,
159 pub(crate) click_source: Option<(ComponentId, crate::ClickPointer)>,
162 click_pointer: Option<crate::ClickPointer>,
164 repeat: Option<(ComponentId, String, usize)>,
166 pub(crate) theme: std::sync::Arc<Theme>,
170 themes: Vec<std::sync::Arc<Theme>>,
172 palette: crate::palette::Palette,
174 scroll_options: crate::ScrollOptions,
176 zoom: f32,
178 zoom_changed: bool,
180 zoom_keys: bool,
182 pub(crate) memory_panel: Option<bool>,
184 font_names: Vec<(String, String)>,
187 color_names: HashMap<(ComponentId, String), (String, crate::color::Color)>,
192 icons: HashMap<String, crate::icons::Icon>,
194 pub(crate) input: HashMap<ComponentId, InputState>,
196 pub(crate) drag_request: Option<(String, String)>,
198 pub(crate) drag_visual_request: Option<crate::DragVisual>,
200 pub(crate) native_drag_image: bool,
203 pub(crate) drop_rejected: bool,
205 pub(crate) screen_pointer: Option<crate::input::ScreenPointer>,
208 pub(crate) animations: Vec<Running>,
209 pub(crate) appear_waiting: Option<Vec<ComponentId>>,
211 pub(crate) hover_within_hosts: Option<Vec<ComponentId>>,
213 pub(crate) style_animating: Cell<bool>,
215 pub(crate) recolored: RefCell<HashMap<(String, ColorOverride), std::rc::Rc<Theme>>>,
218 pub(crate) wake_at: Cell<Option<f64>>,
220 pub(crate) frame_requests: std::cell::RefCell<HashMap<ComponentId, (bool, Option<f64>)>>,
223 pub(crate) timed_frames: std::cell::RefCell<HashMap<ComponentId, f64>>,
227 pub(crate) frame_hooks: Vec<ComponentId>,
229 pub(crate) overlays: std::cell::RefCell<Vec<(crate::geometry::PointF, crate::pages::Page)>>,
232 pub(crate) pending_focus: Option<ComponentId>,
234 close_requested: bool,
235 pub(crate) exceptions: crate::exception::Exceptions,
237 pub(crate) limits: (usize, usize),
239 pub(crate) references: RefCell<Option<crate::references::Index>>,
241 pub(crate) interceptors: crate::intercept::Interceptors,
243 pub(crate) names: RefCell<crate::names::NameIndex>,
245 pub(crate) tasks: crate::tasks::Tasks,
247 pub(crate) instances: crate::instances::Instances,
249 pub(crate) open_forms: Vec<crate::forms::OpenForm>,
251 pub(crate) placements: std::collections::HashMap<ComponentId, crate::forms::WindowPlacement>,
253 pub(crate) monitors: Vec<crate::monitors::Monitor>,
255 pub(crate) monitors_version: u64,
256 pub(crate) form_monitors: std::collections::HashMap<ComponentId, usize>,
257 pub(crate) drop_point: Option<crate::geometry::PointF>,
259 pub(crate) window_drag: Option<(ComponentId, Option<ComponentId>, crate::geometry::PointF)>,
262 pub(crate) minimized_forms: std::collections::HashSet<ComponentId>,
264 pub(crate) form_gpus: std::collections::HashMap<ComponentId, String>,
266 pub(crate) form_pieces: std::collections::HashMap<ComponentId, Vec<RectF>>,
268 pub(crate) piece_requests: std::cell::Cell<Option<(bool, Option<f64>)>>,
270 pub(crate) main_form: Option<ComponentId>,
271 pub(crate) questions: crate::question::Questions,
273 pub(crate) busy: crate::busy::Busy,
275 pub(crate) text_mode: crate::textcore::TextMode,
277 extensions: std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any>>,
279 pub(crate) window_commands: Vec<(ComponentId, crate::window::WindowCommand)>,
281 pub(crate) maximize_buttons: HashMap<ComponentId, (ComponentId, crate::geometry::RectF)>,
284 pub(crate) frames: crate::frames::FrameClock,
286 pub(crate) transitions: Vec<crate::transition::Running>,
288 pub(crate) closing_now: Option<ComponentId>,
290 pub(crate) stacked_forms: bool,
293 pub(crate) activate: Option<ComponentId>,
294 pub(crate) pending_closes: Vec<ComponentId>,
297 pub(crate) call_depth: u32,
299 pub(crate) design_mode: bool,
300 hint_delay: Option<f64>,
302 pub(crate) still_picture: bool,
305 design_reveal: Vec<ComponentId>,
308 design_show_hidden: bool,
310 pub(crate) timeouts: Vec<crate::timers::Timeout>,
312 pub(crate) next_timeout: u64,
313 pub(crate) start_hidden: std::collections::HashSet<ComponentId>,
315 pub(crate) rtl: bool,
317 pub(crate) posted: std::sync::Arc<crate::post::PostQueue>,
319 pub(crate) timers: Vec<crate::timers::TimerEntry>,
321 pub(crate) translations: crate::i18n::Translations,
323 services: Services,
324 pub(crate) time: f64,
325 pub(crate) layout_dirty: bool,
326 pub(crate) dirty_forms: std::collections::HashSet<ComponentId>,
328 pub(crate) repaint_requested: bool,
329 pub(crate) damage_epoch: u64,
332 pub(crate) painted_epoch: HashMap<ComponentId, u64>,
333 pub(crate) ink: RefCell<Option<RectF>>,
336 pub(crate) spilled: Cell<bool>,
337 pub(crate) paint_area: Cell<Option<RectF>>,
338 pub(crate) paint_form: Cell<Option<RectF>>,
341 pub(crate) overlay_users: std::cell::RefCell<std::collections::HashSet<ComponentId>>,
344 pub(crate) frame_ids: std::cell::RefCell<Vec<ComponentId>>,
347 pub(crate) placed_ids: std::cell::RefCell<Vec<ComponentId>>,
350 pub(crate) part_ids: std::cell::RefCell<Vec<(ComponentId, RectF)>>,
352 pub(crate) scroll_moves: std::cell::RefCell<Vec<(ComponentId, RectF, crate::PointF)>>,
354 pub(crate) layer_epoch: std::cell::Cell<u64>,
357 pub(crate) overscroll_style: crate::overscroll::Overscroll,
359 pub(crate) pulls: std::cell::RefCell<crate::overscroll::Pulls>,
361 pub(crate) system_bars: Option<crate::system_bars::SystemBarsStyle>,
363 pub(crate) system_bars_version: u64,
364 pub(crate) paints_status_strip: bool,
365 pub(crate) dead_layers: std::cell::RefCell<Vec<u64>>,
368 pub(crate) auto_layers: std::cell::Cell<bool>,
371 pub(crate) movers: std::cell::RefCell<Vec<(ComponentId, ComponentId)>>,
374 pub(crate) reveal_ids: std::cell::RefCell<std::collections::HashMap<ComponentId, f32>>,
377 pub(crate) backdrop_next: std::cell::Cell<bool>,
379 pub(crate) backdrops: std::cell::RefCell<std::collections::HashMap<ComponentId, crate::paint::Backdrop>>,
381 pub(crate) paint_count: std::cell::Cell<usize>,
384}
385
386impl Default for Ui {
387 fn default() -> Self {
388 Self::new()
389 }
390}
391
392fn shared_theme(dark: bool) -> std::sync::Arc<Theme> {
394 static LIGHT: std::sync::OnceLock<std::sync::Arc<Theme>> = std::sync::OnceLock::new();
395 static DARK: std::sync::OnceLock<std::sync::Arc<Theme>> = std::sync::OnceLock::new();
396 let cell = if dark { &DARK } else { &LIGHT };
397 cell.get_or_init(|| std::sync::Arc::new(if dark { Theme::dark() } else { Theme::light() })).clone()
398}
399
400impl Ui {
401 pub fn new() -> Self {
402 Self {
403 slots: Vec::new(),
404 free_slots: Vec::new(),
405 roots: Vec::new(),
406 registry: ClassRegistry::default(),
407 handlers: HashMap::new(),
408 event_sink: None,
409 event_depth: 0,
410 quiet_changes: 0,
411 running_events: Vec::new(),
412 trace: None,
413 observers: Default::default(),
414 binding_sink: None,
415 binding_refresh: None,
416 views: HashMap::new(),
417 pending: Vec::new(),
418 click_source: None,
419 click_pointer: None,
420 repeat: None,
421 theme: shared_theme(false),
422 themes: vec![shared_theme(false), shared_theme(true)],
423 palette: Vec::new(),
424 scroll_options: crate::ScrollOptions::default(),
425 zoom: 1.0,
426 zoom_changed: false,
427 zoom_keys: false,
428 memory_panel: None,
429 font_names: Vec::new(),
430 color_names: HashMap::new(),
431 icons: HashMap::new(),
432 input: HashMap::new(),
433 drag_request: None,
434 drag_visual_request: None,
435 native_drag_image: false,
436 drop_rejected: false,
437 screen_pointer: None,
438 animations: Vec::new(),
439 appear_waiting: None,
440 hover_within_hosts: None,
441 style_animating: Cell::new(false),
442 recolored: RefCell::new(HashMap::new()),
443 wake_at: Cell::new(None),
444 frame_requests: Default::default(),
445 timed_frames: Default::default(),
446 frame_hooks: Vec::new(),
447 overlays: Default::default(),
448 pending_focus: None,
449 close_requested: false,
450 exceptions: Default::default(),
451 limits: (MAX_TREE_DEPTH, MAX_EVENT_NESTING),
452 references: RefCell::new(None),
453 interceptors: Default::default(),
454 names: RefCell::default(),
455 tasks: Default::default(),
456 instances: Default::default(),
457 open_forms: Vec::new(),
458 placements: std::collections::HashMap::new(),
459 monitors: Vec::new(),
460 monitors_version: 0,
461 form_monitors: std::collections::HashMap::new(),
462 minimized_forms: std::collections::HashSet::new(),
463 drop_point: None,
464 window_drag: None,
465 form_gpus: std::collections::HashMap::new(),
466 form_pieces: std::collections::HashMap::new(),
467 piece_requests: std::cell::Cell::new(None),
468 main_form: None,
469 questions: Default::default(),
470 busy: Default::default(),
471 text_mode: Default::default(),
472 extensions: Default::default(),
473 frames: Default::default(),
474 window_commands: Vec::new(),
475 maximize_buttons: HashMap::new(),
476 transitions: Vec::new(),
477 closing_now: None,
478 stacked_forms: false,
479 activate: None,
480 pending_closes: Vec::new(),
481 call_depth: 0,
482 design_mode: false,
483 hint_delay: None,
484 still_picture: false,
485 design_reveal: Vec::new(),
486 design_show_hidden: false,
487 timeouts: Vec::new(),
488 next_timeout: 0,
489 start_hidden: Default::default(),
490 rtl: false,
491 posted: Default::default(),
492 timers: Vec::new(),
493 translations: Default::default(),
494 services: Services::default(),
495 time: 0.0,
496 layout_dirty: false,
497 dirty_forms: Default::default(),
498 repaint_requested: false,
499 damage_epoch: 0,
500 painted_epoch: HashMap::new(),
501 ink: Default::default(),
502 spilled: Default::default(),
503 paint_area: Default::default(),
504 paint_form: Default::default(),
505 overlay_users: Default::default(),
506 frame_ids: Default::default(),
507 placed_ids: Default::default(),
508 part_ids: Default::default(),
509 scroll_moves: Default::default(),
510 layer_epoch: Default::default(),
511 overscroll_style: crate::overscroll::Overscroll::None,
512 pulls: Default::default(),
513 system_bars: None,
514 system_bars_version: 0,
515 paints_status_strip: false,
516 dead_layers: Default::default(),
517 auto_layers: std::cell::Cell::new(true),
518 movers: Default::default(),
519 reveal_ids: Default::default(),
520 backdrop_next: Default::default(),
521 backdrops: Default::default(),
522 paint_count: Default::default(),
523 }
524 }
525
526 pub(crate) fn entry(&self, id: ComponentId) -> Option<&Entry> {
531 let slot = self.slots.get(id.index as usize)?;
532 if slot.generation != id.generation {
533 return None;
534 }
535 slot.entry.as_ref()
536 }
537
538 pub(crate) fn entry_mut(&mut self, id: ComponentId) -> Option<&mut Entry> {
539 let slot = self.slots.get_mut(id.index as usize)?;
540 if slot.generation != id.generation {
541 return None;
542 }
543 slot.entry.as_mut()
544 }
545
546 fn alloc(&mut self, entry: Entry) -> ComponentId {
547 self.appear_waiting = None;
549 self.hover_within_hosts = None;
550 if let Some(index) = self.free_slots.pop() {
551 let slot = &mut self.slots[index as usize];
552 slot.entry = Some(entry);
553 ComponentId { index, generation: slot.generation }
554 } else {
555 self.slots.push(Slot { generation: 0, entry: Some(entry) });
556 ComponentId { index: (self.slots.len() - 1) as u32, generation: 0 }
557 }
558 }
559
560 pub(crate) fn cb(&self, id: ComponentId) -> Option<&ControlBase> {
562 self.entry(id)?.component.as_deref()?.control()
563 }
564
565 pub(crate) fn cb_mut(&mut self, id: ComponentId) -> Option<&mut ControlBase> {
566 self.entry_mut(id)?.component.as_deref_mut()?.control_mut()
567 }
568
569 #[track_caller]
572 pub fn invalidate(&mut self) {
573 self.layout_dirty = true;
574 self.request_repaint();
575 }
576
577 pub fn invalidate_form(&mut self, id: ComponentId) {
581 let root = self.root_of(id);
582 self.dirty_forms.insert(root);
583 self.damage(id);
584 }
585
586 #[track_caller]
589 pub fn request_repaint(&mut self) {
590 self.repaint_requested = true;
591 self.damage_epoch += 1;
592 }
593
594 pub fn needs_layout(&self) -> bool {
596 self.layout_dirty || !self.dirty_forms.is_empty()
597 }
598
599 pub fn needs_repaint(&self) -> bool {
601 self.repaint_requested || self.needs_layout() || self.is_animating()
602 }
603
604 pub fn add<T: Component>(&mut self, component: T, parent: ComponentId) -> ComponentId {
613 self.add_boxed(Box::new(component), Some(parent))
614 .expect("aylis: Ui::add com pai inexistente ou árvore funda demais")
615 }
616
617 pub fn add_root<T: Component>(&mut self, component: T) -> ComponentId {
619 self.add_boxed(Box::new(component), None).expect("sem pai não há como falhar")
620 }
621
622 pub fn add_boxed(
623 &mut self,
624 component: Box<dyn Component>,
625 parent: Option<ComponentId>,
626 ) -> Result<ComponentId> {
627 if let Some(p) = parent {
628 if !self.contains(p) {
629 return Err(Error::InvalidId);
630 }
631 if self.depth_of(p) + 1 > self.limits.0 {
632 return Err(too_deep(self.limits.0));
633 }
634 }
635 let id = self.alloc(Entry {
636 component: Some(component),
637 name: String::new(),
638 scope: parent.is_none(),
639 parent,
640 children: Vec::new(),
641 events: Vec::new(),
642 paint_hook: None,
643 visual: RefCell::default(),
644 bindings: Vec::new(),
645 });
646 match parent {
647 Some(p) => self.entry_mut(p).expect("verificado acima").children.push(id),
648 None => self.roots.push(id),
649 }
650 self.invalidate_form(id);
651 self.forget_references();
652 self.sync_timer(id);
653 if self.class_name(id) == Some(crate::intercept::INTERCEPTOR_CLASS) {
655 self.interceptors.forget();
656 }
657 Ok(id)
658 }
659
660 pub fn create(&mut self, class: &str, parent: Option<ComponentId>) -> Result<ComponentId> {
665 let (base, variant) = crate::registry::split_variant(class);
666 let create = self
667 .registry
668 .get(base)
669 .ok_or_else(|| Error::UnknownClass(base.to_string()))?
670 .create;
671 let id = self.add_boxed(create(), parent)?;
672 if let Some(variant) = variant {
673 self.apply_variant(id, base, variant)?;
674 }
675 Ok(id)
676 }
677
678 pub fn apply_variant(&mut self, id: ComponentId, class: &str, variant: &str) -> Result<()> {
681 if let Some(info) = self.registry.variant(class, variant).cloned() {
682 for (name, value) in info.props {
683 self.set_prop_quiet(id, &name, value)?;
684 }
685 } else if self.theme.style(&format!("{class}.{variant}")).is_none() {
686 return Err(Error::UnknownClass(format!("{class}.{variant}")));
687 }
688 if let Some(cb) = self.control_mut(id) {
689 cb.set_style(variant);
690 }
691 Ok(())
692 }
693
694 pub fn register_variant(&mut self, class: &str, name: &str, caption: &str, props: Vec<(&str, PropValue)>) {
696 self.registry.register_variant(crate::registry::VariantInfo {
697 class: class.to_string(),
698 name: name.to_string(),
699 caption: caption.to_string(),
700 props: props.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
701 });
702 }
703
704 pub fn variants_of(&self, class: &str) -> Vec<crate::registry::VariantInfo> {
707 let mut out: Vec<crate::registry::VariantInfo> = self.registry.variants_of(class).cloned().collect();
708 for name in self.theme.variants_of(class) {
709 if !out.iter().any(|v| v.name.eq_ignore_ascii_case(&name)) {
710 out.push(crate::registry::VariantInfo { class: class.to_string(), caption: name.clone(), name, props: Vec::new() });
711 }
712 }
713 out
714 }
715
716 pub fn free(&mut self, id: ComponentId) -> bool {
721 self.free_many(&[id]) > 0
722 }
723
724 pub fn free_many(&mut self, ids: &[ComponentId]) -> usize {
730 let mut doomed = Vec::new();
731 let mut doomed_set = std::collections::HashSet::new();
732 let mut tops = Vec::new();
733 for &id in ids {
734 if self.contains(id) && !doomed_set.contains(&id) {
735 let start = doomed.len();
736 self.collect_subtree(id, &mut doomed);
737 doomed_set.extend(doomed[start..].iter().copied());
738 tops.push(id);
739 }
740 }
741 if tops.is_empty() {
742 return 0;
743 }
744 let gone = |c: &ComponentId| doomed_set.contains(c);
745 let freed_forms: Vec<ComponentId> = doomed.iter().copied().filter(|&d| self.class_name(d) == Some("Form")).collect();
747 let orphaned: Vec<(ComponentId, &'static str)> = self.referrers_of_all(&doomed).into_iter().filter(|(c, _)| !gone(c)).collect();
750 let named = doomed.iter().any(|&d| self.name(d).is_some_and(|n| !n.is_empty()));
753 let leaving: Vec<(Option<ComponentId>, Vec<(ComponentId, String)>)> = if named { tops.iter().map(|&t| (self.name_scope_of(t), self.names_with(t))).collect() } else { Vec::new() };
755 for &id in &tops {
756 self.detach(id);
757 }
758 for &d in &doomed {
759 let slot = &mut self.slots[d.index as usize];
760 if let Some(key) = slot.entry.as_ref().and_then(|e| e.visual.borrow_mut().layer_key.take()) {
762 self.dead_layers.get_mut().push(key);
763 }
764 slot.entry = None;
765 slot.generation = slot.generation.wrapping_add(1);
766 self.free_slots.push(d.index);
767 }
768 self.pending.retain(|(sender, _, _, _)| !gone(sender));
769 self.color_names.retain(|(c, _), _| !gone(c));
770 self.drop_tasks_of(&doomed);
771 self.forget_instances(&doomed);
772 self.forget_questions(&doomed);
773 self.animations.retain(|a| !gone(&a.target) && a.owner.is_none_or(|o| !gone(&o)));
774 self.input.retain(|root, _| !gone(root));
775 self.forget_forms(&doomed);
776 self.appear_waiting = None;
777 self.hover_within_hosts = None;
778 for t in self.timers.extract_if(.., |t| gone(&t.id)).collect::<Vec<_>>() {
779 t.stop();
780 }
781 for state in self.input.values_mut() {
782 state.forget(&doomed);
783 }
784 for slot in &mut self.slots {
785 if let Some(c) = slot.entry.as_mut().and_then(|e| e.component.as_mut()) {
786 for &d in &doomed {
787 c.notification(d);
788 }
789 if let Some(cb) = c.control_mut() {
790 if cb.popup_menu.is_some_and(|m| gone(&m)) {
791 cb.popup_menu = None;
792 }
793 cb.forget_drag_image(&doomed);
794 }
795 }
796 }
797 self.prune_references(&doomed_set);
800 for (scope, items) in leaving {
801 self.names_removed(scope, &items);
802 }
803 self.forget_scopes(&doomed);
804 for (c, prop) in orphaned {
805 if matches!(self.get_prop(c, prop), Ok(PropValue::Component(Some(t))) if gone(&t) || !self.contains(t)) {
806 let _ = self.set_prop(c, prop, PropValue::Component(None));
807 }
808 }
809 let dependents: Vec<ComponentId> = self
811 .components()
812 .filter(|&c| self.component(c).and_then(|c| c.popup()).and_then(|p| p.dies_with()).is_some_and(|o| gone(&o)))
813 .collect();
814 self.free_many(&dependents);
815 if !freed_forms.is_empty() {
816 if let Some(hook) = self.busy.freed_hook.clone() {
817 hook(self, &freed_forms);
818 }
819 }
820 self.invalidate();
821 tops.len()
822 }
823
824 fn collect_subtree(&self, id: ComponentId, out: &mut Vec<ComponentId>) {
825 out.push(id);
826 if let Some(e) = self.entry(id) {
827 for &c in &e.children {
828 self.collect_subtree(c, out);
829 }
830 }
831 }
832
833 fn detach(&mut self, id: ComponentId) {
835 match self.entry(id).and_then(|e| e.parent) {
836 Some(p) => {
837 if let Some(e) = self.entry_mut(p) {
838 e.children.retain(|c| *c != id);
839 }
840 }
841 None => self.roots.retain(|r| *r != id),
842 }
843 }
844
845 pub fn contains(&self, id: ComponentId) -> bool {
850 self.entry(id).is_some()
851 }
852
853 pub fn parent(&self, id: ComponentId) -> Option<ComponentId> {
854 self.entry(id)?.parent
855 }
856
857 pub fn children(&self, id: ComponentId) -> &[ComponentId] {
859 self.entry(id).map_or(&[], |e| e.children.as_slice())
860 }
861
862 pub fn roots(&self) -> &[ComponentId] {
863 &self.roots
864 }
865
866 pub fn root_of(&self, id: ComponentId) -> ComponentId {
868 let mut current = id;
869 while let Some(p) = self.parent(current) {
870 current = p;
871 }
872 current
873 }
874
875 fn depth_of(&self, id: ComponentId) -> usize {
878 let mut depth = 1;
879 let mut current = self.parent(id);
880 while let Some(c) = current {
881 depth += 1;
882 current = self.parent(c);
883 }
884 depth
885 }
886
887 fn height_of(&self, id: ComponentId) -> usize {
889 let mut height = 0;
890 let mut stack = vec![(id, 1)];
891 while let Some((node, level)) = stack.pop() {
892 height = height.max(level);
893 stack.extend(self.children(node).iter().map(|&c| (c, level + 1)));
894 }
895 height
896 }
897
898 pub fn set_parent(&mut self, id: ComponentId, parent: Option<ComponentId>) -> Result<()> {
899 if !self.contains(id) {
900 return Err(Error::InvalidId);
901 }
902 let old_root = self.root_of(id);
903 let old_scope = self.name_scope_of(id);
904 let was_scope = self.is_name_scope(id);
905 let moving = self.names_with(id);
906 if let Some(p) = parent {
907 if !self.contains(p) {
908 return Err(Error::InvalidId);
909 }
910 let mut current = Some(p);
911 while let Some(c) = current {
912 if c == id {
913 return Err(Error::Cycle);
914 }
915 current = self.parent(c);
916 }
917 if self.depth_of(p) + self.height_of(id) > self.limits.0 {
918 return Err(too_deep(self.limits.0));
919 }
920 let new_scope = self.form_of(p);
923 if self.name_scope_of(id) != Some(new_scope) {
924 let mut moving = Vec::new();
925 self.collect_scope(id, &mut moving);
926 for &n in &moving {
927 let name = &self.entry(n).expect("subárvore válida").name;
928 if self.find_in(new_scope, name).is_some_and(|other| other != n) {
929 return Err(Error::DuplicateName(name.clone()));
930 }
931 }
932 }
933 }
934 self.detach(id);
935 let entry = self.entry_mut(id).expect("verificado acima");
936 entry.parent = parent;
937 entry.scope |= parent.is_none();
939 match parent {
940 Some(p) => self.entry_mut(p).expect("verificado acima").children.push(id),
941 None => self.roots.push(id),
942 }
943 if let Some(cb) = self.cb_mut(id) {
944 cb.anchor_ref = None;
945 }
946 self.invalidate_form(old_root);
948 self.invalidate_form(id);
949 let new_scope = self.name_scope_of(id);
952 if was_scope || parent.is_some() {
953 if old_scope != new_scope {
954 self.names_removed(old_scope, &moving);
955 self.names_added(new_scope, &moving);
956 }
957 } else {
958 self.forget_scope(old_scope);
960 self.forget_scopes(&[id]);
961 }
962 Ok(())
963 }
964
965 pub fn set_child_index(&mut self, id: ComponentId, index: usize) -> Result<()> {
967 let parent = self.entry(id).ok_or(Error::InvalidId)?.parent;
968 let list = match parent {
969 Some(p) => &mut self.entry_mut(p).expect("pai válido").children,
970 None => &mut self.roots,
971 };
972 list.retain(|c| *c != id);
973 list.insert(index.min(list.len()), id);
974 self.invalidate_form(id);
975 self.names_removed(None, &[]);
977 Ok(())
978 }
979
980 pub fn name(&self, id: ComponentId) -> Option<&str> {
985 self.entry(id).map(|e| e.name.as_str())
986 }
987
988 pub fn set_name(&mut self, id: ComponentId, name: &str) -> Result<()> {
994 if !self.contains(id) {
995 return Err(Error::InvalidId);
996 }
997 if !name.is_empty() {
998 if !is_identifier(name) {
999 return Err(Error::InvalidName(name.to_string()));
1000 }
1001 let other = self.name_scope_of(id).and_then(|scope| self.find_in(scope, name));
1004 if other.is_some_and(|o| o != id) {
1005 return Err(Error::DuplicateName(name.to_string()));
1006 }
1007 }
1008 let old = std::mem::replace(&mut self.entry_mut(id).expect("verificado acima").name, name.to_string());
1009 let scope = self.name_scope_of(id);
1010 self.names_removed(scope, &[(id, old)]);
1011 self.names_added(scope, &[(id, name.to_string())]);
1012 Ok(())
1013 }
1014
1015 pub fn free_name_in(&self, parent: ComponentId, base: &str) -> String {
1019 let scope = self.form_of(parent);
1020 if self.find_in(scope, base).is_none() {
1021 return base.to_string();
1022 }
1023 let first = self.next_suffix(scope, base);
1025 let n = (first..).find(|n| self.find_in(scope, &format!("{base}{n}")).is_none()).expect("sempre há um número livre");
1026 self.set_next_suffix(scope, base, n + 1);
1027 format!("{base}{n}")
1028 }
1029
1030 pub fn find(&self, name: &str) -> Option<ComponentId> {
1034 if name.is_empty() {
1035 return None;
1036 }
1037 self.indexed_find(name)
1038 }
1039
1040 pub(crate) fn find_deep(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1041 let e = self.entry(id)?;
1042 if e.name.eq_ignore_ascii_case(name) {
1043 return Some(id);
1044 }
1045 e.children.iter().find_map(|&c| self.find_deep(c, name))
1046 }
1047
1048 pub fn find_in(&self, scope: ComponentId, name: &str) -> Option<ComponentId> {
1052 let e = self.entry(scope)?;
1053 if !name.is_empty() && e.name.eq_ignore_ascii_case(name) {
1054 return Some(scope);
1055 }
1056 self.find_below(scope, name)
1057 }
1058
1059 fn find_below(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1062 if name.is_empty() {
1063 return None;
1064 }
1065 if self.is_name_scope(id) { self.indexed_find_in_scope(id, name) } else { self.find_in_children(id, name) }
1066 }
1067
1068 pub(crate) fn find_in_children(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1069 self.children(id).iter().find_map(|&c| {
1070 let e = self.entry(c)?;
1071 if !name.is_empty() && e.name.eq_ignore_ascii_case(name) {
1072 Some(c)
1073 } else if e.scope {
1074 None
1075 } else {
1076 self.find_in_children(c, name)
1077 }
1078 })
1079 }
1080
1081 pub fn find_path(&self, path: &str) -> Option<ComponentId> {
1085 let mut parts = path.split('.');
1086 let first = parts.next()?;
1087 let mut current = self
1088 .roots
1089 .iter()
1090 .copied()
1091 .find(|&r| self.entry(r).is_some_and(|e| e.name.eq_ignore_ascii_case(first)))
1092 .or_else(|| self.find(first))?;
1093 for part in parts {
1094 current = self.find_below(current, part)?;
1095 }
1096 Some(current)
1097 }
1098
1099 pub fn path_of(&self, id: ComponentId) -> String {
1101 let mut parts = vec![self.name(id).unwrap_or_default().to_string()];
1102 let mut scope = self.name_scope_of(id);
1103 while let Some(s) = scope {
1104 parts.push(self.name(s).unwrap_or_default().to_string());
1105 scope = self.name_scope_of(s);
1106 }
1107 parts.reverse();
1108 parts.join(".")
1109 }
1110
1111 pub fn resolve_reference(&self, from: ComponentId, text: &str) -> Option<ComponentId> {
1116 if text.contains('.') {
1117 return self.find_path(text);
1118 }
1119 let mut scope = Some(self.form_of(from));
1120 while let Some(s) = scope {
1121 if let Some(found) = self.find_in(s, text) {
1122 return Some(found);
1123 }
1124 scope = self.name_scope_of(s);
1125 }
1126 None
1127 }
1128
1129 pub fn reference_name(&self, from: ComponentId, target: ComponentId) -> Option<String> {
1133 let name = self.name(target).filter(|n| !n.is_empty())?;
1134 if self.resolve_reference(from, name) == Some(target) {
1135 Some(name.to_string())
1136 } else {
1137 Some(self.path_of(target))
1138 }
1139 }
1140
1141 pub fn form_of(&self, id: ComponentId) -> ComponentId {
1144 let mut current = id;
1145 loop {
1146 match self.entry(current) {
1147 Some(e) if !e.scope => match e.parent {
1148 Some(p) => current = p,
1149 None => return current,
1150 },
1151 _ => return current,
1152 }
1153 }
1154 }
1155
1156 pub fn name_scope_of(&self, id: ComponentId) -> Option<ComponentId> {
1158 self.parent(id).map(|p| self.form_of(p))
1159 }
1160
1161 pub fn set_name_scope(&mut self, id: ComponentId, scope: bool) {
1164 if let Some(e) = self.entry_mut(id) {
1165 e.scope = scope || e.parent.is_none();
1166 }
1167 self.forget_scope(self.name_scope_of(id));
1168 self.forget_scopes(&[id]);
1169 }
1170
1171 pub fn is_name_scope(&self, id: ComponentId) -> bool {
1172 self.entry(id).is_some_and(|e| e.scope)
1173 }
1174
1175 pub(crate) fn collect_scope(&self, id: ComponentId, out: &mut Vec<ComponentId>) {
1178 out.push(id);
1179 if self.entry(id).is_some_and(|e| e.scope) {
1180 return;
1181 }
1182 for &c in self.children(id) {
1183 self.collect_scope(c, out);
1184 }
1185 }
1186
1187 pub fn class_name(&self, id: ComponentId) -> Option<&'static str> {
1192 Some(self.component(id)?.class_name())
1193 }
1194
1195 pub fn component(&self, id: ComponentId) -> Option<&dyn Component> {
1196 self.entry(id)?.component.as_deref()
1197 }
1198
1199 pub fn component_mut(&mut self, id: ComponentId) -> Option<&mut dyn Component> {
1200 self.invalidate_form(id);
1202 self.request_repaint();
1203 self.forget_references();
1204 self.entry_mut(id)?.component.as_deref_mut()
1205 }
1206
1207 pub fn get<T: Component>(&self, id: ComponentId) -> Option<&T> {
1210 find_layer(self.component(id)?)
1211 }
1212
1213 pub fn get_mut<T: Component>(&mut self, id: ComponentId) -> Option<&mut T> {
1214 self.invalidate_form(id);
1215 self.request_repaint();
1216 self.forget_references();
1217 find_layer_mut(self.entry_mut(id)?.component.as_deref_mut()?)
1218 }
1219
1220 pub fn control(&self, id: ComponentId) -> Option<&ControlBase> {
1222 self.cb(id)
1223 }
1224
1225 pub fn control_mut(&mut self, id: ComponentId) -> Option<&mut ControlBase> {
1226 self.invalidate_form(id);
1227 self.cb_mut(id)
1228 }
1229
1230 pub fn bounds(&mut self, id: ComponentId) -> Option<RectF> {
1235 self.update_layout();
1236 self.laid_out_bounds(id)
1237 }
1238
1239 pub fn laid_out_bounds(&self, id: ComponentId) -> Option<RectF> {
1241 Some(self.cb(id)?.bounds)
1242 }
1243
1244 pub fn set_safe_area(&mut self, root: ComponentId, insets: Bounds) {
1252 let Some(cb) = self.cb_mut(root) else { return };
1253 if cb.safe_area != insets {
1254 cb.safe_area = insets;
1255 self.invalidate_form(root);
1256 }
1257 }
1258
1259 pub fn safe_area(&self, root: ComponentId) -> Bounds {
1260 self.cb(root).map_or_else(Bounds::default, |cb| cb.safe_area)
1261 }
1262
1263 pub fn to_form(&self, id: ComponentId, rect_in_parent: RectF) -> RectF {
1264 let Some(parent) = self.parent(id) else { return rect_in_parent };
1265 let origin = self.absolute_rect(parent).map_or(crate::geometry::PointF::ZERO, |r| r.origin());
1266 let k = self.inner_scale(parent);
1268 if k == 1.0 {
1269 rect_in_parent.offset(origin.x, origin.y)
1270 } else {
1271 RectF::new(origin.x + rect_in_parent.x * k, origin.y + rect_in_parent.y * k, rect_in_parent.width * k, rect_in_parent.height * k)
1272 }
1273 }
1274
1275 pub fn inner_scale(&self, id: ComponentId) -> f32 {
1278 let mut k = 1.0;
1279 let mut current = Some(id);
1280 while let Some(c) = current {
1281 if let Some(cb) = self.cb(c) {
1282 k *= cb.scale();
1283 }
1284 current = self.parent(c);
1285 }
1286 k
1287 }
1288
1289 pub fn native_views(&self, form: ComponentId) -> Vec<crate::NativeViewSlot> {
1293 let mut out = Vec::new();
1294 if self.design_mode() {
1295 return out;
1296 }
1297 let mut stack = vec![(form, true)];
1298 while let Some((id, shown)) = stack.pop() {
1299 let shown = shown && self.control(id).is_none_or(|c| c.visible());
1300 if let Some(view) = self.component(id).and_then(|c| c.platform_hooks()).and_then(|h| h.native_view()) {
1301 let rect = self.absolute_rect(id).unwrap_or_default();
1305 let mut clip: Option<RectF> = None;
1308 let mut parent = self.parent(id);
1309 while let Some(p) = parent {
1310 if self.control(p).is_some_and(|cb| cb.clip_children()) {
1311 let r = self.absolute_rect(p).unwrap_or_default();
1312 clip = Some(clip.map_or(r, |c| c.intersect(r).unwrap_or(RectF::new(r.x, r.y, 0.0, 0.0))));
1313 }
1314 parent = self.parent(p);
1315 }
1316 let clip = clip.filter(|c| !(c.x <= rect.x && c.y <= rect.y && c.right() >= rect.right() && c.bottom() >= rect.bottom()));
1317 let visible = shown && rect.width > 0.0 && rect.height > 0.0 && clip.is_none_or(|c| c.intersect(rect).is_some_and(|i| i.width > 0.0 && i.height > 0.0));
1318 let commands = self.component(id).and_then(|c| c.platform_hooks()).map(|h| h.take_native_commands()).unwrap_or_default();
1319 out.push(crate::NativeViewSlot { id, rect, clip, visible, view, commands });
1320 }
1321 for c in self.children(id) {
1322 stack.push((*c, shown));
1323 }
1324 }
1325 out
1326 }
1327
1328 pub fn absolute_rect(&self, id: ComponentId) -> Option<RectF> {
1331 let mut rect = self.laid_out_bounds(id)?;
1332 let mut parent = self.parent(id);
1333 while let Some(p) = parent {
1334 if let Some(cb) = self.cb(p) {
1335 let (b, s) = (cb.bounds, cb.scale());
1336 rect = if s == 1.0 { rect.offset(b.x, b.y) } else { RectF::new(b.x + rect.x * s, b.y + rect.y * s, rect.width * s, rect.height * s) };
1337 }
1338 parent = self.parent(p);
1339 }
1340 Some(rect)
1341 }
1342
1343 pub fn register_class<T: Component + Default>(&mut self, category: &'static str) {
1349 let name = T::default().class_name();
1350 self.registry.register(ClassInfo { name, category, create: create_default::<T> });
1351 }
1352
1353 pub fn registry(&self) -> &ClassRegistry {
1354 &self.registry
1355 }
1356
1357 pub fn registry_mut(&mut self) -> &mut ClassRegistry {
1358 &mut self.registry
1359 }
1360
1361 pub fn theme(&self) -> &Theme {
1362 &self.theme
1363 }
1364
1365 pub fn theme_mut(&mut self) -> &mut Theme {
1366 self.request_repaint();
1367 self.recolored.borrow_mut().clear();
1368 std::sync::Arc::make_mut(&mut self.theme)
1369 }
1370
1371 pub fn set_theme(&mut self, theme: Theme) {
1373 self.set_shared_theme(std::sync::Arc::new(theme));
1374 }
1375
1376 pub fn set_shared_theme(&mut self, mut theme: std::sync::Arc<Theme>) {
1380 if !self.palette.is_empty() {
1381 std::sync::Arc::make_mut(&mut theme).apply_palette(&self.palette);
1382 }
1383 self.theme = theme;
1384 self.recolored.borrow_mut().clear();
1385 self.refresh_color_names();
1386 self.request_repaint();
1387 }
1388
1389 pub fn set_palette(&mut self, palette: crate::palette::Palette) {
1392 self.palette = palette;
1393 if !self.palette.is_empty() {
1395 std::sync::Arc::make_mut(&mut self.theme).apply_palette(&self.palette);
1396 for t in &mut self.themes {
1397 std::sync::Arc::make_mut(t).apply_palette(&self.palette);
1398 }
1399 }
1400 self.recolored.borrow_mut().clear();
1401 self.refresh_color_names();
1402 self.request_repaint();
1403 }
1404
1405 pub fn palette(&self) -> &crate::palette::Palette {
1406 &self.palette
1407 }
1408
1409 pub fn scroll_options(&self) -> crate::ScrollOptions {
1412 self.scroll_options
1413 }
1414
1415 pub fn set_scroll_options(&mut self, options: crate::ScrollOptions) {
1416 self.scroll_options = options;
1417 }
1418
1419 pub fn color_names(&self) -> Vec<String> {
1421 let mut names: Vec<String> = self.theme.colors.keys().cloned().collect();
1422 names.sort();
1423 names
1424 }
1425
1426 pub fn color_name(&self, id: ComponentId, prop: &str) -> Option<&str> {
1428 let (name, given) = self.color_names.get(&(id, prop.to_string()))?;
1429 let now = self.component(id).and_then(|c| crate::component::read_prop(c, prop));
1431 match now {
1432 Some(v) if v != PropValue::Color(*given) => None,
1433 _ => Some(name.as_str()),
1434 }
1435 }
1436
1437 pub fn refresh_color_names(&mut self) {
1439 let names: Vec<(ComponentId, String)> = self.color_names.keys().cloned().collect();
1440 for (id, prop) in names {
1441 let Some(spec) = self.color_name(id, &prop).filter(|_| self.contains(id)).map(str::to_string) else {
1443 self.color_names.remove(&(id, prop));
1444 continue;
1445 };
1446 let _ = self.set_prop_quiet(id, &prop, PropValue::String(spec));
1447 }
1448 }
1449
1450 pub fn register_theme(&mut self, mut theme: Theme) {
1454 theme.apply_palette(&self.palette);
1455 self.recolored.borrow_mut().clear();
1456 match self.themes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&theme.name)) {
1457 Some(t) => *t = std::sync::Arc::new(theme),
1458 None => self.themes.push(std::sync::Arc::new(theme)),
1459 }
1460 self.request_repaint();
1461 }
1462
1463 pub fn background_color(&self, id: ComponentId) -> crate::Color {
1467 let Some(component) = self.component(id) else { return crate::Color::TRANSPARENT };
1468 let Some(cb) = component.control() else { return crate::Color::TRANSPARENT };
1469 let mut classes = Vec::new();
1470 component.class_chain(&mut classes);
1471 let base = match cb.theme_name() {
1472 "" => self.theme(),
1473 name => self.theme_named(name).unwrap_or(self.theme()),
1474 };
1475 let theme = self.mixed_theme(base, &classes);
1476 theme.resolve(&classes, cb.style(), cb.state()).fill
1477 }
1478
1479 pub fn theme_named(&self, name: &str) -> Option<&Theme> {
1483 if self.theme.name.eq_ignore_ascii_case(name) {
1484 return Some(&self.theme);
1485 }
1486 self.themes
1487 .iter()
1488 .find(|t| t.name.eq_ignore_ascii_case(name))
1489 .map(|t| &**t)
1490 .or_else(|| crate::themes::builtin(name))
1491 .or_else(|| crate::themes::of_family(name, self.theme.dark))
1493 }
1494
1495 pub fn theme_names(&self) -> Vec<String> {
1497 let mut names: Vec<String> = vec![self.theme.name.clone()];
1498 let others = self.themes.iter().map(|t| t.name.clone()).chain(crate::themes::all().iter().map(|t| t.name.clone()));
1499 for n in others {
1500 if !names.iter().any(|x| x.eq_ignore_ascii_case(&n)) {
1501 names.push(n);
1502 }
1503 }
1504 names
1505 }
1506
1507 pub fn theme_source(&self, id: ComponentId) -> (String, ThemeSource) {
1509 let mut cur = Some(id);
1510 let mut inherited: Option<(&Theme, ThemeSource)> = None;
1511 while let Some(c) = cur {
1512 if let Some(name) = self.control(c).map(|cb| cb.theme_name()).filter(|n| !n.is_empty()) {
1513 if let Some(t) = self.theme_named(name) {
1514 let source = if c == id { ThemeSource::Own } else { ThemeSource::Inherited(c) };
1515 inherited = Some((t, source));
1516 break;
1517 }
1518 }
1519 cur = self.parent(c);
1520 }
1521 let (base, source) = inherited.unwrap_or((&self.theme, ThemeSource::App));
1522 let mut classes = Vec::new();
1523 if let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) {
1524 component.class_chain(&mut classes);
1525 }
1526 if let Some(class) = classes.iter().find(|c| base.components.contains_key(**c)) {
1527 let mixed = self.mixed_theme(base, &classes);
1528 if !std::ptr::eq(mixed, base) {
1529 return (mixed.name.clone(), ThemeSource::Class(class.to_string()));
1530 }
1531 }
1532 (base.name.clone(), source)
1533 }
1534
1535 pub fn theme_of(&self, id: ComponentId) -> &Theme {
1538 let mut inherited: &Theme = &self.theme;
1539 let mut cur = Some(id);
1540 while let Some(c) = cur {
1541 if let Some(name) = self.control(c).map(|cb| cb.theme_name()).filter(|n| !n.is_empty()) {
1542 if let Some(t) = self.theme_named(name) {
1543 inherited = t;
1544 break;
1545 }
1546 }
1547 cur = self.parent(c);
1548 }
1549 let mut classes = Vec::new();
1550 if let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) {
1551 component.class_chain(&mut classes);
1552 }
1553 self.mixed_theme(inherited, &classes)
1554 }
1555
1556 pub(crate) fn mixed_theme<'a>(&'a self, theme: &'a Theme, classes: &[&str]) -> &'a Theme {
1558 theme.mixed_for(classes).and_then(|name| self.theme_named(name)).unwrap_or(theme)
1559 }
1560
1561 pub fn register_icon(&mut self, name: &str, icon: crate::icons::Icon) {
1563 self.icons.insert(name.to_string(), icon);
1564 self.request_repaint();
1565 }
1566
1567 pub fn register_icon_svg(&mut self, name: &str, stroke: &str, fill: &str, size: f32) -> crate::Result<()> {
1569 let icon = crate::icons::Icon::from_svg(stroke, fill, size)
1570 .ok_or_else(|| crate::Error::invalid(format!("caminho SVG inválido no ícone '{name}'")))?;
1571 self.register_icon(name, icon);
1572 Ok(())
1573 }
1574
1575 pub fn register_icon_pack(&mut self, prefix: &str, text: &str) -> crate::Result<usize> {
1578 let pack = crate::icons::parse_pack(text).map_err(crate::Error::invalid)?;
1579 let mut n = 0;
1580 for (name, d) in &pack.icons {
1581 if let Some(icon) = pack.build(d) {
1582 self.icons.insert(format!("{prefix}:{name}"), icon);
1583 n += 1;
1584 }
1585 }
1586 self.request_repaint();
1587 Ok(n)
1588 }
1589
1590 pub fn has_icon_pack(&self, prefix: &str) -> bool {
1593 let start = format!("{prefix}:");
1594 self.icons.keys().any(|k| k.starts_with(&start))
1595 }
1596
1597 pub fn icon(&self, name: &str) -> Option<&crate::icons::Icon> {
1598 self.icons.get(name).or_else(|| crate::icons::builtin(name))
1599 }
1600
1601 pub fn services(&self) -> &Services {
1602 &self.services
1603 }
1604
1605 pub fn services_mut(&mut self) -> &mut Services {
1606 &mut self.services
1607 }
1608
1609 pub fn set_services(&mut self, services: Services) {
1610 self.services = services;
1611 }
1612
1613 pub fn measure_text(&self, text: &str, style: &TextStyle) -> SizeF {
1616 if self.text_mode != crate::textcore::TextMode::Native {
1617 if let Some(size) = crate::textcore::measure(text, style, None) {
1618 return size;
1619 }
1620 }
1621 match &self.services.text {
1622 Some(service) => service.measure(text, style, None),
1623 None => SizeF::new(text.chars().count() as f32 * style.font.size * 0.55, style.font.size * 1.3),
1624 }
1625 }
1626
1627 pub fn measure_text_wrapped(&self, text: &str, style: &TextStyle, max_width: f32) -> SizeF {
1630 if self.text_mode != crate::textcore::TextMode::Native {
1631 if let Some(size) = crate::textcore::measure(text, style, Some(max_width)) {
1632 return size;
1633 }
1634 }
1635 match &self.services.text {
1636 Some(service) => service.measure(text, style, Some(max_width)),
1637 None => {
1638 let one = self.measure_text(text, style);
1639 let lines = (one.width / max_width.max(1.0)).ceil().max(1.0);
1640 SizeF::new(one.width.min(max_width), one.height * lines)
1641 }
1642 }
1643 }
1644
1645 pub fn locale(&self) -> crate::platform::LocaleInfo {
1648 self.services.locale.as_ref().map(|l| l.locale()).unwrap_or_default()
1649 }
1650
1651 pub fn next_paint_wake(&self) -> Option<f64> {
1657 let forms = self.frame_requests.borrow().iter().filter(|(id, _)| self.contains(**id)).filter_map(|(_, f)| f.1).reduce(f64::min);
1658 let controls = self.timed_frames.borrow().iter().filter(|(id, _)| self.contains(**id)).map(|(_, t)| *t).reduce(f64::min);
1661 [forms, controls].into_iter().flatten().reduce(f64::min)
1662 }
1663
1664 pub fn next_wake(&self) -> Option<f64> {
1665 let painted = self.next_paint_wake();
1666 match (painted, self.timers_wake()) {
1667 (Some(a), Some(b)) => Some(a.min(b)),
1668 (a, b) => a.or(b),
1669 }
1670 }
1671
1672 pub fn zoom(&self) -> f32 {
1676 self.zoom
1677 }
1678
1679 pub fn set_zoom(&mut self, zoom: f32) {
1681 let zoom = if zoom.is_finite() { zoom.clamp(0.25, 5.0) } else { 1.0 };
1682 if (zoom - self.zoom).abs() > f32::EPSILON {
1683 self.zoom = zoom;
1684 self.mark_zoom_changed();
1685 }
1686 }
1687
1688 pub fn form_zoom(&self, form: ComponentId) -> f32 {
1691 if self.physical_pixels(form) {
1692 return 1.0;
1693 }
1694 let own = match self.get_prop(form, "zoom") {
1695 Ok(PropValue::Float(z)) if z > 0.0 => z as f32,
1696 Ok(PropValue::Int(z)) if z > 0 => z as f32,
1697 _ => 1.0,
1698 };
1699 (self.zoom * own).clamp(0.25, 5.0)
1700 }
1701
1702 pub fn form_frame_reuse_kb(&self, form: ComponentId) -> Option<u32> {
1706 match self.get_prop(form, "frame_reuse_kb") {
1707 Ok(PropValue::Int(kb)) => crate::image_cache::form_frame_reuse(kb),
1708 _ => None,
1709 }
1710 }
1711
1712 pub fn mark_zoom_changed(&mut self) {
1714 self.zoom_changed = true;
1715 self.request_repaint();
1716 }
1717
1718 pub fn take_zoom_changed(&mut self) -> bool {
1720 std::mem::take(&mut self.zoom_changed)
1721 }
1722
1723 pub fn zoom_keys(&self) -> bool {
1725 self.zoom_keys
1726 }
1727
1728 pub fn set_zoom_keys(&mut self, on: bool) {
1729 self.zoom_keys = on;
1730 }
1731
1732 pub fn set_font_names(&mut self, names: Vec<(String, String)>) {
1736 self.font_names = names;
1737 self.request_repaint();
1738 }
1739
1740 pub fn font_names(&self) -> &[(String, String)] {
1741 &self.font_names
1742 }
1743
1744 pub fn resolve_font(&self, family: &str) -> String {
1747 let mut current = family;
1748 for _ in 0..3 {
1749 match self.font_names.iter().find(|(name, _)| name == current) {
1750 Some((_, target)) => current = target,
1751 None => break,
1752 }
1753 }
1754 current.to_string()
1755 }
1756
1757 pub fn time(&self) -> f64 {
1759 self.time
1760 }
1761
1762 pub fn set_time(&mut self, seconds: f64) {
1763 self.time = seconds;
1764 }
1765
1766 pub fn advance(&mut self, seconds: f64) {
1769 self.time += seconds.max(0.0);
1770 self.run_timers();
1771 }
1772
1773 pub fn prop_infos(&self, id: ComponentId) -> Vec<PropInfo> {
1780 self.component(id).map(crate::component::prop_infos_of).unwrap_or_default()
1781 }
1782
1783 pub fn prop_info(&self, id: ComponentId, name: &str) -> Option<PropInfo> {
1784 crate::component::prop_info_of(self.component(id)?, name)
1785 }
1786
1787 pub fn get_prop(&self, id: ComponentId, name: &str) -> Result<PropValue> {
1793 self.read_prop(id, name, true)
1794 }
1795
1796 pub fn get_declared_prop(&self, id: ComponentId, name: &str) -> Result<PropValue> {
1798 self.read_prop(id, name, false)
1799 }
1800
1801 fn read_prop(&self, id: ComponentId, name: &str, laid_out: bool) -> Result<PropValue> {
1802 let entry = self.entry(id).ok_or(Error::InvalidId)?;
1803 if name == "name" {
1804 return Ok(PropValue::String(entry.name.clone()));
1805 }
1806 if let Some((head, field)) = name.split_once('.') {
1807 let bounds = self.get_prop(id, head)?.to_bounds().map_err(|e| e.with_property(head))?;
1808 return bounds_field(&bounds, field)
1809 .map(PropValue::from)
1810 .ok_or_else(|| Error::UnknownProperty(name.to_string()));
1811 }
1812 if entry.component.is_none() {
1815 return Err(Error::Busy(self.path_of(id)));
1816 }
1817 if laid_out && matches!(name, "width" | "height") && !self.design_mode
1823 && let Some(cb) = self.cb(id)
1824 && cb.visible()
1825 && stretches(cb.align(), name == "width")
1826 {
1827 let b = cb.bounds();
1828 let real = if name == "width" { b.width } else { b.height };
1829 if real > 0.0 {
1830 return Ok(PropValue::Float(real as f64));
1831 }
1832 }
1833 let info = self.prop_info(id, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))?;
1834 if info.kind == PropKind::Color {
1835 if let Some(spec) = self.color_name(id, name) {
1836 return Ok(PropValue::String(spec.to_string()));
1837 }
1838 }
1839 if info.kind == PropKind::Event {
1840 let handler = entry.events.iter().find(|(n, _)| n == name).and_then(|(_, h)| match h {
1841 Handler::Named(n) => Some(n.clone()),
1842 Handler::Closure(_) => None,
1843 });
1844 return Ok(PropValue::Event(handler));
1845 }
1846 if self.design_mode && name == "visible" {
1847 if let Some(cb) = self.cb(id) {
1848 return Ok(PropValue::Bool(!cb.design_hidden));
1849 }
1850 }
1851 let component = entry.component.as_deref().ok_or_else(|| Error::Busy(self.path_of(id)))?;
1852 crate::component::read_prop(component, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))
1853 }
1854
1855 pub fn set_prop(&mut self, id: ComponentId, name: &str, value: impl Into<PropValue>) -> Result<()> {
1862 let value = value.into();
1863 if !self.contains(id) {
1864 return Err(Error::InvalidId);
1865 }
1866 if name == "name" {
1867 let new_name = value.to_str().map_err(|e| e.with_property(name))?.to_string();
1868 return self.set_name(id, &new_name);
1869 }
1870 if let Some((head, field)) = name.split_once('.') {
1871 let mut bounds = self.get_prop(id, head)?.to_bounds().map_err(|e| e.with_property(head))?;
1872 let v = value.to_f32().map_err(|e| e.with_property(name))?;
1873 *bounds_field_mut(&mut bounds, field).ok_or_else(|| Error::UnknownProperty(name.to_string()))? = v;
1874 return self.set_prop(id, head, bounds);
1875 }
1876 if self.entry(id).is_some_and(|e| e.component.is_none()) {
1877 let error = Error::Busy(self.path_of(id));
1878 self.report_busy(&error);
1879 return Err(error);
1880 }
1881
1882 let info = self.prop_info(id, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))?;
1883 if info.read_only {
1884 return Err(Error::ReadOnly(name.to_string()));
1885 }
1886 if matches!(name, "trigger" | "enabled") && info.category == "Animation" {
1888 self.appear_waiting = None;
1889 self.hover_within_hosts = None;
1890 }
1891 let mut color_name = None;
1894 let value = match (&info.kind, value) {
1895 (PropKind::Color, PropValue::String(spec)) if crate::palette::is_named(&spec) => {
1896 let color = self
1897 .theme
1898 .resolve_color(&spec)
1899 .ok_or_else(|| Error::invalid(format!("cor desconhecida '{spec}' (use #hex ou um nome: {})", self.color_names().join(", "))).with_property(name))?;
1900 color_name = Some((spec, color));
1901 PropValue::Color(color)
1902 }
1903 (_, v) => v,
1904 };
1905 if info.kind == PropKind::Color {
1906 match &color_name {
1907 Some(spec) => {
1908 self.color_names.insert((id, name.to_string()), spec.clone());
1909 }
1910 None => {
1911 self.color_names.remove(&(id, name.to_string()));
1912 }
1913 }
1914 }
1915 if info.kind == PropKind::Component {
1916 self.forget_references();
1917 }
1918 let value = match info.kind {
1919 PropKind::Event => {
1920 let handler = value.to_event().map_err(|e| e.with_property(name))?;
1921 if let Some(h) = handler.as_deref().filter(|h| !is_identifier(h)) {
1923 return Err(Error::invalid(format!("nome de handler inválido '{h}' (letras, dígitos e _, sem começar por dígito)")).with_property(name));
1924 }
1925 self.set_event_handler(id, name, handler.map(Handler::Named));
1926 return Ok(());
1927 }
1928 PropKind::Component => match &value {
1929 PropValue::String(target) | PropValue::Enum(target) => {
1930 if target.is_empty() {
1931 PropValue::Component(None)
1932 } else {
1933 let found = self
1934 .resolve_reference(id, target)
1935 .ok_or_else(|| Error::ComponentNotFound(target.clone()))?;
1936 PropValue::Component(Some(found))
1937 }
1938 }
1939 _ => value,
1940 },
1941 _ => value,
1942 };
1943 let value = if self.design_mode && name == "visible" && self.cb(id).is_some() {
1947 let hidden = !value.to_bool().map_err(|e| e.with_property(name))?;
1948 let shown = !hidden || self.design_revealed(id);
1949 let cb = self.cb_mut(id).expect("verificado acima");
1950 cb.design_hidden = hidden;
1951 cb.set_visible(shown);
1953 PropValue::Bool(cb.visible())
1954 } else {
1955 value
1956 };
1957
1958 let paint_only = info.kind == PropKind::Color
1961 || PAINT_ONLY.contains(&name)
1962 || self.entry(id).and_then(|e| e.component.as_deref()).is_some_and(|c| c.paint_only_property(name));
1963 let before = self.cb(id).map(|cb| cb.state());
1964 let old_value = if self.announces_change(id, &info) {
1966 self.entry(id).and_then(|e| e.component.as_deref()).and_then(|c| crate::component::read_prop(c, name))
1967 } else {
1968 None
1969 };
1970 let entry = self.entry_mut(id).expect("verificado acima");
1971 let component = entry.component.as_deref_mut().expect("ocupado já verificado acima");
1972 let result = match set_in_chain(component, name, value.clone()) {
1973 Err(Error::UnknownProperty(_)) => match component.control_mut() {
1974 Some(cb) => cb.set_prop(name, value),
1975 None => Err(Error::UnknownProperty(name.to_string())),
1976 },
1977 other => other,
1978 };
1979 if paint_only && matches!(name, "opacity" | "translate_x" | "translate_y") {
1980 self.damage_placement(id);
1983 } else if paint_only {
1984 self.damage(id);
1985 } else {
1986 self.invalidate_form(id);
1987 }
1988 if let Some(before) = before {
1989 self.sync_state_triggers(id, before);
1990 }
1991 if result.is_ok() {
1992 self.forget_translation_source(id, name);
1993 self.sync_timer(id);
1994 let _ = self.with_component(id, |c, ctx| c.property_changed(ctx, name));
1995 if name == "visible" {
1996 self.drop_hidden_focus(id);
1997 }
1998 if let Some(old) = old_value {
1999 self.fire_value_change(id, name, old);
2000 }
2001 }
2002 result.map_err(|e| e.with_property(name))
2003 }
2004
2005 pub fn set_prop_quiet(&mut self, id: ComponentId, name: &str, value: impl Into<PropValue>) -> Result<()> {
2008 let value = value.into();
2009 self.without_change_events(|ui| ui.set_prop(id, name, value))
2010 }
2011
2012 pub fn without_change_events<R>(&mut self, f: impl FnOnce(&mut Ui) -> R) -> R {
2016 self.quiet_changes += 1;
2017 let result = f(self);
2018 self.quiet_changes -= 1;
2019 result
2020 }
2021
2022 pub fn change_events_enabled(&self) -> bool {
2025 !self.design_mode && self.quiet_changes == 0
2026 }
2027
2028 fn announces_change(&self, id: ComponentId, info: &PropInfo) -> bool {
2032 if !self.change_events_enabled() || !crate::component::is_value_property(info) {
2033 return false;
2034 }
2035 if !self.prop_info(id, "on_change").is_some_and(|i| i.kind == PropKind::Event) {
2038 return false;
2039 }
2040 self.entry(id).is_some_and(|e| e.events.iter().any(|(n, _)| n == "on_change")) || self.is_intercepted(id, "on_change")
2041 }
2042
2043 fn fire_value_change(&mut self, id: ComponentId, name: &str, old: PropValue) {
2047 let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) else { return };
2048 let Some(new) = crate::component::read_prop(component, name) else { return };
2049 if new == old {
2050 return;
2051 }
2052 let Some(args) = component.change_args(name, &new) else { return };
2053 if self.intercept(id, "on_change", &args).is_none() {
2054 self.fire_handler(id, "on_change", &args);
2055 }
2056 }
2057
2058 fn drop_hidden_focus(&mut self, id: ComponentId) {
2062 if self.cb(id).is_none_or(|cb| cb.visible()) {
2063 return;
2064 }
2065 let root = self.root_of(id);
2066 let Some(focused) = self.focused(root) else { return };
2067 let mut current = Some(focused);
2068 while let Some(c) = current {
2069 if c == id {
2070 self.clear_focus(root);
2071 return;
2072 }
2073 current = self.parent(c);
2074 }
2075 }
2076
2077 fn sync_state_triggers(&mut self, id: ComponentId, before: ControlState) {
2080 use crate::anim::Trigger;
2081 let Some(after) = self.cb(id).map(|cb| cb.state()) else { return };
2082 for (trigger, was, is) in [
2083 (Trigger::Hover, before.hover, after.hover),
2084 (Trigger::Pressed, before.pressed, after.pressed),
2085 (Trigger::Focused, before.focused, after.focused),
2086 (Trigger::Checked, before.checked, after.checked),
2087 ] {
2088 if was != is {
2089 self.request_repaint();
2090 self.run_triggers(id, trigger, is);
2091 }
2092 }
2093 }
2094
2095 fn set_event_handler(&mut self, id: ComponentId, event: &str, handler: Option<Handler>) {
2100 if let Some(entry) = self.entry_mut(id) {
2101 entry.events.retain(|(n, _)| n != event);
2102 if let Some(h) = handler {
2103 entry.events.push((event.to_string(), h));
2104 }
2105 }
2106 }
2107
2108 pub fn has_handler(&self, id: ComponentId, event: &str) -> bool {
2110 self.entry(id).is_some_and(|e| e.events.iter().any(|(n, _)| n == event))
2111 }
2112
2113 pub fn listens(&self, id: ComponentId, event: &str) -> bool {
2118 self.has_handler(id, event)
2119 || !self.interceptors_for(id, event).is_empty()
2120 || (crate::bindings::CHANGE_EVENTS.contains(&event) && !self.bindings(id).is_empty() && !self.design_mode)
2121 }
2122
2123 pub fn on(
2125 &mut self,
2126 id: ComponentId,
2127 event: &str,
2128 handler: impl Fn(&mut Ui, ComponentId, &EventArgs) + 'static,
2129 ) {
2130 if cfg!(debug_assertions) && self.contains(id) && self.prop_info(id, event).is_none_or(|p| p.kind != PropKind::Event) {
2134 let class = self.class_name(id).unwrap_or_default();
2135 thread_local!(static WARNED: RefCell<std::collections::HashSet<String>> = RefCell::default());
2136 if WARNED.with(|w| w.borrow_mut().insert(format!("{class}.{event}"))) {
2137 crate::stderr_line!("aylis: {class} não tem o evento {event}: o handler ligado com ui.on só roda se o componente disparar esse nome");
2138 }
2139 }
2140 self.set_event_handler(id, event, Some(Handler::Closure(std::rc::Rc::new(handler))));
2141 }
2142
2143 pub fn on_click(&mut self, id: ComponentId, handler: impl Fn(&mut Ui, ComponentId) + 'static) {
2145 self.on(id, "on_click", move |ui, sender, _| handler(ui, sender));
2146 }
2147
2148 pub fn copy_events(&mut self, from: ComponentId, to: ComponentId) {
2151 let events = self.entry(from).map(|e| e.events.clone()).unwrap_or_default();
2152 for (name, handler) in events {
2153 self.set_event_handler(to, &name, Some(handler));
2154 }
2155 }
2156
2157 pub fn clear_event(&mut self, id: ComponentId, event: &str) {
2159 self.set_event_handler(id, event, None);
2160 }
2161
2162 pub fn register_handler(
2169 &mut self,
2170 name: &str,
2171 handler: impl Fn(&mut Ui, ComponentId, &EventArgs) + 'static,
2172 ) {
2173 let (form, handler_name) = name.rsplit_once('.').unwrap_or(("", name));
2174 self.handlers.entry(form.to_string()).or_default().insert(handler_name.to_string(), std::rc::Rc::new(handler));
2175 }
2176
2177 pub fn set_event_sink(
2179 &mut self,
2180 sink: impl Fn(&mut Ui, ComponentId, &str, &str, &EventArgs) + 'static,
2181 ) {
2182 self.event_sink = Some(std::rc::Rc::new(sink));
2183 }
2184
2185 pub fn on_paint(
2187 &mut self,
2188 id: ComponentId,
2189 hook: impl Fn(&mut dyn Canvas, &PaintCtx<'_>, &dyn Fn(&mut dyn Canvas, &PaintCtx<'_>)) + 'static,
2190 ) {
2191 if let Some(entry) = self.entry_mut(id) {
2192 entry.paint_hook = Some(Box::new(hook));
2193 }
2194 self.request_repaint();
2195 }
2196
2197 pub fn clear_on_paint(&mut self, id: ComponentId) {
2198 if let Some(entry) = self.entry_mut(id) {
2199 entry.paint_hook = None;
2200 }
2201 self.request_repaint();
2202 }
2203
2204 pub fn fire(&mut self, id: ComponentId, event: &str, args: &EventArgs) -> bool {
2211 self.binding_changed(id, event);
2214 if let Some(result) = self.intercept(id, event, args) {
2216 return result;
2217 }
2218 self.fire_handler(id, event, args)
2219 }
2220
2221 pub(crate) fn fire_handler(&mut self, id: ComponentId, event: &str, args: &EventArgs) -> bool {
2223 let Some(entry) = self.entry(id) else {
2224 return false;
2225 };
2226 let Some((event_name, handler)) = entry.events.iter().find(|(n, _)| n == event).map(|(n, h)| (n.clone(), h.clone())) else {
2227 return false;
2228 };
2229 if self.has_observers() {
2230 let name = match &handler {
2231 Handler::Named(n) => n.clone(),
2232 Handler::Closure(_) => String::new(),
2233 };
2234 self.report(&crate::activity::Activity::Event { component: id, event: &event_name, handler: &name });
2235 }
2236 if let Some(trace) = self.trace.clone() {
2237 let name = match &handler {
2238 Handler::Named(n) => n.as_str(),
2239 Handler::Closure(_) => "",
2240 };
2241 trace(self, id, &event_name, name);
2242 }
2243 match handler {
2244 Handler::Closure(f) => {
2245 let _profile = crate::profile::scope(crate::profile::Lane::Event, || format!("{}.{event_name}", self.path_of(id)));
2246 self.nested(id, &event_name, |ui| f(ui, id, args))
2247 }
2248 Handler::Named(handler_name) => self.call_named(id, &event_name, &handler_name, args),
2249 }
2250 }
2251
2252 fn nested(&mut self, id: ComponentId, event: &str, call: impl FnOnce(&mut Ui)) -> bool {
2256 let limit = self.limits.1;
2257 if self.event_depth >= limit {
2258 if self.event_depth == limit {
2260 self.event_depth += 1;
2261 let message = format!("evento recursivo demais: {}.{event} ({limit} níveis)", self.path_of(id));
2262 self.raise_exception(crate::Exception { message, path: self.path_of(id), event: event.to_string() });
2263 self.event_depth -= 1;
2264 }
2265 return false;
2266 }
2267 self.event_depth += 1;
2268 let depth = self.event_depth;
2270 let quiet = self.quiet_changes;
2272 self.running_events.push(event.to_string());
2273 self.guarded(id, event, call);
2274 self.running_events.pop();
2275 self.event_depth = depth - 1;
2276 self.quiet_changes = quiet;
2277 true
2278 }
2279
2280 pub fn set_limits(&mut self, tree_depth: usize, event_nesting: usize) {
2283 self.limits = (tree_depth.max(8), event_nesting.max(8));
2284 }
2285
2286 pub fn limits(&self) -> (usize, usize) {
2288 self.limits
2289 }
2290
2291 pub(crate) fn observers(&self) -> &crate::activity::Observers {
2292 &self.observers
2293 }
2294
2295 pub(crate) fn observers_mut(&mut self) -> &mut crate::activity::Observers {
2296 &mut self.observers
2297 }
2298
2299 pub fn set_event_trace(&mut self, f: Option<impl Fn(&Ui, ComponentId, &str, &str) + 'static>) {
2302 self.trace = f.map(|f| std::rc::Rc::new(f) as std::rc::Rc<TraceFn>);
2303 }
2304
2305 pub fn call_handler(&mut self, id: ComponentId, event: &str, handler: &str, args: &EventArgs) -> bool {
2309 self.call_named(id, event, handler, args)
2310 }
2311
2312 fn call_named(&mut self, id: ComponentId, event: &str, handler_name: &str, args: &EventArgs) -> bool {
2313 let mut form = self.form_of(id);
2321 loop {
2322 let name = self.form_class(form).or_else(|| self.name(form)).unwrap_or_default();
2323 if self.handlers.get(name).is_some_and(|m| m.contains_key(handler_name)) {
2324 break;
2325 }
2326 match self.parent(form).map(|p| self.form_of(p)) {
2327 Some(up) if up != form => form = up,
2328 _ => {
2329 form = self.form_of(id);
2330 break;
2331 }
2332 }
2333 }
2334 let form_name = self.form_class(form).or_else(|| self.name(form)).unwrap_or_default();
2335 let _profile = crate::profile::scope(crate::profile::Lane::Handler, || {
2338 if form_name.is_empty() { handler_name.to_string() } else { format!("{form_name}.{handler_name}") }
2339 });
2340 let of_form = |form: &str| self.handlers.get(form).and_then(|m| m.get(handler_name)).cloned();
2341 let found = if form_name.is_empty() { None } else { of_form(form_name) }.or_else(|| of_form(""));
2343 if let Some(f) = found {
2344 return self.nested(id, event, |ui| f(ui, id, args));
2345 }
2346 if let Some(sink) = self.event_sink.clone() {
2347 return self.nested(id, event, |ui| sink(ui, id, event, handler_name, args));
2348 }
2349 false
2350 }
2351
2352 pub fn queue_event(&mut self, id: ComponentId, event: &str, args: EventArgs) {
2354 let pointer = if event == "on_click" { self.click_source } else { None };
2356 self.pending.push((id, event.to_string(), args, pointer));
2357 }
2358
2359 pub fn click_pointer(&self) -> Option<crate::ClickPointer> {
2365 self.click_pointer
2366 }
2367
2368 pub(crate) fn with_click_pointer<R>(&mut self, pointer: Option<crate::ClickPointer>, f: impl FnOnce(&mut Ui) -> R) -> R {
2371 let saved = (std::mem::replace(&mut self.click_pointer, pointer), self.click_source.take());
2372 let result = f(self);
2373 (self.click_pointer, self.click_source) = saved;
2374 result
2375 }
2376
2377 fn click_pointer_for(&self, id: ComponentId, (target, pointer): (ComponentId, crate::ClickPointer)) -> crate::ClickPointer {
2380 if id == target {
2381 return pointer;
2382 }
2383 crate::ClickPointer { position: self.local_point(id, pointer.form_position), ..pointer }
2384 }
2385
2386 pub fn process_events(&mut self) {
2391 let mut delivered = 0;
2392 let mut busy = Vec::new();
2396 while !self.pending.is_empty() {
2397 let mut batch = std::mem::take(&mut self.pending).into_iter();
2398 for (id, event, args, source) in batch.by_ref() {
2399 if self.entry(id).is_some_and(|e| e.component.is_none()) {
2400 busy.push((id, event, args, source));
2401 continue;
2402 }
2403 self.count_repeat(id, &event);
2404 let pointer = source.filter(|_| self.contains(id)).map(|s| self.click_pointer_for(id, s));
2407 self.with_click_pointer(pointer, |ui| ui.fire(id, &event, &args));
2408 delivered += 1;
2409 if delivered >= EVENTS_PER_ROUND {
2410 break;
2411 }
2412 }
2413 if delivered >= EVENTS_PER_ROUND {
2414 let mut left: Vec<_> = batch.collect();
2416 left.append(&mut self.pending);
2417 busy.append(&mut left);
2418 self.pending = busy;
2419 if !self.pending.is_empty() {
2420 self.poster().wake();
2421 return;
2422 }
2423 busy = Vec::new();
2424 }
2425 }
2426 self.pending = busy;
2427 self.repeat = None;
2428 }
2429
2430 pub fn has_pending_events(&self) -> bool {
2432 !self.pending.is_empty()
2433 }
2434
2435 fn count_repeat(&mut self, id: ComponentId, event: &str) {
2438 let count = match &mut self.repeat {
2439 Some((last, name, count)) if *last == id && name == event => {
2440 *count += 1;
2441 *count
2442 }
2443 _ => {
2444 self.repeat = Some((id, event.to_string(), 1));
2445 1
2446 }
2447 };
2448 if count == LOOP_WARNING {
2449 let message = format!("possível laço: {}.{event} disparado {LOOP_WARNING} vezes seguidas", self.path_of(id));
2450 self.report(&crate::activity::Activity::Error { message: &message });
2451 }
2452 }
2453
2454 pub fn with_component<R>(
2459 &mut self,
2460 id: ComponentId,
2461 f: impl FnOnce(&mut dyn Component, &mut EventCtx<'_>) -> R,
2462 ) -> Option<R> {
2463 let before = self.cb(id).map(|cb| cb.state());
2464 let mut component = self.entry_mut(id)?.component.take()?;
2465 self.call_depth += 1;
2466 let depth = (self.call_depth, self.event_depth);
2467 let result = {
2468 let mut ctx = EventCtx::new(self, id);
2469 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(component.as_mut(), &mut ctx)))
2470 };
2471 (self.call_depth, self.event_depth) = (depth.0 - 1, depth.1);
2472 if let Some(entry) = self.entry_mut(id) {
2475 entry.component = Some(component);
2476 }
2477 let result = match result {
2478 Ok(r) => Some(r),
2479 Err(payload) => {
2480 let message = crate::exception::panic_message(payload.as_ref());
2481 self.raise_exception(crate::Exception { message, path: self.path_of(id), event: String::new() });
2482 None
2483 }
2484 };
2485 if let Some(before) = before {
2486 self.sync_state_triggers(id, before);
2487 }
2488 if let Some(focus) = self.pending_focus.take() {
2489 self.set_focus(focus);
2490 }
2491 self.process_events();
2492 if self.call_depth == 0 {
2493 self.flush_closes();
2494 }
2495 result
2496 }
2497
2498 pub fn send_message(&mut self, id: ComponentId, message: &dyn Any) -> bool {
2501 if let Some(error) = self.busy_error(id) {
2502 self.report_busy(&error);
2503 return false;
2504 }
2505 self.with_component(id, |c, ctx| c.message(ctx, message)).is_some()
2506 }
2507
2508 pub fn invoke(&mut self, id: ComponentId, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
2511 if let Some(error) = self.busy_error(id) {
2512 self.report_busy(&error);
2513 return Err(error.to_string());
2514 }
2515 if method == "render_rgba" {
2518 return self.invoke_render_rgba(id, args);
2519 }
2520 let args = self.component_args(id, method, args);
2521 self.with_component(id, |c, ctx| c.invoke(ctx, method, &args)).unwrap_or_else(|| Err(Error::InvalidId.to_string()))
2522 }
2523
2524 fn component_args(&self, id: ComponentId, method: &str, args: &[PropValue]) -> Vec<PropValue> {
2528 let kinds = self.component(id).and_then(|c| c.methods().iter().find(|m| m.name == method)).map_or(&[][..], |m| m.args);
2529 args.iter()
2530 .enumerate()
2531 .map(|(i, arg)| {
2532 if kinds.get(i) != Some(&PropKind::Component) {
2533 return arg.clone();
2534 }
2535 match arg {
2536 PropValue::String(path) if path.is_empty() => PropValue::Component(None),
2537 PropValue::String(path) => self.find_path(path).map_or_else(|| arg.clone(), |c| PropValue::Component(Some(c))),
2538 PropValue::Int(n) => {
2539 let c = ComponentId::from_u64(*n as u64);
2540 if self.contains(c) { PropValue::Component(Some(c)) } else { arg.clone() }
2541 }
2542 PropValue::Null => PropValue::Component(None),
2543 _ => arg.clone(),
2544 }
2545 })
2546 .collect()
2547 }
2548
2549 fn busy_error(&self, id: ComponentId) -> Option<Error> {
2552 self.entry(id).filter(|e| e.component.is_none()).map(|_| Error::Busy(self.path_of(id)))
2553 }
2554
2555 fn report_busy(&mut self, error: &Error) {
2558 if cfg!(debug_assertions) {
2559 let message = error.to_string();
2560 self.report(&crate::activity::Activity::Error { message: &message });
2561 }
2562 }
2563
2564 pub fn set_hint_delay(&mut self, seconds: Option<f64>) {
2570 self.hint_delay = seconds.map(|s| s.max(0.0));
2571 }
2572
2573 pub fn set_still_picture(&mut self, on: bool) {
2576 self.still_picture = on;
2577 }
2578
2579 pub fn hint_delay(&self) -> f64 {
2581 self.hint_delay
2582 .or_else(|| self.theme.durations.get("hint").map(|ms| *ms as f64 / 1000.0))
2583 .unwrap_or(crate::input::HINT_DELAY)
2584 }
2585
2586 pub fn set_design_mode(&mut self, on: bool) {
2587 self.design_mode = on;
2588 self.request_repaint();
2589 }
2590
2591 pub fn set_design_reveal(&mut self, selected: &[ComponentId], show_all: bool) {
2596 self.design_reveal = selected.to_vec();
2597 self.design_show_hidden = show_all;
2598 let mut stack = self.roots().to_vec();
2599 while let Some(id) = stack.pop() {
2600 stack.extend(self.children(id).iter().copied());
2601 if self.cb(id).is_some_and(|cb| cb.design_hidden) {
2602 let shown = self.design_revealed(id);
2603 if let Some(cb) = self.cb_mut(id) {
2604 cb.set_visible(shown);
2605 }
2606 }
2607 }
2608 self.invalidate();
2609 }
2610
2611 fn design_revealed(&self, id: ComponentId) -> bool {
2614 self.design_show_hidden
2615 || self.design_reveal.iter().any(|&s| {
2616 let mut cur = Some(s);
2617 while let Some(c) = cur {
2618 if c == id {
2619 return true;
2620 }
2621 cur = self.parent(c);
2622 }
2623 false
2624 })
2625 }
2626
2627 pub fn design_mode(&self) -> bool {
2628 self.design_mode
2629 }
2630
2631 pub fn design_changed(&mut self, root: ComponentId) {
2635 let mut stack = vec![root];
2636 while let Some(id) = stack.pop() {
2637 stack.extend(self.children(id).iter().copied());
2638 self.send_message(id, &DesignChanged);
2639 }
2640 }
2641
2642 pub fn request_close(&mut self) {
2644 self.close_requested = true;
2645 }
2646
2647 pub fn close_requested(&self) -> bool {
2649 self.close_requested
2650 }
2651
2652 pub fn clone_component(&mut self, source: ComponentId, parent: Option<ComponentId>) -> Result<ComponentId> {
2657 self.clone_node(source, parent, false)
2658 }
2659
2660 fn clone_node(&mut self, source: ComponentId, parent: Option<ComponentId>, named: bool) -> Result<ComponentId> {
2661 let class = self.class_name(source).ok_or(Error::InvalidId)?.to_string();
2662 let id = self.create(&class, parent)?;
2663 if named {
2664 if let Some(name) = self.name(source).filter(|n| !n.is_empty()).map(str::to_string) {
2665 let _ = self.set_name(id, &name);
2666 }
2667 }
2668 if !named || self.entry(source).is_some_and(|e| e.scope) {
2670 self.set_name_scope(id, true);
2671 }
2672 let mut infos = self.prop_infos(source);
2675 infos.sort_by_key(|i| matches!(i.name, "align" | "anchors"));
2676 for info in infos {
2677 if info.read_only || info.runtime || info.name == "name" {
2678 continue;
2679 }
2680 if let Ok(value) = self.get_prop(source, info.name) {
2681 let _ = self.set_prop_quiet(id, info.name, value);
2682 }
2683 }
2684 for child in self.children(source).to_vec() {
2685 self.clone_node(child, Some(id), true)?;
2686 }
2687 Ok(id)
2688 }
2689
2690 pub fn components(&self) -> impl Iterator<Item = ComponentId> + '_ {
2692 self.slots.iter().enumerate().filter_map(|(index, slot)| {
2693 slot.entry.as_ref().map(|_| ComponentId { index: index as u32, generation: slot.generation })
2694 })
2695 }
2696
2697 pub fn click(&mut self, id: ComponentId) -> bool {
2700 let source = self.click_source.take();
2701 let clicked = self.with_component(id, |c, ctx| c.click(ctx)).is_some();
2702 self.click_source = source;
2703 clicked
2704 }
2705
2706 pub fn dump(&self, id: ComponentId) -> String {
2712 let mut out = String::new();
2713 self.dump_into(id, 0, &mut out);
2714 out
2715 }
2716
2717 fn dump_into(&self, id: ComponentId, depth: usize, out: &mut String) {
2718 let Some(entry) = self.entry(id) else { return };
2719 let class = entry.component.as_deref().map_or("?", |c| c.class_name());
2720 let _ = write!(out, "{:indent$}{class}", "", indent = depth * 2);
2721 if !entry.name.is_empty() {
2722 let _ = write!(out, " {}", entry.name);
2723 }
2724 if let Some(cb) = self.cb(id) {
2725 let b = cb.bounds;
2726 let _ = write!(
2727 out,
2728 " [{:?}] x={} y={} w={} h={}",
2729 cb.align(),
2730 b.x,
2731 b.y,
2732 b.width,
2733 b.height
2734 );
2735 }
2736 out.push('\n');
2737 for &c in &entry.children {
2738 self.dump_into(c, depth + 1, out);
2739 }
2740 }
2741}
2742
2743fn too_deep(limit: usize) -> Error {
2744 Error::invalid(format!("profundidade máxima de componentes ({limit} níveis)"))
2745}
2746
2747pub fn is_identifier(s: &str) -> bool {
2750 let mut chars = s.chars();
2751 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
2752 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
2753}
2754
2755fn bounds_field(b: &Bounds, field: &str) -> Option<f32> {
2756 match field {
2757 "left" => Some(b.left),
2758 "top" => Some(b.top),
2759 "right" => Some(b.right),
2760 "bottom" => Some(b.bottom),
2761 _ => None,
2762 }
2763}
2764
2765fn bounds_field_mut<'a>(b: &'a mut Bounds, field: &str) -> Option<&'a mut f32> {
2766 match field {
2767 "left" => Some(&mut b.left),
2768 "top" => Some(&mut b.top),
2769 "right" => Some(&mut b.right),
2770 "bottom" => Some(&mut b.bottom),
2771 _ => None,
2772 }
2773}
2774
2775fn set_in_chain(c: &mut dyn Component, name: &str, value: PropValue) -> Result<()> {
2777 match c.set_prop(name, value.clone()) {
2778 Err(Error::UnknownProperty(_)) => match c.inner_mut() {
2779 Some(inner) => set_in_chain(inner, name, value),
2780 None => Err(Error::UnknownProperty(name.to_string())),
2781 },
2782 other => other,
2783 }
2784}
2785
2786fn find_layer<T: Component>(c: &dyn Component) -> Option<&T> {
2787 let any: &dyn Any = c;
2788 if let Some(t) = any.downcast_ref::<T>() {
2789 return Some(t);
2790 }
2791 c.inner().and_then(find_layer::<T>)
2792}
2793
2794fn find_layer_mut<T: Component>(c: &mut dyn Component) -> Option<&mut T> {
2795 if (&*c as &dyn Any).is::<T>() {
2796 let any: &mut dyn Any = c;
2797 return any.downcast_mut::<T>();
2798 }
2799 c.inner_mut().and_then(find_layer_mut::<T>)
2800}
2801
2802impl Ui {
2807 pub fn access_items(&self, id: ComponentId) -> Vec<crate::automation::AccessItem> {
2810 self.component(id).and_then(|c| c.accessible_items()).map_or_else(Vec::new, |a| a.access_items(self, id))
2811 }
2812
2813 pub fn access_action(&mut self, id: ComponentId, index: usize, action: crate::automation::ItemAction) -> bool {
2816 let done = self.with_component(id, |c, ctx| c.accessible_items_mut().is_some_and(|a| a.access_action(ctx, index, action))).unwrap_or(false);
2817 if done {
2818 self.request_repaint();
2819 }
2820 done
2821 }
2822
2823 pub fn click_item(&mut self, id: ComponentId, name: &str) -> bool {
2826 let found = self.access_items(id).iter().position(|i| i.name.trim().eq_ignore_ascii_case(name.trim()));
2827 found.is_some_and(|index| self.access_action(id, index, crate::automation::ItemAction::Click))
2828 }
2829}
2830
2831impl Ui {
2832 pub fn style_line_height(&self, id: ComponentId) -> f32 {
2840 let theme = self.theme_of(id);
2841 match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
2842 Some((component, cb)) => {
2843 let mut classes = Vec::new();
2844 component.class_chain(&mut classes);
2845 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).line_height
2846 }
2847 None => 0.0,
2848 }
2849 }
2850
2851 pub fn style_padding(&self, id: ComponentId) -> crate::geometry::Bounds {
2852 let theme = self.theme_of(id);
2853 match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
2854 Some((component, cb)) => {
2855 let mut classes = Vec::new();
2856 component.class_chain(&mut classes);
2857 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).padding
2858 }
2859 None => Default::default(),
2860 }
2861 }
2862
2863 pub fn font_of(&self, id: ComponentId) -> crate::canvas::FontSpec {
2864 let theme = self.theme_of(id);
2865 let mut font = match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
2866 Some((component, cb)) => {
2867 let mut classes = Vec::new();
2868 component.class_chain(&mut classes);
2869 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).font
2870 }
2871 None => theme.fonts.get("default").cloned().unwrap_or_default(),
2872 };
2873 let mut chain = Vec::new();
2874 let mut cur = Some(id);
2875 while let Some(c) = cur {
2876 if let Some(cb) = self.control(c) {
2877 chain.push(cb.font().clone());
2878 }
2879 cur = self.parent(c);
2880 }
2881 let effective = chain.iter().fold(crate::component::FontOverride::default(), |acc, f| acc.over(f));
2883 effective.apply(&mut font);
2884 font.family = self.resolve_font(&font.family);
2885 font.size *= self.control(id).map_or(1.0, |cb| cb.text_scale());
2887 font
2888 }
2889}
2890
2891impl Ui {
2892 pub fn extension<T: Default + 'static>(&mut self) -> &mut T {
2896 self.extensions
2897 .entry(std::any::TypeId::of::<T>())
2898 .or_insert_with(|| Box::new(T::default()))
2899 .downcast_mut::<T>()
2900 .expect("o tipo é a chave")
2901 }
2902
2903 pub fn extension_ref<T: 'static>(&self) -> Option<&T> {
2905 self.extensions.get(&std::any::TypeId::of::<T>()).and_then(|b| b.downcast_ref::<T>())
2906 }
2907}
2908
2909fn stretches(align: crate::align::Align, width: bool) -> bool {
2911 use crate::align::Align;
2912 match align {
2913 Align::None | Align::Center => false,
2914 Align::VertCenter | Align::Horizontal => width,
2915 Align::HorzCenter | Align::Vertical => !width,
2916 Align::Top | Align::Bottom | Align::MostTop | Align::MostBottom => width,
2917 Align::Left | Align::Right | Align::MostLeft | Align::MostRight => !width,
2918 _ => true,
2919 }
2920}