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 project_font: String,
176 scroll_options: crate::ScrollOptions,
178 zoom: f32,
180 zoom_changed: bool,
182 zoom_keys: bool,
184 zoom_limits: (f32, f32),
186 pub(crate) memory_panel: Option<bool>,
188 font_names: Vec<(String, String)>,
191 color_names: HashMap<(ComponentId, String), (String, crate::color::Color)>,
196 icons: HashMap<String, crate::icons::Icon>,
198 pub(crate) input: HashMap<ComponentId, InputState>,
200 pub(crate) drag_request: Option<(String, String)>,
202 pub(crate) drag_visual_request: Option<crate::DragVisual>,
204 pub(crate) native_drag_image: bool,
207 pub(crate) drop_rejected: bool,
209 pub(crate) screen_pointer: Option<crate::input::ScreenPointer>,
212 pub(crate) animations: Vec<Running>,
213 pub(crate) appear_waiting: Option<Vec<ComponentId>>,
215 pub(crate) hover_within_hosts: Option<Vec<ComponentId>>,
217 pub(crate) style_animating: Cell<bool>,
219 pub(crate) recolored: RefCell<HashMap<(String, ColorOverride), std::rc::Rc<Theme>>>,
222 pub(crate) wake_at: Cell<Option<f64>>,
224 pub(crate) frame_requests: std::cell::RefCell<HashMap<ComponentId, (bool, Option<f64>)>>,
227 pub(crate) timed_frames: std::cell::RefCell<HashMap<ComponentId, f64>>,
231 pub(crate) frame_hooks: Vec<ComponentId>,
233 pub(crate) overlays: std::cell::RefCell<Vec<(crate::geometry::PointF, crate::pages::Page)>>,
236 pub(crate) pending_focus: Option<ComponentId>,
238 pub(crate) focus_reason: crate::FocusReason,
240 close_requested: bool,
241 pub(crate) exceptions: crate::exception::Exceptions,
243 pub(crate) limits: (usize, usize),
245 pub(crate) references: RefCell<Option<crate::references::Index>>,
247 pub(crate) interceptors: crate::intercept::Interceptors,
249 pub(crate) names: RefCell<crate::names::NameIndex>,
251 pub(crate) tasks: crate::tasks::Tasks,
253 pub(crate) instances: crate::instances::Instances,
255 pub(crate) open_forms: Vec<crate::forms::OpenForm>,
257 pub(crate) active_form: Option<ComponentId>,
260 pub(crate) focused_window: (Option<ComponentId>, bool),
264 pub(crate) placements: std::collections::HashMap<ComponentId, crate::forms::WindowPlacement>,
266 pub(crate) monitors: Vec<crate::monitors::Monitor>,
268 pub(crate) monitors_version: u64,
269 pub(crate) form_monitors: std::collections::HashMap<ComponentId, usize>,
270 pub(crate) drop_point: Option<crate::geometry::PointF>,
272 pub(crate) window_drag: Option<(ComponentId, Option<ComponentId>, crate::geometry::PointF)>,
275 pub(crate) minimized_forms: std::collections::HashSet<ComponentId>,
277 pub(crate) hidden_forms: std::collections::HashSet<ComponentId>,
279 pub(crate) origins: std::collections::HashMap<ComponentId, ComponentId>,
283 pub(crate) form_gpus: std::collections::HashMap<ComponentId, String>,
285 pub(crate) form_pieces: std::collections::HashMap<ComponentId, Vec<RectF>>,
287 pub(crate) piece_requests: std::cell::Cell<Option<(bool, Option<f64>)>>,
289 pub(crate) main_form: Option<ComponentId>,
290 pub(crate) questions: crate::question::Questions,
292 pub(crate) busy: crate::busy::Busy,
294 pub(crate) text_mode: crate::textcore::TextMode,
296 extensions: std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any>>,
298 pub(crate) window_commands: Vec<(ComponentId, crate::window::WindowCommand)>,
300 pub(crate) maximize_buttons: HashMap<ComponentId, (ComponentId, crate::geometry::RectF)>,
303 pub(crate) frames: crate::frames::FrameClock,
305 pub(crate) transitions: Vec<crate::transition::Running>,
307 pub(crate) closing_now: Option<ComponentId>,
309 pub(crate) stacked_forms: bool,
312 pub(crate) activate: Option<ComponentId>,
313 pub(crate) pending_closes: Vec<ComponentId>,
316 pub(crate) call_depth: u32,
318 pub(crate) design_mode: bool,
319 hint_delay: Option<f64>,
321 pub(crate) still_picture: bool,
324 design_reveal: Vec<ComponentId>,
327 design_show_hidden: bool,
329 pub(crate) timeouts: Vec<crate::timers::Timeout>,
331 pub(crate) next_timeout: u64,
332 pub(crate) start_hidden: std::collections::HashSet<ComponentId>,
334 pub(crate) rtl: bool,
336 pub(crate) posted: std::sync::Arc<crate::post::PostQueue>,
338 pub(crate) timers: Vec<crate::timers::TimerEntry>,
340 pub(crate) translations: crate::i18n::Translations,
342 services: Services,
343 pub(crate) time: f64,
344 pub(crate) layout_dirty: bool,
345 pub(crate) dirty_forms: std::collections::HashSet<ComponentId>,
347 pub(crate) dirty_parts: std::collections::HashSet<ComponentId>,
350 pub(crate) repaint_requested: bool,
351 pub(crate) damage_epoch: u64,
354 pub(crate) painted_epoch: HashMap<ComponentId, u64>,
355 pub(crate) ink: RefCell<Option<RectF>>,
358 pub(crate) plain: Cell<crate::ink::Plain>,
360 pub(crate) spilled: Cell<bool>,
361 pub(crate) paint_area: Cell<Option<RectF>>,
362 pub(crate) paint_form: Cell<Option<RectF>>,
365 pub(crate) overlay_users: std::cell::RefCell<std::collections::HashSet<ComponentId>>,
368 pub(crate) frame_ids: std::cell::RefCell<Vec<ComponentId>>,
371 pub(crate) placed_ids: std::cell::RefCell<Vec<ComponentId>>,
374 pub(crate) part_ids: std::cell::RefCell<Vec<(ComponentId, RectF)>>,
376 pub(crate) scroll_moves: std::cell::RefCell<Vec<(ComponentId, RectF, crate::PointF, bool)>>,
378 pub(crate) layer_epoch: std::cell::Cell<u64>,
381 pub(crate) overscroll_style: crate::overscroll::Overscroll,
383 pub(crate) pulls: std::cell::RefCell<crate::overscroll::Pulls>,
385 pub(crate) system_bars: Option<crate::system_bars::SystemBarsStyle>,
387 pub(crate) system_bars_version: u64,
388 pub(crate) paints_status_strip: bool,
389 pub(crate) dead_layers: std::cell::RefCell<Vec<u64>>,
392 pub(crate) auto_layers: std::cell::Cell<bool>,
395 pub(crate) movers: std::cell::RefCell<Vec<(ComponentId, ComponentId)>>,
398 pub(crate) reveal_ids: std::cell::RefCell<std::collections::HashMap<ComponentId, f32>>,
401 pub(crate) backdrop_next: std::cell::Cell<bool>,
403 pub(crate) backdrops: std::cell::RefCell<std::collections::HashMap<ComponentId, crate::paint::Backdrop>>,
405 pub(crate) paint_count: std::cell::Cell<usize>,
408}
409
410impl Default for Ui {
411 fn default() -> Self {
412 Self::new()
413 }
414}
415
416fn shared_theme(dark: bool) -> std::sync::Arc<Theme> {
418 static LIGHT: std::sync::OnceLock<std::sync::Arc<Theme>> = std::sync::OnceLock::new();
419 static DARK: std::sync::OnceLock<std::sync::Arc<Theme>> = std::sync::OnceLock::new();
420 let cell = if dark { &DARK } else { &LIGHT };
421 cell.get_or_init(|| std::sync::Arc::new(if dark { Theme::dark() } else { Theme::light() })).clone()
422}
423
424impl Ui {
425 pub fn new() -> Self {
426 Self {
427 slots: Vec::new(),
428 free_slots: Vec::new(),
429 roots: Vec::new(),
430 registry: ClassRegistry::default(),
431 handlers: HashMap::new(),
432 event_sink: None,
433 event_depth: 0,
434 quiet_changes: 0,
435 running_events: Vec::new(),
436 trace: None,
437 observers: Default::default(),
438 binding_sink: None,
439 binding_refresh: None,
440 views: HashMap::new(),
441 pending: Vec::new(),
442 click_source: None,
443 click_pointer: None,
444 repeat: None,
445 theme: shared_theme(false),
446 themes: vec![shared_theme(false), shared_theme(true)],
447 palette: Vec::new(),
448 project_font: String::new(),
449 scroll_options: crate::ScrollOptions::default(),
450 zoom: 1.0,
451 zoom_changed: false,
452 zoom_keys: false,
453 zoom_limits: (0.25, 5.0),
454 memory_panel: None,
455 font_names: Vec::new(),
456 color_names: HashMap::new(),
457 icons: HashMap::new(),
458 input: HashMap::new(),
459 drag_request: None,
460 drag_visual_request: None,
461 native_drag_image: false,
462 drop_rejected: false,
463 screen_pointer: None,
464 animations: Vec::new(),
465 appear_waiting: None,
466 hover_within_hosts: None,
467 style_animating: Cell::new(false),
468 recolored: RefCell::new(HashMap::new()),
469 wake_at: Cell::new(None),
470 frame_requests: Default::default(),
471 timed_frames: Default::default(),
472 frame_hooks: Vec::new(),
473 overlays: Default::default(),
474 pending_focus: None,
475 focus_reason: crate::FocusReason::Enter,
476 close_requested: false,
477 exceptions: Default::default(),
478 limits: (MAX_TREE_DEPTH, MAX_EVENT_NESTING),
479 references: RefCell::new(None),
480 interceptors: Default::default(),
481 names: RefCell::default(),
482 tasks: Default::default(),
483 instances: Default::default(),
484 open_forms: Vec::new(),
485 active_form: None,
486 focused_window: (None, false),
487 placements: std::collections::HashMap::new(),
488 monitors: Vec::new(),
489 monitors_version: 0,
490 form_monitors: std::collections::HashMap::new(),
491 minimized_forms: std::collections::HashSet::new(),
492 hidden_forms: std::collections::HashSet::new(),
493 origins: std::collections::HashMap::new(),
494 drop_point: None,
495 window_drag: None,
496 form_gpus: std::collections::HashMap::new(),
497 form_pieces: std::collections::HashMap::new(),
498 piece_requests: std::cell::Cell::new(None),
499 main_form: None,
500 questions: Default::default(),
501 busy: Default::default(),
502 text_mode: Default::default(),
503 extensions: Default::default(),
504 frames: Default::default(),
505 window_commands: Vec::new(),
506 maximize_buttons: HashMap::new(),
507 transitions: Vec::new(),
508 closing_now: None,
509 stacked_forms: false,
510 activate: None,
511 pending_closes: Vec::new(),
512 call_depth: 0,
513 design_mode: false,
514 hint_delay: None,
515 still_picture: false,
516 design_reveal: Vec::new(),
517 design_show_hidden: false,
518 timeouts: Vec::new(),
519 next_timeout: 0,
520 start_hidden: Default::default(),
521 rtl: false,
522 posted: Default::default(),
523 timers: Vec::new(),
524 translations: Default::default(),
525 services: Services::default(),
526 time: 0.0,
527 layout_dirty: false,
528 dirty_forms: Default::default(),
529 dirty_parts: Default::default(),
530 repaint_requested: false,
531 damage_epoch: 0,
532 painted_epoch: HashMap::new(),
533 ink: Default::default(),
534 plain: Default::default(),
535 spilled: Default::default(),
536 paint_area: Default::default(),
537 paint_form: Default::default(),
538 overlay_users: Default::default(),
539 frame_ids: Default::default(),
540 placed_ids: Default::default(),
541 part_ids: Default::default(),
542 scroll_moves: Default::default(),
543 layer_epoch: Default::default(),
544 overscroll_style: crate::overscroll::Overscroll::None,
545 pulls: Default::default(),
546 system_bars: None,
547 system_bars_version: 0,
548 paints_status_strip: false,
549 dead_layers: Default::default(),
550 auto_layers: std::cell::Cell::new(true),
551 movers: Default::default(),
552 reveal_ids: Default::default(),
553 backdrop_next: Default::default(),
554 backdrops: Default::default(),
555 paint_count: Default::default(),
556 }
557 }
558
559 pub(crate) fn entry(&self, id: ComponentId) -> Option<&Entry> {
564 let slot = self.slots.get(id.index as usize)?;
565 if slot.generation != id.generation {
566 return None;
567 }
568 slot.entry.as_ref()
569 }
570
571 pub(crate) fn entry_mut(&mut self, id: ComponentId) -> Option<&mut Entry> {
572 let slot = self.slots.get_mut(id.index as usize)?;
573 if slot.generation != id.generation {
574 return None;
575 }
576 slot.entry.as_mut()
577 }
578
579 fn alloc(&mut self, entry: Entry) -> ComponentId {
580 self.appear_waiting = None;
582 self.hover_within_hosts = None;
583 if let Some(index) = self.free_slots.pop() {
584 let slot = &mut self.slots[index as usize];
585 slot.entry = Some(entry);
586 ComponentId { index, generation: slot.generation }
587 } else {
588 self.slots.push(Slot { generation: 0, entry: Some(entry) });
589 ComponentId { index: (self.slots.len() - 1) as u32, generation: 0 }
590 }
591 }
592
593 pub(crate) fn cb(&self, id: ComponentId) -> Option<&ControlBase> {
595 self.entry(id)?.component.as_deref()?.control()
596 }
597
598 pub(crate) fn cb_mut(&mut self, id: ComponentId) -> Option<&mut ControlBase> {
599 self.entry_mut(id)?.component.as_deref_mut()?.control_mut()
600 }
601
602 #[track_caller]
605 pub fn invalidate(&mut self) {
606 self.layout_dirty = true;
607 self.request_repaint();
608 }
609
610 pub fn invalidate_form(&mut self, id: ComponentId) {
614 let root = self.root_of(id);
615 self.dirty_forms.insert(root);
616 self.damage(id);
617 }
618
619 pub(crate) fn invalidate_part(&mut self, id: ComponentId) {
625 self.damage(id);
626 let root = self.root_of(id);
627 if self.layout_dirty || self.dirty_forms.contains(&root) {
628 return;
629 }
630 let part = if self.views.is_empty() { self.layout_part(id) } else { root };
631 if part == root {
632 self.dirty_forms.insert(root);
633 } else {
634 self.dirty_parts.insert(part);
635 }
636 }
637
638 fn layout_part(&self, id: ComponentId) -> ComponentId {
640 let Some(mut part) = self.parent(id) else { return id };
641 while let Some(up) = self.parent(part) {
642 if self.cb(part).is_some_and(|cb| !cb.auto_size()) {
643 break;
644 }
645 part = up;
646 }
647 part
648 }
649
650 #[track_caller]
653 pub fn request_repaint(&mut self) {
654 self.repaint_requested = true;
655 self.damage_epoch += 1;
656 }
657
658 pub fn needs_layout(&self) -> bool {
660 self.layout_dirty || !self.dirty_forms.is_empty() || !self.dirty_parts.is_empty()
661 }
662
663 pub fn needs_repaint(&self) -> bool {
665 self.repaint_requested || self.needs_layout() || self.is_animating()
666 }
667
668 pub fn add<T: Component>(&mut self, component: T, parent: ComponentId) -> ComponentId {
677 self.add_boxed(Box::new(component), Some(parent))
678 .expect("aylis: Ui::add com pai inexistente ou árvore funda demais")
679 }
680
681 pub fn add_root<T: Component>(&mut self, component: T) -> ComponentId {
683 self.add_boxed(Box::new(component), None).expect("sem pai não há como falhar")
684 }
685
686 pub fn add_boxed(
687 &mut self,
688 component: Box<dyn Component>,
689 parent: Option<ComponentId>,
690 ) -> Result<ComponentId> {
691 if let Some(p) = parent {
692 if !self.contains(p) {
693 return Err(Error::InvalidId);
694 }
695 if self.depth_of(p) + 1 > self.limits.0 {
696 return Err(too_deep(self.limits.0));
697 }
698 }
699 let id = self.alloc(Entry {
700 component: Some(component),
701 name: String::new(),
702 scope: parent.is_none(),
703 parent,
704 children: Vec::new(),
705 events: Vec::new(),
706 paint_hook: None,
707 visual: RefCell::default(),
708 bindings: Vec::new(),
709 });
710 match parent {
711 Some(p) => self.entry_mut(p).expect("verificado acima").children.push(id),
712 None => self.roots.push(id),
713 }
714 self.invalidate_form(id);
715 self.forget_references();
716 self.sync_timer(id);
717 if self.class_name(id) == Some(crate::intercept::INTERCEPTOR_CLASS) {
719 self.interceptors.forget();
720 }
721 Ok(id)
722 }
723
724 pub fn create(&mut self, class: &str, parent: Option<ComponentId>) -> Result<ComponentId> {
729 let (base, variant) = crate::registry::split_variant(class);
730 let create = self
731 .registry
732 .get(base)
733 .ok_or_else(|| Error::UnknownClass(base.to_string()))?
734 .create;
735 let id = self.add_boxed(create(), parent)?;
736 if let Some(variant) = variant {
737 self.apply_variant(id, base, variant)?;
738 }
739 Ok(id)
740 }
741
742 pub fn apply_variant(&mut self, id: ComponentId, class: &str, variant: &str) -> Result<()> {
745 if let Some(info) = self.registry.variant(class, variant).cloned() {
746 for (name, value) in info.props {
747 self.set_prop_quiet(id, &name, value)?;
748 }
749 } else if self.theme.style(&format!("{class}.{variant}")).is_none() {
750 return Err(Error::UnknownClass(format!("{class}.{variant}")));
751 }
752 if let Some(cb) = self.control_mut(id) {
753 cb.set_style(variant);
754 }
755 Ok(())
756 }
757
758 pub fn register_variant(&mut self, class: &str, name: &str, caption: &str, props: Vec<(&str, PropValue)>) {
760 self.registry.register_variant(crate::registry::VariantInfo {
761 class: class.to_string(),
762 name: name.to_string(),
763 caption: caption.to_string(),
764 props: props.into_iter().map(|(k, v)| (k.to_string(), v)).collect(),
765 });
766 }
767
768 pub fn variants_of(&self, class: &str) -> Vec<crate::registry::VariantInfo> {
771 let mut out: Vec<crate::registry::VariantInfo> = self.registry.variants_of(class).cloned().collect();
772 for name in self.theme.variants_of(class) {
773 if !out.iter().any(|v| v.name.eq_ignore_ascii_case(&name)) {
774 out.push(crate::registry::VariantInfo { class: class.to_string(), caption: name.clone(), name, props: Vec::new() });
775 }
776 }
777 out
778 }
779
780 pub fn free(&mut self, id: ComponentId) -> bool {
785 self.free_many(&[id]) > 0
786 }
787
788 pub fn free_many(&mut self, ids: &[ComponentId]) -> usize {
794 let mut doomed = Vec::new();
795 let mut doomed_set = std::collections::HashSet::new();
796 let mut tops = Vec::new();
797 for &id in ids {
798 if self.contains(id) && !doomed_set.contains(&id) {
799 let start = doomed.len();
800 self.collect_subtree(id, &mut doomed);
801 doomed_set.extend(doomed[start..].iter().copied());
802 tops.push(id);
803 }
804 }
805 if tops.is_empty() {
806 return 0;
807 }
808 let gone = |c: &ComponentId| doomed_set.contains(c);
809 let freed_forms: Vec<ComponentId> = doomed.iter().copied().filter(|&d| self.class_name(d) == Some("Form")).collect();
811 let orphaned: Vec<(ComponentId, &'static str)> = self.referrers_of_all(&doomed).into_iter().filter(|(c, _)| !gone(c)).collect();
814 let named = doomed.iter().any(|&d| self.name(d).is_some_and(|n| !n.is_empty()));
817 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() };
819 for &id in &tops {
820 self.detach(id);
821 }
822 for &d in &doomed {
823 let slot = &mut self.slots[d.index as usize];
824 if let Some(key) = slot.entry.as_ref().and_then(|e| e.visual.borrow_mut().layer_key.take()) {
826 self.dead_layers.get_mut().push(key);
827 }
828 slot.entry = None;
829 slot.generation = slot.generation.wrapping_add(1);
830 self.free_slots.push(d.index);
831 }
832 self.pending.retain(|(sender, _, _, _)| !gone(sender));
833 self.color_names.retain(|(c, _), _| !gone(c));
834 self.drop_tasks_of(&doomed);
835 self.forget_instances(&doomed);
836 self.forget_questions(&doomed);
837 self.animations.retain(|a| !gone(&a.target) && a.owner.is_none_or(|o| !gone(&o)));
838 self.input.retain(|root, _| !gone(root));
839 self.forget_forms(&doomed);
840 self.appear_waiting = None;
841 self.hover_within_hosts = None;
842 for t in self.timers.extract_if(.., |t| gone(&t.id)).collect::<Vec<_>>() {
843 t.stop();
844 }
845 for state in self.input.values_mut() {
846 state.forget(&doomed);
847 }
848 for slot in &mut self.slots {
849 if let Some(c) = slot.entry.as_mut().and_then(|e| e.component.as_mut()) {
850 for &d in &doomed {
851 c.notification(d);
852 }
853 if let Some(cb) = c.control_mut() {
854 if cb.popup_menu.is_some_and(|m| gone(&m)) {
855 cb.popup_menu = None;
856 }
857 cb.forget_drag_image(&doomed);
858 }
859 }
860 }
861 self.prune_references(&doomed_set);
864 for (scope, items) in leaving {
865 self.names_removed(scope, &items);
866 }
867 self.forget_scopes(&doomed);
868 let before = self.origins.len();
870 self.origins.retain(|c, o| !gone(c) && !gone(o));
871 if self.origins.len() != before {
872 self.forget_names();
873 }
874 for (c, prop) in orphaned {
875 if matches!(self.get_prop(c, prop), Ok(PropValue::Component(Some(t))) if gone(&t) || !self.contains(t)) {
876 let _ = self.set_prop(c, prop, PropValue::Component(None));
877 }
878 }
879 let dependents: Vec<ComponentId> = self
881 .components()
882 .filter(|&c| self.component(c).and_then(|c| c.popup()).and_then(|p| p.dies_with()).is_some_and(|o| gone(&o)))
883 .collect();
884 self.free_many(&dependents);
885 if !freed_forms.is_empty() {
886 if let Some(hook) = self.busy.freed_hook.clone() {
887 hook(self, &freed_forms);
888 }
889 }
890 self.invalidate();
891 tops.len()
892 }
893
894 fn collect_subtree(&self, id: ComponentId, out: &mut Vec<ComponentId>) {
895 out.push(id);
896 if let Some(e) = self.entry(id) {
897 for &c in &e.children {
898 self.collect_subtree(c, out);
899 }
900 }
901 }
902
903 fn detach(&mut self, id: ComponentId) {
905 match self.entry(id).and_then(|e| e.parent) {
906 Some(p) => {
907 if let Some(e) = self.entry_mut(p) {
908 e.children.retain(|c| *c != id);
909 }
910 }
911 None => self.roots.retain(|r| *r != id),
912 }
913 }
914
915 pub fn contains(&self, id: ComponentId) -> bool {
920 self.entry(id).is_some()
921 }
922
923 pub fn parent(&self, id: ComponentId) -> Option<ComponentId> {
924 self.entry(id)?.parent
925 }
926
927 pub fn children(&self, id: ComponentId) -> &[ComponentId] {
929 self.entry(id).map_or(&[], |e| e.children.as_slice())
930 }
931
932 pub fn roots(&self) -> &[ComponentId] {
933 &self.roots
934 }
935
936 pub fn root_of(&self, id: ComponentId) -> ComponentId {
938 let mut current = id;
939 while let Some(p) = self.parent(current) {
940 current = p;
941 }
942 current
943 }
944
945 fn depth_of(&self, id: ComponentId) -> usize {
948 let mut depth = 1;
949 let mut current = self.parent(id);
950 while let Some(c) = current {
951 depth += 1;
952 current = self.parent(c);
953 }
954 depth
955 }
956
957 fn height_of(&self, id: ComponentId) -> usize {
959 let mut height = 0;
960 let mut stack = vec![(id, 1)];
961 while let Some((node, level)) = stack.pop() {
962 height = height.max(level);
963 stack.extend(self.children(node).iter().map(|&c| (c, level + 1)));
964 }
965 height
966 }
967
968 pub fn set_parent(&mut self, id: ComponentId, parent: Option<ComponentId>) -> Result<()> {
969 if !self.contains(id) {
970 return Err(Error::InvalidId);
971 }
972 let old_root = self.root_of(id);
973 let old_scope = self.name_scope_of(id);
974 let was_scope = self.is_name_scope(id);
975 let moving = self.names_with(id);
976 if let Some(p) = parent {
977 if !self.contains(p) {
978 return Err(Error::InvalidId);
979 }
980 let mut current = Some(p);
981 while let Some(c) = current {
982 if c == id {
983 return Err(Error::Cycle);
984 }
985 current = self.parent(c);
986 }
987 if self.depth_of(p) + self.height_of(id) > self.limits.0 {
988 return Err(too_deep(self.limits.0));
989 }
990 let new_scope = self.form_of(p);
994 if !self.origins.contains_key(&id) && self.name_scope_of(id) != Some(new_scope) {
995 let mut moving = Vec::new();
996 self.collect_scope(id, &mut moving);
997 for &n in &moving {
998 let name = &self.entry(n).expect("subárvore válida").name;
999 if self.find_in(new_scope, name).is_some_and(|other| other != n) {
1000 return Err(Error::DuplicateName(name.clone()));
1001 }
1002 }
1003 }
1004 }
1005 self.detach(id);
1006 let entry = self.entry_mut(id).expect("verificado acima");
1007 entry.parent = parent;
1008 entry.scope |= parent.is_none();
1010 match parent {
1011 Some(p) => self.entry_mut(p).expect("verificado acima").children.push(id),
1012 None => self.roots.push(id),
1013 }
1014 if let Some(cb) = self.cb_mut(id) {
1015 cb.anchor_ref = None;
1016 }
1017 self.invalidate_form(old_root);
1019 self.invalidate_form(id);
1020 let new_scope = self.name_scope_of(id);
1023 if was_scope || parent.is_some() {
1024 if old_scope != new_scope {
1025 self.names_removed(old_scope, &moving);
1026 self.names_added(new_scope, &moving);
1027 }
1028 } else {
1029 self.forget_scope(old_scope);
1031 self.forget_scopes(&[id]);
1032 }
1033 Ok(())
1034 }
1035
1036 pub fn set_child_index(&mut self, id: ComponentId, index: usize) -> Result<()> {
1038 let parent = self.entry(id).ok_or(Error::InvalidId)?.parent;
1039 let list = match parent {
1040 Some(p) => &mut self.entry_mut(p).expect("pai válido").children,
1041 None => &mut self.roots,
1042 };
1043 list.retain(|c| *c != id);
1044 list.insert(index.min(list.len()), id);
1045 self.invalidate_form(id);
1046 self.names_removed(None, &[]);
1048 Ok(())
1049 }
1050
1051 pub fn name(&self, id: ComponentId) -> Option<&str> {
1056 self.entry(id).map(|e| e.name.as_str())
1057 }
1058
1059 pub fn set_name(&mut self, id: ComponentId, name: &str) -> Result<()> {
1065 if !self.contains(id) {
1066 return Err(Error::InvalidId);
1067 }
1068 if !name.is_empty() {
1069 if !is_identifier(name) {
1070 return Err(Error::InvalidName(name.to_string()));
1071 }
1072 let other = self.name_scope_of(id).and_then(|scope| self.find_in(scope, name));
1075 if other.is_some_and(|o| o != id) {
1076 return Err(Error::DuplicateName(name.to_string()));
1077 }
1078 }
1079 let old = std::mem::replace(&mut self.entry_mut(id).expect("verificado acima").name, name.to_string());
1080 let scope = self.name_scope_of(id);
1081 self.names_removed(scope, &[(id, old)]);
1082 self.names_added(scope, &[(id, name.to_string())]);
1083 Ok(())
1084 }
1085
1086 pub fn free_name_in(&self, parent: ComponentId, base: &str) -> String {
1090 let scope = self.form_of(parent);
1091 if self.find_in(scope, base).is_none() {
1092 return base.to_string();
1093 }
1094 let first = self.next_suffix(scope, base);
1096 let n = (first..).find(|n| self.find_in(scope, &format!("{base}{n}")).is_none()).expect("sempre há um número livre");
1097 self.set_next_suffix(scope, base, n + 1);
1098 format!("{base}{n}")
1099 }
1100
1101 pub fn find(&self, name: &str) -> Option<ComponentId> {
1105 if name.is_empty() {
1106 return None;
1107 }
1108 self.indexed_find(name)
1109 }
1110
1111 pub(crate) fn find_deep(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1112 let e = self.entry(id)?;
1113 if e.name.eq_ignore_ascii_case(name) {
1114 return Some(id);
1115 }
1116 e.children.iter().find_map(|&c| self.find_deep(c, name))
1117 }
1118
1119 pub fn find_in(&self, scope: ComponentId, name: &str) -> Option<ComponentId> {
1123 let e = self.entry(scope)?;
1124 if !name.is_empty() && e.name.eq_ignore_ascii_case(name) {
1125 return Some(scope);
1126 }
1127 self.find_below(scope, name)
1128 }
1129
1130 fn find_below(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1133 if name.is_empty() {
1134 return None;
1135 }
1136 if self.is_name_scope(id) { self.indexed_find_in_scope(id, name) } else { self.find_in_children(id, name) }
1137 }
1138
1139 pub(crate) fn find_in_children(&self, id: ComponentId, name: &str) -> Option<ComponentId> {
1140 self.scope_children(id).find_map(|c| {
1141 let e = self.entry(c)?;
1142 if !name.is_empty() && e.name.eq_ignore_ascii_case(name) {
1143 Some(c)
1144 } else if e.scope {
1145 None
1146 } else {
1147 self.find_in_children(c, name)
1148 }
1149 })
1150 }
1151
1152 pub fn find_path(&self, path: &str) -> Option<ComponentId> {
1156 let mut parts = path.split('.');
1157 let first = parts.next()?;
1158 let mut current = self
1159 .roots
1160 .iter()
1161 .copied()
1162 .find(|&r| self.entry(r).is_some_and(|e| e.name.eq_ignore_ascii_case(first)))
1163 .or_else(|| self.find(first))?;
1164 for part in parts {
1165 current = self.find_below(current, part)?;
1166 }
1167 Some(current)
1168 }
1169
1170 pub fn path_of(&self, id: ComponentId) -> String {
1172 let mut parts = vec![self.name(id).unwrap_or_default().to_string()];
1173 let mut scope = self.name_scope_of(id);
1174 while let Some(s) = scope {
1175 parts.push(self.name(s).unwrap_or_default().to_string());
1176 scope = self.name_scope_of(s);
1177 }
1178 parts.reverse();
1179 parts.join(".")
1180 }
1181
1182 pub fn resolve_reference(&self, from: ComponentId, text: &str) -> Option<ComponentId> {
1187 if text.contains('.') {
1188 return self.find_path(text);
1189 }
1190 let mut scope = Some(self.form_of(from));
1191 while let Some(s) = scope {
1192 if let Some(found) = self.find_in(s, text) {
1193 return Some(found);
1194 }
1195 scope = self.name_scope_of(s);
1196 }
1197 None
1198 }
1199
1200 pub fn reference_name(&self, from: ComponentId, target: ComponentId) -> Option<String> {
1204 let name = self.name(target).filter(|n| !n.is_empty())?;
1205 if self.resolve_reference(from, name) == Some(target) {
1206 Some(name.to_string())
1207 } else {
1208 Some(self.path_of(target))
1209 }
1210 }
1211
1212 pub fn form_of(&self, id: ComponentId) -> ComponentId {
1215 let mut current = id;
1216 loop {
1217 match self.entry(current) {
1218 Some(e) if !e.scope => match self.scope_parent(current) {
1219 Some(p) => current = p,
1220 None => return current,
1221 },
1222 _ => return current,
1223 }
1224 }
1225 }
1226
1227 pub fn name_scope_of(&self, id: ComponentId) -> Option<ComponentId> {
1229 self.scope_parent(id).map(|p| self.form_of(p))
1230 }
1231
1232 pub(crate) fn outer_form(&self, form: ComponentId) -> Option<ComponentId> {
1235 self.scope_parent(form).map(|p| self.form_of(p))
1236 }
1237
1238 fn scope_parent(&self, id: ComponentId) -> Option<ComponentId> {
1240 if !self.origins.is_empty() {
1241 if let Some(&origin) = self.origins.get(&id) {
1242 return Some(origin);
1243 }
1244 }
1245 self.parent(id)
1246 }
1247
1248 pub fn scope_children(&self, id: ComponentId) -> impl Iterator<Item = ComponentId> + '_ {
1252 let plain = self.origins.is_empty();
1253 let tree = self.children(id).iter().copied().filter(move |c| plain || !self.origins.contains_key(c));
1254 let adopted = self.origins.iter().filter(move |&(_, &o)| !plain && o == id).map(|(&c, _)| c);
1255 tree.chain(adopted)
1256 }
1257
1258 pub fn set_origin_scope(&mut self, id: ComponentId, origin: Option<ComponentId>) {
1265 if !self.contains(id) {
1266 return;
1267 }
1268 let changed = match origin.filter(|&o| self.contains(o) && o != id) {
1269 Some(o) => self.origins.insert(id, o) != Some(o),
1270 None => self.origins.remove(&id).is_some(),
1271 };
1272 if changed {
1273 self.forget_names();
1274 self.forget_references();
1275 }
1276 }
1277
1278 pub fn origin_scope(&self, id: ComponentId) -> Option<ComponentId> {
1280 self.origins.get(&id).copied()
1281 }
1282
1283 pub fn set_name_scope(&mut self, id: ComponentId, scope: bool) {
1286 if let Some(e) = self.entry_mut(id) {
1287 e.scope = scope || e.parent.is_none();
1288 }
1289 self.forget_scope(self.name_scope_of(id));
1290 self.forget_scopes(&[id]);
1291 }
1292
1293 pub fn is_name_scope(&self, id: ComponentId) -> bool {
1294 self.entry(id).is_some_and(|e| e.scope)
1295 }
1296
1297 pub(crate) fn collect_scope(&self, id: ComponentId, out: &mut Vec<ComponentId>) {
1300 out.push(id);
1301 if self.entry(id).is_some_and(|e| e.scope) {
1302 return;
1303 }
1304 let children: Vec<ComponentId> = self.scope_children(id).collect();
1305 for c in children {
1306 self.collect_scope(c, out);
1307 }
1308 }
1309
1310 pub fn class_name(&self, id: ComponentId) -> Option<&'static str> {
1315 Some(self.component(id)?.class_name())
1316 }
1317
1318 pub fn component(&self, id: ComponentId) -> Option<&dyn Component> {
1319 self.entry(id)?.component.as_deref()
1320 }
1321
1322 pub fn component_mut(&mut self, id: ComponentId) -> Option<&mut dyn Component> {
1323 self.invalidate_form(id);
1325 self.request_repaint();
1326 self.forget_references();
1327 self.entry_mut(id)?.component.as_deref_mut()
1328 }
1329
1330 pub fn get<T: Component>(&self, id: ComponentId) -> Option<&T> {
1333 find_layer(self.component(id)?)
1334 }
1335
1336 pub fn get_mut<T: Component>(&mut self, id: ComponentId) -> Option<&mut T> {
1337 self.invalidate_form(id);
1338 self.request_repaint();
1339 self.forget_references();
1340 find_layer_mut(self.entry_mut(id)?.component.as_deref_mut()?)
1341 }
1342
1343 pub fn control(&self, id: ComponentId) -> Option<&ControlBase> {
1345 self.cb(id)
1346 }
1347
1348 pub fn control_mut(&mut self, id: ComponentId) -> Option<&mut ControlBase> {
1349 self.invalidate_form(id);
1350 self.cb_mut(id)
1351 }
1352
1353 pub fn bounds(&mut self, id: ComponentId) -> Option<RectF> {
1358 self.update_layout();
1359 self.laid_out_bounds(id)
1360 }
1361
1362 pub fn laid_out_bounds(&self, id: ComponentId) -> Option<RectF> {
1364 Some(self.cb(id)?.bounds)
1365 }
1366
1367 pub fn set_safe_area(&mut self, root: ComponentId, insets: Bounds) {
1375 let Some(cb) = self.cb_mut(root) else { return };
1376 if cb.safe_area != insets {
1377 cb.safe_area = insets;
1378 self.invalidate_form(root);
1379 }
1380 }
1381
1382 pub fn safe_area(&self, root: ComponentId) -> Bounds {
1383 self.cb(root).map_or_else(Bounds::default, |cb| cb.safe_area)
1384 }
1385
1386 pub fn to_form(&self, id: ComponentId, rect_in_parent: RectF) -> RectF {
1387 let Some(parent) = self.parent(id) else { return rect_in_parent };
1388 let origin = self.absolute_rect(parent).map_or(crate::geometry::PointF::ZERO, |r| r.origin());
1389 let k = self.inner_scale(parent);
1391 if k == 1.0 {
1392 rect_in_parent.offset(origin.x, origin.y)
1393 } else {
1394 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)
1395 }
1396 }
1397
1398 pub fn inner_scale(&self, id: ComponentId) -> f32 {
1401 let mut k = 1.0;
1402 let mut current = Some(id);
1403 while let Some(c) = current {
1404 if let Some(cb) = self.cb(c) {
1405 k *= cb.scale();
1406 }
1407 current = self.parent(c);
1408 }
1409 k
1410 }
1411
1412 pub fn native_views(&self, form: ComponentId) -> Vec<crate::NativeViewSlot> {
1416 let mut out = Vec::new();
1417 if self.design_mode() {
1418 return out;
1419 }
1420 let mut stack = vec![(form, true)];
1421 while let Some((id, shown)) = stack.pop() {
1422 let shown = shown && self.control(id).is_none_or(|c| c.visible());
1423 if let Some(view) = self.component(id).and_then(|c| c.platform_hooks()).and_then(|h| h.native_view()) {
1424 let rect = self.absolute_rect(id).unwrap_or_default();
1428 let mut clip: Option<RectF> = None;
1431 let mut parent = self.parent(id);
1432 while let Some(p) = parent {
1433 if self.control(p).is_some_and(|cb| cb.clip_children()) {
1434 let r = self.absolute_rect(p).unwrap_or_default();
1435 clip = Some(clip.map_or(r, |c| c.intersect(r).unwrap_or(RectF::new(r.x, r.y, 0.0, 0.0))));
1436 }
1437 parent = self.parent(p);
1438 }
1439 let clip = clip.filter(|c| !(c.x <= rect.x && c.y <= rect.y && c.right() >= rect.right() && c.bottom() >= rect.bottom()));
1440 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));
1441 let commands = self.component(id).and_then(|c| c.platform_hooks()).map(|h| h.take_native_commands()).unwrap_or_default();
1442 out.push(crate::NativeViewSlot { id, rect, clip, visible, view, commands });
1443 }
1444 for c in self.children(id) {
1445 stack.push((*c, shown));
1446 }
1447 }
1448 out
1449 }
1450
1451 pub fn absolute_rect(&self, id: ComponentId) -> Option<RectF> {
1454 let mut rect = self.laid_out_bounds(id)?;
1455 let mut parent = self.parent(id);
1456 while let Some(p) = parent {
1457 if let Some(cb) = self.cb(p) {
1458 let (b, s) = (cb.bounds, cb.scale());
1459 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) };
1460 }
1461 parent = self.parent(p);
1462 }
1463 Some(rect)
1464 }
1465
1466 pub fn register_class<T: Component + Default>(&mut self, category: &'static str) {
1472 let name = T::default().class_name();
1473 self.registry.register(ClassInfo { name, category, create: create_default::<T> });
1474 }
1475
1476 pub fn registry(&self) -> &ClassRegistry {
1477 &self.registry
1478 }
1479
1480 pub fn registry_mut(&mut self) -> &mut ClassRegistry {
1481 &mut self.registry
1482 }
1483
1484 pub fn theme(&self) -> &Theme {
1485 &self.theme
1486 }
1487
1488 pub fn theme_mut(&mut self) -> &mut Theme {
1489 self.request_repaint();
1490 self.recolored.borrow_mut().clear();
1491 std::sync::Arc::make_mut(&mut self.theme)
1492 }
1493
1494 pub fn shared_theme(&self) -> std::sync::Arc<Theme> {
1496 self.theme.clone()
1497 }
1498
1499 pub fn set_theme(&mut self, theme: Theme) {
1501 self.set_shared_theme(std::sync::Arc::new(theme));
1502 }
1503
1504 pub fn set_shared_theme(&mut self, mut theme: std::sync::Arc<Theme>) {
1508 if !self.palette.is_empty() {
1509 std::sync::Arc::make_mut(&mut theme).apply_palette(&self.palette);
1510 }
1511 if !self.project_font.is_empty() && theme.fonts.values().any(|f| f.family != self.project_font && f.family != "monospace" && !f.family.to_lowercase().contains("mono")) {
1514 std::sync::Arc::make_mut(&mut theme).apply_font_family(&self.project_font);
1515 }
1516 self.theme = theme;
1517 self.recolored.borrow_mut().clear();
1518 self.refresh_color_names();
1519 self.request_repaint();
1520 }
1521
1522 pub fn set_project_font(&mut self, family: &str) {
1525 self.project_font = family.to_string();
1526 if family.is_empty() {
1527 return;
1528 }
1529 std::sync::Arc::make_mut(&mut self.theme).apply_font_family(family);
1530 for t in &mut self.themes {
1531 std::sync::Arc::make_mut(t).apply_font_family(family);
1532 }
1533 self.recolored.borrow_mut().clear();
1534 self.invalidate();
1536 }
1537
1538 pub fn project_font(&self) -> &str {
1540 &self.project_font
1541 }
1542
1543 pub fn set_palette(&mut self, palette: crate::palette::Palette) {
1546 self.palette = palette;
1547 if !self.palette.is_empty() {
1549 std::sync::Arc::make_mut(&mut self.theme).apply_palette(&self.palette);
1550 for t in &mut self.themes {
1551 std::sync::Arc::make_mut(t).apply_palette(&self.palette);
1552 }
1553 }
1554 self.recolored.borrow_mut().clear();
1555 self.refresh_color_names();
1556 self.request_repaint();
1557 }
1558
1559 pub fn palette(&self) -> &crate::palette::Palette {
1560 &self.palette
1561 }
1562
1563 pub fn scroll_options(&self) -> crate::ScrollOptions {
1566 self.scroll_options
1567 }
1568
1569 pub fn set_scroll_options(&mut self, options: crate::ScrollOptions) {
1570 self.scroll_options = options;
1571 }
1572
1573 pub fn color_names(&self) -> Vec<String> {
1575 let mut names: Vec<String> = self.theme.colors.keys().cloned().collect();
1576 names.sort();
1577 names
1578 }
1579
1580 pub fn color_name(&self, id: ComponentId, prop: &str) -> Option<&str> {
1582 let (name, given) = self.color_names.get(&(id, prop.to_string()))?;
1583 let now = self.component(id).and_then(|c| crate::component::read_prop(c, prop));
1585 match now {
1586 Some(v) if v != PropValue::Color(*given) => None,
1587 _ => Some(name.as_str()),
1588 }
1589 }
1590
1591 pub fn refresh_color_names(&mut self) {
1593 let names: Vec<(ComponentId, String)> = self.color_names.keys().cloned().collect();
1594 for (id, prop) in names {
1595 let Some(spec) = self.color_name(id, &prop).filter(|_| self.contains(id)).map(str::to_string) else {
1597 self.color_names.remove(&(id, prop));
1598 continue;
1599 };
1600 let _ = self.set_prop_quiet(id, &prop, PropValue::String(spec));
1601 }
1602 }
1603
1604 pub fn register_theme(&mut self, mut theme: Theme) {
1608 theme.apply_palette(&self.palette);
1609 self.recolored.borrow_mut().clear();
1610 match self.themes.iter_mut().find(|t| t.name.eq_ignore_ascii_case(&theme.name)) {
1611 Some(t) => *t = std::sync::Arc::new(theme),
1612 None => self.themes.push(std::sync::Arc::new(theme)),
1613 }
1614 self.request_repaint();
1615 }
1616
1617 pub fn background_color(&self, id: ComponentId) -> crate::Color {
1621 let Some(component) = self.component(id) else { return crate::Color::TRANSPARENT };
1622 let Some(cb) = component.control() else { return crate::Color::TRANSPARENT };
1623 let mut classes = Vec::new();
1624 component.class_chain(&mut classes);
1625 let base = match cb.theme_name() {
1626 "" => self.theme(),
1627 name => self.theme_named(name).unwrap_or(self.theme()),
1628 };
1629 let theme = self.mixed_theme(base, &classes);
1630 theme.resolve(&classes, cb.style(), cb.state()).fill
1631 }
1632
1633 pub fn theme_named(&self, name: &str) -> Option<&Theme> {
1637 if self.theme.name.eq_ignore_ascii_case(name) {
1638 return Some(&self.theme);
1639 }
1640 self.themes
1641 .iter()
1642 .find(|t| t.name.eq_ignore_ascii_case(name))
1643 .map(|t| &**t)
1644 .or_else(|| crate::themes::builtin(name))
1645 .or_else(|| crate::themes::of_family(name, self.theme.dark))
1647 }
1648
1649 pub fn theme_names(&self) -> Vec<String> {
1651 let mut names: Vec<String> = vec![self.theme.name.clone()];
1652 let others = self.themes.iter().map(|t| t.name.clone()).chain(crate::themes::all().iter().map(|t| t.name.clone()));
1653 for n in others {
1654 if !names.iter().any(|x| x.eq_ignore_ascii_case(&n)) {
1655 names.push(n);
1656 }
1657 }
1658 names
1659 }
1660
1661 pub fn theme_source(&self, id: ComponentId) -> (String, ThemeSource) {
1663 let mut cur = Some(id);
1664 let mut inherited: Option<(&Theme, ThemeSource)> = None;
1665 while let Some(c) = cur {
1666 if let Some(name) = self.control(c).map(|cb| cb.theme_name()).filter(|n| !n.is_empty()) {
1667 if let Some(t) = self.theme_named(name) {
1668 let source = if c == id { ThemeSource::Own } else { ThemeSource::Inherited(c) };
1669 inherited = Some((t, source));
1670 break;
1671 }
1672 }
1673 cur = self.parent(c);
1674 }
1675 let (base, source) = inherited.unwrap_or((&self.theme, ThemeSource::App));
1676 let mut classes = Vec::new();
1677 if let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) {
1678 component.class_chain(&mut classes);
1679 }
1680 if let Some(class) = classes.iter().find(|c| base.components.contains_key(**c)) {
1681 let mixed = self.mixed_theme(base, &classes);
1682 if !std::ptr::eq(mixed, base) {
1683 return (mixed.name.clone(), ThemeSource::Class(class.to_string()));
1684 }
1685 }
1686 (base.name.clone(), source)
1687 }
1688
1689 pub fn theme_of(&self, id: ComponentId) -> &Theme {
1692 let mut inherited: &Theme = &self.theme;
1693 let mut cur = Some(id);
1694 while let Some(c) = cur {
1695 if let Some(name) = self.control(c).map(|cb| cb.theme_name()).filter(|n| !n.is_empty()) {
1696 if let Some(t) = self.theme_named(name) {
1697 inherited = t;
1698 break;
1699 }
1700 }
1701 cur = self.parent(c);
1702 }
1703 let mut classes = Vec::new();
1704 if let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) {
1705 component.class_chain(&mut classes);
1706 }
1707 self.mixed_theme(inherited, &classes)
1708 }
1709
1710 pub(crate) fn mixed_theme<'a>(&'a self, theme: &'a Theme, classes: &[&str]) -> &'a Theme {
1712 theme.mixed_for(classes).and_then(|name| self.theme_named(name)).unwrap_or(theme)
1713 }
1714
1715 pub fn register_icon(&mut self, name: &str, icon: crate::icons::Icon) {
1717 self.icons.insert(name.to_string(), icon);
1718 self.request_repaint();
1719 }
1720
1721 pub fn register_icon_svg(&mut self, name: &str, stroke: &str, fill: &str, size: f32) -> crate::Result<()> {
1723 let icon = crate::icons::Icon::from_svg(stroke, fill, size)
1724 .ok_or_else(|| crate::Error::invalid(format!("caminho SVG inválido no ícone '{name}'")))?;
1725 self.register_icon(name, icon);
1726 Ok(())
1727 }
1728
1729 pub fn register_icon_pack(&mut self, prefix: &str, text: &str) -> crate::Result<usize> {
1732 let pack = crate::icons::parse_pack(text).map_err(crate::Error::invalid)?;
1733 let mut n = 0;
1734 for (name, d) in &pack.icons {
1735 if let Some(icon) = pack.build(d) {
1736 self.icons.insert(format!("{prefix}:{name}"), icon);
1737 n += 1;
1738 }
1739 }
1740 self.request_repaint();
1741 Ok(n)
1742 }
1743
1744 pub fn has_icon_pack(&self, prefix: &str) -> bool {
1747 let start = format!("{prefix}:");
1748 self.icons.keys().any(|k| k.starts_with(&start))
1749 }
1750
1751 pub fn icon(&self, name: &str) -> Option<&crate::icons::Icon> {
1755 fn missing_icon_warning(name: &str) {
1756 static WARNED: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
1757 let Some((pack, icon)) = name.split_once(':') else { return };
1758 let word = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
1759 if !word(pack) || !word(icon) {
1760 return;
1761 }
1762 if WARNED.lock().is_ok_and(|mut w| w.insert(name.to_string())) {
1763 crate::stderr_line!("aylis: o ícone '{name}' não está no app (o pacote assets/icons/{pack}.txt não o tem; gere o código ou recompile para o build.rs incluí-lo)");
1764 }
1765 }
1766 let icon = self.icons.get(name).or_else(|| crate::icons::builtin(name));
1767 if cfg!(debug_assertions) && icon.is_none() {
1768 missing_icon_warning(name);
1769 }
1770 icon
1771 }
1772
1773 pub fn services(&self) -> &Services {
1774 &self.services
1775 }
1776
1777 pub fn services_mut(&mut self) -> &mut Services {
1778 &mut self.services
1779 }
1780
1781 pub fn set_services(&mut self, services: Services) {
1782 self.services = services;
1783 }
1784
1785 pub fn measure_text(&self, text: &str, style: &TextStyle) -> SizeF {
1788 if self.text_mode != crate::textcore::TextMode::Native {
1789 if let Some(size) = crate::textcore::measure(text, style, None) {
1790 return size;
1791 }
1792 }
1793 match &self.services.text {
1794 Some(service) => service.measure(text, style, None),
1795 None => SizeF::new(text.chars().count() as f32 * style.font.size * 0.55, style.font.size * 1.3),
1796 }
1797 }
1798
1799 pub fn measure_text_wrapped(&self, text: &str, style: &TextStyle, max_width: f32) -> SizeF {
1802 if self.text_mode != crate::textcore::TextMode::Native {
1803 if let Some(size) = crate::textcore::measure(text, style, Some(max_width)) {
1804 return size;
1805 }
1806 }
1807 match &self.services.text {
1808 Some(service) => service.measure(text, style, Some(max_width)),
1809 None => {
1810 let one = self.measure_text(text, style);
1811 let lines = (one.width / max_width.max(1.0)).ceil().max(1.0);
1812 SizeF::new(one.width.min(max_width), one.height * lines)
1813 }
1814 }
1815 }
1816
1817 pub fn locale(&self) -> crate::platform::LocaleInfo {
1820 self.services.locale.as_ref().map(|l| l.locale()).unwrap_or_default()
1821 }
1822
1823 pub fn next_paint_wake(&self) -> Option<f64> {
1829 let forms = self.frame_requests.borrow().iter().filter(|(id, _)| self.contains(**id) && self.form_shown(**id)).filter_map(|(_, f)| f.1).reduce(f64::min);
1832 let controls = self.timed_frames.borrow().iter().filter(|(id, _)| self.contains(**id) && self.form_shown(**id)).map(|(_, t)| *t).reduce(f64::min);
1835 [forms, controls].into_iter().flatten().reduce(f64::min)
1836 }
1837
1838 pub fn next_wake(&self) -> Option<f64> {
1839 let painted = self.next_paint_wake();
1840 let paced = self.next_paced_paint();
1842 [painted, self.timers_wake(), paced].into_iter().flatten().reduce(f64::min)
1843 }
1844
1845 pub fn zoom(&self) -> f32 {
1849 self.zoom
1850 }
1851
1852 pub fn set_zoom(&mut self, zoom: f32) {
1856 let (min, max) = self.zoom_limits;
1857 let zoom = if zoom.is_finite() { zoom.clamp(min, max) } else { 1.0f32.clamp(min, max) };
1858 if (zoom - self.zoom).abs() > f32::EPSILON {
1859 self.zoom = zoom;
1860 for app in self.application_events() {
1861 self.fire(app, "on_zoom_change", &crate::EventArgs::Value(crate::PropValue::Float(f64::from(zoom))));
1862 }
1863 self.mark_zoom_changed();
1864 }
1865 }
1866
1867 pub fn form_zoom(&self, form: ComponentId) -> f32 {
1870 if self.physical_pixels(form) {
1871 return 1.0;
1872 }
1873 let own = match self.get_prop(form, "zoom") {
1874 Ok(PropValue::Float(z)) if z > 0.0 => z as f32,
1875 Ok(PropValue::Int(z)) if z > 0 => z as f32,
1876 _ => 1.0,
1877 };
1878 (self.zoom * own).clamp(0.25, 5.0)
1879 }
1880
1881 pub fn form_frame_reuse_kb(&self, form: ComponentId) -> Option<u32> {
1885 match self.get_prop(form, "frame_reuse_kb") {
1886 Ok(PropValue::Int(kb)) => crate::image_cache::form_frame_reuse(kb),
1887 _ => None,
1888 }
1889 }
1890
1891 pub fn form_blend_compositor(&self, form: ComponentId) -> Option<crate::gpu::BlendCompositor> {
1894 use crate::PropEnum;
1895 match self.get_prop(form, "blend_compositor") {
1896 Ok(PropValue::Enum(name)) => crate::gpu::FormBlendCompositor::from_name(&name).and_then(crate::gpu::FormBlendCompositor::own),
1897 _ => None,
1898 }
1899 }
1900
1901 pub fn mark_zoom_changed(&mut self) {
1903 self.zoom_changed = true;
1904 self.request_repaint();
1905 }
1906
1907 pub fn take_zoom_changed(&mut self) -> bool {
1909 std::mem::take(&mut self.zoom_changed)
1910 }
1911
1912 pub fn set_zoom_limits(&mut self, min: f32, max: f32) {
1915 let clean = |v: f32, d: f32| if v.is_finite() { v.clamp(0.25, 5.0) } else { d };
1916 let (min, max) = (clean(min, 0.25), clean(max, 5.0));
1917 self.zoom_limits = (min.min(max), max.max(min));
1918 let zoom = self.zoom;
1919 self.set_zoom(zoom);
1920 }
1921
1922 pub fn zoom_limits(&self) -> (f32, f32) {
1923 self.zoom_limits
1924 }
1925
1926 pub fn zoom_step(&mut self, direction: i32) {
1928 let zoom = match direction.signum() {
1929 0 => 1.0,
1930 d => ((self.zoom * 10.0).round() + d as f32) / 10.0,
1931 };
1932 self.set_zoom(zoom);
1933 }
1934
1935 pub fn zoom_keys(&self) -> bool {
1937 self.zoom_keys
1938 }
1939
1940 pub fn set_zoom_keys(&mut self, on: bool) {
1941 self.zoom_keys = on;
1942 }
1943
1944 pub fn set_font_names(&mut self, names: Vec<(String, String)>) {
1948 self.font_names = names;
1949 self.request_repaint();
1950 }
1951
1952 pub fn font_names(&self) -> &[(String, String)] {
1953 &self.font_names
1954 }
1955
1956 pub fn resolve_font(&self, family: &str) -> String {
1959 let mut current = family;
1960 for _ in 0..3 {
1961 match self.font_names.iter().find(|(name, _)| name == current) {
1962 Some((_, target)) => current = target,
1963 None => break,
1964 }
1965 }
1966 current.to_string()
1967 }
1968
1969 pub fn time(&self) -> f64 {
1971 self.time
1972 }
1973
1974 pub fn set_time(&mut self, seconds: f64) {
1975 self.time = seconds;
1976 }
1977
1978 pub fn advance(&mut self, seconds: f64) {
1981 self.time += seconds.max(0.0);
1982 self.run_timers();
1983 }
1984
1985 pub fn prop_infos(&self, id: ComponentId) -> Vec<PropInfo> {
1992 self.component(id).map(crate::component::prop_infos_of).unwrap_or_default()
1993 }
1994
1995 pub fn prop_info(&self, id: ComponentId, name: &str) -> Option<PropInfo> {
1996 crate::component::prop_info_of(self.component(id)?, name)
1997 }
1998
1999 pub fn get_prop(&self, id: ComponentId, name: &str) -> Result<PropValue> {
2005 self.read_prop(id, name, true)
2006 }
2007
2008 pub fn get_declared_prop(&self, id: ComponentId, name: &str) -> Result<PropValue> {
2010 self.read_prop(id, name, false)
2011 }
2012
2013 fn read_prop(&self, id: ComponentId, name: &str, laid_out: bool) -> Result<PropValue> {
2014 let entry = self.entry(id).ok_or(Error::InvalidId)?;
2015 if name == "name" {
2016 return Ok(PropValue::String(entry.name.clone()));
2017 }
2018 if let Some((head, field)) = name.split_once('.') {
2019 let bounds = self.get_prop(id, head)?.to_bounds().map_err(|e| e.with_property(head))?;
2020 return bounds_field(&bounds, field)
2021 .map(PropValue::from)
2022 .ok_or_else(|| Error::UnknownProperty(name.to_string()));
2023 }
2024 if entry.component.is_none() {
2027 return Err(Error::Busy(self.path_of(id)));
2028 }
2029 if laid_out && matches!(name, "width" | "height") && !self.design_mode
2036 && let Some(cb) = self.cb(id)
2037 && stretches(cb, name == "width")
2038 && self.shown_with_parents(id)
2039 {
2040 let b = cb.bounds();
2041 let real = if name == "width" { b.width } else { b.height };
2042 if real > 0.0 {
2043 return Ok(PropValue::Float(real as f64));
2044 }
2045 }
2046 let info = self.prop_info(id, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))?;
2047 if info.kind == PropKind::Color {
2048 if let Some(spec) = self.color_name(id, name) {
2049 return Ok(PropValue::String(spec.to_string()));
2050 }
2051 }
2052 if info.kind == PropKind::Event {
2053 let handler = entry.events.iter().find(|(n, _)| n == name).and_then(|(_, h)| match h {
2054 Handler::Named(n) => Some(n.clone()),
2055 Handler::Closure(_) => None,
2056 });
2057 return Ok(PropValue::Event(handler));
2058 }
2059 if self.design_mode && name == "visible" {
2060 if let Some(cb) = self.cb(id) {
2061 return Ok(PropValue::Bool(!cb.design_hidden));
2062 }
2063 }
2064 let component = entry.component.as_deref().ok_or_else(|| Error::Busy(self.path_of(id)))?;
2065 crate::component::read_prop(component, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))
2066 }
2067
2068 fn shown_with_parents(&self, id: ComponentId) -> bool {
2071 let mut current = Some(id);
2072 while let Some(c) = current {
2073 let parent = self.parent(c);
2074 if (c == id || parent.is_some()) && !self.cb(c).is_some_and(|cb| cb.visible()) {
2075 return false;
2076 }
2077 current = parent;
2078 }
2079 true
2080 }
2081
2082 pub fn set_prop(&mut self, id: ComponentId, name: &str, value: impl Into<PropValue>) -> Result<()> {
2089 let value = value.into();
2090 if !self.contains(id) {
2091 return Err(Error::InvalidId);
2092 }
2093 if name == "name" {
2094 let new_name = value.to_str().map_err(|e| e.with_property(name))?.to_string();
2095 return self.set_name(id, &new_name);
2096 }
2097 if let Some((head, field)) = name.split_once('.') {
2098 let mut bounds = self.get_prop(id, head)?.to_bounds().map_err(|e| e.with_property(head))?;
2099 let v = value.to_f32().map_err(|e| e.with_property(name))?;
2100 *bounds_field_mut(&mut bounds, field).ok_or_else(|| Error::UnknownProperty(name.to_string()))? = v;
2101 return self.set_prop(id, head, bounds);
2102 }
2103 if self.entry(id).is_some_and(|e| e.component.is_none()) {
2104 let error = Error::Busy(self.path_of(id));
2105 self.report_busy(&error);
2106 return Err(error);
2107 }
2108
2109 let info = self.prop_info(id, name).ok_or_else(|| Error::UnknownProperty(name.to_string()))?;
2110 if info.read_only {
2111 return Err(Error::ReadOnly(name.to_string()));
2112 }
2113 if matches!(name, "trigger" | "enabled") && info.category == "Animation" {
2115 self.appear_waiting = None;
2116 self.hover_within_hosts = None;
2117 }
2118 let mut color_name = None;
2121 let value = match (&info.kind, value) {
2122 (PropKind::Color, PropValue::String(spec)) if crate::palette::is_named(&spec) && !spec.trim().eq_ignore_ascii_case("none") => {
2125 let color = self
2126 .theme
2127 .resolve_color(&spec)
2128 .ok_or_else(|| Error::invalid(format!("cor desconhecida '{spec}' (use #hex ou um nome: {})", self.color_names().join(", "))).with_property(name))?;
2129 color_name = Some((spec, color));
2130 PropValue::Color(color)
2131 }
2132 (PropKind::Color, PropValue::String(spec)) if is_hex_with_opacity(&spec) => {
2135 let color = crate::palette::resolve_in(&HashMap::new(), &spec)
2136 .ok_or_else(|| Error::invalid(format!("cor inválida '{spec}' (use #hex, #hex/NN ou um nome)")).with_property(name))?;
2137 PropValue::Color(color)
2138 }
2139 (_, v) => v,
2140 };
2141 if info.kind == PropKind::Color {
2142 match &color_name {
2143 Some(spec) => {
2144 self.color_names.insert((id, name.to_string()), spec.clone());
2145 }
2146 None => {
2147 self.color_names.remove(&(id, name.to_string()));
2148 }
2149 }
2150 }
2151 if info.kind == PropKind::Component {
2152 self.forget_references();
2153 }
2154 let value = match info.kind {
2155 PropKind::Event => {
2156 let handler = value.to_event().map_err(|e| e.with_property(name))?;
2157 if let Some(h) = handler.as_deref().filter(|h| !is_identifier(h)) {
2159 return Err(Error::invalid(format!("nome de handler inválido '{h}' (letras, dígitos e _, sem começar por dígito)")).with_property(name));
2160 }
2161 self.set_event_handler(id, name, handler.map(Handler::Named));
2162 return Ok(());
2163 }
2164 PropKind::Component => match &value {
2165 PropValue::String(target) | PropValue::Enum(target) => {
2166 if target.is_empty() {
2167 PropValue::Component(None)
2168 } else {
2169 let found = self
2170 .resolve_reference(id, target)
2171 .ok_or_else(|| Error::ComponentNotFound(target.clone()))?;
2172 PropValue::Component(Some(found))
2173 }
2174 }
2175 _ => value,
2176 },
2177 _ => value,
2178 };
2179 let value = if self.design_mode && name == "visible" && self.cb(id).is_some() {
2183 let hidden = !value.to_bool().map_err(|e| e.with_property(name))?;
2184 let shown = !hidden || self.design_revealed(id);
2185 let cb = self.cb_mut(id).expect("verificado acima");
2186 cb.design_hidden = hidden;
2187 cb.set_visible(shown);
2189 PropValue::Bool(cb.visible())
2190 } else {
2191 value
2192 };
2193
2194 let paint_only = info.kind == PropKind::Color
2197 || PAINT_ONLY.contains(&name)
2198 || self.entry(id).and_then(|e| e.component.as_deref()).is_some_and(|c| c.paint_only_property(name));
2199 let before = self.cb(id).map(|cb| cb.state());
2200 let old_value = if self.announces_change(id, &info) {
2202 self.entry(id).and_then(|e| e.component.as_deref()).and_then(|c| crate::component::read_prop(c, name))
2203 } else {
2204 None
2205 };
2206 let unchanged = !(self.design_mode && name == "visible")
2210 && match &old_value {
2211 Some(old) => *old == value,
2212 None => self.entry(id).and_then(|e| e.component.as_deref()).and_then(|c| crate::component::read_prop(c, name)).is_some_and(|old| old == value),
2213 };
2214 let entry = self.entry_mut(id).expect("verificado acima");
2215 let component = entry.component.as_deref_mut().expect("ocupado já verificado acima");
2216 let result = match set_in_chain(component, name, value.clone()) {
2217 Err(Error::UnknownProperty(_)) => match component.control_mut() {
2218 Some(cb) => cb.set_prop(name, value),
2219 None => Err(Error::UnknownProperty(name.to_string())),
2220 },
2221 other => other,
2222 };
2223 if unchanged && result.is_ok() {
2224 } else if paint_only && matches!(name, "opacity" | "translate_x" | "translate_y") {
2226 self.damage_placement(id);
2229 } else if paint_only {
2230 self.damage(id);
2231 } else {
2232 self.invalidate_part(id);
2233 }
2234 if let Some(before) = before {
2235 self.sync_state_triggers(id, before);
2236 }
2237 if result.is_ok() {
2238 self.forget_translation_source(id, name);
2239 self.sync_timer(id);
2240 let _ = self.with_component(id, |c, ctx| c.property_changed(ctx, name));
2241 if name == "visible" {
2242 self.drop_hidden_focus(id);
2243 }
2244 if let Some(old) = old_value {
2245 self.fire_value_change(id, name, old);
2246 }
2247 }
2248 result.map_err(|e| e.with_property(name))
2249 }
2250
2251 pub fn set_prop_quiet(&mut self, id: ComponentId, name: &str, value: impl Into<PropValue>) -> Result<()> {
2254 let value = value.into();
2255 self.without_change_events(|ui| ui.set_prop(id, name, value))
2256 }
2257
2258 pub fn without_change_events<R>(&mut self, f: impl FnOnce(&mut Ui) -> R) -> R {
2262 self.quiet_changes += 1;
2263 let result = f(self);
2264 self.quiet_changes -= 1;
2265 result
2266 }
2267
2268 pub fn change_events_enabled(&self) -> bool {
2271 !self.design_mode && self.quiet_changes == 0
2272 }
2273
2274 fn announces_change(&self, id: ComponentId, info: &PropInfo) -> bool {
2278 if !self.change_events_enabled() || !crate::component::is_value_property(info) {
2279 return false;
2280 }
2281 if !self.prop_info(id, "on_change").is_some_and(|i| i.kind == PropKind::Event) {
2284 return false;
2285 }
2286 self.entry(id).is_some_and(|e| e.events.iter().any(|(n, _)| n == "on_change")) || self.is_intercepted(id, "on_change")
2287 }
2288
2289 fn fire_value_change(&mut self, id: ComponentId, name: &str, old: PropValue) {
2293 let Some(component) = self.entry(id).and_then(|e| e.component.as_deref()) else { return };
2294 let Some(new) = crate::component::read_prop(component, name) else { return };
2295 if new == old {
2296 return;
2297 }
2298 let Some(args) = component.change_args(name, &new) else { return };
2299 if self.intercept(id, "on_change", &args).is_none() {
2300 self.fire_handler(id, "on_change", &args);
2301 }
2302 }
2303
2304 fn drop_hidden_focus(&mut self, id: ComponentId) {
2308 if self.cb(id).is_none_or(|cb| cb.visible()) {
2309 return;
2310 }
2311 let root = self.root_of(id);
2312 let Some(focused) = self.focused(root) else { return };
2313 let mut current = Some(focused);
2314 while let Some(c) = current {
2315 if c == id {
2316 self.clear_focus(root);
2317 return;
2318 }
2319 current = self.parent(c);
2320 }
2321 }
2322
2323 fn sync_state_triggers(&mut self, id: ComponentId, before: ControlState) {
2326 use crate::anim::Trigger;
2327 let Some(after) = self.cb(id).map(|cb| cb.state()) else { return };
2328 for (trigger, was, is) in [
2329 (Trigger::Hover, before.hover, after.hover),
2330 (Trigger::Pressed, before.pressed, after.pressed),
2331 (Trigger::Focused, before.focused, after.focused),
2332 (Trigger::Checked, before.checked, after.checked),
2333 ] {
2334 if was != is {
2335 self.request_repaint();
2336 self.run_triggers(id, trigger, is);
2337 }
2338 }
2339 }
2340
2341 fn set_event_handler(&mut self, id: ComponentId, event: &str, handler: Option<Handler>) {
2346 if let Some(entry) = self.entry_mut(id) {
2347 entry.events.retain(|(n, _)| n != event);
2348 if let Some(h) = handler {
2349 entry.events.push((event.to_string(), h));
2350 }
2351 }
2352 }
2353
2354 pub fn has_handler(&self, id: ComponentId, event: &str) -> bool {
2356 self.entry(id).is_some_and(|e| e.events.iter().any(|(n, _)| n == event))
2357 }
2358
2359 pub fn listens(&self, id: ComponentId, event: &str) -> bool {
2364 self.has_handler(id, event)
2365 || !self.interceptors_for(id, event).is_empty()
2366 || (crate::bindings::CHANGE_EVENTS.contains(&event) && !self.bindings(id).is_empty() && !self.design_mode)
2367 }
2368
2369 pub fn on(
2371 &mut self,
2372 id: ComponentId,
2373 event: &str,
2374 handler: impl Fn(&mut Ui, ComponentId, &EventArgs) + 'static,
2375 ) {
2376 if cfg!(debug_assertions) && self.contains(id) && self.prop_info(id, event).is_none_or(|p| p.kind != PropKind::Event) {
2380 let class = self.class_name(id).unwrap_or_default();
2381 thread_local!(static WARNED: RefCell<std::collections::HashSet<String>> = RefCell::default());
2382 if WARNED.with(|w| w.borrow_mut().insert(format!("{class}.{event}"))) {
2383 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");
2384 }
2385 }
2386 self.set_event_handler(id, event, Some(Handler::Closure(std::rc::Rc::new(handler))));
2387 }
2388
2389 pub fn on_click(&mut self, id: ComponentId, handler: impl Fn(&mut Ui, ComponentId) + 'static) {
2391 self.on(id, "on_click", move |ui, sender, _| handler(ui, sender));
2392 }
2393
2394 pub fn copy_events(&mut self, from: ComponentId, to: ComponentId) {
2397 let events = self.entry(from).map(|e| e.events.clone()).unwrap_or_default();
2398 for (name, handler) in events {
2399 self.set_event_handler(to, &name, Some(handler));
2400 }
2401 }
2402
2403 pub fn clear_event(&mut self, id: ComponentId, event: &str) {
2405 self.set_event_handler(id, event, None);
2406 }
2407
2408 pub fn register_handler(
2415 &mut self,
2416 name: &str,
2417 handler: impl Fn(&mut Ui, ComponentId, &EventArgs) + 'static,
2418 ) {
2419 let (form, handler_name) = name.rsplit_once('.').unwrap_or(("", name));
2420 self.handlers.entry(form.to_string()).or_default().insert(handler_name.to_string(), std::rc::Rc::new(handler));
2421 }
2422
2423 pub fn set_event_sink(
2425 &mut self,
2426 sink: impl Fn(&mut Ui, ComponentId, &str, &str, &EventArgs) + 'static,
2427 ) {
2428 self.event_sink = Some(std::rc::Rc::new(sink));
2429 }
2430
2431 pub fn on_paint(
2433 &mut self,
2434 id: ComponentId,
2435 hook: impl Fn(&mut dyn Canvas, &PaintCtx<'_>, &dyn Fn(&mut dyn Canvas, &PaintCtx<'_>)) + 'static,
2436 ) {
2437 if let Some(entry) = self.entry_mut(id) {
2438 entry.paint_hook = Some(Box::new(hook));
2439 }
2440 self.request_repaint();
2441 }
2442
2443 pub fn clear_on_paint(&mut self, id: ComponentId) {
2444 if let Some(entry) = self.entry_mut(id) {
2445 entry.paint_hook = None;
2446 }
2447 self.request_repaint();
2448 }
2449
2450 pub fn fire(&mut self, id: ComponentId, event: &str, args: &EventArgs) -> bool {
2457 self.binding_changed(id, event);
2460 if event == "on_activate" && self.parent(id).is_none() {
2462 self.active_form = Some(id);
2463 self.focused_window = (Some(id), true);
2464 }
2465 if event == "on_deactivate" && self.parent(id).is_none() {
2466 if self.focused_window.0 == Some(id) {
2467 self.focused_window.0 = None;
2468 }
2469 self.focused_window.1 = true;
2470 }
2471 if let Some(result) = self.intercept(id, event, args) {
2473 return result;
2474 }
2475 self.fire_handler(id, event, args)
2476 }
2477
2478 pub(crate) fn fire_handler(&mut self, id: ComponentId, event: &str, args: &EventArgs) -> bool {
2480 let Some(entry) = self.entry(id) else {
2481 return false;
2482 };
2483 let Some((event_name, handler)) = entry.events.iter().find(|(n, _)| n == event).map(|(n, h)| (n.clone(), h.clone())) else {
2484 return false;
2485 };
2486 if self.has_observers() {
2487 let name = match &handler {
2488 Handler::Named(n) => n.clone(),
2489 Handler::Closure(_) => String::new(),
2490 };
2491 self.report(&crate::activity::Activity::Event { component: id, event: &event_name, handler: &name });
2492 }
2493 if let Some(trace) = self.trace.clone() {
2494 let name = match &handler {
2495 Handler::Named(n) => n.as_str(),
2496 Handler::Closure(_) => "",
2497 };
2498 trace(self, id, &event_name, name);
2499 }
2500 match handler {
2501 Handler::Closure(f) => {
2502 let _profile = crate::profile::scope(crate::profile::Lane::Event, || format!("{}.{event_name}", self.path_of(id)));
2503 self.nested(id, &event_name, |ui| f(ui, id, args))
2504 }
2505 Handler::Named(handler_name) => self.call_named(id, &event_name, &handler_name, args),
2506 }
2507 }
2508
2509 fn nested(&mut self, id: ComponentId, event: &str, call: impl FnOnce(&mut Ui)) -> bool {
2513 let limit = self.limits.1;
2514 if self.event_depth >= limit {
2515 if self.event_depth == limit {
2517 self.event_depth += 1;
2518 let message = format!("evento recursivo demais: {}.{event} ({limit} níveis)", self.path_of(id));
2519 self.raise_exception(crate::Exception { message, path: self.path_of(id), event: event.to_string() });
2520 self.event_depth -= 1;
2521 }
2522 return false;
2523 }
2524 self.event_depth += 1;
2525 let depth = self.event_depth;
2527 let quiet = self.quiet_changes;
2529 self.running_events.push(event.to_string());
2530 self.guarded(id, event, call);
2531 self.running_events.pop();
2532 self.event_depth = depth - 1;
2533 self.quiet_changes = quiet;
2534 true
2535 }
2536
2537 pub fn set_limits(&mut self, tree_depth: usize, event_nesting: usize) {
2540 self.limits = (tree_depth.max(8), event_nesting.max(8));
2541 }
2542
2543 pub fn limits(&self) -> (usize, usize) {
2545 self.limits
2546 }
2547
2548 pub(crate) fn observers(&self) -> &crate::activity::Observers {
2549 &self.observers
2550 }
2551
2552 pub(crate) fn observers_mut(&mut self) -> &mut crate::activity::Observers {
2553 &mut self.observers
2554 }
2555
2556 pub fn set_event_trace(&mut self, f: Option<impl Fn(&Ui, ComponentId, &str, &str) + 'static>) {
2559 self.trace = f.map(|f| std::rc::Rc::new(f) as std::rc::Rc<TraceFn>);
2560 }
2561
2562 pub fn call_handler(&mut self, id: ComponentId, event: &str, handler: &str, args: &EventArgs) -> bool {
2566 self.call_named(id, event, handler, args)
2567 }
2568
2569 fn call_named(&mut self, id: ComponentId, event: &str, handler_name: &str, args: &EventArgs) -> bool {
2570 let mut form = self.form_of(id);
2578 loop {
2579 let name = self.form_class(form).or_else(|| self.name(form)).unwrap_or_default();
2580 if self.handlers.get(name).is_some_and(|m| m.contains_key(handler_name)) {
2581 break;
2582 }
2583 match self.outer_form(form) {
2584 Some(up) if up != form => form = up,
2585 _ => {
2586 form = self.form_of(id);
2587 break;
2588 }
2589 }
2590 }
2591 let form_name = self.form_class(form).or_else(|| self.name(form)).unwrap_or_default();
2592 let _profile = crate::profile::scope(crate::profile::Lane::Handler, || {
2595 if form_name.is_empty() { handler_name.to_string() } else { format!("{form_name}.{handler_name}") }
2596 });
2597 let of_form = |form: &str| self.handlers.get(form).and_then(|m| m.get(handler_name)).cloned();
2598 let found = if form_name.is_empty() { None } else { of_form(form_name) }.or_else(|| of_form(""));
2600 if let Some(f) = found {
2601 return self.nested(id, event, |ui| f(ui, id, args));
2602 }
2603 if let Some(sink) = self.event_sink.clone() {
2604 return self.nested(id, event, |ui| sink(ui, id, event, handler_name, args));
2605 }
2606 false
2607 }
2608
2609 pub fn queue_event(&mut self, id: ComponentId, event: &str, args: EventArgs) {
2611 let pointer = if event == "on_click" { self.click_source } else { None };
2613 self.pending.push((id, event.to_string(), args, pointer));
2614 }
2615
2616 pub fn click_pointer(&self) -> Option<crate::ClickPointer> {
2622 self.click_pointer
2623 }
2624
2625 pub(crate) fn with_click_pointer<R>(&mut self, pointer: Option<crate::ClickPointer>, f: impl FnOnce(&mut Ui) -> R) -> R {
2628 let saved = (std::mem::replace(&mut self.click_pointer, pointer), self.click_source.take());
2629 let result = f(self);
2630 (self.click_pointer, self.click_source) = saved;
2631 result
2632 }
2633
2634 fn click_pointer_for(&self, id: ComponentId, (target, pointer): (ComponentId, crate::ClickPointer)) -> crate::ClickPointer {
2637 if id == target {
2638 return pointer;
2639 }
2640 crate::ClickPointer { position: self.local_point(id, pointer.form_position), ..pointer }
2641 }
2642
2643 pub fn process_events(&mut self) {
2648 let mut delivered = 0;
2649 let mut busy = Vec::new();
2653 while !self.pending.is_empty() {
2654 let mut batch = std::mem::take(&mut self.pending).into_iter();
2655 for (id, event, args, source) in batch.by_ref() {
2656 if self.entry(id).is_some_and(|e| e.component.is_none()) {
2657 busy.push((id, event, args, source));
2658 continue;
2659 }
2660 self.count_repeat(id, &event);
2661 let pointer = source.filter(|_| self.contains(id)).map(|s| self.click_pointer_for(id, s));
2664 self.with_click_pointer(pointer, |ui| ui.fire(id, &event, &args));
2665 delivered += 1;
2666 if delivered >= EVENTS_PER_ROUND {
2667 break;
2668 }
2669 }
2670 if delivered >= EVENTS_PER_ROUND {
2671 let mut left: Vec<_> = batch.collect();
2673 left.append(&mut self.pending);
2674 busy.append(&mut left);
2675 self.pending = busy;
2676 if !self.pending.is_empty() {
2677 self.poster().wake();
2678 return;
2679 }
2680 busy = Vec::new();
2681 }
2682 }
2683 self.pending = busy;
2684 self.repeat = None;
2685 }
2686
2687 pub fn has_pending_events(&self) -> bool {
2689 !self.pending.is_empty()
2690 }
2691
2692 fn count_repeat(&mut self, id: ComponentId, event: &str) {
2695 let count = match &mut self.repeat {
2696 Some((last, name, count)) if *last == id && name == event => {
2697 *count += 1;
2698 *count
2699 }
2700 _ => {
2701 self.repeat = Some((id, event.to_string(), 1));
2702 1
2703 }
2704 };
2705 if count == LOOP_WARNING {
2706 let message = format!("possível laço: {}.{event} disparado {LOOP_WARNING} vezes seguidas", self.path_of(id));
2707 self.report(&crate::activity::Activity::Error { message: &message });
2708 }
2709 }
2710
2711 pub fn with_component<R>(
2716 &mut self,
2717 id: ComponentId,
2718 f: impl FnOnce(&mut dyn Component, &mut EventCtx<'_>) -> R,
2719 ) -> Option<R> {
2720 let before = self.cb(id).map(|cb| cb.state());
2721 let mut component = self.entry_mut(id)?.component.take()?;
2722 self.call_depth += 1;
2723 let depth = (self.call_depth, self.event_depth);
2724 let result = {
2725 let mut ctx = EventCtx::new(self, id);
2726 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(component.as_mut(), &mut ctx)))
2727 };
2728 (self.call_depth, self.event_depth) = (depth.0 - 1, depth.1);
2729 if let Some(entry) = self.entry_mut(id) {
2732 entry.component = Some(component);
2733 }
2734 let result = match result {
2735 Ok(r) => Some(r),
2736 Err(payload) => {
2737 let message = crate::exception::panic_message(payload.as_ref());
2738 self.raise_exception(crate::Exception { message, path: self.path_of(id), event: String::new() });
2739 None
2740 }
2741 };
2742 if let Some(before) = before {
2743 self.sync_state_triggers(id, before);
2744 }
2745 if let Some(focus) = self.pending_focus.take() {
2746 self.set_focus(focus);
2747 }
2748 self.process_events();
2749 if self.call_depth == 0 {
2750 self.flush_closes();
2751 }
2752 result
2753 }
2754
2755 pub fn send_message(&mut self, id: ComponentId, message: &dyn Any) -> bool {
2758 if let Some(error) = self.busy_error(id) {
2759 self.report_busy(&error);
2760 return false;
2761 }
2762 self.with_component(id, |c, ctx| c.message(ctx, message)).is_some()
2763 }
2764
2765 pub fn invoke(&mut self, id: ComponentId, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
2768 if let Some(error) = self.busy_error(id) {
2769 self.report_busy(&error);
2770 return Err(error.to_string());
2771 }
2772 if method == "render_rgba" {
2775 return self.invoke_render_rgba(id, args);
2776 }
2777 if method == "begin_drag_files" && self.cb(id).is_some() {
2779 let paths = match args.first() {
2780 Some(PropValue::String(text)) if text.trim_start().starts_with('[') => crate::system_state::json_strings(text),
2781 Some(PropValue::String(text)) => text.split(';').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect(),
2782 _ => Vec::new(),
2783 };
2784 self.begin_drag_files(id, paths);
2785 return Ok(PropValue::Null);
2786 }
2787 if method == "content_height" && self.cb(id).is_some() {
2789 let width = args.first().and_then(|a| a.to_f64().ok()).map(|w| w as f32);
2790 let width = width.or_else(|| self.cb(id).map(|cb| cb.width())).unwrap_or(0.0);
2791 return Ok(self.content_height(id, width).map_or(PropValue::Null, |h| PropValue::Float(f64::from(h))));
2792 }
2793 let args = self.component_args(id, method, args);
2794 self.with_component(id, |c, ctx| c.invoke(ctx, method, &args)).unwrap_or_else(|| Err(Error::InvalidId.to_string()))
2795 }
2796
2797 fn component_args(&self, id: ComponentId, method: &str, args: &[PropValue]) -> Vec<PropValue> {
2801 let kinds = self.component(id).and_then(|c| c.methods().iter().find(|m| m.name == method)).map_or(&[][..], |m| m.args);
2802 args.iter()
2803 .enumerate()
2804 .map(|(i, arg)| {
2805 if kinds.get(i) != Some(&PropKind::Component) {
2806 return arg.clone();
2807 }
2808 match arg {
2809 PropValue::String(path) if path.is_empty() => PropValue::Component(None),
2810 PropValue::String(path) => self.find_path(path).map_or_else(|| arg.clone(), |c| PropValue::Component(Some(c))),
2811 PropValue::Int(n) => {
2812 let c = ComponentId::from_u64(*n as u64);
2813 if self.contains(c) { PropValue::Component(Some(c)) } else { arg.clone() }
2814 }
2815 PropValue::Null => PropValue::Component(None),
2816 _ => arg.clone(),
2817 }
2818 })
2819 .collect()
2820 }
2821
2822 fn busy_error(&self, id: ComponentId) -> Option<Error> {
2825 self.entry(id).filter(|e| e.component.is_none()).map(|_| Error::Busy(self.path_of(id)))
2826 }
2827
2828 fn report_busy(&mut self, error: &Error) {
2831 if cfg!(debug_assertions) {
2832 let message = error.to_string();
2833 self.report(&crate::activity::Activity::Error { message: &message });
2834 }
2835 }
2836
2837 pub fn set_hint_delay(&mut self, seconds: Option<f64>) {
2843 self.hint_delay = seconds.map(|s| s.max(0.0));
2844 }
2845
2846 pub fn set_still_picture(&mut self, on: bool) {
2849 self.still_picture = on;
2850 }
2851
2852 pub fn hint_delay(&self) -> f64 {
2854 self.hint_delay
2855 .or_else(|| self.theme.durations.get("hint").map(|ms| *ms as f64 / 1000.0))
2856 .unwrap_or(crate::input::HINT_DELAY)
2857 }
2858
2859 pub fn set_design_mode(&mut self, on: bool) {
2860 self.design_mode = on;
2861 self.request_repaint();
2862 }
2863
2864 pub fn set_design_reveal(&mut self, selected: &[ComponentId], show_all: bool) {
2869 self.design_reveal = selected.to_vec();
2870 self.design_show_hidden = show_all;
2871 let mut stack = self.roots().to_vec();
2872 while let Some(id) = stack.pop() {
2873 stack.extend(self.children(id).iter().copied());
2874 if self.cb(id).is_some_and(|cb| cb.design_hidden) {
2875 let shown = self.design_revealed(id);
2876 if let Some(cb) = self.cb_mut(id) {
2877 cb.set_visible(shown);
2878 }
2879 }
2880 }
2881 self.invalidate();
2882 }
2883
2884 fn design_revealed(&self, id: ComponentId) -> bool {
2887 self.design_show_hidden
2888 || self.design_reveal.iter().any(|&s| {
2889 let mut cur = Some(s);
2890 while let Some(c) = cur {
2891 if c == id {
2892 return true;
2893 }
2894 cur = self.parent(c);
2895 }
2896 false
2897 })
2898 }
2899
2900 pub fn design_mode(&self) -> bool {
2901 self.design_mode
2902 }
2903
2904 pub fn design_changed(&mut self, root: ComponentId) {
2908 let mut stack = vec![root];
2909 while let Some(id) = stack.pop() {
2910 stack.extend(self.children(id).iter().copied());
2911 self.send_message(id, &DesignChanged);
2912 }
2913 }
2914
2915 pub fn request_close(&mut self) {
2917 self.close_requested = true;
2918 }
2919
2920 pub fn close_requested(&self) -> bool {
2922 self.close_requested
2923 }
2924
2925 pub fn clone_component(&mut self, source: ComponentId, parent: Option<ComponentId>) -> Result<ComponentId> {
2930 self.clone_node(source, parent, false, &mut Vec::new())
2931 }
2932
2933 pub fn clone_component_mapped(&mut self, source: ComponentId, parent: Option<ComponentId>) -> Result<(ComponentId, Vec<(ComponentId, ComponentId)>)> {
2938 let mut map = Vec::new();
2939 let id = self.clone_node(source, parent, false, &mut map)?;
2940 Ok((id, map))
2941 }
2942
2943 fn clone_node(&mut self, source: ComponentId, parent: Option<ComponentId>, named: bool, map: &mut Vec<(ComponentId, ComponentId)>) -> Result<ComponentId> {
2944 let class = self.class_name(source).ok_or(Error::InvalidId)?.to_string();
2945 let id = self.create(&class, parent)?;
2946 map.push((source, id));
2947 if named {
2948 if let Some(name) = self.name(source).filter(|n| !n.is_empty()).map(str::to_string) {
2949 let _ = self.set_name(id, &name);
2950 }
2951 }
2952 if !named || self.entry(source).is_some_and(|e| e.scope) {
2954 self.set_name_scope(id, true);
2955 }
2956 let mut infos = self.prop_infos(source);
2959 infos.sort_by_key(|i| matches!(i.name, "align" | "anchors"));
2960 for info in infos {
2961 if info.read_only || info.runtime || info.name == "name" {
2962 continue;
2963 }
2964 if let Ok(value) = self.get_declared_prop(source, info.name) {
2966 let _ = self.set_prop_quiet(id, info.name, value);
2967 }
2968 }
2969 for child in self.children(source).to_vec() {
2970 self.clone_node(child, Some(id), true, map)?;
2971 }
2972 Ok(id)
2973 }
2974
2975 pub fn components(&self) -> impl Iterator<Item = ComponentId> + '_ {
2977 self.slots.iter().enumerate().filter_map(|(index, slot)| {
2978 slot.entry.as_ref().map(|_| ComponentId { index: index as u32, generation: slot.generation })
2979 })
2980 }
2981
2982 pub fn click(&mut self, id: ComponentId) -> bool {
2985 let source = self.click_source.take();
2986 let clicked = self.with_component(id, |c, ctx| c.click(ctx)).is_some();
2987 self.click_source = source;
2988 clicked
2989 }
2990
2991 pub fn dump(&self, id: ComponentId) -> String {
2997 let mut out = String::new();
2998 self.dump_into(id, 0, &mut out);
2999 out
3000 }
3001
3002 fn dump_into(&self, id: ComponentId, depth: usize, out: &mut String) {
3003 let Some(entry) = self.entry(id) else { return };
3004 let class = entry.component.as_deref().map_or("?", |c| c.class_name());
3005 let _ = write!(out, "{:indent$}{class}", "", indent = depth * 2);
3006 if !entry.name.is_empty() {
3007 let _ = write!(out, " {}", entry.name);
3008 }
3009 if let Some(cb) = self.cb(id) {
3010 let b = cb.bounds;
3011 let _ = write!(
3012 out,
3013 " [{:?}] x={} y={} w={} h={}",
3014 cb.align(),
3015 b.x,
3016 b.y,
3017 b.width,
3018 b.height
3019 );
3020 }
3021 out.push('\n');
3022 for &c in &entry.children {
3023 self.dump_into(c, depth + 1, out);
3024 }
3025 }
3026}
3027
3028fn too_deep(limit: usize) -> Error {
3029 Error::invalid(format!("profundidade máxima de componentes ({limit} níveis)"))
3030}
3031
3032pub fn is_identifier(s: &str) -> bool {
3035 let mut chars = s.chars();
3036 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
3037 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
3038}
3039
3040fn bounds_field(b: &Bounds, field: &str) -> Option<f32> {
3041 match field {
3042 "left" => Some(b.left),
3043 "top" => Some(b.top),
3044 "right" => Some(b.right),
3045 "bottom" => Some(b.bottom),
3046 _ => None,
3047 }
3048}
3049
3050fn bounds_field_mut<'a>(b: &'a mut Bounds, field: &str) -> Option<&'a mut f32> {
3051 match field {
3052 "left" => Some(&mut b.left),
3053 "top" => Some(&mut b.top),
3054 "right" => Some(&mut b.right),
3055 "bottom" => Some(&mut b.bottom),
3056 _ => None,
3057 }
3058}
3059
3060fn set_in_chain(c: &mut dyn Component, name: &str, value: PropValue) -> Result<()> {
3062 match c.set_prop(name, value.clone()) {
3063 Err(Error::UnknownProperty(_)) => match c.inner_mut() {
3064 Some(inner) => set_in_chain(inner, name, value),
3065 None => Err(Error::UnknownProperty(name.to_string())),
3066 },
3067 other => other,
3068 }
3069}
3070
3071fn find_layer<T: Component>(c: &dyn Component) -> Option<&T> {
3072 let any: &dyn Any = c;
3073 if let Some(t) = any.downcast_ref::<T>() {
3074 return Some(t);
3075 }
3076 c.inner().and_then(find_layer::<T>)
3077}
3078
3079fn find_layer_mut<T: Component>(c: &mut dyn Component) -> Option<&mut T> {
3080 if (&*c as &dyn Any).is::<T>() {
3081 let any: &mut dyn Any = c;
3082 return any.downcast_mut::<T>();
3083 }
3084 c.inner_mut().and_then(find_layer_mut::<T>)
3085}
3086
3087impl Ui {
3092 pub fn access_items(&self, id: ComponentId) -> Vec<crate::automation::AccessItem> {
3095 self.component(id).and_then(|c| c.accessible_items()).map_or_else(Vec::new, |a| a.access_items(self, id))
3096 }
3097
3098 pub fn access_table_size(&self, id: ComponentId) -> Option<(usize, usize)> {
3101 self.component(id).and_then(|c| c.accessible_items()).and_then(|a| a.access_table_size(self))
3102 }
3103
3104 pub fn access_action(&mut self, id: ComponentId, index: usize, action: crate::automation::ItemAction) -> bool {
3107 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);
3108 if done {
3109 self.request_repaint();
3110 }
3111 done
3112 }
3113
3114 pub fn click_item(&mut self, id: ComponentId, name: &str) -> bool {
3117 let found = self.access_items(id).iter().position(|i| i.name.trim().eq_ignore_ascii_case(name.trim()));
3118 found.is_some_and(|index| self.access_action(id, index, crate::automation::ItemAction::Click))
3119 }
3120}
3121
3122impl Ui {
3123 pub fn style_line_height(&self, id: ComponentId) -> f32 {
3131 let theme = self.theme_of(id);
3132 match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
3133 Some((component, cb)) => {
3134 let mut classes = Vec::new();
3135 component.class_chain(&mut classes);
3136 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).line_height
3137 }
3138 None => 0.0,
3139 }
3140 }
3141
3142 pub fn style_padding(&self, id: ComponentId) -> crate::geometry::Bounds {
3143 let theme = self.theme_of(id);
3144 match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
3145 Some((component, cb)) => {
3146 let mut classes = Vec::new();
3147 component.class_chain(&mut classes);
3148 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).padding
3149 }
3150 None => Default::default(),
3151 }
3152 }
3153
3154 pub fn font_of(&self, id: ComponentId) -> crate::canvas::FontSpec {
3155 let theme = self.theme_of(id);
3156 let mut font = match self.component(id).and_then(|c| c.control().map(|cb| (c, cb))) {
3157 Some((component, cb)) => {
3158 let mut classes = Vec::new();
3159 component.class_chain(&mut classes);
3160 self.mixed_theme(theme, &classes).resolve(&classes, cb.style(), cb.state()).font
3161 }
3162 None => theme.fonts.get("default").cloned().unwrap_or_default(),
3163 };
3164 let mut chain = Vec::new();
3165 let mut cur = Some(id);
3166 while let Some(c) = cur {
3167 if let Some(cb) = self.control(c) {
3168 chain.push(cb.font().clone());
3169 }
3170 cur = self.parent(c);
3171 }
3172 let effective = chain.iter().fold(crate::component::FontOverride::default(), |acc, f| acc.over(f));
3174 effective.apply(&mut font);
3175 font.family = self.resolve_font(&font.family);
3176 font.size *= self.control(id).map_or(1.0, |cb| cb.text_scale());
3178 font
3179 }
3180}
3181
3182impl Ui {
3183 pub fn extension<T: Default + 'static>(&mut self) -> &mut T {
3187 self.extensions
3188 .entry(std::any::TypeId::of::<T>())
3189 .or_insert_with(|| Box::new(T::default()))
3190 .downcast_mut::<T>()
3191 .expect("o tipo é a chave")
3192 }
3193
3194 pub fn extension_ref<T: 'static>(&self) -> Option<&T> {
3196 self.extensions.get(&std::any::TypeId::of::<T>()).and_then(|b| b.downcast_ref::<T>())
3197 }
3198}
3199
3200pub(crate) fn is_hex_with_opacity(spec: &str) -> bool {
3203 let s = spec.trim();
3204 s.starts_with('#') && s.contains('/')
3205}
3206
3207fn stretches(cb: &ControlBase, width: bool) -> bool {
3211 use crate::align::{Align, SelfAlign};
3212 let band = cb.self_align() == SelfAlign::Stretch;
3213 match cb.align() {
3214 Align::None | Align::Center => false,
3215 Align::VertCenter | Align::Horizontal => width,
3216 Align::HorzCenter | Align::Vertical => !width,
3217 Align::Top | Align::Bottom | Align::MostTop | Align::MostBottom => width && (band || cb.max_width() > 0.0),
3218 Align::Left | Align::Right | Align::MostLeft | Align::MostRight => !width && (band || cb.max_height() > 0.0),
3219 _ => true,
3220 }
3221}