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 child_pointer_mut(&mut self) -> Option<&mut dyn ChildPointer> {
528 self.inner_mut().and_then(|i| i.child_pointer_mut())
529 }
530
531 fn popup(&self) -> Option<&dyn Popup> {
534 self.inner().and_then(|i| i.popup())
535 }
536
537 fn popup_mut(&mut self) -> Option<&mut dyn Popup> {
538 self.inner_mut().and_then(|i| i.popup_mut())
539 }
540
541 fn accessible_items(&self) -> Option<&dyn AccessibleItems> {
544 self.inner().and_then(|i| i.accessible_items())
545 }
546
547 fn accessible_items_mut(&mut self) -> Option<&mut dyn AccessibleItems> {
548 self.inner_mut().and_then(|i| i.accessible_items_mut())
549 }
550
551 fn attach(&self) -> Option<(ComponentId, f32, f32)> {
555 self.inner().and_then(|i| i.attach())
556 }
557
558 fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
562 self.inner().map(|i| i.event_info(event)).unwrap_or_default()
563 }
564
565 fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
569 if let Some(inner) = self.inner_mut() {
570 inner.message(ctx, message);
571 }
572 }
573
574 fn methods(&self) -> &'static [MethodInfo] {
577 &[]
578 }
579
580 fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
584 let class = self.class_name();
585 match self.inner_mut() {
586 Some(inner) => inner.invoke(ctx, method, args),
587 None => Err(format!("{class} não tem o método '{method}'")),
588 }
589 }
590
591}
592
593pub trait AccessibleItems {
598 fn access_items(&self, _ui: &crate::Ui, _id: ComponentId) -> Vec<crate::automation::AccessItem> {
601 Vec::new()
602 }
603
604 fn access_action(&mut self, _ctx: &mut EventCtx<'_>, _index: usize, _action: crate::automation::ItemAction) -> bool {
607 false
608 }
609}
610
611pub trait Popup {
616 fn closes_on_outside_press(&self) -> bool {
623 false
624 }
625
626 fn dismissed(&mut self, _ctx: &mut EventCtx<'_>) -> bool {
632 false
633 }
634
635 fn dies_with(&self) -> Option<ComponentId> {
639 None
640 }
641}
642
643pub trait LayoutHooks {
647 fn arrange(&self, _area: RectF, _children: &[ArrangeItem]) -> Option<Vec<RectF>> {
652 None
653 }
654
655 fn baseline(&self, _ui: &crate::Ui, _id: ComponentId, _height: f32) -> Option<f32> {
659 None
660 }
661
662 fn dock_gap(&self) -> f32 {
665 0.0
666 }
667
668 fn auto_height(&self, _ui: &crate::Ui, _id: ComponentId, _width: f32) -> Option<f32> {
672 None
673 }
674
675 fn auto_width(&self, _ui: &crate::Ui, _id: ComponentId) -> Option<f32> {
679 None
680 }
681}
682
683pub trait Timed {
688 fn timer_interval(&self) -> Option<f64> {
691 None
692 }
693
694 fn timer_precision(&self) -> crate::TimerPrecision {
696 crate::TimerPrecision::default()
697 }
698
699 fn timer_background(&self) -> bool {
702 false
703 }
704
705 fn timer_late(&mut self, _late: f64) {}
707
708 fn frame(&mut self, _ctx: &mut EventCtx<'_>) -> bool {
712 false
713 }
714
715 fn timer(&mut self, ctx: &mut EventCtx<'_>) {
718 ctx.fire("on_timer", EventArgs::None);
719 }
720}
721
722pub trait ChildPointer {
733 fn child_pressed(&mut self, ctx: &mut EventCtx<'_>, child: ComponentId, event: &PointerEvent);
736 fn child_clicked(&mut self, ctx: &mut EventCtx<'_>, child: ComponentId);
738}
739
740pub trait DragDrop {
741 fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
746 None
747 }
748
749 fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
752 None
753 }
754
755 fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
760 false
761 }
762
763 fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
766
767 fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
769
770 fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
772
773 fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
775}
776
777pub trait PlatformHooks {
781 fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
783 None
784 }
785
786 fn tray(&self) -> Option<crate::tray::TraySpec> {
788 None
789 }
790
791 fn native_view(&self) -> Option<NativeView> {
795 None
796 }
797
798 fn take_native_commands(&self) -> Vec<NativeCommand> {
800 Vec::new()
801 }
802
803 fn connection(&self) -> Option<Connection> {
807 None
808 }
809
810 fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
813 false
814 }
815
816 fn files_hovering(&mut self, _ctx: &mut EventCtx<'_>, _paths: Option<&[String]>) -> bool {
819 false
820 }
821}
822
823pub trait DesignHooks {
827 fn design_grip(&self, _local: PointF) -> Option<usize> {
830 None
831 }
832
833 fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
837 None
838 }
839}
840
841#[derive(Clone, Copy, Debug, PartialEq)]
843pub struct ArrangeItem {
844 pub id: ComponentId,
845 pub size: SizeF,
846 pub margins: Bounds,
848 pub span: u32,
850 pub row_span: u32,
852 pub cell: Option<(u32, u32)>,
854 pub grow: f32,
856 pub baseline: Option<f32>,
858 pub spacing: f32,
861}
862
863impl ArrangeItem {
864 pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
866 ArrangeItem {
867 id,
868 size: SizeF::new(cb.width(), cb.height()),
869 margins: cb.margins(),
870 span: cb.column_span(),
871 row_span: cb.row_span(),
872 cell: cb.grid_cell(),
873 grow: cb.grow(),
874 baseline: None,
875 spacing: cb.spacing_scale(),
876 }
877 }
878}
879
880#[derive(Clone, Debug, PartialEq)]
882pub enum NativeView {
883 Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String, background: Option<crate::Color>, data_dir: String, browser_args: String },
892}
893
894#[derive(Clone, Debug, PartialEq)]
898pub struct WebMessage {
899 pub text: String,
900 pub url: String,
901}
902
903pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
907 allowed.is_empty()
908 || url.starts_with("about:")
909 || url.starts_with("data:")
910 || allowed.iter().any(|a| {
911 let a = a.trim_end_matches('/');
912 url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
913 })
914}
915
916pub fn url_origin(url: &str) -> String {
918 let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
919 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
920 format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
921}
922
923#[derive(Clone, Copy, Debug, PartialEq)]
926pub struct MethodInfo {
927 pub name: &'static str,
928 pub args: &'static [PropKind],
929 pub returns: Option<PropKind>,
930 pub params: &'static [&'static str],
933 pub arg_types: &'static [&'static str],
936 pub returns_type: &'static str,
937}
938
939impl MethodInfo {
940 pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
941 Self { name, args, returns, params: &[], arg_types: &[], returns_type: "" }
942 }
943
944 pub const fn types(self, args: &'static [&'static str], returns: &'static str) -> Self {
946 Self { arg_types: args, returns_type: returns, ..self }
947 }
948
949 pub const fn params(self, names: &'static [&'static str]) -> Self {
952 Self { params: names, ..self }
953 }
954}
955
956#[derive(Clone, Debug, PartialEq)]
958pub enum NativeCommand {
959 Eval(String),
961 Back,
962 Forward,
963 Reload,
964}
965
966#[derive(Clone, Debug, PartialEq)]
968pub struct NativeViewSlot {
969 pub id: ComponentId,
970 pub rect: crate::RectF,
971 pub clip: Option<crate::RectF>,
974 pub visible: bool,
975 pub view: NativeView,
976 pub commands: Vec<NativeCommand>,
977}
978
979pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
985 let mut out: Vec<PropInfo> = Vec::new();
986 let mut seen = std::collections::HashSet::new();
989 let mut push = |info: &PropInfo| {
990 if seen.insert(info.name) {
991 out.push(*info);
992 }
993 };
994 let mut layer = Some(component);
995 while let Some(l) = layer {
996 l.props().iter().for_each(&mut push);
997 layer = l.inner();
998 }
999 if component.control().is_some() {
1000 ControlBase::PROPS.iter().for_each(&mut push);
1001 }
1002 out
1003}
1004
1005pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
1008 let mut layer = Some(component);
1009 while let Some(l) = layer {
1010 if let Some(info) = l.props().iter().find(|p| p.name == name) {
1011 return Some(*info);
1012 }
1013 layer = l.inner();
1014 }
1015 if component.control().is_some() {
1016 return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
1017 }
1018 None
1019}
1020
1021pub const VALUE_PROPERTIES: [&str; 19] = [
1026 "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
1027 "angle", "pressed", "position", "low", "high",
1028];
1029
1030pub fn is_value_property(info: &PropInfo) -> bool {
1034 match info.name {
1035 "tab_index" | "expanded" => true,
1036 name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
1037 }
1038}
1039
1040pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
1041 let mut layer = Some(component);
1042 while let Some(l) = layer {
1043 if let Some(v) = l.get_prop(name) {
1044 return Some(v);
1045 }
1046 layer = l.inner();
1047 }
1048 component.control().and_then(|cb| cb.get_prop(name))
1049}
1050
1051#[derive(Clone, Copy, Debug, PartialEq)]
1054pub(crate) struct AnchorRef {
1055 pub(crate) parent: SizeF,
1056 pub(crate) rect: RectF,
1057}
1058
1059#[derive(Clone, Debug)]
1064pub struct ControlBase {
1065 left: f32,
1067 top: f32,
1069 width: f32,
1071 height: f32,
1073 margins: Bounds,
1075 padding: Bounds,
1077 align: Align,
1079 anchors: Anchors,
1081 visible: bool,
1083 enabled: bool,
1085 hit_test: bool,
1087 clip_children: bool,
1089 inherit_state: bool,
1092 translatable: bool,
1096 captures_wheel: bool,
1099 captures_gesture: bool,
1102 can_focus: bool,
1104 draggable: bool,
1106 accepts_drops: bool,
1108 drag: Option<Box<DragDecl>>,
1111 tab_stop: bool,
1113 pan_on_touch: bool,
1115 hover_within: bool,
1118 pub(crate) popup_menu: Option<ComponentId>,
1120 cursor: CursorShape,
1122 opacity: f32,
1124 blend_mode: crate::BlendMode,
1127 rotation: f32,
1129 scale: f32,
1134 translate: PointF,
1136 cache_layer: bool,
1139 aspect_ratio: f32,
1141 max_width: f32,
1143 min_width: f32,
1145 min_height: f32,
1147 max_height: f32,
1149 self_align: SelfAlign,
1151 auto_size: bool,
1153 column_span: u32,
1155 grid_row: i16,
1158 grid_column: i16,
1160 row_span: u16,
1162 grow: f32,
1165 pub(crate) text_scale: f32,
1168 pub(crate) spacing_scale: f32,
1169 shadow: Option<crate::canvas::Shadow>,
1171 tag: i64,
1173 rare: Option<Box<RareTexts>>,
1176 style: String,
1178 theme: String,
1180 hint: String,
1182 state: ControlState,
1183 pub(crate) bounds: RectF,
1184 pub(crate) anchor_ref: Option<AnchorRef>,
1185 pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1188 pub(crate) design_hidden: bool,
1191 pub(crate) design_only: bool,
1193 pub(crate) keep_left_to_right: bool,
1196 pub(crate) colors: ColorOverride,
1198 pub(crate) font: FontOverride,
1200 scroll_offset: PointF,
1202 pub(crate) laid_out_scroll: PointF,
1205 pub(crate) safe_area: Bounds,
1207 pub(crate) content_size: SizeF,
1209}
1210
1211impl Default for ControlBase {
1212 fn default() -> Self {
1213 Self::new(100.0, 100.0)
1214 }
1215}
1216
1217impl ControlBase {
1218 pub const PROPS: &'static [PropInfo] = &[
1220 PropInfo::new("left", PropKind::Float, "Layout"),
1221 PropInfo::new("top", PropKind::Float, "Layout"),
1222 PropInfo::new("width", PropKind::Float, "Layout"),
1223 PropInfo::new("height", PropKind::Float, "Layout"),
1224 PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout").rust_type("Align"),
1225 PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout").rust_type("Anchors"),
1226 PropInfo::new("margins", PropKind::Bounds, "Layout"),
1227 PropInfo::new("padding", PropKind::Bounds, "Layout"),
1228 PropInfo::new("visible", PropKind::Bool, "Behavior"),
1229 PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1230 PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1231 PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1232 PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1233 PropInfo::new("translate", PropKind::Bool, "Behavior"),
1234 PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1235 PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1236 PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1237 PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1238 PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1239 PropInfo::new("drag_data", PropKind::String, "Behavior"),
1240 PropInfo::new("drag_label", PropKind::String, "Behavior"),
1241 PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1242 PropInfo::new("drop_types", PropKind::String, "Behavior"),
1243 PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1244 PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior").rust_type("CursorShape"),
1245 PropInfo::new("opacity", PropKind::Float, "Appearance"),
1246 PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance").rust_type("BlendMode"),
1247 PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1248 PropInfo::new("rotation", PropKind::Angle, "Layout"),
1249 PropInfo::new("scale", PropKind::Float, "Layout"),
1250 PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1251 PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1252 PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1253 PropInfo::new("max_width", PropKind::Float, "Layout"),
1254 PropInfo::new("min_width", PropKind::Float, "Layout"),
1255 PropInfo::new("min_height", PropKind::Float, "Layout"),
1256 PropInfo::new("max_height", PropKind::Float, "Layout"),
1257 PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout").rust_type("SelfAlign"),
1258 PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1259 PropInfo::new("column_span", PropKind::Int, "Layout"),
1260 PropInfo::new("grid_row", PropKind::Int, "Layout"),
1261 PropInfo::new("grid_column", PropKind::Int, "Layout"),
1262 PropInfo::new("row_span", PropKind::Int, "Layout"),
1263 PropInfo::new("grow", PropKind::Float, "Layout"),
1264 PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1265 PropInfo::new("style", PropKind::StyleName, "Appearance"),
1266 PropInfo::new("theme", PropKind::ThemeName, "Appearance"),
1267 PropInfo::new("fill", PropKind::Color, "Appearance"),
1268 PropInfo::new("border_color", PropKind::Color, "Appearance"),
1269 PropInfo::new("text_color", PropKind::Color, "Appearance"),
1270 PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1271 PropInfo::new("success_color", PropKind::Color, "Appearance"),
1272 PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1273 PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1274 PropInfo::new("font_family", PropKind::String, "Font"),
1275 PropInfo::new("font_size", PropKind::Float, "Font"),
1276 PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1277 PropInfo::new("font_italic", PropKind::Bool, "Font"),
1278 PropInfo::new("font_underline", PropKind::Bool, "Font"),
1279 PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1280 PropInfo::new("hint", PropKind::String, "Behavior"),
1281 PropInfo::new("tag", PropKind::Int, "Misc"),
1282 PropInfo::new("tag_string", PropKind::String, "Misc"),
1283 PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1284 PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1285 PropInfo::new("on_click", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1286 PropInfo::new("on_dbl_click", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1287 PropInfo::new("on_long_press", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1288 PropInfo::new("on_pointer_down", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1289 PropInfo::new("on_pointer_up", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1290 PropInfo::new("on_pointer_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1291 PropInfo::new("on_pointer_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1292 PropInfo::new("on_pointer_leave", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1293 PropInfo::new("on_wheel", PropKind::Event, "Events").event_arg(crate::EventArg::Wheel),
1294 PropInfo::new("on_gesture", PropKind::Event, "Events").event_arg(crate::EventArg::Gesture),
1295 PropInfo::new("on_swipe", PropKind::Event, "Events").event_arg(crate::EventArg::Swipe),
1296 PropInfo::new("on_key_down", PropKind::Event, "Events"),
1297 PropInfo::new("on_key_press", PropKind::Event, "Events"),
1298 PropInfo::new("on_key_up", PropKind::Event, "Events").event_arg(crate::EventArg::Key),
1299 PropInfo::new("on_enter", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1300 PropInfo::new("on_exit", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1301 PropInfo::new("on_resize", PropKind::Event, "Events").event_arg(crate::EventArg::None),
1302 PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1303 PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1304 PropInfo::new("on_drag_move", PropKind::Event, "Events").event_arg(crate::EventArg::Pointer),
1305 PropInfo::new("on_drag_leave", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1306 PropInfo::new("on_drag_drop", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::String)),
1307 PropInfo::new("on_drag_end", PropKind::Event, "Events").event_arg(crate::EventArg::Value(PropKind::Bool)),
1308 ];
1309
1310 pub fn new(width: f32, height: f32) -> Self {
1311 Self {
1312 left: 0.0,
1313 top: 0.0,
1314 width,
1315 height,
1316 margins: Bounds::ZERO,
1317 padding: Bounds::ZERO,
1318 align: Align::None,
1319 anchors: Anchors::default(),
1320 visible: true,
1321 enabled: true,
1322 hit_test: true,
1323 clip_children: false,
1324 inherit_state: false,
1325 translatable: true,
1326 captures_wheel: false,
1327 captures_gesture: false,
1328 can_focus: false,
1329 draggable: false,
1330 accepts_drops: false,
1331 drag: None,
1332 tab_stop: true,
1333 pan_on_touch: true,
1334 hover_within: false,
1335 popup_menu: None,
1336 cursor: CursorShape::Default,
1337 opacity: 1.0,
1338 blend_mode: crate::BlendMode::Normal,
1339 rotation: 0.0,
1340 scale: 1.0,
1341 translate: PointF::ZERO,
1342 cache_layer: false,
1343 aspect_ratio: 0.0,
1344 max_width: 0.0,
1345 min_width: 0.0,
1346 min_height: 0.0,
1347 max_height: 0.0,
1348 self_align: SelfAlign::Stretch,
1349 auto_size: false,
1350 column_span: 1,
1351 grid_row: -1,
1352 grid_column: -1,
1353 row_span: 1,
1354 grow: 0.0,
1355 text_scale: 1.0,
1356 spacing_scale: 1.0,
1357 shadow: None,
1358 tag: 0,
1359 rare: None,
1360 style: String::new(),
1361 theme: String::new(),
1362 hint: String::new(),
1363 state: ControlState::default(),
1364 bounds: RectF::new(0.0, 0.0, width, height),
1365 anchor_ref: None,
1366 follow: None,
1367 design_hidden: false,
1368 design_only: false,
1369 keep_left_to_right: false,
1370 colors: ColorOverride::default(),
1371 font: FontOverride::default(),
1372 scroll_offset: PointF::ZERO,
1373 laid_out_scroll: PointF::ZERO,
1374 content_size: SizeF::ZERO,
1375 safe_area: Bounds::default(),
1376 }
1377 }
1378
1379 pub fn left(&self) -> f32 {
1382 self.left
1383 }
1384
1385 pub fn top(&self) -> f32 {
1386 self.top
1387 }
1388
1389 pub fn width(&self) -> f32 {
1390 self.width
1391 }
1392
1393 pub fn height(&self) -> f32 {
1394 self.height
1395 }
1396
1397 pub fn position(&self) -> PointF {
1398 PointF::new(self.left, self.top)
1399 }
1400
1401 pub fn size(&self) -> SizeF {
1402 SizeF::new(self.width, self.height)
1403 }
1404
1405 pub fn margins(&self) -> Bounds {
1408 if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1409 }
1410
1411 pub fn padding(&self) -> Bounds {
1413 if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1414 }
1415
1416 pub fn align(&self) -> Align {
1417 self.align
1418 }
1419
1420 pub fn anchors(&self) -> Anchors {
1421 self.anchors
1422 }
1423
1424 pub fn visible(&self) -> bool {
1425 self.visible
1426 }
1427
1428 pub fn design_only(&self) -> bool {
1430 self.design_only
1431 }
1432
1433 pub fn colors(&self) -> ColorOverride {
1435 self.colors
1436 }
1437
1438 pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1439 self.colors = colors;
1440 self
1441 }
1442
1443 pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1444 self.design_only = on;
1445 self
1446 }
1447
1448 pub fn keep_left_to_right(&self) -> bool {
1450 self.keep_left_to_right
1451 }
1452
1453 pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1454 self.keep_left_to_right = on;
1455 self
1456 }
1457
1458 pub fn enabled(&self) -> bool {
1459 self.enabled
1460 }
1461
1462 pub fn hit_test(&self) -> bool {
1463 self.hit_test
1464 }
1465
1466 pub fn translatable(&self) -> bool {
1467 self.translatable
1468 }
1469
1470 pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1471 self.translatable = v;
1472 self
1473 }
1474
1475 pub fn inherit_state(&self) -> bool {
1476 self.inherit_state
1477 }
1478
1479 pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1480 self.inherit_state = v;
1481 self
1482 }
1483
1484 pub fn clip_children(&self) -> bool {
1485 self.clip_children
1486 }
1487
1488 pub fn captures_wheel(&self) -> bool {
1489 self.captures_wheel
1490 }
1491
1492 pub fn captures_gesture(&self) -> bool {
1493 self.captures_gesture
1494 }
1495
1496 pub fn draggable(&self) -> bool {
1501 self.draggable
1502 }
1503
1504 pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1505 self.draggable = v;
1506 self
1507 }
1508
1509 pub fn accepts_drops(&self) -> bool {
1512 self.accepts_drops
1513 }
1514
1515 pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1516 self.accepts_drops = v;
1517 self
1518 }
1519
1520 pub fn drag_data(&self) -> &str {
1522 self.drag.as_ref().map_or("", |d| d.data.as_str())
1523 }
1524
1525 pub fn drag_label(&self) -> &str {
1526 self.drag.as_ref().map_or("", |d| d.label.as_str())
1527 }
1528
1529 pub fn drag_image(&self) -> Option<ComponentId> {
1531 self.drag.as_ref().and_then(|d| d.image)
1532 }
1533
1534 pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1536 if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1537 d.image = None;
1538 }
1539 }
1540
1541 pub fn drop_types(&self) -> &str {
1543 self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1544 }
1545
1546 fn drag_decl(&mut self) -> &mut DragDecl {
1547 self.drag.get_or_insert_with(Default::default)
1548 }
1549
1550 pub fn can_focus(&self) -> bool {
1551 self.can_focus
1552 }
1553
1554 pub fn tab_stop(&self) -> bool {
1556 self.tab_stop
1557 }
1558
1559 pub fn popup_menu(&self) -> Option<ComponentId> {
1561 self.popup_menu
1562 }
1563
1564 pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1565 self.popup_menu = menu;
1566 self
1567 }
1568
1569 pub fn pan_on_touch(&self) -> bool {
1571 self.pan_on_touch
1572 }
1573
1574 pub fn hover_within(&self) -> bool {
1576 self.hover_within
1577 }
1578
1579 pub fn set_hover_within(&mut self, v: bool) -> &mut Self {
1583 self.hover_within = v;
1584 self
1585 }
1586
1587 pub fn cursor(&self) -> CursorShape {
1589 self.cursor
1590 }
1591
1592 pub fn opacity(&self) -> f32 {
1593 self.opacity
1594 }
1595
1596 pub fn blend_mode(&self) -> crate::BlendMode {
1598 self.blend_mode
1599 }
1600
1601 pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1602 self.blend_mode = mode;
1603 self
1604 }
1605
1606 pub fn cache_layer(&self) -> bool {
1608 self.cache_layer
1609 }
1610
1611 pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1612 self.cache_layer = on;
1613 self
1614 }
1615
1616 pub fn rotation(&self) -> f32 {
1619 self.rotation
1620 }
1621
1622 pub fn scale(&self) -> f32 {
1624 self.scale
1625 }
1626
1627 pub fn inner_size(&self) -> SizeF {
1630 let s = self.scale;
1631 if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1632 }
1633
1634 pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1635 self.shadow
1636 }
1637
1638 pub fn aspect_ratio(&self) -> f32 {
1642 self.aspect_ratio
1643 }
1644
1645 pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1646 self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1647 self
1648 }
1649
1650 pub fn max_width(&self) -> f32 {
1654 self.max_width
1655 }
1656
1657 pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1658 self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1659 self
1660 }
1661
1662 pub fn min_width(&self) -> f32 {
1667 self.min_width
1668 }
1669
1670 pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1671 self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1672 self
1673 }
1674
1675 pub fn min_height(&self) -> f32 {
1677 self.min_height
1678 }
1679
1680 pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1681 self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1682 self
1683 }
1684
1685 pub fn max_height(&self) -> f32 {
1687 self.max_height
1688 }
1689
1690 pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1691 self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1692 self
1693 }
1694
1695 pub fn clamp_width(&self, available: f32) -> f32 {
1698 let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1699 w.max(self.min_width)
1700 }
1701
1702 pub fn clamp_height(&self, height: f32) -> f32 {
1704 let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1705 h.max(self.min_height)
1706 }
1707
1708 pub fn self_align(&self) -> SelfAlign {
1711 self.self_align
1712 }
1713
1714 pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1715 self.self_align = align;
1716 self
1717 }
1718
1719 pub fn band_width(&self, available: f32) -> f32 {
1723 match self.self_align {
1724 SelfAlign::Stretch => self.clamp_width(available),
1725 _ if self.max_width > 0.0 => self.clamp_width(available),
1726 _ => self.clamp_width(self.width),
1727 }
1728 }
1729
1730 pub fn band_height(&self, available: f32) -> f32 {
1733 match self.self_align {
1734 SelfAlign::Stretch => self.clamp_height(available),
1735 _ if self.max_height > 0.0 => self.clamp_height(available),
1736 _ => self.clamp_height(self.height),
1737 }
1738 }
1739
1740 pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1743 let spare = (available - size).max(0.0);
1744 match self.self_align {
1745 SelfAlign::Start => 0.0,
1746 SelfAlign::End => spare,
1747 SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1748 }
1749 }
1750
1751 pub fn auto_size(&self) -> bool {
1756 self.auto_size
1757 }
1758
1759 pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1760 self.auto_size = on;
1761 self
1762 }
1763
1764 pub fn column_span(&self) -> u32 {
1767 self.column_span.max(1)
1768 }
1769
1770 pub fn grid_cell(&self) -> Option<(u32, u32)> {
1772 (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1773 }
1774
1775 pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1776 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));
1777 self.grid_row = r;
1778 self.grid_column = c;
1779 self
1780 }
1781
1782 pub fn row_span(&self) -> u32 {
1784 u32::from(self.row_span.max(1))
1785 }
1786
1787 pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1788 self.row_span = span.clamp(1, 64) as u16;
1789 self
1790 }
1791
1792 pub fn grow(&self) -> f32 {
1793 self.grow
1794 }
1795
1796 pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1797 self.grow = grow.max(0.0);
1798 self
1799 }
1800
1801 pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1802 self.column_span = span.max(1);
1803 self
1804 }
1805
1806 pub fn text_scale(&self) -> f32 {
1808 self.text_scale
1809 }
1810
1811 pub fn spacing_scale(&self) -> f32 {
1813 self.spacing_scale
1814 }
1815
1816 pub fn tag(&self) -> i64 {
1817 self.tag
1818 }
1819
1820 pub fn accessible_name(&self) -> &str {
1823 self.rare.as_ref().map_or("", |r| &r.accessible_name)
1824 }
1825
1826 pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1827 self.rare_mut(|r| r.accessible_name = v.into());
1828 self
1829 }
1830
1831 fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1832 let rare = self.rare.get_or_insert_with(Default::default);
1833 change(rare);
1834 if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1835 self.rare = None;
1836 }
1837 }
1838
1839 pub fn tag_string(&self) -> &str {
1840 self.rare.as_ref().map_or("", |r| &r.tag_string)
1841 }
1842
1843 pub fn style(&self) -> &str {
1845 &self.style
1846 }
1847
1848 pub fn theme_name(&self) -> &str {
1850 &self.theme
1851 }
1852
1853 pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1854 self.theme = v.into();
1855 self
1856 }
1857
1858 pub fn hint(&self) -> &str {
1860 &self.hint
1861 }
1862
1863 pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1864 self.hint = v.into();
1865 self
1866 }
1867
1868 pub fn state(&self) -> ControlState {
1869 self.state
1870 }
1871
1872 pub fn bounds(&self) -> RectF {
1874 self.bounds
1875 }
1876
1877 pub fn scroll_offset(&self) -> PointF {
1879 self.scroll_offset
1880 }
1881
1882 pub fn laid_out_scroll(&self) -> PointF {
1885 self.laid_out_scroll
1886 }
1887
1888 pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1891 self.scroll_offset = offset;
1892 self
1893 }
1894
1895 pub fn content_size(&self) -> SizeF {
1898 self.content_size
1899 }
1900
1901 pub fn set_left(&mut self, v: f32) -> &mut Self {
1908 if self.left != v {
1909 self.left = v;
1910 self.anchor_ref = None;
1911 }
1912 self
1913 }
1914
1915 pub fn set_top(&mut self, v: f32) -> &mut Self {
1916 if self.top != v {
1917 self.top = v;
1918 self.anchor_ref = None;
1919 }
1920 self
1921 }
1922
1923 pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1924 self.set_left(left).set_top(top)
1925 }
1926
1927 pub fn set_width(&mut self, v: f32) -> &mut Self {
1928 if self.width != v.max(0.0) {
1929 self.width = v.max(0.0);
1930 self.anchor_ref = None;
1931 }
1932 self
1933 }
1934
1935 pub fn set_height(&mut self, v: f32) -> &mut Self {
1936 if self.height != v.max(0.0) {
1937 self.height = v.max(0.0);
1938 self.anchor_ref = None;
1939 }
1940 self
1941 }
1942
1943 pub(crate) fn set_measured_width(&mut self, v: f32) {
1945 self.width = v.max(0.0);
1946 if let Some(r) = self.anchor_ref.as_mut() {
1947 r.rect.width = self.width;
1948 }
1949 }
1950
1951 pub(crate) fn set_measured_height(&mut self, v: f32) {
1954 self.height = v.max(0.0);
1955 if let Some(r) = self.anchor_ref.as_mut() {
1956 r.rect.height = self.height;
1957 }
1958 }
1959
1960 pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1961 self.set_width(width).set_height(height)
1962 }
1963
1964 pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1966 self.set_position(left, top).set_size(width, height)
1967 }
1968
1969 pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1970 self.margins = v.into();
1971 self
1972 }
1973
1974 pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1975 self.padding = v.into();
1976 self
1977 }
1978
1979 pub fn set_align(&mut self, v: Align) -> &mut Self {
1980 self.align = v;
1981 self.anchor_ref = None;
1982 self
1983 }
1984
1985 pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1986 self.anchors = v;
1987 self.anchor_ref = None;
1988 self
1989 }
1990
1991 pub fn set_visible(&mut self, v: bool) -> &mut Self {
1992 self.visible = v;
1993 self
1994 }
1995
1996 pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1997 self.enabled = v;
1998 self
1999 }
2000
2001 pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
2002 self.hit_test = v;
2003 self
2004 }
2005
2006 pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
2007 self.clip_children = v;
2008 self
2009 }
2010
2011 pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
2012 self.captures_wheel = v;
2013 self
2014 }
2015
2016 pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
2017 self.captures_gesture = v;
2018 self
2019 }
2020
2021 pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
2022 self.can_focus = v;
2023 self
2024 }
2025
2026 pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
2030 self.pan_on_touch = v;
2031 self
2032 }
2033
2034 pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
2035 self.tab_stop = v;
2036 self
2037 }
2038
2039 pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
2040 self.cursor = v;
2041 self
2042 }
2043
2044 pub fn set_opacity(&mut self, v: f32) -> &mut Self {
2045 self.opacity = v.clamp(0.0, 1.0);
2046 self
2047 }
2048
2049 pub fn translate(&self) -> PointF {
2051 self.translate
2052 }
2053
2054 pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
2055 self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
2056 self
2057 }
2058
2059 pub fn set_scale(&mut self, scale: f32) -> &mut Self {
2061 self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
2062 self
2063 }
2064
2065 pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
2066 self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
2067 self
2068 }
2069
2070 pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
2071 self.shadow = shadow;
2072 self
2073 }
2074
2075 pub fn set_tag(&mut self, v: i64) -> &mut Self {
2076 self.tag = v;
2077 self
2078 }
2079
2080 pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
2081 self.rare_mut(|r| r.tag_string = v.into());
2082 self
2083 }
2084
2085 pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
2086 self.style = v.into();
2087 self
2088 }
2089
2090 pub fn state_mut(&mut self) -> &mut ControlState {
2093 &mut self.state
2094 }
2095
2096 pub fn get_prop(&self, name: &str) -> Option<PropValue> {
2099 Some(match name {
2100 "left" => self.left.into(),
2101 "top" => self.top.into(),
2102 "width" => self.width.into(),
2103 "height" => self.height.into(),
2104 "align" => self.align.into(),
2105 "anchors" => self.anchors.into(),
2106 "margins" => self.margins.into(),
2107 "padding" => self.padding.into(),
2108 "visible" => self.visible.into(),
2109 "enabled" => self.enabled.into(),
2110 "hit_test" => self.hit_test.into(),
2111 "clip_children" => self.clip_children.into(),
2112 "inherit_state" => self.inherit_state.into(),
2113 "translate" => self.translatable.into(),
2114 "captures_wheel" => self.captures_wheel.into(),
2115 "captures_gesture" => self.captures_gesture.into(),
2116 "can_focus" => self.can_focus.into(),
2117 "draggable" => self.draggable.into(),
2118 "accepts_drops" => self.accepts_drops.into(),
2119 "drag_data" => self.drag_data().into(),
2120 "drag_label" => self.drag_label().into(),
2121 "drag_image" => PropValue::Component(self.drag_image()),
2122 "drop_types" => self.drop_types().into(),
2123 "tab_stop" => self.tab_stop.into(),
2124 "cursor" => PropValue::enum_value(self.cursor),
2125 "opacity" => self.opacity.into(),
2126 "blend_mode" => PropValue::enum_value(self.blend_mode),
2127 "cache_layer" => self.cache_layer.into(),
2128 "rotation" => self.rotation.into(),
2129 "scale" => self.scale.into(),
2130 "translate_x" => self.translate.x.into(),
2131 "translate_y" => self.translate.y.into(),
2132 "aspect_ratio" => self.aspect_ratio.into(),
2133 "max_width" => self.max_width.into(),
2134 "min_width" => self.min_width.into(),
2135 "min_height" => self.min_height.into(),
2136 "max_height" => self.max_height.into(),
2137 "self_align" => PropValue::enum_value(self.self_align),
2138 "auto_size" => self.auto_size.into(),
2139 "column_span" => (self.column_span() as i64).into(),
2140 "grid_row" => i64::from(self.grid_row).into(),
2141 "grid_column" => i64::from(self.grid_column).into(),
2142 "row_span" => (self.row_span() as i64).into(),
2143 "grow" => f64::from(self.grow).into(),
2144 "shadow" => crate::prop::PropType::to_value(&self.shadow),
2145 "style" => self.style.clone().into(),
2146 "fill" => crate::prop::PropType::to_value(&self.colors.fill),
2147 "border_color" => crate::prop::PropType::to_value(&self.colors.border),
2148 "text_color" => crate::prop::PropType::to_value(&self.colors.text),
2149 "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
2150 "success_color" => crate::prop::PropType::to_value(&self.colors.success),
2151 "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
2152 "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
2153 "font_family" => self.font.family.clone().into(),
2154 "font_size" => crate::prop::PropType::to_value(&self.font.size),
2155 "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
2156 "font_italic" => self.font.italic.into(),
2157 "font_underline" => self.font.underline.into(),
2158 "font_strikeout" => self.font.strikeout.into(),
2159 "theme" => self.theme.clone().into(),
2160 "hint" => self.hint.clone().into(),
2161 "tag" => self.tag.into(),
2162 "tag_string" => self.tag_string().to_string().into(),
2163 "accessible_name" => self.accessible_name().to_string().into(),
2164 "popup_menu" => PropValue::Component(self.popup_menu),
2165 _ => return None,
2166 })
2167 }
2168
2169 pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
2170 match name {
2171 "left" => self.set_left(value.to_f32()?),
2172 "top" => self.set_top(value.to_f32()?),
2173 "width" => self.set_width(value.to_f32()?),
2174 "height" => self.set_height(value.to_f32()?),
2175 "align" => self.set_align(value.to_enum()?),
2176 "anchors" => self.set_anchors(value.to_anchors()?),
2177 "margins" => self.set_margins(value.to_bounds()?),
2178 "padding" => self.set_padding(value.to_bounds()?),
2179 "visible" => self.set_visible(value.to_bool()?),
2180 "enabled" => self.set_enabled(value.to_bool()?),
2181 "hit_test" => self.set_hit_test(value.to_bool()?),
2182 "clip_children" => self.set_clip_children(value.to_bool()?),
2183 "inherit_state" => self.set_inherit_state(value.to_bool()?),
2184 "translate" => self.set_translatable(value.to_bool()?),
2185 "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2186 "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2187 "can_focus" => self.set_can_focus(value.to_bool()?),
2188 "draggable" => self.set_draggable(value.to_bool()?),
2189 "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2190 "drag_data" => {
2191 self.drag_decl().data = value.to_str()?.to_string();
2192 self
2193 }
2194 "drag_label" => {
2195 self.drag_decl().label = value.to_str()?.to_string();
2196 self
2197 }
2198 "drag_image" => {
2199 self.drag_decl().image = value.to_component()?;
2200 self
2201 }
2202 "drop_types" => {
2203 self.drag_decl().drop_types = value.to_str()?.to_string();
2204 self
2205 }
2206 "tab_stop" => self.set_tab_stop(value.to_bool()?),
2207 "cursor" => self.set_cursor(value.to_enum()?),
2208 "opacity" => self.set_opacity(value.to_f32()?),
2209 "blend_mode" => self.set_blend_mode(value.to_enum()?),
2210 "cache_layer" => self.set_cache_layer(value.to_bool()?),
2211 "rotation" => self.set_rotation(value.to_f32()?),
2212 "scale" => self.set_scale(value.to_f32()?),
2213 "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2214 "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2215 "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2216 "max_width" => self.set_max_width(value.to_f32()?),
2217 "min_width" => self.set_min_width(value.to_f32()?),
2218 "min_height" => self.set_min_height(value.to_f32()?),
2219 "max_height" => self.set_max_height(value.to_f32()?),
2220 "self_align" => self.set_self_align(value.to_enum()?),
2221 "auto_size" => self.set_auto_size(value.to_bool()?),
2222 "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2223 "grid_row" => {
2224 self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2225 self
2226 }
2227 "grid_column" => {
2228 self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2229 self
2230 }
2231 "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2232 "grow" => self.set_grow(value.to_f32()?),
2233 "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2234 "style" => self.set_style(value.to_str()?),
2235 "fill" => {
2236 self.colors.fill = crate::prop::PropType::from_value(value)?;
2237 self
2238 }
2239 "border_color" => {
2240 self.colors.border = crate::prop::PropType::from_value(value)?;
2241 self
2242 }
2243 "text_color" => {
2244 self.colors.text = crate::prop::PropType::from_value(value)?;
2245 self
2246 }
2247 "accent_color" => {
2248 self.colors.accent = crate::prop::PropType::from_value(value)?;
2249 self
2250 }
2251 "success_color" => {
2252 self.colors.success = crate::prop::PropType::from_value(value)?;
2253 self
2254 }
2255 "warning_color" => {
2256 self.colors.warning = crate::prop::PropType::from_value(value)?;
2257 self
2258 }
2259 "danger_color" => {
2260 self.colors.danger = crate::prop::PropType::from_value(value)?;
2261 self
2262 }
2263 "font_family" => {
2264 self.font.family = value.to_str()?.to_string();
2265 self
2266 }
2267 "font_size" => {
2268 self.font.size = crate::prop::PropType::from_value(value)?;
2269 self
2270 }
2271 "font_weight" => {
2272 self.font.weight = font_weight_named(value.to_str()?)?;
2273 self
2274 }
2275 "font_italic" => {
2276 self.font.italic = value.to_bool()?;
2277 self
2278 }
2279 "font_underline" => {
2280 self.font.underline = value.to_bool()?;
2281 self
2282 }
2283 "font_strikeout" => {
2284 self.font.strikeout = value.to_bool()?;
2285 self
2286 }
2287 "theme" => self.set_theme_name(value.to_str()?),
2288 "hint" => self.set_hint(value.to_str()?),
2289 "tag" => self.set_tag(value.to_i64()?),
2290 "tag_string" => self.set_tag_string(value.to_str()?),
2291 "accessible_name" => self.set_accessible_name(value.to_str()?),
2292 "popup_menu" => {
2293 self.popup_menu = value.to_component()?;
2294 self
2295 }
2296 _ => return Err(Error::UnknownProperty(name.to_string())),
2297 };
2298 Ok(())
2299 }
2300}
2301
2302pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2304
2305fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2306 use crate::canvas::FontWeight::*;
2307 let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2308 match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2309 Some(0) => Ok(None),
2310 Some(i) => Ok(Some(all[i - 1])),
2311 None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2312 }
2313}
2314
2315#[derive(Clone, Debug, Default, PartialEq)]
2319pub struct FontOverride {
2320 pub family: String,
2322 pub size: Option<f32>,
2324 pub weight: Option<crate::canvas::FontWeight>,
2326 pub italic: bool,
2328 pub underline: bool,
2330 pub strikeout: bool,
2332}
2333
2334impl FontOverride {
2335 pub fn is_empty(&self) -> bool {
2336 *self == Self::default()
2337 }
2338
2339 pub fn over(&self, parent: &FontOverride) -> FontOverride {
2341 FontOverride {
2342 family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2343 size: self.size.or(parent.size),
2344 weight: self.weight.or(parent.weight),
2345 italic: self.italic || parent.italic,
2346 underline: self.underline || parent.underline,
2347 strikeout: self.strikeout || parent.strikeout,
2348 }
2349 }
2350
2351 pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2353 if !self.family.is_empty() {
2354 font.family = self.family.clone();
2355 }
2356 if let Some(size) = self.size.filter(|s| *s > 0.0) {
2357 font.size = size;
2358 }
2359 if let Some(weight) = self.weight {
2360 font.weight = weight;
2361 }
2362 font.italic |= self.italic;
2363 font.underline |= self.underline;
2364 font.strikeout |= self.strikeout;
2365 }
2366}
2367
2368impl ControlBase {
2369 pub fn font(&self) -> &FontOverride {
2371 &self.font
2372 }
2373
2374 pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2375 self.font = font;
2376 self
2377 }
2378}
2379
2380#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2386pub struct ColorOverride {
2387 pub fill: Option<crate::Color>,
2389 pub border: Option<crate::Color>,
2391 pub text: Option<crate::Color>,
2393 pub accent: Option<crate::Color>,
2396 pub success: Option<crate::Color>,
2399 pub warning: Option<crate::Color>,
2401 pub danger: Option<crate::Color>,
2403}
2404
2405impl ColorOverride {
2406 pub fn is_empty(&self) -> bool {
2407 *self == Self::default()
2408 }
2409
2410 pub(crate) fn recolors_theme(&self) -> bool {
2412 !self.is_empty()
2413 }
2414
2415 pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2417 use crate::Color;
2418 let mut t = theme.clone();
2419 let mut set = |name: &str, c: Color| {
2420 t.colors.insert(name.to_string(), c);
2421 };
2422 if let Some(a) = self.accent {
2423 let dark = luminance(a) < 0.5;
2424 set("primary", a);
2425 set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2426 set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2427 set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2428 set("focus_ring", a);
2429 set("selection", a.with_opacity(0.25));
2430 set("primary_soft", a.with_opacity(0.1));
2431 set("primary_container", a.lerp(Color::WHITE, 0.82));
2432 }
2433 if let Some(c) = self.fill {
2434 let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2436 set("surface", c);
2437 set("background", c);
2438 set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2439 }
2440 if let Some(c) = self.text {
2441 set("text", c);
2442 set("text_muted", c.with_opacity(0.65));
2443 for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2444 set(on, c);
2445 }
2446 }
2447 if let Some(c) = self.border {
2448 set("border", c);
2449 set("track", c);
2450 }
2451 for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2452 if let Some(c) = color {
2453 set(token, c);
2454 set(&format!("{token}_soft"), c.with_opacity(0.1));
2455 set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2456 set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2457 if token == "success" {
2458 set("meter_low", c);
2459 } else if token == "danger" {
2460 set("meter_high", c);
2461 } else {
2462 set("meter_mid", c);
2463 }
2464 }
2465 }
2466 t
2467 }
2468}
2469
2470pub(crate) fn luminance(c: crate::Color) -> f32 {
2472 (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2473}
2474
2475#[derive(Clone, Copy, Debug, PartialEq)]
2477pub struct Connection {
2478 pub from: ComponentId,
2479 pub from_at: (f32, f32),
2481 pub to: ComponentId,
2482 pub to_at: (f32, f32),
2483}
2484
2485impl Connection {
2486 pub const STUB: f32 = 16.0;
2488
2489 fn normal(at: (f32, f32)) -> PointF {
2491 let (x, y) = at;
2492 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))];
2493 d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2494 }
2495
2496 pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2499 let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2500 let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2501 let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2502 let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2503 let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2504 let mut points = vec![p0, s0];
2505 if n0.x != 0.0 {
2506 let mx = (s0.x + s1.x) / 2.0;
2508 points.push(PointF::new(mx, s0.y));
2509 points.push(PointF::new(mx, s1.y));
2510 } else {
2511 let my = (s0.y + s1.y) / 2.0;
2512 points.push(PointF::new(s0.x, my));
2513 points.push(PointF::new(s1.x, my));
2514 }
2515 points.push(s1);
2516 points.push(p1);
2517 points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2518 points
2519 }
2520}
2521
2522#[derive(Clone, Debug, Default, PartialEq)]
2524pub struct DragDecl {
2525 pub data: String,
2528 pub label: String,
2530 pub drop_types: String,
2533 pub image: Option<ComponentId>,
2535}
2536
2537#[derive(Clone, Debug, Default)]
2539struct RareTexts {
2540 tag_string: Box<str>,
2542 accessible_name: Box<str>,
2545}