1use std::any::Any;
5use std::fmt;
6
7use crate::align::{Align, Anchors, SelfAlign};
8use crate::canvas::Canvas;
9use crate::error::{Error, Result};
10use crate::event::{EventArgs, EventCtx, KeyEvent, PointerEvent, WheelEvent};
11use crate::geometry::{Bounds, PointF, RectF, SizeF};
12use crate::paint::PaintCtx;
13use crate::platform::CursorShape;
14use crate::prop::{PropInfo, PropKind, PropValue};
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct ComponentId {
22 pub(crate) index: u32,
23 pub(crate) generation: u32,
24}
25
26impl ComponentId {
27 pub fn to_u64(self) -> u64 {
29 (self.generation as u64) << 32 | self.index as u64
30 }
31
32 pub fn from_u64(value: u64) -> Self {
34 Self { index: value as u32, generation: (value >> 32) as u32 }
35 }
36}
37
38impl fmt::Display for ComponentId {
39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40 write!(f, "#{}v{}", self.index, self.generation)
41 }
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub struct ControlState {
47 pub hover: bool,
48 pub pressed: bool,
49 pub focused: bool,
50 pub checked: bool,
51 pub disabled: bool,
53}
54
55pub trait Component: Any {
86 fn class_name(&self) -> &'static str;
89
90 fn inner(&self) -> Option<&dyn Component> {
92 None
93 }
94
95 fn inner_mut(&mut self) -> Option<&mut dyn Component> {
96 None
97 }
98
99 fn class_chain(&self, out: &mut Vec<&'static str>) {
102 out.push(self.class_name());
103 if let Some(inner) = self.inner() {
104 inner.class_chain(out);
105 }
106 }
107
108 fn control(&self) -> Option<&ControlBase> {
110 self.inner().and_then(|i| i.control())
111 }
112
113 fn control_mut(&mut self) -> Option<&mut ControlBase> {
114 self.inner_mut().and_then(|i| i.control_mut())
115 }
116
117 fn props(&self) -> &'static [PropInfo] {
120 &[]
121 }
122
123 fn default_event(&self) -> Option<&'static str> {
127 self.inner().and_then(|c| c.default_event())
128 }
129
130 fn get_prop(&self, _name: &str) -> Option<PropValue> {
132 None
133 }
134
135 fn set_prop(&mut self, name: &str, _value: PropValue) -> Result<()> {
138 Err(Error::UnknownProperty(name.to_string()))
139 }
140
141 fn notification(&mut self, freed: ComponentId) {
144 if let Some(inner) = self.inner_mut() {
145 inner.notification(freed);
146 }
147 }
148
149 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
151 if let Some(inner) = self.inner() {
152 inner.paint(canvas, ctx);
153 }
154 }
155
156 fn transparent_background(&self) -> bool {
160 self.inner().is_some_and(|i| i.transparent_background())
161 }
162
163 fn opaque(&self, style: &crate::theme::ResolvedStyle) -> bool {
168 self.inner().is_some_and(|i| i.opaque(style))
169 }
170
171 fn paint_after(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
173 if let Some(inner) = self.inner() {
174 inner.paint_after(canvas, ctx);
175 }
176 }
177
178 fn paint_is_pure(&self) -> bool {
185 false
186 }
187
188 fn provided(&self) -> Option<crate::providers::Provided<'_>> {
191 None
192 }
193
194 fn resized(&mut self, ctx: &mut EventCtx<'_>) {
196 if let Some(inner) = self.inner_mut() {
197 inner.resized(ctx);
198 }
199 }
200
201 fn click(&mut self, ctx: &mut EventCtx<'_>) {
203 match self.inner_mut() {
204 Some(inner) => inner.click(ctx),
205 None => ctx.fire("on_click", EventArgs::None),
206 }
207 }
208
209 fn pointer_down(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
210 if let Some(inner) = self.inner_mut() {
211 inner.pointer_down(ctx, event);
212 }
213 }
214
215 fn pointer_up(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
216 if let Some(inner) = self.inner_mut() {
217 inner.pointer_up(ctx, event);
218 }
219 }
220
221 fn pointer_move(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
222 if let Some(inner) = self.inner_mut() {
223 inner.pointer_move(ctx, event);
224 }
225 }
226
227 fn pointer_enter(&mut self, ctx: &mut EventCtx<'_>) {
228 if let Some(inner) = self.inner_mut() {
229 inner.pointer_enter(ctx);
230 }
231 }
232
233 fn pointer_leave(&mut self, ctx: &mut EventCtx<'_>) {
234 if let Some(inner) = self.inner_mut() {
235 inner.pointer_leave(ctx);
236 }
237 }
238
239 fn wheel(&mut self, ctx: &mut EventCtx<'_>, event: &WheelEvent) {
240 if let Some(inner) = self.inner_mut() {
241 inner.wheel(ctx, event);
242 }
243 }
244
245 fn gesture(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::GestureEvent) {
248 if let Some(inner) = self.inner_mut() {
249 inner.gesture(ctx, event);
250 }
251 }
252
253 fn key_down(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
254 if let Some(inner) = self.inner_mut() {
255 inner.key_down(ctx, event);
256 }
257 }
258
259 fn key_up(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
260 if let Some(inner) = self.inner_mut() {
261 inner.key_up(ctx, event);
262 }
263 }
264
265 fn shortcut(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
269 if let Some(inner) = self.inner_mut() {
270 inner.shortcut(ctx, event);
271 }
272 }
273
274 fn platform_hooks(&self) -> Option<&dyn PlatformHooks> {
277 self.inner().and_then(|i| i.platform_hooks())
278 }
279
280 fn platform_hooks_mut(&mut self) -> Option<&mut dyn PlatformHooks> {
281 self.inner_mut().and_then(|i| i.platform_hooks_mut())
282 }
283
284 fn design_hooks(&self) -> Option<&dyn DesignHooks> {
287 self.inner().and_then(|i| i.design_hooks())
288 }
289
290 fn design_hooks_mut(&mut self) -> Option<&mut dyn DesignHooks> {
291 self.inner_mut().and_then(|i| i.design_hooks_mut())
292 }
293
294 fn contains_point(&self, local: PointF, size: SizeF) -> bool {
297 self.inner().map_or(true, |i| i.contains_point(local, size))
298 }
299
300 fn hit_slop(&self) -> f32 {
304 self.inner().map_or(0.0, |i| i.hit_slop())
305 }
306
307 fn scroll_axes(&self) -> (bool, bool) {
310 self.inner().map_or((false, false), |i| i.scroll_axes())
311 }
312
313 fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
318 None
319 }
320
321 fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
324 None
325 }
326
327 fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
332 false
333 }
334
335 fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
338
339 fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
341
342 fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
344
345 fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
347
348 fn accepts_text(&self) -> bool {
349 self.inner().is_some_and(|i| i.accepts_text())
350 }
351
352 fn captures_key(&self, event: &KeyEvent) -> bool {
355 self.inner().is_some_and(|i| i.captures_key(event))
356 }
357
358 fn mnemonic_text(&self) -> Option<&str> {
361 self.inner().and_then(|i| i.mnemonic_text())
362 }
363
364 fn mnemonic_focuses_child(&self) -> bool {
366 self.inner().is_some_and(|i| i.mnemonic_focuses_child())
367 }
368
369 fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
371 if let Some(inner) = self.inner_mut() {
372 inner.text_input(ctx, text);
373 }
374 }
375
376 fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
377 if let Some(inner) = self.inner_mut() {
378 inner.focus_enter(ctx);
379 }
380 }
381
382 fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
383 if let Some(inner) = self.inner_mut() {
384 inner.focus_exit(ctx);
385 }
386 }
387
388 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
392 if let Some(inner) = self.inner_mut() {
393 inner.property_changed(ctx, name);
394 }
395 }
396
397 fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
403 match self.inner() {
404 Some(inner) => inner.change_args(name, value),
405 None => Some(EventArgs::Value(value.clone())),
406 }
407 }
408
409 fn paint_only_property(&self, name: &str) -> bool {
414 self.inner().is_some_and(|inner| inner.paint_only_property(name))
415 }
416
417 fn timer_interval(&self) -> Option<f64> {
420 self.inner().and_then(|i| i.timer_interval())
421 }
422
423 fn timer_precision(&self) -> crate::TimerPrecision {
425 self.inner().map(|i| i.timer_precision()).unwrap_or_default()
426 }
427
428 fn timer_background(&self) -> bool {
431 self.inner().is_some_and(|i| i.timer_background())
432 }
433
434 fn timer_late(&mut self, late: f64) {
436 if let Some(inner) = self.inner_mut() {
437 inner.timer_late(late);
438 }
439 }
440
441 fn frame(&mut self, ctx: &mut EventCtx<'_>) -> bool {
445 self.inner_mut().is_some_and(|inner| inner.frame(ctx))
446 }
447
448 fn timer(&mut self, ctx: &mut EventCtx<'_>) {
451 match self.inner_mut() {
452 Some(inner) => inner.timer(ctx),
453 None => ctx.fire("on_timer", EventArgs::None),
454 }
455 }
456
457 fn arrange(&self, area: RectF, children: &[ArrangeItem]) -> Option<Vec<RectF>> {
462 self.inner().and_then(|i| i.arrange(area, children))
463 }
464
465 fn auto_height(&self, ui: &crate::Ui, id: ComponentId, width: f32) -> Option<f32> {
469 self.inner().and_then(|i| i.auto_height(ui, id, width))
470 }
471
472 fn closes_on_outside_press(&self) -> bool {
479 false
480 }
481
482 fn dies_with(&self) -> Option<ComponentId> {
486 self.inner().and_then(|i| i.dies_with())
487 }
488
489 fn access_items(&self, ui: &crate::Ui, id: ComponentId) -> Vec<crate::automation::AccessItem> {
492 self.inner().map_or_else(Vec::new, |i| i.access_items(ui, id))
493 }
494
495 fn access_action(&mut self, ctx: &mut EventCtx<'_>, index: usize, action: crate::automation::ItemAction) -> bool {
498 self.inner_mut().is_some_and(|i| i.access_action(ctx, index, action))
499 }
500
501 fn attach(&self) -> Option<(ComponentId, f32, f32)> {
505 self.inner().and_then(|i| i.attach())
506 }
507
508 fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
512 self.inner().map(|i| i.event_info(event)).unwrap_or_default()
513 }
514
515 fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
519 if let Some(inner) = self.inner_mut() {
520 inner.message(ctx, message);
521 }
522 }
523
524 fn methods(&self) -> &'static [MethodInfo] {
527 &[]
528 }
529
530 fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
534 let class = self.class_name();
535 match self.inner_mut() {
536 Some(inner) => inner.invoke(ctx, method, args),
537 None => Err(format!("{class} não tem o método '{method}'")),
538 }
539 }
540
541}
542
543pub trait PlatformHooks {
547 fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
549 None
550 }
551
552 fn tray(&self) -> Option<crate::tray::TraySpec> {
554 None
555 }
556
557 fn native_view(&self) -> Option<NativeView> {
561 None
562 }
563
564 fn take_native_commands(&self) -> Vec<NativeCommand> {
566 Vec::new()
567 }
568
569 fn connection(&self) -> Option<Connection> {
573 None
574 }
575
576 fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
579 false
580 }
581}
582
583pub trait DesignHooks {
587 fn design_grip(&self, _local: PointF) -> Option<usize> {
590 None
591 }
592
593 fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
597 None
598 }
599}
600
601#[derive(Clone, Copy, Debug, PartialEq)]
603pub struct ArrangeItem {
604 pub id: ComponentId,
605 pub size: SizeF,
606 pub margins: Bounds,
608 pub span: u32,
610 pub spacing: f32,
613}
614
615impl ArrangeItem {
616 pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
618 ArrangeItem { id, size: SizeF::new(cb.width(), cb.height()), margins: cb.margins(), span: cb.column_span(), spacing: cb.spacing_scale() }
619 }
620}
621
622#[derive(Clone, Debug, PartialEq)]
624pub enum NativeView {
625 Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String },
630}
631
632#[derive(Clone, Debug, PartialEq)]
636pub struct WebMessage {
637 pub text: String,
638 pub url: String,
639}
640
641pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
645 allowed.is_empty()
646 || url.starts_with("about:")
647 || url.starts_with("data:")
648 || allowed.iter().any(|a| {
649 let a = a.trim_end_matches('/');
650 url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
651 })
652}
653
654pub fn url_origin(url: &str) -> String {
656 let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
657 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
658 format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
659}
660
661#[derive(Clone, Copy, Debug, PartialEq)]
664pub struct MethodInfo {
665 pub name: &'static str,
666 pub args: &'static [PropKind],
667 pub returns: Option<PropKind>,
668 pub params: &'static [&'static str],
671}
672
673impl MethodInfo {
674 pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
675 Self { name, args, returns, params: &[] }
676 }
677
678 pub const fn params(self, names: &'static [&'static str]) -> Self {
681 Self { params: names, ..self }
682 }
683}
684
685#[derive(Clone, Debug, PartialEq)]
687pub enum NativeCommand {
688 Eval(String),
690 Back,
691 Forward,
692 Reload,
693}
694
695#[derive(Clone, Debug, PartialEq)]
697pub struct NativeViewSlot {
698 pub id: ComponentId,
699 pub rect: crate::RectF,
700 pub clip: Option<crate::RectF>,
703 pub visible: bool,
704 pub view: NativeView,
705 pub commands: Vec<NativeCommand>,
706}
707
708pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
714 let mut out: Vec<PropInfo> = Vec::new();
715 let mut seen = std::collections::HashSet::new();
718 let mut push = |info: &PropInfo| {
719 if seen.insert(info.name) {
720 out.push(*info);
721 }
722 };
723 let mut layer = Some(component);
724 while let Some(l) = layer {
725 l.props().iter().for_each(&mut push);
726 layer = l.inner();
727 }
728 if component.control().is_some() {
729 ControlBase::PROPS.iter().for_each(&mut push);
730 }
731 out
732}
733
734pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
737 let mut layer = Some(component);
738 while let Some(l) = layer {
739 if let Some(info) = l.props().iter().find(|p| p.name == name) {
740 return Some(*info);
741 }
742 layer = l.inner();
743 }
744 if component.control().is_some() {
745 return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
746 }
747 None
748}
749
750pub const VALUE_PROPERTIES: [&str; 19] = [
755 "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
756 "angle", "pressed", "position", "low", "high",
757];
758
759pub fn is_value_property(info: &PropInfo) -> bool {
763 match info.name {
764 "tab_index" | "expanded" => true,
765 name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
766 }
767}
768
769pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
770 let mut layer = Some(component);
771 while let Some(l) = layer {
772 if let Some(v) = l.get_prop(name) {
773 return Some(v);
774 }
775 layer = l.inner();
776 }
777 component.control().and_then(|cb| cb.get_prop(name))
778}
779
780#[derive(Clone, Copy, Debug, PartialEq)]
783pub(crate) struct AnchorRef {
784 pub(crate) parent: SizeF,
785 pub(crate) rect: RectF,
786}
787
788#[derive(Clone, Debug)]
793pub struct ControlBase {
794 left: f32,
795 top: f32,
796 width: f32,
797 height: f32,
798 margins: Bounds,
799 padding: Bounds,
800 align: Align,
801 anchors: Anchors,
802 visible: bool,
803 enabled: bool,
804 hit_test: bool,
805 clip_children: bool,
806 captures_wheel: bool,
809 can_focus: bool,
810 draggable: bool,
811 accepts_drops: bool,
812 drag: Option<Box<DragDecl>>,
815 tab_stop: bool,
816 pan_on_touch: bool,
817 pub(crate) popup_menu: Option<ComponentId>,
819 cursor: CursorShape,
820 opacity: f32,
821 rotation: f32,
823 translate: PointF,
825 cache_layer: bool,
828 aspect_ratio: f32,
830 max_width: f32,
832 min_width: f32,
834 min_height: f32,
835 max_height: f32,
836 self_align: SelfAlign,
838 auto_size: bool,
840 column_span: u32,
842 pub(crate) text_scale: f32,
845 pub(crate) spacing_scale: f32,
846 shadow: Option<crate::canvas::Shadow>,
848 tag: i64,
849 style: String,
850 theme: String,
852 hint: String,
854 state: ControlState,
855 pub(crate) bounds: RectF,
856 pub(crate) anchor_ref: Option<AnchorRef>,
857 pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
860 pub(crate) design_hidden: bool,
863 pub(crate) design_only: bool,
865 pub(crate) keep_left_to_right: bool,
868 pub(crate) colors: ColorOverride,
870 pub(crate) font: FontOverride,
872 scroll_offset: PointF,
874 pub(crate) laid_out_scroll: PointF,
877 pub(crate) safe_area: Bounds,
879 pub(crate) content_size: SizeF,
881}
882
883impl Default for ControlBase {
884 fn default() -> Self {
885 Self::new(100.0, 100.0)
886 }
887}
888
889impl ControlBase {
890 pub const PROPS: &'static [PropInfo] = &[
892 PropInfo::new("left", PropKind::Float, "Layout"),
893 PropInfo::new("top", PropKind::Float, "Layout"),
894 PropInfo::new("width", PropKind::Float, "Layout"),
895 PropInfo::new("height", PropKind::Float, "Layout"),
896 PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
897 PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
898 PropInfo::new("margins", PropKind::Bounds, "Layout"),
899 PropInfo::new("padding", PropKind::Bounds, "Layout"),
900 PropInfo::new("visible", PropKind::Bool, "Behavior"),
901 PropInfo::new("enabled", PropKind::Bool, "Behavior"),
902 PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
903 PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
904 PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
905 PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
906 PropInfo::new("draggable", PropKind::Bool, "Behavior"),
907 PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
908 PropInfo::new("drag_data", PropKind::String, "Behavior"),
909 PropInfo::new("drag_label", PropKind::String, "Behavior"),
910 PropInfo::new("drag_image", PropKind::Component, "Behavior"),
911 PropInfo::new("drop_types", PropKind::String, "Behavior"),
912 PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
913 PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
914 PropInfo::new("opacity", PropKind::Float, "Appearance"),
915 PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
916 PropInfo::new("rotation", PropKind::Angle, "Layout"),
917 PropInfo::new("translate_x", PropKind::Float, "Appearance"),
918 PropInfo::new("translate_y", PropKind::Float, "Appearance"),
919 PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
920 PropInfo::new("max_width", PropKind::Float, "Layout"),
921 PropInfo::new("min_width", PropKind::Float, "Layout"),
922 PropInfo::new("min_height", PropKind::Float, "Layout"),
923 PropInfo::new("max_height", PropKind::Float, "Layout"),
924 PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
925 PropInfo::new("auto_size", PropKind::Bool, "Layout"),
926 PropInfo::new("column_span", PropKind::Int, "Layout"),
927 PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
928 PropInfo::new("style", PropKind::String, "Appearance"),
929 PropInfo::new("theme", PropKind::String, "Appearance"),
930 PropInfo::new("fill", PropKind::Color, "Appearance"),
931 PropInfo::new("border_color", PropKind::Color, "Appearance"),
932 PropInfo::new("text_color", PropKind::Color, "Appearance"),
933 PropInfo::new("accent_color", PropKind::Color, "Appearance"),
934 PropInfo::new("success_color", PropKind::Color, "Appearance"),
935 PropInfo::new("warning_color", PropKind::Color, "Appearance"),
936 PropInfo::new("danger_color", PropKind::Color, "Appearance"),
937 PropInfo::new("font_family", PropKind::String, "Font"),
938 PropInfo::new("font_size", PropKind::Float, "Font"),
939 PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
940 PropInfo::new("font_italic", PropKind::Bool, "Font"),
941 PropInfo::new("font_underline", PropKind::Bool, "Font"),
942 PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
943 PropInfo::new("hint", PropKind::String, "Behavior"),
944 PropInfo::new("tag", PropKind::Int, "Misc"),
945 PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
946 PropInfo::new("on_click", PropKind::Event, "Events"),
947 PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
948 PropInfo::new("on_long_press", PropKind::Event, "Events"),
949 PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
950 PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
951 PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
952 PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
953 PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
954 PropInfo::new("on_wheel", PropKind::Event, "Events"),
955 PropInfo::new("on_gesture", PropKind::Event, "Events"),
956 PropInfo::new("on_key_down", PropKind::Event, "Events"),
957 PropInfo::new("on_key_press", PropKind::Event, "Events"),
958 PropInfo::new("on_key_up", PropKind::Event, "Events"),
959 PropInfo::new("on_enter", PropKind::Event, "Events"),
960 PropInfo::new("on_exit", PropKind::Event, "Events"),
961 PropInfo::new("on_resize", PropKind::Event, "Events"),
962 PropInfo::new("on_drag_start", PropKind::Event, "Events"),
963 PropInfo::new("on_drag_over", PropKind::Event, "Events"),
964 PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
965 PropInfo::new("on_drag_end", PropKind::Event, "Events"),
966 ];
967
968 pub fn new(width: f32, height: f32) -> Self {
969 Self {
970 left: 0.0,
971 top: 0.0,
972 width,
973 height,
974 margins: Bounds::ZERO,
975 padding: Bounds::ZERO,
976 align: Align::None,
977 anchors: Anchors::default(),
978 visible: true,
979 enabled: true,
980 hit_test: true,
981 clip_children: false,
982 captures_wheel: false,
983 can_focus: false,
984 draggable: false,
985 accepts_drops: false,
986 drag: None,
987 tab_stop: true,
988 pan_on_touch: true,
989 popup_menu: None,
990 cursor: CursorShape::Default,
991 opacity: 1.0,
992 rotation: 0.0,
993 translate: PointF::ZERO,
994 cache_layer: false,
995 aspect_ratio: 0.0,
996 max_width: 0.0,
997 min_width: 0.0,
998 min_height: 0.0,
999 max_height: 0.0,
1000 self_align: SelfAlign::Stretch,
1001 auto_size: false,
1002 column_span: 1,
1003 text_scale: 1.0,
1004 spacing_scale: 1.0,
1005 shadow: None,
1006 tag: 0,
1007 style: String::new(),
1008 theme: String::new(),
1009 hint: String::new(),
1010 state: ControlState::default(),
1011 bounds: RectF::new(0.0, 0.0, width, height),
1012 anchor_ref: None,
1013 follow: None,
1014 design_hidden: false,
1015 design_only: false,
1016 keep_left_to_right: false,
1017 colors: ColorOverride::default(),
1018 font: FontOverride::default(),
1019 scroll_offset: PointF::ZERO,
1020 laid_out_scroll: PointF::ZERO,
1021 content_size: SizeF::ZERO,
1022 safe_area: Bounds::default(),
1023 }
1024 }
1025
1026 pub fn left(&self) -> f32 {
1029 self.left
1030 }
1031
1032 pub fn top(&self) -> f32 {
1033 self.top
1034 }
1035
1036 pub fn width(&self) -> f32 {
1037 self.width
1038 }
1039
1040 pub fn height(&self) -> f32 {
1041 self.height
1042 }
1043
1044 pub fn position(&self) -> PointF {
1045 PointF::new(self.left, self.top)
1046 }
1047
1048 pub fn size(&self) -> SizeF {
1049 SizeF::new(self.width, self.height)
1050 }
1051
1052 pub fn margins(&self) -> Bounds {
1055 if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1056 }
1057
1058 pub fn padding(&self) -> Bounds {
1060 if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1061 }
1062
1063 pub fn align(&self) -> Align {
1064 self.align
1065 }
1066
1067 pub fn anchors(&self) -> Anchors {
1068 self.anchors
1069 }
1070
1071 pub fn visible(&self) -> bool {
1072 self.visible
1073 }
1074
1075 pub fn design_only(&self) -> bool {
1077 self.design_only
1078 }
1079
1080 pub fn colors(&self) -> ColorOverride {
1082 self.colors
1083 }
1084
1085 pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1086 self.colors = colors;
1087 self
1088 }
1089
1090 pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1091 self.design_only = on;
1092 self
1093 }
1094
1095 pub fn keep_left_to_right(&self) -> bool {
1097 self.keep_left_to_right
1098 }
1099
1100 pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1101 self.keep_left_to_right = on;
1102 self
1103 }
1104
1105 pub fn enabled(&self) -> bool {
1106 self.enabled
1107 }
1108
1109 pub fn hit_test(&self) -> bool {
1110 self.hit_test
1111 }
1112
1113 pub fn clip_children(&self) -> bool {
1114 self.clip_children
1115 }
1116
1117 pub fn captures_wheel(&self) -> bool {
1118 self.captures_wheel
1119 }
1120
1121 pub fn draggable(&self) -> bool {
1126 self.draggable
1127 }
1128
1129 pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1130 self.draggable = v;
1131 self
1132 }
1133
1134 pub fn accepts_drops(&self) -> bool {
1137 self.accepts_drops
1138 }
1139
1140 pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1141 self.accepts_drops = v;
1142 self
1143 }
1144
1145 pub fn drag_data(&self) -> &str {
1147 self.drag.as_ref().map_or("", |d| d.data.as_str())
1148 }
1149
1150 pub fn drag_label(&self) -> &str {
1151 self.drag.as_ref().map_or("", |d| d.label.as_str())
1152 }
1153
1154 pub fn drag_image(&self) -> Option<ComponentId> {
1156 self.drag.as_ref().and_then(|d| d.image)
1157 }
1158
1159 pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1161 if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1162 d.image = None;
1163 }
1164 }
1165
1166 pub fn drop_types(&self) -> &str {
1168 self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1169 }
1170
1171 fn drag_decl(&mut self) -> &mut DragDecl {
1172 self.drag.get_or_insert_with(Default::default)
1173 }
1174
1175 pub fn can_focus(&self) -> bool {
1176 self.can_focus
1177 }
1178
1179 pub fn tab_stop(&self) -> bool {
1181 self.tab_stop
1182 }
1183
1184 pub fn popup_menu(&self) -> Option<ComponentId> {
1186 self.popup_menu
1187 }
1188
1189 pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1190 self.popup_menu = menu;
1191 self
1192 }
1193
1194 pub fn pan_on_touch(&self) -> bool {
1196 self.pan_on_touch
1197 }
1198
1199 pub fn cursor(&self) -> CursorShape {
1201 self.cursor
1202 }
1203
1204 pub fn opacity(&self) -> f32 {
1205 self.opacity
1206 }
1207
1208 pub fn cache_layer(&self) -> bool {
1210 self.cache_layer
1211 }
1212
1213 pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1214 self.cache_layer = on;
1215 self
1216 }
1217
1218 pub fn rotation(&self) -> f32 {
1221 self.rotation
1222 }
1223
1224 pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1225 self.shadow
1226 }
1227
1228 pub fn aspect_ratio(&self) -> f32 {
1232 self.aspect_ratio
1233 }
1234
1235 pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1236 self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1237 self
1238 }
1239
1240 pub fn max_width(&self) -> f32 {
1244 self.max_width
1245 }
1246
1247 pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1248 self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1249 self
1250 }
1251
1252 pub fn min_width(&self) -> f32 {
1257 self.min_width
1258 }
1259
1260 pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1261 self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1262 self
1263 }
1264
1265 pub fn min_height(&self) -> f32 {
1267 self.min_height
1268 }
1269
1270 pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1271 self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1272 self
1273 }
1274
1275 pub fn max_height(&self) -> f32 {
1277 self.max_height
1278 }
1279
1280 pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1281 self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1282 self
1283 }
1284
1285 pub fn clamp_width(&self, available: f32) -> f32 {
1288 let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1289 w.max(self.min_width)
1290 }
1291
1292 pub fn clamp_height(&self, height: f32) -> f32 {
1294 let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1295 h.max(self.min_height)
1296 }
1297
1298 pub fn self_align(&self) -> SelfAlign {
1301 self.self_align
1302 }
1303
1304 pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1305 self.self_align = align;
1306 self
1307 }
1308
1309 pub fn band_width(&self, available: f32) -> f32 {
1313 match self.self_align {
1314 SelfAlign::Stretch => self.clamp_width(available),
1315 _ if self.max_width > 0.0 => self.clamp_width(available),
1316 _ => self.clamp_width(self.width),
1317 }
1318 }
1319
1320 pub fn band_height(&self, available: f32) -> f32 {
1323 match self.self_align {
1324 SelfAlign::Stretch => self.clamp_height(available),
1325 _ if self.max_height > 0.0 => self.clamp_height(available),
1326 _ => self.clamp_height(self.height),
1327 }
1328 }
1329
1330 pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1333 let spare = (available - size).max(0.0);
1334 match self.self_align {
1335 SelfAlign::Start => 0.0,
1336 SelfAlign::End => spare,
1337 SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1338 }
1339 }
1340
1341 pub fn auto_size(&self) -> bool {
1346 self.auto_size
1347 }
1348
1349 pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1350 self.auto_size = on;
1351 self
1352 }
1353
1354 pub fn column_span(&self) -> u32 {
1357 self.column_span.max(1)
1358 }
1359
1360 pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1361 self.column_span = span.max(1);
1362 self
1363 }
1364
1365 pub fn text_scale(&self) -> f32 {
1367 self.text_scale
1368 }
1369
1370 pub fn spacing_scale(&self) -> f32 {
1372 self.spacing_scale
1373 }
1374
1375 pub fn tag(&self) -> i64 {
1376 self.tag
1377 }
1378
1379 pub fn style(&self) -> &str {
1381 &self.style
1382 }
1383
1384 pub fn theme_name(&self) -> &str {
1386 &self.theme
1387 }
1388
1389 pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1390 self.theme = v.into();
1391 self
1392 }
1393
1394 pub fn hint(&self) -> &str {
1396 &self.hint
1397 }
1398
1399 pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1400 self.hint = v.into();
1401 self
1402 }
1403
1404 pub fn state(&self) -> ControlState {
1405 self.state
1406 }
1407
1408 pub fn bounds(&self) -> RectF {
1410 self.bounds
1411 }
1412
1413 pub fn scroll_offset(&self) -> PointF {
1415 self.scroll_offset
1416 }
1417
1418 pub fn laid_out_scroll(&self) -> PointF {
1421 self.laid_out_scroll
1422 }
1423
1424 pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1427 self.scroll_offset = offset;
1428 self
1429 }
1430
1431 pub fn content_size(&self) -> SizeF {
1434 self.content_size
1435 }
1436
1437 pub fn set_left(&mut self, v: f32) -> &mut Self {
1440 self.left = v;
1441 self.anchor_ref = None;
1442 self
1443 }
1444
1445 pub fn set_top(&mut self, v: f32) -> &mut Self {
1446 self.top = v;
1447 self.anchor_ref = None;
1448 self
1449 }
1450
1451 pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1452 self.set_left(left).set_top(top)
1453 }
1454
1455 pub fn set_width(&mut self, v: f32) -> &mut Self {
1456 self.width = v.max(0.0);
1457 self.anchor_ref = None;
1458 self
1459 }
1460
1461 pub fn set_height(&mut self, v: f32) -> &mut Self {
1462 self.height = v.max(0.0);
1463 self.anchor_ref = None;
1464 self
1465 }
1466
1467 pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1468 self.set_width(width).set_height(height)
1469 }
1470
1471 pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1473 self.set_position(left, top).set_size(width, height)
1474 }
1475
1476 pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1477 self.margins = v.into();
1478 self
1479 }
1480
1481 pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1482 self.padding = v.into();
1483 self
1484 }
1485
1486 pub fn set_align(&mut self, v: Align) -> &mut Self {
1487 self.align = v;
1488 self.anchor_ref = None;
1489 self
1490 }
1491
1492 pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1493 self.anchors = v;
1494 self.anchor_ref = None;
1495 self
1496 }
1497
1498 pub fn set_visible(&mut self, v: bool) -> &mut Self {
1499 self.visible = v;
1500 self
1501 }
1502
1503 pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1504 self.enabled = v;
1505 self
1506 }
1507
1508 pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1509 self.hit_test = v;
1510 self
1511 }
1512
1513 pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1514 self.clip_children = v;
1515 self
1516 }
1517
1518 pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1519 self.captures_wheel = v;
1520 self
1521 }
1522
1523 pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1524 self.can_focus = v;
1525 self
1526 }
1527
1528 pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1532 self.pan_on_touch = v;
1533 self
1534 }
1535
1536 pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1537 self.tab_stop = v;
1538 self
1539 }
1540
1541 pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1542 self.cursor = v;
1543 self
1544 }
1545
1546 pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1547 self.opacity = v.clamp(0.0, 1.0);
1548 self
1549 }
1550
1551 pub fn translate(&self) -> PointF {
1553 self.translate
1554 }
1555
1556 pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1557 self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1558 self
1559 }
1560
1561 pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1562 self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1563 self
1564 }
1565
1566 pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1567 self.shadow = shadow;
1568 self
1569 }
1570
1571 pub fn set_tag(&mut self, v: i64) -> &mut Self {
1572 self.tag = v;
1573 self
1574 }
1575
1576 pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1577 self.style = v.into();
1578 self
1579 }
1580
1581 pub fn state_mut(&mut self) -> &mut ControlState {
1584 &mut self.state
1585 }
1586
1587 pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1590 Some(match name {
1591 "left" => self.left.into(),
1592 "top" => self.top.into(),
1593 "width" => self.width.into(),
1594 "height" => self.height.into(),
1595 "align" => self.align.into(),
1596 "anchors" => self.anchors.into(),
1597 "margins" => self.margins.into(),
1598 "padding" => self.padding.into(),
1599 "visible" => self.visible.into(),
1600 "enabled" => self.enabled.into(),
1601 "hit_test" => self.hit_test.into(),
1602 "clip_children" => self.clip_children.into(),
1603 "captures_wheel" => self.captures_wheel.into(),
1604 "can_focus" => self.can_focus.into(),
1605 "draggable" => self.draggable.into(),
1606 "accepts_drops" => self.accepts_drops.into(),
1607 "drag_data" => self.drag_data().into(),
1608 "drag_label" => self.drag_label().into(),
1609 "drag_image" => PropValue::Component(self.drag_image()),
1610 "drop_types" => self.drop_types().into(),
1611 "tab_stop" => self.tab_stop.into(),
1612 "cursor" => PropValue::enum_value(self.cursor),
1613 "opacity" => self.opacity.into(),
1614 "cache_layer" => self.cache_layer.into(),
1615 "rotation" => self.rotation.into(),
1616 "translate_x" => self.translate.x.into(),
1617 "translate_y" => self.translate.y.into(),
1618 "aspect_ratio" => self.aspect_ratio.into(),
1619 "max_width" => self.max_width.into(),
1620 "min_width" => self.min_width.into(),
1621 "min_height" => self.min_height.into(),
1622 "max_height" => self.max_height.into(),
1623 "self_align" => PropValue::enum_value(self.self_align),
1624 "auto_size" => self.auto_size.into(),
1625 "column_span" => (self.column_span() as i64).into(),
1626 "shadow" => crate::prop::PropType::to_value(&self.shadow),
1627 "style" => self.style.clone().into(),
1628 "fill" => crate::prop::PropType::to_value(&self.colors.fill),
1629 "border_color" => crate::prop::PropType::to_value(&self.colors.border),
1630 "text_color" => crate::prop::PropType::to_value(&self.colors.text),
1631 "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
1632 "success_color" => crate::prop::PropType::to_value(&self.colors.success),
1633 "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
1634 "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
1635 "font_family" => self.font.family.clone().into(),
1636 "font_size" => crate::prop::PropType::to_value(&self.font.size),
1637 "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
1638 "font_italic" => self.font.italic.into(),
1639 "font_underline" => self.font.underline.into(),
1640 "font_strikeout" => self.font.strikeout.into(),
1641 "theme" => self.theme.clone().into(),
1642 "hint" => self.hint.clone().into(),
1643 "tag" => self.tag.into(),
1644 "popup_menu" => PropValue::Component(self.popup_menu),
1645 _ => return None,
1646 })
1647 }
1648
1649 pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
1650 match name {
1651 "left" => self.set_left(value.to_f32()?),
1652 "top" => self.set_top(value.to_f32()?),
1653 "width" => self.set_width(value.to_f32()?),
1654 "height" => self.set_height(value.to_f32()?),
1655 "align" => self.set_align(value.to_enum()?),
1656 "anchors" => self.set_anchors(value.to_anchors()?),
1657 "margins" => self.set_margins(value.to_bounds()?),
1658 "padding" => self.set_padding(value.to_bounds()?),
1659 "visible" => self.set_visible(value.to_bool()?),
1660 "enabled" => self.set_enabled(value.to_bool()?),
1661 "hit_test" => self.set_hit_test(value.to_bool()?),
1662 "clip_children" => self.set_clip_children(value.to_bool()?),
1663 "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
1664 "can_focus" => self.set_can_focus(value.to_bool()?),
1665 "draggable" => self.set_draggable(value.to_bool()?),
1666 "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
1667 "drag_data" => {
1668 self.drag_decl().data = value.to_str()?.to_string();
1669 self
1670 }
1671 "drag_label" => {
1672 self.drag_decl().label = value.to_str()?.to_string();
1673 self
1674 }
1675 "drag_image" => {
1676 self.drag_decl().image = value.to_component()?;
1677 self
1678 }
1679 "drop_types" => {
1680 self.drag_decl().drop_types = value.to_str()?.to_string();
1681 self
1682 }
1683 "tab_stop" => self.set_tab_stop(value.to_bool()?),
1684 "cursor" => self.set_cursor(value.to_enum()?),
1685 "opacity" => self.set_opacity(value.to_f32()?),
1686 "cache_layer" => self.set_cache_layer(value.to_bool()?),
1687 "rotation" => self.set_rotation(value.to_f32()?),
1688 "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
1689 "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
1690 "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
1691 "max_width" => self.set_max_width(value.to_f32()?),
1692 "min_width" => self.set_min_width(value.to_f32()?),
1693 "min_height" => self.set_min_height(value.to_f32()?),
1694 "max_height" => self.set_max_height(value.to_f32()?),
1695 "self_align" => self.set_self_align(value.to_enum()?),
1696 "auto_size" => self.set_auto_size(value.to_bool()?),
1697 "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
1698 "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
1699 "style" => self.set_style(value.to_str()?),
1700 "fill" => {
1701 self.colors.fill = crate::prop::PropType::from_value(value)?;
1702 self
1703 }
1704 "border_color" => {
1705 self.colors.border = crate::prop::PropType::from_value(value)?;
1706 self
1707 }
1708 "text_color" => {
1709 self.colors.text = crate::prop::PropType::from_value(value)?;
1710 self
1711 }
1712 "accent_color" => {
1713 self.colors.accent = crate::prop::PropType::from_value(value)?;
1714 self
1715 }
1716 "success_color" => {
1717 self.colors.success = crate::prop::PropType::from_value(value)?;
1718 self
1719 }
1720 "warning_color" => {
1721 self.colors.warning = crate::prop::PropType::from_value(value)?;
1722 self
1723 }
1724 "danger_color" => {
1725 self.colors.danger = crate::prop::PropType::from_value(value)?;
1726 self
1727 }
1728 "font_family" => {
1729 self.font.family = value.to_str()?.to_string();
1730 self
1731 }
1732 "font_size" => {
1733 self.font.size = crate::prop::PropType::from_value(value)?;
1734 self
1735 }
1736 "font_weight" => {
1737 self.font.weight = font_weight_named(value.to_str()?)?;
1738 self
1739 }
1740 "font_italic" => {
1741 self.font.italic = value.to_bool()?;
1742 self
1743 }
1744 "font_underline" => {
1745 self.font.underline = value.to_bool()?;
1746 self
1747 }
1748 "font_strikeout" => {
1749 self.font.strikeout = value.to_bool()?;
1750 self
1751 }
1752 "theme" => self.set_theme_name(value.to_str()?),
1753 "hint" => self.set_hint(value.to_str()?),
1754 "tag" => self.set_tag(value.to_i64()?),
1755 "popup_menu" => {
1756 self.popup_menu = value.to_component()?;
1757 self
1758 }
1759 _ => return Err(Error::UnknownProperty(name.to_string())),
1760 };
1761 Ok(())
1762 }
1763}
1764
1765pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
1767
1768fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
1769 use crate::canvas::FontWeight::*;
1770 let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
1771 match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
1772 Some(0) => Ok(None),
1773 Some(i) => Ok(Some(all[i - 1])),
1774 None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
1775 }
1776}
1777
1778#[derive(Clone, Debug, Default, PartialEq)]
1782pub struct FontOverride {
1783 pub family: String,
1785 pub size: Option<f32>,
1786 pub weight: Option<crate::canvas::FontWeight>,
1787 pub italic: bool,
1789 pub underline: bool,
1790 pub strikeout: bool,
1791}
1792
1793impl FontOverride {
1794 pub fn is_empty(&self) -> bool {
1795 *self == Self::default()
1796 }
1797
1798 pub fn over(&self, parent: &FontOverride) -> FontOverride {
1800 FontOverride {
1801 family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
1802 size: self.size.or(parent.size),
1803 weight: self.weight.or(parent.weight),
1804 italic: self.italic || parent.italic,
1805 underline: self.underline || parent.underline,
1806 strikeout: self.strikeout || parent.strikeout,
1807 }
1808 }
1809
1810 pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
1812 if !self.family.is_empty() {
1813 font.family = self.family.clone();
1814 }
1815 if let Some(size) = self.size.filter(|s| *s > 0.0) {
1816 font.size = size;
1817 }
1818 if let Some(weight) = self.weight {
1819 font.weight = weight;
1820 }
1821 font.italic |= self.italic;
1822 font.underline |= self.underline;
1823 font.strikeout |= self.strikeout;
1824 }
1825}
1826
1827impl ControlBase {
1828 pub fn font(&self) -> &FontOverride {
1830 &self.font
1831 }
1832
1833 pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
1834 self.font = font;
1835 self
1836 }
1837}
1838
1839#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1845pub struct ColorOverride {
1846 pub fill: Option<crate::Color>,
1848 pub border: Option<crate::Color>,
1849 pub text: Option<crate::Color>,
1850 pub accent: Option<crate::Color>,
1853 pub success: Option<crate::Color>,
1855 pub warning: Option<crate::Color>,
1856 pub danger: Option<crate::Color>,
1857}
1858
1859impl ColorOverride {
1860 pub fn is_empty(&self) -> bool {
1861 *self == Self::default()
1862 }
1863
1864 pub(crate) fn recolors_theme(&self) -> bool {
1866 !self.is_empty()
1867 }
1868
1869 pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
1871 use crate::Color;
1872 let mut t = theme.clone();
1873 let mut set = |name: &str, c: Color| {
1874 t.colors.insert(name.to_string(), c);
1875 };
1876 if let Some(a) = self.accent {
1877 let dark = luminance(a) < 0.5;
1878 set("primary", a);
1879 set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
1880 set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
1881 set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
1882 set("focus_ring", a);
1883 set("selection", a.with_opacity(0.25));
1884 set("primary_soft", a.with_opacity(0.1));
1885 set("primary_container", a.lerp(Color::WHITE, 0.82));
1886 }
1887 if let Some(c) = self.fill {
1888 let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
1890 set("surface", c);
1891 set("background", c);
1892 set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
1893 }
1894 if let Some(c) = self.text {
1895 set("text", c);
1896 set("text_muted", c.with_opacity(0.65));
1897 for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
1898 set(on, c);
1899 }
1900 }
1901 if let Some(c) = self.border {
1902 set("border", c);
1903 set("track", c);
1904 }
1905 for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
1906 if let Some(c) = color {
1907 set(token, c);
1908 set(&format!("{token}_soft"), c.with_opacity(0.1));
1909 set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
1910 set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
1911 if token == "success" {
1912 set("meter_low", c);
1913 } else if token == "danger" {
1914 set("meter_high", c);
1915 } else {
1916 set("meter_mid", c);
1917 }
1918 }
1919 }
1920 t
1921 }
1922}
1923
1924pub(crate) fn luminance(c: crate::Color) -> f32 {
1926 (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
1927}
1928
1929#[derive(Clone, Copy, Debug, PartialEq)]
1931pub struct Connection {
1932 pub from: ComponentId,
1933 pub from_at: (f32, f32),
1935 pub to: ComponentId,
1936 pub to_at: (f32, f32),
1937}
1938
1939impl Connection {
1940 pub const STUB: f32 = 16.0;
1942
1943 fn normal(at: (f32, f32)) -> PointF {
1945 let (x, y) = at;
1946 let d = [(x, PointF::new(-1.0, 0.0)), (1.0 - x, PointF::new(1.0, 0.0)), (y, PointF::new(0.0, -1.0)), (1.0 - y, PointF::new(0.0, 1.0))];
1947 d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
1948 }
1949
1950 pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
1953 let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
1954 let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
1955 let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
1956 let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
1957 let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
1958 let mut points = vec![p0, s0];
1959 if n0.x != 0.0 {
1960 let mx = (s0.x + s1.x) / 2.0;
1962 points.push(PointF::new(mx, s0.y));
1963 points.push(PointF::new(mx, s1.y));
1964 } else {
1965 let my = (s0.y + s1.y) / 2.0;
1966 points.push(PointF::new(s0.x, my));
1967 points.push(PointF::new(s1.x, my));
1968 }
1969 points.push(s1);
1970 points.push(p1);
1971 points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
1972 points
1973 }
1974}
1975
1976#[derive(Clone, Debug, Default, PartialEq)]
1978pub struct DragDecl {
1979 pub data: String,
1980 pub label: String,
1981 pub drop_types: String,
1982 pub image: Option<ComponentId>,
1984}