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 pub arg_types: &'static [&'static str],
850 pub returns_type: &'static str,
851}
852
853impl MethodInfo {
854 pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
855 Self { name, args, returns, params: &[], arg_types: &[], returns_type: "" }
856 }
857
858 pub const fn types(self, args: &'static [&'static str], returns: &'static str) -> Self {
860 Self { arg_types: args, returns_type: returns, ..self }
861 }
862
863 pub const fn params(self, names: &'static [&'static str]) -> Self {
866 Self { params: names, ..self }
867 }
868}
869
870#[derive(Clone, Debug, PartialEq)]
872pub enum NativeCommand {
873 Eval(String),
875 Back,
876 Forward,
877 Reload,
878}
879
880#[derive(Clone, Debug, PartialEq)]
882pub struct NativeViewSlot {
883 pub id: ComponentId,
884 pub rect: crate::RectF,
885 pub clip: Option<crate::RectF>,
888 pub visible: bool,
889 pub view: NativeView,
890 pub commands: Vec<NativeCommand>,
891}
892
893pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
899 let mut out: Vec<PropInfo> = Vec::new();
900 let mut seen = std::collections::HashSet::new();
903 let mut push = |info: &PropInfo| {
904 if seen.insert(info.name) {
905 out.push(*info);
906 }
907 };
908 let mut layer = Some(component);
909 while let Some(l) = layer {
910 l.props().iter().for_each(&mut push);
911 layer = l.inner();
912 }
913 if component.control().is_some() {
914 ControlBase::PROPS.iter().for_each(&mut push);
915 }
916 out
917}
918
919pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
922 let mut layer = Some(component);
923 while let Some(l) = layer {
924 if let Some(info) = l.props().iter().find(|p| p.name == name) {
925 return Some(*info);
926 }
927 layer = l.inner();
928 }
929 if component.control().is_some() {
930 return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
931 }
932 None
933}
934
935pub const VALUE_PROPERTIES: [&str; 19] = [
940 "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
941 "angle", "pressed", "position", "low", "high",
942];
943
944pub fn is_value_property(info: &PropInfo) -> bool {
948 match info.name {
949 "tab_index" | "expanded" => true,
950 name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
951 }
952}
953
954pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
955 let mut layer = Some(component);
956 while let Some(l) = layer {
957 if let Some(v) = l.get_prop(name) {
958 return Some(v);
959 }
960 layer = l.inner();
961 }
962 component.control().and_then(|cb| cb.get_prop(name))
963}
964
965#[derive(Clone, Copy, Debug, PartialEq)]
968pub(crate) struct AnchorRef {
969 pub(crate) parent: SizeF,
970 pub(crate) rect: RectF,
971}
972
973#[derive(Clone, Debug)]
978pub struct ControlBase {
979 left: f32,
981 top: f32,
983 width: f32,
985 height: f32,
987 margins: Bounds,
989 padding: Bounds,
991 align: Align,
993 anchors: Anchors,
995 visible: bool,
997 enabled: bool,
999 hit_test: bool,
1001 clip_children: bool,
1003 inherit_state: bool,
1006 translatable: bool,
1010 captures_wheel: bool,
1013 captures_gesture: bool,
1016 can_focus: bool,
1018 draggable: bool,
1020 accepts_drops: bool,
1022 drag: Option<Box<DragDecl>>,
1025 tab_stop: bool,
1027 pan_on_touch: bool,
1029 pub(crate) popup_menu: Option<ComponentId>,
1031 cursor: CursorShape,
1033 opacity: f32,
1035 blend_mode: crate::BlendMode,
1038 rotation: f32,
1040 scale: f32,
1045 translate: PointF,
1047 cache_layer: bool,
1050 aspect_ratio: f32,
1052 max_width: f32,
1054 min_width: f32,
1056 min_height: f32,
1058 max_height: f32,
1060 self_align: SelfAlign,
1062 auto_size: bool,
1064 column_span: u32,
1066 grid_row: i16,
1069 grid_column: i16,
1071 row_span: u16,
1073 grow: f32,
1076 pub(crate) text_scale: f32,
1079 pub(crate) spacing_scale: f32,
1080 shadow: Option<crate::canvas::Shadow>,
1082 tag: i64,
1084 rare: Option<Box<RareTexts>>,
1087 style: String,
1089 theme: String,
1091 hint: String,
1093 state: ControlState,
1094 pub(crate) bounds: RectF,
1095 pub(crate) anchor_ref: Option<AnchorRef>,
1096 pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1099 pub(crate) design_hidden: bool,
1102 pub(crate) design_only: bool,
1104 pub(crate) keep_left_to_right: bool,
1107 pub(crate) colors: ColorOverride,
1109 pub(crate) font: FontOverride,
1111 scroll_offset: PointF,
1113 pub(crate) laid_out_scroll: PointF,
1116 pub(crate) safe_area: Bounds,
1118 pub(crate) content_size: SizeF,
1120}
1121
1122impl Default for ControlBase {
1123 fn default() -> Self {
1124 Self::new(100.0, 100.0)
1125 }
1126}
1127
1128impl ControlBase {
1129 pub const PROPS: &'static [PropInfo] = &[
1131 PropInfo::new("left", PropKind::Float, "Layout"),
1132 PropInfo::new("top", PropKind::Float, "Layout"),
1133 PropInfo::new("width", PropKind::Float, "Layout"),
1134 PropInfo::new("height", PropKind::Float, "Layout"),
1135 PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout").rust_type("Align"),
1136 PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout").rust_type("Anchors"),
1137 PropInfo::new("margins", PropKind::Bounds, "Layout"),
1138 PropInfo::new("padding", PropKind::Bounds, "Layout"),
1139 PropInfo::new("visible", PropKind::Bool, "Behavior"),
1140 PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1141 PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1142 PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1143 PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1144 PropInfo::new("translate", PropKind::Bool, "Behavior"),
1145 PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1146 PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1147 PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1148 PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1149 PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1150 PropInfo::new("drag_data", PropKind::String, "Behavior"),
1151 PropInfo::new("drag_label", PropKind::String, "Behavior"),
1152 PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1153 PropInfo::new("drop_types", PropKind::String, "Behavior"),
1154 PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1155 PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior").rust_type("CursorShape"),
1156 PropInfo::new("opacity", PropKind::Float, "Appearance"),
1157 PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance").rust_type("BlendMode"),
1158 PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1159 PropInfo::new("rotation", PropKind::Angle, "Layout"),
1160 PropInfo::new("scale", PropKind::Float, "Layout"),
1161 PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1162 PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1163 PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1164 PropInfo::new("max_width", PropKind::Float, "Layout"),
1165 PropInfo::new("min_width", PropKind::Float, "Layout"),
1166 PropInfo::new("min_height", PropKind::Float, "Layout"),
1167 PropInfo::new("max_height", PropKind::Float, "Layout"),
1168 PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout").rust_type("SelfAlign"),
1169 PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1170 PropInfo::new("column_span", PropKind::Int, "Layout"),
1171 PropInfo::new("grid_row", PropKind::Int, "Layout"),
1172 PropInfo::new("grid_column", PropKind::Int, "Layout"),
1173 PropInfo::new("row_span", PropKind::Int, "Layout"),
1174 PropInfo::new("grow", PropKind::Float, "Layout"),
1175 PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1176 PropInfo::new("style", PropKind::StyleName, "Appearance"),
1177 PropInfo::new("theme", PropKind::ThemeName, "Appearance"),
1178 PropInfo::new("fill", PropKind::Color, "Appearance"),
1179 PropInfo::new("border_color", PropKind::Color, "Appearance"),
1180 PropInfo::new("text_color", PropKind::Color, "Appearance"),
1181 PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1182 PropInfo::new("success_color", PropKind::Color, "Appearance"),
1183 PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1184 PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1185 PropInfo::new("font_family", PropKind::String, "Font"),
1186 PropInfo::new("font_size", PropKind::Float, "Font"),
1187 PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1188 PropInfo::new("font_italic", PropKind::Bool, "Font"),
1189 PropInfo::new("font_underline", PropKind::Bool, "Font"),
1190 PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1191 PropInfo::new("hint", PropKind::String, "Behavior"),
1192 PropInfo::new("tag", PropKind::Int, "Misc"),
1193 PropInfo::new("tag_string", PropKind::String, "Misc"),
1194 PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1195 PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1196 PropInfo::new("on_click", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1197 PropInfo::new("on_dbl_click", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1198 PropInfo::new("on_long_press", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1199 PropInfo::new("on_pointer_down", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1200 PropInfo::new("on_pointer_up", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1201 PropInfo::new("on_pointer_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1202 PropInfo::new("on_pointer_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1203 PropInfo::new("on_pointer_leave", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1204 PropInfo::new("on_wheel", PropKind::Event, "Events").event_arg(crate::EventArg::Wheel),
1205 PropInfo::new("on_gesture", PropKind::Event, "Events").event_arg(crate::EventArg::Gesture),
1206 PropInfo::new("on_swipe", PropKind::Event, "Events").event_arg(crate::EventArg::Swipe),
1207 PropInfo::new("on_key_down", PropKind::Event, "Events"),
1208 PropInfo::new("on_key_press", PropKind::Event, "Events"),
1209 PropInfo::new("on_key_up", PropKind::Event, "Events").event_arg(crate::EventArg::Key),
1210 PropInfo::new("on_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1211 PropInfo::new("on_exit", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1212 PropInfo::new("on_resize", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1213 PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1214 PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1215 PropInfo::new("on_drag_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1216 PropInfo::new("on_drag_leave", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1217 PropInfo::new("on_drag_drop", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1218 PropInfo::new("on_drag_end", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::Bool)),
1219 ];
1220
1221 pub fn new(width: f32, height: f32) -> Self {
1222 Self {
1223 left: 0.0,
1224 top: 0.0,
1225 width,
1226 height,
1227 margins: Bounds::ZERO,
1228 padding: Bounds::ZERO,
1229 align: Align::None,
1230 anchors: Anchors::default(),
1231 visible: true,
1232 enabled: true,
1233 hit_test: true,
1234 clip_children: false,
1235 inherit_state: false,
1236 translatable: true,
1237 captures_wheel: false,
1238 captures_gesture: false,
1239 can_focus: false,
1240 draggable: false,
1241 accepts_drops: false,
1242 drag: None,
1243 tab_stop: true,
1244 pan_on_touch: true,
1245 popup_menu: None,
1246 cursor: CursorShape::Default,
1247 opacity: 1.0,
1248 blend_mode: crate::BlendMode::Normal,
1249 rotation: 0.0,
1250 scale: 1.0,
1251 translate: PointF::ZERO,
1252 cache_layer: false,
1253 aspect_ratio: 0.0,
1254 max_width: 0.0,
1255 min_width: 0.0,
1256 min_height: 0.0,
1257 max_height: 0.0,
1258 self_align: SelfAlign::Stretch,
1259 auto_size: false,
1260 column_span: 1,
1261 grid_row: -1,
1262 grid_column: -1,
1263 row_span: 1,
1264 grow: 0.0,
1265 text_scale: 1.0,
1266 spacing_scale: 1.0,
1267 shadow: None,
1268 tag: 0,
1269 rare: None,
1270 style: String::new(),
1271 theme: String::new(),
1272 hint: String::new(),
1273 state: ControlState::default(),
1274 bounds: RectF::new(0.0, 0.0, width, height),
1275 anchor_ref: None,
1276 follow: None,
1277 design_hidden: false,
1278 design_only: false,
1279 keep_left_to_right: false,
1280 colors: ColorOverride::default(),
1281 font: FontOverride::default(),
1282 scroll_offset: PointF::ZERO,
1283 laid_out_scroll: PointF::ZERO,
1284 content_size: SizeF::ZERO,
1285 safe_area: Bounds::default(),
1286 }
1287 }
1288
1289 pub fn left(&self) -> f32 {
1292 self.left
1293 }
1294
1295 pub fn top(&self) -> f32 {
1296 self.top
1297 }
1298
1299 pub fn width(&self) -> f32 {
1300 self.width
1301 }
1302
1303 pub fn height(&self) -> f32 {
1304 self.height
1305 }
1306
1307 pub fn position(&self) -> PointF {
1308 PointF::new(self.left, self.top)
1309 }
1310
1311 pub fn size(&self) -> SizeF {
1312 SizeF::new(self.width, self.height)
1313 }
1314
1315 pub fn margins(&self) -> Bounds {
1318 if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1319 }
1320
1321 pub fn padding(&self) -> Bounds {
1323 if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1324 }
1325
1326 pub fn align(&self) -> Align {
1327 self.align
1328 }
1329
1330 pub fn anchors(&self) -> Anchors {
1331 self.anchors
1332 }
1333
1334 pub fn visible(&self) -> bool {
1335 self.visible
1336 }
1337
1338 pub fn design_only(&self) -> bool {
1340 self.design_only
1341 }
1342
1343 pub fn colors(&self) -> ColorOverride {
1345 self.colors
1346 }
1347
1348 pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1349 self.colors = colors;
1350 self
1351 }
1352
1353 pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1354 self.design_only = on;
1355 self
1356 }
1357
1358 pub fn keep_left_to_right(&self) -> bool {
1360 self.keep_left_to_right
1361 }
1362
1363 pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1364 self.keep_left_to_right = on;
1365 self
1366 }
1367
1368 pub fn enabled(&self) -> bool {
1369 self.enabled
1370 }
1371
1372 pub fn hit_test(&self) -> bool {
1373 self.hit_test
1374 }
1375
1376 pub fn translatable(&self) -> bool {
1377 self.translatable
1378 }
1379
1380 pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1381 self.translatable = v;
1382 self
1383 }
1384
1385 pub fn inherit_state(&self) -> bool {
1386 self.inherit_state
1387 }
1388
1389 pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1390 self.inherit_state = v;
1391 self
1392 }
1393
1394 pub fn clip_children(&self) -> bool {
1395 self.clip_children
1396 }
1397
1398 pub fn captures_wheel(&self) -> bool {
1399 self.captures_wheel
1400 }
1401
1402 pub fn captures_gesture(&self) -> bool {
1403 self.captures_gesture
1404 }
1405
1406 pub fn draggable(&self) -> bool {
1411 self.draggable
1412 }
1413
1414 pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1415 self.draggable = v;
1416 self
1417 }
1418
1419 pub fn accepts_drops(&self) -> bool {
1422 self.accepts_drops
1423 }
1424
1425 pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1426 self.accepts_drops = v;
1427 self
1428 }
1429
1430 pub fn drag_data(&self) -> &str {
1432 self.drag.as_ref().map_or("", |d| d.data.as_str())
1433 }
1434
1435 pub fn drag_label(&self) -> &str {
1436 self.drag.as_ref().map_or("", |d| d.label.as_str())
1437 }
1438
1439 pub fn drag_image(&self) -> Option<ComponentId> {
1441 self.drag.as_ref().and_then(|d| d.image)
1442 }
1443
1444 pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1446 if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1447 d.image = None;
1448 }
1449 }
1450
1451 pub fn drop_types(&self) -> &str {
1453 self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1454 }
1455
1456 fn drag_decl(&mut self) -> &mut DragDecl {
1457 self.drag.get_or_insert_with(Default::default)
1458 }
1459
1460 pub fn can_focus(&self) -> bool {
1461 self.can_focus
1462 }
1463
1464 pub fn tab_stop(&self) -> bool {
1466 self.tab_stop
1467 }
1468
1469 pub fn popup_menu(&self) -> Option<ComponentId> {
1471 self.popup_menu
1472 }
1473
1474 pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1475 self.popup_menu = menu;
1476 self
1477 }
1478
1479 pub fn pan_on_touch(&self) -> bool {
1481 self.pan_on_touch
1482 }
1483
1484 pub fn cursor(&self) -> CursorShape {
1486 self.cursor
1487 }
1488
1489 pub fn opacity(&self) -> f32 {
1490 self.opacity
1491 }
1492
1493 pub fn blend_mode(&self) -> crate::BlendMode {
1495 self.blend_mode
1496 }
1497
1498 pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1499 self.blend_mode = mode;
1500 self
1501 }
1502
1503 pub fn cache_layer(&self) -> bool {
1505 self.cache_layer
1506 }
1507
1508 pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1509 self.cache_layer = on;
1510 self
1511 }
1512
1513 pub fn rotation(&self) -> f32 {
1516 self.rotation
1517 }
1518
1519 pub fn scale(&self) -> f32 {
1521 self.scale
1522 }
1523
1524 pub fn inner_size(&self) -> SizeF {
1527 let s = self.scale;
1528 if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1529 }
1530
1531 pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1532 self.shadow
1533 }
1534
1535 pub fn aspect_ratio(&self) -> f32 {
1539 self.aspect_ratio
1540 }
1541
1542 pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1543 self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1544 self
1545 }
1546
1547 pub fn max_width(&self) -> f32 {
1551 self.max_width
1552 }
1553
1554 pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1555 self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1556 self
1557 }
1558
1559 pub fn min_width(&self) -> f32 {
1564 self.min_width
1565 }
1566
1567 pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1568 self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1569 self
1570 }
1571
1572 pub fn min_height(&self) -> f32 {
1574 self.min_height
1575 }
1576
1577 pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1578 self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1579 self
1580 }
1581
1582 pub fn max_height(&self) -> f32 {
1584 self.max_height
1585 }
1586
1587 pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1588 self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1589 self
1590 }
1591
1592 pub fn clamp_width(&self, available: f32) -> f32 {
1595 let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1596 w.max(self.min_width)
1597 }
1598
1599 pub fn clamp_height(&self, height: f32) -> f32 {
1601 let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1602 h.max(self.min_height)
1603 }
1604
1605 pub fn self_align(&self) -> SelfAlign {
1608 self.self_align
1609 }
1610
1611 pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1612 self.self_align = align;
1613 self
1614 }
1615
1616 pub fn band_width(&self, available: f32) -> f32 {
1620 match self.self_align {
1621 SelfAlign::Stretch => self.clamp_width(available),
1622 _ if self.max_width > 0.0 => self.clamp_width(available),
1623 _ => self.clamp_width(self.width),
1624 }
1625 }
1626
1627 pub fn band_height(&self, available: f32) -> f32 {
1630 match self.self_align {
1631 SelfAlign::Stretch => self.clamp_height(available),
1632 _ if self.max_height > 0.0 => self.clamp_height(available),
1633 _ => self.clamp_height(self.height),
1634 }
1635 }
1636
1637 pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1640 let spare = (available - size).max(0.0);
1641 match self.self_align {
1642 SelfAlign::Start => 0.0,
1643 SelfAlign::End => spare,
1644 SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1645 }
1646 }
1647
1648 pub fn auto_size(&self) -> bool {
1653 self.auto_size
1654 }
1655
1656 pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1657 self.auto_size = on;
1658 self
1659 }
1660
1661 pub fn column_span(&self) -> u32 {
1664 self.column_span.max(1)
1665 }
1666
1667 pub fn grid_cell(&self) -> Option<(u32, u32)> {
1669 (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1670 }
1671
1672 pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1673 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));
1674 self.grid_row = r;
1675 self.grid_column = c;
1676 self
1677 }
1678
1679 pub fn row_span(&self) -> u32 {
1681 u32::from(self.row_span.max(1))
1682 }
1683
1684 pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1685 self.row_span = span.clamp(1, 64) as u16;
1686 self
1687 }
1688
1689 pub fn grow(&self) -> f32 {
1690 self.grow
1691 }
1692
1693 pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1694 self.grow = grow.max(0.0);
1695 self
1696 }
1697
1698 pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1699 self.column_span = span.max(1);
1700 self
1701 }
1702
1703 pub fn text_scale(&self) -> f32 {
1705 self.text_scale
1706 }
1707
1708 pub fn spacing_scale(&self) -> f32 {
1710 self.spacing_scale
1711 }
1712
1713 pub fn tag(&self) -> i64 {
1714 self.tag
1715 }
1716
1717 pub fn accessible_name(&self) -> &str {
1720 self.rare.as_ref().map_or("", |r| &r.accessible_name)
1721 }
1722
1723 pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1724 self.rare_mut(|r| r.accessible_name = v.into());
1725 self
1726 }
1727
1728 fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1729 let rare = self.rare.get_or_insert_with(Default::default);
1730 change(rare);
1731 if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1732 self.rare = None;
1733 }
1734 }
1735
1736 pub fn tag_string(&self) -> &str {
1737 self.rare.as_ref().map_or("", |r| &r.tag_string)
1738 }
1739
1740 pub fn style(&self) -> &str {
1742 &self.style
1743 }
1744
1745 pub fn theme_name(&self) -> &str {
1747 &self.theme
1748 }
1749
1750 pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1751 self.theme = v.into();
1752 self
1753 }
1754
1755 pub fn hint(&self) -> &str {
1757 &self.hint
1758 }
1759
1760 pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1761 self.hint = v.into();
1762 self
1763 }
1764
1765 pub fn state(&self) -> ControlState {
1766 self.state
1767 }
1768
1769 pub fn bounds(&self) -> RectF {
1771 self.bounds
1772 }
1773
1774 pub fn scroll_offset(&self) -> PointF {
1776 self.scroll_offset
1777 }
1778
1779 pub fn laid_out_scroll(&self) -> PointF {
1782 self.laid_out_scroll
1783 }
1784
1785 pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1788 self.scroll_offset = offset;
1789 self
1790 }
1791
1792 pub fn content_size(&self) -> SizeF {
1795 self.content_size
1796 }
1797
1798 pub fn set_left(&mut self, v: f32) -> &mut Self {
1805 if self.left != v {
1806 self.left = v;
1807 self.anchor_ref = None;
1808 }
1809 self
1810 }
1811
1812 pub fn set_top(&mut self, v: f32) -> &mut Self {
1813 if self.top != v {
1814 self.top = v;
1815 self.anchor_ref = None;
1816 }
1817 self
1818 }
1819
1820 pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1821 self.set_left(left).set_top(top)
1822 }
1823
1824 pub fn set_width(&mut self, v: f32) -> &mut Self {
1825 if self.width != v.max(0.0) {
1826 self.width = v.max(0.0);
1827 self.anchor_ref = None;
1828 }
1829 self
1830 }
1831
1832 pub fn set_height(&mut self, v: f32) -> &mut Self {
1833 if self.height != v.max(0.0) {
1834 self.height = v.max(0.0);
1835 self.anchor_ref = None;
1836 }
1837 self
1838 }
1839
1840 pub(crate) fn set_measured_width(&mut self, v: f32) {
1842 self.width = v.max(0.0);
1843 if let Some(r) = self.anchor_ref.as_mut() {
1844 r.rect.width = self.width;
1845 }
1846 }
1847
1848 pub(crate) fn set_measured_height(&mut self, v: f32) {
1851 self.height = v.max(0.0);
1852 if let Some(r) = self.anchor_ref.as_mut() {
1853 r.rect.height = self.height;
1854 }
1855 }
1856
1857 pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1858 self.set_width(width).set_height(height)
1859 }
1860
1861 pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1863 self.set_position(left, top).set_size(width, height)
1864 }
1865
1866 pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1867 self.margins = v.into();
1868 self
1869 }
1870
1871 pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1872 self.padding = v.into();
1873 self
1874 }
1875
1876 pub fn set_align(&mut self, v: Align) -> &mut Self {
1877 self.align = v;
1878 self.anchor_ref = None;
1879 self
1880 }
1881
1882 pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1883 self.anchors = v;
1884 self.anchor_ref = None;
1885 self
1886 }
1887
1888 pub fn set_visible(&mut self, v: bool) -> &mut Self {
1889 self.visible = v;
1890 self
1891 }
1892
1893 pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1894 self.enabled = v;
1895 self
1896 }
1897
1898 pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1899 self.hit_test = v;
1900 self
1901 }
1902
1903 pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1904 self.clip_children = v;
1905 self
1906 }
1907
1908 pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1909 self.captures_wheel = v;
1910 self
1911 }
1912
1913 pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
1914 self.captures_gesture = v;
1915 self
1916 }
1917
1918 pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1919 self.can_focus = v;
1920 self
1921 }
1922
1923 pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1927 self.pan_on_touch = v;
1928 self
1929 }
1930
1931 pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1932 self.tab_stop = v;
1933 self
1934 }
1935
1936 pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1937 self.cursor = v;
1938 self
1939 }
1940
1941 pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1942 self.opacity = v.clamp(0.0, 1.0);
1943 self
1944 }
1945
1946 pub fn translate(&self) -> PointF {
1948 self.translate
1949 }
1950
1951 pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1952 self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1953 self
1954 }
1955
1956 pub fn set_scale(&mut self, scale: f32) -> &mut Self {
1958 self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
1959 self
1960 }
1961
1962 pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1963 self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1964 self
1965 }
1966
1967 pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1968 self.shadow = shadow;
1969 self
1970 }
1971
1972 pub fn set_tag(&mut self, v: i64) -> &mut Self {
1973 self.tag = v;
1974 self
1975 }
1976
1977 pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
1978 self.rare_mut(|r| r.tag_string = v.into());
1979 self
1980 }
1981
1982 pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1983 self.style = v.into();
1984 self
1985 }
1986
1987 pub fn state_mut(&mut self) -> &mut ControlState {
1990 &mut self.state
1991 }
1992
1993 pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1996 Some(match name {
1997 "left" => self.left.into(),
1998 "top" => self.top.into(),
1999 "width" => self.width.into(),
2000 "height" => self.height.into(),
2001 "align" => self.align.into(),
2002 "anchors" => self.anchors.into(),
2003 "margins" => self.margins.into(),
2004 "padding" => self.padding.into(),
2005 "visible" => self.visible.into(),
2006 "enabled" => self.enabled.into(),
2007 "hit_test" => self.hit_test.into(),
2008 "clip_children" => self.clip_children.into(),
2009 "inherit_state" => self.inherit_state.into(),
2010 "translate" => self.translatable.into(),
2011 "captures_wheel" => self.captures_wheel.into(),
2012 "captures_gesture" => self.captures_gesture.into(),
2013 "can_focus" => self.can_focus.into(),
2014 "draggable" => self.draggable.into(),
2015 "accepts_drops" => self.accepts_drops.into(),
2016 "drag_data" => self.drag_data().into(),
2017 "drag_label" => self.drag_label().into(),
2018 "drag_image" => PropValue::Component(self.drag_image()),
2019 "drop_types" => self.drop_types().into(),
2020 "tab_stop" => self.tab_stop.into(),
2021 "cursor" => PropValue::enum_value(self.cursor),
2022 "opacity" => self.opacity.into(),
2023 "blend_mode" => PropValue::enum_value(self.blend_mode),
2024 "cache_layer" => self.cache_layer.into(),
2025 "rotation" => self.rotation.into(),
2026 "scale" => self.scale.into(),
2027 "translate_x" => self.translate.x.into(),
2028 "translate_y" => self.translate.y.into(),
2029 "aspect_ratio" => self.aspect_ratio.into(),
2030 "max_width" => self.max_width.into(),
2031 "min_width" => self.min_width.into(),
2032 "min_height" => self.min_height.into(),
2033 "max_height" => self.max_height.into(),
2034 "self_align" => PropValue::enum_value(self.self_align),
2035 "auto_size" => self.auto_size.into(),
2036 "column_span" => (self.column_span() as i64).into(),
2037 "grid_row" => i64::from(self.grid_row).into(),
2038 "grid_column" => i64::from(self.grid_column).into(),
2039 "row_span" => (self.row_span() as i64).into(),
2040 "grow" => f64::from(self.grow).into(),
2041 "shadow" => crate::prop::PropType::to_value(&self.shadow),
2042 "style" => self.style.clone().into(),
2043 "fill" => crate::prop::PropType::to_value(&self.colors.fill),
2044 "border_color" => crate::prop::PropType::to_value(&self.colors.border),
2045 "text_color" => crate::prop::PropType::to_value(&self.colors.text),
2046 "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
2047 "success_color" => crate::prop::PropType::to_value(&self.colors.success),
2048 "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
2049 "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
2050 "font_family" => self.font.family.clone().into(),
2051 "font_size" => crate::prop::PropType::to_value(&self.font.size),
2052 "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
2053 "font_italic" => self.font.italic.into(),
2054 "font_underline" => self.font.underline.into(),
2055 "font_strikeout" => self.font.strikeout.into(),
2056 "theme" => self.theme.clone().into(),
2057 "hint" => self.hint.clone().into(),
2058 "tag" => self.tag.into(),
2059 "tag_string" => self.tag_string().to_string().into(),
2060 "accessible_name" => self.accessible_name().to_string().into(),
2061 "popup_menu" => PropValue::Component(self.popup_menu),
2062 _ => return None,
2063 })
2064 }
2065
2066 pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
2067 match name {
2068 "left" => self.set_left(value.to_f32()?),
2069 "top" => self.set_top(value.to_f32()?),
2070 "width" => self.set_width(value.to_f32()?),
2071 "height" => self.set_height(value.to_f32()?),
2072 "align" => self.set_align(value.to_enum()?),
2073 "anchors" => self.set_anchors(value.to_anchors()?),
2074 "margins" => self.set_margins(value.to_bounds()?),
2075 "padding" => self.set_padding(value.to_bounds()?),
2076 "visible" => self.set_visible(value.to_bool()?),
2077 "enabled" => self.set_enabled(value.to_bool()?),
2078 "hit_test" => self.set_hit_test(value.to_bool()?),
2079 "clip_children" => self.set_clip_children(value.to_bool()?),
2080 "inherit_state" => self.set_inherit_state(value.to_bool()?),
2081 "translate" => self.set_translatable(value.to_bool()?),
2082 "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2083 "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2084 "can_focus" => self.set_can_focus(value.to_bool()?),
2085 "draggable" => self.set_draggable(value.to_bool()?),
2086 "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2087 "drag_data" => {
2088 self.drag_decl().data = value.to_str()?.to_string();
2089 self
2090 }
2091 "drag_label" => {
2092 self.drag_decl().label = value.to_str()?.to_string();
2093 self
2094 }
2095 "drag_image" => {
2096 self.drag_decl().image = value.to_component()?;
2097 self
2098 }
2099 "drop_types" => {
2100 self.drag_decl().drop_types = value.to_str()?.to_string();
2101 self
2102 }
2103 "tab_stop" => self.set_tab_stop(value.to_bool()?),
2104 "cursor" => self.set_cursor(value.to_enum()?),
2105 "opacity" => self.set_opacity(value.to_f32()?),
2106 "blend_mode" => self.set_blend_mode(value.to_enum()?),
2107 "cache_layer" => self.set_cache_layer(value.to_bool()?),
2108 "rotation" => self.set_rotation(value.to_f32()?),
2109 "scale" => self.set_scale(value.to_f32()?),
2110 "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2111 "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2112 "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2113 "max_width" => self.set_max_width(value.to_f32()?),
2114 "min_width" => self.set_min_width(value.to_f32()?),
2115 "min_height" => self.set_min_height(value.to_f32()?),
2116 "max_height" => self.set_max_height(value.to_f32()?),
2117 "self_align" => self.set_self_align(value.to_enum()?),
2118 "auto_size" => self.set_auto_size(value.to_bool()?),
2119 "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2120 "grid_row" => {
2121 self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2122 self
2123 }
2124 "grid_column" => {
2125 self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2126 self
2127 }
2128 "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2129 "grow" => self.set_grow(value.to_f32()?),
2130 "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2131 "style" => self.set_style(value.to_str()?),
2132 "fill" => {
2133 self.colors.fill = crate::prop::PropType::from_value(value)?;
2134 self
2135 }
2136 "border_color" => {
2137 self.colors.border = crate::prop::PropType::from_value(value)?;
2138 self
2139 }
2140 "text_color" => {
2141 self.colors.text = crate::prop::PropType::from_value(value)?;
2142 self
2143 }
2144 "accent_color" => {
2145 self.colors.accent = crate::prop::PropType::from_value(value)?;
2146 self
2147 }
2148 "success_color" => {
2149 self.colors.success = crate::prop::PropType::from_value(value)?;
2150 self
2151 }
2152 "warning_color" => {
2153 self.colors.warning = crate::prop::PropType::from_value(value)?;
2154 self
2155 }
2156 "danger_color" => {
2157 self.colors.danger = crate::prop::PropType::from_value(value)?;
2158 self
2159 }
2160 "font_family" => {
2161 self.font.family = value.to_str()?.to_string();
2162 self
2163 }
2164 "font_size" => {
2165 self.font.size = crate::prop::PropType::from_value(value)?;
2166 self
2167 }
2168 "font_weight" => {
2169 self.font.weight = font_weight_named(value.to_str()?)?;
2170 self
2171 }
2172 "font_italic" => {
2173 self.font.italic = value.to_bool()?;
2174 self
2175 }
2176 "font_underline" => {
2177 self.font.underline = value.to_bool()?;
2178 self
2179 }
2180 "font_strikeout" => {
2181 self.font.strikeout = value.to_bool()?;
2182 self
2183 }
2184 "theme" => self.set_theme_name(value.to_str()?),
2185 "hint" => self.set_hint(value.to_str()?),
2186 "tag" => self.set_tag(value.to_i64()?),
2187 "tag_string" => self.set_tag_string(value.to_str()?),
2188 "accessible_name" => self.set_accessible_name(value.to_str()?),
2189 "popup_menu" => {
2190 self.popup_menu = value.to_component()?;
2191 self
2192 }
2193 _ => return Err(Error::UnknownProperty(name.to_string())),
2194 };
2195 Ok(())
2196 }
2197}
2198
2199pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2201
2202fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2203 use crate::canvas::FontWeight::*;
2204 let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2205 match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2206 Some(0) => Ok(None),
2207 Some(i) => Ok(Some(all[i - 1])),
2208 None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2209 }
2210}
2211
2212#[derive(Clone, Debug, Default, PartialEq)]
2216pub struct FontOverride {
2217 pub family: String,
2219 pub size: Option<f32>,
2221 pub weight: Option<crate::canvas::FontWeight>,
2223 pub italic: bool,
2225 pub underline: bool,
2227 pub strikeout: bool,
2229}
2230
2231impl FontOverride {
2232 pub fn is_empty(&self) -> bool {
2233 *self == Self::default()
2234 }
2235
2236 pub fn over(&self, parent: &FontOverride) -> FontOverride {
2238 FontOverride {
2239 family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2240 size: self.size.or(parent.size),
2241 weight: self.weight.or(parent.weight),
2242 italic: self.italic || parent.italic,
2243 underline: self.underline || parent.underline,
2244 strikeout: self.strikeout || parent.strikeout,
2245 }
2246 }
2247
2248 pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2250 if !self.family.is_empty() {
2251 font.family = self.family.clone();
2252 }
2253 if let Some(size) = self.size.filter(|s| *s > 0.0) {
2254 font.size = size;
2255 }
2256 if let Some(weight) = self.weight {
2257 font.weight = weight;
2258 }
2259 font.italic |= self.italic;
2260 font.underline |= self.underline;
2261 font.strikeout |= self.strikeout;
2262 }
2263}
2264
2265impl ControlBase {
2266 pub fn font(&self) -> &FontOverride {
2268 &self.font
2269 }
2270
2271 pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2272 self.font = font;
2273 self
2274 }
2275}
2276
2277#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2283pub struct ColorOverride {
2284 pub fill: Option<crate::Color>,
2286 pub border: Option<crate::Color>,
2288 pub text: Option<crate::Color>,
2290 pub accent: Option<crate::Color>,
2293 pub success: Option<crate::Color>,
2296 pub warning: Option<crate::Color>,
2298 pub danger: Option<crate::Color>,
2300}
2301
2302impl ColorOverride {
2303 pub fn is_empty(&self) -> bool {
2304 *self == Self::default()
2305 }
2306
2307 pub(crate) fn recolors_theme(&self) -> bool {
2309 !self.is_empty()
2310 }
2311
2312 pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2314 use crate::Color;
2315 let mut t = theme.clone();
2316 let mut set = |name: &str, c: Color| {
2317 t.colors.insert(name.to_string(), c);
2318 };
2319 if let Some(a) = self.accent {
2320 let dark = luminance(a) < 0.5;
2321 set("primary", a);
2322 set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2323 set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2324 set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2325 set("focus_ring", a);
2326 set("selection", a.with_opacity(0.25));
2327 set("primary_soft", a.with_opacity(0.1));
2328 set("primary_container", a.lerp(Color::WHITE, 0.82));
2329 }
2330 if let Some(c) = self.fill {
2331 let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2333 set("surface", c);
2334 set("background", c);
2335 set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2336 }
2337 if let Some(c) = self.text {
2338 set("text", c);
2339 set("text_muted", c.with_opacity(0.65));
2340 for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2341 set(on, c);
2342 }
2343 }
2344 if let Some(c) = self.border {
2345 set("border", c);
2346 set("track", c);
2347 }
2348 for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2349 if let Some(c) = color {
2350 set(token, c);
2351 set(&format!("{token}_soft"), c.with_opacity(0.1));
2352 set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2353 set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2354 if token == "success" {
2355 set("meter_low", c);
2356 } else if token == "danger" {
2357 set("meter_high", c);
2358 } else {
2359 set("meter_mid", c);
2360 }
2361 }
2362 }
2363 t
2364 }
2365}
2366
2367pub(crate) fn luminance(c: crate::Color) -> f32 {
2369 (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2370}
2371
2372#[derive(Clone, Copy, Debug, PartialEq)]
2374pub struct Connection {
2375 pub from: ComponentId,
2376 pub from_at: (f32, f32),
2378 pub to: ComponentId,
2379 pub to_at: (f32, f32),
2380}
2381
2382impl Connection {
2383 pub const STUB: f32 = 16.0;
2385
2386 fn normal(at: (f32, f32)) -> PointF {
2388 let (x, y) = at;
2389 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))];
2390 d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2391 }
2392
2393 pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2396 let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2397 let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2398 let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2399 let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2400 let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2401 let mut points = vec![p0, s0];
2402 if n0.x != 0.0 {
2403 let mx = (s0.x + s1.x) / 2.0;
2405 points.push(PointF::new(mx, s0.y));
2406 points.push(PointF::new(mx, s1.y));
2407 } else {
2408 let my = (s0.y + s1.y) / 2.0;
2409 points.push(PointF::new(s0.x, my));
2410 points.push(PointF::new(s1.x, my));
2411 }
2412 points.push(s1);
2413 points.push(p1);
2414 points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2415 points
2416 }
2417}
2418
2419#[derive(Clone, Debug, Default, PartialEq)]
2421pub struct DragDecl {
2422 pub data: String,
2425 pub label: String,
2427 pub drop_types: String,
2430 pub image: Option<ComponentId>,
2432}
2433
2434#[derive(Clone, Debug, Default)]
2436struct RareTexts {
2437 tag_string: Box<str>,
2439 accessible_name: Box<str>,
2442}