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_drop(&self) -> Option<&dyn DragDrop> {
427 None
428 }
429
430 fn drag_drop_mut(&mut self) -> Option<&mut dyn DragDrop> {
431 None
432 }
433
434 fn accepts_text(&self) -> bool {
435 self.inner().is_some_and(|i| i.accepts_text())
436 }
437
438 fn captures_key(&self, event: &KeyEvent) -> bool {
441 self.inner().is_some_and(|i| i.captures_key(event))
442 }
443
444 fn mnemonic_text(&self) -> Option<&str> {
447 self.inner().and_then(|i| i.mnemonic_text())
448 }
449
450 fn mnemonic_focuses_child(&self) -> bool {
452 self.inner().is_some_and(|i| i.mnemonic_focuses_child())
453 }
454
455 fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
457 if let Some(inner) = self.inner_mut() {
458 inner.text_input(ctx, text);
459 }
460 }
461
462 fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
463 if let Some(inner) = self.inner_mut() {
464 inner.focus_enter(ctx);
465 }
466 }
467
468 fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
469 if let Some(inner) = self.inner_mut() {
470 inner.focus_exit(ctx);
471 }
472 }
473
474 fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
478 if let Some(inner) = self.inner_mut() {
479 inner.property_changed(ctx, name);
480 }
481 }
482
483 fn checked_state(&self) -> Option<bool> {
486 self.inner().and_then(|i| i.checked_state())
487 }
488
489 fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
496 match self.inner() {
497 Some(inner) => inner.change_args(name, value),
498 None => Some(EventArgs::Value(value.clone())),
499 }
500 }
501
502 fn paint_only_property(&self, name: &str) -> bool {
507 self.inner().is_some_and(|inner| inner.paint_only_property(name))
508 }
509
510 fn timed(&self) -> Option<&dyn Timed> {
512 self.inner().and_then(|i| i.timed())
513 }
514
515 fn timed_mut(&mut self) -> Option<&mut dyn Timed> {
516 self.inner_mut().and_then(|i| i.timed_mut())
517 }
518
519 fn layout_hooks(&self) -> Option<&dyn LayoutHooks> {
522 self.inner().and_then(|i| i.layout_hooks())
523 }
524
525 fn popup(&self) -> Option<&dyn Popup> {
528 self.inner().and_then(|i| i.popup())
529 }
530
531 fn popup_mut(&mut self) -> Option<&mut dyn Popup> {
532 self.inner_mut().and_then(|i| i.popup_mut())
533 }
534
535 fn accessible_items(&self) -> Option<&dyn AccessibleItems> {
538 self.inner().and_then(|i| i.accessible_items())
539 }
540
541 fn accessible_items_mut(&mut self) -> Option<&mut dyn AccessibleItems> {
542 self.inner_mut().and_then(|i| i.accessible_items_mut())
543 }
544
545 fn attach(&self) -> Option<(ComponentId, f32, f32)> {
549 self.inner().and_then(|i| i.attach())
550 }
551
552 fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
556 self.inner().map(|i| i.event_info(event)).unwrap_or_default()
557 }
558
559 fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
563 if let Some(inner) = self.inner_mut() {
564 inner.message(ctx, message);
565 }
566 }
567
568 fn methods(&self) -> &'static [MethodInfo] {
571 &[]
572 }
573
574 fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
578 let class = self.class_name();
579 match self.inner_mut() {
580 Some(inner) => inner.invoke(ctx, method, args),
581 None => Err(format!("{class} não tem o método '{method}'")),
582 }
583 }
584
585}
586
587pub trait AccessibleItems {
592 fn access_items(&self, _ui: &crate::Ui, _id: ComponentId) -> Vec<crate::automation::AccessItem> {
595 Vec::new()
596 }
597
598 fn access_action(&mut self, _ctx: &mut EventCtx<'_>, _index: usize, _action: crate::automation::ItemAction) -> bool {
601 false
602 }
603}
604
605pub trait Popup {
610 fn closes_on_outside_press(&self) -> bool {
617 false
618 }
619
620 fn dismissed(&mut self, _ctx: &mut EventCtx<'_>) -> bool {
626 false
627 }
628
629 fn dies_with(&self) -> Option<ComponentId> {
633 None
634 }
635}
636
637pub trait LayoutHooks {
641 fn arrange(&self, _area: RectF, _children: &[ArrangeItem]) -> Option<Vec<RectF>> {
646 None
647 }
648
649 fn baseline(&self, _ui: &crate::Ui, _id: ComponentId, _height: f32) -> Option<f32> {
653 None
654 }
655
656 fn dock_gap(&self) -> f32 {
659 0.0
660 }
661
662 fn auto_height(&self, _ui: &crate::Ui, _id: ComponentId, _width: f32) -> Option<f32> {
666 None
667 }
668
669 fn auto_width(&self, _ui: &crate::Ui, _id: ComponentId) -> Option<f32> {
673 None
674 }
675}
676
677pub trait Timed {
682 fn timer_interval(&self) -> Option<f64> {
685 None
686 }
687
688 fn timer_precision(&self) -> crate::TimerPrecision {
690 crate::TimerPrecision::default()
691 }
692
693 fn timer_background(&self) -> bool {
696 false
697 }
698
699 fn timer_late(&mut self, _late: f64) {}
701
702 fn frame(&mut self, _ctx: &mut EventCtx<'_>) -> bool {
706 false
707 }
708
709 fn timer(&mut self, ctx: &mut EventCtx<'_>) {
712 ctx.fire("on_timer", EventArgs::None);
713 }
714}
715
716pub trait DragDrop {
722 fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
727 None
728 }
729
730 fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
733 None
734 }
735
736 fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
741 false
742 }
743
744 fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
747
748 fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
750
751 fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
753
754 fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
756}
757
758pub trait PlatformHooks {
762 fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
764 None
765 }
766
767 fn tray(&self) -> Option<crate::tray::TraySpec> {
769 None
770 }
771
772 fn native_view(&self) -> Option<NativeView> {
776 None
777 }
778
779 fn take_native_commands(&self) -> Vec<NativeCommand> {
781 Vec::new()
782 }
783
784 fn connection(&self) -> Option<Connection> {
788 None
789 }
790
791 fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
794 false
795 }
796
797 fn files_hovering(&mut self, _ctx: &mut EventCtx<'_>, _paths: Option<&[String]>) -> bool {
800 false
801 }
802}
803
804pub trait DesignHooks {
808 fn design_grip(&self, _local: PointF) -> Option<usize> {
811 None
812 }
813
814 fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
818 None
819 }
820}
821
822#[derive(Clone, Copy, Debug, PartialEq)]
824pub struct ArrangeItem {
825 pub id: ComponentId,
826 pub size: SizeF,
827 pub margins: Bounds,
829 pub span: u32,
831 pub row_span: u32,
833 pub cell: Option<(u32, u32)>,
835 pub grow: f32,
837 pub baseline: Option<f32>,
839 pub spacing: f32,
842}
843
844impl ArrangeItem {
845 pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
847 ArrangeItem {
848 id,
849 size: SizeF::new(cb.width(), cb.height()),
850 margins: cb.margins(),
851 span: cb.column_span(),
852 row_span: cb.row_span(),
853 cell: cb.grid_cell(),
854 grow: cb.grow(),
855 baseline: None,
856 spacing: cb.spacing_scale(),
857 }
858 }
859}
860
861#[derive(Clone, Debug, PartialEq)]
863pub enum NativeView {
864 Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String, background: Option<crate::Color>, data_dir: String, browser_args: String },
873}
874
875#[derive(Clone, Debug, PartialEq)]
879pub struct WebMessage {
880 pub text: String,
881 pub url: String,
882}
883
884pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
888 allowed.is_empty()
889 || url.starts_with("about:")
890 || url.starts_with("data:")
891 || allowed.iter().any(|a| {
892 let a = a.trim_end_matches('/');
893 url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
894 })
895}
896
897pub fn url_origin(url: &str) -> String {
899 let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
900 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
901 format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
902}
903
904#[derive(Clone, Copy, Debug, PartialEq)]
907pub struct MethodInfo {
908 pub name: &'static str,
909 pub args: &'static [PropKind],
910 pub returns: Option<PropKind>,
911 pub params: &'static [&'static str],
914 pub arg_types: &'static [&'static str],
917 pub returns_type: &'static str,
918}
919
920impl MethodInfo {
921 pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
922 Self { name, args, returns, params: &[], arg_types: &[], returns_type: "" }
923 }
924
925 pub const fn types(self, args: &'static [&'static str], returns: &'static str) -> Self {
927 Self { arg_types: args, returns_type: returns, ..self }
928 }
929
930 pub const fn params(self, names: &'static [&'static str]) -> Self {
933 Self { params: names, ..self }
934 }
935}
936
937#[derive(Clone, Debug, PartialEq)]
939pub enum NativeCommand {
940 Eval(String),
942 Back,
943 Forward,
944 Reload,
945}
946
947#[derive(Clone, Debug, PartialEq)]
949pub struct NativeViewSlot {
950 pub id: ComponentId,
951 pub rect: crate::RectF,
952 pub clip: Option<crate::RectF>,
955 pub visible: bool,
956 pub view: NativeView,
957 pub commands: Vec<NativeCommand>,
958}
959
960pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
966 let mut out: Vec<PropInfo> = Vec::new();
967 let mut seen = std::collections::HashSet::new();
970 let mut push = |info: &PropInfo| {
971 if seen.insert(info.name) {
972 out.push(*info);
973 }
974 };
975 let mut layer = Some(component);
976 while let Some(l) = layer {
977 l.props().iter().for_each(&mut push);
978 layer = l.inner();
979 }
980 if component.control().is_some() {
981 ControlBase::PROPS.iter().for_each(&mut push);
982 }
983 out
984}
985
986pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
989 let mut layer = Some(component);
990 while let Some(l) = layer {
991 if let Some(info) = l.props().iter().find(|p| p.name == name) {
992 return Some(*info);
993 }
994 layer = l.inner();
995 }
996 if component.control().is_some() {
997 return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
998 }
999 None
1000}
1001
1002pub const VALUE_PROPERTIES: [&str; 19] = [
1007 "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
1008 "angle", "pressed", "position", "low", "high",
1009];
1010
1011pub fn is_value_property(info: &PropInfo) -> bool {
1015 match info.name {
1016 "tab_index" | "expanded" => true,
1017 name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
1018 }
1019}
1020
1021pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
1022 let mut layer = Some(component);
1023 while let Some(l) = layer {
1024 if let Some(v) = l.get_prop(name) {
1025 return Some(v);
1026 }
1027 layer = l.inner();
1028 }
1029 component.control().and_then(|cb| cb.get_prop(name))
1030}
1031
1032#[derive(Clone, Copy, Debug, PartialEq)]
1035pub(crate) struct AnchorRef {
1036 pub(crate) parent: SizeF,
1037 pub(crate) rect: RectF,
1038}
1039
1040#[derive(Clone, Debug)]
1045pub struct ControlBase {
1046 left: f32,
1048 top: f32,
1050 width: f32,
1052 height: f32,
1054 margins: Bounds,
1056 padding: Bounds,
1058 align: Align,
1060 anchors: Anchors,
1062 visible: bool,
1064 enabled: bool,
1066 hit_test: bool,
1068 clip_children: bool,
1070 inherit_state: bool,
1073 translatable: bool,
1077 captures_wheel: bool,
1080 captures_gesture: bool,
1083 can_focus: bool,
1085 draggable: bool,
1087 accepts_drops: bool,
1089 drag: Option<Box<DragDecl>>,
1092 tab_stop: bool,
1094 pan_on_touch: bool,
1096 pub(crate) popup_menu: Option<ComponentId>,
1098 cursor: CursorShape,
1100 opacity: f32,
1102 blend_mode: crate::BlendMode,
1105 rotation: f32,
1107 scale: f32,
1112 translate: PointF,
1114 cache_layer: bool,
1117 aspect_ratio: f32,
1119 max_width: f32,
1121 min_width: f32,
1123 min_height: f32,
1125 max_height: f32,
1127 self_align: SelfAlign,
1129 auto_size: bool,
1131 column_span: u32,
1133 grid_row: i16,
1136 grid_column: i16,
1138 row_span: u16,
1140 grow: f32,
1143 pub(crate) text_scale: f32,
1146 pub(crate) spacing_scale: f32,
1147 shadow: Option<crate::canvas::Shadow>,
1149 tag: i64,
1151 rare: Option<Box<RareTexts>>,
1154 style: String,
1156 theme: String,
1158 hint: String,
1160 state: ControlState,
1161 pub(crate) bounds: RectF,
1162 pub(crate) anchor_ref: Option<AnchorRef>,
1163 pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1166 pub(crate) design_hidden: bool,
1169 pub(crate) design_only: bool,
1171 pub(crate) keep_left_to_right: bool,
1174 pub(crate) colors: ColorOverride,
1176 pub(crate) font: FontOverride,
1178 scroll_offset: PointF,
1180 pub(crate) laid_out_scroll: PointF,
1183 pub(crate) safe_area: Bounds,
1185 pub(crate) content_size: SizeF,
1187}
1188
1189impl Default for ControlBase {
1190 fn default() -> Self {
1191 Self::new(100.0, 100.0)
1192 }
1193}
1194
1195impl ControlBase {
1196 pub const PROPS: &'static [PropInfo] = &[
1198 PropInfo::new("left", PropKind::Float, "Layout"),
1199 PropInfo::new("top", PropKind::Float, "Layout"),
1200 PropInfo::new("width", PropKind::Float, "Layout"),
1201 PropInfo::new("height", PropKind::Float, "Layout"),
1202 PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout").rust_type("Align"),
1203 PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout").rust_type("Anchors"),
1204 PropInfo::new("margins", PropKind::Bounds, "Layout"),
1205 PropInfo::new("padding", PropKind::Bounds, "Layout"),
1206 PropInfo::new("visible", PropKind::Bool, "Behavior"),
1207 PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1208 PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1209 PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1210 PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1211 PropInfo::new("translate", PropKind::Bool, "Behavior"),
1212 PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1213 PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1214 PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1215 PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1216 PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1217 PropInfo::new("drag_data", PropKind::String, "Behavior"),
1218 PropInfo::new("drag_label", PropKind::String, "Behavior"),
1219 PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1220 PropInfo::new("drop_types", PropKind::String, "Behavior"),
1221 PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1222 PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior").rust_type("CursorShape"),
1223 PropInfo::new("opacity", PropKind::Float, "Appearance"),
1224 PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance").rust_type("BlendMode"),
1225 PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1226 PropInfo::new("rotation", PropKind::Angle, "Layout"),
1227 PropInfo::new("scale", PropKind::Float, "Layout"),
1228 PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1229 PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1230 PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1231 PropInfo::new("max_width", PropKind::Float, "Layout"),
1232 PropInfo::new("min_width", PropKind::Float, "Layout"),
1233 PropInfo::new("min_height", PropKind::Float, "Layout"),
1234 PropInfo::new("max_height", PropKind::Float, "Layout"),
1235 PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout").rust_type("SelfAlign"),
1236 PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1237 PropInfo::new("column_span", PropKind::Int, "Layout"),
1238 PropInfo::new("grid_row", PropKind::Int, "Layout"),
1239 PropInfo::new("grid_column", PropKind::Int, "Layout"),
1240 PropInfo::new("row_span", PropKind::Int, "Layout"),
1241 PropInfo::new("grow", PropKind::Float, "Layout"),
1242 PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1243 PropInfo::new("style", PropKind::StyleName, "Appearance"),
1244 PropInfo::new("theme", PropKind::ThemeName, "Appearance"),
1245 PropInfo::new("fill", PropKind::Color, "Appearance"),
1246 PropInfo::new("border_color", PropKind::Color, "Appearance"),
1247 PropInfo::new("text_color", PropKind::Color, "Appearance"),
1248 PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1249 PropInfo::new("success_color", PropKind::Color, "Appearance"),
1250 PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1251 PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1252 PropInfo::new("font_family", PropKind::String, "Font"),
1253 PropInfo::new("font_size", PropKind::Float, "Font"),
1254 PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1255 PropInfo::new("font_italic", PropKind::Bool, "Font"),
1256 PropInfo::new("font_underline", PropKind::Bool, "Font"),
1257 PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1258 PropInfo::new("hint", PropKind::String, "Behavior"),
1259 PropInfo::new("tag", PropKind::Int, "Misc"),
1260 PropInfo::new("tag_string", PropKind::String, "Misc"),
1261 PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1262 PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1263 PropInfo::new("on_click", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1264 PropInfo::new("on_dbl_click", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1265 PropInfo::new("on_long_press", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1266 PropInfo::new("on_pointer_down", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1267 PropInfo::new("on_pointer_up", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1268 PropInfo::new("on_pointer_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1269 PropInfo::new("on_pointer_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1270 PropInfo::new("on_pointer_leave", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1271 PropInfo::new("on_wheel", PropKind::Event, "Events").event_arg(crate::EventArg::Wheel),
1272 PropInfo::new("on_gesture", PropKind::Event, "Events").event_arg(crate::EventArg::Gesture),
1273 PropInfo::new("on_swipe", PropKind::Event, "Events").event_arg(crate::EventArg::Swipe),
1274 PropInfo::new("on_key_down", PropKind::Event, "Events"),
1275 PropInfo::new("on_key_press", PropKind::Event, "Events"),
1276 PropInfo::new("on_key_up", PropKind::Event, "Events").event_arg(crate::EventArg::Key),
1277 PropInfo::new("on_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1278 PropInfo::new("on_exit", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1279 PropInfo::new("on_resize", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1280 PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1281 PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1282 PropInfo::new("on_drag_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1283 PropInfo::new("on_drag_leave", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1284 PropInfo::new("on_drag_drop", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1285 PropInfo::new("on_drag_end", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::Bool)),
1286 ];
1287
1288 pub fn new(width: f32, height: f32) -> Self {
1289 Self {
1290 left: 0.0,
1291 top: 0.0,
1292 width,
1293 height,
1294 margins: Bounds::ZERO,
1295 padding: Bounds::ZERO,
1296 align: Align::None,
1297 anchors: Anchors::default(),
1298 visible: true,
1299 enabled: true,
1300 hit_test: true,
1301 clip_children: false,
1302 inherit_state: false,
1303 translatable: true,
1304 captures_wheel: false,
1305 captures_gesture: false,
1306 can_focus: false,
1307 draggable: false,
1308 accepts_drops: false,
1309 drag: None,
1310 tab_stop: true,
1311 pan_on_touch: true,
1312 popup_menu: None,
1313 cursor: CursorShape::Default,
1314 opacity: 1.0,
1315 blend_mode: crate::BlendMode::Normal,
1316 rotation: 0.0,
1317 scale: 1.0,
1318 translate: PointF::ZERO,
1319 cache_layer: false,
1320 aspect_ratio: 0.0,
1321 max_width: 0.0,
1322 min_width: 0.0,
1323 min_height: 0.0,
1324 max_height: 0.0,
1325 self_align: SelfAlign::Stretch,
1326 auto_size: false,
1327 column_span: 1,
1328 grid_row: -1,
1329 grid_column: -1,
1330 row_span: 1,
1331 grow: 0.0,
1332 text_scale: 1.0,
1333 spacing_scale: 1.0,
1334 shadow: None,
1335 tag: 0,
1336 rare: None,
1337 style: String::new(),
1338 theme: String::new(),
1339 hint: String::new(),
1340 state: ControlState::default(),
1341 bounds: RectF::new(0.0, 0.0, width, height),
1342 anchor_ref: None,
1343 follow: None,
1344 design_hidden: false,
1345 design_only: false,
1346 keep_left_to_right: false,
1347 colors: ColorOverride::default(),
1348 font: FontOverride::default(),
1349 scroll_offset: PointF::ZERO,
1350 laid_out_scroll: PointF::ZERO,
1351 content_size: SizeF::ZERO,
1352 safe_area: Bounds::default(),
1353 }
1354 }
1355
1356 pub fn left(&self) -> f32 {
1359 self.left
1360 }
1361
1362 pub fn top(&self) -> f32 {
1363 self.top
1364 }
1365
1366 pub fn width(&self) -> f32 {
1367 self.width
1368 }
1369
1370 pub fn height(&self) -> f32 {
1371 self.height
1372 }
1373
1374 pub fn position(&self) -> PointF {
1375 PointF::new(self.left, self.top)
1376 }
1377
1378 pub fn size(&self) -> SizeF {
1379 SizeF::new(self.width, self.height)
1380 }
1381
1382 pub fn margins(&self) -> Bounds {
1385 if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1386 }
1387
1388 pub fn padding(&self) -> Bounds {
1390 if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1391 }
1392
1393 pub fn align(&self) -> Align {
1394 self.align
1395 }
1396
1397 pub fn anchors(&self) -> Anchors {
1398 self.anchors
1399 }
1400
1401 pub fn visible(&self) -> bool {
1402 self.visible
1403 }
1404
1405 pub fn design_only(&self) -> bool {
1407 self.design_only
1408 }
1409
1410 pub fn colors(&self) -> ColorOverride {
1412 self.colors
1413 }
1414
1415 pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1416 self.colors = colors;
1417 self
1418 }
1419
1420 pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1421 self.design_only = on;
1422 self
1423 }
1424
1425 pub fn keep_left_to_right(&self) -> bool {
1427 self.keep_left_to_right
1428 }
1429
1430 pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1431 self.keep_left_to_right = on;
1432 self
1433 }
1434
1435 pub fn enabled(&self) -> bool {
1436 self.enabled
1437 }
1438
1439 pub fn hit_test(&self) -> bool {
1440 self.hit_test
1441 }
1442
1443 pub fn translatable(&self) -> bool {
1444 self.translatable
1445 }
1446
1447 pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1448 self.translatable = v;
1449 self
1450 }
1451
1452 pub fn inherit_state(&self) -> bool {
1453 self.inherit_state
1454 }
1455
1456 pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1457 self.inherit_state = v;
1458 self
1459 }
1460
1461 pub fn clip_children(&self) -> bool {
1462 self.clip_children
1463 }
1464
1465 pub fn captures_wheel(&self) -> bool {
1466 self.captures_wheel
1467 }
1468
1469 pub fn captures_gesture(&self) -> bool {
1470 self.captures_gesture
1471 }
1472
1473 pub fn draggable(&self) -> bool {
1478 self.draggable
1479 }
1480
1481 pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1482 self.draggable = v;
1483 self
1484 }
1485
1486 pub fn accepts_drops(&self) -> bool {
1489 self.accepts_drops
1490 }
1491
1492 pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1493 self.accepts_drops = v;
1494 self
1495 }
1496
1497 pub fn drag_data(&self) -> &str {
1499 self.drag.as_ref().map_or("", |d| d.data.as_str())
1500 }
1501
1502 pub fn drag_label(&self) -> &str {
1503 self.drag.as_ref().map_or("", |d| d.label.as_str())
1504 }
1505
1506 pub fn drag_image(&self) -> Option<ComponentId> {
1508 self.drag.as_ref().and_then(|d| d.image)
1509 }
1510
1511 pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1513 if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1514 d.image = None;
1515 }
1516 }
1517
1518 pub fn drop_types(&self) -> &str {
1520 self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1521 }
1522
1523 fn drag_decl(&mut self) -> &mut DragDecl {
1524 self.drag.get_or_insert_with(Default::default)
1525 }
1526
1527 pub fn can_focus(&self) -> bool {
1528 self.can_focus
1529 }
1530
1531 pub fn tab_stop(&self) -> bool {
1533 self.tab_stop
1534 }
1535
1536 pub fn popup_menu(&self) -> Option<ComponentId> {
1538 self.popup_menu
1539 }
1540
1541 pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1542 self.popup_menu = menu;
1543 self
1544 }
1545
1546 pub fn pan_on_touch(&self) -> bool {
1548 self.pan_on_touch
1549 }
1550
1551 pub fn cursor(&self) -> CursorShape {
1553 self.cursor
1554 }
1555
1556 pub fn opacity(&self) -> f32 {
1557 self.opacity
1558 }
1559
1560 pub fn blend_mode(&self) -> crate::BlendMode {
1562 self.blend_mode
1563 }
1564
1565 pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1566 self.blend_mode = mode;
1567 self
1568 }
1569
1570 pub fn cache_layer(&self) -> bool {
1572 self.cache_layer
1573 }
1574
1575 pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1576 self.cache_layer = on;
1577 self
1578 }
1579
1580 pub fn rotation(&self) -> f32 {
1583 self.rotation
1584 }
1585
1586 pub fn scale(&self) -> f32 {
1588 self.scale
1589 }
1590
1591 pub fn inner_size(&self) -> SizeF {
1594 let s = self.scale;
1595 if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1596 }
1597
1598 pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1599 self.shadow
1600 }
1601
1602 pub fn aspect_ratio(&self) -> f32 {
1606 self.aspect_ratio
1607 }
1608
1609 pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1610 self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1611 self
1612 }
1613
1614 pub fn max_width(&self) -> f32 {
1618 self.max_width
1619 }
1620
1621 pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1622 self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1623 self
1624 }
1625
1626 pub fn min_width(&self) -> f32 {
1631 self.min_width
1632 }
1633
1634 pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1635 self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1636 self
1637 }
1638
1639 pub fn min_height(&self) -> f32 {
1641 self.min_height
1642 }
1643
1644 pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1645 self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1646 self
1647 }
1648
1649 pub fn max_height(&self) -> f32 {
1651 self.max_height
1652 }
1653
1654 pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1655 self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1656 self
1657 }
1658
1659 pub fn clamp_width(&self, available: f32) -> f32 {
1662 let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1663 w.max(self.min_width)
1664 }
1665
1666 pub fn clamp_height(&self, height: f32) -> f32 {
1668 let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1669 h.max(self.min_height)
1670 }
1671
1672 pub fn self_align(&self) -> SelfAlign {
1675 self.self_align
1676 }
1677
1678 pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1679 self.self_align = align;
1680 self
1681 }
1682
1683 pub fn band_width(&self, available: f32) -> f32 {
1687 match self.self_align {
1688 SelfAlign::Stretch => self.clamp_width(available),
1689 _ if self.max_width > 0.0 => self.clamp_width(available),
1690 _ => self.clamp_width(self.width),
1691 }
1692 }
1693
1694 pub fn band_height(&self, available: f32) -> f32 {
1697 match self.self_align {
1698 SelfAlign::Stretch => self.clamp_height(available),
1699 _ if self.max_height > 0.0 => self.clamp_height(available),
1700 _ => self.clamp_height(self.height),
1701 }
1702 }
1703
1704 pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1707 let spare = (available - size).max(0.0);
1708 match self.self_align {
1709 SelfAlign::Start => 0.0,
1710 SelfAlign::End => spare,
1711 SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1712 }
1713 }
1714
1715 pub fn auto_size(&self) -> bool {
1720 self.auto_size
1721 }
1722
1723 pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1724 self.auto_size = on;
1725 self
1726 }
1727
1728 pub fn column_span(&self) -> u32 {
1731 self.column_span.max(1)
1732 }
1733
1734 pub fn grid_cell(&self) -> Option<(u32, u32)> {
1736 (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1737 }
1738
1739 pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1740 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));
1741 self.grid_row = r;
1742 self.grid_column = c;
1743 self
1744 }
1745
1746 pub fn row_span(&self) -> u32 {
1748 u32::from(self.row_span.max(1))
1749 }
1750
1751 pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1752 self.row_span = span.clamp(1, 64) as u16;
1753 self
1754 }
1755
1756 pub fn grow(&self) -> f32 {
1757 self.grow
1758 }
1759
1760 pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1761 self.grow = grow.max(0.0);
1762 self
1763 }
1764
1765 pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1766 self.column_span = span.max(1);
1767 self
1768 }
1769
1770 pub fn text_scale(&self) -> f32 {
1772 self.text_scale
1773 }
1774
1775 pub fn spacing_scale(&self) -> f32 {
1777 self.spacing_scale
1778 }
1779
1780 pub fn tag(&self) -> i64 {
1781 self.tag
1782 }
1783
1784 pub fn accessible_name(&self) -> &str {
1787 self.rare.as_ref().map_or("", |r| &r.accessible_name)
1788 }
1789
1790 pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1791 self.rare_mut(|r| r.accessible_name = v.into());
1792 self
1793 }
1794
1795 fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1796 let rare = self.rare.get_or_insert_with(Default::default);
1797 change(rare);
1798 if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1799 self.rare = None;
1800 }
1801 }
1802
1803 pub fn tag_string(&self) -> &str {
1804 self.rare.as_ref().map_or("", |r| &r.tag_string)
1805 }
1806
1807 pub fn style(&self) -> &str {
1809 &self.style
1810 }
1811
1812 pub fn theme_name(&self) -> &str {
1814 &self.theme
1815 }
1816
1817 pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1818 self.theme = v.into();
1819 self
1820 }
1821
1822 pub fn hint(&self) -> &str {
1824 &self.hint
1825 }
1826
1827 pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1828 self.hint = v.into();
1829 self
1830 }
1831
1832 pub fn state(&self) -> ControlState {
1833 self.state
1834 }
1835
1836 pub fn bounds(&self) -> RectF {
1838 self.bounds
1839 }
1840
1841 pub fn scroll_offset(&self) -> PointF {
1843 self.scroll_offset
1844 }
1845
1846 pub fn laid_out_scroll(&self) -> PointF {
1849 self.laid_out_scroll
1850 }
1851
1852 pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1855 self.scroll_offset = offset;
1856 self
1857 }
1858
1859 pub fn content_size(&self) -> SizeF {
1862 self.content_size
1863 }
1864
1865 pub fn set_left(&mut self, v: f32) -> &mut Self {
1872 if self.left != v {
1873 self.left = v;
1874 self.anchor_ref = None;
1875 }
1876 self
1877 }
1878
1879 pub fn set_top(&mut self, v: f32) -> &mut Self {
1880 if self.top != v {
1881 self.top = v;
1882 self.anchor_ref = None;
1883 }
1884 self
1885 }
1886
1887 pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1888 self.set_left(left).set_top(top)
1889 }
1890
1891 pub fn set_width(&mut self, v: f32) -> &mut Self {
1892 if self.width != v.max(0.0) {
1893 self.width = v.max(0.0);
1894 self.anchor_ref = None;
1895 }
1896 self
1897 }
1898
1899 pub fn set_height(&mut self, v: f32) -> &mut Self {
1900 if self.height != v.max(0.0) {
1901 self.height = v.max(0.0);
1902 self.anchor_ref = None;
1903 }
1904 self
1905 }
1906
1907 pub(crate) fn set_measured_width(&mut self, v: f32) {
1909 self.width = v.max(0.0);
1910 if let Some(r) = self.anchor_ref.as_mut() {
1911 r.rect.width = self.width;
1912 }
1913 }
1914
1915 pub(crate) fn set_measured_height(&mut self, v: f32) {
1918 self.height = v.max(0.0);
1919 if let Some(r) = self.anchor_ref.as_mut() {
1920 r.rect.height = self.height;
1921 }
1922 }
1923
1924 pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1925 self.set_width(width).set_height(height)
1926 }
1927
1928 pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1930 self.set_position(left, top).set_size(width, height)
1931 }
1932
1933 pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1934 self.margins = v.into();
1935 self
1936 }
1937
1938 pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1939 self.padding = v.into();
1940 self
1941 }
1942
1943 pub fn set_align(&mut self, v: Align) -> &mut Self {
1944 self.align = v;
1945 self.anchor_ref = None;
1946 self
1947 }
1948
1949 pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1950 self.anchors = v;
1951 self.anchor_ref = None;
1952 self
1953 }
1954
1955 pub fn set_visible(&mut self, v: bool) -> &mut Self {
1956 self.visible = v;
1957 self
1958 }
1959
1960 pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1961 self.enabled = v;
1962 self
1963 }
1964
1965 pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1966 self.hit_test = v;
1967 self
1968 }
1969
1970 pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1971 self.clip_children = v;
1972 self
1973 }
1974
1975 pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1976 self.captures_wheel = v;
1977 self
1978 }
1979
1980 pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
1981 self.captures_gesture = v;
1982 self
1983 }
1984
1985 pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1986 self.can_focus = v;
1987 self
1988 }
1989
1990 pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1994 self.pan_on_touch = v;
1995 self
1996 }
1997
1998 pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1999 self.tab_stop = v;
2000 self
2001 }
2002
2003 pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
2004 self.cursor = v;
2005 self
2006 }
2007
2008 pub fn set_opacity(&mut self, v: f32) -> &mut Self {
2009 self.opacity = v.clamp(0.0, 1.0);
2010 self
2011 }
2012
2013 pub fn translate(&self) -> PointF {
2015 self.translate
2016 }
2017
2018 pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
2019 self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
2020 self
2021 }
2022
2023 pub fn set_scale(&mut self, scale: f32) -> &mut Self {
2025 self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
2026 self
2027 }
2028
2029 pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
2030 self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
2031 self
2032 }
2033
2034 pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
2035 self.shadow = shadow;
2036 self
2037 }
2038
2039 pub fn set_tag(&mut self, v: i64) -> &mut Self {
2040 self.tag = v;
2041 self
2042 }
2043
2044 pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
2045 self.rare_mut(|r| r.tag_string = v.into());
2046 self
2047 }
2048
2049 pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
2050 self.style = v.into();
2051 self
2052 }
2053
2054 pub fn state_mut(&mut self) -> &mut ControlState {
2057 &mut self.state
2058 }
2059
2060 pub fn get_prop(&self, name: &str) -> Option<PropValue> {
2063 Some(match name {
2064 "left" => self.left.into(),
2065 "top" => self.top.into(),
2066 "width" => self.width.into(),
2067 "height" => self.height.into(),
2068 "align" => self.align.into(),
2069 "anchors" => self.anchors.into(),
2070 "margins" => self.margins.into(),
2071 "padding" => self.padding.into(),
2072 "visible" => self.visible.into(),
2073 "enabled" => self.enabled.into(),
2074 "hit_test" => self.hit_test.into(),
2075 "clip_children" => self.clip_children.into(),
2076 "inherit_state" => self.inherit_state.into(),
2077 "translate" => self.translatable.into(),
2078 "captures_wheel" => self.captures_wheel.into(),
2079 "captures_gesture" => self.captures_gesture.into(),
2080 "can_focus" => self.can_focus.into(),
2081 "draggable" => self.draggable.into(),
2082 "accepts_drops" => self.accepts_drops.into(),
2083 "drag_data" => self.drag_data().into(),
2084 "drag_label" => self.drag_label().into(),
2085 "drag_image" => PropValue::Component(self.drag_image()),
2086 "drop_types" => self.drop_types().into(),
2087 "tab_stop" => self.tab_stop.into(),
2088 "cursor" => PropValue::enum_value(self.cursor),
2089 "opacity" => self.opacity.into(),
2090 "blend_mode" => PropValue::enum_value(self.blend_mode),
2091 "cache_layer" => self.cache_layer.into(),
2092 "rotation" => self.rotation.into(),
2093 "scale" => self.scale.into(),
2094 "translate_x" => self.translate.x.into(),
2095 "translate_y" => self.translate.y.into(),
2096 "aspect_ratio" => self.aspect_ratio.into(),
2097 "max_width" => self.max_width.into(),
2098 "min_width" => self.min_width.into(),
2099 "min_height" => self.min_height.into(),
2100 "max_height" => self.max_height.into(),
2101 "self_align" => PropValue::enum_value(self.self_align),
2102 "auto_size" => self.auto_size.into(),
2103 "column_span" => (self.column_span() as i64).into(),
2104 "grid_row" => i64::from(self.grid_row).into(),
2105 "grid_column" => i64::from(self.grid_column).into(),
2106 "row_span" => (self.row_span() as i64).into(),
2107 "grow" => f64::from(self.grow).into(),
2108 "shadow" => crate::prop::PropType::to_value(&self.shadow),
2109 "style" => self.style.clone().into(),
2110 "fill" => crate::prop::PropType::to_value(&self.colors.fill),
2111 "border_color" => crate::prop::PropType::to_value(&self.colors.border),
2112 "text_color" => crate::prop::PropType::to_value(&self.colors.text),
2113 "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
2114 "success_color" => crate::prop::PropType::to_value(&self.colors.success),
2115 "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
2116 "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
2117 "font_family" => self.font.family.clone().into(),
2118 "font_size" => crate::prop::PropType::to_value(&self.font.size),
2119 "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
2120 "font_italic" => self.font.italic.into(),
2121 "font_underline" => self.font.underline.into(),
2122 "font_strikeout" => self.font.strikeout.into(),
2123 "theme" => self.theme.clone().into(),
2124 "hint" => self.hint.clone().into(),
2125 "tag" => self.tag.into(),
2126 "tag_string" => self.tag_string().to_string().into(),
2127 "accessible_name" => self.accessible_name().to_string().into(),
2128 "popup_menu" => PropValue::Component(self.popup_menu),
2129 _ => return None,
2130 })
2131 }
2132
2133 pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
2134 match name {
2135 "left" => self.set_left(value.to_f32()?),
2136 "top" => self.set_top(value.to_f32()?),
2137 "width" => self.set_width(value.to_f32()?),
2138 "height" => self.set_height(value.to_f32()?),
2139 "align" => self.set_align(value.to_enum()?),
2140 "anchors" => self.set_anchors(value.to_anchors()?),
2141 "margins" => self.set_margins(value.to_bounds()?),
2142 "padding" => self.set_padding(value.to_bounds()?),
2143 "visible" => self.set_visible(value.to_bool()?),
2144 "enabled" => self.set_enabled(value.to_bool()?),
2145 "hit_test" => self.set_hit_test(value.to_bool()?),
2146 "clip_children" => self.set_clip_children(value.to_bool()?),
2147 "inherit_state" => self.set_inherit_state(value.to_bool()?),
2148 "translate" => self.set_translatable(value.to_bool()?),
2149 "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2150 "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2151 "can_focus" => self.set_can_focus(value.to_bool()?),
2152 "draggable" => self.set_draggable(value.to_bool()?),
2153 "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2154 "drag_data" => {
2155 self.drag_decl().data = value.to_str()?.to_string();
2156 self
2157 }
2158 "drag_label" => {
2159 self.drag_decl().label = value.to_str()?.to_string();
2160 self
2161 }
2162 "drag_image" => {
2163 self.drag_decl().image = value.to_component()?;
2164 self
2165 }
2166 "drop_types" => {
2167 self.drag_decl().drop_types = value.to_str()?.to_string();
2168 self
2169 }
2170 "tab_stop" => self.set_tab_stop(value.to_bool()?),
2171 "cursor" => self.set_cursor(value.to_enum()?),
2172 "opacity" => self.set_opacity(value.to_f32()?),
2173 "blend_mode" => self.set_blend_mode(value.to_enum()?),
2174 "cache_layer" => self.set_cache_layer(value.to_bool()?),
2175 "rotation" => self.set_rotation(value.to_f32()?),
2176 "scale" => self.set_scale(value.to_f32()?),
2177 "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2178 "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2179 "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2180 "max_width" => self.set_max_width(value.to_f32()?),
2181 "min_width" => self.set_min_width(value.to_f32()?),
2182 "min_height" => self.set_min_height(value.to_f32()?),
2183 "max_height" => self.set_max_height(value.to_f32()?),
2184 "self_align" => self.set_self_align(value.to_enum()?),
2185 "auto_size" => self.set_auto_size(value.to_bool()?),
2186 "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2187 "grid_row" => {
2188 self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2189 self
2190 }
2191 "grid_column" => {
2192 self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2193 self
2194 }
2195 "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2196 "grow" => self.set_grow(value.to_f32()?),
2197 "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2198 "style" => self.set_style(value.to_str()?),
2199 "fill" => {
2200 self.colors.fill = crate::prop::PropType::from_value(value)?;
2201 self
2202 }
2203 "border_color" => {
2204 self.colors.border = crate::prop::PropType::from_value(value)?;
2205 self
2206 }
2207 "text_color" => {
2208 self.colors.text = crate::prop::PropType::from_value(value)?;
2209 self
2210 }
2211 "accent_color" => {
2212 self.colors.accent = crate::prop::PropType::from_value(value)?;
2213 self
2214 }
2215 "success_color" => {
2216 self.colors.success = crate::prop::PropType::from_value(value)?;
2217 self
2218 }
2219 "warning_color" => {
2220 self.colors.warning = crate::prop::PropType::from_value(value)?;
2221 self
2222 }
2223 "danger_color" => {
2224 self.colors.danger = crate::prop::PropType::from_value(value)?;
2225 self
2226 }
2227 "font_family" => {
2228 self.font.family = value.to_str()?.to_string();
2229 self
2230 }
2231 "font_size" => {
2232 self.font.size = crate::prop::PropType::from_value(value)?;
2233 self
2234 }
2235 "font_weight" => {
2236 self.font.weight = font_weight_named(value.to_str()?)?;
2237 self
2238 }
2239 "font_italic" => {
2240 self.font.italic = value.to_bool()?;
2241 self
2242 }
2243 "font_underline" => {
2244 self.font.underline = value.to_bool()?;
2245 self
2246 }
2247 "font_strikeout" => {
2248 self.font.strikeout = value.to_bool()?;
2249 self
2250 }
2251 "theme" => self.set_theme_name(value.to_str()?),
2252 "hint" => self.set_hint(value.to_str()?),
2253 "tag" => self.set_tag(value.to_i64()?),
2254 "tag_string" => self.set_tag_string(value.to_str()?),
2255 "accessible_name" => self.set_accessible_name(value.to_str()?),
2256 "popup_menu" => {
2257 self.popup_menu = value.to_component()?;
2258 self
2259 }
2260 _ => return Err(Error::UnknownProperty(name.to_string())),
2261 };
2262 Ok(())
2263 }
2264}
2265
2266pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2268
2269fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2270 use crate::canvas::FontWeight::*;
2271 let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2272 match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2273 Some(0) => Ok(None),
2274 Some(i) => Ok(Some(all[i - 1])),
2275 None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2276 }
2277}
2278
2279#[derive(Clone, Debug, Default, PartialEq)]
2283pub struct FontOverride {
2284 pub family: String,
2286 pub size: Option<f32>,
2288 pub weight: Option<crate::canvas::FontWeight>,
2290 pub italic: bool,
2292 pub underline: bool,
2294 pub strikeout: bool,
2296}
2297
2298impl FontOverride {
2299 pub fn is_empty(&self) -> bool {
2300 *self == Self::default()
2301 }
2302
2303 pub fn over(&self, parent: &FontOverride) -> FontOverride {
2305 FontOverride {
2306 family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2307 size: self.size.or(parent.size),
2308 weight: self.weight.or(parent.weight),
2309 italic: self.italic || parent.italic,
2310 underline: self.underline || parent.underline,
2311 strikeout: self.strikeout || parent.strikeout,
2312 }
2313 }
2314
2315 pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2317 if !self.family.is_empty() {
2318 font.family = self.family.clone();
2319 }
2320 if let Some(size) = self.size.filter(|s| *s > 0.0) {
2321 font.size = size;
2322 }
2323 if let Some(weight) = self.weight {
2324 font.weight = weight;
2325 }
2326 font.italic |= self.italic;
2327 font.underline |= self.underline;
2328 font.strikeout |= self.strikeout;
2329 }
2330}
2331
2332impl ControlBase {
2333 pub fn font(&self) -> &FontOverride {
2335 &self.font
2336 }
2337
2338 pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2339 self.font = font;
2340 self
2341 }
2342}
2343
2344#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2350pub struct ColorOverride {
2351 pub fill: Option<crate::Color>,
2353 pub border: Option<crate::Color>,
2355 pub text: Option<crate::Color>,
2357 pub accent: Option<crate::Color>,
2360 pub success: Option<crate::Color>,
2363 pub warning: Option<crate::Color>,
2365 pub danger: Option<crate::Color>,
2367}
2368
2369impl ColorOverride {
2370 pub fn is_empty(&self) -> bool {
2371 *self == Self::default()
2372 }
2373
2374 pub(crate) fn recolors_theme(&self) -> bool {
2376 !self.is_empty()
2377 }
2378
2379 pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2381 use crate::Color;
2382 let mut t = theme.clone();
2383 let mut set = |name: &str, c: Color| {
2384 t.colors.insert(name.to_string(), c);
2385 };
2386 if let Some(a) = self.accent {
2387 let dark = luminance(a) < 0.5;
2388 set("primary", a);
2389 set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2390 set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2391 set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2392 set("focus_ring", a);
2393 set("selection", a.with_opacity(0.25));
2394 set("primary_soft", a.with_opacity(0.1));
2395 set("primary_container", a.lerp(Color::WHITE, 0.82));
2396 }
2397 if let Some(c) = self.fill {
2398 let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2400 set("surface", c);
2401 set("background", c);
2402 set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2403 }
2404 if let Some(c) = self.text {
2405 set("text", c);
2406 set("text_muted", c.with_opacity(0.65));
2407 for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2408 set(on, c);
2409 }
2410 }
2411 if let Some(c) = self.border {
2412 set("border", c);
2413 set("track", c);
2414 }
2415 for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2416 if let Some(c) = color {
2417 set(token, c);
2418 set(&format!("{token}_soft"), c.with_opacity(0.1));
2419 set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2420 set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2421 if token == "success" {
2422 set("meter_low", c);
2423 } else if token == "danger" {
2424 set("meter_high", c);
2425 } else {
2426 set("meter_mid", c);
2427 }
2428 }
2429 }
2430 t
2431 }
2432}
2433
2434pub(crate) fn luminance(c: crate::Color) -> f32 {
2436 (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2437}
2438
2439#[derive(Clone, Copy, Debug, PartialEq)]
2441pub struct Connection {
2442 pub from: ComponentId,
2443 pub from_at: (f32, f32),
2445 pub to: ComponentId,
2446 pub to_at: (f32, f32),
2447}
2448
2449impl Connection {
2450 pub const STUB: f32 = 16.0;
2452
2453 fn normal(at: (f32, f32)) -> PointF {
2455 let (x, y) = at;
2456 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))];
2457 d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2458 }
2459
2460 pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2463 let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2464 let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2465 let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2466 let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2467 let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2468 let mut points = vec![p0, s0];
2469 if n0.x != 0.0 {
2470 let mx = (s0.x + s1.x) / 2.0;
2472 points.push(PointF::new(mx, s0.y));
2473 points.push(PointF::new(mx, s1.y));
2474 } else {
2475 let my = (s0.y + s1.y) / 2.0;
2476 points.push(PointF::new(s0.x, my));
2477 points.push(PointF::new(s1.x, my));
2478 }
2479 points.push(s1);
2480 points.push(p1);
2481 points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2482 points
2483 }
2484}
2485
2486#[derive(Clone, Debug, Default, PartialEq)]
2488pub struct DragDecl {
2489 pub data: String,
2492 pub label: String,
2494 pub drop_types: String,
2497 pub image: Option<ComponentId>,
2499}
2500
2501#[derive(Clone, Debug, Default)]
2503struct RareTexts {
2504 tag_string: Box<str>,
2506 accessible_name: Box<str>,
2509}