1use std::cell::Cell;
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_animation::{
15 Animatable, Animation, AnimationController, AnimationStatus, ConstantTween, Cubic, Curve,
16 CurveTween, CurvedAnimation, Curves, Tween, TweenSequence, TweenSequenceItem,
17};
18use waft_cupertino::{CupertinoColors, CupertinoDynamicColor};
19use waft_embedder::{
20 Brightness, Canvas, ClipOp, Color, Offset, Paint, PaintStyle, RRect, Radius, Rect, Size,
21 Stroke, TargetPlatform, TextDirection, lerp_double, rrect_radii_elliptical,
22};
23use waft_foundation::{
24 App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, FlagProperty, Handle,
25 K_IS_WEB, ObjectFlagProperty, OptionRetained, Ref, ValueChanged,
26};
27use waft_gestures::{DragEndDetails, DragStartBehavior, DragStartDetails, DragUpdateDetails};
28use waft_painting::{
29 AnyColor, BlurStyle, BorderSide, BoxPainter, BoxShadow, Decoration, EdgeInsetsGeometry,
30 FontVariation, HSLColor, ImageConfiguration, PaintingBinding, ShapeDecoration, StadiumBorder,
31 TextPainter, TextSpan, TextStyle, draw_rrect,
32};
33use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
34use waft_services::{MouseCursorRef, SystemMouseCursors};
35use waft_widgets::{
36 BuildContext, Directionality, FocusNodeRef, GestureDetector, Icon, IconTheme, IconThemeData,
37 IntoWidget, KeyRef, Opacity, Semantics, State, StateData, StatefulWidget, StatelessWidget,
38 TickerProviderStateMixin, TickerProviderStateMixinData, ToggleablePainter,
39 ToggleablePainterData, ToggleablePainterRef, ToggleableStateMixin, ToggleableStateMixinData,
40 WidgetRef, WidgetState, WidgetStateMouseCursor, WidgetStateProperty, WidgetStatePropertyRef,
41 WidgetStates, create_local_image_configuration,
42};
43
44use crate::color_scheme::ColorScheme;
45use crate::colors::Colors;
46use crate::constants::{
47 K_MIN_INTERACTIVE_DIMENSION, K_RADIAL_REACTION_ALPHA, K_RADIAL_REACTION_DURATION,
48 K_RADIAL_REACTION_RADIUS,
49};
50use crate::debug::debug_check_has_material;
51use crate::generated::switch_defaults_m3::{SwitchConfigM3, SwitchDefaultsM3};
52use crate::shadows::k_elevation_to_shadow;
53use crate::switch_theme::{SwitchTheme, SwitchThemeData, SwitchThemeDataGetters};
54use crate::theme::Theme;
55use crate::theme_data::{Adaptation, MaterialTapTargetSize, ThemeData};
56use crate::theme_data_getters::DefaultsContext;
57
58#[allow(deprecated)]
61fn with_opacity(color: Color, opacity: f64) -> Color {
62 color.with_opacity(opacity)
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
66enum SwitchType {
67 Material,
68 Adaptive,
69}
70
71#[derive(Clone)]
104pub struct Switch {
105 pub key: Option<KeyRef>,
106 pub value: bool,
108 pub on_changed: Option<ValueChanged<bool>>,
119 #[deprecated(
126 note = "Use activeThumbColor or activeTrackColor instead. This feature was deprecated after v3.31.0-2.0.pre."
127 )]
128 pub active_color: Option<Color>,
129 pub active_thumb_color: Option<Color>,
136 pub active_track_color: Option<Color>,
143 pub inactive_thumb_color: Option<Color>,
150 pub inactive_track_color: Option<Color>,
157 pub thumb_color: Option<WidgetStatePropertyRef<Option<Color>>>,
177 pub track_color: Option<WidgetStatePropertyRef<Option<Color>>>,
197 pub track_outline_color: Option<WidgetStatePropertyRef<Option<Color>>>,
209 pub track_outline_width: Option<WidgetStatePropertyRef<Option<f64>>>,
219 pub thumb_icon: Option<WidgetStatePropertyRef<Option<Rc<Icon>>>>,
230 pub material_tap_target_size: Option<MaterialTapTargetSize>,
239 switch_type: SwitchType,
240 pub apply_cupertino_theme: Option<bool>,
247 pub drag_start_behavior: DragStartBehavior,
260 pub mouse_cursor: Option<MouseCursorRef>,
273 pub focus_color: Option<Color>,
281 pub hover_color: Option<Color>,
289 pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
305 pub splash_radius: Option<f64>,
310 pub focus_node: Option<FocusNodeRef>,
316 pub on_focus_change: Option<ValueChanged<bool>>,
320 pub autofocus: bool,
325 pub padding: Option<EdgeInsetsGeometry>,
330}
331
332impl Switch {
333 pub fn new(value: bool, on_changed: Option<ValueChanged<bool>>) -> Switch {
350 Switch::with_type(value, on_changed, SwitchType::Material)
351 }
352
353 pub fn adaptive(value: bool, on_changed: Option<ValueChanged<bool>>) -> Switch {
367 Switch::with_type(value, on_changed, SwitchType::Adaptive)
368 }
369
370 #[allow(deprecated)]
371 fn with_type(
372 value: bool,
373 on_changed: Option<ValueChanged<bool>>,
374 switch_type: SwitchType,
375 ) -> Switch {
376 Switch {
377 key: None,
378 value,
379 on_changed,
380 active_color: None,
381 active_thumb_color: None,
382 active_track_color: None,
383 inactive_thumb_color: None,
384 inactive_track_color: None,
385 thumb_color: None,
386 track_color: None,
387 track_outline_color: None,
388 track_outline_width: None,
389 thumb_icon: None,
390 material_tap_target_size: None,
391 switch_type,
392 apply_cupertino_theme: None,
393 drag_start_behavior: DragStartBehavior::Start,
394 mouse_cursor: None,
395 focus_color: None,
396 hover_color: None,
397 overlay_color: None,
398 splash_radius: None,
399 focus_node: None,
400 on_focus_change: None,
401 autofocus: false,
402 padding: None,
403 }
404 }
405
406 pub fn key(mut self, key: KeyRef) -> Switch {
408 self.key = Some(key);
409 self
410 }
411
412 #[deprecated(
414 note = "Use activeThumbColor instead. This feature was deprecated after v3.31.0-2.0.pre."
415 )]
416 #[allow(deprecated)]
417 pub fn active_color(mut self, active_color: Color) -> Switch {
418 self.active_color = Some(active_color);
419 self
420 }
421
422 pub fn active_thumb_color(mut self, active_thumb_color: Color) -> Switch {
424 self.active_thumb_color = Some(active_thumb_color);
425 self
426 }
427
428 pub fn active_track_color(mut self, active_track_color: Color) -> Switch {
430 self.active_track_color = Some(active_track_color);
431 self
432 }
433
434 pub fn inactive_thumb_color(mut self, inactive_thumb_color: Color) -> Switch {
436 self.inactive_thumb_color = Some(inactive_thumb_color);
437 self
438 }
439
440 pub fn inactive_track_color(mut self, inactive_track_color: Color) -> Switch {
442 self.inactive_track_color = Some(inactive_track_color);
443 self
444 }
445
446 pub fn thumb_color(mut self, thumb_color: WidgetStatePropertyRef<Option<Color>>) -> Switch {
448 self.thumb_color = Some(thumb_color);
449 self
450 }
451
452 pub fn track_color(mut self, track_color: WidgetStatePropertyRef<Option<Color>>) -> Switch {
454 self.track_color = Some(track_color);
455 self
456 }
457
458 pub fn track_outline_color(
460 mut self,
461 track_outline_color: WidgetStatePropertyRef<Option<Color>>,
462 ) -> Switch {
463 self.track_outline_color = Some(track_outline_color);
464 self
465 }
466
467 pub fn track_outline_width(
469 mut self,
470 track_outline_width: WidgetStatePropertyRef<Option<f64>>,
471 ) -> Switch {
472 self.track_outline_width = Some(track_outline_width);
473 self
474 }
475
476 pub fn thumb_icon(mut self, thumb_icon: WidgetStatePropertyRef<Option<Rc<Icon>>>) -> Switch {
478 self.thumb_icon = Some(thumb_icon);
479 self
480 }
481
482 pub fn material_tap_target_size(
484 mut self,
485 material_tap_target_size: MaterialTapTargetSize,
486 ) -> Switch {
487 self.material_tap_target_size = Some(material_tap_target_size);
488 self
489 }
490
491 pub fn apply_cupertino_theme(mut self, apply_cupertino_theme: bool) -> Switch {
493 self.apply_cupertino_theme = Some(apply_cupertino_theme);
494 self
495 }
496
497 pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Switch {
499 self.drag_start_behavior = drag_start_behavior;
500 self
501 }
502
503 pub fn mouse_cursor(mut self, mouse_cursor: impl Into<MouseCursorRef>) -> Switch {
505 self.mouse_cursor = Some(mouse_cursor.into());
506 self
507 }
508
509 pub fn focus_color(mut self, focus_color: Color) -> Switch {
511 self.focus_color = Some(focus_color);
512 self
513 }
514
515 pub fn hover_color(mut self, hover_color: Color) -> Switch {
517 self.hover_color = Some(hover_color);
518 self
519 }
520
521 pub fn overlay_color(mut self, overlay_color: WidgetStatePropertyRef<Option<Color>>) -> Switch {
523 self.overlay_color = Some(overlay_color);
524 self
525 }
526
527 pub fn splash_radius(mut self, splash_radius: f64) -> Switch {
529 self.splash_radius = Some(splash_radius);
530 self
531 }
532
533 pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Switch {
535 self.focus_node = Some(focus_node);
536 self
537 }
538
539 pub fn on_focus_change(mut self, on_focus_change: impl Fn(&mut App, bool) + 'static) -> Switch {
541 self.on_focus_change = Some(Rc::new(on_focus_change));
542 self
543 }
544
545 pub fn autofocus(mut self, autofocus: bool) -> Switch {
547 self.autofocus = autofocus;
548 self
549 }
550
551 pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Switch {
553 self.padding = Some(padding.into());
554 self
555 }
556
557 pub fn effective_apply_cupertino_theme(&self) -> Option<bool> {
561 match self.switch_type {
562 SwitchType::Material => Some(false),
563 SwitchType::Adaptive => self.apply_cupertino_theme,
564 }
565 }
566
567 fn get_switch_size(&self, app: &mut App, context: BuildContext) -> Size {
569 let theme = Theme::of(app, context);
570 let mut switch_theme = SwitchTheme::of(app, context);
571 let defaults = switch_defaults(app, context, theme.use_material3);
572 if self.switch_type == SwitchType::Adaptive {
573 let switch_adaptation = theme
574 .get_adaptation::<SwitchThemeData>()
575 .unwrap_or(&SwitchThemeAdaptation);
576 switch_theme = switch_adaptation.adapt(&theme, switch_theme);
577 }
578 let switch_config = switch_config(app, context, theme.use_material3);
579
580 let effective_material_tap_target_size = self
581 .material_tap_target_size
582 .or(switch_theme.material_tap_target_size)
583 .unwrap_or(theme.material_tap_target_size);
584 let effective_padding = self
585 .padding
586 .or(switch_theme.padding)
587 .or_else(|| defaults.padding(app))
588 .expect("the defaults give a padding");
589 match effective_material_tap_target_size {
590 MaterialTapTargetSize::Padded => Size::new(
591 switch_config.switch_width() + effective_padding.horizontal(),
592 switch_config.switch_height() + effective_padding.vertical(),
593 ),
594 MaterialTapTargetSize::ShrinkWrap => Size::new(
595 switch_config.switch_width() + effective_padding.horizontal(),
596 switch_config.switch_height_collapsed() + effective_padding.vertical(),
597 ),
598 }
599 }
600}
601
602fn switch_config(
604 app: &mut App,
605 context: BuildContext,
606 use_material3: bool,
607) -> Box<dyn SwitchConfig> {
608 if use_material3 {
609 Box::new(SwitchConfigM3::new(app, context))
610 } else {
611 Box::new(SwitchConfigM2::new())
612 }
613}
614
615fn switch_defaults(
617 app: &mut App,
618 context: BuildContext,
619 use_material3: bool,
620) -> Box<dyn SwitchThemeDataGetters> {
621 if use_material3 {
622 Box::new(SwitchDefaultsM3::new(context))
623 } else {
624 Box::new(SwitchDefaultsM2::new(app, context))
625 }
626}
627
628impl Debug for Switch {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 f.debug_struct("Switch")
631 .field("value", &if self.value { "on" } else { "off" })
632 .field(
633 "on_changed",
634 &if self.on_changed.is_some() {
635 "enabled"
636 } else {
637 "disabled"
638 },
639 )
640 .finish_non_exhaustive()
641 }
642}
643
644impl StatelessWidget for Switch {
645 fn key(&self) -> Option<&KeyRef> {
646 self.key.as_ref()
647 }
648
649 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
650 properties.add(
651 FlagProperty::new("value", Some(self.value))
652 .if_true("on")
653 .if_false("off")
654 .with_show_name(true),
655 );
656 properties.add(
657 ObjectFlagProperty::<String>::new(
658 "onChanged",
659 self.on_changed.as_ref().map(|_| String::new()),
660 )
661 .if_null("disabled"),
662 );
663 }
664
665 #[allow(deprecated)]
666 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
667 let mut effective_active_thumb_color = None;
668 let mut effective_active_track_color = None;
669 match self.switch_type {
670 SwitchType::Material => {
671 effective_active_thumb_color = self.active_color;
672 }
673 SwitchType::Adaptive => match Theme::of(app, context).platform {
674 TargetPlatform::Android
675 | TargetPlatform::Fuchsia
676 | TargetPlatform::Linux
677 | TargetPlatform::Windows => {
678 effective_active_thumb_color = self.active_color;
679 }
680 TargetPlatform::IOS | TargetPlatform::MacOS => {
681 effective_active_track_color = self.active_color;
682 }
683 },
684 }
685 MaterialSwitch {
686 value: self.value,
687 on_changed: self.on_changed.clone(),
688 size: self.get_switch_size(app, context),
689 active_thumb_color: self.active_thumb_color.or(effective_active_thumb_color),
690 active_track_color: self.active_track_color.or(effective_active_track_color),
691 inactive_thumb_color: self.inactive_thumb_color,
692 inactive_track_color: self.inactive_track_color,
693 thumb_color: self.thumb_color.clone(),
694 track_color: self.track_color.clone(),
695 track_outline_color: self.track_outline_color.clone(),
696 track_outline_width: self.track_outline_width.clone(),
697 thumb_icon: self.thumb_icon.clone(),
698 material_tap_target_size: self.material_tap_target_size,
699 drag_start_behavior: self.drag_start_behavior,
700 mouse_cursor: self.mouse_cursor.clone(),
701 focus_color: self.focus_color,
702 hover_color: self.hover_color,
703 overlay_color: self.overlay_color.clone(),
704 splash_radius: self.splash_radius,
705 focus_node: self.focus_node.clone(),
706 on_focus_change: self.on_focus_change.clone(),
707 autofocus: self.autofocus,
708 apply_cupertino_theme: self.effective_apply_cupertino_theme(),
709 switch_type: self.switch_type,
710 }
711 .into_widget()
712 }
713}
714
715#[derive(Clone)]
717struct MaterialSwitch {
718 value: bool,
719 on_changed: Option<ValueChanged<bool>>,
720 active_thumb_color: Option<Color>,
721 active_track_color: Option<Color>,
722 inactive_thumb_color: Option<Color>,
723 inactive_track_color: Option<Color>,
724 thumb_color: Option<WidgetStatePropertyRef<Option<Color>>>,
725 track_color: Option<WidgetStatePropertyRef<Option<Color>>>,
726 track_outline_color: Option<WidgetStatePropertyRef<Option<Color>>>,
727 track_outline_width: Option<WidgetStatePropertyRef<Option<f64>>>,
728 thumb_icon: Option<WidgetStatePropertyRef<Option<Rc<Icon>>>>,
729 #[expect(
730 dead_code,
731 reason = "Dart's field; the size Switch works out from it is what the state reads"
732 )]
733 material_tap_target_size: Option<MaterialTapTargetSize>,
734 drag_start_behavior: DragStartBehavior,
735 mouse_cursor: Option<MouseCursorRef>,
736 focus_color: Option<Color>,
737 hover_color: Option<Color>,
738 overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
739 splash_radius: Option<f64>,
740 focus_node: Option<FocusNodeRef>,
741 on_focus_change: Option<ValueChanged<bool>>,
742 autofocus: bool,
743 size: Size,
744 apply_cupertino_theme: Option<bool>,
745 switch_type: SwitchType,
746}
747
748impl Debug for MaterialSwitch {
749 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750 f.debug_struct("_MaterialSwitch")
751 .field("value", &self.value)
752 .field("size", &self.size)
753 .finish_non_exhaustive()
754 }
755}
756
757impl StatefulWidget for MaterialSwitch {
758 type State = MaterialSwitchState;
759
760 fn create_state(&self) -> MaterialSwitchState {
761 MaterialSwitchState {
762 state: StateData::new(),
763 ticker_provider: TickerProviderStateMixinData::new(),
764 toggleable: ToggleableStateMixinData::new(),
765 painter: None,
766 needs_position_animation: false,
767 is_cupertino: false,
768 }
769 }
770}
771
772struct MaterialSwitchState {
774 state: StateData<MaterialSwitch>,
775 ticker_provider: TickerProviderStateMixinData,
776 toggleable: ToggleableStateMixinData,
777 painter: Option<Ref<SwitchPainter>>,
780 needs_position_animation: bool,
781 is_cupertino: bool,
782}
783
784impl MaterialSwitchState {
785 fn painter(self: Handle<Self>, app: &App) -> Handle<SwitchPainter> {
786 app.get(self)
787 .painter
788 .handle()
789 .expect("created in init_state")
790 }
791
792 fn update_curve(self: Handle<Self>, app: &mut App) {
793 let context = self.context(app);
794 let position = self.position(app).handle();
795 if Theme::of(app, context).use_material3 {
796 let position = app.get_mut(position);
797 position.curve = Curves::ease_out_back();
798 position.reverse_curve = Some(Rc::new(Curves::ease_out_back().flipped()));
799 } else {
800 let position = app.get_mut(position);
801 position.curve = Curves::ease_in();
802 position.reverse_curve = Some(Curves::ease_out());
803 }
804 }
805
806 fn widget_thumb_color(widget: &MaterialSwitch) -> WidgetStatePropertyRef<Option<Color>> {
808 let (active_thumb_color, inactive_thumb_color) =
809 (widget.active_thumb_color, widget.inactive_thumb_color);
810 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
811 if states.contains(&WidgetState::Disabled) {
812 return inactive_thumb_color;
813 }
814 if states.contains(&WidgetState::Selected) {
815 return active_thumb_color;
816 }
817 inactive_thumb_color
818 })
819 }
820
821 fn widget_track_color(widget: &MaterialSwitch) -> WidgetStatePropertyRef<Option<Color>> {
823 let (active_track_color, inactive_track_color) =
824 (widget.active_track_color, widget.inactive_track_color);
825 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
826 if states.contains(&WidgetState::Selected) {
827 return active_track_color;
828 }
829 inactive_track_color
830 })
831 }
832
833 fn track_inner_length(self: Handle<Self>, app: &mut App) -> f64 {
835 let context = self.context(app);
836 let theme = Theme::of(app, context);
837 let config = match self.widget(app).switch_type {
838 SwitchType::Adaptive => match theme.platform {
839 TargetPlatform::Android
840 | TargetPlatform::Fuchsia
841 | TargetPlatform::Linux
842 | TargetPlatform::Windows => switch_config(app, context, theme.use_material3),
843 TargetPlatform::IOS | TargetPlatform::MacOS => {
844 Box::new(SwitchConfigCupertino::new(app, context)) as Box<dyn SwitchConfig>
845 }
846 },
847 SwitchType::Material => switch_config(app, context, theme.use_material3),
848 };
849 let track_inner_start = config.track_height() / 2.0;
850 let track_inner_end = config.track_width() - track_inner_start;
851 track_inner_end - track_inner_start
852 }
853
854 fn handle_drag_start(self: Handle<Self>, app: &mut App, _details: DragStartDetails) {
855 if self.is_interactive(app) {
856 self.reaction_controller(app).forward(app, None);
857 }
858 }
859
860 fn handle_drag_update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
861 if self.is_interactive(app) {
862 let position = self.position(app).handle();
863 let position = app.get_mut(position);
864 position.curve = Curves::linear();
865 position.reverse_curve = None;
866 let delta = details
867 .primary_delta
868 .expect("a horizontal drag has a primary delta")
869 / self.track_inner_length(app);
870 let context = self.context(app);
871 let delta = match Directionality::of(app, context) {
872 TextDirection::Rtl => -delta,
873 TextDirection::Ltr => delta,
874 };
875 let position_controller = self.position_controller(app);
876 let value = position_controller.value(app);
877 position_controller.set_value(app, value + delta);
878 }
879 }
880
881 fn handle_drag_end(self: Handle<Self>, app: &mut App, _details: DragEndDetails) {
882 let widget_value = self.widget(app).value;
883 if (self.position(app).value(app) >= 0.5) != widget_value {
884 if let Some(on_changed) = self.widget(app).on_changed.clone() {
885 on_changed(app, !widget_value);
886 }
887 self.set_state(app, |state| state.needs_position_animation = true);
890 } else {
891 self.animate_to_value(app);
892 }
893 self.reaction_controller(app).reverse(app, None);
894 }
895
896 fn handle_changed(self: Handle<Self>, app: &mut App, value: Option<bool>) {
897 debug_assert!(value.is_some());
898 let on_changed = self.widget(app).on_changed.clone();
899 debug_assert!(on_changed.is_some());
900 if let Some(on_changed) = on_changed {
901 on_changed(app, value.expect("a two-state toggle"));
902 }
903 }
904}
905
906fn resolve<T: 'static>(
908 property: &Option<WidgetStatePropertyRef<Option<T>>>,
909 states: &WidgetStates,
910) -> Option<T> {
911 property
912 .as_ref()
913 .and_then(|property| property.resolve(states))
914}
915
916impl TickerProviderStateMixin for MaterialSwitchState {
917 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
918 &app.get(self).ticker_provider
919 }
920
921 fn ticker_provider_data_mut(
922 self: Handle<Self>,
923 app: &mut App,
924 ) -> &mut TickerProviderStateMixinData {
925 &mut app.get_mut(self).ticker_provider
926 }
927}
928
929impl TickerProviderObject for MaterialSwitchState {
931 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
932 TickerProviderStateMixin::create_ticker(self, app, on_tick)
933 }
934}
935
936impl ToggleableStateMixin for MaterialSwitchState {
937 fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData {
938 &app.get(self).toggleable
939 }
940
941 fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData {
942 &mut app.get_mut(self).toggleable
943 }
944
945 fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>> {
946 self.widget(app).on_changed.as_ref()?;
947 Some(Rc::new(move |app: &mut App, value| {
948 self.handle_changed(app, value)
949 }))
950 }
951
952 fn tristate(self: Handle<Self>, _app: &App) -> bool {
953 false
954 }
955
956 fn value(self: Handle<Self>, app: &App) -> Option<bool> {
957 Some(self.widget(app).value)
958 }
959
960 fn reaction_animation_duration(self: Handle<Self>, _app: &App) -> Option<Duration> {
961 Some(K_RADIAL_REACTION_DURATION)
962 }
963}
964
965impl State for MaterialSwitchState {
966 type Widget = MaterialSwitch;
967 waft_widgets::state_accessors!();
968
969 fn init_state(self: Handle<Self>, app: &mut App) {
970 let painter = SwitchPainter::new(app);
971 app.get_mut(self).painter = Some(painter);
972 ToggleableStateMixin::init_state(self, app);
973 }
974
975 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MaterialSwitch) {
976 if old_widget.value != self.widget(app).value {
977 let position_value = self.position(app).value(app);
980 if position_value == 0.0 || position_value == 1.0 {
981 match self.widget(app).switch_type {
982 SwitchType::Adaptive => {
983 let context = self.context(app);
984 match Theme::of(app, context).platform {
985 TargetPlatform::Android
986 | TargetPlatform::Fuchsia
987 | TargetPlatform::Linux
988 | TargetPlatform::Windows => self.update_curve(app),
989 TargetPlatform::IOS | TargetPlatform::MacOS => {
990 let position = self.position(app).handle();
991 let position = app.get_mut(position);
992 position.curve = Curves::linear();
993 position.reverse_curve = Some(Curves::linear());
994 }
995 }
996 }
997 SwitchType::Material => self.update_curve(app),
998 }
999 }
1000 self.animate_to_value(app);
1001 }
1002 }
1003
1004 fn activate(self: Handle<Self>, app: &mut App) {
1005 TickerProviderStateMixin::activate(self, app);
1006 }
1007
1008 fn dispose(self: Handle<Self>, app: &mut App) {
1009 let painter = self.painter(app);
1010 painter.dispose(app);
1011 ToggleableStateMixin::dispose(self, app);
1012 TickerProviderStateMixin::dispose(self, app);
1013 }
1014
1015 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1016 debug_assert!(debug_check_has_material(app, context));
1017
1018 if app.get(self).needs_position_animation {
1019 app.get_mut(self).needs_position_animation = false;
1020 self.animate_to_value(app);
1021 }
1022
1023 let theme = Theme::of(app, context);
1024 let mut switch_theme = SwitchTheme::of(app, context);
1025 let cupertino_primary_color = theme
1026 .cupertino_override_theme
1027 .as_ref()
1028 .and_then(|override_theme| override_theme.primary_color.as_ref())
1029 .map(AnyColor::color)
1030 .unwrap_or(theme.color_scheme.primary());
1031 let widget = self.widget(app).clone();
1032
1033 let switch_config: Box<dyn SwitchConfig>;
1034 let defaults: Box<dyn SwitchThemeDataGetters>;
1035 let mut apply_cupertino_theme = false;
1036 let mut disabled_opacity = 1.0;
1037 match widget.switch_type {
1038 SwitchType::Material => {
1039 switch_config = self::switch_config(app, context, theme.use_material3);
1040 defaults = switch_defaults(app, context, theme.use_material3);
1041 }
1042 SwitchType::Adaptive => {
1043 let switch_adaptation = theme
1044 .get_adaptation::<SwitchThemeData>()
1045 .unwrap_or(&SwitchThemeAdaptation);
1046 switch_theme = switch_adaptation.adapt(&theme, switch_theme);
1047 match theme.platform {
1048 TargetPlatform::Android
1049 | TargetPlatform::Fuchsia
1050 | TargetPlatform::Linux
1051 | TargetPlatform::Windows => {
1052 switch_config = self::switch_config(app, context, theme.use_material3);
1053 defaults = switch_defaults(app, context, theme.use_material3);
1054 }
1055 TargetPlatform::IOS | TargetPlatform::MacOS => {
1056 app.get_mut(self).is_cupertino = true;
1057 apply_cupertino_theme = widget
1058 .apply_cupertino_theme
1059 .or_else(|| {
1060 theme
1061 .cupertino_override_theme
1062 .as_ref()
1063 .and_then(|override_theme| override_theme.apply_theme_to_all)
1064 })
1065 .unwrap_or(false);
1066 disabled_opacity = 0.5;
1067 switch_config = Box::new(SwitchConfigCupertino::new(app, context));
1068 defaults = Box::new(SwitchDefaultsCupertino::new(context));
1069 let reaction_controller = self.reaction_controller(app);
1070 app.get_mut(reaction_controller).duration =
1071 Some(Duration::from_millis(200));
1072 }
1073 }
1074 }
1075 }
1076
1077 let position_controller = self.position_controller(app);
1078 app.get_mut(position_controller).duration =
1079 Some(Duration::from_millis(switch_config.toggle_duration()));
1080
1081 let mut active_states = self.states(app);
1084 active_states.insert(WidgetState::Selected);
1085 let mut inactive_states = self.states(app);
1086 inactive_states.remove(&WidgetState::Selected);
1087
1088 let widget_thumb_color = Self::widget_thumb_color(&widget);
1089 let widget_track_color = Self::widget_track_color(&widget);
1090
1091 let active_thumb_color = resolve(&widget.thumb_color, &active_states)
1092 .or_else(|| widget_thumb_color.resolve(&active_states))
1093 .or_else(|| resolve(&switch_theme.thumb_color, &active_states));
1094 let effective_active_thumb_color = active_thumb_color
1095 .or_else(|| resolve(&defaults.thumb_color(app), &active_states))
1096 .expect("the defaults give a thumb color");
1097 let inactive_thumb_color = resolve(&widget.thumb_color, &inactive_states)
1098 .or_else(|| widget_thumb_color.resolve(&inactive_states))
1099 .or_else(|| resolve(&switch_theme.thumb_color, &inactive_states));
1100 let effective_inactive_thumb_color = inactive_thumb_color
1101 .or_else(|| resolve(&defaults.thumb_color(app), &inactive_states))
1102 .expect("the defaults give a thumb color");
1103 let effective_active_track_color = resolve(&widget.track_color, &active_states)
1104 .or_else(|| widget_track_color.resolve(&active_states))
1105 .or_else(|| {
1106 if apply_cupertino_theme {
1107 Some(cupertino_primary_color)
1108 } else {
1109 resolve(&switch_theme.track_color, &active_states)
1110 }
1111 })
1112 .or_else(|| {
1113 widget_thumb_color
1114 .resolve(&active_states)
1115 .map(|color| color.with_alpha(0x80))
1116 })
1117 .or_else(|| resolve(&defaults.track_color(app), &active_states))
1118 .expect("the defaults give a track color");
1119 let effective_active_track_outline_color =
1120 resolve(&widget.track_outline_color, &active_states)
1121 .or_else(|| resolve(&switch_theme.track_outline_color, &active_states))
1122 .or_else(|| {
1123 defaults
1124 .track_outline_color(app)
1125 .as_ref()
1126 .expect("the defaults give a track outline color")
1127 .resolve(&active_states)
1128 });
1129 let effective_active_track_outline_width =
1130 resolve(&widget.track_outline_width, &active_states)
1131 .or_else(|| resolve(&switch_theme.track_outline_width, &active_states))
1132 .or_else(|| resolve(&defaults.track_outline_width(app), &active_states));
1133
1134 let effective_inactive_track_color = resolve(&widget.track_color, &inactive_states)
1135 .or_else(|| widget_track_color.resolve(&inactive_states))
1136 .or_else(|| resolve(&switch_theme.track_color, &inactive_states))
1137 .or_else(|| resolve(&defaults.track_color(app), &inactive_states))
1138 .expect("the defaults give a track color");
1139 let effective_inactive_track_outline_color =
1140 resolve(&widget.track_outline_color, &inactive_states)
1141 .or_else(|| resolve(&switch_theme.track_outline_color, &inactive_states))
1142 .or_else(|| resolve(&defaults.track_outline_color(app), &inactive_states));
1143 let effective_inactive_track_outline_width =
1144 resolve(&widget.track_outline_width, &inactive_states)
1145 .or_else(|| resolve(&switch_theme.track_outline_width, &inactive_states))
1146 .or_else(|| resolve(&defaults.track_outline_width(app), &inactive_states));
1147
1148 let effective_active_icon = resolve(&widget.thumb_icon, &active_states)
1149 .or_else(|| resolve(&switch_theme.thumb_icon, &active_states));
1150 let effective_inactive_icon = resolve(&widget.thumb_icon, &inactive_states)
1151 .or_else(|| resolve(&switch_theme.thumb_icon, &inactive_states));
1152
1153 let effective_active_icon_color = effective_active_icon
1154 .as_ref()
1155 .and_then(|icon| icon.color.as_ref())
1156 .map(AnyColor::color)
1157 .unwrap_or_else(|| switch_config.icon_color().resolve(&active_states));
1158 let effective_inactive_icon_color = effective_inactive_icon
1159 .as_ref()
1160 .and_then(|icon| icon.color.as_ref())
1161 .map(AnyColor::color)
1162 .unwrap_or_else(|| switch_config.icon_color().resolve(&inactive_states));
1163
1164 let mut focused_states = self.states(app);
1165 focused_states.insert(WidgetState::Focused);
1166 let effective_focus_overlay_color = resolve(&widget.overlay_color, &focused_states)
1167 .or(widget.focus_color)
1168 .or_else(|| resolve(&switch_theme.overlay_color, &focused_states))
1169 .or_else(|| {
1170 apply_cupertino_theme.then(|| {
1171 HSLColor::from_color(with_opacity(cupertino_primary_color, 0.80))
1172 .with_lightness(0.69)
1173 .with_saturation(0.835)
1174 .to_color()
1175 })
1176 })
1177 .or_else(|| resolve(&defaults.overlay_color(app), &focused_states))
1178 .expect("the defaults give a focus overlay color");
1179
1180 let mut hovered_states = self.states(app);
1181 hovered_states.insert(WidgetState::Hovered);
1182 let effective_hover_overlay_color = resolve(&widget.overlay_color, &hovered_states)
1183 .or(widget.hover_color)
1184 .or_else(|| resolve(&switch_theme.overlay_color, &hovered_states))
1185 .or_else(|| resolve(&defaults.overlay_color(app), &hovered_states))
1186 .expect("the defaults give a hover overlay color");
1187
1188 let mut active_pressed_states = active_states;
1189 active_pressed_states.insert(WidgetState::Pressed);
1190 let effective_active_pressed_thumb_color =
1191 resolve(&widget.thumb_color, &active_pressed_states)
1192 .or_else(|| widget_thumb_color.resolve(&active_pressed_states))
1193 .or_else(|| resolve(&switch_theme.thumb_color, &active_pressed_states))
1194 .or_else(|| resolve(&defaults.thumb_color(app), &active_pressed_states))
1195 .expect("the defaults give a thumb color");
1196 let effective_active_pressed_overlay_color =
1197 resolve(&widget.overlay_color, &active_pressed_states)
1198 .or_else(|| resolve(&switch_theme.overlay_color, &active_pressed_states))
1199 .or_else(|| {
1200 active_thumb_color.map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA))
1201 })
1202 .or_else(|| resolve(&defaults.overlay_color(app), &active_pressed_states))
1203 .expect("the defaults give a pressed overlay color");
1204
1205 let mut inactive_pressed_states = inactive_states;
1206 inactive_pressed_states.insert(WidgetState::Pressed);
1207 let effective_inactive_pressed_thumb_color =
1208 resolve(&widget.thumb_color, &inactive_pressed_states)
1209 .or_else(|| widget_thumb_color.resolve(&inactive_pressed_states))
1210 .or_else(|| resolve(&switch_theme.thumb_color, &inactive_pressed_states))
1211 .or_else(|| resolve(&defaults.thumb_color(app), &inactive_pressed_states))
1212 .expect("the defaults give a thumb color");
1213 let effective_inactive_pressed_overlay_color =
1214 resolve(&widget.overlay_color, &inactive_pressed_states)
1215 .or_else(|| resolve(&switch_theme.overlay_color, &inactive_pressed_states))
1216 .or_else(|| {
1217 inactive_thumb_color.map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA))
1218 })
1219 .or_else(|| resolve(&defaults.overlay_color(app), &inactive_pressed_states))
1220 .expect("the defaults give a pressed overlay color");
1221
1222 let effective_mouse_cursor = {
1223 let mouse_cursor = widget.mouse_cursor.clone();
1224 let theme_mouse_cursor = switch_theme.mouse_cursor.clone();
1225 let default_mouse_cursor = defaults.mouse_cursor(app);
1226 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_with(move |states: &WidgetStates| {
1227 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, states)
1228 .or_else(|| resolve(&theme_mouse_cursor, states))
1229 .or_else(|| resolve(&default_mouse_cursor, states))
1230 .expect("the defaults give a mouse cursor")
1231 })
1232 };
1233
1234 let effective_active_thumb_radius = if effective_active_icon.is_none() {
1237 switch_config.active_thumb_radius()
1238 } else {
1239 switch_config.thumb_radius_with_icon()
1240 };
1241 let effective_inactive_thumb_radius = if effective_inactive_icon.is_none() {
1242 switch_config.inactive_thumb_radius()
1243 } else {
1244 switch_config.thumb_radius_with_icon()
1245 };
1246 let effective_splash_radius = widget
1247 .splash_radius
1248 .or(switch_theme.splash_radius)
1249 .or_else(|| defaults.splash_radius(app))
1250 .expect("the defaults give a splash radius");
1251
1252 let configuration = create_local_image_configuration(app, context, None);
1253 let track_inner_length = self.track_inner_length(app);
1254 let text_direction = Directionality::of(app, context);
1255 let icon_theme = IconTheme::of(app, context);
1256 let states = self.states(app);
1257 let is_cupertino = app.get(self).is_cupertino;
1258
1259 let painter = app
1260 .get(self)
1261 .painter
1262 .clone()
1263 .expect("created in init_state");
1264 painter.set_position(app, self.position(app).erase());
1265 painter.set_reaction(app, self.reaction(app).erase());
1266 painter.set_reaction_focus_fade(app, self.reaction_focus_fade(app).erase());
1267 painter.set_reaction_hover_fade(app, self.reaction_hover_fade(app).erase());
1268 painter.set_inactive_reaction_color(app, effective_inactive_pressed_overlay_color);
1269 painter.set_reaction_color(app, effective_active_pressed_overlay_color);
1270 painter.set_hover_color(app, effective_hover_overlay_color);
1271 painter.set_focus_color(app, effective_focus_overlay_color);
1272 painter.set_splash_radius(app, effective_splash_radius);
1273 painter.set_down_position(app, self.down_position(app));
1274 painter.set_is_focused(app, Some(states.contains(&WidgetState::Focused)));
1275 painter.set_is_hovered(app, Some(states.contains(&WidgetState::Hovered)));
1276 painter.set_active_color(app, effective_active_thumb_color);
1277 painter.set_inactive_color(app, effective_inactive_thumb_color);
1278 painter.set_active_pressed_color(app, effective_active_pressed_thumb_color);
1279 painter.set_inactive_pressed_color(app, effective_inactive_pressed_thumb_color);
1280 painter.set_active_track_color(app, effective_active_track_color);
1281 painter.set_active_track_outline_color(app, effective_active_track_outline_color);
1282 painter.set_active_track_outline_width(app, effective_active_track_outline_width);
1283 painter.set_inactive_track_color(app, effective_inactive_track_color);
1284 painter.set_inactive_track_outline_color(app, effective_inactive_track_outline_color);
1285 painter.set_inactive_track_outline_width(app, effective_inactive_track_outline_width);
1286 painter.set_configuration(app, configuration);
1287 painter.set_is_interactive(app, self.is_interactive(app));
1288 painter.set_track_inner_length(app, track_inner_length);
1289 painter.set_text_direction(app, text_direction);
1290 painter.set_surface_color(app, theme.color_scheme.surface());
1291 painter.set_inactive_thumb_radius(app, effective_inactive_thumb_radius);
1292 painter.set_active_thumb_radius(app, effective_active_thumb_radius);
1293 painter.set_pressed_thumb_radius(app, switch_config.pressed_thumb_radius());
1294 painter.set_thumb_offset(app, switch_config.thumb_offset());
1295 painter.set_track_height(app, switch_config.track_height());
1296 painter.set_track_width(app, switch_config.track_width());
1297 painter.set_active_icon_color(app, effective_active_icon_color);
1298 painter.set_inactive_icon_color(app, effective_inactive_icon_color);
1299 painter.set_active_icon(app, effective_active_icon);
1300 painter.set_inactive_icon(app, effective_inactive_icon);
1301 painter.set_icon_theme(app, Some(icon_theme));
1302 painter.set_thumb_shadow(app, switch_config.thumb_shadow());
1303 painter.set_transitional_thumb_size(app, switch_config.transitional_thumb_size());
1304 painter.set_position_controller(app, position_controller.keep(app));
1305 painter.set_is_cupertino(app, is_cupertino);
1306
1307 let opacity = if ToggleableStateMixin::on_changed(self, app).is_none() {
1308 disabled_opacity
1309 } else {
1310 1.0
1311 };
1312 let toggleable = self.build_toggleable(
1313 app,
1314 widget.focus_node,
1315 widget.on_focus_change.clone(),
1316 widget.autofocus,
1317 Some(effective_mouse_cursor),
1318 widget.size,
1319 ToggleablePainterRef::new(painter),
1320 );
1321 let detector = GestureDetector::new()
1323 .on_horizontal_drag_start(Rc::new(move |app: &mut App, details| {
1324 self.handle_drag_start(app, details)
1325 }))
1326 .on_horizontal_drag_update(Rc::new(move |app: &mut App, details| {
1327 self.handle_drag_update(app, details)
1328 }))
1329 .on_horizontal_drag_end(Rc::new(move |app: &mut App, details| {
1330 self.handle_drag_end(app, details)
1331 }))
1332 .drag_start_behavior(widget.drag_start_behavior)
1333 .child(Opacity::new(opacity).child(toggleable));
1334 Semantics::new()
1335 .toggled(widget.value)
1336 .child(detector)
1337 .into_widget()
1338 }
1339}
1340
1341struct SwitchPainter {
1343 change_notifier: ChangeNotifierData,
1344 toggleable_painter: ToggleablePainterData,
1345 position_controller: Option<Ref<AnimationController>>,
1346 color_animation: Option<Ref<CurvedAnimation>>,
1347 active_icon: Option<Rc<Icon>>,
1348 inactive_icon: Option<Rc<Icon>>,
1349 icon_theme: Option<IconThemeData>,
1350 active_icon_color: Option<Color>,
1351 inactive_icon_color: Option<Color>,
1352 active_pressed_color: Option<Color>,
1353 inactive_pressed_color: Option<Color>,
1354 active_thumb_radius: Option<f64>,
1355 inactive_thumb_radius: Option<f64>,
1356 pressed_thumb_radius: Option<f64>,
1357 thumb_offset: Option<f64>,
1358 transitional_thumb_size: Option<Size>,
1359 track_height: Option<f64>,
1360 track_width: Option<f64>,
1361 active_track_color: Option<Color>,
1362 active_track_outline_color: Option<Color>,
1363 inactive_track_outline_color: Option<Color>,
1364 active_track_outline_width: Option<f64>,
1365 inactive_track_outline_width: Option<f64>,
1366 inactive_track_color: Option<Color>,
1367 configuration: Option<ImageConfiguration>,
1368 text_direction: Option<TextDirection>,
1369 surface_color: Option<Color>,
1370 is_interactive: Option<bool>,
1371 track_inner_length: Option<f64>,
1372 is_cupertino: Option<bool>,
1373 thumb_shadow: Option<Vec<BoxShadow>>,
1374 text_painter: TextPainter,
1375 cached_thumb_color: Option<Color>,
1376 cached_thumb_painter: Option<Box<dyn BoxPainter>>,
1377 is_painting: Rc<Cell<bool>>,
1380 stop_press_animation: bool,
1381 pressed_inactive_thumb_radius: Option<f64>,
1382 pressed_active_thumb_radius: Option<f64>,
1383 pressed_thumb_extension: f64,
1384}
1385
1386macro_rules! painter_field {
1388 ($field:ident, $setter:ident, $ty:ty) => {
1389 fn $field(self: Handle<Self>, app: &App) -> $ty {
1390 app.get(self).$field.expect("set before painting")
1391 }
1392
1393 fn $setter(self: Handle<Self>, app: &mut App, value: $ty) {
1394 if Some(value) == app.get(self).$field {
1395 return;
1396 }
1397 app.get_mut(self).$field = Some(value);
1398 self.notify_listeners(app);
1399 }
1400 };
1401}
1402
1403macro_rules! nullable_painter_field {
1405 ($field:ident, $setter:ident, $ty:ty) => {
1406 fn $field(self: Handle<Self>, app: &App) -> Option<$ty> {
1407 app.get(self).$field
1408 }
1409
1410 fn $setter(self: Handle<Self>, app: &mut App, value: Option<$ty>) {
1411 if value == app.get(self).$field {
1412 return;
1413 }
1414 app.get_mut(self).$field = value;
1415 self.notify_listeners(app);
1416 }
1417 };
1418}
1419
1420impl SwitchPainter {
1421 fn new(app: &mut App) -> Ref<SwitchPainter> {
1422 app.create(SwitchPainter {
1423 change_notifier: ChangeNotifierData::new(),
1424 toggleable_painter: ToggleablePainterData::new(),
1425 position_controller: None,
1426 color_animation: None,
1427 active_icon: None,
1428 inactive_icon: None,
1429 icon_theme: None,
1430 active_icon_color: None,
1431 inactive_icon_color: None,
1432 active_pressed_color: None,
1433 inactive_pressed_color: None,
1434 active_thumb_radius: None,
1435 inactive_thumb_radius: None,
1436 pressed_thumb_radius: None,
1437 thumb_offset: None,
1438 transitional_thumb_size: None,
1439 track_height: None,
1440 track_width: None,
1441 active_track_color: None,
1442 active_track_outline_color: None,
1443 inactive_track_outline_color: None,
1444 active_track_outline_width: None,
1445 inactive_track_outline_width: None,
1446 inactive_track_color: None,
1447 configuration: None,
1448 text_direction: None,
1449 surface_color: None,
1450 is_interactive: None,
1451 track_inner_length: None,
1452 is_cupertino: None,
1453 thumb_shadow: None,
1454 text_painter: TextPainter::new(),
1455 cached_thumb_color: None,
1456 cached_thumb_painter: None,
1457 is_painting: Rc::new(Cell::new(false)),
1458 stop_press_animation: false,
1459 pressed_inactive_thumb_radius: None,
1460 pressed_active_thumb_radius: None,
1461 pressed_thumb_extension: 0.0,
1462 })
1463 }
1464
1465 fn position_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
1466 app.get(self)
1467 .position_controller
1468 .handle()
1469 .expect("set before painting")
1470 }
1471
1472 fn set_position_controller(self: Handle<Self>, app: &mut App, value: Ref<AnimationController>) {
1473 if app.get(self).position_controller.handle() == Some(value.handle()) {
1474 return;
1475 }
1476 app.get_mut(self).position_controller = Some(value.clone());
1477 if let Some(color_animation) = app.get_mut(self).color_animation.take() {
1478 color_animation.dispose(app);
1479 }
1480 let color_animation = CurvedAnimation::new(
1481 app,
1482 value.erase(),
1483 Curves::ease_out(),
1484 Some(Curves::ease_in()),
1485 );
1486 app.get_mut(self).color_animation = Some(color_animation);
1487 self.notify_listeners(app);
1488 }
1489
1490 fn active_icon(self: Handle<Self>, app: &App) -> Option<Rc<Icon>> {
1491 app.get(self).active_icon.clone()
1492 }
1493
1494 fn set_active_icon(self: Handle<Self>, app: &mut App, value: Option<Rc<Icon>>) {
1495 if value == app.get(self).active_icon {
1496 return;
1497 }
1498 app.get_mut(self).active_icon = value;
1499 self.notify_listeners(app);
1500 }
1501
1502 fn inactive_icon(self: Handle<Self>, app: &App) -> Option<Rc<Icon>> {
1503 app.get(self).inactive_icon.clone()
1504 }
1505
1506 fn set_inactive_icon(self: Handle<Self>, app: &mut App, value: Option<Rc<Icon>>) {
1507 if value == app.get(self).inactive_icon {
1508 return;
1509 }
1510 app.get_mut(self).inactive_icon = value;
1511 self.notify_listeners(app);
1512 }
1513
1514 fn icon_theme(self: Handle<Self>, app: &App) -> Option<&IconThemeData> {
1515 app.get(self).icon_theme.as_ref()
1516 }
1517
1518 fn set_icon_theme(self: Handle<Self>, app: &mut App, value: Option<IconThemeData>) {
1519 if value == app.get(self).icon_theme {
1520 return;
1521 }
1522 app.get_mut(self).icon_theme = value;
1523 self.notify_listeners(app);
1524 }
1525
1526 painter_field!(active_icon_color, set_active_icon_color, Color);
1527 painter_field!(inactive_icon_color, set_inactive_icon_color, Color);
1528 painter_field!(active_pressed_color, set_active_pressed_color, Color);
1529 painter_field!(inactive_pressed_color, set_inactive_pressed_color, Color);
1530 painter_field!(active_thumb_radius, set_active_thumb_radius, f64);
1531 painter_field!(inactive_thumb_radius, set_inactive_thumb_radius, f64);
1532 painter_field!(pressed_thumb_radius, set_pressed_thumb_radius, f64);
1533 nullable_painter_field!(thumb_offset, set_thumb_offset, f64);
1534 painter_field!(transitional_thumb_size, set_transitional_thumb_size, Size);
1535 painter_field!(track_height, set_track_height, f64);
1536 painter_field!(track_width, set_track_width, f64);
1537 painter_field!(active_track_color, set_active_track_color, Color);
1538 nullable_painter_field!(
1539 active_track_outline_color,
1540 set_active_track_outline_color,
1541 Color
1542 );
1543 nullable_painter_field!(
1544 inactive_track_outline_color,
1545 set_inactive_track_outline_color,
1546 Color
1547 );
1548 nullable_painter_field!(
1549 active_track_outline_width,
1550 set_active_track_outline_width,
1551 f64
1552 );
1553 nullable_painter_field!(
1554 inactive_track_outline_width,
1555 set_inactive_track_outline_width,
1556 f64
1557 );
1558 painter_field!(inactive_track_color, set_inactive_track_color, Color);
1559
1560 fn configuration(self: Handle<Self>, app: &App) -> &ImageConfiguration {
1561 app.get(self)
1562 .configuration
1563 .as_ref()
1564 .expect("set before painting")
1565 }
1566
1567 fn set_configuration(self: Handle<Self>, app: &mut App, value: ImageConfiguration) {
1568 if app.get(self).configuration.as_ref() == Some(&value) {
1569 return;
1570 }
1571 app.get_mut(self).configuration = Some(value);
1572 self.notify_listeners(app);
1573 }
1574
1575 painter_field!(text_direction, set_text_direction, TextDirection);
1576 painter_field!(surface_color, set_surface_color, Color);
1577 #[expect(
1578 dead_code,
1579 reason = "Dart's getter; only the setter is called, from the state's build"
1580 )]
1581 fn is_interactive(self: Handle<Self>, app: &App) -> bool {
1582 app.get(self).is_interactive.expect("set before painting")
1583 }
1584
1585 fn set_is_interactive(self: Handle<Self>, app: &mut App, value: bool) {
1586 if Some(value) == app.get(self).is_interactive {
1587 return;
1588 }
1589 app.get_mut(self).is_interactive = Some(value);
1590 self.notify_listeners(app);
1591 }
1592
1593 painter_field!(track_inner_length, set_track_inner_length, f64);
1594 painter_field!(is_cupertino, set_is_cupertino, bool);
1595
1596 fn thumb_shadow(self: Handle<Self>, app: &App) -> Option<&[BoxShadow]> {
1597 app.get(self).thumb_shadow.as_deref()
1598 }
1599
1600 fn set_thumb_shadow(self: Handle<Self>, app: &mut App, value: Option<Vec<BoxShadow>>) {
1601 if value == app.get(self).thumb_shadow {
1602 return;
1603 }
1604 app.get_mut(self).thumb_shadow = value;
1605 self.notify_listeners(app);
1606 }
1607
1608 fn create_default_thumb_decoration(
1610 self: Handle<Self>,
1611 app: &App,
1612 color: Color,
1613 ) -> ShapeDecoration {
1614 let decoration = ShapeDecoration::new(StadiumBorder::new(BorderSide::NONE)).color(color);
1615 match self.thumb_shadow(app) {
1616 Some(thumb_shadow) if !self.is_cupertino(app) => {
1617 decoration.shadows(thumb_shadow.to_vec())
1618 }
1619 _ => decoration,
1620 }
1621 }
1622
1623 fn handle_decoration_changed(self: Handle<Self>, app: &mut App, is_painting: &Cell<bool>) {
1629 if !is_painting.get() {
1630 self.notify_listeners(app);
1631 }
1632 }
1633
1634 fn thumb_size_animation_value(
1637 self: Handle<Self>,
1638 app: &mut App,
1639 is_forward: bool,
1640 inactive_thumb_size: Size,
1641 active_thumb_size: Size,
1642 ) -> Size {
1643 let transitional_thumb_size = self.transitional_thumb_size(app);
1644 let cubic = |a, b, c, d| Rc::new(Cubic::new(a, b, c, d)) as Rc<dyn Curve>;
1645 let tween = |app: &mut App, begin: Size, end: Size, curve: Rc<dyn Curve>| {
1646 let tween = Tween::new(app, Some(begin), Some(end));
1647 let curve = CurveTween::new(app, curve);
1648 Rc::new(tween.chain(curve)) as Rc<dyn Animatable<Size>>
1649 };
1650 let thumb_size_sequence = if is_forward {
1651 let first = tween(
1652 app,
1653 inactive_thumb_size,
1654 transitional_thumb_size,
1655 cubic(0.31, 0.00, 0.56, 1.00),
1656 );
1657 let second = tween(
1658 app,
1659 transitional_thumb_size,
1660 active_thumb_size,
1661 cubic(0.20, 0.00, 0.00, 1.00),
1662 );
1663 let constant = ConstantTween::new(app, active_thumb_size);
1664 vec![
1665 TweenSequenceItem::new(first, 11.0),
1666 TweenSequenceItem::new(second, 72.0),
1667 TweenSequenceItem::new(Rc::new(constant), 17.0),
1668 ]
1669 } else {
1670 let constant = ConstantTween::new(app, inactive_thumb_size);
1671 let first = tween(
1672 app,
1673 inactive_thumb_size,
1674 transitional_thumb_size,
1675 Rc::new(cubic(0.20, 0.00, 0.00, 1.00).flipped()),
1676 );
1677 let second = tween(
1678 app,
1679 transitional_thumb_size,
1680 active_thumb_size,
1681 Rc::new(cubic(0.31, 0.00, 0.56, 1.00).flipped()),
1682 );
1683 vec![
1684 TweenSequenceItem::new(Rc::new(constant), 17.0),
1685 TweenSequenceItem::new(first, 72.0),
1686 TweenSequenceItem::new(second, 11.0),
1687 ]
1688 };
1689
1690 let position_controller = self.position_controller(app);
1691
1692 TweenSequence::new(thumb_size_sequence).evaluate(app, position_controller.as_animation())
1693 }
1694
1695 fn compute_track_paint_offset(
1697 canvas_size: Size,
1698 track_width: f64,
1699 track_height: f64,
1700 ) -> Offset {
1701 let horizontal_offset = (canvas_size.width() - track_width) / 2.0;
1702 let vertical_offset = (canvas_size.height() - track_height) / 2.0;
1703
1704 Offset::new(horizontal_offset, vertical_offset)
1705 }
1706
1707 fn compute_thumb_paint_offset(
1710 self: Handle<Self>,
1711 app: &App,
1712 track_paint_offset: Offset,
1713 thumb_size: Size,
1714 visual_position: f64,
1715 ) -> Offset {
1716 let track_radius = self.track_height(app) / 2.0;
1718 let additional_thumb_radius = thumb_size.height() / 2.0 - track_radius;
1719
1720 let pressed_thumb_extension = app.get(self).pressed_thumb_extension;
1721 let horizontal_progress =
1722 visual_position * (self.track_inner_length(app) - pressed_thumb_extension);
1723 let thumb_horizontal_offset =
1724 track_paint_offset.dx() + track_radius + (pressed_thumb_extension / 2.0)
1725 - thumb_size.width() / 2.0
1726 + horizontal_progress;
1727 let thumb_vertical_offset = track_paint_offset.dy() - additional_thumb_radius;
1728 Offset::new(thumb_horizontal_offset, thumb_vertical_offset)
1729 }
1730
1731 fn paint_track_with(
1732 self: Handle<Self>,
1733 app: &App,
1734 canvas: &mut Canvas,
1735 paint: &Paint,
1736 track_paint_offset: Offset,
1737 track_outline_color: Option<Color>,
1738 track_outline_width: Option<f64>,
1739 ) {
1740 let track_width = self.track_width(app);
1741 let track_height = self.track_height(app);
1742 let track_rect = Rect::from_ltwh(
1743 track_paint_offset.dx(),
1744 track_paint_offset.dy(),
1745 track_width,
1746 track_height,
1747 );
1748 let track_radius = track_height / 2.0;
1749 let track_rrect = RRect::from_rect_and_radius(track_rect, Radius::circular(track_radius));
1750
1751 draw_rrect(canvas, track_rrect, paint);
1752
1753 if let Some(track_outline_color) = track_outline_color {
1755 let outline_track_rect = Rect::from_ltwh(
1756 track_paint_offset.dx() + 1.0,
1757 track_paint_offset.dy() + 1.0,
1758 track_width - 2.0,
1759 track_height - 2.0,
1760 );
1761 let outline_track_rrect =
1762 RRect::from_rect_and_radius(outline_track_rect, Radius::circular(track_radius));
1763
1764 let outline_paint = Paint {
1765 style: PaintStyle::Stroke(Stroke::new(track_outline_width.unwrap_or(2.0) as f32)),
1766 color: track_outline_color.into(),
1767 ..Paint::default()
1768 };
1769
1770 draw_rrect(canvas, outline_track_rrect, &outline_paint);
1771 }
1772
1773 if self.is_cupertino(app) {
1774 if self.is_focused(app) {
1775 let focused_outline = track_rrect.inflate(1.75);
1776 let focused_paint = Paint {
1777 style: PaintStyle::Stroke(Stroke::new(K_CUPERTINO_FOCUS_TRACK_OUTLINE as f32)),
1778 color: self.focus_color(app).into(),
1779 ..Paint::default()
1780 };
1781 draw_rrect(canvas, focused_outline, &focused_paint);
1782 }
1783 canvas.clip_rrect_radii_elliptical(
1784 track_rrect.outer_rect(),
1785 rrect_radii_elliptical(track_rrect),
1786 ClipOp::Intersect,
1787 true,
1788 );
1789 }
1790 }
1791
1792 #[allow(clippy::too_many_arguments)]
1793 fn paint_thumb_with(
1794 self: Handle<Self>,
1795 app: &mut App,
1796 thumb_paint_offset: Offset,
1797 canvas: &mut Canvas,
1798 current_value: f64,
1799 thumb_color: Color,
1800 thumb_icon: Option<Rc<Icon>>,
1801 thumb_size: Size,
1802 ) {
1803 let is_painting = Rc::clone(&app.get(self).is_painting);
1804 let _painting = PaintingGuard::enter(&is_painting);
1805 self.update_cached_thumb_painter(app, thumb_color);
1806
1807 if self.is_cupertino(app) {
1808 self.paint_cupertino_thumb_shadow_and_border(
1809 app,
1810 canvas,
1811 thumb_paint_offset,
1812 thumb_size,
1813 );
1814 }
1815
1816 let configuration =
1817 self.configuration(app)
1818 .copy_with(None, None, None, None, Some(thumb_size), None);
1819 app.get_mut(self)
1820 .cached_thumb_painter
1821 .as_mut()
1822 .expect("created above")
1823 .paint(canvas, thumb_paint_offset, &configuration);
1824
1825 if let Some(thumb_icon) = thumb_icon
1826 && let Some(icon_data) = &thumb_icon.icon
1827 {
1828 let icon_color = Color::lerp(
1829 Some(self.inactive_icon_color(app)),
1830 Some(self.active_icon_color(app)),
1831 current_value,
1832 )
1833 .expect("lerping non-null colors");
1834 let icon_size = thumb_icon.size.unwrap_or(SwitchConfigM3::ICON_SIZE);
1835 let icon_theme = self.icon_theme(app);
1836 let icon_weight = thumb_icon
1837 .weight
1838 .or(icon_theme.and_then(|theme| theme.weight));
1839 let icon_fill = thumb_icon.fill.or(icon_theme.and_then(|theme| theme.fill));
1840 let icon_grade = thumb_icon
1841 .grade
1842 .or(icon_theme.and_then(|theme| theme.grade));
1843 let icon_optical_size = thumb_icon
1844 .optical_size
1845 .or(icon_theme.and_then(|theme| theme.optical_size));
1846 let icon_shadows = thumb_icon
1847 .shadows
1848 .clone()
1849 .or_else(|| icon_theme.and_then(|theme| theme.shadows.clone()));
1850
1851 let font_variations = [
1852 ("FILL", icon_fill),
1853 ("wght", icon_weight),
1854 ("GRAD", icon_grade),
1855 ("opsz", icon_optical_size),
1856 ]
1857 .into_iter()
1858 .filter_map(|(axis, value)| value.map(|value| FontVariation::new(axis, value)))
1859 .collect();
1860 let mut style = TextStyle::new()
1861 .font_variations(font_variations)
1862 .color(icon_color)
1863 .font_size(icon_size)
1864 .inherit(false);
1865 if let Some(font_family) = &icon_data.font_family {
1866 style = style.font_family(font_family.clone());
1867 }
1868 if let Some(font_package) = &icon_data.font_package {
1869 style = style.package(font_package.clone());
1870 }
1871 if let Some(icon_shadows) = icon_shadows {
1872 style = style.shadows(icon_shadows);
1873 }
1874 let code_point = char::from_u32(icon_data.code_point)
1875 .expect("an IconData code point is a Unicode scalar value");
1876 let text_span = TextSpan::new().text(code_point.to_string()).style(style);
1877 let additional_horizontal_offset = (thumb_size.width() - icon_size) / 2.0;
1878 let additional_vertical_offset = (thumb_size.height() - icon_size) / 2.0;
1879 let offset = thumb_paint_offset
1880 + Offset::new(additional_horizontal_offset, additional_vertical_offset);
1881 self.paint_icon(app, canvas, text_span, offset);
1882 }
1883 }
1884
1885 fn update_cached_thumb_painter(self: Handle<Self>, app: &mut App, thumb_color: Color) {
1888 let painter = app.get(self);
1889 if painter.cached_thumb_painter.is_some() && painter.cached_thumb_color == Some(thumb_color)
1890 {
1891 return;
1892 }
1893 let decoration = self.create_default_thumb_decoration(app, thumb_color);
1894 let painter = app.get_mut(self);
1895 painter.cached_thumb_color = Some(thumb_color);
1896 if let Some(mut old) = painter.cached_thumb_painter.take() {
1897 old.dispose();
1898 }
1899 let is_painting = Rc::clone(&painter.is_painting);
1900 let on_changed: Rc<dyn Fn(&mut App)> =
1901 Rc::new(move |app: &mut App| self.handle_decoration_changed(app, &is_painting));
1902 app.get_mut(self).cached_thumb_painter =
1903 Some(decoration.create_box_painter(Some(on_changed)));
1904 }
1905
1906 fn paint_icon(
1909 self: Handle<Self>,
1910 app: &mut App,
1911 canvas: &mut Canvas,
1912 text: TextSpan,
1913 offset: Offset,
1914 ) {
1915 let text_direction = self.text_direction(app);
1916 let fonts = PaintingBinding::instance(app).fonts(app);
1917 let (painter, fonts) = app.get_disjoint_mut(self, fonts);
1918 painter
1919 .text_painter
1920 .set_text_direction(Some(text_direction));
1921 painter.text_painter.set_text(Some(Rc::new(text)));
1922 painter.text_painter.layout(fonts, 0.0, f64::INFINITY);
1923 painter.text_painter.paint(fonts, canvas, offset);
1924 }
1925
1926 fn paint_cupertino_thumb_shadow_and_border(
1927 self: Handle<Self>,
1928 app: &App,
1929 canvas: &mut Canvas,
1930 thumb_paint_offset: Offset,
1931 thumb_size: Size,
1932 ) {
1933 let thumb_bounds = RRect::from_ltrbr(
1934 thumb_paint_offset.dx(),
1935 thumb_paint_offset.dy(),
1936 thumb_paint_offset.dx() + thumb_size.width(),
1937 thumb_paint_offset.dy() + thumb_size.height(),
1938 Radius::circular(thumb_size.height() / 2.0),
1939 );
1940 if let Some(thumb_shadow) = self.thumb_shadow(app) {
1941 for shadow in thumb_shadow {
1942 draw_rrect(
1943 canvas,
1944 thumb_bounds.shift(shadow.offset),
1945 &shadow.to_paint(),
1946 );
1947 }
1948 }
1949
1950 draw_rrect(
1951 canvas,
1952 thumb_bounds.inflate(0.5),
1953 &Paint::from_color(Color::new(0x0A000000).into()),
1954 );
1955 }
1956
1957 fn dispose(self: Handle<Self>, app: &mut App) {
1959 let painter = app.get_mut(self);
1960 painter.text_painter.dispose();
1961 if let Some(mut cached_thumb_painter) = painter.cached_thumb_painter.take() {
1962 cached_thumb_painter.dispose();
1963 }
1964 painter.cached_thumb_color = None;
1965 let color_animation = painter.color_animation.take();
1966 if let Some(color_animation) = color_animation {
1967 color_animation.dispose(app);
1968 }
1969 ToggleablePainter::dispose(self, app);
1970 }
1971}
1972
1973struct PaintingGuard {
1975 flag: Rc<Cell<bool>>,
1976}
1977
1978impl PaintingGuard {
1979 fn enter(flag: &Rc<Cell<bool>>) -> PaintingGuard {
1980 flag.set(true);
1981 PaintingGuard {
1982 flag: Rc::clone(flag),
1983 }
1984 }
1985}
1986
1987impl Drop for PaintingGuard {
1988 fn drop(&mut self) {
1989 self.flag.set(false);
1990 }
1991}
1992
1993impl ChangeNotifier for SwitchPainter {
1994 fn change_notifier_data(&self) -> &ChangeNotifierData {
1995 &self.change_notifier
1996 }
1997
1998 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1999 &mut self.change_notifier
2000 }
2001}
2002
2003impl ToggleablePainter for SwitchPainter {
2004 fn toggleable_painter_data(self: Handle<Self>, app: &App) -> &ToggleablePainterData {
2005 &app.get(self).toggleable_painter
2006 }
2007
2008 fn toggleable_painter_data_mut(
2009 self: Handle<Self>,
2010 app: &mut App,
2011 ) -> &mut ToggleablePainterData {
2012 &mut app.get_mut(self).toggleable_painter
2013 }
2014
2015 fn paint(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, size: Size) {
2016 let current_value = self.position(app).value(app);
2017
2018 let visual_position = match self.text_direction(app) {
2019 TextDirection::Rtl => 1.0 - current_value,
2020 TextDirection::Ltr => current_value,
2021 };
2022 let reaction = self.reaction(app);
2023 let stop_press_animation = app.get(self).stop_press_animation;
2024 app.get_mut(self).stop_press_animation =
2025 reaction.status(app) == AnimationStatus::Reverse && !stop_press_animation;
2026
2027 let is_cupertino = self.is_cupertino(app);
2028 let inactive_thumb_radius = self.inactive_thumb_radius(app);
2029 let active_thumb_radius = self.active_thumb_radius(app);
2030 let pressed_thumb_radius = self.pressed_thumb_radius(app);
2031
2032 if !app.get(self).stop_press_animation {
2035 let reaction_value = reaction.value(app);
2036 let pressed_thumb_extension = if is_cupertino {
2037 reaction_value * 7.0
2038 } else {
2039 0.0
2040 };
2041 let painter = app.get_mut(self);
2042 painter.pressed_thumb_extension = pressed_thumb_extension;
2043 if reaction.is_completed(app) {
2044 let painter = app.get_mut(self);
2046 painter.pressed_inactive_thumb_radius = lerp_double(
2047 Some(inactive_thumb_radius),
2048 Some(pressed_thumb_radius),
2049 reaction_value,
2050 );
2051 painter.pressed_active_thumb_radius = lerp_double(
2052 Some(active_thumb_radius),
2053 Some(pressed_thumb_radius),
2054 reaction_value,
2055 );
2056 }
2057 let painter = app.get_mut(self);
2058 if current_value == 0.0 {
2059 painter.pressed_inactive_thumb_radius = lerp_double(
2060 Some(inactive_thumb_radius),
2061 Some(pressed_thumb_radius),
2062 reaction_value,
2063 );
2064 painter.pressed_active_thumb_radius = Some(active_thumb_radius);
2065 }
2066 if current_value == 1.0 {
2067 painter.pressed_active_thumb_radius = lerp_double(
2068 Some(active_thumb_radius),
2069 Some(pressed_thumb_radius),
2070 reaction_value,
2071 );
2072 painter.pressed_inactive_thumb_radius = Some(inactive_thumb_radius);
2073 }
2074 }
2075 let painter = app.get(self);
2076 let pressed_thumb_extension = painter.pressed_thumb_extension;
2077 let effective_pressed_inactive_thumb_radius = painter
2078 .pressed_inactive_thumb_radius
2079 .unwrap_or(inactive_thumb_radius);
2080 let effective_pressed_active_thumb_radius = painter
2081 .pressed_active_thumb_radius
2082 .unwrap_or(active_thumb_radius);
2083 let inactive_thumb_size = if is_cupertino {
2084 Size::new(
2085 effective_pressed_inactive_thumb_radius * 2.0 + pressed_thumb_extension,
2086 effective_pressed_inactive_thumb_radius * 2.0,
2087 )
2088 } else {
2089 Size::from_radius(effective_pressed_inactive_thumb_radius)
2090 };
2091 let active_thumb_size = if is_cupertino {
2092 Size::new(
2093 effective_pressed_active_thumb_radius * 2.0 + pressed_thumb_extension,
2094 effective_pressed_active_thumb_radius * 2.0,
2095 )
2096 } else {
2097 Size::from_radius(effective_pressed_active_thumb_radius)
2098 };
2099
2100 let position = self.position(app);
2101 let position_forward_or_dismissed =
2102 position.is_dismissed(app) || position.status(app) == AnimationStatus::Forward;
2103 #[allow(clippy::if_same_then_else)]
2105 let thumb_size = if is_cupertino {
2106 if reaction.is_completed(app) {
2107 Size::new(
2108 effective_pressed_inactive_thumb_radius * 2.0 + pressed_thumb_extension,
2109 effective_pressed_inactive_thumb_radius * 2.0,
2110 )
2111 } else if position_forward_or_dismissed {
2112 Size::lerp(
2113 Some(inactive_thumb_size),
2114 Some(active_thumb_size),
2115 position.value(app),
2116 )
2117 .expect("lerping non-null sizes")
2118 } else {
2119 Size::lerp(
2120 Some(inactive_thumb_size),
2121 Some(active_thumb_size),
2122 position.value(app),
2123 )
2124 .expect("lerping non-null sizes")
2125 }
2126 } else if reaction.is_completed(app) {
2127 Size::from_radius(pressed_thumb_radius)
2128 } else if position_forward_or_dismissed {
2129 self.thumb_size_animation_value(app, true, inactive_thumb_size, active_thumb_size)
2130 } else {
2131 self.thumb_size_animation_value(app, false, inactive_thumb_size, active_thumb_size)
2132 };
2133
2134 let inset = match self.thumb_offset(app) {
2136 None => 0.0,
2137 Some(thumb_offset) => 1.0 - (current_value - thumb_offset).abs() * 2.0,
2138 };
2139 let thumb_size = Size::new(thumb_size.width() - inset, thumb_size.height() - inset);
2140
2141 let color_value = app
2142 .get(self)
2143 .color_animation
2144 .handle()
2145 .expect("set with the position controller")
2146 .value(app);
2147 let track_color = Color::lerp(
2148 Some(self.inactive_track_color(app)),
2149 Some(self.active_track_color(app)),
2150 color_value,
2151 )
2152 .expect("lerping non-null colors");
2153 let track_outline_color = match (
2154 self.inactive_track_outline_color(app),
2155 self.active_track_outline_color(app),
2156 ) {
2157 (Some(inactive), Some(active)) => {
2158 Color::lerp(Some(inactive), Some(active), color_value)
2159 }
2160 _ => None,
2161 };
2162 let track_outline_width = lerp_double(
2163 self.inactive_track_outline_width(app),
2164 self.active_track_outline_width(app),
2165 color_value,
2166 );
2167 let position_status = self.position_controller(app).status(app);
2168 let lerped_thumb_color = if !reaction.is_dismissed(app) {
2169 Color::lerp(
2170 Some(self.inactive_pressed_color(app)),
2171 Some(self.active_pressed_color(app)),
2172 color_value,
2173 )
2174 } else if position_status == AnimationStatus::Forward {
2175 Color::lerp(
2176 Some(self.inactive_pressed_color(app)),
2177 Some(self.active_color(app)),
2178 color_value,
2179 )
2180 } else if position_status == AnimationStatus::Reverse {
2181 Color::lerp(
2182 Some(self.inactive_color(app)),
2183 Some(self.active_pressed_color(app)),
2184 color_value,
2185 )
2186 } else {
2187 Color::lerp(
2188 Some(self.inactive_color(app)),
2189 Some(self.active_color(app)),
2190 color_value,
2191 )
2192 }
2193 .expect("lerping non-null colors");
2194
2195 let thumb_color = Color::alpha_blend(lerped_thumb_color, self.surface_color(app));
2199
2200 let thumb_icon = if current_value < 0.5 {
2201 self.inactive_icon(app)
2202 } else {
2203 self.active_icon(app)
2204 };
2205
2206 let paint = Paint::from_color(track_color.into());
2207
2208 let track_paint_offset =
2209 Self::compute_track_paint_offset(size, self.track_width(app), self.track_height(app));
2210 let thumb_paint_offset =
2211 self.compute_thumb_paint_offset(app, track_paint_offset, thumb_size, visual_position);
2212 let radial_reaction_origin = Offset::new(
2213 thumb_paint_offset.dx() + thumb_size.height() / 2.0,
2214 size.height() / 2.0,
2215 );
2216
2217 self.paint_track_with(
2218 app,
2219 canvas,
2220 &paint,
2221 track_paint_offset,
2222 track_outline_color,
2223 track_outline_width,
2224 );
2225 self.paint_radial_reaction(app, canvas, Offset::ZERO, radial_reaction_origin);
2226 self.paint_thumb_with(
2227 app,
2228 thumb_paint_offset,
2229 canvas,
2230 color_value,
2231 thumb_color,
2232 thumb_icon,
2233 thumb_size,
2234 );
2235 }
2236}
2237
2238#[derive(Debug)]
2240struct SwitchThemeAdaptation;
2241
2242impl Adaptation<SwitchThemeData> for SwitchThemeAdaptation {
2243 fn adapt(&self, theme: &ThemeData, default_value: SwitchThemeData) -> SwitchThemeData {
2244 match theme.platform {
2245 TargetPlatform::Android
2246 | TargetPlatform::Fuchsia
2247 | TargetPlatform::Linux
2248 | TargetPlatform::Windows => default_value,
2249 TargetPlatform::IOS | TargetPlatform::MacOS => SwitchThemeData::new(),
2250 }
2251 }
2252}
2253
2254pub(crate) trait SwitchConfig {
2257 fn track_height(&self) -> f64;
2258 fn track_width(&self) -> f64;
2259 fn switch_width(&self) -> f64;
2260 fn switch_height(&self) -> f64;
2261 fn switch_height_collapsed(&self) -> f64;
2262 fn active_thumb_radius(&self) -> f64;
2263 fn inactive_thumb_radius(&self) -> f64;
2264 fn pressed_thumb_radius(&self) -> f64;
2265 fn thumb_radius_with_icon(&self) -> f64;
2266 fn thumb_shadow(&self) -> Option<Vec<BoxShadow>>;
2267 fn icon_color(&self) -> WidgetStatePropertyRef<Color>;
2268 fn thumb_offset(&self) -> Option<f64>;
2269 fn transitional_thumb_size(&self) -> Size;
2270 fn toggle_duration(&self) -> u64;
2272 fn switch_min_size(&self) -> Size;
2273}
2274
2275struct SwitchDefaultsCupertino {
2277 switch_theme_data: SwitchThemeData,
2279 context: DefaultsContext,
2280}
2281
2282impl SwitchDefaultsCupertino {
2283 fn new(context: BuildContext) -> SwitchDefaultsCupertino {
2284 SwitchDefaultsCupertino {
2285 switch_theme_data: SwitchThemeData::new(),
2286 context: DefaultsContext::new(context),
2287 }
2288 }
2289}
2290
2291impl SwitchThemeDataGetters for SwitchDefaultsCupertino {
2292 fn switch_theme_data(&self) -> &SwitchThemeData {
2293 &self.switch_theme_data
2294 }
2295
2296 fn mouse_cursor(
2297 &self,
2298 _app: &mut App,
2299 ) -> Option<WidgetStatePropertyRef<Option<MouseCursorRef>>> {
2300 Some(<dyn WidgetStateProperty<_>>::resolve_with(
2301 |states: &WidgetStates| -> Option<MouseCursorRef> {
2302 if states.contains(&WidgetState::Disabled) {
2303 return Some(SystemMouseCursors::BASIC.into());
2304 }
2305 Some(if K_IS_WEB {
2306 SystemMouseCursors::CLICK.into()
2307 } else {
2308 SystemMouseCursors::BASIC.into()
2309 })
2310 },
2311 ))
2312 }
2313
2314 fn thumb_color(&self, _app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2315 Some(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
2316 Colors::WHITE,
2317 )))
2318 }
2319
2320 fn track_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2321 let system_green = CupertinoDynamicColor::resolve(
2322 &CupertinoColors::SYSTEM_GREEN,
2323 app,
2324 self.context.context(),
2325 )
2326 .color();
2327 let secondary_system_fill = CupertinoDynamicColor::resolve(
2328 &CupertinoColors::SECONDARY_SYSTEM_FILL,
2329 app,
2330 self.context.context(),
2331 )
2332 .color();
2333 Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2334 move |states: &WidgetStates| {
2335 if states.contains(&WidgetState::Selected) {
2336 return Some(system_green);
2337 }
2338 Some(secondary_system_fill)
2339 },
2340 ))
2341 }
2342
2343 fn track_outline_color(&self, _app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2344 Some(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
2345 Colors::TRANSPARENT,
2346 )))
2347 }
2348
2349 fn overlay_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2350 let system_green = CupertinoDynamicColor::resolve(
2351 &CupertinoColors::SYSTEM_GREEN,
2352 app,
2353 self.context.context(),
2354 )
2355 .color();
2356 Some(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2357 move |states: &WidgetStates| {
2358 if states.contains(&WidgetState::Focused) {
2359 return Some(
2360 HSLColor::from_color(with_opacity(system_green, 0.80))
2361 .with_lightness(0.69)
2362 .with_saturation(0.835)
2363 .to_color(),
2364 );
2365 }
2366 Some(Colors::TRANSPARENT)
2367 },
2368 ))
2369 }
2370
2371 fn splash_radius(&self, _app: &mut App) -> Option<f64> {
2372 Some(0.0)
2373 }
2374}
2375
2376const K_CUPERTINO_FOCUS_TRACK_OUTLINE: f64 = 3.5;
2377
2378struct SwitchConfigCupertino {
2380 colors: ColorScheme,
2381}
2382
2383impl SwitchConfigCupertino {
2384 fn new(app: &mut App, context: BuildContext) -> SwitchConfigCupertino {
2386 SwitchConfigCupertino {
2387 colors: Theme::of(app, context).color_scheme.clone(),
2388 }
2389 }
2390}
2391
2392impl SwitchConfig for SwitchConfigCupertino {
2393 fn icon_color(&self) -> WidgetStatePropertyRef<Color> {
2394 let colors = self.colors.clone();
2395 <dyn WidgetStateProperty<Color>>::resolve_with(move |states: &WidgetStates| {
2396 if states.contains(&WidgetState::Disabled) {
2397 return with_opacity(colors.on_surface(), 0.38);
2398 }
2399 colors.on_primary_container()
2400 })
2401 }
2402
2403 fn active_thumb_radius(&self) -> f64 {
2404 14.0
2405 }
2406
2407 fn inactive_thumb_radius(&self) -> f64 {
2408 14.0
2409 }
2410
2411 fn pressed_thumb_radius(&self) -> f64 {
2412 14.0
2413 }
2414
2415 fn switch_height(&self) -> f64 {
2416 self.switch_min_size().height() + 8.0
2417 }
2418
2419 fn switch_height_collapsed(&self) -> f64 {
2420 self.switch_min_size().height()
2421 }
2422
2423 fn switch_width(&self) -> f64 {
2424 60.0
2425 }
2426
2427 fn thumb_radius_with_icon(&self) -> f64 {
2428 14.0
2429 }
2430
2431 fn thumb_shadow(&self) -> Option<Vec<BoxShadow>> {
2432 Some(vec![
2433 BoxShadow::new(
2434 Color::new(0x26000000),
2435 Offset::new(0.0, 3.0),
2436 8.0,
2437 0.0,
2438 BlurStyle::Normal,
2439 ),
2440 BoxShadow::new(
2441 Color::new(0x0F000000),
2442 Offset::new(0.0, 3.0),
2443 1.0,
2444 0.0,
2445 BlurStyle::Normal,
2446 ),
2447 ])
2448 }
2449
2450 fn track_height(&self) -> f64 {
2451 31.0
2452 }
2453
2454 fn track_width(&self) -> f64 {
2455 51.0
2456 }
2457
2458 fn transitional_thumb_size(&self) -> Size {
2460 Size::new(28.0, 28.0)
2461 }
2462
2463 fn toggle_duration(&self) -> u64 {
2465 140
2466 }
2467
2468 fn thumb_offset(&self) -> Option<f64> {
2470 None
2471 }
2472
2473 fn switch_min_size(&self) -> Size {
2474 Size::square(K_MIN_INTERACTIVE_DIMENSION - 8.0)
2475 }
2476}
2477
2478struct SwitchConfigM2;
2480
2481impl SwitchConfigM2 {
2482 fn new() -> SwitchConfigM2 {
2484 SwitchConfigM2
2485 }
2486}
2487
2488impl SwitchConfig for SwitchConfigM2 {
2489 fn active_thumb_radius(&self) -> f64 {
2490 10.0
2491 }
2492
2493 fn icon_color(&self) -> WidgetStatePropertyRef<Color> {
2494 <dyn WidgetStateProperty<Color>>::all(Colors::TRANSPARENT)
2495 }
2496
2497 fn inactive_thumb_radius(&self) -> f64 {
2498 10.0
2499 }
2500
2501 fn pressed_thumb_radius(&self) -> f64 {
2502 10.0
2503 }
2504
2505 fn switch_height(&self) -> f64 {
2506 self.switch_min_size().height() + 8.0
2507 }
2508
2509 fn switch_height_collapsed(&self) -> f64 {
2510 self.switch_min_size().height()
2511 }
2512
2513 fn switch_width(&self) -> f64 {
2514 self.track_width() - 2.0 * (self.track_height() / 2.0) + self.switch_min_size().width()
2515 }
2516
2517 fn thumb_radius_with_icon(&self) -> f64 {
2518 10.0
2519 }
2520
2521 fn thumb_shadow(&self) -> Option<Vec<BoxShadow>> {
2522 k_elevation_to_shadow(1).map(<[BoxShadow]>::to_vec)
2523 }
2524
2525 fn track_height(&self) -> f64 {
2526 14.0
2527 }
2528
2529 fn track_width(&self) -> f64 {
2530 33.0
2531 }
2532
2533 fn thumb_offset(&self) -> Option<f64> {
2534 Some(0.5)
2535 }
2536
2537 fn transitional_thumb_size(&self) -> Size {
2538 Size::new(20.0, 20.0)
2539 }
2540
2541 fn toggle_duration(&self) -> u64 {
2542 200
2543 }
2544
2545 fn switch_min_size(&self) -> Size {
2546 Size::square(K_MIN_INTERACTIVE_DIMENSION - 8.0)
2547 }
2548}
2549
2550struct SwitchDefaultsM2 {
2552 switch_theme_data: SwitchThemeData,
2554 context: DefaultsContext,
2555}
2556
2557impl SwitchDefaultsM2 {
2558 fn new(app: &mut App, context: BuildContext) -> SwitchDefaultsM2 {
2559 SwitchDefaultsM2 {
2560 switch_theme_data: SwitchThemeData::new(),
2561 context: DefaultsContext::with_theme(app, context),
2562 }
2563 }
2564}
2565
2566impl SwitchThemeDataGetters for SwitchDefaultsM2 {
2567 fn switch_theme_data(&self) -> &SwitchThemeData {
2568 &self.switch_theme_data
2569 }
2570
2571 fn thumb_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2572 let theme = self.context.theme(app);
2573 let colors = theme.color_scheme.clone();
2574 let is_dark = theme.brightness() == Brightness::Dark;
2575 let thumb_color = {
2576 let secondary = colors.secondary();
2577 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
2578 if states.contains(&WidgetState::Disabled) {
2579 return Some(if is_dark {
2580 Colors::GREY.shade800()
2581 } else {
2582 Colors::GREY.shade400()
2583 });
2584 }
2585 if states.contains(&WidgetState::Selected) {
2586 return Some(secondary);
2587 }
2588 Some(if is_dark {
2589 Colors::GREY.shade400()
2590 } else {
2591 Colors::GREY.shade50()
2592 })
2593 })
2594 };
2595 Some(thumb_color)
2596 }
2597
2598 fn track_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2599 let theme = self.context.theme(app);
2600 let colors = theme.color_scheme.clone();
2601 let is_dark = theme.brightness() == Brightness::Dark;
2602 let track_color = {
2603 let secondary = colors.secondary();
2604 const BLACK32: Color = Color::new(0x52000000); <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
2606 if states.contains(&WidgetState::Disabled) {
2607 return Some(if is_dark {
2608 Colors::WHITE10
2609 } else {
2610 Colors::BLACK12
2611 });
2612 }
2613 if states.contains(&WidgetState::Selected) {
2614 let active_color = secondary;
2615 return Some(active_color.with_alpha(0x80));
2616 }
2617 Some(if is_dark { Colors::WHITE30 } else { BLACK32 })
2618 })
2619 };
2620 Some(track_color)
2621 }
2622
2623 fn track_outline_color(&self, _app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2624 Some(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
2625 Colors::TRANSPARENT,
2626 )))
2627 }
2628
2629 fn material_tap_target_size(&self, app: &mut App) -> Option<MaterialTapTargetSize> {
2630 let theme = self.context.theme(app);
2631 Some(theme.material_tap_target_size)
2632 }
2633
2634 fn mouse_cursor(
2635 &self,
2636 _app: &mut App,
2637 ) -> Option<WidgetStatePropertyRef<Option<MouseCursorRef>>> {
2638 Some(<dyn WidgetStateProperty<_>>::resolve_with(
2639 |states: &WidgetStates| Some(WidgetStateMouseCursor::clickable().resolve(states)),
2640 ))
2641 }
2642
2643 fn overlay_color(&self, app: &mut App) -> Option<WidgetStatePropertyRef<Option<Color>>> {
2644 let theme = self.context.theme(app);
2645 let colors = theme.color_scheme.clone();
2646 let is_dark = theme.brightness() == Brightness::Dark;
2647 let thumb_color = {
2648 let secondary = colors.secondary();
2649 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
2650 if states.contains(&WidgetState::Disabled) {
2651 return Some(if is_dark {
2652 Colors::GREY.shade800()
2653 } else {
2654 Colors::GREY.shade400()
2655 });
2656 }
2657 if states.contains(&WidgetState::Selected) {
2658 return Some(secondary);
2659 }
2660 Some(if is_dark {
2661 Colors::GREY.shade400()
2662 } else {
2663 Colors::GREY.shade50()
2664 })
2665 })
2666 };
2667 let overlay_color = {
2668 let thumb_color = Rc::clone(&thumb_color);
2669 let (hover_color, focus_color) = (theme.hover_color, theme.focus_color);
2670 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(move |states: &WidgetStates| {
2671 if states.contains(&WidgetState::Pressed) {
2672 return thumb_color
2673 .resolve(states)
2674 .map(|color| color.with_alpha(K_RADIAL_REACTION_ALPHA));
2675 }
2676 if states.contains(&WidgetState::Hovered) {
2677 return Some(hover_color);
2678 }
2679 if states.contains(&WidgetState::Focused) {
2680 return Some(focus_color);
2681 }
2682 None
2683 })
2684 };
2685 Some(overlay_color)
2686 }
2687
2688 fn splash_radius(&self, _app: &mut App) -> Option<f64> {
2689 Some(K_RADIAL_REACTION_RADIUS)
2690 }
2691
2692 fn padding(&self, _app: &mut App) -> Option<EdgeInsetsGeometry> {
2693 Some(EdgeInsetsGeometry::ZERO)
2694 }
2695}
2696
2697#[cfg(test)]
2698pub(crate) mod tests {
2699 use std::cell::{Cell, RefCell};
2706 use std::time::Duration;
2707
2708 use waft_embedder::PointerChange;
2709 use waft_embedder::valo::Op;
2710 use waft_painting::AlignmentGeometry;
2711 use waft_rendering::{
2712 AnyRenderObject, RenderBox, RenderCustomPaint, RenderHandle, RenderObject, RenderOpacity,
2713 };
2714 use waft_services::{LogicalKeyboardKey, PhysicalKeyboardKey};
2715 use waft_widgets::{
2716 Align, AnyElement, Center, Container, FocusHighlightStrategy, FocusNode, IconData,
2717 MediaQuery, MediaQueryData, MouseRegion, StateSetter, StatefulBuilder, UnfocusDisposition,
2718 };
2719
2720 use waft_widgets::testing::{
2721 TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
2722 finds_one_widget, test_widgets, test_widgets_variant,
2723 };
2724
2725 use super::*;
2726 use crate::icons::Icons;
2727 use crate::material::Material;
2728 use crate::scaffold::Scaffold;
2729 use crate::test_support::PaintInspection;
2730 use crate::theme_data::AdaptationRef;
2731 use crate::tooltip::tests::{m2, m3, pump_app};
2732 use waft_embedder::{RRect, Radius};
2733 use waft_rendering::testing::{PaintCall, PaintedStyle, RecordedCall, assert_paints, paints};
2734
2735 fn argb(color: waft_embedder::Color) -> u32 {
2736 color.to_argb32()
2737 }
2738
2739 fn call_color(call: &RecordedCall) -> Option<u32> {
2741 match call {
2742 RecordedCall::Rect { color, .. }
2743 | RecordedCall::Circle { color, .. }
2744 | RecordedCall::RRect { color, .. }
2745 | RecordedCall::DRRect { color }
2746 | RecordedCall::Line { color, .. }
2747 | RecordedCall::Path { color, .. }
2748 | RecordedCall::Shadow { color, .. } => Some(argb(*color)),
2749 _ => None,
2750 }
2751 }
2752
2753 pub(crate) fn color_of(op: &Op) -> Option<u32> {
2755 call_color(&RecordedCall::of(op))
2756 }
2757
2758 fn bounds_of(call: &RecordedCall) -> Option<Rect> {
2760 match call {
2761 RecordedCall::Rect { rect, .. } => Some(*rect),
2762 RecordedCall::RRect { bounds, .. } | RecordedCall::Path { bounds, .. } => Some(*bounds),
2763 RecordedCall::Circle { center, radius, .. } => Some(Rect::from_ltrb(
2764 center.dx() - radius,
2765 center.dy() - radius,
2766 center.dx() + radius,
2767 center.dy() + radius,
2768 )),
2769 _ => None,
2770 }
2771 }
2772
2773 fn call_fill(call: &RecordedCall) -> Option<(u32, Rect)> {
2775 let stroke = match call {
2776 RecordedCall::Circle { stroke_width, .. }
2777 | RecordedCall::RRect { stroke_width, .. }
2778 | RecordedCall::Path { stroke_width, .. } => *stroke_width,
2779 RecordedCall::Rect { .. } => None,
2780 _ => return None,
2781 };
2782 match stroke {
2783 None => Some((call_color(call)?, bounds_of(call)?)),
2784 Some(_) => None,
2785 }
2786 }
2787
2788 fn call_stroke(call: &RecordedCall) -> Option<(u32, f32, Rect)> {
2790 match call {
2791 RecordedCall::Circle { stroke_width, .. }
2792 | RecordedCall::RRect { stroke_width, .. }
2793 | RecordedCall::Path { stroke_width, .. } => {
2794 Some((call_color(call)?, (*stroke_width)? as f32, bounds_of(call)?))
2795 }
2796 _ => None,
2797 }
2798 }
2799
2800 pub(crate) fn stroke_of(op: &Op) -> Option<(u32, f32, Rect)> {
2802 call_stroke(&RecordedCall::of(op))
2803 }
2804
2805 pub(crate) fn colors(drawn: &[Op]) -> Vec<u32> {
2807 drawn.iter().filter_map(color_of).collect()
2808 }
2809
2810 pub(crate) fn glyph_origins(drawn: &[Op]) -> Vec<(f64, f64)> {
2812 drawn
2813 .iter()
2814 .filter_map(|op| match op {
2815 Op::GlyphRun { content_bounds, .. } => {
2816 Some((f64::from(content_bounds.x), f64::from(content_bounds.y)))
2817 }
2818 _ => None,
2819 })
2820 .collect()
2821 }
2822
2823 pub(crate) fn c(color: Color) -> u32 {
2824 color.to_argb32()
2825 }
2826
2827 fn find<T: RenderObject>(app: &App, node: AnyRenderObject) -> Option<RenderHandle<T>> {
2828 if let Some(found) = node.downcast::<T>(app) {
2829 return Some(found);
2830 }
2831 let mut found = None;
2832 node.visit_children(app, &mut |child| {
2833 if found.is_none() {
2834 found = find::<T>(app, child);
2835 }
2836 });
2837 found
2838 }
2839
2840 fn switch_element(tester: &WidgetTester) -> AnyElement {
2841 *find::by_type::<Switch>()
2842 .evaluate(tester)
2843 .first()
2844 .expect("a Switch")
2845 }
2846
2847 pub(crate) fn switch_rect(tester: &WidgetTester) -> Rect {
2849 tester.get_rect(switch_element(tester))
2850 }
2851
2852 pub(crate) fn drawn(tester: &WidgetTester) -> Vec<Op> {
2855 let render = tester.render_box_of(switch_element(tester)).as_object();
2856 let mut app = tester.cell.borrow_mut();
2857 let custom = find::<RenderCustomPaint>(&app, render).expect("the switch's CustomPaint");
2858 let painter = custom.painter(&app).expect("the switch's painter");
2859 let size = custom.size(&app);
2860 let mut canvas = Canvas::new();
2861 painter.paint(&mut app, &mut canvas, size);
2862 canvas
2863 .build()
2864 .ops()
2865 .iter()
2866 .filter(|op| {
2867 matches!(
2868 RecordedCall::of(op),
2869 RecordedCall::Rect { .. }
2870 | RecordedCall::Circle { .. }
2871 | RecordedCall::RRect { .. }
2872 | RecordedCall::DRRect { .. }
2873 | RecordedCall::Line { .. }
2874 | RecordedCall::Path { .. }
2875 | RecordedCall::Shadow { .. }
2876 | RecordedCall::Clip
2877 ) || matches!(op, Op::GlyphRun { .. })
2878 })
2879 .cloned()
2880 .collect()
2881 }
2882
2883 fn opacity(tester: &WidgetTester) -> f64 {
2885 let render = tester.render_box_of(switch_element(tester)).as_object();
2886 let app = tester.cell.borrow();
2887 find::<RenderOpacity>(&app, render)
2888 .expect("the switch's Opacity")
2889 .opacity(&app)
2890 }
2891
2892 fn state(tester: &WidgetTester) -> Handle<MaterialSwitchState> {
2894 let element = *find::by_type::<MaterialSwitch>()
2895 .evaluate(tester)
2896 .first()
2897 .expect("a _MaterialSwitch");
2898 let app = tester.cell.borrow();
2899 element
2900 .state_handle::<MaterialSwitchState>(&app)
2901 .expect("a _MaterialSwitch's state")
2902 }
2903
2904 fn position(tester: &WidgetTester) -> f64 {
2906 let state = state(tester);
2907 let app = tester.cell.borrow();
2908 state.position(&app).value(&app)
2909 }
2910
2911 fn colors_of(app: &App, theme: fn(&App) -> ThemeData) -> ColorScheme {
2912 theme(app).color_scheme
2913 }
2914
2915 type Shared = Rc<Cell<bool>>;
2917
2918 fn shared(value: bool) -> Shared {
2919 Rc::new(Cell::new(value))
2920 }
2921
2922 fn host(
2925 value: &Shared,
2926 enabled: bool,
2927 make: impl Fn(bool, Option<ValueChanged<bool>>) -> Switch + 'static,
2928 ) -> WidgetRef {
2929 let value = Rc::clone(value);
2930 StatefulBuilder::new(move |_app, _context, set_state| {
2931 let on_changed = enabled.then(|| {
2932 let value = Rc::clone(&value);
2933 Rc::new(move |app: &mut App, new_value: bool| {
2934 let value = Rc::clone(&value);
2935 set_state(app, &mut move |_app| value.set(new_value));
2936 }) as ValueChanged<bool>
2937 });
2938 make(value.get(), on_changed).into_widget()
2939 })
2940 .into_widget()
2941 }
2942
2943 pub(crate) fn material_ops(tester: &WidgetTester) -> Vec<Op> {
2946 tester.nearest_material_ops(switch_element(tester))
2947 }
2948
2949 #[track_caller]
2951 fn assert_paints_because(ops: &[Op], pattern: &[PaintCall], reason: &str) {
2952 if let Err(mismatch) = paints(ops, pattern) {
2953 panic!("{reason}: {mismatch}");
2954 }
2955 }
2956
2957 fn rrect(rrect: Option<RRect>, color: Option<Color>, style: Option<PaintedStyle>) -> PaintCall {
2959 PaintCall::RRect {
2960 rrect,
2961 color,
2962 style,
2963 has_mask_filter: None,
2964 }
2965 }
2966
2967 fn ltrbr(left: f64, top: f64, right: f64, bottom: f64, radius: f64) -> RRect {
2969 RRect::from_ltrbr(left, top, right, bottom, Radius::circular(radius))
2970 }
2971
2972 fn m2_track(color: Color) -> PaintCall {
2974 rrect(Some(ltrbr(13.0, 17.0, 46.0, 31.0, 7.0)), Some(color), None)
2975 }
2976
2977 fn m3_track(color: Color, style: Option<PaintedStyle>) -> PaintCall {
2979 rrect(Some(ltrbr(4.0, 8.0, 56.0, 40.0, 16.0)), Some(color), style)
2980 }
2981
2982 fn m3_outline(color: Color) -> PaintCall {
2984 rrect(
2985 Some(ltrbr(5.0, 9.0, 55.0, 39.0, 16.0)),
2986 Some(color),
2987 Some(PaintedStyle::Stroke(None)),
2988 )
2989 }
2990
2991 fn m2_pattern(track: Color, reaction: Option<Color>, thumb: Color) -> Vec<PaintCall> {
2994 let mut pattern = vec![m2_track(track)];
2995 pattern.extend(reaction.map(|color| PaintCall::circle(Some(color))));
2996 pattern.extend([
2997 PaintCall::rrect(Some(Color::new(0x33000000))),
2998 PaintCall::rrect(Some(Color::new(0x24000000))),
2999 PaintCall::rrect(Some(Color::new(0x1f000000))),
3000 PaintCall::rrect(Some(thumb)),
3001 ]);
3002 pattern
3003 }
3004
3005 fn cupertino_pattern(track: PaintCall, thumb: PaintCall) -> Vec<PaintCall> {
3009 vec![
3010 track,
3011 PaintCall::rrect(Some(Color::new(0x26000000))),
3012 PaintCall::rrect(Some(Color::new(0x0f000000))),
3013 PaintCall::rrect(Some(Color::new(0x0a000000))), thumb,
3015 ]
3016 }
3017
3018 fn in_material(direction: TextDirection, child: WidgetRef) -> WidgetRef {
3020 Directionality::new(direction, Material::new().child(Center::new().child(child)))
3021 .into_widget()
3022 }
3023
3024 #[test]
3030 fn an_adaptive_switch_given_its_colors_does_not_depend_on_high_contrast() {
3031 test_widgets(|_| {
3032 let built_child = |tester: &WidgetTester| -> WidgetRef {
3033 let element = *find::by_type::<Switch>()
3034 .evaluate(tester)
3035 .first()
3036 .expect("a switch");
3037 let app = tester.cell.borrow();
3038 let material_switch = element.children(&app)[0];
3039 material_switch.children(&app)[0].widget(&app).clone()
3040 };
3041 let pump = |tester: &mut WidgetTester, high_contrast: bool, switch: &WidgetRef| {
3042 let home = in_material(
3043 TextDirection::Ltr,
3044 MediaQuery::new(
3045 MediaQueryData::new().high_contrast(high_contrast),
3046 switch.clone(),
3047 )
3048 .into_widget(),
3049 );
3050 pump_app(tester, m3, move |_app| home);
3051 };
3052 let mut tester = WidgetTester::on(TargetPlatform::IOS);
3053 let tester = &mut tester;
3054 let switch = Switch::adaptive(true, ignore())
3055 .track_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3056 Colors::RED.primary(),
3057 )))
3058 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3059 Colors::BLUE.primary(),
3060 )))
3061 .into_widget();
3062 pump(tester, false, &switch);
3063 let built = built_child(tester);
3064 pump(tester, true, &switch);
3065 assert!(waft_widgets::same_widget(&built, &built_child(tester)));
3066
3067 let switch = Switch::adaptive(true, ignore()).into_widget();
3069 pump(tester, false, &switch);
3070 let built = built_child(tester);
3071 pump(tester, true, &switch);
3072 assert!(!waft_widgets::same_widget(&built, &built_child(tester)));
3073 });
3074 }
3075
3076 pub(crate) fn ignore() -> Option<ValueChanged<bool>> {
3078 Some(Rc::new(|_app: &mut App, _value: bool| {}))
3079 }
3080
3081 fn pump_host(
3084 tester: &mut WidgetTester,
3085 theme: impl FnOnce(&App) -> ThemeData,
3086 direction: TextDirection,
3087 value: &Shared,
3088 enabled: bool,
3089 make: impl Fn(bool, Option<ValueChanged<bool>>) -> Switch + 'static,
3090 ) {
3091 let home = in_material(direction, host(value, enabled, make));
3092 pump_app(tester, theme, move |_app| home);
3093 }
3094
3095 fn pump_switch(
3097 tester: &mut WidgetTester,
3098 theme: impl FnOnce(&App) -> ThemeData,
3099 switch: Switch,
3100 ) {
3101 let home = in_material(TextDirection::Ltr, switch.into_widget());
3102 pump_app(tester, theme, move |_app| home);
3103 }
3104
3105 pub(crate) fn center(tester: &WidgetTester) -> Offset {
3106 switch_rect(tester).center()
3107 }
3108
3109 pub(crate) fn tap(tester: &mut WidgetTester) {
3111 let at = center(tester);
3112 tester.tap_at(at, 1);
3113 }
3114
3115 fn drag(tester: &mut WidgetTester, dx: f64) {
3117 let at = center(tester);
3118 tester.drag_from(at, Offset::new(dx, 0.0), 1);
3119 }
3120
3121 pub(crate) fn press(tester: &mut WidgetTester) -> TestPointer {
3123 let at = center(tester);
3124 let mut touch = TestPointer::touch(2);
3125 tester.down(&mut touch, at);
3126 touch
3127 }
3128
3129 pub(crate) fn hover(tester: &mut WidgetTester) -> TestPointer {
3131 let mut mouse = TestPointer::mouse(1, 0);
3132 tester.add_pointer(&mut mouse, Offset::ZERO);
3133 let at = center(tester);
3134 tester.move_to(&mut mouse, at, false);
3135 mouse
3136 }
3137
3138 fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
3139 FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
3140 }
3141
3142 fn adaptive_on(platform: TargetPlatform) -> impl FnOnce(&App) -> ThemeData {
3143 move |app| ThemeData::builder().platform(platform).build(app)
3144 }
3145
3146 const MOBILE: [TargetPlatform; 2] = [TargetPlatform::Android, TargetPlatform::Fuchsia];
3147 const CUPERTINO_PLATFORMS: [TargetPlatform; 2] = [TargetPlatform::IOS, TargetPlatform::MacOS];
3148 const ALL_PLATFORMS: [TargetPlatform; 6] = [
3149 TargetPlatform::Android,
3150 TargetPlatform::Fuchsia,
3151 TargetPlatform::IOS,
3152 TargetPlatform::Linux,
3153 TargetPlatform::MacOS,
3154 TargetPlatform::Windows,
3155 ];
3156
3157 pub(crate) const M2_SHADOWS: [u32; 3] = [0x33000000, 0x24000000, 0x1f000000];
3158
3159 #[test]
3160 fn a_tap_toggles_the_switch() {
3161 test_widgets(|tester| {
3162 let value = shared(false);
3163 pump_host(
3164 tester,
3165 m3,
3166 TextDirection::Ltr,
3167 &value,
3168 true,
3169 |value, on_changed| {
3170 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3171 },
3172 );
3173 assert!(!value.get());
3174 tap(tester);
3175 assert!(value.get());
3176 });
3177 }
3178
3179 #[test]
3180 fn the_switch_size_follows_the_theme_material_tap_target_size() {
3181 test_widgets(|tester| {
3182 for (theme, padded, shrink_wrapped) in [
3186 (
3187 m3 as fn(&App) -> ThemeData,
3188 Size::new(60.0, 48.0),
3189 Size::new(60.0, 40.0),
3190 ),
3191 (m2, Size::new(59.0, 48.0), Size::new(59.0, 40.0)),
3192 ] {
3193 for (size, expected) in [
3194 (MaterialTapTargetSize::Padded, padded),
3195 (MaterialTapTargetSize::ShrinkWrap, shrink_wrapped),
3196 ] {
3197 let data = theme(&tester.cell.borrow())
3198 .copy_with()
3199 .material_tap_target_size(size)
3200 .build();
3201 let switch =
3202 Switch::new(true, ignore()).drag_start_behavior(DragStartBehavior::Down);
3203 tester.pump_widget(Theme::new(
3204 data,
3205 in_material(TextDirection::Ltr, switch.into_widget()),
3206 ));
3207 assert_eq!(switch_rect(tester).size(), expected, "{size:?}");
3208 }
3209 }
3210 });
3211 }
3212
3213 #[test]
3214 fn a_drag_toggles_the_switch_toward_its_direction() {
3215 test_widgets(|tester| {
3216 let value = shared(false);
3217 pump_host(
3218 tester,
3219 m3,
3220 TextDirection::Ltr,
3221 &value,
3222 true,
3223 |value, on_changed| {
3224 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3225 },
3226 );
3227 assert!(!value.get());
3228 drag(tester, -30.0);
3229 assert!(!value.get());
3230 drag(tester, 30.0);
3231 assert!(value.get());
3232 tester.pump();
3233 drag(tester, 30.0);
3234 assert!(value.get());
3235 tester.pump();
3236 drag(tester, -30.0);
3237 assert!(!value.get());
3238 });
3239 }
3240
3241 #[test]
3242 fn a_drag_toggles_the_switch_with_either_drag_start_behavior() {
3243 test_widgets(|tester| {
3244 let value = shared(false);
3245 pump_host(
3246 tester,
3247 m3,
3248 TextDirection::Ltr,
3249 &value,
3250 true,
3251 |value, on_changed| {
3252 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3253 },
3254 );
3255 assert!(!value.get());
3256 drag(tester, -30.0);
3257 assert!(!value.get());
3258 drag(tester, 30.0);
3259 assert!(value.get());
3260 tester.pump();
3261 drag(tester, 30.0);
3262 assert!(value.get());
3263 tester.pump();
3264 drag(tester, -30.0);
3265 assert!(!value.get());
3266
3267 pump_host(tester, m3, TextDirection::Ltr, &value, true, Switch::new);
3268 tester.pump_and_settle();
3269 let start = center(tester);
3270 for (dx, before_up, after_up) in [
3271 (20.0, false, true),
3272 (20.0, true, true),
3273 (-20.0, true, false),
3274 ] {
3275 let mut gesture = TestPointer::touch(3);
3276 tester.down(&mut gesture, start);
3277 tester.move_to(&mut gesture, start + Offset::new(dx, 0.0), true);
3280 tester.move_to(&mut gesture, start + Offset::new(2.0 * dx, 0.0), true);
3281 assert_eq!(value.get(), before_up, "{dx}");
3282 tester.up(&gesture);
3283 assert_eq!(value.get(), after_up, "{dx}");
3284 tester.pump();
3285 }
3286 });
3287 }
3288
3289 #[test]
3290 fn a_right_to_left_switch_turns_on_toward_the_left() {
3291 test_widgets(|tester| {
3292 let value = shared(false);
3293 pump_host(
3294 tester,
3295 m3,
3296 TextDirection::Rtl,
3297 &value,
3298 true,
3299 |value, on_changed| {
3300 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3301 },
3302 );
3303 drag(tester, 30.0);
3304 assert!(!value.get());
3305 drag(tester, -30.0);
3306 assert!(value.get());
3307 tester.pump();
3308 drag(tester, -30.0);
3309 assert!(value.get());
3310 tester.pump();
3311 drag(tester, 30.0);
3312 assert!(!value.get());
3313 });
3314 }
3315
3316 #[test]
3317 fn an_m2_switch_has_its_default_colors_when_enabled() {
3318 test_widgets(|tester| {
3319 let value = shared(false);
3320 pump_host(
3321 tester,
3322 m2,
3323 TextDirection::Rtl,
3324 &value,
3325 true,
3326 |value, on_changed| {
3327 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3328 },
3329 );
3330 assert_paints(
3332 &material_ops(tester),
3333 &m2_pattern(Color::new(0x52000000), None, Colors::GREY.shade50()),
3334 );
3335 drag(tester, -30.0);
3336 tester.pump();
3337 assert_paints(
3339 &material_ops(tester),
3340 &m2_pattern(Color::new(0x802196f3), None, Color::new(0xff2196f3)),
3341 );
3342 });
3343 }
3344
3345 #[test]
3348 fn an_m3_switch_has_its_default_colors_when_enabled() {
3349 for adaptive in [false, true] {
3350 test_widgets(|tester| {
3351 let colors_ = colors_of(&tester.cell.borrow(), m3);
3352 let value = shared(false);
3353 pump_host(
3354 tester,
3355 m3,
3356 TextDirection::Rtl,
3357 &value,
3358 true,
3359 move |value, on_changed| {
3360 let switch = if adaptive {
3361 Switch::adaptive(value, on_changed)
3362 } else {
3363 Switch::new(value, on_changed)
3364 };
3365 switch.drag_start_behavior(DragStartBehavior::Down)
3366 },
3367 );
3368 assert_paints(
3370 &material_ops(tester),
3371 &[
3372 PaintCall::Save,
3373 m3_track(
3374 colors_.surface_container_highest(),
3375 Some(PaintedStyle::Fill),
3376 ),
3377 m3_outline(colors_.outline()),
3378 PaintCall::rrect(Some(colors_.outline())), ],
3380 );
3381 drag(tester, -30.0);
3382 tester.pump();
3383 assert_paints(
3385 &material_ops(tester),
3386 &[
3387 PaintCall::Save,
3388 m3_track(colors_.primary(), Some(PaintedStyle::Fill)),
3389 PaintCall::rrect(Some(colors_.on_primary())), ],
3392 );
3393 });
3394 }
3395 }
3396
3397 #[test]
3398 fn an_m2_switch_has_its_default_colors_when_disabled() {
3399 for value in [false, true] {
3400 test_widgets(|tester| {
3401 let home = Directionality::new(
3402 TextDirection::Rtl,
3403 Material::new().child(Center::new().child(Switch::new(value, None))),
3404 )
3405 .into_widget();
3406 pump_app(tester, m2, move |_app| home);
3407 assert_paints(
3409 &material_ops(tester),
3410 &m2_pattern(Colors::BLACK12, None, Colors::GREY.shade400()),
3411 );
3412 });
3413 }
3414 }
3415
3416 #[test]
3417 fn an_m3_switch_has_its_default_colors_when_disabled() {
3418 test_widgets(|tester| {
3419 let colors_ = colors_of(&tester.cell.borrow(), m3);
3420 let home = in_material(TextDirection::Rtl, Switch::new(false, None).into_widget());
3421 pump_app(tester, m3, move |_app| home);
3422 assert_paints(
3424 &material_ops(tester),
3425 &[
3426 PaintCall::Save,
3427 m3_track(
3428 with_opacity(colors_.surface_container_highest(), 0.12),
3429 Some(PaintedStyle::Fill),
3430 ),
3431 m3_outline(with_opacity(colors_.on_surface(), 0.12)),
3432 PaintCall::rrect(Some(Color::alpha_blend(
3434 with_opacity(colors_.on_surface(), 0.38),
3435 colors_.surface(),
3436 ))),
3437 ],
3438 );
3439
3440 let home = in_material(TextDirection::Rtl, Switch::new(true, None).into_widget());
3441 pump_app(tester, m3, move |_app| home);
3442 tester.pump_and_settle();
3444 assert_paints(
3446 &material_ops(tester),
3447 &[
3448 PaintCall::Save,
3449 m3_track(
3450 with_opacity(colors_.on_surface(), 0.12),
3451 Some(PaintedStyle::Fill),
3452 ),
3453 PaintCall::rrect(Some(colors_.surface())), ],
3456 );
3457 });
3458 }
3459
3460 pub(crate) fn circles(painted: &[Op], radius: f64) -> Vec<u32> {
3463 painted
3464 .iter()
3465 .filter_map(|op| {
3466 let (color, rect) = call_fill(&RecordedCall::of(op))?;
3467 ((rect.width() - 2.0 * radius).abs() < 1e-6
3468 && (rect.height() - 2.0 * radius).abs() < 1e-6)
3469 .then_some(color)
3470 })
3471 .collect()
3472 }
3473
3474 #[test]
3475 fn the_default_overlay_resolves_the_focused_then_the_hovered_state() {
3476 for (theme, use_material3) in [(m2 as fn(&App) -> ThemeData, false), (m3, true)] {
3477 test_widgets(|tester| {
3478 let data = theme(&tester.cell.borrow());
3479 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
3480 let node = focus_node(tester);
3481 let home = Scaffold::new()
3482 .body(Switch::new(true, ignore()).focus_node(node.clone()))
3483 .into_widget();
3484 pump_app(tester, theme, move |_app| home);
3485
3486 node.request_focus(&mut tester.cell.borrow_mut(), None);
3488 tester.pump_and_settle();
3489 let (focused, hovered) = if use_material3 {
3490 (
3491 with_opacity(data.color_scheme.primary(), 0.1),
3492 with_opacity(data.color_scheme.primary(), 0.08),
3493 )
3494 } else {
3495 (data.focus_color, data.hover_color)
3496 };
3497 assert_paints(&material_ops(tester), &[PaintCall::circle(Some(focused))]);
3498
3499 hover(tester);
3501 tester.pump_and_settle();
3502 assert_paints(&material_ops(tester), &[PaintCall::circle(Some(hovered))]);
3503 });
3504 }
3505 }
3506
3507 #[test]
3508 #[allow(deprecated)]
3509 fn an_m2_switch_takes_the_colors_it_is_given() {
3510 test_widgets(|tester| {
3511 let value = shared(false);
3512 pump_host(
3513 tester,
3514 m2,
3515 TextDirection::Rtl,
3516 &value,
3517 true,
3518 |value, on_changed| {
3519 Switch::new(value, on_changed)
3520 .drag_start_behavior(DragStartBehavior::Down)
3521 .active_color(Colors::RED.shade500())
3522 .active_track_color(Colors::GREEN.shade500())
3523 .inactive_thumb_color(Colors::YELLOW.shade500())
3524 .inactive_track_color(Colors::BLUE.shade500())
3525 },
3526 );
3527 assert_paints(
3528 &material_ops(tester),
3529 &m2_pattern(Colors::BLUE.shade500(), None, Colors::YELLOW.shade500()),
3530 );
3531 drag(tester, -30.0);
3532 tester.pump();
3533 assert_paints(
3534 &material_ops(tester),
3535 &m2_pattern(Colors::GREEN.shade500(), None, Colors::RED.shade500()),
3536 );
3537 });
3538 }
3539
3540 #[test]
3541 #[allow(deprecated)]
3542 fn an_m3_switch_takes_the_colors_it_is_given() {
3543 test_widgets(|tester| {
3544 let colors_ = colors_of(&tester.cell.borrow(), m3);
3545 let value = shared(false);
3546 pump_host(
3547 tester,
3548 m3,
3549 TextDirection::Rtl,
3550 &value,
3551 true,
3552 |value, on_changed| {
3553 Switch::new(value, on_changed)
3554 .drag_start_behavior(DragStartBehavior::Down)
3555 .active_color(Colors::RED.shade500())
3556 .active_track_color(Colors::GREEN.shade500())
3557 .inactive_thumb_color(Colors::YELLOW.shade500())
3558 .inactive_track_color(Colors::BLUE.shade500())
3559 },
3560 );
3561 assert_paints(
3562 &material_ops(tester),
3563 &[
3564 m3_track(Colors::BLUE.shade500(), Some(PaintedStyle::Fill)),
3565 rrect(
3566 None,
3567 Some(colors_.outline()),
3568 Some(PaintedStyle::Stroke(None)),
3569 ),
3570 PaintCall::rrect(Some(Colors::YELLOW.shade500())), ],
3572 );
3573 drag(tester, -30.0);
3574 tester.pump();
3575 assert_paints(
3576 &material_ops(tester),
3577 &[
3578 m3_track(Colors::GREEN.shade500(), Some(PaintedStyle::Fill)),
3579 PaintCall::rrect(Some(Colors::RED.shade500())), ],
3582 );
3583 });
3584 }
3585
3586 #[test]
3587 fn a_drag_ends_after_its_animation_completes() {
3588 test_widgets(|tester| {
3589 let value = shared(false);
3590 pump_host(
3591 tester,
3592 m3,
3593 TextDirection::Ltr,
3594 &value,
3595 true,
3596 |value, on_changed| {
3597 Switch::new(value, on_changed).drag_start_behavior(DragStartBehavior::Down)
3598 },
3599 );
3600 assert!(!value.get());
3601 let switch_rect = switch_rect(tester);
3602 let mut gesture = TestPointer::touch(1);
3603 tester.down(&mut gesture, switch_rect.center_left());
3604 tester.pump();
3605 let to = gesture.position + Offset::new(switch_rect.width(), 0.0);
3606 tester.move_to(&mut gesture, to, true);
3607 tester.pump();
3608 tester.up(&gesture);
3609 tester.pump();
3610 tester.pump_by(Duration::from_millis(200));
3611 assert!(value.get());
3612 assert!(!tester.has_running_animations());
3613 });
3614 }
3615
3616 #[test]
3617 fn a_vetoed_drag_animates_the_thumb_back() {
3618 test_widgets(|tester| {
3619 let value = Rc::new(Cell::new(false));
3620 let home = {
3621 let value = Rc::clone(&value);
3622 in_material(
3623 TextDirection::Ltr,
3624 StatefulBuilder::new(move |_app, _context, set_state| {
3625 let shared = Rc::clone(&value);
3626 let on_changed: ValueChanged<bool> =
3627 Rc::new(move |app: &mut App, new_value: bool| {
3628 let shared = Rc::clone(&shared);
3629 set_state(app, &mut move |_app| {
3630 shared.set(shared.get() || new_value)
3631 });
3632 });
3633 Switch::new(value.get(), Some(on_changed))
3634 .drag_start_behavior(DragStartBehavior::Down)
3635 .into_widget()
3636 })
3637 .into_widget(),
3638 )
3639 };
3640 pump_app(tester, m3, move |_app| home);
3641 let slop = waft_gestures::K_TOUCH_SLOP;
3642
3643 let start = center(tester);
3645 let mut gesture = TestPointer::touch(1);
3646 tester.down(&mut gesture, start);
3647 tester.move_to(&mut gesture, start + Offset::new(slop + 0.1, 0.0), true);
3648 tester.pump();
3649 let at = gesture.position + Offset::new(-slop + 5.1, 0.0);
3650 tester.move_to(&mut gesture, at, true);
3651 tester.pump();
3652 tester.up(&gesture);
3653 tester.pump();
3654 assert!(!value.get());
3655 assert!(position(tester) < 0.5);
3656 tester.pump();
3657 tester.pump_and_settle();
3658 assert!(!value.get());
3659 assert_eq!(position(tester), 0.0);
3660
3661 let mut gesture = TestPointer::touch(2);
3663 tester.down(&mut gesture, start);
3664 tester.move_to(&mut gesture, start + Offset::new(slop + 0.1, 0.0), true);
3665 tester.pump();
3666 tester.up(&gesture);
3667 tester.pump();
3668 assert!(value.get());
3669 assert!(position(tester) > 0.5);
3670 tester.pump();
3671 tester.pump_and_settle();
3672 assert!(value.get());
3673 assert_eq!(position(tester), 1.0);
3674
3675 let mut gesture = TestPointer::touch(3);
3677 tester.down(&mut gesture, start);
3678 tester.move_to(&mut gesture, start + Offset::new(-slop - 0.1, 0.0), true);
3679 tester.pump();
3680 tester.up(&gesture);
3681 tester.pump();
3682 assert!(value.get());
3683 assert!(position(tester) < 0.5);
3684 tester.pump();
3685 tester.pump_and_settle();
3686 assert!(value.get());
3687 assert_eq!(position(tester), 1.0);
3688 });
3689 }
3690
3691 #[test]
3692 #[allow(deprecated)]
3693 fn an_adaptive_switch_is_a_material_switch_that_toggles_on_every_platform() {
3694 test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
3695 let platform = tester.target_platform();
3696 const ACTIVE_TRACK_COLOR: Color = Color::new(0xffff1200);
3697 const INACTIVE_TRACK_COLOR: Color = Color::new(0xffff12ff);
3698 const THUMB_COLOR: Color = Color::new(0xffffff00);
3699 const FOCUS_COLOR: Color = Color::new(0xff00ff00);
3700
3701 let value = shared(false);
3702 let home = host(&value, true, |value, on_changed| {
3703 Switch::adaptive(value, on_changed)
3704 .active_color(ACTIVE_TRACK_COLOR)
3705 .inactive_track_color(INACTIVE_TRACK_COLOR)
3706 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3707 THUMB_COLOR,
3708 )))
3709 .focus_color(FOCUS_COLOR)
3710 });
3711 let home = Material::new()
3712 .child(Center::new().child(home))
3713 .into_widget();
3714 pump_app(tester, adaptive_on(platform), move |_app| home);
3715 expect(tester, &find::by_type::<Switch>(), finds_one_widget());
3716 assert!(
3717 find::by_type::<waft_cupertino::CupertinoSwitch>()
3718 .evaluate(tester)
3719 .is_empty()
3720 );
3721 tester.widget(switch_element(tester), |switch: &Switch| {
3722 assert_eq!(switch.active_color, Some(ACTIVE_TRACK_COLOR));
3723 assert_eq!(switch.inactive_track_color, Some(INACTIVE_TRACK_COLOR));
3724 assert_eq!(
3725 switch
3726 .thumb_color
3727 .as_ref()
3728 .and_then(|color| color.resolve(&WidgetStates::new())),
3729 Some(THUMB_COLOR)
3730 );
3731 assert_eq!(switch.focus_color, Some(FOCUS_COLOR));
3732 });
3733 assert!(!value.get(), "on {platform:?}");
3734 tap(tester);
3735 assert!(value.get(), "on {platform:?}");
3736 });
3737 }
3738
3739 #[derive(Clone, Default)]
3741 struct AdaptiveSwitch {
3742 disabled: bool,
3743 off: bool,
3744 autofocus: bool,
3745 focus_node: Option<FocusNodeRef>,
3746 focus_color: Option<Color>,
3747 overall_switch_theme_data: Option<SwitchThemeData>,
3748 switch_theme_data: Option<SwitchThemeData>,
3749 switch_theme_adaptation: bool,
3750 }
3751
3752 #[derive(Debug)]
3754 struct TestSwitchThemeAdaptation;
3755
3756 impl Adaptation<SwitchThemeData> for TestSwitchThemeAdaptation {
3757 fn adapt(&self, theme: &ThemeData, default_value: SwitchThemeData) -> SwitchThemeData {
3758 match theme.platform {
3759 TargetPlatform::Android
3760 | TargetPlatform::Fuchsia
3761 | TargetPlatform::Windows
3762 | TargetPlatform::Linux => default_value,
3763 TargetPlatform::IOS | TargetPlatform::MacOS => SwitchThemeData::new()
3764 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3765 Colors::LIGHT_GREEN.primary(),
3766 )))
3767 .track_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3768 Colors::DEEP_PURPLE.primary(),
3769 ))),
3770 }
3771 }
3772 }
3773
3774 impl AdaptiveSwitch {
3775 fn pump(self, tester: &mut WidgetTester, platform: TargetPlatform) {
3776 let mut adaptive_switch =
3777 Switch::adaptive(!self.off, if self.disabled { None } else { ignore() })
3778 .autofocus(self.autofocus);
3779 if let Some(focus_node) = self.focus_node {
3780 adaptive_switch = adaptive_switch.focus_node(focus_node);
3781 }
3782 if let Some(focus_color) = self.focus_color {
3783 adaptive_switch = adaptive_switch.focus_color(focus_color);
3784 }
3785 let child = match self.switch_theme_data {
3786 None => adaptive_switch.into_widget(),
3787 Some(data) => SwitchTheme::new(data, adaptive_switch).into_widget(),
3788 };
3789 let home = Material::new()
3790 .child(Center::new().child(child))
3791 .into_widget();
3792 let (overall, adaptation) =
3793 (self.overall_switch_theme_data, self.switch_theme_adaptation);
3794 pump_app(
3795 tester,
3796 move |app| {
3797 let mut builder = ThemeData::builder().platform(platform);
3798 if let Some(overall) = overall {
3799 builder = builder.switch_theme(overall);
3800 }
3801 if adaptation {
3802 builder = builder
3803 .adaptations(vec![AdaptationRef::new(TestSwitchThemeAdaptation)]);
3804 }
3805 builder.build(app)
3806 },
3807 move |_app| home,
3808 );
3809 }
3810 }
3811
3812 #[test]
3813 fn an_adaptive_cupertino_switch_shows_the_default_mouse_cursor() {
3814 test_widgets(|_| {
3815 let platform_cursor: MouseCursorRef = if K_IS_WEB {
3816 SystemMouseCursors::CLICK.into()
3817 } else {
3818 SystemMouseCursors::BASIC.into()
3819 };
3820 let mut tester = WidgetTester::on(TargetPlatform::IOS);
3823 let tester = &mut tester;
3824 for platform in CUPERTINO_PLATFORMS {
3825 AdaptiveSwitch {
3826 off: true,
3827 ..AdaptiveSwitch::default()
3828 }
3829 .pump(tester, platform);
3830 assert_eq!(switch_rect(tester).size(), Size::new(60.0, 48.0));
3831 let mut mouse = TestPointer::mouse(1, 0);
3832 let at = center(tester);
3833 tester.add_pointer(&mut mouse, at);
3834 tester.pump();
3835 tester.move_to(&mut mouse, at, false);
3836 assert_eq!(Some(tester.active_cursor(1)), Some(platform_cursor.clone()));
3837
3838 AdaptiveSwitch::default().pump(tester, platform);
3839 assert_eq!(Some(tester.active_cursor(1)), Some(platform_cursor.clone()));
3840
3841 AdaptiveSwitch {
3843 disabled: true,
3844 off: true,
3845 ..AdaptiveSwitch::default()
3846 }
3847 .pump(tester, platform);
3848 assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
3849 tester.send(&mouse, PointerChange::Remove);
3850 tester.pump();
3851 }
3852 });
3853 }
3854
3855 #[test]
3856 fn an_adaptive_cupertino_switch_has_its_default_thumb_and_track_colors_and_size() {
3857 for platform in CUPERTINO_PLATFORMS {
3858 test_widgets(|_| {
3859 const THUMB_COLOR: Color = Colors::WHITE;
3860 const INACTIVE_TRACK_COLOR: Color = Color::from_argb(40, 120, 120, 128);
3862 const ACTIVE_TRACK_COLOR: Color = Color::from_argb(255, 52, 199, 89);
3864 let (track, inactive_thumb, active_thumb) = if platform == TargetPlatform::IOS {
3866 (
3867 ltrbr(4.5, 8.5, 55.5, 39.5, 15.5),
3868 ltrbr(6.0, 10.0, 34.0, 38.0, 14.0),
3869 ltrbr(26.0, 10.0, 54.0, 38.0, 14.0),
3870 )
3871 } else {
3872 (
3873 ltrbr(4.5, 4.5, 55.5, 35.5, 15.5),
3874 ltrbr(6.0, 6.0, 34.0, 34.0, 14.0),
3875 ltrbr(26.0, 6.0, 54.0, 34.0, 14.0),
3876 )
3877 };
3878 for (disabled, off, expected_opacity) in [
3879 (false, true, 1.0),
3880 (false, false, 1.0),
3881 (true, true, 0.5),
3882 (true, false, 0.5),
3883 ] {
3884 let mut tester = WidgetTester::on(platform);
3885 let tester = &mut tester;
3886 AdaptiveSwitch {
3887 disabled,
3888 off,
3889 ..AdaptiveSwitch::default()
3890 }
3891 .pump(tester, platform);
3892 tester.pump();
3893 let (track_color, thumb) = if off {
3894 (INACTIVE_TRACK_COLOR, inactive_thumb)
3895 } else {
3896 (ACTIVE_TRACK_COLOR, active_thumb)
3897 };
3898 assert_paints(
3900 &material_ops(tester),
3901 &cupertino_pattern(
3902 rrect(Some(track), Some(track_color), None),
3903 rrect(Some(thumb), Some(THUMB_COLOR), None),
3904 ),
3905 );
3906 assert_eq!(opacity(tester), expected_opacity);
3907 }
3908 });
3909 }
3910 }
3911
3912 #[test]
3913 fn an_adaptive_cupertino_switch_ignores_the_switch_themes() {
3914 for overall in [true, false] {
3915 test_widgets(|tester| {
3916 const DEFAULT_THUMB_COLOR: Color = Colors::WHITE;
3917 const DEFAULT_INACTIVE_TRACK_COLOR: Color = Color::from_argb(40, 120, 120, 128);
3918 const DEFAULT_ACTIVE_TRACK_COLOR: Color = Color::from_argb(255, 52, 199, 89);
3919 let updated_thumb_color = Colors::RED.primary();
3920 let updated_track_color = Colors::GREEN.primary();
3921 let theme = SwitchThemeData::new()
3922 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3923 updated_thumb_color,
3924 )))
3925 .track_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3926 updated_track_color,
3927 )));
3928 let with_theme = |switch: AdaptiveSwitch| {
3931 if overall {
3932 AdaptiveSwitch {
3933 overall_switch_theme_data: Some(theme.clone()),
3934 ..switch
3935 }
3936 } else {
3937 AdaptiveSwitch {
3938 switch_theme_data: Some(theme.clone()),
3939 ..switch
3940 }
3941 }
3942 };
3943 for platform in CUPERTINO_PLATFORMS {
3944 for (disabled, off, track) in [
3945 (false, false, DEFAULT_ACTIVE_TRACK_COLOR),
3946 (false, true, DEFAULT_INACTIVE_TRACK_COLOR),
3947 (true, true, DEFAULT_INACTIVE_TRACK_COLOR),
3948 ] {
3949 let mut tester = WidgetTester::on(platform);
3950 let tester = &mut tester;
3951 with_theme(AdaptiveSwitch {
3952 disabled,
3953 off,
3954 ..AdaptiveSwitch::default()
3955 })
3956 .pump(tester, platform);
3957 assert_paints(
3959 &material_ops(tester),
3960 &cupertino_pattern(
3961 PaintCall::rrect(Some(track)),
3962 PaintCall::rrect(Some(DEFAULT_THUMB_COLOR)),
3963 ),
3964 );
3965 }
3966 }
3967
3968 with_theme(AdaptiveSwitch::default()).pump(tester, TargetPlatform::Android);
3969 assert_paints(
3971 &material_ops(tester),
3972 &[
3973 PaintCall::rrect(Some(Color::new(updated_track_color.to_argb32()))),
3974 PaintCall::rrect(Some(Color::new(updated_thumb_color.to_argb32()))),
3976 ],
3977 );
3978 });
3979 }
3980 }
3981
3982 #[test]
3983 fn an_adaptation_overrides_the_adaptive_switch_theme_on_ios_and_macos_only() {
3984 test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
3985 let platform = tester.target_platform();
3986 let switch_theme_data = SwitchThemeData::new()
3987 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3988 Colors::YELLOW.primary(),
3989 )))
3990 .track_color(<dyn WidgetStateProperty<Option<Color>>>::all(Some(
3991 Colors::BROWN.primary(),
3992 )));
3993
3994 AdaptiveSwitch {
3995 switch_theme_data: Some(switch_theme_data.clone()),
3996 switch_theme_adaptation: true,
3997 ..AdaptiveSwitch::default()
3998 }
3999 .pump(tester, platform);
4000 if CUPERTINO_PLATFORMS.contains(&platform) {
4001 assert_paints(
4003 &material_ops(tester),
4004 &[
4005 PaintCall::rrect(Some(Color::new(
4006 Colors::DEEP_PURPLE.primary().to_argb32(),
4007 ))),
4008 PaintCall::rrect(None),
4009 PaintCall::rrect(None),
4010 PaintCall::rrect(None),
4011 PaintCall::rrect(Some(Color::new(
4012 Colors::LIGHT_GREEN.primary().to_argb32(),
4013 ))),
4014 ],
4015 );
4016 } else {
4017 assert_paints(
4019 &material_ops(tester),
4020 &[
4021 PaintCall::rrect(Some(Color::new(Colors::BROWN.primary().to_argb32()))),
4022 PaintCall::rrect(Some(Color::new(Colors::YELLOW.primary().to_argb32()))),
4024 ],
4025 );
4026 }
4027 });
4028 }
4029
4030 #[test]
4031 fn an_adaptive_cupertino_switch_has_its_default_focus_color() {
4032 test_widgets(|_| {
4033 for (focus_color, ring) in [
4034 (None, Color::new(0xcc6ef28f)),
4035 (
4036 Some(Colors::RED.primary()),
4037 Color::new(Colors::RED.primary().to_argb32()),
4038 ),
4039 ] {
4040 let mut tester = WidgetTester::on(TargetPlatform::MacOS);
4041 let tester = &mut tester;
4042 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4043 let node = focus_node(tester);
4044 AdaptiveSwitch {
4045 autofocus: true,
4046 focus_node: Some(node.clone()),
4047 focus_color,
4048 ..AdaptiveSwitch::default()
4049 }
4050 .pump(tester, TargetPlatform::MacOS);
4051 tester.pump_and_settle();
4052 assert!(node.has_primary_focus(&tester.cell.borrow()));
4053 assert_paints(
4054 &material_ops(tester),
4055 &[
4056 PaintCall::rrect(Some(Color::new(0xff34c759))), rrect(None, Some(ring), Some(PaintedStyle::Stroke(Some(3.5)))), PaintCall::rrect(None),
4060 PaintCall::rrect(None),
4061 PaintCall::rrect(None),
4062 PaintCall::rrect(Some(Color::new(0xffffffff))), ],
4064 );
4065 }
4066 });
4067 }
4068
4069 #[test]
4070 fn an_m3_switch_is_focusable_and_has_its_focus_color() {
4071 test_widgets(|tester| {
4072 let colors_ = colors_of(&tester.cell.borrow(), m3);
4073 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4074 let node = focus_node(tester);
4075 let value = shared(true);
4076 let orange = Colors::ORANGE.shade500();
4077 for enabled in [true, true, false] {
4078 if !enabled {
4079 value.set(false);
4080 }
4081 pump_host(tester, m3, TextDirection::Ltr, &value, enabled, {
4082 let node = node.clone();
4083 move |value, on_changed| {
4084 Switch::new(value, on_changed)
4085 .focus_color(orange)
4086 .autofocus(true)
4087 .focus_node(node.clone())
4088 }
4089 });
4090 tester.pump_and_settle();
4091 let painted = material_ops(tester);
4092 if !enabled {
4093 assert!(!node.has_primary_focus(&tester.cell.borrow()));
4095 assert_paints(
4096 &painted,
4097 &[
4098 m3_track(
4099 with_opacity(colors_.surface_container_highest(), 0.12),
4100 Some(PaintedStyle::Fill),
4101 ),
4102 m3_outline(with_opacity(colors_.on_surface(), 0.12)),
4103 PaintCall::rrect(Some(Color::alpha_blend(
4104 with_opacity(colors_.on_surface(), 0.38),
4105 colors_.surface(),
4106 ))),
4107 ],
4108 );
4109 break;
4110 }
4111 assert!(node.has_primary_focus(&tester.cell.borrow()));
4112 if value.get() {
4113 assert_paints(
4115 &painted,
4116 &[
4117 m3_track(colors_.primary(), Some(PaintedStyle::Fill)),
4118 PaintCall::circle(Some(orange)),
4119 ],
4120 );
4121 value.set(false);
4123 } else {
4124 assert_paints(
4125 &painted,
4126 &[
4127 m3_track(
4128 colors_.surface_container_highest(),
4129 Some(PaintedStyle::Fill),
4130 ),
4131 m3_outline(colors_.outline()),
4132 PaintCall::circle(Some(orange)),
4133 ],
4134 );
4135 }
4136 }
4137 });
4138 }
4139
4140 #[test]
4141 fn the_splash_radius_sizes_the_focus_circle() {
4142 test_widgets(|tester| {
4143 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4144 const SPLASH_RADIUS: f64 = 30.0;
4145 pump_switch(
4146 tester,
4147 m3,
4148 Switch::new(true, ignore())
4149 .focus_color(Colors::ORANGE.shade500())
4150 .autofocus(true)
4151 .splash_radius(SPLASH_RADIUS),
4152 );
4153 tester.pump_and_settle();
4154 assert_paints(
4155 &material_ops(tester),
4156 &[PaintCall::Circle {
4157 x: None,
4158 y: None,
4159 radius: Some(SPLASH_RADIUS),
4160 color: Some(Colors::ORANGE.shade500()),
4161 style: None,
4162 }],
4163 );
4164 });
4165 }
4166
4167 #[test]
4168 fn an_m2_switch_can_be_hovered_and_has_its_hover_color() {
4169 test_widgets(|tester| {
4170 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4171 let value = shared(true);
4172 let orange = Colors::ORANGE.shade500();
4173 let make = move |value, on_changed| Switch::new(value, on_changed).hover_color(orange);
4174 pump_host(tester, m2, TextDirection::Ltr, &value, true, make);
4175 tester.pump_and_settle();
4176 assert_paints(
4177 &material_ops(tester),
4178 &m2_pattern(Color::new(0x802196f3), None, Color::new(0xff2196f3)),
4179 );
4180
4181 hover(tester);
4183 pump_host(tester, m2, TextDirection::Ltr, &value, true, make);
4184 tester.pump_and_settle();
4185 assert_paints(
4186 &material_ops(tester),
4187 &m2_pattern(Color::new(0x802196f3), Some(orange), Color::new(0xff2196f3)),
4188 );
4189
4190 pump_host(tester, m2, TextDirection::Ltr, &value, false, make);
4192 tester.pump_and_settle();
4193 assert_paints(
4194 &material_ops(tester),
4195 &m2_pattern(Color::new(0x1f000000), None, Color::new(0xffbdbdbd)),
4196 );
4197 });
4198 }
4199
4200 #[test]
4201 fn an_m3_switch_can_be_hovered_and_has_its_hover_color() {
4202 test_widgets(|tester| {
4203 let colors_ = colors_of(&tester.cell.borrow(), m3);
4204 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4205 let value = shared(true);
4206 let orange = Colors::ORANGE.shade500();
4207 let make = move |value, on_changed| Switch::new(value, on_changed).hover_color(orange);
4208
4209 pump_host(tester, m3, TextDirection::Ltr, &value, true, make);
4211 tester.pump_and_settle();
4212 assert_paints(
4213 &material_ops(tester),
4214 &[
4215 m3_track(colors_.primary(), None),
4216 PaintCall::rrect(Some(colors_.on_primary())),
4218 ],
4219 );
4220
4221 hover(tester);
4223 pump_host(tester, m3, TextDirection::Ltr, &value, true, make);
4224 tester.pump_and_settle();
4225 assert_paints(
4226 &material_ops(tester),
4227 &[
4228 m3_track(colors_.primary(), None),
4229 PaintCall::circle(Some(orange)),
4230 ],
4231 );
4232
4233 pump_host(tester, m3, TextDirection::Ltr, &value, false, make);
4235 tester.pump_and_settle();
4236 assert_paints(
4237 &material_ops(tester),
4238 &[
4239 m3_track(with_opacity(colors_.on_surface(), 0.12), None),
4240 PaintCall::rrect(Some(with_opacity(colors_.surface(), 1.0))),
4242 ],
4243 );
4244 });
4245 }
4246
4247 #[test]
4248 fn the_enter_and_space_keys_toggle_the_switch() {
4249 test_widgets(|tester| {
4250 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4251 let value = shared(true);
4252 pump_host(
4253 tester,
4254 m3,
4255 TextDirection::Ltr,
4256 &value,
4257 true,
4258 |value, on_changed| {
4259 Switch::new(value, on_changed)
4260 .focus_color(Colors::ORANGE.shade500())
4261 .autofocus(true)
4262 },
4263 );
4264 tester.pump_and_settle();
4265 tester.send_key_event(PhysicalKeyboardKey::ENTER, LogicalKeyboardKey::ENTER);
4266 tester.pump_and_settle();
4267 assert_eq!(value.get(), K_IS_WEB);
4269 tester.send_key_event(PhysicalKeyboardKey::ENTER, LogicalKeyboardKey::ENTER);
4270 tester.pump_and_settle();
4271 assert!(value.get());
4272 tester.send_key_event(PhysicalKeyboardKey::SPACE, LogicalKeyboardKey::SPACE);
4273 tester.pump_and_settle();
4274 assert!(!value.get());
4275 tester.send_key_event(PhysicalKeyboardKey::SPACE, LogicalKeyboardKey::SPACE);
4276 tester.pump_and_settle();
4277 assert!(value.get());
4278 });
4279 }
4280
4281 #[test]
4282 fn a_hovered_switch_shows_its_mouse_cursor() {
4283 test_widgets(|tester| {
4284 let pump = |tester: &mut WidgetTester, switch: Switch| {
4285 let home = Scaffold::new()
4286 .body(
4287 Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
4288 Material::new().child(
4289 MouseRegion::new()
4290 .cursor(SystemMouseCursors::FORBIDDEN.into())
4291 .child(switch),
4292 ),
4293 ),
4294 )
4295 .into_widget();
4296 pump_app(tester, m3, move |_app| home);
4297 };
4298 pump(
4300 tester,
4301 Switch::adaptive(true, ignore()).mouse_cursor(SystemMouseCursors::TEXT),
4302 );
4303 let mut mouse = TestPointer::mouse(1, 0);
4304 let at = center(tester);
4305 tester.add_pointer(&mut mouse, at);
4306 tester.pump();
4307 assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
4308
4309 pump(
4311 tester,
4312 Switch::new(true, ignore()).mouse_cursor(SystemMouseCursors::TEXT),
4313 );
4314 let at = center(tester);
4315 tester.move_to(&mut mouse, at, false);
4316 assert_eq!(tester.active_cursor(1), SystemMouseCursors::TEXT.into());
4317
4318 pump(tester, Switch::new(true, ignore()));
4320 assert_eq!(tester.active_cursor(1), SystemMouseCursors::CLICK.into());
4321
4322 pump(tester, Switch::new(true, None));
4324 assert_eq!(tester.active_cursor(1), SystemMouseCursors::BASIC.into());
4325
4326 tester.pump_and_settle();
4327 });
4328 }
4329
4330 #[test]
4331 fn an_m3_thumb_color_resolves_in_the_selected_and_disabled_states() {
4332 test_widgets(|tester| {
4333 const ACTIVE_ENABLED: Color = Color::new(0xFF000001);
4334 const ACTIVE_DISABLED: Color = Color::new(0xFF000002);
4335 const INACTIVE_ENABLED: Color = Color::new(0xFF000003);
4336 const INACTIVE_DISABLED: Color = Color::new(0xFF000004);
4337 let thumb_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
4338 Some(if states.contains(&WidgetState::Disabled) {
4339 if states.contains(&WidgetState::Selected) {
4340 ACTIVE_DISABLED
4341 } else {
4342 INACTIVE_DISABLED
4343 }
4344 } else if states.contains(&WidgetState::Selected) {
4345 ACTIVE_ENABLED
4346 } else {
4347 INACTIVE_ENABLED
4348 })
4349 });
4350 let colors_ = colors_of(&tester.cell.borrow(), m3);
4351 for (enabled, active, track, thumb) in [
4352 (
4353 false,
4354 false,
4355 with_opacity(colors_.surface_container_highest(), 0.12),
4356 INACTIVE_DISABLED,
4357 ),
4358 (
4359 false,
4360 true,
4361 with_opacity(colors_.on_surface(), 0.12),
4362 ACTIVE_DISABLED,
4363 ),
4364 (
4365 true,
4366 false,
4367 colors_.surface_container_highest(),
4368 INACTIVE_ENABLED,
4369 ),
4370 (true, true, colors_.primary(), ACTIVE_ENABLED),
4371 ] {
4372 let home = in_material(
4373 TextDirection::Rtl,
4374 Switch::new(active, if enabled { ignore() } else { None })
4375 .thumb_color(Rc::clone(&thumb_color))
4376 .into_widget(),
4377 );
4378 pump_app(tester, m3, move |_app| home);
4379 tester.pump_and_settle();
4380 let mut pattern = vec![m3_track(track, Some(PaintedStyle::Fill))];
4381 match (enabled, active) {
4382 (false, false) => {
4383 pattern.push(m3_outline(with_opacity(colors_.on_surface(), 0.12)))
4384 }
4385 (true, false) => pattern.push(PaintCall::rrect(None)),
4387 (_, true) => {}
4389 }
4390 pattern.push(PaintCall::rrect(Some(thumb)));
4391 assert_paints(&material_ops(tester), &pattern);
4392 }
4393 });
4394 }
4395
4396 #[test]
4397 fn an_m3_thumb_color_resolves_in_the_hovered_and_focused_states() {
4398 test_widgets(|tester| {
4399 const HOVERED: Color = Color::new(0xFF000001);
4400 const FOCUSED: Color = Color::new(0xFF000002);
4401 let colors_ = colors_of(&tester.cell.borrow(), m3);
4402 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4403 let node = focus_node(tester);
4404 let home = in_material(
4405 TextDirection::Rtl,
4406 Switch::new(true, ignore())
4407 .focus_node(node.clone())
4408 .autofocus(true)
4409 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
4410 |states| {
4411 Some(if states.contains(&WidgetState::Hovered) {
4412 HOVERED
4413 } else if states.contains(&WidgetState::Focused) {
4414 FOCUSED
4415 } else {
4416 Colors::TRANSPARENT
4417 })
4418 },
4419 ))
4420 .into_widget(),
4421 );
4422 pump_app(tester, m3, move |_app| home);
4423 tester.pump_and_settle();
4424 assert!(node.has_primary_focus(&tester.cell.borrow()));
4425 assert_paints(
4426 &material_ops(tester),
4427 &[
4428 m3_track(colors_.primary(), Some(PaintedStyle::Fill)),
4429 PaintCall::circle(Some(with_opacity(colors_.primary(), 0.1))),
4430 PaintCall::rrect(Some(FOCUSED)),
4431 ],
4432 );
4433
4434 hover(tester);
4436 tester.pump_and_settle();
4437 assert_paints(
4438 &material_ops(tester),
4439 &[
4440 m3_track(colors_.primary(), Some(PaintedStyle::Fill)),
4441 PaintCall::circle(Some(with_opacity(colors_.primary(), 0.08))),
4442 PaintCall::rrect(Some(HOVERED)),
4443 ],
4444 );
4445 });
4446 }
4447
4448 #[test]
4449 fn the_overlay_color_resolves_in_the_pressed_focused_and_hovered_states() {
4450 test_widgets(|tester| {
4451 const ACTIVE_THUMB: Color = Color::new(0xFF000000);
4452 const INACTIVE_THUMB: Color = Color::new(0xFF000010);
4453 const ACTIVE_PRESSED_OVERLAY: Color = Color::new(0xFF000001);
4454 const INACTIVE_PRESSED_OVERLAY: Color = Color::new(0xFF000002);
4455 const HOVER_OVERLAY: Color = Color::new(0xFF000003);
4456 const FOCUS_OVERLAY: Color = Color::new(0xFF000004);
4457 const HOVER: Color = Color::new(0xFF000005);
4458 const FOCUS: Color = Color::new(0xFF000006);
4459 const SPLASH_RADIUS: f64 = 24.0;
4460 let overlay = |color: Color| {
4462 [
4463 PaintCall::rrect(None),
4464 PaintCall::Circle {
4465 x: None,
4466 y: None,
4467 radius: Some(SPLASH_RADIUS),
4468 color: Some(color),
4469 style: None,
4470 },
4471 ]
4472 };
4473 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4474 let node = focus_node(tester);
4475 let pump =
4476 |tester: &mut WidgetTester, active: bool, focused: bool, use_overlay: bool| {
4477 let mut switch = Switch::new(active, ignore())
4478 .focus_node(node.clone())
4479 .autofocus(focused)
4480 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
4481 |states| {
4482 Some(if states.contains(&WidgetState::Selected) {
4483 ACTIVE_THUMB
4484 } else {
4485 INACTIVE_THUMB
4486 })
4487 },
4488 ))
4489 .hover_color(HOVER)
4490 .focus_color(FOCUS)
4491 .splash_radius(SPLASH_RADIUS);
4492 if use_overlay {
4493 switch = switch.overlay_color(
4494 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
4495 if states.contains(&WidgetState::Pressed) {
4496 if states.contains(&WidgetState::Selected) {
4497 return Some(ACTIVE_PRESSED_OVERLAY);
4498 }
4499 return Some(INACTIVE_PRESSED_OVERLAY);
4500 }
4501 if states.contains(&WidgetState::Hovered) {
4502 return Some(HOVER_OVERLAY);
4503 }
4504 if states.contains(&WidgetState::Focused) {
4505 return Some(FOCUS_OVERLAY);
4506 }
4507 None
4508 }),
4509 );
4510 }
4511 let home = Scaffold::new().body(switch).into_widget();
4512 pump_app(tester, m3, move |_app| home);
4513 };
4514
4515 for (active, use_overlay, expected) in [
4516 (
4517 false,
4518 false,
4519 INACTIVE_THUMB.with_alpha(K_RADIAL_REACTION_ALPHA),
4520 ),
4521 (
4522 true,
4523 false,
4524 ACTIVE_THUMB.with_alpha(K_RADIAL_REACTION_ALPHA),
4525 ),
4526 (false, true, INACTIVE_PRESSED_OVERLAY),
4527 (true, true, ACTIVE_PRESSED_OVERLAY),
4528 ] {
4529 pump(tester, active, false, use_overlay);
4530 let touch = press(tester);
4531 tester.pump_and_settle();
4532 assert_paints(&material_ops(tester), &overlay(expected));
4533 tester.up(&touch);
4534 tester.pump_and_settle();
4535 }
4536
4537 pump(tester, false, true, true);
4538 tester.pump_and_settle();
4539 assert!(node.has_primary_focus(&tester.cell.borrow()));
4540 assert_paints(&material_ops(tester), &overlay(FOCUS_OVERLAY));
4541
4542 hover(tester);
4544 tester.pump_and_settle();
4545 assert_paints(&material_ops(tester), &overlay(HOVER_OVERLAY));
4546 });
4547 }
4548
4549 #[test]
4550 fn an_m3_switch_animates_for_300_milliseconds_and_its_thumb_bounces() {
4551 for bounce in [false, true] {
4552 test_widgets(|tester| {
4553 let value = shared(false);
4554 let direction = if bounce {
4555 TextDirection::Ltr
4556 } else {
4557 TextDirection::Rtl
4558 };
4559 pump_host(tester, m3, direction, &value, true, Switch::new);
4560 assert!(!value.get());
4561 let switch_rect = switch_rect(tester);
4562 let mut gesture = TestPointer::touch(1);
4563 tester.down(&mut gesture, switch_rect.center_left());
4564 tester.pump();
4565 tester.up(&gesture);
4566 tester.pump();
4567 if bounce {
4568 tester.pump_by(Duration::from_millis(113));
4571 assert!(tester.has_running_animations());
4572 assert!(position(tester) > 1.0, "{}", position(tester));
4573 } else {
4574 tester.pump_by(Duration::from_millis(200)); assert!(tester.has_running_animations());
4576 tester.pump_by(Duration::from_millis(101));
4577 assert!(!tester.has_running_animations());
4578 }
4579 });
4580 }
4581 }
4582
4583 #[test]
4584 fn an_m3_thumb_shows_its_pressed_color() {
4585 for platform in MOBILE.into_iter().chain([TargetPlatform::IOS]) {
4586 test_widgets(|_| {
4587 let colors_ = colors_of(&WidgetTester::on(platform).cell.borrow(), m3);
4588 for (enabled, value, track, outline, thumb) in [
4589 (
4590 true,
4591 true,
4592 colors_.primary(),
4593 None,
4594 PaintCall::rrect_at(
4595 ltrbr(26.0, 10.0, 54.0, 38.0, 14.0),
4596 Some(colors_.primary_container()),
4597 ),
4598 ),
4599 (
4600 true,
4601 false,
4602 colors_.surface_container_highest(),
4603 Some(colors_.outline()),
4604 PaintCall::rrect(Some(colors_.on_surface_variant())),
4605 ),
4606 (
4607 false,
4608 true,
4609 with_opacity(colors_.on_surface(), 0.12),
4610 None,
4611 PaintCall::rrect(Some(with_opacity(colors_.surface(), 1.0))),
4612 ),
4613 (
4614 false,
4615 false,
4616 with_opacity(colors_.surface_container_highest(), 0.12),
4617 Some(with_opacity(colors_.on_surface(), 0.12)),
4618 PaintCall::rrect(Some(Color::alpha_blend(
4619 with_opacity(colors_.on_surface(), 0.38),
4620 colors_.surface(),
4621 ))),
4622 ),
4623 ] {
4624 let mut tester = WidgetTester::on(platform);
4625 let tester = &mut tester;
4626 let shared = shared(value);
4627 pump_host(
4628 tester,
4629 m3,
4630 TextDirection::Ltr,
4631 &shared,
4632 enabled,
4633 Switch::new,
4634 );
4635 let _touch = press(tester);
4636 tester.pump_and_settle();
4637 let mut pattern = vec![rrect(None, Some(track), Some(PaintedStyle::Fill))];
4638 pattern.extend(outline.map(|outline| {
4640 rrect(None, Some(outline), Some(PaintedStyle::Stroke(None)))
4641 }));
4642 pattern.push(thumb);
4643 assert_paints(&material_ops(tester), &pattern);
4644 }
4645 });
4646 }
4647 }
4648
4649 #[test]
4650 fn the_track_outline_color_and_width_resolve_in_the_selected_and_disabled_states() {
4651 test_widgets(|tester| {
4652 let color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
4653 let disabled = states.contains(&WidgetState::Disabled);
4654 let selected = states.contains(&WidgetState::Selected);
4655 Some(Color::new(match (disabled, selected) {
4656 (true, true) => 0xFF000002,
4657 (true, false) => 0xFF000004,
4658 (false, true) => 0xFF000001,
4659 (false, false) => 0xFF000003,
4660 }))
4661 });
4662 let width = <dyn WidgetStateProperty<Option<f64>>>::resolve_with(|states| {
4663 let disabled = states.contains(&WidgetState::Disabled);
4664 let selected = states.contains(&WidgetState::Selected);
4665 Some(match (disabled, selected) {
4666 (true, true) => 2.0,
4667 (true, false) => 4.0,
4668 (false, true) => 1.0,
4669 (false, false) => 3.0,
4670 })
4671 });
4672 for (enabled, active, expected_color, expected_width) in [
4673 (false, false, 0xFF000004, 4.0),
4674 (false, true, 0xFF000002, 2.0),
4675 (true, false, 0xFF000003, 3.0),
4676 (true, true, 0xFF000001, 1.0),
4677 ] {
4678 let home = in_material(
4679 TextDirection::Rtl,
4680 Switch::new(active, if enabled { ignore() } else { None })
4681 .track_outline_color(Rc::clone(&color))
4682 .track_outline_width(Rc::clone(&width))
4683 .into_widget(),
4684 );
4685 pump_app(tester, m3, move |_app| home);
4686 tester.pump_and_settle();
4687 let outline_style = (!enabled).then_some(PaintedStyle::Stroke(None));
4689 assert_paints(
4690 &material_ops(tester),
4691 &[
4692 rrect(None, None, Some(PaintedStyle::Fill)),
4693 rrect(None, Some(Color::new(expected_color)), outline_style),
4694 ],
4695 );
4696 assert_paints(
4697 &material_ops(tester),
4698 &[
4699 rrect(None, None, Some(PaintedStyle::Fill)),
4700 rrect(None, None, Some(PaintedStyle::Stroke(Some(expected_width)))),
4701 ],
4702 );
4703 }
4704 });
4705 }
4706
4707 #[test]
4708 fn the_track_outline_resolves_in_the_hovered_and_focused_states() {
4709 test_widgets(|tester| {
4710 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4711 let node = focus_node(tester);
4712 let home = in_material(
4713 TextDirection::Rtl,
4714 Switch::new(true, ignore())
4715 .focus_node(node.clone())
4716 .autofocus(true)
4717 .track_outline_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
4718 |states| {
4719 Some(Color::new(if states.contains(&WidgetState::Hovered) {
4720 0xFF000001
4721 } else if states.contains(&WidgetState::Focused) {
4722 0xFF000002
4723 } else {
4724 0x00000000
4725 }))
4726 },
4727 ))
4728 .track_outline_width(<dyn WidgetStateProperty<Option<f64>>>::resolve_with(
4729 |states| {
4730 Some(if states.contains(&WidgetState::Hovered) {
4731 4.0
4732 } else if states.contains(&WidgetState::Focused) {
4733 6.0
4734 } else {
4735 8.0
4736 })
4737 },
4738 ))
4739 .into_widget(),
4740 );
4741 pump_app(tester, m3, move |_app| home);
4742 tester.pump_and_settle();
4743 assert!(node.has_primary_focus(&tester.cell.borrow()));
4744 let outline = |color: u32, width: f64| {
4745 [
4746 [
4747 rrect(None, None, Some(PaintedStyle::Fill)),
4748 rrect(
4749 None,
4750 Some(Color::new(color)),
4751 Some(PaintedStyle::Stroke(None)),
4752 ),
4753 ],
4754 [
4755 rrect(None, None, Some(PaintedStyle::Fill)),
4756 rrect(None, None, Some(PaintedStyle::Stroke(Some(width)))),
4757 ],
4758 ]
4759 };
4760 for pattern in outline(0xFF000002, 6.0) {
4761 assert_paints(&material_ops(tester), &pattern);
4762 }
4763
4764 hover(tester);
4766 tester.pump_and_settle();
4767 for pattern in outline(0xFF000001, 4.0) {
4768 assert_paints(&material_ops(tester), &pattern);
4769 }
4770 });
4771 }
4772
4773 #[test]
4774 fn an_m3_thumb_shows_the_icon_for_its_side_only() {
4775 test_widgets(|tester| {
4776 crate::icons::install_material_icon_font(&mut tester.cell.borrow_mut());
4777 let theme = |app: &App| {
4778 ThemeData::builder()
4779 .color_scheme_seed(Color::new(0xff6750a4))
4780 .brightness(Brightness::Light)
4781 .build(app)
4782 };
4783 let mut pump =
4784 |active: bool, active_icon: Option<IconData>, inactive_icon: Option<IconData>| {
4785 let (active_icon, inactive_icon) = (
4786 active_icon.map(|icon| Rc::new(Icon::new(Some(icon)))),
4787 inactive_icon.map(|icon| Rc::new(Icon::new(Some(icon)))),
4788 );
4789 let home = Directionality::new(
4790 TextDirection::Ltr,
4791 Material::new().child(Center::new().child(
4792 Switch::new(active, ignore()).thumb_icon(<dyn WidgetStateProperty<
4793 Option<Rc<Icon>>,
4794 >>::resolve_with(
4795 move |states| {
4796 if states.contains(&WidgetState::Selected) {
4797 return active_icon.clone();
4798 }
4799 inactive_icon.clone()
4800 },
4801 )),
4802 )),
4803 )
4804 .into_widget();
4805 pump_app(tester, theme, move |_app| home);
4806 tester.pump_and_settle();
4807 glyph_origins(&drawn(tester))
4808 };
4809 let inside = |glyphs: &[(f64, f64)], left: f64, top: f64| matches!(glyphs, [(x, y)] if *x >= left && *x < left + 16.0 && *y >= top && *y < top + 16.0);
4811
4812 let glyphs = pump(true, Some(Icons::close()), None);
4814 assert!(inside(&glyphs, 32.0, 16.0), "{glyphs:?}");
4815 let glyphs = pump(false, None, Some(Icons::close()));
4817 assert!(inside(&glyphs, 12.0, 16.0), "{glyphs:?}");
4818 assert_eq!(pump(false, Some(Icons::check()), None), []);
4820 assert_eq!(pump(true, None, Some(Icons::check())), []);
4822 assert_eq!(pump(false, None, None), []);
4824 });
4825 }
4826
4827 #[test]
4828 fn an_adaptive_cupertino_switch_is_focusable_and_has_its_focus_color() {
4829 test_widgets(|_| {
4830 const FOCUS_COLOR: u32 = 0xffff0000;
4831 let mut tester = WidgetTester::on(TargetPlatform::IOS);
4832 let tester = &mut tester;
4833 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
4834 let node = focus_node(tester);
4835 let value = shared(true);
4836 let pump = |tester: &mut WidgetTester, enabled: bool| {
4837 let home = Material::new()
4838 .child(host(&value, enabled, {
4839 let node = node.clone();
4840 move |value, on_changed| {
4841 Switch::adaptive(value, on_changed)
4842 .focus_color(Color::new(FOCUS_COLOR))
4843 .focus_node(node.clone())
4844 .autofocus(true)
4845 }
4846 }))
4847 .into_widget();
4848 let home = Center::new().child(home).into_widget();
4849 pump_app(tester, adaptive_on(TargetPlatform::IOS), move |_app| home);
4850 tester.pump_and_settle();
4851 };
4852 let pattern = |track: u32, focused: bool| {
4856 let mut pattern = vec![PaintCall::rrect(Some(Color::new(track)))];
4857 if focused {
4858 pattern.push(PaintCall::rrect(Some(Color::new(FOCUS_COLOR))));
4859 }
4860 pattern.push(PaintCall::Clip);
4861 pattern.extend(
4862 [0x26000000, 0x0f000000, 0x0a000000, 0xffffffff]
4863 .map(|color| PaintCall::rrect(Some(Color::new(color)))),
4864 );
4865 pattern
4866 };
4867 let switch_ops = |tester: &WidgetTester| {
4868 tester.painted_ops_deep(tester.render_object(find::by_type::<Switch>()))
4869 };
4870
4871 pump(tester, true);
4872 assert!(node.has_primary_focus(&tester.cell.borrow()));
4873 assert_paints(&switch_ops(tester), &pattern(0xff34c759, true));
4874
4875 value.set(false);
4877 pump(tester, true);
4878 assert!(node.has_primary_focus(&tester.cell.borrow()));
4879 assert_paints(&switch_ops(tester), &pattern(0x28787880, true));
4880
4881 pump(tester, false);
4883 assert!(!node.has_primary_focus(&tester.cell.borrow()));
4884 assert_paints(&switch_ops(tester), &pattern(0x28787880, false));
4885 });
4886 }
4887
4888 #[test]
4889 fn on_focus_change_hears_focus_arrive_and_leave() {
4890 test_widgets(|tester| {
4891 let node = focus_node(tester);
4892 let focused = Rc::new(Cell::new(false));
4893 let switch = {
4894 let focused = Rc::clone(&focused);
4895 Switch::new(true, ignore())
4896 .focus_node(node.clone())
4897 .on_focus_change(move |_app, value| focused.set(value))
4898 };
4899 pump_switch(tester, m3, switch);
4900
4901 node.request_focus(&mut tester.cell.borrow_mut(), None);
4902 tester.pump();
4903 assert!(focused.get());
4904 assert!(node.has_focus(&tester.cell.borrow_mut()));
4905
4906 node.unfocus(&mut tester.cell.borrow_mut(), UnfocusDisposition::Scope);
4907 tester.pump();
4908 assert!(!focused.get());
4909 assert!(!node.has_focus(&tester.cell.borrow_mut()));
4910 });
4911 }
4912
4913 #[test]
4914 fn the_padding_is_respected() {
4915 test_widgets(|tester| {
4916 for (padding, expected) in [
4917 (None, Size::new(60.0, 48.0)),
4918 (Some(EdgeInsetsGeometry::ZERO), Size::new(52.0, 48.0)),
4919 (Some(EdgeInsetsGeometry::all(4.0)), Size::new(60.0, 56.0)),
4920 ] {
4921 let mut switch = Switch::new(true, ignore());
4922 if let Some(padding) = padding {
4923 switch = switch.padding(padding);
4924 }
4925 pump_switch(tester, m3, switch);
4926 assert_eq!(switch_rect(tester).size(), expected, "{padding:?}");
4927 }
4928 });
4929 }
4930
4931 #[test]
4932 #[allow(deprecated)]
4933 fn the_active_thumb_color_wins_over_the_active_color() {
4934 for (theme, use_material3) in [(m2 as fn(&App) -> ThemeData, false), (m3, true)] {
4935 test_widgets(|tester| {
4936 const ACTIVE_COLOR: Color = Color::new(0xffff0000);
4937 const ACTIVE_THUMB_COLOR: Color = Color::new(0xff00ff00);
4938 const ACTIVE_TRACK_COLOR: Color = Color::new(0xff0000ff);
4939 let value = shared(true);
4940 pump_host(
4941 tester,
4942 theme,
4943 TextDirection::Rtl,
4944 &value,
4945 true,
4946 |_value, on_changed| {
4947 Switch::new(true, on_changed)
4948 .drag_start_behavior(DragStartBehavior::Down)
4949 .active_color(ACTIVE_COLOR)
4950 .active_thumb_color(ACTIVE_THUMB_COLOR)
4951 .active_track_color(ACTIVE_TRACK_COLOR)
4952 },
4953 );
4954 tester.widget(switch_element(tester), |switch: &Switch| {
4955 assert_eq!(switch.active_thumb_color, Some(ACTIVE_THUMB_COLOR));
4956 });
4957 if use_material3 {
4958 assert_paints(
4959 &material_ops(tester),
4960 &[
4961 m3_track(ACTIVE_TRACK_COLOR, Some(PaintedStyle::Fill)),
4962 PaintCall::rrect(Some(ACTIVE_THUMB_COLOR)),
4964 ],
4965 );
4966 } else {
4967 assert_paints(
4968 &material_ops(tester),
4969 &m2_pattern(ACTIVE_TRACK_COLOR, None, ACTIVE_THUMB_COLOR),
4970 );
4971 }
4972 });
4973 }
4974 }
4975
4976 #[test]
4977 #[allow(deprecated)]
4978 fn an_adaptive_switch_takes_its_active_thumb_color_on_every_platform() {
4979 for use_material3 in [false, true] {
4980 for platform in ALL_PLATFORMS {
4981 test_widgets(|_| {
4982 const ACTIVE_COLOR: Color = Color::new(0xffff0000);
4983 const ACTIVE_THUMB_COLOR: Color = Color::new(0xff00ff00);
4984 const ACTIVE_TRACK_COLOR: Color = Color::new(0xff0000ff);
4985 let mut tester = WidgetTester::on(platform);
4986 let tester = &mut tester;
4987 let value = shared(true);
4988 pump_host(
4989 tester,
4990 move |app| {
4991 ThemeData::builder()
4992 .platform(platform)
4993 .use_material3(use_material3)
4994 .build(app)
4995 },
4996 TextDirection::Rtl,
4997 &value,
4998 true,
4999 |_value, on_changed| {
5000 Switch::adaptive(true, on_changed)
5001 .drag_start_behavior(DragStartBehavior::Down)
5002 .active_color(ACTIVE_COLOR)
5003 .active_thumb_color(ACTIVE_THUMB_COLOR)
5004 .active_track_color(ACTIVE_TRACK_COLOR)
5005 },
5006 );
5007 let compact = !MOBILE.contains(&platform) && platform != TargetPlatform::IOS;
5008 let thumb = PaintCall::rrect(Some(ACTIVE_THUMB_COLOR));
5009 let pattern = if CUPERTINO_PLATFORMS.contains(&platform) {
5010 let (left, right) = if use_material3 {
5011 (4.5, 55.5)
5012 } else {
5013 (4.0, 55.0)
5014 };
5015 let (top, bottom) = if compact { (4.5, 35.5) } else { (8.5, 39.5) };
5016 cupertino_pattern(
5017 rrect(
5018 Some(ltrbr(left, top, right, bottom, 15.5)),
5019 Some(ACTIVE_TRACK_COLOR),
5020 None,
5021 ),
5022 thumb,
5023 )
5024 } else if use_material3 {
5025 let track = if compact {
5026 ltrbr(4.0, 4.0, 56.0, 36.0, 16.0)
5027 } else {
5028 ltrbr(4.0, 8.0, 56.0, 40.0, 16.0)
5029 };
5030 vec![
5031 rrect(
5032 Some(track),
5033 Some(ACTIVE_TRACK_COLOR),
5034 Some(PaintedStyle::Fill),
5035 ),
5036 thumb,
5038 ]
5039 } else {
5040 let track = if compact {
5041 ltrbr(13.0, 13.0, 46.0, 27.0, 7.0)
5042 } else {
5043 ltrbr(13.0, 17.0, 46.0, 31.0, 7.0)
5044 };
5045 let mut pattern = m2_pattern(ACTIVE_TRACK_COLOR, None, ACTIVE_THUMB_COLOR);
5046 pattern[0] = rrect(Some(track), Some(ACTIVE_TRACK_COLOR), None);
5047 pattern
5048 };
5049 assert_paints(&material_ops(tester), &pattern);
5050 });
5051 }
5052 }
5053 }
5054
5055 #[test]
5058 fn an_adaptive_cupertino_switch_applies_the_cupertino_theme_where_asked() {
5059 test_widgets(|_| {
5060 const PRIMARY: Color = Color::new(0xffffc107);
5061 for (apply_to_all, apply, expected) in [
5062 (false, None, 0xff34c759),
5063 (false, Some(true), c(PRIMARY)),
5064 (true, None, c(PRIMARY)),
5065 (true, Some(false), 0xff34c759),
5066 ] {
5067 let mut tester = WidgetTester::on(TargetPlatform::IOS);
5068 let tester = &mut tester;
5069 let mut switch = Switch::adaptive(true, ignore());
5070 if let Some(apply) = apply {
5071 switch = switch.apply_cupertino_theme(apply);
5072 }
5073 pump_switch(
5074 tester,
5075 move |app| {
5076 ThemeData::builder()
5077 .platform(TargetPlatform::IOS)
5078 .cupertino_override_theme(waft_cupertino::NoDefaultCupertinoThemeData {
5079 primary_color: Some(PRIMARY.into()),
5080 apply_theme_to_all: Some(apply_to_all),
5081 ..waft_cupertino::NoDefaultCupertinoThemeData::default()
5082 })
5083 .build(app)
5084 },
5085 switch,
5086 );
5087 assert_eq!(
5088 color_of(&drawn(tester)[0]),
5089 Some(expected),
5090 "apply to all {apply_to_all}, apply {apply:?}"
5091 );
5092 }
5093 });
5094 }
5095
5096 #[test]
5097 fn a_switch_that_disappears_while_a_pointer_is_down_does_not_crash() {
5098 test_widgets(|tester| {
5099 pump_switch(tester, m3, Switch::new(true, ignore()));
5100 let at = center(tester);
5101 let mut gesture = TestPointer::touch(1);
5103 tester.down(&mut gesture, at);
5104 tester.pump();
5105 let home = in_material(TextDirection::Ltr, Container::new().into_widget());
5107 pump_app(tester, m3, move |_app| home);
5108 expect(tester, &find::by_type::<Switch>(), finds_nothing());
5109 tester.up(&gesture);
5111 });
5112 }
5113
5114 fn first_painted_host(
5117 value: &Shared,
5118 visible: &Shared,
5119 set_state_slot: &Rc<RefCell<Option<StateSetter>>>,
5120 interactive: bool,
5121 ) -> WidgetRef {
5122 let (value, visible, slot) = (
5123 Rc::clone(value),
5124 Rc::clone(visible),
5125 Rc::clone(set_state_slot),
5126 );
5127 let home = StatefulBuilder::new(move |_app, _context, set_state| {
5128 *slot.borrow_mut() = Some(Rc::clone(&set_state));
5129 let on_changed: ValueChanged<bool> = {
5130 let (value, visible) = (Rc::clone(&value), Rc::clone(&visible));
5131 Rc::new(move |app: &mut App, new_value: bool| {
5132 if interactive {
5133 let (value, visible) = (Rc::clone(&value), Rc::clone(&visible));
5134 set_state(app, &mut move |_app| {
5135 value.set(new_value);
5136 visible.set(true);
5137 });
5138 }
5139 })
5140 };
5141 Opacity::new(if visible.get() { 1.0 } else { 0.0 })
5142 .child(Switch::adaptive(value.get(), Some(on_changed)))
5143 .into_widget()
5144 });
5145 Material::new()
5146 .child(Center::new().child(home))
5147 .into_widget()
5148 }
5149
5150 #[test]
5151 fn a_switch_first_painted_while_its_press_reaction_reverses_does_not_panic() {
5152 test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
5153 let platform = tester.target_platform();
5154
5155 let (value, visible) = (shared(false), shared(false));
5156 let slot = Rc::new(RefCell::new(None));
5157 let home = first_painted_host(&value, &visible, &slot, true);
5158 pump_app(tester, adaptive_on(platform), move |_app| home);
5159
5160 let at = center(tester);
5162 let mut gesture = TestPointer::touch(1);
5163 tester.down(&mut gesture, at);
5164 tester.pump_by(waft_gestures::K_PRESS_TIMEOUT);
5165 tester.pump_by(Duration::from_millis(50));
5166
5167 tester.up(&gesture);
5170 let state = state(tester);
5171 {
5172 let app = tester.cell.borrow();
5173 assert_eq!(
5174 state.reaction(&app).status(&app),
5175 AnimationStatus::Reverse,
5176 "{platform:?}"
5177 );
5178 }
5179 assert!(value.get());
5180
5181 tester.pump();
5183 drawn(tester);
5184 });
5185 }
5186
5187 #[test]
5188 fn a_switch_first_painted_during_its_toggle_animation_does_not_panic() {
5189 test_widgets_variant(TargetPlatformVariant::new(ALL_PLATFORMS), |tester| {
5190 let platform = tester.target_platform();
5191
5192 let (value, visible) = (shared(false), shared(false));
5193 let slot: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
5194 let home = first_painted_host(&value, &visible, &slot, false);
5195 pump_app(tester, adaptive_on(platform), move |_app| home);
5196 let set_state = slot.borrow().clone().expect("the builder ran");
5197
5198 {
5200 let value = Rc::clone(&value);
5201 set_state(&mut tester.cell.borrow_mut(), &mut move |_app| {
5202 value.set(true)
5203 });
5204 }
5205 tester.pump();
5206 tester.pump(); tester.pump_by(Duration::from_millis(50));
5208 let position = position(tester);
5209 assert!(position > 0.0 && position < 1.0, "{platform:?}: {position}");
5210
5211 {
5213 let visible = Rc::clone(&visible);
5214 set_state(&mut tester.cell.borrow_mut(), &mut move |_app| {
5215 visible.set(true)
5216 });
5217 }
5218 tester.pump();
5219 drawn(tester);
5220 });
5221 }
5222
5223 #[test]
5224 fn an_m2_switch_is_focusable_and_has_its_focus_color() {
5225 test_widgets(|tester| {
5226 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
5227 let node = focus_node(tester);
5228 let value = shared(true);
5229 let orange = Colors::ORANGE.shade500();
5230 let pump = |tester: &mut WidgetTester, enabled: bool| {
5231 pump_host(tester, m2, TextDirection::Ltr, &value, enabled, {
5232 let node = node.clone();
5233 move |value, on_changed| {
5234 Switch::new(value, on_changed)
5235 .focus_color(orange)
5236 .autofocus(true)
5237 .focus_node(node.clone())
5238 }
5239 });
5240 tester.pump_and_settle();
5241 };
5242
5243 pump(tester, true);
5244 assert!(node.has_primary_focus(&tester.cell.borrow()));
5245 assert_paints(
5246 &material_ops(tester),
5247 &m2_pattern(Color::new(0x802196f3), Some(orange), Color::new(0xff2196f3)),
5248 );
5249
5250 value.set(false);
5252 pump(tester, true);
5253 assert!(node.has_primary_focus(&tester.cell.borrow()));
5254 assert_paints(
5255 &material_ops(tester),
5256 &m2_pattern(Color::new(0x52000000), Some(orange), Color::new(0xfffafafa)),
5257 );
5258
5259 pump(tester, false);
5261 assert!(!node.has_primary_focus(&tester.cell.borrow()));
5262 assert_paints(
5263 &material_ops(tester),
5264 &m2_pattern(Color::new(0x1f000000), None, Color::new(0xffbdbdbd)),
5265 );
5266 });
5267 }
5268
5269 #[test]
5271 fn a_material_switch_keeps_its_render_object_when_disabled_mid_animation() {
5272 test_widgets(|tester| {
5273 let (value, enabled) = (shared(true), shared(true));
5274 let slot: Rc<RefCell<Option<StateSetter>>> = Rc::new(RefCell::new(None));
5275 let home = {
5276 let (value, enabled, slot) =
5277 (Rc::clone(&value), Rc::clone(&enabled), Rc::clone(&slot));
5278 StatefulBuilder::new(move |_app, _context, set_state| {
5279 *slot.borrow_mut() = Some(Rc::clone(&set_state));
5280 let on_changed = enabled.get().then(|| {
5281 let value = Rc::clone(&value);
5282 Rc::new(move |app: &mut App, new_value: bool| {
5283 let value = Rc::clone(&value);
5284 set_state(app, &mut move |_app| value.set(new_value));
5285 }) as ValueChanged<bool>
5286 });
5287 Material::new()
5288 .child(Center::new().child(Switch::new(value.get(), on_changed)))
5289 .into_widget()
5290 })
5291 .into_widget()
5292 };
5293 let home = Directionality::new(TextDirection::Ltr, home).into_widget();
5294 pump_app(tester, m3, move |_app| home);
5295 let old_switch_state = state(tester);
5296 let set_state = slot.borrow().clone().expect("the builder ran");
5297
5298 {
5299 let value = Rc::clone(&value);
5300 set_state(&mut tester.cell.borrow_mut(), &mut move |_app| {
5301 value.set(false)
5302 });
5303 }
5304 tester.pump();
5305 {
5307 let enabled = Rc::clone(&enabled);
5308 set_state(&mut tester.cell.borrow_mut(), &mut move |_app| {
5309 enabled.set(false)
5310 });
5311 }
5312 tester.pump();
5313
5314 let updated_switch_state = state(tester);
5315 let app = tester.cell.borrow();
5316 assert!(!updated_switch_state.is_interactive(&app));
5317 assert_eq!(updated_switch_state, old_switch_state);
5318 let status = updated_switch_state.position(&app).status(&app);
5319 assert!(!status.is_completed(), "{status:?}");
5320 assert!(!status.is_dismissed(), "{status:?}");
5321 });
5322 }
5323
5324 #[test]
5325 fn an_m2_thumb_color_resolves_in_the_selected_and_disabled_states() {
5326 test_widgets(|tester| {
5327 const ACTIVE_ENABLED: Color = Color::new(0xFF000001);
5328 const ACTIVE_DISABLED: Color = Color::new(0xFF000002);
5329 const INACTIVE_ENABLED: Color = Color::new(0xFF000003);
5330 const INACTIVE_DISABLED: Color = Color::new(0xFF000004);
5331 let thumb_color = <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
5332 Some(if states.contains(&WidgetState::Disabled) {
5333 if states.contains(&WidgetState::Selected) {
5334 ACTIVE_DISABLED
5335 } else {
5336 INACTIVE_DISABLED
5337 }
5338 } else if states.contains(&WidgetState::Selected) {
5339 ACTIVE_ENABLED
5340 } else {
5341 INACTIVE_ENABLED
5342 })
5343 });
5344 for (index, (enabled, active, track, thumb, reason)) in [
5345 (
5346 false,
5347 false,
5348 c(Colors::BLACK12),
5349 INACTIVE_DISABLED,
5350 "Inactive disabled switch should default track and custom thumb color",
5351 ),
5352 (
5353 false,
5354 true,
5355 c(Colors::BLACK12),
5356 ACTIVE_DISABLED,
5357 "Active disabled switch should match these colors",
5358 ),
5359 (
5360 true,
5361 false,
5362 0x52000000, INACTIVE_ENABLED,
5364 "Inactive enabled switch should match these colors",
5365 ),
5366 (
5367 false,
5368 false,
5369 c(Colors::BLACK12),
5370 INACTIVE_DISABLED,
5371 "Inactive disabled switch should match these colors",
5372 ),
5373 ]
5374 .into_iter()
5375 .enumerate()
5376 {
5377 let home = in_material(
5378 TextDirection::Rtl,
5379 Switch::new(active, if enabled { ignore() } else { None })
5380 .thumb_color(Rc::clone(&thumb_color))
5381 .into_widget(),
5382 );
5383 pump_app(tester, m2, move |_app| home);
5384 if index > 0 {
5385 tester.pump_and_settle();
5386 }
5387 assert_paints_because(
5388 &material_ops(tester),
5389 &m2_pattern(Color::new(track), None, thumb),
5390 reason,
5391 );
5392 }
5393 });
5394 }
5395
5396 #[test]
5397 fn an_m2_thumb_color_resolves_in_the_hovered_and_focused_states() {
5398 test_widgets(|tester| {
5399 const HOVERED: Color = Color::new(0xFF000001);
5400 const FOCUSED: Color = Color::new(0xFF000002);
5401 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
5402 let node = focus_node(tester);
5403 pump_switch(
5404 tester,
5405 m2,
5406 Switch::new(true, ignore())
5407 .focus_node(node.clone())
5408 .autofocus(true)
5409 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
5410 |states| {
5411 Some(if states.contains(&WidgetState::Hovered) {
5412 HOVERED
5413 } else if states.contains(&WidgetState::Focused) {
5414 FOCUSED
5415 } else {
5416 Colors::TRANSPARENT
5417 })
5418 },
5419 )),
5420 );
5421 tester.pump_and_settle();
5422 assert!(node.has_primary_focus(&tester.cell.borrow()));
5423 let assert_painted = |tester: &WidgetTester, thumb: Color| {
5425 let mut pattern = m2_pattern(Color::new(0x802196f3), None, thumb);
5426 pattern.insert(1, PaintCall::circle(None)); assert_paints(&material_ops(tester), &pattern);
5428 };
5429 assert_painted(tester, FOCUSED);
5430
5431 hover(tester);
5433 tester.pump_and_settle();
5434 assert_painted(tester, HOVERED);
5435 });
5436 }
5437
5438 #[test]
5441 fn the_track_color_resolves_in_the_selected_and_disabled_states() {
5442 for (theme, use_material3) in [(m2 as fn(&App) -> ThemeData, false), (m3, true)] {
5443 test_widgets(|tester| {
5444 const ACTIVE_ENABLED: Color = Color::new(0xFF000001);
5445 const ACTIVE_DISABLED: Color = Color::new(0xFF000002);
5446 const INACTIVE_ENABLED: Color = Color::new(0xFF000003);
5447 const INACTIVE_DISABLED: Color = Color::new(0xFF000004);
5448 let track_color =
5449 <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
5450 Some(if states.contains(&WidgetState::Disabled) {
5451 if states.contains(&WidgetState::Selected) {
5452 ACTIVE_DISABLED
5453 } else {
5454 INACTIVE_DISABLED
5455 }
5456 } else if states.contains(&WidgetState::Selected) {
5457 ACTIVE_ENABLED
5458 } else {
5459 INACTIVE_ENABLED
5460 })
5461 });
5462
5463 let (direction, track, last) = if use_material3 {
5464 (
5465 TextDirection::Rtl,
5466 ltrbr(4.0, 8.0, 56.0, 40.0, 16.0),
5467 (true, true, ACTIVE_ENABLED, "Active enabled switch"),
5468 )
5469 } else {
5470 (
5471 TextDirection::Ltr,
5472 ltrbr(13.0, 17.0, 46.0, 31.0, 7.0),
5473 (false, false, INACTIVE_DISABLED, "Inactive disabled switch"),
5474 )
5475 };
5476 for (index, (enabled, active, expected, reason)) in [
5477 (
5478 false,
5479 false,
5480 INACTIVE_DISABLED,
5481 "Inactive disabled switch track",
5482 ),
5483 (false, true, ACTIVE_DISABLED, "Active disabled switch"),
5484 (true, false, INACTIVE_ENABLED, "Inactive enabled switch"),
5485 last,
5486 ]
5487 .into_iter()
5488 .enumerate()
5489 {
5490 let home = in_material(
5491 direction,
5492 Switch::new(active, if enabled { ignore() } else { None })
5493 .track_color(Rc::clone(&track_color))
5494 .into_widget(),
5495 );
5496 pump_app(tester, theme, move |_app| home);
5497 if index > 0 {
5498 tester.pump_and_settle();
5499 }
5500 assert_paints_because(
5501 &material_ops(tester),
5502 &[rrect(Some(track), Some(expected), None)],
5503 reason,
5504 );
5505 }
5506 });
5507 }
5508 }
5509
5510 #[test]
5513 fn the_track_color_resolves_in_the_hovered_and_focused_states() {
5514 for (theme, track) in [
5515 (
5516 m2 as fn(&App) -> ThemeData,
5517 ltrbr(13.0, 17.0, 46.0, 31.0, 7.0),
5518 ),
5519 (m3, ltrbr(4.0, 8.0, 56.0, 40.0, 16.0)),
5520 ] {
5521 test_widgets(|tester| {
5522 const HOVERED: Color = Color::new(0xFF000001);
5523 const FOCUSED: Color = Color::new(0xFF000002);
5524 tester.set_highlight_strategy(FocusHighlightStrategy::AlwaysTraditional);
5525 let node = focus_node(tester);
5526 let home = in_material(
5527 TextDirection::Rtl,
5528 Switch::new(true, ignore())
5529 .focus_node(node.clone())
5530 .autofocus(true)
5531 .track_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
5532 |states| {
5533 Some(if states.contains(&WidgetState::Hovered) {
5534 HOVERED
5535 } else if states.contains(&WidgetState::Focused) {
5536 FOCUSED
5537 } else {
5538 Colors::TRANSPARENT
5539 })
5540 },
5541 ))
5542 .into_widget(),
5543 );
5544 pump_app(tester, theme, move |_app| home);
5545 tester.pump_and_settle();
5546 assert!(node.has_primary_focus(&tester.cell.borrow()));
5547 assert_paints(
5548 &material_ops(tester),
5549 &[rrect(Some(track), Some(FOCUSED), None)],
5550 );
5551
5552 hover(tester);
5554 tester.pump_and_settle();
5555 assert_paints(
5556 &material_ops(tester),
5557 &[rrect(Some(track), Some(HOVERED), None)],
5558 );
5559 });
5560 }
5561 }
5562
5563 #[test]
5566 fn the_thumb_color_is_blended_against_the_surface_color() {
5567 for (theme, use_material3) in [(m2 as fn(&App) -> ThemeData, false), (m3, true)] {
5568 test_widgets(|tester| {
5569 let active_disabled_thumb_color = with_opacity(Colors::BLUE.primary(), 0.60);
5570 let colors_ = colors_of(&tester.cell.borrow(), theme);
5571 let home = in_material(
5572 TextDirection::Rtl,
5573 Switch::new(true, None)
5574 .thumb_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
5575 move |states| {
5576 Some(if states.contains(&WidgetState::Disabled) {
5577 active_disabled_thumb_color
5578 } else {
5579 Colors::BLACK
5580 })
5581 },
5582 ))
5583 .into_widget(),
5584 );
5585 pump_app(tester, theme, move |_app| home);
5586 let expected_thumb_color =
5587 Color::alpha_blend(active_disabled_thumb_color, colors_.surface());
5588 if use_material3 {
5590 assert_paints(
5591 &material_ops(tester),
5592 &[
5593 m3_track(with_opacity(colors_.on_surface(), 0.12), None),
5594 PaintCall::rrect(Some(expected_thumb_color)),
5596 ],
5597 );
5598 } else {
5599 assert_paints(
5600 &material_ops(tester),
5601 &m2_pattern(Colors::BLACK12, None, expected_thumb_color),
5602 );
5603 }
5604 });
5605 }
5606 }
5607
5608 #[test]
5609 fn a_disabled_switch_shows_its_tooltip() {
5610 test_widgets(|tester| {
5611 const LONG_PRESS_TOOLTIP: &str = "long press tooltip";
5612 const TAP_TOOLTIP: &str = "tap tooltip";
5613 let frame = |tester: &mut WidgetTester, tooltip: crate::tooltip::Tooltip| {
5614 tester.pump_widget(
5615 crate::app::MaterialApp::new()
5616 .home(Material::new().child(tooltip.child(Switch::new(true, None))))
5617 .into_widget(),
5618 );
5619 };
5620 let tooltip_center = |tester: &WidgetTester| {
5621 let tooltip = find::by_type::<crate::tooltip::Tooltip>().evaluate(tester)[0];
5622 tester.get_rect(tooltip).center()
5623 };
5624 frame(
5625 tester,
5626 crate::tooltip::Tooltip::new().message(LONG_PRESS_TOOLTIP),
5627 );
5628
5629 expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
5631
5632 let center = tooltip_center(tester);
5633 tester.tap_at(center, 1);
5634 tester.pump_by(Duration::from_millis(10));
5635 expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
5636
5637 let mut gesture_long_press = TestPointer::touch(2);
5638 tester.down(&mut gesture_long_press, center);
5639 tester.pump();
5640 tester.pump_by(waft_gestures::K_LONG_PRESS_TIMEOUT);
5641 tester.up(&gesture_long_press);
5642 tester.pump();
5643
5644 expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_one_widget());
5645
5646 frame(
5648 tester,
5649 crate::tooltip::Tooltip::new()
5650 .trigger_mode(waft_widgets::TooltipTriggerMode::Tap)
5651 .message(TAP_TOOLTIP),
5652 );
5653
5654 tester.pump_by(Duration::from_secs(24 * 60 * 60));
5655 tester.pump_and_settle();
5656 expect(tester, &find::text(TAP_TOOLTIP), finds_nothing());
5657 expect(tester, &find::text(LONG_PRESS_TOOLTIP), finds_nothing());
5658
5659 let center = tooltip_center(tester);
5660 tester.tap_at(center, 3);
5661 tester.pump_by(Duration::from_millis(10));
5662 expect(tester, &find::text(TAP_TOOLTIP), finds_one_widget());
5663 });
5664 }
5665}