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
55#[derive(Clone, Debug, PartialEq)]
57pub enum ClipShape {
58 RoundRect(f32),
60 Corners(crate::Bounds),
63 Ellipse,
65 Path(std::sync::Arc<crate::Path>),
68}
69
70impl ClipShape {
71 pub fn radius(&self, rect: crate::RectF) -> f32 {
74 let limit = rect.width.min(rect.height) / 2.0;
75 match self {
76 ClipShape::RoundRect(r) => r.clamp(0.0, limit),
77 ClipShape::Corners(c) => c.left.max(c.top).max(c.right).max(c.bottom).clamp(0.0, limit),
78 ClipShape::Ellipse => limit,
79 ClipShape::Path(_) => 0.0,
80 }
81 }
82
83 pub fn outline(&self, rect: crate::RectF) -> crate::Path {
85 let mut path = crate::Path::new();
86 match self {
87 ClipShape::RoundRect(_) => {
88 path.rect(rect, self.radius(rect));
89 }
90 ClipShape::Corners(c) => path = crate::Path::corners(rect, *c),
91 ClipShape::Ellipse => {
92 path.ellipse(rect);
93 }
94 ClipShape::Path(p) => {
95 let b = p.bounds();
96 let sx = if b.width > 0.0 { rect.width / b.width } else { 1.0 };
97 let sy = if b.height > 0.0 { rect.height / b.height } else { 1.0 };
98 path = p.map_points(|q| crate::PointF::new(rect.x + (q.x - b.x) * sx, rect.y + (q.y - b.y) * sy));
99 }
100 }
101 path
102 }
103
104 pub fn fill(&self, canvas: &mut dyn crate::Canvas, rect: crate::RectF, brush: &crate::Brush) {
106 match self {
107 ClipShape::RoundRect(_) => canvas.fill_rect(rect, self.radius(rect), brush),
108 ClipShape::Ellipse => canvas.fill_ellipse(rect, brush),
109 _ => canvas.fill_path(&self.outline(rect), brush),
110 }
111 }
112
113 pub fn clip(&self, canvas: &mut dyn crate::Canvas, rect: crate::RectF) {
115 match self {
116 ClipShape::RoundRect(_) => canvas.clip_round_rect(rect, self.radius(rect)),
117 _ => canvas.clip_path(&self.outline(rect), false),
118 }
119 }
120}
121
122pub trait Component: Any {
153 fn class_name(&self) -> &'static str;
156
157 fn inner(&self) -> Option<&dyn Component> {
159 None
160 }
161
162 fn inner_mut(&mut self) -> Option<&mut dyn Component> {
163 None
164 }
165
166 fn class_chain(&self, out: &mut Vec<&'static str>) {
169 out.push(self.class_name());
170 if let Some(inner) = self.inner() {
171 inner.class_chain(out);
172 }
173 }
174
175 fn control(&self) -> Option<&ControlBase> {
177 self.inner().and_then(|i| i.control())
178 }
179
180 fn control_mut(&mut self) -> Option<&mut ControlBase> {
181 self.inner_mut().and_then(|i| i.control_mut())
182 }
183
184 fn props(&self) -> &'static [PropInfo] {
187 &[]
188 }
189
190 fn default_event(&self) -> Option<&'static str> {
194 self.inner().and_then(|c| c.default_event())
195 }
196
197 fn get_prop(&self, _name: &str) -> Option<PropValue> {
199 None
200 }
201
202 fn set_prop(&mut self, name: &str, _value: PropValue) -> Result<()> {
205 Err(Error::UnknownProperty(name.to_string()))
206 }
207
208 fn notification(&mut self, freed: ComponentId) {
211 if let Some(inner) = self.inner_mut() {
212 inner.notification(freed);
213 }
214 }
215
216 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
218 if let Some(inner) = self.inner() {
219 inner.paint(canvas, ctx);
220 }
221 }
222
223 fn transparent_background(&self) -> bool {
227 self.inner().is_some_and(|i| i.transparent_background())
228 }
229
230 fn opaque(&self, style: &crate::theme::ResolvedStyle) -> bool {
235 self.inner().is_some_and(|i| i.opaque(style))
236 }
237
238 fn clip_shape(&self) -> Option<ClipShape> {
242 self.inner().and_then(|i| i.clip_shape())
243 }
244
245 fn paint_after(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
247 if let Some(inner) = self.inner() {
248 inner.paint_after(canvas, ctx);
249 }
250 }
251
252 fn paint_is_pure(&self) -> bool {
259 false
260 }
261
262 fn provided(&self) -> Option<crate::providers::Provided<'_>> {
265 None
266 }
267
268 fn resized(&mut self, ctx: &mut EventCtx<'_>) {
270 if let Some(inner) = self.inner_mut() {
271 inner.resized(ctx);
272 }
273 }
274
275 fn click(&mut self, ctx: &mut EventCtx<'_>) {
277 match self.inner_mut() {
278 Some(inner) => inner.click(ctx),
279 None => ctx.fire("on_click", EventArgs::None),
280 }
281 }
282
283 fn pointer_down(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
284 if let Some(inner) = self.inner_mut() {
285 inner.pointer_down(ctx, event);
286 }
287 }
288
289 fn pointer_up(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
290 if let Some(inner) = self.inner_mut() {
291 inner.pointer_up(ctx, event);
292 }
293 }
294
295 fn pointer_move(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
296 if let Some(inner) = self.inner_mut() {
297 inner.pointer_move(ctx, event);
298 }
299 }
300
301 fn pointer_enter(&mut self, ctx: &mut EventCtx<'_>) {
302 if let Some(inner) = self.inner_mut() {
303 inner.pointer_enter(ctx);
304 }
305 }
306
307 fn pointer_leave(&mut self, ctx: &mut EventCtx<'_>) {
308 if let Some(inner) = self.inner_mut() {
309 inner.pointer_leave(ctx);
310 }
311 }
312
313 fn wheel(&mut self, ctx: &mut EventCtx<'_>, event: &WheelEvent) {
314 if let Some(inner) = self.inner_mut() {
315 inner.wheel(ctx, event);
316 }
317 }
318
319 fn gesture(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::GestureEvent) {
322 if let Some(inner) = self.inner_mut() {
323 inner.gesture(ctx, event);
324 }
325 }
326
327 fn swipe(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::SwipeEvent) {
330 if let Some(inner) = self.inner_mut() {
331 inner.swipe(ctx, event);
332 }
333 }
334
335 fn touch_end(&mut self, ctx: &mut EventCtx<'_>) {
339 if let Some(inner) = self.inner_mut() {
340 inner.touch_end(ctx);
341 }
342 }
343
344 fn edge_swipe(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::SwipeEvent) -> bool {
347 match self.inner_mut() {
348 Some(inner) => inner.edge_swipe(ctx, event),
349 None => false,
350 }
351 }
352
353 fn context_menu(&mut self, ctx: &mut EventCtx<'_>, at: PointF, touch: bool) -> bool {
358 match self.inner_mut() {
359 Some(inner) => inner.context_menu(ctx, at, touch),
360 None => false,
361 }
362 }
363
364 fn key_down(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
365 if let Some(inner) = self.inner_mut() {
366 inner.key_down(ctx, event);
367 }
368 }
369
370 fn key_up(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
371 if let Some(inner) = self.inner_mut() {
372 inner.key_up(ctx, event);
373 }
374 }
375
376 fn shortcut(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
380 if let Some(inner) = self.inner_mut() {
381 inner.shortcut(ctx, event);
382 }
383 }
384
385 fn platform_hooks(&self) -> Option<&dyn PlatformHooks> {
388 self.inner().and_then(|i| i.platform_hooks())
389 }
390
391 fn platform_hooks_mut(&mut self) -> Option<&mut dyn PlatformHooks> {
392 self.inner_mut().and_then(|i| i.platform_hooks_mut())
393 }
394
395 fn design_hooks(&self) -> Option<&dyn DesignHooks> {
398 self.inner().and_then(|i| i.design_hooks())
399 }
400
401 fn design_hooks_mut(&mut self) -> Option<&mut dyn DesignHooks> {
402 self.inner_mut().and_then(|i| i.design_hooks_mut())
403 }
404
405 fn contains_point(&self, local: PointF, size: SizeF) -> bool {
408 self.inner().map_or(true, |i| i.contains_point(local, size))
409 }
410
411 fn hit_slop(&self) -> f32 {
415 self.inner().map_or(0.0, |i| i.hit_slop())
416 }
417
418 fn scroll_axes(&self) -> (bool, bool) {
421 self.inner().map_or((false, false), |i| i.scroll_axes())
422 }
423
424 fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
429 None
430 }
431
432 fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
435 None
436 }
437
438 fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
443 false
444 }
445
446 fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
449
450 fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
452
453 fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
455
456 fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
458
459 fn accepts_text(&self) -> bool {
460 self.inner().is_some_and(|i| i.accepts_text())
461 }
462
463 fn captures_key(&self, event: &KeyEvent) -> bool {
466 self.inner().is_some_and(|i| i.captures_key(event))
467 }
468
469 fn mnemonic_text(&self) -> Option<&str> {
472 self.inner().and_then(|i| i.mnemonic_text())
473 }
474
475 fn mnemonic_focuses_child(&self) -> bool {
477 self.inner().is_some_and(|i| i.mnemonic_focuses_child())
478 }
479
480 fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
482 if let Some(inner) = self.inner_mut() {
483 inner.text_input(ctx, text);
484 }
485 }
486
487 fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
488 if let Some(inner) = self.inner_mut() {
489 inner.focus_enter(ctx);
490 }
491 }
492
493 fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
494 if let Some(inner) = self.inner_mut() {
495 inner.focus_exit(ctx);
496 }
497 }
498
499 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
503 if let Some(inner) = self.inner_mut() {
504 inner.property_changed(ctx, name);
505 }
506 }
507
508 fn checked_state(&self) -> Option<bool> {
511 self.inner().and_then(|i| i.checked_state())
512 }
513
514 fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
521 match self.inner() {
522 Some(inner) => inner.change_args(name, value),
523 None => Some(EventArgs::Value(value.clone())),
524 }
525 }
526
527 fn paint_only_property(&self, name: &str) -> bool {
532 self.inner().is_some_and(|inner| inner.paint_only_property(name))
533 }
534
535 fn timer_interval(&self) -> Option<f64> {
538 self.inner().and_then(|i| i.timer_interval())
539 }
540
541 fn timer_precision(&self) -> crate::TimerPrecision {
543 self.inner().map(|i| i.timer_precision()).unwrap_or_default()
544 }
545
546 fn timer_background(&self) -> bool {
549 self.inner().is_some_and(|i| i.timer_background())
550 }
551
552 fn timer_late(&mut self, late: f64) {
554 if let Some(inner) = self.inner_mut() {
555 inner.timer_late(late);
556 }
557 }
558
559 fn frame(&mut self, ctx: &mut EventCtx<'_>) -> bool {
563 self.inner_mut().is_some_and(|inner| inner.frame(ctx))
564 }
565
566 fn timer(&mut self, ctx: &mut EventCtx<'_>) {
569 match self.inner_mut() {
570 Some(inner) => inner.timer(ctx),
571 None => ctx.fire("on_timer", EventArgs::None),
572 }
573 }
574
575 fn arrange(&self, area: RectF, children: &[ArrangeItem]) -> Option<Vec<RectF>> {
580 self.inner().and_then(|i| i.arrange(area, children))
581 }
582
583 fn baseline(&self, ui: &crate::Ui, id: ComponentId, height: f32) -> Option<f32> {
587 self.inner().and_then(|i| i.baseline(ui, id, height))
588 }
589
590 fn dock_gap(&self) -> f32 {
593 self.inner().map_or(0.0, |i| i.dock_gap())
594 }
595
596 fn auto_height(&self, ui: &crate::Ui, id: ComponentId, width: f32) -> Option<f32> {
600 self.inner().and_then(|i| i.auto_height(ui, id, width))
601 }
602
603 fn auto_width(&self, ui: &crate::Ui, id: ComponentId) -> Option<f32> {
607 self.inner().and_then(|i| i.auto_width(ui, id))
608 }
609
610 fn closes_on_outside_press(&self) -> bool {
617 false
618 }
619
620 fn dismissed(&mut self, ctx: &mut EventCtx<'_>) -> bool {
626 let _ = ctx;
627 false
628 }
629
630 fn dies_with(&self) -> Option<ComponentId> {
634 self.inner().and_then(|i| i.dies_with())
635 }
636
637 fn access_items(&self, ui: &crate::Ui, id: ComponentId) -> Vec<crate::automation::AccessItem> {
640 self.inner().map_or_else(Vec::new, |i| i.access_items(ui, id))
641 }
642
643 fn access_action(&mut self, ctx: &mut EventCtx<'_>, index: usize, action: crate::automation::ItemAction) -> bool {
646 self.inner_mut().is_some_and(|i| i.access_action(ctx, index, action))
647 }
648
649 fn attach(&self) -> Option<(ComponentId, f32, f32)> {
653 self.inner().and_then(|i| i.attach())
654 }
655
656 fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
660 self.inner().map(|i| i.event_info(event)).unwrap_or_default()
661 }
662
663 fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
667 if let Some(inner) = self.inner_mut() {
668 inner.message(ctx, message);
669 }
670 }
671
672 fn methods(&self) -> &'static [MethodInfo] {
675 &[]
676 }
677
678 fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
682 let class = self.class_name();
683 match self.inner_mut() {
684 Some(inner) => inner.invoke(ctx, method, args),
685 None => Err(format!("{class} não tem o método '{method}'")),
686 }
687 }
688
689}
690
691pub trait PlatformHooks {
695 fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
697 None
698 }
699
700 fn tray(&self) -> Option<crate::tray::TraySpec> {
702 None
703 }
704
705 fn native_view(&self) -> Option<NativeView> {
709 None
710 }
711
712 fn take_native_commands(&self) -> Vec<NativeCommand> {
714 Vec::new()
715 }
716
717 fn connection(&self) -> Option<Connection> {
721 None
722 }
723
724 fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
727 false
728 }
729
730 fn files_hovering(&mut self, _ctx: &mut EventCtx<'_>, _paths: Option<&[String]>) -> bool {
733 false
734 }
735}
736
737pub trait DesignHooks {
741 fn design_grip(&self, _local: PointF) -> Option<usize> {
744 None
745 }
746
747 fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
751 None
752 }
753}
754
755#[derive(Clone, Copy, Debug, PartialEq)]
757pub struct ArrangeItem {
758 pub id: ComponentId,
759 pub size: SizeF,
760 pub margins: Bounds,
762 pub span: u32,
764 pub row_span: u32,
766 pub cell: Option<(u32, u32)>,
768 pub grow: f32,
770 pub baseline: Option<f32>,
772 pub spacing: f32,
775}
776
777impl ArrangeItem {
778 pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
780 ArrangeItem {
781 id,
782 size: SizeF::new(cb.width(), cb.height()),
783 margins: cb.margins(),
784 span: cb.column_span(),
785 row_span: cb.row_span(),
786 cell: cb.grid_cell(),
787 grow: cb.grow(),
788 baseline: None,
789 spacing: cb.spacing_scale(),
790 }
791 }
792}
793
794#[derive(Clone, Debug, PartialEq)]
796pub enum NativeView {
797 Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String, background: Option<crate::Color>, data_dir: String, browser_args: String },
806}
807
808#[derive(Clone, Debug, PartialEq)]
812pub struct WebMessage {
813 pub text: String,
814 pub url: String,
815}
816
817pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
821 allowed.is_empty()
822 || url.starts_with("about:")
823 || url.starts_with("data:")
824 || allowed.iter().any(|a| {
825 let a = a.trim_end_matches('/');
826 url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
827 })
828}
829
830pub fn url_origin(url: &str) -> String {
832 let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
833 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
834 format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
835}
836
837#[derive(Clone, Copy, Debug, PartialEq)]
840pub struct MethodInfo {
841 pub name: &'static str,
842 pub args: &'static [PropKind],
843 pub returns: Option<PropKind>,
844 pub params: &'static [&'static str],
847}
848
849impl MethodInfo {
850 pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
851 Self { name, args, returns, params: &[] }
852 }
853
854 pub const fn params(self, names: &'static [&'static str]) -> Self {
857 Self { params: names, ..self }
858 }
859}
860
861#[derive(Clone, Debug, PartialEq)]
863pub enum NativeCommand {
864 Eval(String),
866 Back,
867 Forward,
868 Reload,
869}
870
871#[derive(Clone, Debug, PartialEq)]
873pub struct NativeViewSlot {
874 pub id: ComponentId,
875 pub rect: crate::RectF,
876 pub clip: Option<crate::RectF>,
879 pub visible: bool,
880 pub view: NativeView,
881 pub commands: Vec<NativeCommand>,
882}
883
884pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
890 let mut out: Vec<PropInfo> = Vec::new();
891 let mut seen = std::collections::HashSet::new();
894 let mut push = |info: &PropInfo| {
895 if seen.insert(info.name) {
896 out.push(*info);
897 }
898 };
899 let mut layer = Some(component);
900 while let Some(l) = layer {
901 l.props().iter().for_each(&mut push);
902 layer = l.inner();
903 }
904 if component.control().is_some() {
905 ControlBase::PROPS.iter().for_each(&mut push);
906 }
907 out
908}
909
910pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
913 let mut layer = Some(component);
914 while let Some(l) = layer {
915 if let Some(info) = l.props().iter().find(|p| p.name == name) {
916 return Some(*info);
917 }
918 layer = l.inner();
919 }
920 if component.control().is_some() {
921 return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
922 }
923 None
924}
925
926pub const VALUE_PROPERTIES: [&str; 19] = [
931 "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
932 "angle", "pressed", "position", "low", "high",
933];
934
935pub fn is_value_property(info: &PropInfo) -> bool {
939 match info.name {
940 "tab_index" | "expanded" => true,
941 name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
942 }
943}
944
945pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
946 let mut layer = Some(component);
947 while let Some(l) = layer {
948 if let Some(v) = l.get_prop(name) {
949 return Some(v);
950 }
951 layer = l.inner();
952 }
953 component.control().and_then(|cb| cb.get_prop(name))
954}
955
956#[derive(Clone, Copy, Debug, PartialEq)]
959pub(crate) struct AnchorRef {
960 pub(crate) parent: SizeF,
961 pub(crate) rect: RectF,
962}
963
964#[derive(Clone, Debug)]
969pub struct ControlBase {
970 left: f32,
972 top: f32,
974 width: f32,
976 height: f32,
978 margins: Bounds,
980 padding: Bounds,
982 align: Align,
984 anchors: Anchors,
986 visible: bool,
988 enabled: bool,
990 hit_test: bool,
992 clip_children: bool,
994 inherit_state: bool,
997 translatable: bool,
1001 captures_wheel: bool,
1004 captures_gesture: bool,
1007 can_focus: bool,
1009 draggable: bool,
1011 accepts_drops: bool,
1013 drag: Option<Box<DragDecl>>,
1016 tab_stop: bool,
1018 pan_on_touch: bool,
1020 pub(crate) popup_menu: Option<ComponentId>,
1022 cursor: CursorShape,
1024 opacity: f32,
1026 blend_mode: crate::BlendMode,
1029 rotation: f32,
1031 scale: f32,
1036 translate: PointF,
1038 cache_layer: bool,
1041 aspect_ratio: f32,
1043 max_width: f32,
1045 min_width: f32,
1047 min_height: f32,
1049 max_height: f32,
1051 self_align: SelfAlign,
1053 auto_size: bool,
1055 column_span: u32,
1057 grid_row: i16,
1060 grid_column: i16,
1062 row_span: u16,
1064 grow: f32,
1067 pub(crate) text_scale: f32,
1070 pub(crate) spacing_scale: f32,
1071 shadow: Option<crate::canvas::Shadow>,
1073 tag: i64,
1075 rare: Option<Box<RareTexts>>,
1078 style: String,
1080 theme: String,
1082 hint: String,
1084 state: ControlState,
1085 pub(crate) bounds: RectF,
1086 pub(crate) anchor_ref: Option<AnchorRef>,
1087 pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1090 pub(crate) design_hidden: bool,
1093 pub(crate) design_only: bool,
1095 pub(crate) keep_left_to_right: bool,
1098 pub(crate) colors: ColorOverride,
1100 pub(crate) font: FontOverride,
1102 scroll_offset: PointF,
1104 pub(crate) laid_out_scroll: PointF,
1107 pub(crate) safe_area: Bounds,
1109 pub(crate) content_size: SizeF,
1111}
1112
1113impl Default for ControlBase {
1114 fn default() -> Self {
1115 Self::new(100.0, 100.0)
1116 }
1117}
1118
1119impl ControlBase {
1120 pub const PROPS: &'static [PropInfo] = &[
1122 PropInfo::new("left", PropKind::Float, "Layout"),
1123 PropInfo::new("top", PropKind::Float, "Layout"),
1124 PropInfo::new("width", PropKind::Float, "Layout"),
1125 PropInfo::new("height", PropKind::Float, "Layout"),
1126 PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
1127 PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
1128 PropInfo::new("margins", PropKind::Bounds, "Layout"),
1129 PropInfo::new("padding", PropKind::Bounds, "Layout"),
1130 PropInfo::new("visible", PropKind::Bool, "Behavior"),
1131 PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1132 PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1133 PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1134 PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1135 PropInfo::new("translate", PropKind::Bool, "Behavior"),
1136 PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1137 PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1138 PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1139 PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1140 PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1141 PropInfo::new("drag_data", PropKind::String, "Behavior"),
1142 PropInfo::new("drag_label", PropKind::String, "Behavior"),
1143 PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1144 PropInfo::new("drop_types", PropKind::String, "Behavior"),
1145 PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1146 PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
1147 PropInfo::new("opacity", PropKind::Float, "Appearance"),
1148 PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance"),
1149 PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1150 PropInfo::new("rotation", PropKind::Angle, "Layout"),
1151 PropInfo::new("scale", PropKind::Float, "Layout"),
1152 PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1153 PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1154 PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1155 PropInfo::new("max_width", PropKind::Float, "Layout"),
1156 PropInfo::new("min_width", PropKind::Float, "Layout"),
1157 PropInfo::new("min_height", PropKind::Float, "Layout"),
1158 PropInfo::new("max_height", PropKind::Float, "Layout"),
1159 PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
1160 PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1161 PropInfo::new("column_span", PropKind::Int, "Layout"),
1162 PropInfo::new("grid_row", PropKind::Int, "Layout"),
1163 PropInfo::new("grid_column", PropKind::Int, "Layout"),
1164 PropInfo::new("row_span", PropKind::Int, "Layout"),
1165 PropInfo::new("grow", PropKind::Float, "Layout"),
1166 PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1167 PropInfo::new("style", PropKind::String, "Appearance"),
1168 PropInfo::new("theme", PropKind::String, "Appearance"),
1169 PropInfo::new("fill", PropKind::Color, "Appearance"),
1170 PropInfo::new("border_color", PropKind::Color, "Appearance"),
1171 PropInfo::new("text_color", PropKind::Color, "Appearance"),
1172 PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1173 PropInfo::new("success_color", PropKind::Color, "Appearance"),
1174 PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1175 PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1176 PropInfo::new("font_family", PropKind::String, "Font"),
1177 PropInfo::new("font_size", PropKind::Float, "Font"),
1178 PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1179 PropInfo::new("font_italic", PropKind::Bool, "Font"),
1180 PropInfo::new("font_underline", PropKind::Bool, "Font"),
1181 PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1182 PropInfo::new("hint", PropKind::String, "Behavior"),
1183 PropInfo::new("tag", PropKind::Int, "Misc"),
1184 PropInfo::new("tag_string", PropKind::String, "Misc"),
1185 PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1186 PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1187 PropInfo::new("on_click", PropKind::Event, "Events"),
1188 PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
1189 PropInfo::new("on_long_press", PropKind::Event, "Events"),
1190 PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
1191 PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
1192 PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
1193 PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
1194 PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
1195 PropInfo::new("on_wheel", PropKind::Event, "Events"),
1196 PropInfo::new("on_gesture", PropKind::Event, "Events"),
1197 PropInfo::new("on_swipe", PropKind::Event, "Events"),
1198 PropInfo::new("on_key_down", PropKind::Event, "Events"),
1199 PropInfo::new("on_key_press", PropKind::Event, "Events"),
1200 PropInfo::new("on_key_up", PropKind::Event, "Events"),
1201 PropInfo::new("on_enter", PropKind::Event, "Events"),
1202 PropInfo::new("on_exit", PropKind::Event, "Events"),
1203 PropInfo::new("on_resize", PropKind::Event, "Events"),
1204 PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1205 PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1206 PropInfo::new("on_drag_move", PropKind::Event, "Events"),
1207 PropInfo::new("on_drag_leave", PropKind::Event, "Events"),
1208 PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
1209 PropInfo::new("on_drag_end", PropKind::Event, "Events"),
1210 ];
1211
1212 pub fn new(width: f32, height: f32) -> Self {
1213 Self {
1214 left: 0.0,
1215 top: 0.0,
1216 width,
1217 height,
1218 margins: Bounds::ZERO,
1219 padding: Bounds::ZERO,
1220 align: Align::None,
1221 anchors: Anchors::default(),
1222 visible: true,
1223 enabled: true,
1224 hit_test: true,
1225 clip_children: false,
1226 inherit_state: false,
1227 translatable: true,
1228 captures_wheel: false,
1229 captures_gesture: false,
1230 can_focus: false,
1231 draggable: false,
1232 accepts_drops: false,
1233 drag: None,
1234 tab_stop: true,
1235 pan_on_touch: true,
1236 popup_menu: None,
1237 cursor: CursorShape::Default,
1238 opacity: 1.0,
1239 blend_mode: crate::BlendMode::Normal,
1240 rotation: 0.0,
1241 scale: 1.0,
1242 translate: PointF::ZERO,
1243 cache_layer: false,
1244 aspect_ratio: 0.0,
1245 max_width: 0.0,
1246 min_width: 0.0,
1247 min_height: 0.0,
1248 max_height: 0.0,
1249 self_align: SelfAlign::Stretch,
1250 auto_size: false,
1251 column_span: 1,
1252 grid_row: -1,
1253 grid_column: -1,
1254 row_span: 1,
1255 grow: 0.0,
1256 text_scale: 1.0,
1257 spacing_scale: 1.0,
1258 shadow: None,
1259 tag: 0,
1260 rare: None,
1261 style: String::new(),
1262 theme: String::new(),
1263 hint: String::new(),
1264 state: ControlState::default(),
1265 bounds: RectF::new(0.0, 0.0, width, height),
1266 anchor_ref: None,
1267 follow: None,
1268 design_hidden: false,
1269 design_only: false,
1270 keep_left_to_right: false,
1271 colors: ColorOverride::default(),
1272 font: FontOverride::default(),
1273 scroll_offset: PointF::ZERO,
1274 laid_out_scroll: PointF::ZERO,
1275 content_size: SizeF::ZERO,
1276 safe_area: Bounds::default(),
1277 }
1278 }
1279
1280 pub fn left(&self) -> f32 {
1283 self.left
1284 }
1285
1286 pub fn top(&self) -> f32 {
1287 self.top
1288 }
1289
1290 pub fn width(&self) -> f32 {
1291 self.width
1292 }
1293
1294 pub fn height(&self) -> f32 {
1295 self.height
1296 }
1297
1298 pub fn position(&self) -> PointF {
1299 PointF::new(self.left, self.top)
1300 }
1301
1302 pub fn size(&self) -> SizeF {
1303 SizeF::new(self.width, self.height)
1304 }
1305
1306 pub fn margins(&self) -> Bounds {
1309 if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1310 }
1311
1312 pub fn padding(&self) -> Bounds {
1314 if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1315 }
1316
1317 pub fn align(&self) -> Align {
1318 self.align
1319 }
1320
1321 pub fn anchors(&self) -> Anchors {
1322 self.anchors
1323 }
1324
1325 pub fn visible(&self) -> bool {
1326 self.visible
1327 }
1328
1329 pub fn design_only(&self) -> bool {
1331 self.design_only
1332 }
1333
1334 pub fn colors(&self) -> ColorOverride {
1336 self.colors
1337 }
1338
1339 pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1340 self.colors = colors;
1341 self
1342 }
1343
1344 pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1345 self.design_only = on;
1346 self
1347 }
1348
1349 pub fn keep_left_to_right(&self) -> bool {
1351 self.keep_left_to_right
1352 }
1353
1354 pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1355 self.keep_left_to_right = on;
1356 self
1357 }
1358
1359 pub fn enabled(&self) -> bool {
1360 self.enabled
1361 }
1362
1363 pub fn hit_test(&self) -> bool {
1364 self.hit_test
1365 }
1366
1367 pub fn translatable(&self) -> bool {
1368 self.translatable
1369 }
1370
1371 pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1372 self.translatable = v;
1373 self
1374 }
1375
1376 pub fn inherit_state(&self) -> bool {
1377 self.inherit_state
1378 }
1379
1380 pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1381 self.inherit_state = v;
1382 self
1383 }
1384
1385 pub fn clip_children(&self) -> bool {
1386 self.clip_children
1387 }
1388
1389 pub fn captures_wheel(&self) -> bool {
1390 self.captures_wheel
1391 }
1392
1393 pub fn captures_gesture(&self) -> bool {
1394 self.captures_gesture
1395 }
1396
1397 pub fn draggable(&self) -> bool {
1402 self.draggable
1403 }
1404
1405 pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1406 self.draggable = v;
1407 self
1408 }
1409
1410 pub fn accepts_drops(&self) -> bool {
1413 self.accepts_drops
1414 }
1415
1416 pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1417 self.accepts_drops = v;
1418 self
1419 }
1420
1421 pub fn drag_data(&self) -> &str {
1423 self.drag.as_ref().map_or("", |d| d.data.as_str())
1424 }
1425
1426 pub fn drag_label(&self) -> &str {
1427 self.drag.as_ref().map_or("", |d| d.label.as_str())
1428 }
1429
1430 pub fn drag_image(&self) -> Option<ComponentId> {
1432 self.drag.as_ref().and_then(|d| d.image)
1433 }
1434
1435 pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1437 if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1438 d.image = None;
1439 }
1440 }
1441
1442 pub fn drop_types(&self) -> &str {
1444 self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1445 }
1446
1447 fn drag_decl(&mut self) -> &mut DragDecl {
1448 self.drag.get_or_insert_with(Default::default)
1449 }
1450
1451 pub fn can_focus(&self) -> bool {
1452 self.can_focus
1453 }
1454
1455 pub fn tab_stop(&self) -> bool {
1457 self.tab_stop
1458 }
1459
1460 pub fn popup_menu(&self) -> Option<ComponentId> {
1462 self.popup_menu
1463 }
1464
1465 pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1466 self.popup_menu = menu;
1467 self
1468 }
1469
1470 pub fn pan_on_touch(&self) -> bool {
1472 self.pan_on_touch
1473 }
1474
1475 pub fn cursor(&self) -> CursorShape {
1477 self.cursor
1478 }
1479
1480 pub fn opacity(&self) -> f32 {
1481 self.opacity
1482 }
1483
1484 pub fn blend_mode(&self) -> crate::BlendMode {
1486 self.blend_mode
1487 }
1488
1489 pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1490 self.blend_mode = mode;
1491 self
1492 }
1493
1494 pub fn cache_layer(&self) -> bool {
1496 self.cache_layer
1497 }
1498
1499 pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1500 self.cache_layer = on;
1501 self
1502 }
1503
1504 pub fn rotation(&self) -> f32 {
1507 self.rotation
1508 }
1509
1510 pub fn scale(&self) -> f32 {
1512 self.scale
1513 }
1514
1515 pub fn inner_size(&self) -> SizeF {
1518 let s = self.scale;
1519 if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1520 }
1521
1522 pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1523 self.shadow
1524 }
1525
1526 pub fn aspect_ratio(&self) -> f32 {
1530 self.aspect_ratio
1531 }
1532
1533 pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1534 self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1535 self
1536 }
1537
1538 pub fn max_width(&self) -> f32 {
1542 self.max_width
1543 }
1544
1545 pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1546 self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1547 self
1548 }
1549
1550 pub fn min_width(&self) -> f32 {
1555 self.min_width
1556 }
1557
1558 pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1559 self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1560 self
1561 }
1562
1563 pub fn min_height(&self) -> f32 {
1565 self.min_height
1566 }
1567
1568 pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1569 self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1570 self
1571 }
1572
1573 pub fn max_height(&self) -> f32 {
1575 self.max_height
1576 }
1577
1578 pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1579 self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1580 self
1581 }
1582
1583 pub fn clamp_width(&self, available: f32) -> f32 {
1586 let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1587 w.max(self.min_width)
1588 }
1589
1590 pub fn clamp_height(&self, height: f32) -> f32 {
1592 let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1593 h.max(self.min_height)
1594 }
1595
1596 pub fn self_align(&self) -> SelfAlign {
1599 self.self_align
1600 }
1601
1602 pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1603 self.self_align = align;
1604 self
1605 }
1606
1607 pub fn band_width(&self, available: f32) -> f32 {
1611 match self.self_align {
1612 SelfAlign::Stretch => self.clamp_width(available),
1613 _ if self.max_width > 0.0 => self.clamp_width(available),
1614 _ => self.clamp_width(self.width),
1615 }
1616 }
1617
1618 pub fn band_height(&self, available: f32) -> f32 {
1621 match self.self_align {
1622 SelfAlign::Stretch => self.clamp_height(available),
1623 _ if self.max_height > 0.0 => self.clamp_height(available),
1624 _ => self.clamp_height(self.height),
1625 }
1626 }
1627
1628 pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1631 let spare = (available - size).max(0.0);
1632 match self.self_align {
1633 SelfAlign::Start => 0.0,
1634 SelfAlign::End => spare,
1635 SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1636 }
1637 }
1638
1639 pub fn auto_size(&self) -> bool {
1644 self.auto_size
1645 }
1646
1647 pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1648 self.auto_size = on;
1649 self
1650 }
1651
1652 pub fn column_span(&self) -> u32 {
1655 self.column_span.max(1)
1656 }
1657
1658 pub fn grid_cell(&self) -> Option<(u32, u32)> {
1660 (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1661 }
1662
1663 pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1664 let (r, c) = cell.map_or((-1, -1), |(r, c)| (r.min(i16::MAX as u32) as i16, c.min(i16::MAX as u32) as i16));
1665 self.grid_row = r;
1666 self.grid_column = c;
1667 self
1668 }
1669
1670 pub fn row_span(&self) -> u32 {
1672 u32::from(self.row_span.max(1))
1673 }
1674
1675 pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1676 self.row_span = span.clamp(1, 64) as u16;
1677 self
1678 }
1679
1680 pub fn grow(&self) -> f32 {
1681 self.grow
1682 }
1683
1684 pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1685 self.grow = grow.max(0.0);
1686 self
1687 }
1688
1689 pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1690 self.column_span = span.max(1);
1691 self
1692 }
1693
1694 pub fn text_scale(&self) -> f32 {
1696 self.text_scale
1697 }
1698
1699 pub fn spacing_scale(&self) -> f32 {
1701 self.spacing_scale
1702 }
1703
1704 pub fn tag(&self) -> i64 {
1705 self.tag
1706 }
1707
1708 pub fn accessible_name(&self) -> &str {
1711 self.rare.as_ref().map_or("", |r| &r.accessible_name)
1712 }
1713
1714 pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1715 self.rare_mut(|r| r.accessible_name = v.into());
1716 self
1717 }
1718
1719 fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1720 let rare = self.rare.get_or_insert_with(Default::default);
1721 change(rare);
1722 if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1723 self.rare = None;
1724 }
1725 }
1726
1727 pub fn tag_string(&self) -> &str {
1728 self.rare.as_ref().map_or("", |r| &r.tag_string)
1729 }
1730
1731 pub fn style(&self) -> &str {
1733 &self.style
1734 }
1735
1736 pub fn theme_name(&self) -> &str {
1738 &self.theme
1739 }
1740
1741 pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1742 self.theme = v.into();
1743 self
1744 }
1745
1746 pub fn hint(&self) -> &str {
1748 &self.hint
1749 }
1750
1751 pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1752 self.hint = v.into();
1753 self
1754 }
1755
1756 pub fn state(&self) -> ControlState {
1757 self.state
1758 }
1759
1760 pub fn bounds(&self) -> RectF {
1762 self.bounds
1763 }
1764
1765 pub fn scroll_offset(&self) -> PointF {
1767 self.scroll_offset
1768 }
1769
1770 pub fn laid_out_scroll(&self) -> PointF {
1773 self.laid_out_scroll
1774 }
1775
1776 pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1779 self.scroll_offset = offset;
1780 self
1781 }
1782
1783 pub fn content_size(&self) -> SizeF {
1786 self.content_size
1787 }
1788
1789 pub fn set_left(&mut self, v: f32) -> &mut Self {
1796 if self.left != v {
1797 self.left = v;
1798 self.anchor_ref = None;
1799 }
1800 self
1801 }
1802
1803 pub fn set_top(&mut self, v: f32) -> &mut Self {
1804 if self.top != v {
1805 self.top = v;
1806 self.anchor_ref = None;
1807 }
1808 self
1809 }
1810
1811 pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1812 self.set_left(left).set_top(top)
1813 }
1814
1815 pub fn set_width(&mut self, v: f32) -> &mut Self {
1816 if self.width != v.max(0.0) {
1817 self.width = v.max(0.0);
1818 self.anchor_ref = None;
1819 }
1820 self
1821 }
1822
1823 pub fn set_height(&mut self, v: f32) -> &mut Self {
1824 if self.height != v.max(0.0) {
1825 self.height = v.max(0.0);
1826 self.anchor_ref = None;
1827 }
1828 self
1829 }
1830
1831 pub(crate) fn set_measured_width(&mut self, v: f32) {
1833 self.width = v.max(0.0);
1834 if let Some(r) = self.anchor_ref.as_mut() {
1835 r.rect.width = self.width;
1836 }
1837 }
1838
1839 pub(crate) fn set_measured_height(&mut self, v: f32) {
1842 self.height = v.max(0.0);
1843 if let Some(r) = self.anchor_ref.as_mut() {
1844 r.rect.height = self.height;
1845 }
1846 }
1847
1848 pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1849 self.set_width(width).set_height(height)
1850 }
1851
1852 pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1854 self.set_position(left, top).set_size(width, height)
1855 }
1856
1857 pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1858 self.margins = v.into();
1859 self
1860 }
1861
1862 pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1863 self.padding = v.into();
1864 self
1865 }
1866
1867 pub fn set_align(&mut self, v: Align) -> &mut Self {
1868 self.align = v;
1869 self.anchor_ref = None;
1870 self
1871 }
1872
1873 pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1874 self.anchors = v;
1875 self.anchor_ref = None;
1876 self
1877 }
1878
1879 pub fn set_visible(&mut self, v: bool) -> &mut Self {
1880 self.visible = v;
1881 self
1882 }
1883
1884 pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1885 self.enabled = v;
1886 self
1887 }
1888
1889 pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1890 self.hit_test = v;
1891 self
1892 }
1893
1894 pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1895 self.clip_children = v;
1896 self
1897 }
1898
1899 pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1900 self.captures_wheel = v;
1901 self
1902 }
1903
1904 pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
1905 self.captures_gesture = v;
1906 self
1907 }
1908
1909 pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1910 self.can_focus = v;
1911 self
1912 }
1913
1914 pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1918 self.pan_on_touch = v;
1919 self
1920 }
1921
1922 pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1923 self.tab_stop = v;
1924 self
1925 }
1926
1927 pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1928 self.cursor = v;
1929 self
1930 }
1931
1932 pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1933 self.opacity = v.clamp(0.0, 1.0);
1934 self
1935 }
1936
1937 pub fn translate(&self) -> PointF {
1939 self.translate
1940 }
1941
1942 pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1943 self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1944 self
1945 }
1946
1947 pub fn set_scale(&mut self, scale: f32) -> &mut Self {
1949 self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
1950 self
1951 }
1952
1953 pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1954 self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1955 self
1956 }
1957
1958 pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1959 self.shadow = shadow;
1960 self
1961 }
1962
1963 pub fn set_tag(&mut self, v: i64) -> &mut Self {
1964 self.tag = v;
1965 self
1966 }
1967
1968 pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
1969 self.rare_mut(|r| r.tag_string = v.into());
1970 self
1971 }
1972
1973 pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1974 self.style = v.into();
1975 self
1976 }
1977
1978 pub fn state_mut(&mut self) -> &mut ControlState {
1981 &mut self.state
1982 }
1983
1984 pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1987 Some(match name {
1988 "left" => self.left.into(),
1989 "top" => self.top.into(),
1990 "width" => self.width.into(),
1991 "height" => self.height.into(),
1992 "align" => self.align.into(),
1993 "anchors" => self.anchors.into(),
1994 "margins" => self.margins.into(),
1995 "padding" => self.padding.into(),
1996 "visible" => self.visible.into(),
1997 "enabled" => self.enabled.into(),
1998 "hit_test" => self.hit_test.into(),
1999 "clip_children" => self.clip_children.into(),
2000 "inherit_state" => self.inherit_state.into(),
2001 "translate" => self.translatable.into(),
2002 "captures_wheel" => self.captures_wheel.into(),
2003 "captures_gesture" => self.captures_gesture.into(),
2004 "can_focus" => self.can_focus.into(),
2005 "draggable" => self.draggable.into(),
2006 "accepts_drops" => self.accepts_drops.into(),
2007 "drag_data" => self.drag_data().into(),
2008 "drag_label" => self.drag_label().into(),
2009 "drag_image" => PropValue::Component(self.drag_image()),
2010 "drop_types" => self.drop_types().into(),
2011 "tab_stop" => self.tab_stop.into(),
2012 "cursor" => PropValue::enum_value(self.cursor),
2013 "opacity" => self.opacity.into(),
2014 "blend_mode" => PropValue::enum_value(self.blend_mode),
2015 "cache_layer" => self.cache_layer.into(),
2016 "rotation" => self.rotation.into(),
2017 "scale" => self.scale.into(),
2018 "translate_x" => self.translate.x.into(),
2019 "translate_y" => self.translate.y.into(),
2020 "aspect_ratio" => self.aspect_ratio.into(),
2021 "max_width" => self.max_width.into(),
2022 "min_width" => self.min_width.into(),
2023 "min_height" => self.min_height.into(),
2024 "max_height" => self.max_height.into(),
2025 "self_align" => PropValue::enum_value(self.self_align),
2026 "auto_size" => self.auto_size.into(),
2027 "column_span" => (self.column_span() as i64).into(),
2028 "grid_row" => i64::from(self.grid_row).into(),
2029 "grid_column" => i64::from(self.grid_column).into(),
2030 "row_span" => (self.row_span() as i64).into(),
2031 "grow" => f64::from(self.grow).into(),
2032 "shadow" => crate::prop::PropType::to_value(&self.shadow),
2033 "style" => self.style.clone().into(),
2034 "fill" => crate::prop::PropType::to_value(&self.colors.fill),
2035 "border_color" => crate::prop::PropType::to_value(&self.colors.border),
2036 "text_color" => crate::prop::PropType::to_value(&self.colors.text),
2037 "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
2038 "success_color" => crate::prop::PropType::to_value(&self.colors.success),
2039 "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
2040 "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
2041 "font_family" => self.font.family.clone().into(),
2042 "font_size" => crate::prop::PropType::to_value(&self.font.size),
2043 "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
2044 "font_italic" => self.font.italic.into(),
2045 "font_underline" => self.font.underline.into(),
2046 "font_strikeout" => self.font.strikeout.into(),
2047 "theme" => self.theme.clone().into(),
2048 "hint" => self.hint.clone().into(),
2049 "tag" => self.tag.into(),
2050 "tag_string" => self.tag_string().to_string().into(),
2051 "accessible_name" => self.accessible_name().to_string().into(),
2052 "popup_menu" => PropValue::Component(self.popup_menu),
2053 _ => return None,
2054 })
2055 }
2056
2057 pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
2058 match name {
2059 "left" => self.set_left(value.to_f32()?),
2060 "top" => self.set_top(value.to_f32()?),
2061 "width" => self.set_width(value.to_f32()?),
2062 "height" => self.set_height(value.to_f32()?),
2063 "align" => self.set_align(value.to_enum()?),
2064 "anchors" => self.set_anchors(value.to_anchors()?),
2065 "margins" => self.set_margins(value.to_bounds()?),
2066 "padding" => self.set_padding(value.to_bounds()?),
2067 "visible" => self.set_visible(value.to_bool()?),
2068 "enabled" => self.set_enabled(value.to_bool()?),
2069 "hit_test" => self.set_hit_test(value.to_bool()?),
2070 "clip_children" => self.set_clip_children(value.to_bool()?),
2071 "inherit_state" => self.set_inherit_state(value.to_bool()?),
2072 "translate" => self.set_translatable(value.to_bool()?),
2073 "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2074 "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2075 "can_focus" => self.set_can_focus(value.to_bool()?),
2076 "draggable" => self.set_draggable(value.to_bool()?),
2077 "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2078 "drag_data" => {
2079 self.drag_decl().data = value.to_str()?.to_string();
2080 self
2081 }
2082 "drag_label" => {
2083 self.drag_decl().label = value.to_str()?.to_string();
2084 self
2085 }
2086 "drag_image" => {
2087 self.drag_decl().image = value.to_component()?;
2088 self
2089 }
2090 "drop_types" => {
2091 self.drag_decl().drop_types = value.to_str()?.to_string();
2092 self
2093 }
2094 "tab_stop" => self.set_tab_stop(value.to_bool()?),
2095 "cursor" => self.set_cursor(value.to_enum()?),
2096 "opacity" => self.set_opacity(value.to_f32()?),
2097 "blend_mode" => self.set_blend_mode(value.to_enum()?),
2098 "cache_layer" => self.set_cache_layer(value.to_bool()?),
2099 "rotation" => self.set_rotation(value.to_f32()?),
2100 "scale" => self.set_scale(value.to_f32()?),
2101 "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2102 "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2103 "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2104 "max_width" => self.set_max_width(value.to_f32()?),
2105 "min_width" => self.set_min_width(value.to_f32()?),
2106 "min_height" => self.set_min_height(value.to_f32()?),
2107 "max_height" => self.set_max_height(value.to_f32()?),
2108 "self_align" => self.set_self_align(value.to_enum()?),
2109 "auto_size" => self.set_auto_size(value.to_bool()?),
2110 "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2111 "grid_row" => {
2112 self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2113 self
2114 }
2115 "grid_column" => {
2116 self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2117 self
2118 }
2119 "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2120 "grow" => self.set_grow(value.to_f32()?),
2121 "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2122 "style" => self.set_style(value.to_str()?),
2123 "fill" => {
2124 self.colors.fill = crate::prop::PropType::from_value(value)?;
2125 self
2126 }
2127 "border_color" => {
2128 self.colors.border = crate::prop::PropType::from_value(value)?;
2129 self
2130 }
2131 "text_color" => {
2132 self.colors.text = crate::prop::PropType::from_value(value)?;
2133 self
2134 }
2135 "accent_color" => {
2136 self.colors.accent = crate::prop::PropType::from_value(value)?;
2137 self
2138 }
2139 "success_color" => {
2140 self.colors.success = crate::prop::PropType::from_value(value)?;
2141 self
2142 }
2143 "warning_color" => {
2144 self.colors.warning = crate::prop::PropType::from_value(value)?;
2145 self
2146 }
2147 "danger_color" => {
2148 self.colors.danger = crate::prop::PropType::from_value(value)?;
2149 self
2150 }
2151 "font_family" => {
2152 self.font.family = value.to_str()?.to_string();
2153 self
2154 }
2155 "font_size" => {
2156 self.font.size = crate::prop::PropType::from_value(value)?;
2157 self
2158 }
2159 "font_weight" => {
2160 self.font.weight = font_weight_named(value.to_str()?)?;
2161 self
2162 }
2163 "font_italic" => {
2164 self.font.italic = value.to_bool()?;
2165 self
2166 }
2167 "font_underline" => {
2168 self.font.underline = value.to_bool()?;
2169 self
2170 }
2171 "font_strikeout" => {
2172 self.font.strikeout = value.to_bool()?;
2173 self
2174 }
2175 "theme" => self.set_theme_name(value.to_str()?),
2176 "hint" => self.set_hint(value.to_str()?),
2177 "tag" => self.set_tag(value.to_i64()?),
2178 "tag_string" => self.set_tag_string(value.to_str()?),
2179 "accessible_name" => self.set_accessible_name(value.to_str()?),
2180 "popup_menu" => {
2181 self.popup_menu = value.to_component()?;
2182 self
2183 }
2184 _ => return Err(Error::UnknownProperty(name.to_string())),
2185 };
2186 Ok(())
2187 }
2188}
2189
2190pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2192
2193fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2194 use crate::canvas::FontWeight::*;
2195 let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2196 match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2197 Some(0) => Ok(None),
2198 Some(i) => Ok(Some(all[i - 1])),
2199 None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2200 }
2201}
2202
2203#[derive(Clone, Debug, Default, PartialEq)]
2207pub struct FontOverride {
2208 pub family: String,
2210 pub size: Option<f32>,
2212 pub weight: Option<crate::canvas::FontWeight>,
2214 pub italic: bool,
2216 pub underline: bool,
2218 pub strikeout: bool,
2220}
2221
2222impl FontOverride {
2223 pub fn is_empty(&self) -> bool {
2224 *self == Self::default()
2225 }
2226
2227 pub fn over(&self, parent: &FontOverride) -> FontOverride {
2229 FontOverride {
2230 family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2231 size: self.size.or(parent.size),
2232 weight: self.weight.or(parent.weight),
2233 italic: self.italic || parent.italic,
2234 underline: self.underline || parent.underline,
2235 strikeout: self.strikeout || parent.strikeout,
2236 }
2237 }
2238
2239 pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2241 if !self.family.is_empty() {
2242 font.family = self.family.clone();
2243 }
2244 if let Some(size) = self.size.filter(|s| *s > 0.0) {
2245 font.size = size;
2246 }
2247 if let Some(weight) = self.weight {
2248 font.weight = weight;
2249 }
2250 font.italic |= self.italic;
2251 font.underline |= self.underline;
2252 font.strikeout |= self.strikeout;
2253 }
2254}
2255
2256impl ControlBase {
2257 pub fn font(&self) -> &FontOverride {
2259 &self.font
2260 }
2261
2262 pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2263 self.font = font;
2264 self
2265 }
2266}
2267
2268#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2274pub struct ColorOverride {
2275 pub fill: Option<crate::Color>,
2277 pub border: Option<crate::Color>,
2279 pub text: Option<crate::Color>,
2281 pub accent: Option<crate::Color>,
2284 pub success: Option<crate::Color>,
2287 pub warning: Option<crate::Color>,
2289 pub danger: Option<crate::Color>,
2291}
2292
2293impl ColorOverride {
2294 pub fn is_empty(&self) -> bool {
2295 *self == Self::default()
2296 }
2297
2298 pub(crate) fn recolors_theme(&self) -> bool {
2300 !self.is_empty()
2301 }
2302
2303 pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2305 use crate::Color;
2306 let mut t = theme.clone();
2307 let mut set = |name: &str, c: Color| {
2308 t.colors.insert(name.to_string(), c);
2309 };
2310 if let Some(a) = self.accent {
2311 let dark = luminance(a) < 0.5;
2312 set("primary", a);
2313 set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2314 set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2315 set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2316 set("focus_ring", a);
2317 set("selection", a.with_opacity(0.25));
2318 set("primary_soft", a.with_opacity(0.1));
2319 set("primary_container", a.lerp(Color::WHITE, 0.82));
2320 }
2321 if let Some(c) = self.fill {
2322 let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2324 set("surface", c);
2325 set("background", c);
2326 set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2327 }
2328 if let Some(c) = self.text {
2329 set("text", c);
2330 set("text_muted", c.with_opacity(0.65));
2331 for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2332 set(on, c);
2333 }
2334 }
2335 if let Some(c) = self.border {
2336 set("border", c);
2337 set("track", c);
2338 }
2339 for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2340 if let Some(c) = color {
2341 set(token, c);
2342 set(&format!("{token}_soft"), c.with_opacity(0.1));
2343 set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2344 set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2345 if token == "success" {
2346 set("meter_low", c);
2347 } else if token == "danger" {
2348 set("meter_high", c);
2349 } else {
2350 set("meter_mid", c);
2351 }
2352 }
2353 }
2354 t
2355 }
2356}
2357
2358pub(crate) fn luminance(c: crate::Color) -> f32 {
2360 (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2361}
2362
2363#[derive(Clone, Copy, Debug, PartialEq)]
2365pub struct Connection {
2366 pub from: ComponentId,
2367 pub from_at: (f32, f32),
2369 pub to: ComponentId,
2370 pub to_at: (f32, f32),
2371}
2372
2373impl Connection {
2374 pub const STUB: f32 = 16.0;
2376
2377 fn normal(at: (f32, f32)) -> PointF {
2379 let (x, y) = at;
2380 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))];
2381 d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2382 }
2383
2384 pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2387 let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2388 let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2389 let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2390 let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2391 let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2392 let mut points = vec![p0, s0];
2393 if n0.x != 0.0 {
2394 let mx = (s0.x + s1.x) / 2.0;
2396 points.push(PointF::new(mx, s0.y));
2397 points.push(PointF::new(mx, s1.y));
2398 } else {
2399 let my = (s0.y + s1.y) / 2.0;
2400 points.push(PointF::new(s0.x, my));
2401 points.push(PointF::new(s1.x, my));
2402 }
2403 points.push(s1);
2404 points.push(p1);
2405 points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2406 points
2407 }
2408}
2409
2410#[derive(Clone, Debug, Default, PartialEq)]
2412pub struct DragDecl {
2413 pub data: String,
2416 pub label: String,
2418 pub drop_types: String,
2421 pub image: Option<ComponentId>,
2423}
2424
2425#[derive(Clone, Debug, Default)]
2427struct RareTexts {
2428 tag_string: Box<str>,
2430 accessible_name: Box<str>,
2433}