1use std::any::{Any, type_name};
4use std::collections::HashSet;
5use std::fmt::{self, Debug};
6use std::ops::{BitAnd, BitOr, Deref, Not};
7use std::rc::Rc;
8
9use waft_embedder::{Canvas, Color, Offset, Paint, Path, Rect, Size};
10use waft_foundation::Ref;
11use waft_foundation::{
12 App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsProperty,
13 Handle, K_IS_WEB, describe_enum, describe_identity,
14};
15use waft_painting::{
16 AnyBorderSide, AnyColor, AnyTextStyle, BorderSide, BorderSideExtension, ColorExtension,
17 EdgeInsetsGeometry, OutlinedBorder, OutlinedBorderRef, RoundedRectangleBorder, ShapeBorder,
18 ShapeBorderRef, TextDirection, TextStyle, TextStyleExtension,
19};
20use waft_services::{MouseCursor, MouseCursorRef, MouseCursorSession, SystemMouseCursors};
21
22pub type WidgetStates = HashSet<WidgetState>;
24
25pub trait WidgetStatesConstraint: Debug + 'static {
36 fn is_satisfied_by(&self, states: &WidgetStates) -> bool;
53
54 fn as_any(&self) -> &dyn Any;
56
57 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
59 std::ptr::addr_eq(
60 self as *const Self,
61 other as *const dyn WidgetStatesConstraint,
62 )
63 }
64}
65
66impl PartialEq for dyn WidgetStatesConstraint {
67 fn eq(&self, other: &dyn WidgetStatesConstraint) -> bool {
68 self.eq_constraint(other)
69 }
70}
71
72#[derive(Clone)]
78pub struct WidgetStatesConstraintRef(Rc<dyn WidgetStatesConstraint>);
79
80impl WidgetStatesConstraintRef {
81 pub fn new(constraint: impl WidgetStatesConstraint) -> WidgetStatesConstraintRef {
83 WidgetStatesConstraintRef(Rc::new(constraint))
84 }
85}
86
87impl<C: WidgetStatesConstraint> From<C> for WidgetStatesConstraintRef {
88 fn from(constraint: C) -> WidgetStatesConstraintRef {
89 WidgetStatesConstraintRef::new(constraint)
90 }
91}
92
93impl Deref for WidgetStatesConstraintRef {
94 type Target = dyn WidgetStatesConstraint;
95
96 fn deref(&self) -> &dyn WidgetStatesConstraint {
97 &*self.0
98 }
99}
100
101impl PartialEq for WidgetStatesConstraintRef {
102 fn eq(&self, other: &WidgetStatesConstraintRef) -> bool {
103 self.0.eq_constraint(&*other.0)
104 }
105}
106
107impl Debug for WidgetStatesConstraintRef {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 self.0.fmt(f)
110 }
111}
112
113impl fmt::Display for WidgetStatesConstraintRef {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 let constraint = self.as_any();
118 if let Some(state) = constraint.downcast_ref::<WidgetState>() {
119 return write!(f, "WidgetState.{}", describe_enum(state));
120 }
121 if constraint.is::<AnyWidgetStates>() {
122 return f.write_str("WidgetState.any");
123 }
124 if let Some(and) = constraint.downcast_ref::<WidgetStateAnd>() {
125 return write!(f, "({} & {})", and.first, and.second);
126 }
127 if let Some(or) = constraint.downcast_ref::<WidgetStateOr>() {
128 return write!(f, "({} | {})", or.first, or.second);
129 }
130 if let Some(not) = constraint.downcast_ref::<WidgetStateNot>() {
131 return write!(f, "~{}", not.value);
132 }
133 write!(f, "{self:?}")
134 }
135}
136
137macro_rules! widget_states_constraint_operators {
139 ($constraint:ty) => {
140 impl<R: Into<WidgetStatesConstraintRef>> BitAnd<R> for $constraint {
141 type Output = WidgetStatesConstraintRef;
142
143 fn bitand(self, other: R) -> WidgetStatesConstraintRef {
145 WidgetStatesConstraintRef::new(WidgetStateAnd {
146 first: self.into(),
147 second: other.into(),
148 })
149 }
150 }
151
152 impl<R: Into<WidgetStatesConstraintRef>> BitOr<R> for $constraint {
153 type Output = WidgetStatesConstraintRef;
154
155 fn bitor(self, other: R) -> WidgetStatesConstraintRef {
157 WidgetStatesConstraintRef::new(WidgetStateOr {
158 first: self.into(),
159 second: other.into(),
160 })
161 }
162 }
163
164 impl Not for $constraint {
165 type Output = WidgetStatesConstraintRef;
166
167 fn not(self) -> WidgetStatesConstraintRef {
169 WidgetStatesConstraintRef::new(WidgetStateNot { value: self.into() })
170 }
171 }
172 };
173}
174
175widget_states_constraint_operators!(WidgetStatesConstraintRef);
176
177struct WidgetStateAnd {
180 first: WidgetStatesConstraintRef,
181 second: WidgetStatesConstraintRef,
182}
183
184impl WidgetStatesConstraint for WidgetStateAnd {
185 fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
186 self.first.is_satisfied_by(states) && self.second.is_satisfied_by(states)
187 }
188
189 fn as_any(&self) -> &dyn Any {
190 self
191 }
192
193 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
194 other
195 .as_any()
196 .downcast_ref::<WidgetStateAnd>()
197 .is_some_and(|other| other.first == self.first && other.second == self.second)
198 }
199}
200
201impl Debug for WidgetStateAnd {
202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203 write!(f, "({:?} & {:?})", self.first, self.second)
204 }
205}
206
207struct WidgetStateOr {
208 first: WidgetStatesConstraintRef,
209 second: WidgetStatesConstraintRef,
210}
211
212impl WidgetStatesConstraint for WidgetStateOr {
213 fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
214 self.first.is_satisfied_by(states) || self.second.is_satisfied_by(states)
215 }
216
217 fn as_any(&self) -> &dyn Any {
218 self
219 }
220
221 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
222 other
223 .as_any()
224 .downcast_ref::<WidgetStateOr>()
225 .is_some_and(|other| other.first == self.first && other.second == self.second)
226 }
227}
228
229impl Debug for WidgetStateOr {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 write!(f, "({:?} | {:?})", self.first, self.second)
232 }
233}
234
235struct WidgetStateNot {
236 value: WidgetStatesConstraintRef,
237}
238
239impl WidgetStatesConstraint for WidgetStateNot {
240 fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
241 !self.value.is_satisfied_by(states)
242 }
243
244 fn as_any(&self) -> &dyn Any {
245 self
246 }
247
248 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
249 other
250 .as_any()
251 .downcast_ref::<WidgetStateNot>()
252 .is_some_and(|other| other.value == self.value)
253 }
254}
255
256impl Debug for WidgetStateNot {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 write!(f, "~{:?}", self.value)
259 }
260}
261
262struct AnyWidgetStates;
265
266impl WidgetStatesConstraint for AnyWidgetStates {
267 fn is_satisfied_by(&self, _states: &WidgetStates) -> bool {
268 true
269 }
270
271 fn as_any(&self) -> &dyn Any {
272 self
273 }
274
275 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
276 other.as_any().is::<AnyWidgetStates>()
277 }
278}
279
280impl Debug for AnyWidgetStates {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.write_str("WidgetState.any")
283 }
284}
285
286#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
315pub enum WidgetState {
316 Hovered,
320
321 Focused,
328
329 Pressed,
333
334 Dragged,
339
340 Selected,
347
348 ScrolledUnder,
353
354 Disabled,
361
362 Error,
366}
367
368impl WidgetState {
369 pub fn any() -> WidgetStatesConstraintRef {
373 WidgetStatesConstraintRef::new(AnyWidgetStates)
374 }
375}
376
377pub fn widget_states(states: &WidgetStates) -> String {
380 let mut names: Vec<String> = states
381 .iter()
382 .map(|state| format!("WidgetState.{}", describe_enum(state)))
383 .collect();
384 names.sort();
385 format!("{{{}}}", names.join(", "))
386}
387
388impl WidgetStatesConstraint for WidgetState {
389 fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
390 states.contains(self)
391 }
392
393 fn as_any(&self) -> &dyn Any {
394 self
395 }
396
397 fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
398 other.as_any().downcast_ref::<WidgetState>() == Some(self)
399 }
400}
401
402widget_states_constraint_operators!(WidgetState);
403
404pub type WidgetPropertyResolver<T> = Rc<dyn Fn(&WidgetStates) -> T>;
407
408pub struct WidgetStateColor {
430 subclass: ColorSubclass,
431}
432
433enum ColorSubclass {
435 ResolveWith(WidgetPropertyResolver<Color>),
437 Transparent,
439 Mapper(WidgetStateMapper<Color>),
441}
442
443impl WidgetStateColor {
444 pub fn resolve_with(callback: impl Fn(&WidgetStates) -> Color + 'static) -> WidgetStateColor {
453 WidgetStateColor {
454 subclass: ColorSubclass::ResolveWith(Rc::new(callback)),
455 }
456 }
457
458 pub fn from_map(map: WidgetStateMap<Color>) -> WidgetStateColor {
470 WidgetStateColor {
471 subclass: ColorSubclass::Mapper(WidgetStateMapper::new(map)),
472 }
473 }
474
475 pub fn transparent() -> WidgetStateColor {
477 WidgetStateColor {
478 subclass: ColorSubclass::Transparent,
479 }
480 }
481
482 pub fn into_any(self) -> AnyColor {
485 let default_value = self.resolve(&WidgetStates::new());
486 AnyColor::with_shared(default_value, Rc::new(self))
487 }
488}
489
490impl WidgetStateProperty<Color> for WidgetStateColor {
491 fn resolve(&self, states: &WidgetStates) -> Color {
494 match &self.subclass {
495 ColorSubclass::ResolveWith(resolve) => resolve(states),
496 ColorSubclass::Transparent => Color::new(0x00000000),
497 ColorSubclass::Mapper(mapper) => mapper.resolve(states),
498 }
499 }
500
501 fn as_any(&self) -> &dyn Any {
502 self
503 }
504
505 fn as_mapper(&self) -> Option<&WidgetStateMapper<Color>> {
506 match &self.subclass {
507 ColorSubclass::Mapper(mapper) => Some(mapper),
508 _ => None,
509 }
510 }
511
512 fn eq_property(&self, other: &dyn WidgetStateProperty<Color>) -> bool {
515 if let ColorSubclass::Mapper(mapper) = &self.subclass {
516 return mapper.eq_property(other);
517 }
518 let default_states = WidgetStates::new();
519 other
520 .as_any()
521 .downcast_ref::<WidgetStateColor>()
522 .is_some_and(|other| {
523 self.eq_extension(other)
524 && self.resolve(&default_states) == other.resolve(&default_states)
525 })
526 }
527}
528
529impl ColorExtension for WidgetStateColor {
530 fn as_any(&self) -> &dyn Any {
531 self
532 }
533
534 fn eq_extension(&self, other: &dyn ColorExtension) -> bool {
537 other
538 .as_any()
539 .downcast_ref::<WidgetStateColor>()
540 .is_some_and(|other| match (&self.subclass, &other.subclass) {
541 (ColorSubclass::ResolveWith(_), ColorSubclass::ResolveWith(_))
542 | (ColorSubclass::Transparent, ColorSubclass::Transparent) => true,
543 (ColorSubclass::Mapper(mine), ColorSubclass::Mapper(theirs)) => mine == theirs,
544 _ => false,
545 })
546 }
547}
548
549impl Debug for WidgetStateColor {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 match &self.subclass {
552 ColorSubclass::ResolveWith(_) => f.write_str("WidgetStateColor.resolveWith"),
553 ColorSubclass::Transparent => f.write_str("WidgetStateColor.transparent"),
554 ColorSubclass::Mapper(mapper) => mapper.fmt(f),
555 }
556 }
557}
558
559impl From<WidgetStateColor> for AnyColor {
560 fn from(color: WidgetStateColor) -> AnyColor {
561 color.into_any()
562 }
563}
564
565impl MaybeWidgetStateProperty<Color> for AnyColor {
566 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Color>> {
567 self.extension::<WidgetStateColor>()
568 .map(|color| color as &dyn WidgetStateProperty<Color>)
569 }
570
571 fn from_resolved(value: Color) -> AnyColor {
572 AnyColor::new(value)
573 }
574}
575
576pub struct WidgetStateMouseCursor {
619 subclass: MouseCursorSubclass,
620}
621
622enum MouseCursorSubclass {
624 ResolveWith {
626 resolve: WidgetPropertyResolver<MouseCursorRef>,
627 debug_description: String,
628 },
629 Mapper(WidgetStateMapper<MouseCursorRef>),
631}
632
633impl WidgetStateMouseCursor {
634 pub fn resolve_with(
643 callback: impl Fn(&WidgetStates) -> MouseCursorRef + 'static,
644 debug_description: Option<&str>,
645 ) -> WidgetStateMouseCursor {
646 WidgetStateMouseCursor {
647 subclass: MouseCursorSubclass::ResolveWith {
648 resolve: Rc::new(callback),
649 debug_description: debug_description
650 .unwrap_or("WidgetStateMouseCursor()")
651 .to_owned(),
652 },
653 }
654 }
655
656 pub fn from_map(map: WidgetStateMap<MouseCursorRef>) -> WidgetStateMouseCursor {
664 WidgetStateMouseCursor {
665 subclass: MouseCursorSubclass::Mapper(WidgetStateMapper::new(map)),
666 }
667 }
668
669 pub fn clickable() -> WidgetStateMouseCursor {
675 thread_local! {
676 static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
677 Rc::new(WidgetStateMouseCursor::resolve_clickable);
678 }
679 Self::canonical(&RESOLVE, "WidgetStateMouseCursor(clickable)")
680 }
681
682 fn resolve_clickable(states: &WidgetStates) -> MouseCursorRef {
683 if states.contains(&WidgetState::Disabled) {
684 return SystemMouseCursors::BASIC.into();
685 }
686 SystemMouseCursors::CLICK.into()
687 }
688
689 pub fn adaptive_clickable() -> WidgetStateMouseCursor {
703 thread_local! {
704 static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
705 Rc::new(WidgetStateMouseCursor::resolve_adaptive_clickable);
706 }
707 Self::canonical(&RESOLVE, "WidgetStateMouseCursor(adaptiveClickable)")
708 }
709
710 fn resolve_adaptive_clickable(states: &WidgetStates) -> MouseCursorRef {
711 if states.contains(&WidgetState::Disabled) {
712 return SystemMouseCursors::BASIC.into();
713 }
714 if K_IS_WEB {
715 SystemMouseCursors::CLICK.into()
716 } else {
717 SystemMouseCursors::BASIC.into()
718 }
719 }
720
721 pub fn textable() -> WidgetStateMouseCursor {
729 thread_local! {
730 static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
731 Rc::new(WidgetStateMouseCursor::resolve_textable);
732 }
733 Self::canonical(&RESOLVE, "WidgetStateMouseCursor(textable)")
734 }
735
736 fn canonical(
739 resolve: &'static std::thread::LocalKey<WidgetPropertyResolver<MouseCursorRef>>,
740 debug_description: &str,
741 ) -> WidgetStateMouseCursor {
742 WidgetStateMouseCursor {
743 subclass: MouseCursorSubclass::ResolveWith {
744 resolve: resolve.with(Rc::clone),
745 debug_description: debug_description.to_owned(),
746 },
747 }
748 }
749
750 fn same_resolver(&self, other: &WidgetStateMouseCursor) -> bool {
753 match (&self.subclass, &other.subclass) {
754 (
755 MouseCursorSubclass::ResolveWith { resolve: mine, .. },
756 MouseCursorSubclass::ResolveWith {
757 resolve: theirs, ..
758 },
759 ) => Rc::ptr_eq(mine, theirs),
760 _ => false,
761 }
762 }
763
764 fn resolve_textable(states: &WidgetStates) -> MouseCursorRef {
765 if states.contains(&WidgetState::Disabled) {
766 return SystemMouseCursors::BASIC.into();
767 }
768 SystemMouseCursors::TEXT.into()
769 }
770}
771
772impl MouseCursor for WidgetStateMouseCursor {
773 fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession> {
774 self.resolve(&WidgetStates::new()).create_session(device)
775 }
776
777 fn debug_description(&self) -> String {
778 match &self.subclass {
779 MouseCursorSubclass::ResolveWith {
780 debug_description, ..
781 } => debug_description.clone(),
782 MouseCursorSubclass::Mapper(mapper) => format!("{mapper:?}"),
783 }
784 }
785
786 fn as_any(&self) -> &dyn Any {
787 self
788 }
789
790 fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
792 let Some(other) = other.as_any().downcast_ref::<WidgetStateMouseCursor>() else {
793 return false;
794 };
795 match (&self.subclass, &other.subclass) {
796 (MouseCursorSubclass::Mapper(mine), MouseCursorSubclass::Mapper(theirs)) => {
797 mine == theirs
798 }
799 _ => self.same_resolver(other),
800 }
801 }
802}
803
804impl WidgetStateProperty<MouseCursorRef> for WidgetStateMouseCursor {
805 fn resolve(&self, states: &WidgetStates) -> MouseCursorRef {
808 match &self.subclass {
809 MouseCursorSubclass::ResolveWith { resolve, .. } => resolve(states),
810 MouseCursorSubclass::Mapper(mapper) => mapper.resolve(states),
811 }
812 }
813
814 fn as_any(&self) -> &dyn Any {
815 self
816 }
817
818 fn as_mapper(&self) -> Option<&WidgetStateMapper<MouseCursorRef>> {
819 match &self.subclass {
820 MouseCursorSubclass::Mapper(mapper) => Some(mapper),
821 MouseCursorSubclass::ResolveWith { .. } => None,
822 }
823 }
824
825 fn eq_property(&self, other: &dyn WidgetStateProperty<MouseCursorRef>) -> bool {
827 match &self.subclass {
828 MouseCursorSubclass::Mapper(mapper) => mapper.eq_property(other),
829 MouseCursorSubclass::ResolveWith { .. } => other
830 .as_any()
831 .downcast_ref::<WidgetStateMouseCursor>()
832 .is_some_and(|other| self.same_resolver(other)),
833 }
834 }
835}
836
837impl Debug for WidgetStateMouseCursor {
838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839 f.write_str(&self.debug_description())
840 }
841}
842
843impl From<WidgetStateMouseCursor> for MouseCursorRef {
844 fn from(cursor: WidgetStateMouseCursor) -> MouseCursorRef {
845 Rc::new(cursor)
846 }
847}
848
849impl MaybeWidgetStateProperty<MouseCursorRef> for MouseCursorRef {
850 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<MouseCursorRef>> {
851 self.as_any()
852 .downcast_ref::<WidgetStateMouseCursor>()
853 .map(|cursor| cursor as &dyn WidgetStateProperty<MouseCursorRef>)
854 }
855
856 fn from_resolved(value: MouseCursorRef) -> MouseCursorRef {
857 value
858 }
859}
860
861pub struct WidgetStateBorderSide {
880 subclass: BorderSideSubclass,
881}
882
883enum BorderSideSubclass {
885 ResolveWith(WidgetPropertyResolver<Option<BorderSide>>),
887 Mapper(WidgetStateMapper<Option<BorderSide>>),
889}
890
891impl WidgetStateBorderSide {
892 pub fn resolve_with(
898 callback: impl Fn(&WidgetStates) -> Option<BorderSide> + 'static,
899 ) -> WidgetStateBorderSide {
900 WidgetStateBorderSide {
901 subclass: BorderSideSubclass::ResolveWith(Rc::new(callback)),
902 }
903 }
904
905 pub fn from_map(map: WidgetStateMap<Option<BorderSide>>) -> WidgetStateBorderSide {
910 WidgetStateBorderSide {
911 subclass: BorderSideSubclass::Mapper(WidgetStateMapper::new(map)),
912 }
913 }
914
915 pub fn into_any(self) -> AnyBorderSide {
918 AnyBorderSide::with_shared(BorderSide::default(), Rc::new(self))
919 }
920
921 pub fn lerp(
923 a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
924 b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
925 t: f64,
926 ) -> Option<WidgetStatePropertyRef<Option<BorderSide>>> {
927 if a.is_none() && b.is_none() {
929 return None;
930 }
931 if let (Some(a), Some(b)) = (&a, &b)
932 && Rc::ptr_eq(a, b)
933 {
934 return Some(Rc::clone(a));
935 }
936 Some(Rc::new(LerpSides { a, b, t }))
937 }
938}
939
940impl WidgetStateProperty<Option<BorderSide>> for WidgetStateBorderSide {
941 fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
942 match &self.subclass {
943 BorderSideSubclass::ResolveWith(resolve) => resolve(states),
944 BorderSideSubclass::Mapper(mapper) => mapper.resolve(states),
945 }
946 }
947
948 fn as_any(&self) -> &dyn Any {
949 self
950 }
951
952 fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<BorderSide>>> {
953 match &self.subclass {
954 BorderSideSubclass::Mapper(mapper) => Some(mapper),
955 BorderSideSubclass::ResolveWith(_) => None,
956 }
957 }
958
959 fn eq_property(&self, other: &dyn WidgetStateProperty<Option<BorderSide>>) -> bool {
961 if let BorderSideSubclass::Mapper(mapper) = &self.subclass {
962 return mapper.eq_property(other);
963 }
964 other
965 .as_any()
966 .downcast_ref::<WidgetStateBorderSide>()
967 .is_some_and(|other| self.eq_extension(other))
968 }
969}
970
971impl BorderSideExtension for WidgetStateBorderSide {
972 fn as_any(&self) -> &dyn Any {
973 self
974 }
975
976 fn eq_extension(&self, other: &dyn BorderSideExtension) -> bool {
979 other
980 .as_any()
981 .downcast_ref::<WidgetStateBorderSide>()
982 .is_some_and(|other| match (&self.subclass, &other.subclass) {
983 (BorderSideSubclass::ResolveWith(_), BorderSideSubclass::ResolveWith(_)) => true,
984 (BorderSideSubclass::Mapper(mine), BorderSideSubclass::Mapper(theirs)) => {
985 mine == theirs
986 }
987 _ => false,
988 })
989 }
990}
991
992impl Debug for WidgetStateBorderSide {
993 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
994 match &self.subclass {
995 BorderSideSubclass::ResolveWith(_) => f.write_str("WidgetStateBorderSide.resolveWith"),
996 BorderSideSubclass::Mapper(mapper) => mapper.fmt(f),
997 }
998 }
999}
1000
1001impl From<WidgetStateBorderSide> for AnyBorderSide {
1002 fn from(side: WidgetStateBorderSide) -> AnyBorderSide {
1003 side.into_any()
1004 }
1005}
1006
1007impl MaybeWidgetStateProperty<Option<BorderSide>> for Option<AnyBorderSide> {
1009 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Option<BorderSide>>> {
1010 self.as_ref()
1011 .and_then(|side| side.extension::<WidgetStateBorderSide>())
1012 .map(|side| side as &dyn WidgetStateProperty<Option<BorderSide>>)
1013 }
1014
1015 fn from_resolved(value: Option<BorderSide>) -> Option<AnyBorderSide> {
1016 value.map(AnyBorderSide::new)
1017 }
1018}
1019
1020struct LerpSides {
1022 a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
1023 b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
1024 t: f64,
1025}
1026
1027impl WidgetStateProperty<Option<BorderSide>> for LerpSides {
1028 fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
1029 let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
1030 let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
1031 match (resolved_a, resolved_b) {
1032 (None, None) => None,
1033 (None, Some(resolved_b)) => Some(BorderSide::lerp(
1034 BorderSide {
1035 width: 0.0,
1036 color: resolved_b.color.with_alpha(0),
1037 ..BorderSide::default()
1038 },
1039 resolved_b,
1040 self.t,
1041 )),
1042 (Some(resolved_a), None) => Some(BorderSide::lerp(
1043 resolved_a,
1044 BorderSide {
1045 width: 0.0,
1046 color: resolved_a.color.with_alpha(0),
1047 ..BorderSide::default()
1048 },
1049 self.t,
1050 )),
1051 (Some(resolved_a), Some(resolved_b)) => {
1052 Some(BorderSide::lerp(resolved_a, resolved_b, self.t))
1053 }
1054 }
1055 }
1056
1057 fn as_any(&self) -> &dyn Any {
1058 self
1059 }
1060}
1061
1062impl Debug for LerpSides {
1063 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1064 write!(f, "_LerpSides({:?}, {:?}, {})", self.a, self.b, self.t)
1065 }
1066}
1067
1068#[derive(Clone)]
1083pub struct WidgetStateOutlinedBorder {
1084 subclass: OutlinedBorderSubclass,
1085 border: RoundedRectangleBorder,
1087}
1088
1089#[derive(Clone)]
1091enum OutlinedBorderSubclass {
1092 ResolveWith(WidgetPropertyResolver<Option<OutlinedBorderRef>>),
1094 Mapper(Rc<WidgetStateMapper<Option<OutlinedBorderRef>>>),
1096}
1097
1098impl WidgetStateOutlinedBorder {
1099 pub fn resolve_with(
1105 callback: impl Fn(&WidgetStates) -> Option<OutlinedBorderRef> + 'static,
1106 ) -> WidgetStateOutlinedBorder {
1107 WidgetStateOutlinedBorder {
1108 subclass: OutlinedBorderSubclass::ResolveWith(Rc::new(callback)),
1109 border: RoundedRectangleBorder::default(),
1110 }
1111 }
1112
1113 pub fn from_map(map: WidgetStateMap<Option<OutlinedBorderRef>>) -> WidgetStateOutlinedBorder {
1118 WidgetStateOutlinedBorder {
1119 subclass: OutlinedBorderSubclass::Mapper(Rc::new(WidgetStateMapper::new(map))),
1120 border: RoundedRectangleBorder::default(),
1121 }
1122 }
1123}
1124
1125impl WidgetStateProperty<Option<OutlinedBorderRef>> for WidgetStateOutlinedBorder {
1126 fn resolve(&self, states: &WidgetStates) -> Option<OutlinedBorderRef> {
1127 match &self.subclass {
1128 OutlinedBorderSubclass::ResolveWith(resolve) => resolve(states),
1129 OutlinedBorderSubclass::Mapper(mapper) => mapper.resolve(states),
1130 }
1131 }
1132
1133 fn as_any(&self) -> &dyn Any {
1134 self
1135 }
1136
1137 fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<OutlinedBorderRef>>> {
1138 match &self.subclass {
1139 OutlinedBorderSubclass::Mapper(mapper) => Some(mapper.as_ref()),
1140 OutlinedBorderSubclass::ResolveWith(_) => None,
1141 }
1142 }
1143
1144 fn eq_property(&self, other: &dyn WidgetStateProperty<Option<OutlinedBorderRef>>) -> bool {
1146 if let OutlinedBorderSubclass::Mapper(mapper) = &self.subclass {
1147 return mapper.eq_property(other);
1148 }
1149 other
1150 .as_any()
1151 .downcast_ref::<WidgetStateOutlinedBorder>()
1152 .is_some_and(|other| self.eq_shape(other))
1153 }
1154}
1155
1156impl Debug for WidgetStateOutlinedBorder {
1157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1158 match &self.subclass {
1159 OutlinedBorderSubclass::ResolveWith(_) => {
1160 f.write_str("WidgetStateOutlinedBorder.resolveWith")
1161 }
1162 OutlinedBorderSubclass::Mapper(mapper) => mapper.fmt(f),
1163 }
1164 }
1165}
1166
1167impl ShapeBorder for WidgetStateOutlinedBorder {
1170 fn dimensions(&self) -> EdgeInsetsGeometry {
1171 self.border.dimensions()
1172 }
1173
1174 fn scale(&self, t: f64) -> ShapeBorderRef {
1175 ShapeBorder::scale(&self.border, t)
1176 }
1177
1178 fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1179 self.border.lerp_from(a, t)
1180 }
1181
1182 fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1183 self.border.lerp_to(b, t)
1184 }
1185
1186 fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1187 self.border.get_outer_path(rect, text_direction)
1188 }
1189
1190 fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1191 self.border.get_inner_path(rect, text_direction)
1192 }
1193
1194 fn hit_test(
1195 &self,
1196 rect: Rect,
1197 position: Offset,
1198 text_direction: Option<TextDirection>,
1199 ) -> bool {
1200 self.border.hit_test(rect, position, text_direction)
1201 }
1202
1203 fn paint_interior(
1204 &self,
1205 canvas: &mut Canvas,
1206 rect: Rect,
1207 paint: &Paint,
1208 text_direction: Option<TextDirection>,
1209 ) {
1210 self.border
1211 .paint_interior(canvas, rect, paint, text_direction);
1212 }
1213
1214 fn prefer_paint_interior(&self) -> bool {
1215 self.border.prefer_paint_interior()
1216 }
1217
1218 fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
1219 self.border.paint(canvas, rect, text_direction);
1220 }
1221
1222 fn as_any(&self) -> &dyn Any {
1223 self
1224 }
1225
1226 fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1227 Some(self)
1228 }
1229
1230 fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1231 Some(self)
1232 }
1233
1234 fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1237 other
1238 .as_any()
1239 .downcast_ref::<WidgetStateOutlinedBorder>()
1240 .is_some_and(|other| {
1241 self.border.eq_shape(&other.border)
1242 && match (&self.subclass, &other.subclass) {
1243 (
1244 OutlinedBorderSubclass::ResolveWith(_),
1245 OutlinedBorderSubclass::ResolveWith(_),
1246 ) => true,
1247 (
1248 OutlinedBorderSubclass::Mapper(mine),
1249 OutlinedBorderSubclass::Mapper(theirs),
1250 ) => mine == theirs,
1251 _ => false,
1252 }
1253 })
1254 }
1255}
1256
1257impl OutlinedBorder for WidgetStateOutlinedBorder {
1258 fn side(&self) -> BorderSide {
1259 self.border.side()
1260 }
1261
1262 fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
1263 OutlinedBorder::copy_with(&self.border, side)
1264 }
1265}
1266
1267impl MaybeWidgetStateProperty<Option<OutlinedBorderRef>> for Option<OutlinedBorderRef> {
1270 fn as_widget_state_property(
1271 &self,
1272 ) -> Option<&dyn WidgetStateProperty<Option<OutlinedBorderRef>>> {
1273 self.as_ref()
1274 .and_then(|border| border.as_any().downcast_ref::<WidgetStateOutlinedBorder>())
1275 .map(|border| border as &dyn WidgetStateProperty<Option<OutlinedBorderRef>>)
1276 }
1277
1278 fn from_resolved(value: Option<OutlinedBorderRef>) -> Option<OutlinedBorderRef> {
1279 value
1280 }
1281}
1282
1283pub struct WidgetStateTextStyle {
1299 subclass: TextStyleSubclass,
1300}
1301
1302enum TextStyleSubclass {
1304 ResolveWith(WidgetPropertyResolver<TextStyle>),
1306 Mapper(WidgetStateMapper<TextStyle>),
1308}
1309
1310impl WidgetStateTextStyle {
1311 pub fn resolve_with(
1319 callback: impl Fn(&WidgetStates) -> TextStyle + 'static,
1320 ) -> WidgetStateTextStyle {
1321 WidgetStateTextStyle {
1322 subclass: TextStyleSubclass::ResolveWith(Rc::new(callback)),
1323 }
1324 }
1325
1326 pub fn from_map(map: WidgetStateMap<TextStyle>) -> WidgetStateTextStyle {
1331 WidgetStateTextStyle {
1332 subclass: TextStyleSubclass::Mapper(WidgetStateMapper::new(map)),
1333 }
1334 }
1335
1336 pub fn into_any(self) -> AnyTextStyle {
1339 AnyTextStyle::with_shared(TextStyle::new(), Rc::new(self))
1340 }
1341}
1342
1343impl WidgetStateProperty<TextStyle> for WidgetStateTextStyle {
1344 fn resolve(&self, states: &WidgetStates) -> TextStyle {
1345 match &self.subclass {
1346 TextStyleSubclass::ResolveWith(resolve) => resolve(states),
1347 TextStyleSubclass::Mapper(mapper) => mapper.resolve(states),
1348 }
1349 }
1350
1351 fn as_any(&self) -> &dyn Any {
1352 self
1353 }
1354
1355 fn as_mapper(&self) -> Option<&WidgetStateMapper<TextStyle>> {
1356 match &self.subclass {
1357 TextStyleSubclass::Mapper(mapper) => Some(mapper),
1358 TextStyleSubclass::ResolveWith(_) => None,
1359 }
1360 }
1361
1362 fn eq_property(&self, other: &dyn WidgetStateProperty<TextStyle>) -> bool {
1364 if let TextStyleSubclass::Mapper(mapper) = &self.subclass {
1365 return mapper.eq_property(other);
1366 }
1367 other
1368 .as_any()
1369 .downcast_ref::<WidgetStateTextStyle>()
1370 .is_some_and(|other| self.eq_extension(other))
1371 }
1372}
1373
1374impl TextStyleExtension for WidgetStateTextStyle {
1375 fn as_any(&self) -> &dyn Any {
1376 self
1377 }
1378
1379 fn eq_extension(&self, other: &dyn TextStyleExtension) -> bool {
1382 other
1383 .as_any()
1384 .downcast_ref::<WidgetStateTextStyle>()
1385 .is_some_and(|other| match (&self.subclass, &other.subclass) {
1386 (TextStyleSubclass::ResolveWith(_), TextStyleSubclass::ResolveWith(_)) => true,
1387 (TextStyleSubclass::Mapper(mine), TextStyleSubclass::Mapper(theirs)) => {
1388 mine == theirs
1389 }
1390 _ => false,
1391 })
1392 }
1393}
1394
1395impl Debug for WidgetStateTextStyle {
1396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397 match &self.subclass {
1398 TextStyleSubclass::ResolveWith(_) => f.write_str("WidgetStateTextStyle.resolveWith"),
1399 TextStyleSubclass::Mapper(mapper) => mapper.fmt(f),
1400 }
1401 }
1402}
1403
1404impl From<WidgetStateTextStyle> for AnyTextStyle {
1405 fn from(style: WidgetStateTextStyle) -> AnyTextStyle {
1406 style.into_any()
1407 }
1408}
1409
1410impl MaybeWidgetStateProperty<TextStyle> for AnyTextStyle {
1411 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<TextStyle>> {
1412 self.extension::<WidgetStateTextStyle>()
1413 .map(|style| style as &dyn WidgetStateProperty<TextStyle>)
1414 }
1415
1416 fn from_resolved(value: TextStyle) -> AnyTextStyle {
1417 AnyTextStyle::new(value)
1418 }
1419}
1420
1421pub trait WidgetStateProperty<T>: Debug + 'static {
1464 fn resolve(&self, states: &WidgetStates) -> T;
1470
1471 fn as_any(&self) -> &dyn Any;
1473
1474 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1477 let _ = properties;
1478 }
1479
1480 fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
1483 None
1484 }
1485
1486 fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1489 std::ptr::addr_eq(
1490 self as *const Self,
1491 other as *const dyn WidgetStateProperty<T>,
1492 )
1493 }
1494}
1495
1496impl<T: 'static> PartialEq for dyn WidgetStateProperty<T> {
1497 fn eq(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1498 self.eq_property(other)
1499 }
1500}
1501
1502pub type WidgetStatePropertyRef<T> = Rc<dyn WidgetStateProperty<T>>;
1504
1505pub trait WidgetStatePropertyValue {
1508 fn state_property_value(&self) -> String;
1510
1511 const DART_TYPE: &'static str;
1513}
1514
1515macro_rules! display_state_value {
1516 ($($t:ty),* $(,)?) => {
1517 $(
1518 impl WidgetStatePropertyValue for Option<$t> {
1519 const DART_TYPE: &'static str = concat!(stringify!($t), "?");
1520
1521 fn state_property_value(&self) -> String {
1522 match self {
1523 Some(value) => value.to_string(),
1524 None => "null".to_string(),
1525 }
1526 }
1527 }
1528 )*
1529 };
1530}
1531
1532display_state_value!(
1533 Color,
1534 Size,
1535 EdgeInsetsGeometry,
1536 BorderSide,
1537 ShapeBorderRef,
1538 TextStyle
1539);
1540
1541impl WidgetStatePropertyValue for Option<bool> {
1542 const DART_TYPE: &'static str = "bool?";
1543
1544 fn state_property_value(&self) -> String {
1545 match self {
1546 Some(value) => value.to_string(),
1547 None => "null".to_string(),
1548 }
1549 }
1550}
1551
1552impl WidgetStatePropertyValue for Option<f64> {
1553 const DART_TYPE: &'static str = "double?";
1554
1555 fn state_property_value(&self) -> String {
1556 waft_foundation::debug_format_double(*self)
1557 }
1558}
1559
1560impl WidgetStatePropertyValue for f64 {
1561 const DART_TYPE: &'static str = "double";
1562
1563 fn state_property_value(&self) -> String {
1564 waft_foundation::debug_format_double(Some(*self))
1565 }
1566}
1567
1568impl WidgetStatePropertyValue for Option<OutlinedBorderRef> {
1569 const DART_TYPE: &'static str = "OutlinedBorder?";
1570
1571 fn state_property_value(&self) -> String {
1572 match self {
1573 Some(value) => format!("{value:?}"),
1574 None => "null".to_string(),
1575 }
1576 }
1577}
1578
1579impl WidgetStatePropertyValue for Option<MouseCursorRef> {
1580 const DART_TYPE: &'static str = "MouseCursor?";
1581
1582 fn state_property_value(&self) -> String {
1583 match self {
1584 Some(value) => value.debug_description(),
1585 None => "null".to_string(),
1586 }
1587 }
1588}
1589
1590impl WidgetStatePropertyValue for Option<crate::WidgetRef> {
1591 const DART_TYPE: &'static str = "Widget?";
1592
1593 fn state_property_value(&self) -> String {
1594 match self {
1595 Some(widget) => widget.to_string_short(),
1596 None => "null".to_string(),
1597 }
1598 }
1599}
1600
1601impl WidgetStatePropertyValue for Option<Rc<crate::Icon>> {
1602 const DART_TYPE: &'static str = "Icon?";
1603
1604 fn state_property_value(&self) -> String {
1605 match self {
1606 Some(icon) => match &icon.icon {
1607 Some(icon_data) => {
1608 format!("Icon(IconData(U+{:05X}))", icon_data.code_point)
1609 }
1610 None => "Icon".to_string(),
1611 },
1612 None => "null".to_string(),
1613 }
1614 }
1615}
1616
1617impl WidgetStatePropertyValue for Option<crate::IconThemeData> {
1618 const DART_TYPE: &'static str = "IconThemeData?";
1619
1620 fn state_property_value(&self) -> String {
1621 match self {
1622 Some(value) => value.to_string(),
1623 None => "null".to_string(),
1624 }
1625 }
1626}
1627
1628pub trait MaybeWidgetStateProperty<T>: Clone {
1634 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>>;
1636
1637 fn from_resolved(value: T) -> Self;
1639}
1640
1641impl<T, V: MaybeWidgetStateProperty<T>> MaybeWidgetStateProperty<T> for Option<V> {
1642 fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>> {
1643 self.as_ref().and_then(V::as_widget_state_property)
1644 }
1645
1646 fn from_resolved(value: T) -> Option<V> {
1647 Some(V::from_resolved(value))
1648 }
1649}
1650
1651impl<T: 'static> dyn WidgetStateProperty<T> {
1652 #[allow(
1656 clippy::inherent_to_string,
1657 reason = "Dart's toString needs a value bound Rust's Display cannot carry here"
1658 )]
1659 pub fn to_string(&self) -> String
1660 where
1661 T: WidgetStatePropertyValue + Debug,
1662 {
1663 if let Some(all) = self.as_any().downcast_ref::<WidgetStatePropertyAll<T>>() {
1664 return format!(
1665 "WidgetStatePropertyAll({})",
1666 all.value.state_property_value()
1667 );
1668 }
1669 if self.as_any().is::<WidgetStatePropertyWith<T>>() {
1670 return format!("Instance of '_WidgetStatePropertyWith<{}>'", T::DART_TYPE);
1671 }
1672 if let Some(mapper) = self.as_mapper() {
1673 return mapper.to_string();
1674 }
1675 format!("{self:?}")
1676 }
1677
1678 pub fn from_map(map: WidgetStateMap<T>) -> WidgetStatePropertyRef<T>
1688 where
1689 T: Clone + Debug + PartialEq,
1690 {
1691 Rc::new(WidgetStateMapper::new(map))
1692 }
1693
1694 pub fn resolve_as<V: MaybeWidgetStateProperty<T>>(value: &V, states: &WidgetStates) -> V {
1705 if let Some(property) = value.as_widget_state_property() {
1706 return V::from_resolved(property.resolve(states));
1707 }
1708 value.clone()
1709 }
1710
1711 pub fn resolve_with(
1714 callback: impl Fn(&WidgetStates) -> T + 'static,
1715 ) -> WidgetStatePropertyRef<T> {
1716 Rc::new(WidgetStatePropertyWith {
1717 resolve: Rc::new(callback),
1718 })
1719 }
1720
1721 pub fn all(value: T) -> WidgetStatePropertyRef<T>
1726 where
1727 T: Clone + Debug + PartialEq,
1728 {
1729 Rc::new(WidgetStatePropertyAll::new(value))
1730 }
1731
1732 pub fn lerp(
1734 a: Option<WidgetStatePropertyRef<T>>,
1735 b: Option<WidgetStatePropertyRef<T>>,
1736 t: f64,
1737 lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
1738 ) -> Option<WidgetStatePropertyRef<Option<T>>> {
1739 if a.is_none() && b.is_none() {
1741 return None;
1742 }
1743 Some(Rc::new(LerpProperties {
1744 a,
1745 b,
1746 t,
1747 lerp_function: Rc::new(lerp_function),
1748 }))
1749 }
1750}
1751
1752type LerpFunction<T> = Rc<dyn Fn(Option<T>, Option<T>, f64) -> Option<T>>;
1754
1755struct LerpProperties<T> {
1756 a: Option<WidgetStatePropertyRef<T>>,
1757 b: Option<WidgetStatePropertyRef<T>>,
1758 t: f64,
1759 lerp_function: LerpFunction<T>,
1760}
1761
1762impl<T: 'static> WidgetStateProperty<Option<T>> for LerpProperties<T> {
1763 fn resolve(&self, states: &WidgetStates) -> Option<T> {
1764 let resolved_a = self.a.as_ref().map(|a| a.resolve(states));
1765 let resolved_b = self.b.as_ref().map(|b| b.resolve(states));
1766 (self.lerp_function)(resolved_a, resolved_b, self.t)
1767 }
1768
1769 fn as_any(&self) -> &dyn Any {
1770 self
1771 }
1772}
1773
1774impl<T> Debug for LerpProperties<T> {
1775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1776 write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
1777 }
1778}
1779
1780impl<T: 'static> dyn WidgetStateProperty<Option<T>> {
1781 pub fn lerp_optional(
1789 a: Option<WidgetStatePropertyRef<Option<T>>>,
1790 b: Option<WidgetStatePropertyRef<Option<T>>>,
1791 t: f64,
1792 lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
1793 ) -> Option<WidgetStatePropertyRef<Option<T>>> {
1794 if a.is_none() && b.is_none() {
1796 return None;
1797 }
1798 Some(Rc::new(LerpOptionalProperties {
1799 a,
1800 b,
1801 t,
1802 lerp_function: Rc::new(lerp_function),
1803 }))
1804 }
1805}
1806
1807struct LerpOptionalProperties<T> {
1809 a: Option<WidgetStatePropertyRef<Option<T>>>,
1810 b: Option<WidgetStatePropertyRef<Option<T>>>,
1811 t: f64,
1812 lerp_function: LerpFunction<T>,
1813}
1814
1815impl<T: 'static> WidgetStateProperty<Option<T>> for LerpOptionalProperties<T> {
1816 fn resolve(&self, states: &WidgetStates) -> Option<T> {
1817 let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
1818 let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
1819 (self.lerp_function)(resolved_a, resolved_b, self.t)
1820 }
1821
1822 fn as_any(&self) -> &dyn Any {
1823 self
1824 }
1825}
1826
1827impl<T> Debug for LerpOptionalProperties<T> {
1828 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829 write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
1830 }
1831}
1832
1833struct WidgetStatePropertyWith<T> {
1834 resolve: WidgetPropertyResolver<T>,
1835}
1836
1837impl<T: 'static> WidgetStateProperty<T> for WidgetStatePropertyWith<T> {
1838 fn resolve(&self, states: &WidgetStates) -> T {
1839 (self.resolve)(states)
1840 }
1841
1842 fn as_any(&self) -> &dyn Any {
1843 self
1844 }
1845}
1846
1847impl<T> Debug for WidgetStatePropertyWith<T> {
1848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1849 f.write_str("WidgetStateProperty.resolveWith")
1850 }
1851}
1852
1853pub type WidgetStateMap<T> = Vec<(WidgetStatesConstraintRef, T)>;
1912
1913#[derive(Clone)]
1926pub struct WidgetStateMapper<T> {
1927 map: WidgetStateMap<T>,
1928}
1929
1930impl<T> WidgetStateMapper<T> {
1931 pub fn new(map: WidgetStateMap<T>) -> WidgetStateMapper<T> {
1934 WidgetStateMapper { map }
1935 }
1936}
1937
1938impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStateMapper<T> {
1939 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1940 properties.add(DiagnosticsProperty::<String>::new(
1941 "map",
1942 Some(format!("{:?}", self.map)),
1943 ));
1944 }
1945
1946 fn resolve(&self, states: &WidgetStates) -> T {
1947 for (key, value) in &self.map {
1948 if key.is_satisfied_by(states) {
1949 return value.clone();
1950 }
1951 }
1952
1953 panic!(
1954 "The current set of widget states is {states:?}.\n\
1955 None of the provided map keys matched this set, \
1956 and the type \"{t}\" is non-nullable.\n\
1957 Consider using \"WidgetStateMapper<Option<{t}>>\" with a final \
1958 \"WidgetState::any()\" key mapped to None, \
1959 or adding the \"WidgetState::any()\" key to this map.",
1960 t = type_name::<T>()
1961 );
1962 }
1963
1964 fn as_any(&self) -> &dyn Any {
1965 self
1966 }
1967
1968 fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
1969 Some(self)
1970 }
1971
1972 fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
1974 other.as_mapper().is_some_and(|other| self == other)
1975 }
1976}
1977
1978impl<T: PartialEq> PartialEq for WidgetStateMapper<T> {
1979 fn eq(&self, other: &WidgetStateMapper<T>) -> bool {
1981 self.map.len() == other.map.len()
1982 && self.map.iter().all(|(key, value)| {
1983 other
1984 .map
1985 .iter()
1986 .any(|(other_key, other_value)| other_key == key && other_value == value)
1987 })
1988 }
1989}
1990
1991impl<T: WidgetStatePropertyValue + Debug> WidgetStateMapper<T> {
1992 #[allow(
1994 clippy::inherent_to_string,
1995 reason = "Dart's toString needs Dart's value formatting, not Display"
1996 )]
1997 pub fn to_string(&self) -> String {
1998 let entries: Vec<String> = self
1999 .map
2000 .iter()
2001 .map(|(key, value)| format!("{key}: {}", value.state_property_value()))
2002 .collect();
2003 format!(
2004 "WidgetStateMapper<{}>({{{}}})",
2005 T::DART_TYPE,
2006 entries.join(", ")
2007 )
2008 }
2009}
2010
2011impl<T: Debug> Debug for WidgetStateMapper<T> {
2012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2013 write!(f, "WidgetStateMapper<{}>({:?})", type_name::<T>(), self.map)
2014 }
2015}
2016
2017#[derive(Clone, PartialEq)]
2025pub struct WidgetStatePropertyAll<T> {
2026 pub value: T,
2028}
2029
2030impl<T> WidgetStatePropertyAll<T> {
2031 pub const fn new(value: T) -> WidgetStatePropertyAll<T> {
2034 WidgetStatePropertyAll { value }
2035 }
2036}
2037
2038impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStatePropertyAll<T> {
2039 fn resolve(&self, _states: &WidgetStates) -> T {
2040 self.value.clone()
2041 }
2042
2043 fn as_any(&self) -> &dyn Any {
2044 self
2045 }
2046
2047 fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
2050 other
2051 .as_any()
2052 .downcast_ref::<WidgetStatePropertyAll<T>>()
2053 .is_some_and(|other| other.value == self.value)
2054 }
2055}
2056
2057impl<T: Debug> Debug for WidgetStatePropertyAll<T> {
2058 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2059 write!(f, "WidgetStatePropertyAll({:?})", self.value)
2060 }
2061}
2062
2063#[derive(Debug)]
2105pub struct WidgetStatesController {
2106 change_notifier: ChangeNotifierData,
2107 value: WidgetStates,
2108}
2109
2110impl WidgetStatesController {
2111 pub fn new(app: &mut App, value: Option<WidgetStates>) -> Ref<WidgetStatesController> {
2113 app.create(WidgetStatesController {
2114 change_notifier: ChangeNotifierData::new(),
2115 value: value.unwrap_or_default(),
2116 })
2117 }
2118
2119 pub fn value(&self) -> &WidgetStates {
2121 &self.value
2122 }
2123
2124 pub fn set_value(self: Handle<Self>, app: &mut App, new_value: WidgetStates) {
2127 if app.get(self).value == new_value {
2128 return;
2129 }
2130 app.get_mut(self).value = new_value;
2131 self.notify_listeners(app);
2132 }
2133
2134 pub fn dispose(self: Handle<Self>, app: &mut App) {
2136 ChangeNotifierData::dispose(app, self);
2137 }
2138
2139 pub fn to_string(self: Handle<Self>, app: &App) -> String {
2142 format!(
2143 "{}({})",
2144 describe_identity("WidgetStatesController", self.id().identity_hash()),
2145 widget_states(app.get(self).value())
2146 )
2147 }
2148
2149 pub fn update(self: Handle<Self>, app: &mut App, state: WidgetState, add: bool) {
2152 let value = &mut app.get_mut(self).value;
2153 let value_changed = if add {
2154 value.insert(state)
2155 } else {
2156 value.remove(&state)
2157 };
2158 if value_changed {
2159 self.notify_listeners(app);
2160 }
2161 }
2162}
2163
2164impl ChangeNotifier for WidgetStatesController {
2165 fn change_notifier_data(&self) -> &ChangeNotifierData {
2166 &self.change_notifier
2167 }
2168
2169 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
2170 &mut self.change_notifier
2171 }
2172}
2173
2174#[cfg(test)]
2175mod tests {
2176 use std::cell::Cell;
2177 use waft_foundation::AppCell;
2178
2179 use waft_foundation::{Listenable, Listener};
2180 use waft_painting::TextStyle;
2181
2182 use super::*;
2183
2184 const WHITE: Color = Color::new(0xFFFFFFFF);
2185 const BLACK: Color = Color::new(0xFF000000);
2186 const RED: Color = Color::new(0xFFFF0000);
2187
2188 fn states(states: impl IntoIterator<Item = WidgetState>) -> WidgetStates {
2189 states.into_iter().collect()
2190 }
2191
2192 fn cursor(cursor: MouseCursorRef) -> MouseCursorRef {
2193 cursor
2194 }
2195
2196 #[test]
2198 fn resolve_with_resolves_through_the_callback() {
2199 let value = <dyn WidgetStateProperty<WidgetState>>::resolve_with(|states| {
2200 states.iter().next().copied().expect("one state")
2201 });
2202 for state in [
2203 WidgetState::Hovered,
2204 WidgetState::Focused,
2205 WidgetState::Pressed,
2206 WidgetState::Dragged,
2207 WidgetState::Selected,
2208 WidgetState::Disabled,
2209 WidgetState::Error,
2210 ] {
2211 assert_eq!(value.resolve(&states([state])), state);
2212 }
2213 }
2214
2215 #[test]
2217 fn a_map_resolves_to_the_first_satisfied_key_through_the_combinators() {
2218 let active = WidgetState::Hovered | WidgetState::Focused | WidgetState::Pressed;
2219 let value = <dyn WidgetStateProperty<Option<&str>>>::from_map(vec![
2220 (active.clone() & WidgetState::Error, Some("active error")),
2221 (
2222 WidgetState::Disabled | WidgetState::Error,
2223 Some("kinda sus"),
2224 ),
2225 (
2226 !(WidgetState::Dragged | WidgetState::Selected) & !active.clone(),
2227 Some("this is boring"),
2228 ),
2229 (active, Some("active")),
2230 (WidgetState::any(), None),
2231 ]);
2232 assert_eq!(
2233 value.resolve(&states([WidgetState::Focused, WidgetState::Error])),
2234 Some("active error")
2235 );
2236 assert_eq!(
2237 value.resolve(&states([WidgetState::ScrolledUnder])),
2238 Some("this is boring")
2239 );
2240 assert_eq!(
2241 value.resolve(&states([WidgetState::Disabled])),
2242 Some("kinda sus")
2243 );
2244 assert_eq!(
2245 value.resolve(&states([WidgetState::Hovered])),
2246 Some("active")
2247 );
2248 assert_eq!(value.resolve(&states([WidgetState::Dragged])), None);
2249 }
2250
2251 #[test]
2252 fn any_is_satisfied_by_every_set_and_a_constraint_prints_as_dart_does() {
2253 assert!(WidgetState::any().is_satisfied_by(&WidgetStates::new()));
2254 assert!(WidgetState::any().is_satisfied_by(&states([WidgetState::Disabled])));
2255 assert_eq!(WidgetState::any(), WidgetState::any());
2256 assert_eq!(format!("{:?}", WidgetState::any()), "WidgetState.any");
2257 assert_eq!(
2258 format!("{:?}", !(WidgetState::Hovered & WidgetState::Focused)),
2259 "~(Hovered & Focused)"
2260 );
2261 assert_eq!(
2262 WidgetState::Hovered | WidgetState::Focused,
2263 WidgetState::Hovered | WidgetState::Focused
2264 );
2265 assert_ne!(
2266 WidgetState::Hovered | WidgetState::Focused,
2267 WidgetState::Focused | WidgetState::Hovered
2268 );
2269 assert_ne!(
2270 WidgetState::Hovered | WidgetState::Focused,
2271 WidgetState::Hovered & WidgetState::Focused
2272 );
2273 }
2274
2275 #[test]
2276 #[should_panic(expected = "None of the provided map keys matched this set")]
2277 fn a_map_with_no_satisfied_key_panics_with_darts_message() {
2278 let value = WidgetStateMapper::new(vec![(WidgetState::Hovered.into(), 1)]);
2279 value.resolve(&states([WidgetState::Focused]));
2280 }
2281
2282 #[test]
2284 fn all_resolves_to_its_value_for_every_state() {
2285 let value = <dyn WidgetStateProperty<i32>>::all(123);
2286 let constant = WidgetStatePropertyAll::new(123);
2287 assert_eq!(constant.resolve(&WidgetStates::new()), 123);
2288 for state in [
2289 WidgetState::Hovered,
2290 WidgetState::Focused,
2291 WidgetState::Pressed,
2292 WidgetState::Dragged,
2293 WidgetState::Selected,
2294 WidgetState::Disabled,
2295 WidgetState::Error,
2296 ] {
2297 assert_eq!(value.resolve(&states([state])), 123);
2298 assert_eq!(constant.resolve(&states([state])), 123);
2299 }
2300 assert_eq!(
2301 format!("{:?}", WidgetStatePropertyAll::new(Some(WHITE))),
2302 format!("WidgetStatePropertyAll({:?})", Some(WHITE))
2303 );
2304 assert_eq!(
2305 WidgetStatePropertyAll::new(1),
2306 WidgetStatePropertyAll::new(1)
2307 );
2308 assert_ne!(
2309 WidgetStatePropertyAll::new(1),
2310 WidgetStatePropertyAll::new(2)
2311 );
2312 }
2313
2314 #[test]
2316 fn lerp_interpolates_the_resolved_values() {
2317 let enabled = WidgetStates::new();
2318 let text_style_1: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
2319 TextStyle::new().font_size(14.0),
2320 ));
2321 let text_style_2: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
2322 TextStyle::new().font_size(20.0),
2323 ));
2324 let lerp = |t: f64| {
2325 <dyn WidgetStateProperty<TextStyle>>::lerp(
2326 Some(Rc::clone(&text_style_1)),
2327 Some(Rc::clone(&text_style_2)),
2328 t,
2329 |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
2330 )
2331 .expect("one side")
2332 .resolve(&enabled)
2333 .expect("both sides")
2334 .font_size
2335 };
2336 assert_eq!(lerp(0.0), Some(14.0));
2337 assert_eq!(lerp(0.5), Some(17.0));
2338 assert_eq!(lerp(1.0), Some(20.0));
2339 assert!(
2340 <dyn WidgetStateProperty<TextStyle>>::lerp(None, None, 0.5, |_, _, _| None).is_none()
2341 );
2342 }
2343
2344 #[test]
2345 fn lerp_optional_interpolates_nullable_values_and_hands_a_none_side_on() {
2346 let enabled = WidgetStates::new();
2347 let some: WidgetStatePropertyRef<Option<f64>> =
2348 Rc::new(WidgetStatePropertyAll::new(Some(10.0)));
2349 let none: WidgetStatePropertyRef<Option<f64>> = Rc::new(WidgetStatePropertyAll::new(None));
2350 let lerp = |a: &WidgetStatePropertyRef<Option<f64>>,
2351 b: Option<&WidgetStatePropertyRef<Option<f64>>>,
2352 t: f64| {
2353 <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(
2354 Some(Rc::clone(a)),
2355 b.cloned(),
2356 t,
2357 |a, b, t| match (a, b) {
2358 (Some(a), Some(b)) => Some(a + (b - a) * t),
2359 (Some(a), None) => Some(a * (1.0 - t)),
2360 (None, Some(b)) => Some(b * t),
2361 (None, None) => None,
2362 },
2363 )
2364 .expect("one side")
2365 .resolve(&enabled)
2366 };
2367 let twenty: WidgetStatePropertyRef<Option<f64>> =
2368 Rc::new(WidgetStatePropertyAll::new(Some(20.0)));
2369 assert_eq!(lerp(&some, Some(&twenty), 0.5), Some(15.0));
2370 assert_eq!(lerp(&some, Some(&none), 0.5), Some(5.0));
2371 assert_eq!(lerp(&some, None, 0.5), Some(5.0));
2372 assert_eq!(lerp(&none, Some(&none), 0.5), None);
2373 assert!(
2374 <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(None, None, 0.5, |_, _, _| None)
2375 .is_none()
2376 );
2377 }
2378
2379 #[test]
2380 fn a_widget_state_color_resolves_per_state_and_travels_through_a_text_style() {
2381 let color = WidgetStateColor::resolve_with(|states| {
2382 if states.contains(&WidgetState::Pressed) {
2383 return RED;
2384 }
2385 BLACK
2386 });
2387 assert_eq!(color.resolve(&states([WidgetState::Pressed])), RED);
2388 assert_eq!(color.resolve(&WidgetStates::new()), BLACK);
2389
2390 let style = TextStyle::new().color(color);
2391 let color = style.color.clone().expect("set above");
2392 assert_eq!(color.color(), BLACK, "the default-state value is the Color");
2393 let property = color
2394 .extension::<WidgetStateColor>()
2395 .expect("the extension survives the style");
2396 assert_eq!(property.resolve(&states([WidgetState::Pressed])), RED);
2397
2398 assert_eq!(
2399 <dyn WidgetStateProperty<Color>>::resolve_as(&color, &states([WidgetState::Pressed])),
2400 AnyColor::new(RED)
2401 );
2402 assert_eq!(
2403 <dyn WidgetStateProperty<Color>>::resolve_as(
2404 &Some(color),
2405 &states([WidgetState::Pressed])
2406 ),
2407 Some(AnyColor::new(RED))
2408 );
2409 }
2410
2411 #[test]
2412 fn resolve_as_returns_a_plain_color_unchanged() {
2413 let plain = AnyColor::new(RED);
2414 assert_eq!(
2415 <dyn WidgetStateProperty<Color>>::resolve_as(&plain, &states([WidgetState::Pressed])),
2416 plain
2417 );
2418 assert_eq!(
2419 <dyn WidgetStateProperty<Color>>::resolve_as(
2420 &None::<AnyColor>,
2421 &states([WidgetState::Pressed])
2422 ),
2423 None
2424 );
2425 }
2426
2427 #[test]
2428 fn transparent_resolves_transparent_and_a_from_map_color_resolves_its_first_key() {
2429 let transparent = WidgetStateColor::transparent().into_any();
2430 assert_eq!(transparent.color(), Color::new(0x00000000));
2431 assert_eq!(
2432 transparent
2433 .extension::<WidgetStateColor>()
2434 .expect("a WidgetStateColor")
2435 .resolve(&states([WidgetState::Pressed])),
2436 Color::new(0x00000000)
2437 );
2438 assert_eq!(transparent, WidgetStateColor::transparent().into_any());
2439
2440 let color = WidgetStateColor::from_map(vec![
2441 (WidgetState::Focused | WidgetState::Hovered, WHITE),
2442 (WidgetState::any(), BLACK),
2443 ]);
2444 assert_eq!(color.resolve(&states([WidgetState::Hovered])), WHITE);
2445 assert_eq!(color.resolve(&states([WidgetState::Pressed])), BLACK);
2446 assert_eq!(color.into_any().color(), BLACK);
2447 }
2448
2449 #[test]
2451 fn from_map_constructors_perform_accurate_equality_checks() {
2452 let color_1 = WidgetStateColor::from_map(vec![
2453 (WidgetState::Focused | WidgetState::Hovered, WHITE),
2454 (WidgetState::any(), BLACK),
2455 ])
2456 .into_any();
2457 let color_2 = WidgetStateColor::from_map(vec![
2458 (WidgetState::Focused | WidgetState::Hovered, WHITE),
2459 (WidgetState::any(), BLACK),
2460 ])
2461 .into_any();
2462 let color_3 = WidgetStateColor::from_map(vec![
2463 (WidgetState::Focused | WidgetState::Hovered, BLACK),
2464 (WidgetState::any(), WHITE),
2465 ])
2466 .into_any();
2467 assert!(color_1 == color_2);
2468 assert!(color_1 != color_3);
2469
2470 let cursor_1 = cursor(
2471 WidgetStateMouseCursor::from_map(vec![
2472 (
2473 WidgetState::Focused | WidgetState::Hovered,
2474 <dyn MouseCursor>::defer(),
2475 ),
2476 (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
2477 ])
2478 .into(),
2479 );
2480 let cursor_2 = cursor(
2481 WidgetStateMouseCursor::from_map(vec![
2482 (
2483 WidgetState::Focused | WidgetState::Hovered,
2484 <dyn MouseCursor>::defer(),
2485 ),
2486 (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
2487 ])
2488 .into(),
2489 );
2490 let cursor_3 = cursor(
2491 WidgetStateMouseCursor::from_map(vec![
2492 (
2493 WidgetState::Focused | WidgetState::Hovered,
2494 <dyn MouseCursor>::uncontrolled(),
2495 ),
2496 (WidgetState::any(), <dyn MouseCursor>::defer()),
2497 ])
2498 .into(),
2499 );
2500 assert!(*cursor_1 == *cursor_2);
2501 assert!(*cursor_1 != *cursor_3);
2502
2503 let white_border = BorderSide {
2504 color: WHITE,
2505 ..BorderSide::default()
2506 };
2507 let black_border = BorderSide::default();
2508 let side = |first: BorderSide, rest: BorderSide| {
2509 WidgetStateBorderSide::from_map(vec![
2510 (WidgetState::Focused | WidgetState::Hovered, Some(first)),
2511 (WidgetState::any(), Some(rest)),
2512 ])
2513 .into_any()
2514 };
2515 assert!(side(white_border, black_border) == side(white_border, black_border));
2516 assert!(side(white_border, black_border) != side(black_border, white_border));
2517
2518 let rrect = |side: BorderSide| -> OutlinedBorderRef {
2519 OutlinedBorderRef::new(RoundedRectangleBorder {
2520 side,
2521 ..RoundedRectangleBorder::default()
2522 })
2523 };
2524 let border = |first: BorderSide, rest: BorderSide| {
2525 WidgetStateOutlinedBorder::from_map(vec![
2526 (
2527 WidgetState::Focused | WidgetState::Hovered,
2528 Some(rrect(first)),
2529 ),
2530 (WidgetState::any(), Some(rrect(rest))),
2531 ])
2532 };
2533 assert!(border(white_border, black_border).eq_shape(&border(white_border, black_border)));
2534 assert!(!border(white_border, black_border).eq_shape(&border(black_border, white_border)));
2535
2536 let text = |first: Color, rest: Color| {
2537 WidgetStateTextStyle::from_map(vec![
2538 (
2539 WidgetState::Focused | WidgetState::Hovered,
2540 TextStyle::new().color(first),
2541 ),
2542 (WidgetState::any(), TextStyle::new().color(rest)),
2543 ])
2544 .into_any()
2545 };
2546 assert!(text(WHITE, BLACK) == text(WHITE, BLACK));
2547 assert!(text(WHITE, BLACK) != text(BLACK, WHITE));
2548 }
2549
2550 #[test]
2553 fn erased_properties_compare_as_darts_equality_overrides_do() {
2554 let all = |value: f64| <dyn WidgetStateProperty<f64>>::all(value);
2555 assert!(*all(1.0) == *all(1.0));
2556 assert!(*all(1.0) != *all(2.0));
2557
2558 let map = |first: Color, rest: Color| {
2559 <dyn WidgetStateProperty<Color>>::from_map(vec![
2560 (WidgetState::Disabled.into(), first),
2561 (WidgetState::any(), rest),
2562 ])
2563 };
2564 assert!(*map(WHITE, BLACK) == *map(WHITE, BLACK));
2565 assert!(*map(WHITE, BLACK) != *map(BLACK, WHITE));
2566 let mapped_color: WidgetStatePropertyRef<Color> =
2567 Rc::new(WidgetStateColor::from_map(vec![
2568 (WidgetState::Disabled.into(), WHITE),
2569 (WidgetState::any(), BLACK),
2570 ]));
2571 assert!(*map(WHITE, BLACK) == *mapped_color);
2572 assert!(*mapped_color == *map(WHITE, BLACK));
2573 assert!(*map(WHITE, BLACK) != *<dyn WidgetStateProperty<Color>>::all(WHITE));
2574
2575 let resolved = <dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0);
2576 assert!(*resolved == *Rc::clone(&resolved));
2577 assert!(*resolved != *<dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0));
2578
2579 let color = |value: Color| -> WidgetStatePropertyRef<Color> {
2580 Rc::new(WidgetStateColor::resolve_with(move |_| value))
2581 };
2582 assert!(*color(WHITE) == *color(WHITE));
2583 assert!(*color(WHITE) != *color(BLACK));
2584
2585 use crate::framework::{IntoWidget, WidgetRef};
2587 let icon: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
2588 let widget = |widget: &WidgetRef| {
2589 <dyn WidgetStateProperty<Option<WidgetRef>>>::all(Some(Rc::clone(widget)))
2590 };
2591 assert!(*widget(&icon) == *widget(&icon));
2592 let other: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
2593 assert!(*widget(&icon) != *widget(&other));
2594 }
2595
2596 #[test]
2598 fn border_side_lerp_interpolates_the_resolved_sides() {
2599 let side_1: WidgetStatePropertyRef<Option<BorderSide>> =
2600 Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
2601 color: Color::new(0xffff0000),
2602 width: 4.0,
2603 ..BorderSide::default()
2604 })));
2605 let side_2: WidgetStatePropertyRef<Option<BorderSide>> =
2606 Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
2607 color: Color::new(0xff0000ff),
2608 width: 12.0,
2609 ..BorderSide::default()
2610 })));
2611 let lerp = |t: f64| {
2612 WidgetStateBorderSide::lerp(Some(Rc::clone(&side_1)), Some(Rc::clone(&side_2)), t)
2613 .expect("two sides")
2614 .resolve(&WidgetStates::new())
2615 .expect("a side")
2616 };
2617 assert_eq!(lerp(0.0).color, Color::new(0xffff0000));
2618 assert_eq!(lerp(0.0).width, 4.0);
2619 #[allow(deprecated)]
2621 let (red, blue) = (lerp(0.5).color.red(), lerp(0.5).color.blue());
2622 assert!(
2623 (red - 0x7f).abs() <= 1 && (blue - 0x7f).abs() <= 1,
2624 "{:?}",
2625 lerp(0.5).color
2626 );
2627 assert_eq!(lerp(0.5).width, 8.0);
2628 assert_eq!(lerp(1.0).color, Color::new(0xff0000ff));
2629 assert_eq!(lerp(1.0).width, 12.0);
2630 assert!(WidgetStateBorderSide::lerp(None, None, 0.5).is_none());
2631 }
2632
2633 #[test]
2636 fn the_widget_state_values_are_their_default_and_resolve_through_resolve_as() {
2637 let pressed = states([WidgetState::Pressed]);
2638 let red_side = BorderSide {
2639 color: RED,
2640 ..BorderSide::default()
2641 };
2642 let side: Option<AnyBorderSide> = Some(
2643 WidgetStateBorderSide::resolve_with(move |states| {
2644 states.contains(&WidgetState::Pressed).then_some(red_side)
2645 })
2646 .into(),
2647 );
2648 assert_eq!(
2649 *side.as_ref().expect("a side").value(),
2650 BorderSide::default()
2651 );
2652 let resolved = <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &pressed);
2653 assert_eq!(resolved, Some(AnyBorderSide::new(red_side)));
2654 let resolved =
2655 <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &WidgetStates::new());
2656 assert_eq!(resolved, None);
2657
2658 let style: AnyTextStyle = WidgetStateTextStyle::resolve_with(|states| {
2659 TextStyle::new().font_size(if states.contains(&WidgetState::Pressed) {
2660 20.0
2661 } else {
2662 10.0
2663 })
2664 })
2665 .into();
2666 assert_eq!(*style.value(), TextStyle::new());
2667 let resolved = <dyn WidgetStateProperty<TextStyle>>::resolve_as(&style, &pressed);
2668 assert_eq!(resolved.font_size, Some(20.0));
2669
2670 let border: Option<OutlinedBorderRef> = Some(OutlinedBorderRef::new(
2671 WidgetStateOutlinedBorder::resolve_with(|states| {
2672 states.contains(&WidgetState::Pressed).then(|| {
2673 OutlinedBorderRef::new(RoundedRectangleBorder {
2674 side: BorderSide {
2675 width: 3.0,
2676 ..BorderSide::default()
2677 },
2678 ..RoundedRectangleBorder::default()
2679 })
2680 })
2681 }),
2682 ));
2683 assert_eq!(
2684 border.as_ref().expect("a border").side(),
2685 RoundedRectangleBorder::default().side,
2686 "as a plain border it is the default rounded rectangle"
2687 );
2688 let resolved =
2689 <dyn WidgetStateProperty<Option<OutlinedBorderRef>>>::resolve_as(&border, &pressed)
2690 .expect("a border");
2691 assert_eq!(resolved.side().width, 3.0);
2692 }
2693
2694 #[test]
2695 fn clickable_resolves_to_basic_when_disabled_and_is_a_mouse_cursor() {
2696 let clickable = WidgetStateMouseCursor::clickable();
2697 assert!(
2698 *clickable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::CLICK.into())
2699 );
2700 assert!(
2701 *clickable.resolve(&states([WidgetState::Disabled]))
2702 == *cursor(SystemMouseCursors::BASIC.into())
2703 );
2704 assert_eq!(
2705 clickable.debug_description(),
2706 "WidgetStateMouseCursor(clickable)"
2707 );
2708
2709 let textable = WidgetStateMouseCursor::textable();
2710 assert!(
2711 *textable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::TEXT.into())
2712 );
2713
2714 let as_property =
2717 |cursor: WidgetStateMouseCursor| -> WidgetStatePropertyRef<MouseCursorRef> {
2718 Rc::new(cursor)
2719 };
2720 assert!(
2721 *as_property(WidgetStateMouseCursor::clickable())
2722 == *as_property(WidgetStateMouseCursor::clickable())
2723 );
2724 assert!(
2725 *as_property(WidgetStateMouseCursor::clickable())
2726 != *as_property(WidgetStateMouseCursor::textable())
2727 );
2728 let as_cursor = |cursor: WidgetStateMouseCursor| -> MouseCursorRef { Rc::new(cursor) };
2729 assert!(
2730 *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
2731 == *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
2732 );
2733 let resolve_click =
2734 |_: &WidgetStates| -> MouseCursorRef { SystemMouseCursors::CLICK.into() };
2735 assert!(
2736 *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
2737 != *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
2738 );
2739 assert!(
2740 *textable.resolve(&states([WidgetState::Disabled]))
2741 == *cursor(SystemMouseCursors::BASIC.into())
2742 );
2743
2744 let session = clickable.create_session(1);
2746 assert!(*session.cursor() == *cursor(SystemMouseCursors::CLICK.into()));
2747 assert_eq!(session.device(), 1);
2748
2749 let erased: MouseCursorRef = clickable.into();
2750 assert!(erased.as_any().is::<WidgetStateMouseCursor>());
2751 assert!(
2752 *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
2753 &erased,
2754 &states([WidgetState::Disabled])
2755 ) == *cursor(SystemMouseCursors::BASIC.into())
2756 );
2757 assert!(
2758 *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
2759 &Some(Rc::clone(&erased)),
2760 &states([WidgetState::Disabled])
2761 )
2762 .expect("some")
2763 == *cursor(SystemMouseCursors::BASIC.into())
2764 );
2765 let plain = cursor(SystemMouseCursors::GRAB.into());
2766 assert!(Rc::ptr_eq(
2767 &<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&plain, &WidgetStates::new()),
2768 &plain
2769 ));
2770 }
2771
2772 #[test]
2774 fn a_resolve_with_cursor_can_forbid_when_disabled() {
2775 let cursor = WidgetStateMouseCursor::resolve_with(
2776 |states| {
2777 if states.contains(&WidgetState::Disabled) {
2778 return SystemMouseCursors::FORBIDDEN.into();
2779 }
2780 SystemMouseCursors::CLICK.into()
2781 },
2782 None,
2783 );
2784 assert!(
2785 *cursor.resolve(&states([WidgetState::Disabled]))
2786 == *MouseCursorRef::from(SystemMouseCursors::FORBIDDEN)
2787 );
2788 assert!(
2789 *cursor.resolve(&WidgetStates::new())
2790 == *MouseCursorRef::from(SystemMouseCursors::CLICK)
2791 );
2792 assert_eq!(cursor.debug_description(), "WidgetStateMouseCursor()");
2793 }
2794
2795 #[test]
2797 fn controller_starts_with_the_given_states() {
2798 let cell = AppCell::new();
2799 let mut app = cell.borrow_mut();
2800 let empty = WidgetStatesController::new(&mut app, None);
2801 assert_eq!(*app.get(&empty).value(), WidgetStates::new());
2802 let selected = WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
2803 assert_eq!(*app.get(&selected).value(), states([WidgetState::Selected]));
2804 }
2805
2806 #[test]
2808 fn controller_update_notifies_only_on_change() {
2809 let cell = AppCell::new();
2810 let mut app = cell.borrow_mut();
2811 let count = Rc::new(Cell::new(0));
2812 let value_changed = Listener::new({
2813 let count = Rc::clone(&count);
2814 move |_app| count.set(count.get() + 1)
2815 });
2816
2817 let controller = WidgetStatesController::new(&mut app, None);
2818 controller.add_listener(&mut app, value_changed.clone());
2819
2820 let expect = |app: &App, expected: &[WidgetState], expected_count: i32| {
2821 assert_eq!(
2822 *app.get(&controller).value(),
2823 states(expected.iter().copied())
2824 );
2825 assert_eq!(count.get(), expected_count);
2826 };
2827
2828 controller.update(&mut app, WidgetState::Selected, true);
2829 expect(&app, &[WidgetState::Selected], 1);
2830 controller.update(&mut app, WidgetState::Selected, true);
2831 expect(&app, &[WidgetState::Selected], 1);
2832
2833 controller.update(&mut app, WidgetState::Hovered, false);
2834 expect(&app, &[WidgetState::Selected], 1);
2835 controller.update(&mut app, WidgetState::Selected, false);
2836 expect(&app, &[], 2);
2837
2838 controller.update(&mut app, WidgetState::Hovered, true);
2839 expect(&app, &[WidgetState::Hovered], 3);
2840 controller.update(&mut app, WidgetState::Hovered, true);
2841 expect(&app, &[WidgetState::Hovered], 3);
2842 controller.update(&mut app, WidgetState::Pressed, true);
2843 expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 4);
2844 controller.update(&mut app, WidgetState::Selected, true);
2845 expect(
2846 &app,
2847 &[
2848 WidgetState::Hovered,
2849 WidgetState::Pressed,
2850 WidgetState::Selected,
2851 ],
2852 5,
2853 );
2854 controller.update(&mut app, WidgetState::Selected, false);
2855 expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
2856 controller.update(&mut app, WidgetState::Selected, false);
2857 expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
2858 controller.update(&mut app, WidgetState::Pressed, false);
2859 expect(&app, &[WidgetState::Hovered], 7);
2860 controller.update(&mut app, WidgetState::Hovered, false);
2861 expect(&app, &[], 8);
2862
2863 controller.remove_listener(&mut app, &value_changed);
2864 controller.update(&mut app, WidgetState::Selected, true);
2865 expect(&app, &[WidgetState::Selected], 8);
2866 }
2867
2868 #[test]
2870 fn controller_with_an_initial_value_notifies_only_on_change() {
2871 let cell = AppCell::new();
2872 let mut app = cell.borrow_mut();
2873 let count = Rc::new(Cell::new(0));
2874 let controller =
2875 WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
2876 controller.add_listener(&mut app, {
2877 let count = Rc::clone(&count);
2878 Listener::new(move |_app| count.set(count.get() + 1))
2879 });
2880
2881 controller.update(&mut app, WidgetState::Selected, true);
2882 assert_eq!(
2883 *app.get(&controller).value(),
2884 states([WidgetState::Selected])
2885 );
2886 assert_eq!(count.get(), 0);
2887
2888 controller.update(&mut app, WidgetState::Selected, false);
2889 assert_eq!(*app.get(&controller).value(), WidgetStates::new());
2890 assert_eq!(count.get(), 1);
2891
2892 controller.set_value(&mut app, states([WidgetState::Hovered]));
2893 assert_eq!(count.get(), 2);
2894 controller.set_value(&mut app, states([WidgetState::Hovered]));
2895 assert_eq!(count.get(), 2);
2896
2897 controller.dispose(&mut app);
2898 assert!(!app.get(&controller).change_notifier_data().has_listeners());
2899 }
2900}