1#![allow(deprecated)]
6
7use std::any::TypeId;
8use std::collections::{HashMap, HashSet};
9use std::fmt;
10use std::hash::Hash;
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_embedder::{Canvas, Color, Matrix4, Offset, Paint, RRect, Rect, TextDirection};
15use waft_foundation::{
16 App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, HandleId,
17 IterableProperty, Listenable, ListenableObject, Listener, OptionRetained, Ref, Retained, Timer,
18 ValueChanged,
19};
20use waft_gestures::{
21 GestureLongPressCallback, GestureLongPressUpCallback, GestureTapCallback,
22 GestureTapCancelCallback, GestureTapDownCallback, GestureTapUpCallback, PointerEnterEvent,
23 PointerExitEvent, TapDownDetails, TapUpDetails,
24};
25use waft_painting::{BorderRadius, BoxShape, ShapeBorder, ShapeBorderRef, get_as_translation};
26use waft_rendering::{AnyRenderBox, HitTestBehavior};
27use waft_services::MouseCursorRef;
28use waft_widgets::{
29 ActionRef, Actions, ActivateIntent, AutomaticKeepAliveClientMixin,
30 AutomaticKeepAliveClientMixinData, BuildContext, ButtonActivateIntent, CallbackAction,
31 DefaultSelectionStyle, Directionality, Feedback, Focus, FocusHighlightMode, FocusManager,
32 FocusNodeRef, GestureDetector, HighlightModeListener, InheritedWidget, IntoWidget, KeyRef,
33 MediaQuery, MouseRegion, NavigationMode, Semantics, State, StateData, StatefulWidget,
34 StatelessWidget, WidgetRef, WidgetState, WidgetStateMouseCursor, WidgetStateProperty,
35 WidgetStatePropertyRef, WidgetStates, debug_check_has_directionality,
36};
37
38use crate::debug::debug_check_has_material;
39use crate::ink_highlight::InkHighlight;
40use crate::material::{
41 AnyInkFeature, AnyMaterialInkController, InkFeatureLeaf, InkFeatureLeafData, InkFeatureObject,
42 Material, RectCallback,
43};
44use crate::material_state::MaterialStatesController;
45use crate::theme::Theme;
46
47pub struct InteractiveInkFeatureData {
50 color: Color,
51 custom_border: Option<ShapeBorderRef>,
52}
53
54impl InteractiveInkFeatureData {
55 pub fn new(color: Color, custom_border: Option<ShapeBorderRef>) -> InteractiveInkFeatureData {
57 InteractiveInkFeatureData {
58 color,
59 custom_border,
60 }
61 }
62
63 pub(crate) fn custom_border_ref(&self) -> Option<&dyn ShapeBorder> {
65 self.custom_border.as_deref()
66 }
67}
68
69pub trait InteractiveInkFeatureLeafData: InkFeatureLeafData {
71 fn interactive_ink_feature(&self) -> &InteractiveInkFeatureData;
73
74 fn interactive_ink_feature_mut(&mut self) -> &mut InteractiveInkFeatureData;
76}
77
78pub trait InteractiveInkFeatureLeaf: InkFeatureLeaf + InteractiveInkFeatureLeafData {
94 fn confirm(self: Handle<Self>, app: &mut App) {
99 let _ = (self, app);
100 }
101
102 fn cancel(self: Handle<Self>, app: &mut App) {
107 let _ = (self, app);
108 }
109}
110
111pub trait InteractiveInkFeatureObject: Sized + 'static {
113 fn as_interactive_ink_feature(self: Handle<Self>) -> AnyInteractiveInkFeature;
116}
117
118pub type InteractiveInkFeatureRef = Retained<AnyInteractiveInkFeature>;
120
121waft_foundation::erased_handle!(
122 AnyInteractiveInkFeature: InteractiveInkFeatureLeaf
123 => InteractiveInkFeatureObject::as_interactive_ink_feature
124);
125
126impl<F: InteractiveInkFeatureLeaf> InteractiveInkFeatureObject for F {
127 fn as_interactive_ink_feature(self: Handle<Self>) -> AnyInteractiveInkFeature {
128 AnyInteractiveInkFeature {
129 id: self.id(),
130 vtable: const { &InteractiveInkFeatureVTable::of::<F>() },
131 }
132 }
133}
134
135struct InteractiveInkFeatureVTable {
137 type_name: fn() -> &'static str,
138 as_ink_feature: fn(HandleId) -> AnyInkFeature,
139 confirm: fn(&mut App, HandleId),
140 cancel: fn(&mut App, HandleId),
141 color: fn(&App, HandleId) -> Color,
142 set_color: fn(&mut App, HandleId, Color),
143 custom_border: fn(&App, HandleId) -> Option<ShapeBorderRef>,
144 set_custom_border: fn(&mut App, HandleId, Option<ShapeBorderRef>),
145}
146
147fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
149 Handle::from_id(id)
150}
151
152impl InteractiveInkFeatureVTable {
153 const fn of<F: InteractiveInkFeatureLeaf>() -> InteractiveInkFeatureVTable {
154 InteractiveInkFeatureVTable {
155 type_name: std::any::type_name::<F>,
156 as_ink_feature: |id| resolve::<F>(id).as_ink_feature(),
157 confirm: |app, id| F::confirm(resolve(id), app),
158 cancel: |app, id| F::cancel(resolve(id), app),
159 color: |app, id| InteractiveInkFeature::color(resolve::<F>(id), app),
160 set_color: |app, id, value| {
161 InteractiveInkFeature::set_color(resolve::<F>(id), app, value)
162 },
163 custom_border: |app, id| InteractiveInkFeature::custom_border(resolve::<F>(id), app),
164 set_custom_border: |app, id, value| {
165 InteractiveInkFeature::set_custom_border(resolve::<F>(id), app, value)
166 },
167 }
168 }
169}
170
171#[derive(Clone, Copy)]
175pub struct AnyInteractiveInkFeature {
176 id: HandleId,
177 vtable: &'static InteractiveInkFeatureVTable,
178}
179
180impl fmt::Debug for AnyInteractiveInkFeature {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
183 }
184}
185
186impl AnyInteractiveInkFeature {
187 pub fn id(self) -> HandleId {
189 self.id
190 }
191
192 pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
194 app.handle::<T>(self.id)
195 }
196
197 pub fn as_ink_feature(self) -> AnyInkFeature {
199 (self.vtable.as_ink_feature)(self.id)
200 }
201
202 pub fn confirm(self, app: &mut App) {
204 (self.vtable.confirm)(app, self.id);
205 }
206
207 pub fn cancel(self, app: &mut App) {
209 (self.vtable.cancel)(app, self.id);
210 }
211
212 pub fn dispose(self, app: &mut App) {
214 self.as_ink_feature().dispose(app);
215 }
216
217 pub fn color(self, app: &App) -> Color {
219 (self.vtable.color)(app, self.id)
220 }
221
222 pub fn set_color(self, app: &mut App, value: Color) {
224 (self.vtable.set_color)(app, self.id, value);
225 }
226
227 pub fn custom_border(self, app: &App) -> Option<ShapeBorderRef> {
229 (self.vtable.custom_border)(app, self.id)
230 }
231
232 pub fn set_custom_border(self, app: &mut App, value: Option<ShapeBorderRef>) {
234 (self.vtable.set_custom_border)(app, self.id, value);
235 }
236}
237
238pub struct InteractiveInkFeature;
244
245impl InteractiveInkFeature {
246 pub fn color<F: InteractiveInkFeatureLeaf>(this: Handle<F>, app: &App) -> Color {
248 app.get(this).interactive_ink_feature().color
249 }
250
251 pub fn set_color<F: InteractiveInkFeatureLeaf>(this: Handle<F>, app: &mut App, value: Color) {
253 if value == InteractiveInkFeature::color(this, app) {
254 return;
255 }
256 app.get_mut(this).interactive_ink_feature_mut().color = value;
257 crate::material::InkFeature::controller(this, app).mark_needs_paint(app);
258 }
259
260 pub fn custom_border<F: InteractiveInkFeatureLeaf>(
262 this: Handle<F>,
263 app: &App,
264 ) -> Option<ShapeBorderRef> {
265 app.get(this)
266 .interactive_ink_feature()
267 .custom_border
268 .clone()
269 }
270
271 pub fn set_custom_border<F: InteractiveInkFeatureLeaf>(
273 this: Handle<F>,
274 app: &mut App,
275 value: Option<ShapeBorderRef>,
276 ) {
277 if value == app.get(this).interactive_ink_feature().custom_border {
278 return;
279 }
280 app.get_mut(this)
281 .interactive_ink_feature_mut()
282 .custom_border = value;
283 crate::material::InkFeature::controller(this, app).mark_needs_paint(app);
284 }
285
286 #[allow(clippy::too_many_arguments)]
318 pub fn paint_ink_circle(
319 app: &App,
320 canvas: &mut Canvas,
321 transform: &Matrix4,
322 paint: &Paint,
323 center: Offset,
324 radius: f64,
325 text_direction: Option<TextDirection>,
326 custom_border: Option<&dyn ShapeBorder>,
327 border_radius: BorderRadius,
328 clip_callback: Option<&RectCallback>,
329 ) {
330 let origin_offset = get_as_translation(*transform);
331 canvas.save();
332 match origin_offset {
333 None => canvas.concat(transform),
334 Some(origin_offset) => {
335 canvas.translate(origin_offset.dx() as f32, origin_offset.dy() as f32)
336 }
337 }
338 if let Some(clip_callback) = clip_callback {
339 let rect = clip_callback(app);
340 if let Some(custom_border) = custom_border {
341 let path = custom_border.get_outer_path(rect, text_direction);
342 canvas.clip_path(
343 path.as_valo(),
344 path.fill_type,
345 waft_embedder::ClipOp::Intersect,
346 true,
347 );
348 } else if border_radius != BorderRadius::ZERO {
349 clip_rrect(canvas, rrect_from_rect_and_corners(rect, border_radius));
350 } else {
351 canvas.clip_rect(rect, waft_embedder::ClipOp::Intersect, true);
352 }
353 }
354 canvas.draw_circle(center, radius as f32, paint);
355 canvas.restore();
356 }
357}
358
359pub(crate) fn rrect_from_rect_and_corners(rect: Rect, border_radius: BorderRadius) -> RRect {
362 RRect::from_rect_and_corners(
363 rect,
364 border_radius.top_left,
365 border_radius.top_right,
366 border_radius.bottom_right,
367 border_radius.bottom_left,
368 )
369}
370
371pub(crate) fn clip_rrect(canvas: &mut Canvas, rrect: RRect) {
373 canvas.clip_rrect_radii_elliptical(
374 rrect.outer_rect(),
375 waft_embedder::rrect_radii_elliptical(rrect),
376 waft_embedder::ClipOp::Intersect,
377 true,
378 );
379}
380
381pub trait InteractiveInkFeatureFactory: fmt::Debug {
394 #[allow(clippy::too_many_arguments)]
399 fn create(
400 &self,
401 app: &mut App,
402 controller: AnyMaterialInkController,
403 reference_box: AnyRenderBox,
404 position: Offset,
405 color: Color,
406 text_direction: TextDirection,
407 contained_ink_well: bool,
408 rect_callback: Option<RectCallback>,
409 border_radius: Option<BorderRadius>,
410 custom_border: Option<ShapeBorderRef>,
411 radius: Option<f64>,
412 on_removed: Option<Listener>,
413 ) -> InteractiveInkFeatureRef;
414}
415
416pub type InteractiveInkFeatureFactoryRef = Rc<dyn InteractiveInkFeatureFactory>;
419
420impl PartialEq for dyn InteractiveInkFeatureFactory {
422 fn eq(&self, other: &dyn InteractiveInkFeatureFactory) -> bool {
423 std::ptr::addr_eq(
424 self as *const dyn InteractiveInkFeatureFactory,
425 other as *const dyn InteractiveInkFeatureFactory,
426 )
427 }
428}
429
430#[derive(Debug)]
432struct ParentInkResponseProvider {
433 state: Handle<InkResponseState>,
434 child: WidgetRef,
435}
436
437impl ParentInkResponseProvider {
438 fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<InkResponseState>> {
439 context
440 .depend_on_inherited_widget_of_exact_type::<ParentInkResponseProvider>(app)
441 .map(|provider| provider.state)
442 }
443}
444
445impl InheritedWidget for ParentInkResponseProvider {
446 fn child(&self) -> &WidgetRef {
447 &self.child
448 }
449
450 fn update_should_notify(&self, old_widget: &ParentInkResponseProvider) -> bool {
451 self.state != old_widget.state
452 }
453}
454
455pub type GetRectCallback = Rc<dyn Fn(&App, AnyRenderBox) -> Option<RectCallback>>;
457
458pub type CheckContext = Rc<dyn Fn(&App, BuildContext) -> bool>;
460
461#[derive(Clone)]
525pub struct InkResponse {
526 pub key: Option<KeyRef>,
527
528 pub child: Option<WidgetRef>,
530
531 pub on_tap: Option<GestureTapCallback>,
533
534 pub on_tap_down: Option<GestureTapDownCallback>,
536
537 pub on_tap_up: Option<GestureTapUpCallback>,
540
541 pub on_tap_cancel: Option<GestureTapCallback>,
544
545 pub on_double_tap: Option<GestureTapCallback>,
547
548 pub on_long_press: Option<GestureLongPressCallback>,
550
551 pub on_long_press_up: Option<GestureLongPressUpCallback>,
564
565 pub on_secondary_tap: Option<GestureTapCallback>,
571
572 pub on_secondary_tap_down: Option<GestureTapDownCallback>,
579
580 pub on_secondary_tap_up: Option<GestureTapUpCallback>,
590
591 pub on_secondary_tap_cancel: Option<GestureTapCallback>,
598
599 pub on_tertiary_tap_down: Option<GestureTapDownCallback>,
609
610 pub on_tertiary_tap_up: Option<GestureTapUpCallback>,
619
620 pub on_tertiary_tap_cancel: Option<GestureTapCancelCallback>,
627
628 pub on_highlight_changed: Option<ValueChanged<bool>>,
643
644 pub on_hover: Option<ValueChanged<bool>>,
650
651 pub mouse_cursor: Option<MouseCursorRef>,
663
664 pub contained_ink_well: bool,
680
681 pub highlight_shape: BoxShape,
703
704 pub radius: Option<f64>,
716
717 pub border_radius: Option<BorderRadius>,
722
723 pub custom_border: Option<ShapeBorderRef>,
727
728 pub focus_color: Option<Color>,
741
742 pub hover_color: Option<Color>,
756
757 pub highlight_color: Option<Color>,
771
772 pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
797
798 pub splash_color: Option<Color>,
808
809 pub splash_factory: Option<InteractiveInkFeatureFactoryRef>,
823
824 pub enable_feedback: bool,
833
834 pub exclude_from_semantics: bool,
842
843 pub on_focus_change: Option<ValueChanged<bool>>,
848
849 pub autofocus: bool,
852
853 pub focus_node: Option<FocusNodeRef>,
855
856 pub can_request_focus: bool,
858
859 pub states_controller: Option<Ref<MaterialStatesController>>,
869
870 pub hover_duration: Option<Duration>,
874
875 pub get_rect_callback: GetRectCallback,
880
881 pub debug_check_context: CheckContext,
888}
889
890impl fmt::Debug for InkResponse {
891 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892 f.debug_struct("InkResponse")
893 .field("contained_ink_well", &self.contained_ink_well)
894 .field("highlight_shape", &self.highlight_shape)
895 .field("child", &self.child)
896 .finish_non_exhaustive()
897 }
898}
899
900impl Default for InkResponse {
901 fn default() -> InkResponse {
902 InkResponse {
903 key: None,
904 child: None,
905 on_tap: None,
906 on_tap_down: None,
907 on_tap_up: None,
908 on_tap_cancel: None,
909 on_double_tap: None,
910 on_long_press: None,
911 on_long_press_up: None,
912 on_secondary_tap: None,
913 on_secondary_tap_down: None,
914 on_secondary_tap_up: None,
915 on_secondary_tap_cancel: None,
916 on_tertiary_tap_down: None,
917 on_tertiary_tap_up: None,
918 on_tertiary_tap_cancel: None,
919 on_highlight_changed: None,
920 on_hover: None,
921 mouse_cursor: None,
922 contained_ink_well: false,
923 highlight_shape: BoxShape::Circle,
924 radius: None,
925 border_radius: None,
926 custom_border: None,
927 focus_color: None,
928 hover_color: None,
929 highlight_color: None,
930 overlay_color: None,
931 splash_color: None,
932 splash_factory: None,
933 enable_feedback: true,
934 exclude_from_semantics: false,
935 on_focus_change: None,
936 autofocus: false,
937 focus_node: None,
938 can_request_focus: true,
939 states_controller: None,
940 hover_duration: None,
941 get_rect_callback: Rc::new(|_app, _reference_box| None),
942 debug_check_context: Rc::new(InkResponse::debug_check_context),
943 }
944 }
945}
946
947macro_rules! ink_response_setters {
950 ($name:ident, $($field:ident: $ty:ty),* $(,)?) => {
951 $(
952 #[doc = concat!("Dart `", stringify!($name), "(", stringify!($field), ":)`.")]
953 pub fn $field(mut self, $field: $ty) -> $name {
954 self.ink_response_mut().$field = Some($field);
955 self
956 }
957 )*
958 };
959}
960
961macro_rules! ink_response_value_setters {
963 ($name:ident, $($field:ident: $ty:ty),* $(,)?) => {
964 $(
965 #[doc = concat!("Dart `", stringify!($name), "(", stringify!($field), ":)`.")]
966 pub fn $field(mut self, $field: $ty) -> $name {
967 self.ink_response_mut().$field = $field;
968 self
969 }
970 )*
971 };
972}
973
974macro_rules! ink_response_shared_setters {
976 ($name:ident) => {
977 ink_response_setters!(
978 $name,
979 key: KeyRef,
980 on_tap: GestureTapCallback,
981 on_tap_down: GestureTapDownCallback,
982 on_tap_up: GestureTapUpCallback,
983 on_tap_cancel: GestureTapCallback,
984 on_double_tap: GestureTapCallback,
985 on_long_press: GestureLongPressCallback,
986 on_long_press_up: GestureLongPressUpCallback,
987 on_secondary_tap: GestureTapCallback,
988 on_secondary_tap_up: GestureTapUpCallback,
989 on_secondary_tap_down: GestureTapDownCallback,
990 on_secondary_tap_cancel: GestureTapCallback,
991 on_tertiary_tap_up: GestureTapUpCallback,
992 on_tertiary_tap_down: GestureTapDownCallback,
993 on_tertiary_tap_cancel: GestureTapCancelCallback,
994 on_highlight_changed: ValueChanged<bool>,
995 on_hover: ValueChanged<bool>,
996 mouse_cursor: MouseCursorRef,
997 radius: f64,
998 border_radius: BorderRadius,
999 focus_color: Color,
1000 hover_color: Color,
1001 highlight_color: Color,
1002 overlay_color: WidgetStatePropertyRef<Option<Color>>,
1003 splash_color: Color,
1004 splash_factory: InteractiveInkFeatureFactoryRef,
1005 on_focus_change: ValueChanged<bool>,
1006 focus_node: FocusNodeRef,
1007 states_controller: Ref<MaterialStatesController>,
1008 hover_duration: Duration,
1009 );
1010 ink_response_value_setters!(
1011 $name,
1012 enable_feedback: bool,
1013 exclude_from_semantics: bool,
1014 can_request_focus: bool,
1015 autofocus: bool,
1016 );
1017
1018 #[doc = concat!("Dart `", stringify!($name), "(child:)`.")]
1019 #[cfg_attr(debug_assertions, track_caller)]
1020 pub fn child<K>(mut self, child: impl IntoWidget<K>) -> $name {
1021 self.ink_response_mut().child = Some(child.into_widget());
1022 self
1023 }
1024
1025 #[doc = concat!("Dart `", stringify!($name), "(customBorder:)`.")]
1026 pub fn custom_border(mut self, custom_border: impl Into<ShapeBorderRef>) -> $name {
1027 self.ink_response_mut().custom_border = Some(custom_border.into());
1028 self
1029 }
1030
1031 pub fn override_get_rect_callback(
1034 mut self,
1035 get_rect_callback: impl Fn(&App, AnyRenderBox) -> Option<RectCallback> + 'static,
1036 ) -> $name {
1037 self.ink_response_mut().get_rect_callback = Rc::new(get_rect_callback);
1038 self
1039 }
1040
1041 pub fn override_debug_check_context(
1047 mut self,
1048 debug_check_context: impl Fn(&App, BuildContext) -> bool + 'static,
1049 ) -> $name {
1050 self.ink_response_mut().debug_check_context = Rc::new(debug_check_context);
1051 self
1052 }
1053 };
1054}
1055
1056impl InkResponse {
1057 pub fn new() -> InkResponse {
1062 InkResponse::default()
1063 }
1064
1065 fn ink_response_mut(&mut self) -> &mut InkResponse {
1066 self
1067 }
1068
1069 ink_response_shared_setters!(InkResponse);
1070
1071 ink_response_value_setters!(
1072 InkResponse,
1073 contained_ink_well: bool,
1074 highlight_shape: BoxShape,
1075 );
1076
1077 pub fn get_rect_callback(
1089 &self,
1090 app: &App,
1091 reference_box: AnyRenderBox,
1092 ) -> Option<RectCallback> {
1093 (self.get_rect_callback)(app, reference_box)
1094 }
1095
1096 pub fn debug_check_context(app: &App, context: BuildContext) -> bool {
1104 debug_assert!(debug_check_has_material(app, context));
1105 debug_assert!(debug_check_has_directionality(
1106 app, context, None, None, None
1107 ));
1108 true
1109 }
1110
1111 pub(crate) fn build_state_widget(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1112 let parent_state = ParentInkResponseProvider::maybe_of(app, context);
1113 InkResponseStateWidget {
1114 response: self.clone(),
1115 parent_state,
1116 }
1117 .into_widget()
1118 }
1119}
1120
1121impl StatelessWidget for InkResponse {
1122 fn key(&self) -> Option<&KeyRef> {
1123 self.key.as_ref()
1124 }
1125
1126 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1127 self.build_state_widget(app, context)
1128 }
1129}
1130
1131#[derive(Debug)]
1134struct InkResponseStateWidget {
1135 response: InkResponse,
1136 parent_state: Option<Handle<InkResponseState>>,
1137}
1138
1139impl StatefulWidget for InkResponseStateWidget {
1140 type State = InkResponseState;
1141
1142 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1143 let response = &self.response;
1144 let gestures: Vec<String> = [
1145 (response.on_tap.is_some(), "tap"),
1146 (response.on_double_tap.is_some(), "double tap"),
1147 (response.on_long_press.is_some(), "long press"),
1148 (response.on_long_press_up.is_some(), "long press up"),
1149 (response.on_tap_down.is_some(), "tap down"),
1150 (response.on_tap_up.is_some(), "tap up"),
1151 (response.on_tap_cancel.is_some(), "tap cancel"),
1152 (response.on_secondary_tap.is_some(), "secondary tap"),
1153 (response.on_secondary_tap_up.is_some(), "secondary tap up"),
1154 (
1155 response.on_secondary_tap_down.is_some(),
1156 "secondary tap down",
1157 ),
1158 (
1159 response.on_secondary_tap_cancel.is_some(),
1160 "secondary tap cancel",
1161 ),
1162 ]
1163 .into_iter()
1164 .filter(|(present, _)| *present)
1165 .map(|(_, name)| name.to_string())
1166 .collect();
1167 properties
1168 .add(IterableProperty::<String>::new("gestures", Some(gestures)).if_empty("<none>"));
1169 properties.add(DiagnosticsProperty::<String>::new(
1170 "mouseCursor",
1171 response
1172 .mouse_cursor
1173 .as_ref()
1174 .map(|cursor| cursor.debug_description()),
1175 ));
1176 properties.add(
1177 DiagnosticsProperty::<bool>::new("containedInkWell", response.contained_ink_well)
1178 .with_level(DiagnosticLevel::Fine),
1179 );
1180 properties.add(
1181 DiagnosticsProperty::<BoxShape>::new("highlightShape", Some(response.highlight_shape))
1182 .description(format!(
1183 "{}{}",
1184 if response.contained_ink_well {
1185 "clipped to "
1186 } else {
1187 ""
1188 },
1189 response.highlight_shape
1190 ))
1191 .with_show_name(false),
1192 );
1193 }
1194
1195 fn create_state(&self) -> InkResponseState {
1196 InkResponseState {
1197 state: StateData::new(),
1198 automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
1199 splashes: None,
1200 current_splash: None,
1201 hovering: false,
1202 highlights: HashMap::new(),
1203 action_map: HashMap::new(),
1204 internal_states_controller: None,
1205 active_children: Vec::new(),
1206 activation_timer: None,
1207 has_focus: false,
1208 focus_highlight_mode_listener: None,
1209 }
1210 }
1211}
1212
1213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1216enum HighlightType {
1217 Pressed,
1218 Hover,
1219 Focus,
1220}
1221
1222struct InkResponseState {
1224 state: StateData<InkResponseStateWidget>,
1225 automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
1226 splashes: Option<HashSet<InteractiveInkFeatureRef>>,
1227 current_splash: Option<InteractiveInkFeatureRef>,
1228 hovering: bool,
1229 highlights: HashMap<HighlightType, Option<Ref<InkHighlight>>>,
1230 action_map: HashMap<TypeId, ActionRef>,
1231 internal_states_controller: Option<Ref<MaterialStatesController>>,
1232 active_children: Vec<Handle<InkResponseState>>,
1233 activation_timer: Option<Timer>,
1234 has_focus: bool,
1235 focus_highlight_mode_listener: Option<HighlightModeListener>,
1236}
1237
1238impl InkResponseState {
1239 const ACTIVATION_DURATION: Duration = Duration::from_millis(100);
1240
1241 fn highlights_exist(self: Handle<Self>, app: &App) -> bool {
1242 app.get(self).highlights.values().any(Option::is_some)
1243 }
1244
1245 fn mark_child_ink_response_pressed(
1246 self: Handle<Self>,
1247 app: &mut App,
1248 child_state: Handle<InkResponseState>,
1249 value: bool,
1250 ) {
1251 let last_any_pressed = self.any_child_ink_response_pressed(app);
1252 let active_children = &mut app.get_mut(self).active_children;
1253 if value {
1254 active_children.push(child_state);
1255 } else if let Some(index) = active_children
1256 .iter()
1257 .position(|child| *child == child_state)
1258 {
1259 active_children.remove(index);
1260 }
1261 let now_any_pressed = self.any_child_ink_response_pressed(app);
1262 if now_any_pressed != last_any_pressed
1263 && let Some(parent_state) = self.widget(app).parent_state
1264 {
1265 parent_state.mark_child_ink_response_pressed(app, self, now_any_pressed);
1266 }
1267 }
1268
1269 fn any_child_ink_response_pressed(self: Handle<Self>, app: &App) -> bool {
1270 !app.get(self).active_children.is_empty()
1271 }
1272
1273 fn activate_on_intent(self: Handle<Self>, app: &mut App) {
1274 if let Some(timer) = app.get_mut(self).activation_timer.take() {
1275 timer.cancel(app);
1276 }
1277 let context = self.context(app);
1278 self.start_new_splash(app, None, Some(context));
1279 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1280 current_splash.confirm(app);
1281 }
1282 if let Some(on_tap) = self.widget(app).response.on_tap.clone() {
1283 if self.widget(app).response.enable_feedback {
1284 Feedback::for_tap(app, context);
1285 }
1286 on_tap.call(app);
1287 }
1288 let timer = Timer::new(
1291 app,
1292 Self::ACTIVATION_DURATION,
1293 Listener::new(move |app| {
1294 self.update_highlight(app, HighlightType::Pressed, false, true);
1295 }),
1296 );
1297 app.get_mut(self).activation_timer = Some(timer);
1298 }
1299
1300 fn simulate_tap(self: Handle<Self>, app: &mut App) {
1302 let context = self.context(app);
1303 self.start_new_splash(app, None, Some(context));
1304 self.handle_tap(app);
1305 }
1306
1307 fn simulate_long_press(self: Handle<Self>, app: &mut App) {
1309 let context = self.context(app);
1310 self.start_new_splash(app, None, Some(context));
1311 self.handle_long_press(app);
1312 }
1313
1314 fn handle_states_controller_change(self: Handle<Self>, app: &mut App) {
1315 self.set_state(app, |_state| {});
1317 }
1318
1319 fn states_controller(self: Handle<Self>, app: &App) -> Handle<MaterialStatesController> {
1320 self.widget(app)
1321 .response
1322 .states_controller
1323 .handle()
1324 .or(app.get(self).internal_states_controller.handle())
1325 .expect("created in init_states_controller")
1326 }
1327
1328 fn states(self: Handle<Self>, app: &App) -> WidgetStates {
1329 app.get(self.states_controller(app)).value().clone()
1330 }
1331
1332 fn init_states_controller(self: Handle<Self>, app: &mut App) {
1333 if self.widget(app).response.states_controller.is_none() {
1334 let controller = MaterialStatesController::new(app, None);
1335 app.get_mut(self).internal_states_controller = Some(controller);
1336 }
1337 let enabled = self.enabled(app);
1338 let states_controller = self.states_controller(app);
1339 states_controller.update(app, WidgetState::Disabled, !enabled);
1340 states_controller.add_listener(
1341 app,
1342 Listener::handle_method(self, Self::handle_states_controller_change),
1343 );
1344 }
1345
1346 fn get_fade_duration_for_type(
1347 self: Handle<Self>,
1348 app: &App,
1349 r#type: HighlightType,
1350 ) -> Duration {
1351 match r#type {
1352 HighlightType::Pressed => Duration::from_millis(200),
1353 HighlightType::Hover | HighlightType::Focus => self
1354 .widget(app)
1355 .response
1356 .hover_duration
1357 .unwrap_or(Duration::from_millis(50)),
1358 }
1359 }
1360
1361 fn update_highlight(
1362 self: Handle<Self>,
1363 app: &mut App,
1364 r#type: HighlightType,
1365 value: bool,
1366 call_on_hover: bool,
1367 ) {
1368 let highlight = app
1369 .get(self)
1370 .highlights
1371 .get(&r#type)
1372 .and_then(|highlight| highlight.handle());
1373 let handle_ink_removal = Listener::new(move |app| {
1374 debug_assert!(
1375 app.get(self)
1376 .highlights
1377 .get(&r#type)
1378 .and_then(|highlight| highlight.handle())
1379 .is_some()
1380 );
1381 app.get_mut(self).highlights.insert(r#type, None);
1382 self.update_keep_alive(app);
1383 });
1384
1385 let states_controller = self.states_controller(app);
1386 match r#type {
1387 HighlightType::Pressed => {
1388 states_controller.update(app, WidgetState::Pressed, value);
1389 }
1390 HighlightType::Hover => {
1391 if call_on_hover {
1392 states_controller.update(app, WidgetState::Hovered, value);
1393 }
1394 }
1395 HighlightType::Focus => {
1396 }
1398 }
1399
1400 if r#type == HighlightType::Pressed
1401 && let Some(parent_state) = self.widget(app).parent_state
1402 {
1403 parent_state.mark_child_ink_response_pressed(app, self, value);
1404 }
1405 if value == highlight.is_some_and(|highlight| highlight.active(app)) {
1406 return;
1407 }
1408
1409 if value {
1410 match highlight {
1411 None => {
1412 let response = self.widget(app).response.clone();
1413 let states = self.states(app);
1414 let context = self.context(app);
1415 let resolved_overlay_color = response
1416 .overlay_color
1417 .as_ref()
1418 .and_then(|overlay_color| overlay_color.resolve(&states))
1419 .unwrap_or_else(|| match r#type {
1420 HighlightType::Pressed => response
1422 .highlight_color
1423 .unwrap_or_else(|| Theme::of(app, context).highlight_color),
1424 HighlightType::Focus => response
1425 .focus_color
1426 .unwrap_or_else(|| Theme::of(app, context).focus_color),
1427 HighlightType::Hover => response
1428 .hover_color
1429 .unwrap_or_else(|| Theme::of(app, context).hover_color),
1430 });
1431 let reference_box = context
1432 .find_render_object(app)
1433 .and_then(|render_object| render_object.as_box())
1434 .expect("an ink response has a render box");
1435 let enabled = self.enabled(app);
1436 let controller = Material::of(app, context);
1437 let rect_callback = response.get_rect_callback(app, reference_box);
1438 let text_direction = Directionality::of(app, context);
1439 let fade_duration = self.get_fade_duration_for_type(app, r#type);
1440 let created = InkHighlight::new(
1441 app,
1442 controller,
1443 reference_box,
1444 if enabled {
1445 resolved_overlay_color
1446 } else {
1447 resolved_overlay_color.with_alpha(0)
1448 },
1449 text_direction,
1450 response.highlight_shape,
1451 response.radius,
1452 response.border_radius,
1453 response.custom_border.clone(),
1454 rect_callback,
1455 Some(handle_ink_removal),
1456 fade_duration,
1457 );
1458 app.get_mut(self).highlights.insert(r#type, Some(created));
1459 self.update_keep_alive(app);
1460 }
1461 Some(highlight) => highlight.activate(app),
1462 }
1463 } else {
1464 highlight
1465 .expect("an active highlight exists")
1466 .deactivate(app);
1467 }
1468 debug_assert!(
1469 value
1470 == app
1471 .get(self)
1472 .highlights
1473 .get(&r#type)
1474 .and_then(|highlight| highlight.handle())
1475 .is_some_and(|highlight| highlight.active(app))
1476 );
1477
1478 match r#type {
1479 HighlightType::Pressed => {
1480 if let Some(on_highlight_changed) =
1481 self.widget(app).response.on_highlight_changed.clone()
1482 {
1483 on_highlight_changed(app, value);
1484 }
1485 }
1486 HighlightType::Hover => {
1487 if call_on_hover && let Some(on_hover) = self.widget(app).response.on_hover.clone()
1488 {
1489 on_hover(app, value);
1490 }
1491 }
1492 HighlightType::Focus => {}
1493 }
1494 }
1495
1496 fn update_highlights_and_splashes(self: Handle<Self>, app: &mut App) {
1497 let custom_border = self.widget(app).response.custom_border.clone();
1498 let highlights: Vec<Handle<InkHighlight>> = app
1499 .get(self)
1500 .highlights
1501 .values()
1502 .flatten()
1503 .map(Retained::handle)
1504 .collect();
1505 for highlight in highlights {
1506 InteractiveInkFeature::set_custom_border(highlight, app, custom_border.clone());
1507 }
1508 if let Some(current_splash) = app.get(self).current_splash.handle() {
1509 current_splash.set_custom_border(app, custom_border.clone());
1510 }
1511
1512 let splashes: Vec<AnyInteractiveInkFeature> = app
1513 .get(self)
1514 .splashes
1515 .iter()
1516 .flatten()
1517 .map(Retained::handle)
1518 .collect();
1519 for ink_feature in splashes {
1520 ink_feature.set_custom_border(app, custom_border.clone());
1521 }
1522 }
1523
1524 fn create_splash(
1525 self: Handle<Self>,
1526 app: &mut App,
1527 global_position: Offset,
1528 ) -> InteractiveInkFeatureRef {
1529 let context = self.context(app);
1530 let ink_controller = Material::of(app, context);
1531 let reference_box = context
1532 .find_render_object(app)
1533 .and_then(|render_object| render_object.as_box())
1534 .expect("an ink response has a render box");
1535 let position = reference_box.global_to_local(app, global_position, None);
1536 let response = self.widget(app).response.clone();
1537 let states = self.states(app);
1538 let color = response
1539 .overlay_color
1540 .as_ref()
1541 .and_then(|overlay_color| overlay_color.resolve(&states))
1542 .or(response.splash_color)
1543 .unwrap_or_else(|| Theme::of(app, context).splash_color);
1544 let rect_callback = if response.contained_ink_well {
1545 response.get_rect_callback(app, reference_box)
1546 } else {
1547 None
1548 };
1549 let border_radius = response.border_radius;
1550 let custom_border = response.custom_border.clone();
1551
1552 let splash: Rc<std::cell::Cell<Option<AnyInteractiveInkFeature>>> = Rc::default();
1553 let on_removed = Listener::new({
1554 let splash = Rc::clone(&splash);
1555 move |app| {
1556 let splash = splash.get();
1557 if let Some(splashes) = &mut app.get_mut(self).splashes {
1558 debug_assert!(splash.is_some_and(|splash| splashes.contains(&splash)));
1559 if let Some(splash) = splash {
1560 splashes.remove(&splash);
1561 }
1562 if app.get(self).current_splash.handle() == splash {
1563 app.get_mut(self).current_splash = None;
1564 }
1565 self.update_keep_alive(app);
1566 } }
1568 });
1569
1570 let splash_factory = response
1571 .splash_factory
1572 .clone()
1573 .unwrap_or_else(|| Theme::of(app, context).splash_factory.clone());
1574 let text_direction = Directionality::of(app, context);
1575 let created = splash_factory.create(
1576 app,
1577 ink_controller,
1578 reference_box,
1579 position,
1580 color,
1581 text_direction,
1582 response.contained_ink_well,
1583 rect_callback,
1584 border_radius,
1585 custom_border,
1586 response.radius,
1587 Some(on_removed),
1588 );
1589 splash.set(Some(created.handle()));
1590 created
1591 }
1592
1593 fn handle_focus_highlight_mode_change(
1594 self: Handle<Self>,
1595 app: &mut App,
1596 _mode: FocusHighlightMode,
1597 ) {
1598 if !self.mounted(app) {
1599 return;
1600 }
1601 self.update_focus_highlights(app);
1602 self.set_state(app, |_state| {});
1603 }
1604
1605 fn should_show_focus(self: Handle<Self>, app: &mut App) -> bool {
1606 let context = self.context(app);
1607 match MediaQuery::maybe_navigation_mode_of(app, context) {
1608 Some(NavigationMode::Traditional) | None => {
1609 self.enabled(app) && app.get(self).has_focus
1610 }
1611 Some(NavigationMode::Directional) => app.get(self).has_focus,
1612 }
1613 }
1614
1615 fn update_focus_highlights(self: Handle<Self>, app: &mut App) {
1616 let show_focus = match FocusManager::instance(app).highlight_mode(app) {
1617 FocusHighlightMode::Touch => false,
1618 FocusHighlightMode::Traditional => self.should_show_focus(app),
1619 };
1620 self.update_highlight(app, HighlightType::Focus, show_focus, true);
1621 }
1622
1623 fn handle_focus_update(self: Handle<Self>, app: &mut App, has_focus: bool) {
1624 app.get_mut(self).has_focus = has_focus;
1625 self.states_controller(app)
1630 .update(app, WidgetState::Focused, has_focus);
1631 self.update_focus_highlights(app);
1632 if let Some(on_focus_change) = self.widget(app).response.on_focus_change.clone() {
1633 on_focus_change(app, has_focus);
1634 }
1635 }
1636
1637 fn handle_any_tap_down(self: Handle<Self>, app: &mut App, details: &TapDownDetails) {
1638 if self.any_child_ink_response_pressed(app) {
1639 return;
1640 }
1641 self.start_new_splash(app, Some(details), None);
1642 }
1643
1644 fn handle_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
1645 self.handle_any_tap_down(app, &details);
1646 if let Some(on_tap_down) = self.widget(app).response.on_tap_down.clone() {
1647 on_tap_down(app, details);
1648 }
1649 }
1650
1651 fn handle_tap_up(self: Handle<Self>, app: &mut App, details: TapUpDetails) {
1652 if let Some(on_tap_up) = self.widget(app).response.on_tap_up.clone() {
1653 on_tap_up(app, details);
1654 }
1655 }
1656
1657 fn handle_secondary_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
1658 self.handle_any_tap_down(app, &details);
1659 if let Some(on_secondary_tap_down) = self.widget(app).response.on_secondary_tap_down.clone()
1660 {
1661 on_secondary_tap_down(app, details);
1662 }
1663 }
1664
1665 fn handle_secondary_tap_up(self: Handle<Self>, app: &mut App, details: TapUpDetails) {
1666 if let Some(on_secondary_tap_up) = self.widget(app).response.on_secondary_tap_up.clone() {
1667 on_secondary_tap_up(app, details);
1668 }
1669 }
1670
1671 fn handle_tertiary_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
1672 self.handle_any_tap_down(app, &details);
1673 if let Some(on_tertiary_tap_down) = self.widget(app).response.on_tertiary_tap_down.clone() {
1674 on_tertiary_tap_down(app, details);
1675 }
1676 }
1677
1678 fn handle_tertiary_tap_up(self: Handle<Self>, app: &mut App, details: TapUpDetails) {
1679 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1680 current_splash.confirm(app);
1681 }
1682 self.update_highlight(app, HighlightType::Pressed, false, true);
1683 if let Some(on_tertiary_tap_up) = self.widget(app).response.on_tertiary_tap_up.clone() {
1684 on_tertiary_tap_up(app, details);
1685 }
1686 }
1687
1688 fn handle_tertiary_tap_cancel(self: Handle<Self>, app: &mut App) {
1689 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1690 current_splash.cancel(app);
1691 }
1692 if let Some(on_tertiary_tap_cancel) =
1693 self.widget(app).response.on_tertiary_tap_cancel.clone()
1694 {
1695 on_tertiary_tap_cancel.call(app);
1696 }
1697 self.update_highlight(app, HighlightType::Pressed, false, true);
1698 }
1699
1700 fn start_new_splash(
1701 self: Handle<Self>,
1702 app: &mut App,
1703 details: Option<&TapDownDetails>,
1704 context: Option<BuildContext>,
1705 ) {
1706 debug_assert!(details.is_some() || context.is_some());
1707
1708 let global_position = match context {
1709 Some(context) => {
1710 let reference_box = context
1711 .find_render_object(app)
1712 .and_then(|render_object| render_object.as_box())
1713 .expect("an ink response has a render box");
1714 debug_assert!(
1715 reference_box.has_size(app),
1716 "InkResponse must be done with layout before starting a splash."
1717 );
1718 let center = reference_box.as_object().paint_bounds(app).center();
1719 reference_box.local_to_global(app, center, None)
1720 }
1721 None => details.expect("asserted above").global_position,
1722 };
1723 self.states_controller(app)
1724 .update(app, WidgetState::Pressed, true); let splash = self.create_splash(app, global_position);
1726 app.get_mut(self)
1727 .splashes
1728 .get_or_insert_with(HashSet::new)
1729 .insert(splash.clone());
1730 if let Some(current_splash) = app.get(self).current_splash.handle() {
1731 current_splash.cancel(app);
1732 }
1733 app.get_mut(self).current_splash = Some(splash);
1734 self.update_keep_alive(app);
1735 self.update_highlight(app, HighlightType::Pressed, true, true);
1736 }
1737
1738 fn handle_tap(self: Handle<Self>, app: &mut App) {
1739 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1740 current_splash.confirm(app);
1741 }
1742 self.update_highlight(app, HighlightType::Pressed, false, true);
1743 if let Some(on_tap) = self.widget(app).response.on_tap.clone() {
1744 if self.widget(app).response.enable_feedback {
1745 let context = self.context(app);
1746 Feedback::for_tap(app, context);
1747 }
1748 on_tap.call(app);
1749 }
1750 }
1751
1752 fn handle_tap_cancel(self: Handle<Self>, app: &mut App) {
1753 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1754 current_splash.cancel(app);
1755 }
1756 if let Some(on_tap_cancel) = self.widget(app).response.on_tap_cancel.clone() {
1757 on_tap_cancel.call(app);
1758 }
1759 self.update_highlight(app, HighlightType::Pressed, false, true);
1760 }
1761
1762 fn handle_double_tap(self: Handle<Self>, app: &mut App) {
1765 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1766 current_splash.confirm(app);
1767 }
1768 self.update_highlight(app, HighlightType::Pressed, false, true);
1769 if let Some(on_double_tap) = self.widget(app).response.on_double_tap.clone() {
1770 on_double_tap.call(app);
1771 }
1772 }
1773
1774 fn handle_long_press(self: Handle<Self>, app: &mut App) {
1775 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1776 current_splash.confirm(app);
1777 }
1778 if let Some(on_long_press) = self.widget(app).response.on_long_press.clone() {
1779 if self.widget(app).response.enable_feedback {
1780 let context = self.context(app);
1781 Feedback::for_long_press(app, context);
1782 }
1783 on_long_press.call(app);
1784 }
1785 }
1786
1787 fn handle_long_press_up(self: Handle<Self>, app: &mut App) {
1788 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1789 current_splash.confirm(app);
1790 }
1791 if let Some(on_long_press_up) = self.widget(app).response.on_long_press_up.clone() {
1792 on_long_press_up.call(app);
1793 }
1794 }
1795
1796 fn handle_secondary_tap(self: Handle<Self>, app: &mut App) {
1797 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1798 current_splash.confirm(app);
1799 }
1800 self.update_highlight(app, HighlightType::Pressed, false, true);
1801 if let Some(on_secondary_tap) = self.widget(app).response.on_secondary_tap.clone() {
1802 on_secondary_tap.call(app);
1803 }
1804 }
1805
1806 fn handle_secondary_tap_cancel(self: Handle<Self>, app: &mut App) {
1807 if let Some(current_splash) = app.get_mut(self).current_splash.take() {
1808 current_splash.cancel(app);
1809 }
1810 if let Some(on_secondary_tap_cancel) =
1811 self.widget(app).response.on_secondary_tap_cancel.clone()
1812 {
1813 on_secondary_tap_cancel.call(app);
1814 }
1815 self.update_highlight(app, HighlightType::Pressed, false, true);
1816 }
1817
1818 fn is_widget_enabled(widget: &InkResponseStateWidget) -> bool {
1819 Self::primary_button_enabled(widget)
1820 || Self::secondary_button_enabled(widget)
1821 || Self::tertiary_button_enabled(widget)
1822 }
1823
1824 fn primary_button_enabled(widget: &InkResponseStateWidget) -> bool {
1825 let response = &widget.response;
1826 response.on_tap.is_some()
1827 || response.on_double_tap.is_some()
1828 || response.on_long_press.is_some()
1829 || response.on_long_press_up.is_some()
1830 || response.on_tap_up.is_some()
1831 || response.on_tap_down.is_some()
1832 }
1833
1834 fn secondary_button_enabled(widget: &InkResponseStateWidget) -> bool {
1835 let response = &widget.response;
1836 response.on_secondary_tap.is_some()
1837 || response.on_secondary_tap_up.is_some()
1838 || response.on_secondary_tap_down.is_some()
1839 }
1840
1841 fn tertiary_button_enabled(widget: &InkResponseStateWidget) -> bool {
1842 let response = &widget.response;
1843 response.on_tertiary_tap_up.is_some() || response.on_tertiary_tap_down.is_some()
1844 }
1845
1846 fn enabled(self: Handle<Self>, app: &App) -> bool {
1847 Self::is_widget_enabled(self.widget(app))
1848 }
1849
1850 fn primary_enabled(self: Handle<Self>, app: &App) -> bool {
1851 Self::primary_button_enabled(self.widget(app))
1852 }
1853
1854 fn secondary_enabled(self: Handle<Self>, app: &App) -> bool {
1855 Self::secondary_button_enabled(self.widget(app))
1856 }
1857
1858 fn tertiary_enabled(self: Handle<Self>, app: &App) -> bool {
1859 Self::tertiary_button_enabled(self.widget(app))
1860 }
1861
1862 fn handle_mouse_enter(self: Handle<Self>, app: &mut App, _event: PointerEnterEvent) {
1863 app.get_mut(self).hovering = true;
1864 if self.enabled(app) {
1865 self.handle_hover_change(app);
1866 }
1867 }
1868
1869 fn handle_mouse_exit(self: Handle<Self>, app: &mut App, _event: PointerExitEvent) {
1870 app.get_mut(self).hovering = false;
1871 self.handle_hover_change(app);
1874 }
1875
1876 fn handle_hover_change(self: Handle<Self>, app: &mut App) {
1877 let hovering = app.get(self).hovering;
1878 self.update_highlight(app, HighlightType::Hover, hovering, true);
1879 }
1880
1881 fn can_request_focus(self: Handle<Self>, app: &mut App) -> bool {
1882 let context = self.context(app);
1883 match MediaQuery::maybe_navigation_mode_of(app, context) {
1884 Some(NavigationMode::Traditional) | None => {
1885 self.enabled(app) && self.widget(app).response.can_request_focus
1886 }
1887 Some(NavigationMode::Directional) => true,
1888 }
1889 }
1890}
1891
1892impl AutomaticKeepAliveClientMixin for InkResponseState {
1893 fn automatic_keep_alive_client_data(
1894 self: Handle<Self>,
1895 app: &App,
1896 ) -> &AutomaticKeepAliveClientMixinData {
1897 &app.get(self).automatic_keep_alive_client
1898 }
1899
1900 fn automatic_keep_alive_client_data_mut(
1901 self: Handle<Self>,
1902 app: &mut App,
1903 ) -> &mut AutomaticKeepAliveClientMixinData {
1904 &mut app.get_mut(self).automatic_keep_alive_client
1905 }
1906
1907 fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
1908 self.highlights_exist(app)
1909 || app
1910 .get(self)
1911 .splashes
1912 .as_ref()
1913 .is_some_and(|splashes| !splashes.is_empty())
1914 }
1915}
1916
1917impl State for InkResponseState {
1918 type Widget = InkResponseStateWidget;
1919 waft_widgets::state_accessors!();
1920
1921 fn init_state(self: Handle<Self>, app: &mut App) {
1922 AutomaticKeepAliveClientMixin::init_state(self, app);
1923 let activate = CallbackAction::<ActivateIntent>::new(
1924 app,
1925 Rc::new(move |app: &mut App, _intent: &ActivateIntent| {
1926 self.activate_on_intent(app);
1927 None
1928 }),
1929 );
1930 let button_activate = CallbackAction::<ButtonActivateIntent>::new(
1931 app,
1932 Rc::new(move |app: &mut App, _intent: &ButtonActivateIntent| {
1933 self.activate_on_intent(app);
1934 None
1935 }),
1936 );
1937 let action_map = &mut app.get_mut(self).action_map;
1938 action_map.insert(TypeId::of::<ActivateIntent>(), activate.into_erased());
1939 action_map.insert(
1940 TypeId::of::<ButtonActivateIntent>(),
1941 button_activate.into_erased(),
1942 );
1943 self.init_states_controller(app);
1944 let listener: HighlightModeListener =
1945 Rc::new(move |app, mode| self.handle_focus_highlight_mode_change(app, mode));
1946 app.get_mut(self).focus_highlight_mode_listener = Some(Rc::clone(&listener));
1947 FocusManager::instance(app).add_highlight_mode_listener(app, listener);
1948 }
1949
1950 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &InkResponseStateWidget) {
1951 let widget = &self.widget(app).response;
1952 let old = &old_widget.response;
1953 if widget.states_controller != old.states_controller {
1954 if let Some(old_states_controller) = old.states_controller.clone() {
1955 old_states_controller.remove_listener(
1956 app,
1957 &Listener::handle_method(self, Self::handle_states_controller_change),
1958 );
1959 }
1960 if self.widget(app).response.states_controller.is_some()
1961 && let Some(internal) = app.get_mut(self).internal_states_controller.take()
1962 {
1963 internal.dispose(app);
1964 }
1965 self.init_states_controller(app);
1966 }
1967 let widget = &self.widget(app).response;
1968 if widget.radius != old.radius
1969 || widget.highlight_shape != old.highlight_shape
1970 || widget.border_radius != old.border_radius
1971 {
1972 if let Some(hover_highlight) = app
1973 .get(self)
1974 .highlights
1975 .get(&HighlightType::Hover)
1976 .and_then(|highlight| highlight.handle())
1977 {
1978 InkFeatureLeaf::dispose(hover_highlight, app);
1979 let hovering = app.get(self).hovering;
1980 self.update_highlight(app, HighlightType::Hover, hovering, false);
1981 }
1982 if let Some(focus_highlight) = app
1983 .get(self)
1984 .highlights
1985 .get(&HighlightType::Focus)
1986 .and_then(|highlight| highlight.handle())
1987 {
1988 InkFeatureLeaf::dispose(focus_highlight, app);
1989 }
1991 }
1992 let custom_border_changed = self.widget(app).response.custom_border != old.custom_border;
1993 if custom_border_changed {
1994 self.update_highlights_and_splashes(app);
1995 }
1996 let enabled = self.enabled(app);
1997 if enabled != Self::is_widget_enabled(old_widget) {
1998 let states_controller = self.states_controller(app);
1999 states_controller.update(app, WidgetState::Disabled, !enabled);
2000 if !enabled {
2001 states_controller.update(app, WidgetState::Pressed, false);
2002 if let Some(hover_highlight) = app
2008 .get(self)
2009 .highlights
2010 .get(&HighlightType::Hover)
2011 .and_then(|highlight| highlight.handle())
2012 {
2013 InkFeatureLeaf::dispose(hover_highlight, app);
2014 }
2015 }
2016 let hovering = app.get(self).hovering;
2019 self.update_highlight(app, HighlightType::Hover, hovering, false);
2020 }
2021 self.update_focus_highlights(app);
2022 }
2023
2024 fn dispose(self: Handle<Self>, app: &mut App) {
2025 if let Some(listener) = app.get_mut(self).focus_highlight_mode_listener.take() {
2026 FocusManager::instance(app).remove_highlight_mode_listener(app, &listener);
2027 }
2028 self.states_controller(app).remove_listener(
2029 app,
2030 &Listener::handle_method(self, Self::handle_states_controller_change),
2031 );
2032 if let Some(internal) = app.get_mut(self).internal_states_controller.take() {
2033 internal.dispose(app);
2034 }
2035 if let Some(timer) = app.get_mut(self).activation_timer.take() {
2036 timer.cancel(app);
2037 }
2038 }
2039
2040 fn deactivate(self: Handle<Self>, app: &mut App) {
2041 if let Some(splashes) = app.get_mut(self).splashes.take() {
2042 for splash in splashes {
2043 splash.dispose(app);
2044 }
2045 app.get_mut(self).current_splash = None;
2046 }
2047 debug_assert!(app.get(self).current_splash.is_none());
2048 let highlights: Vec<HighlightType> = app.get(self).highlights.keys().copied().collect();
2049 for highlight in highlights {
2050 if let Some(ink) = app
2051 .get(self)
2052 .highlights
2053 .get(&highlight)
2054 .and_then(|highlight| highlight.handle())
2055 {
2056 InkFeatureLeaf::dispose(ink, app);
2057 }
2058 app.get_mut(self).highlights.insert(highlight, None);
2059 }
2060 if let Some(parent_state) = self.widget(app).parent_state {
2061 parent_state.mark_child_ink_response_pressed(app, self, false);
2062 }
2063 AutomaticKeepAliveClientMixin::deactivate(self, app);
2064 }
2065
2066 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2067 let response = self.widget(app).response.clone();
2068 debug_assert!((response.debug_check_context)(app, context));
2069 AutomaticKeepAliveClientMixin::build(self, app); let theme = Theme::of(app, context);
2072 let highlightable_states = [
2073 WidgetState::Focused,
2074 WidgetState::Hovered,
2075 WidgetState::Pressed,
2076 ];
2077 let non_highlightable_states: WidgetStates = self
2078 .states(app)
2079 .into_iter()
2080 .filter(|state| !highlightable_states.contains(state))
2081 .collect();
2082 let with = |state: WidgetState| {
2085 let mut states = non_highlightable_states.clone();
2086 states.insert(state);
2087 states
2088 };
2089 let pressed = with(WidgetState::Pressed);
2090 let focused = with(WidgetState::Focused);
2091 let hovered = with(WidgetState::Hovered);
2092
2093 let get_highlight_color_for_type = |r#type: HighlightType| -> Color {
2094 let overlay = |states: &WidgetStates| {
2095 response
2096 .overlay_color
2097 .as_ref()
2098 .and_then(|overlay_color| overlay_color.resolve(states))
2099 };
2100 match r#type {
2101 HighlightType::Pressed => overlay(&pressed)
2105 .or(response.highlight_color)
2106 .unwrap_or(theme.highlight_color),
2107 HighlightType::Focus => overlay(&focused)
2108 .or(response.focus_color)
2109 .unwrap_or(theme.focus_color),
2110 HighlightType::Hover => overlay(&hovered)
2111 .or(response.hover_color)
2112 .unwrap_or(theme.hover_color),
2113 }
2114 };
2115
2116 let highlights: Vec<(HighlightType, Option<Handle<InkHighlight>>)> = app
2117 .get(self)
2118 .highlights
2119 .iter()
2120 .map(|(r#type, highlight)| (*r#type, highlight.handle()))
2121 .collect();
2122 for (r#type, highlight) in highlights {
2123 if let Some(highlight) = highlight {
2124 InteractiveInkFeature::set_color(
2125 highlight,
2126 app,
2127 get_highlight_color_for_type(r#type),
2128 );
2129 }
2130 }
2131
2132 if let Some(current_splash) = app.get(self).current_splash.handle() {
2133 let states = self.states(app);
2134 let color = response
2135 .overlay_color
2136 .as_ref()
2137 .and_then(|overlay_color| overlay_color.resolve(&states))
2138 .or(response.splash_color)
2139 .unwrap_or(theme.splash_color);
2140 current_splash.set_color(app, color);
2141 }
2142
2143 let states = self.states(app);
2144 let mouse_cursor: MouseCursorRef = response
2145 .mouse_cursor
2146 .clone()
2147 .unwrap_or_else(|| Rc::new(WidgetStateMouseCursor::adaptive_clickable()));
2148 let effective_mouse_cursor =
2149 <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&mouse_cursor, &states);
2150
2151 let primary_enabled = self.primary_enabled(app);
2152 let secondary_enabled = self.secondary_enabled(app);
2153 let tertiary_enabled = self.tertiary_enabled(app);
2154 let mut detector = GestureDetector::new().behavior(HitTestBehavior::Opaque);
2155 if primary_enabled {
2156 detector = detector
2157 .on_tap_down(Rc::new(move |app, details| {
2158 self.handle_tap_down(app, details)
2159 }))
2160 .on_tap_up(Rc::new(move |app, details| {
2161 self.handle_tap_up(app, details)
2162 }))
2163 .on_tap(Listener::new(move |app| self.handle_tap(app)))
2164 .on_tap_cancel(Listener::new(move |app| self.handle_tap_cancel(app)));
2165 }
2166 if response.on_double_tap.is_some() {
2167 detector =
2168 detector.on_double_tap(Listener::new(move |app| self.handle_double_tap(app)));
2169 }
2170 if response.on_long_press.is_some() {
2171 detector =
2172 detector.on_long_press(Listener::new(move |app| self.handle_long_press(app)));
2173 }
2174 if response.on_long_press_up.is_some() {
2175 detector =
2176 detector.on_long_press_up(Listener::new(move |app| self.handle_long_press_up(app)));
2177 }
2178 if secondary_enabled {
2179 detector = detector
2180 .on_secondary_tap_down(Rc::new(move |app, details| {
2181 self.handle_secondary_tap_down(app, details)
2182 }))
2183 .on_secondary_tap_up(Rc::new(move |app, details| {
2184 self.handle_secondary_tap_up(app, details)
2185 }))
2186 .on_secondary_tap(Listener::new(move |app| self.handle_secondary_tap(app)))
2187 .on_secondary_tap_cancel(Listener::new(move |app| {
2188 self.handle_secondary_tap_cancel(app)
2189 }));
2190 }
2191 if tertiary_enabled {
2192 detector = detector
2193 .on_tertiary_tap_down(Rc::new(move |app, details| {
2194 self.handle_tertiary_tap_down(app, details)
2195 }))
2196 .on_tertiary_tap_up(Rc::new(move |app, details| {
2197 self.handle_tertiary_tap_up(app, details)
2198 }))
2199 .on_tertiary_tap_cancel(Listener::new(move |app| {
2200 self.handle_tertiary_tap_cancel(app)
2201 }));
2202 }
2203 if let Some(child) = response.child.clone() {
2204 detector = detector.child(child);
2205 }
2206
2207 let can_request_focus = self.can_request_focus(app);
2208 let mut semantics = Semantics::new();
2209 if !(response.exclude_from_semantics || response.on_tap.is_none()) {
2210 semantics = semantics.on_tap(Rc::new(move |app: &mut App| self.simulate_tap(app)));
2211 }
2212 if !(response.exclude_from_semantics || response.on_long_press.is_none()) {
2213 semantics = semantics
2214 .on_long_press(Rc::new(move |app: &mut App| self.simulate_long_press(app)));
2215 }
2216 let selection_style = DefaultSelectionStyle::merge(semantics.child(detector))
2217 .mouse_cursor(effective_mouse_cursor.clone());
2218 let region = MouseRegion::new()
2219 .cursor(effective_mouse_cursor)
2220 .on_enter(Rc::new(move |app, event| {
2221 self.handle_mouse_enter(app, event)
2222 }))
2223 .on_exit(Rc::new(move |app, event| {
2224 self.handle_mouse_exit(app, event)
2225 }))
2226 .child(selection_style);
2227 let mut focus = Focus::new(region)
2228 .can_request_focus(can_request_focus)
2229 .on_focus_change(move |app, has_focus| self.handle_focus_update(app, has_focus))
2230 .autofocus(response.autofocus);
2231 if let Some(focus_node) = response.focus_node {
2232 focus = focus.focus_node(focus_node);
2233 }
2234 ParentInkResponseProvider {
2235 state: self,
2236 child: Actions::new(app.get(self).action_map.clone(), focus).into_widget(),
2237 }
2238 .into_widget()
2239 }
2240}
2241
2242#[derive(Clone, Debug)]
2307pub struct InkWell {
2308 pub ink_response: InkResponse,
2310}
2311
2312impl Default for InkWell {
2313 fn default() -> InkWell {
2314 InkWell {
2315 ink_response: InkResponse {
2316 contained_ink_well: true,
2317 highlight_shape: BoxShape::Rectangle,
2318 ..InkResponse::default()
2319 },
2320 }
2321 }
2322}
2323
2324impl InkWell {
2325 pub fn new() -> InkWell {
2329 InkWell::default()
2330 }
2331
2332 fn ink_response_mut(&mut self) -> &mut InkResponse {
2333 &mut self.ink_response
2334 }
2335
2336 ink_response_shared_setters!(InkWell);
2337}
2338
2339impl StatelessWidget for InkWell {
2340 fn key(&self) -> Option<&KeyRef> {
2341 self.ink_response.key.as_ref()
2342 }
2343
2344 fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2345 self.ink_response.build_state_widget(app, context)
2346 }
2347}
2348
2349#[cfg(test)]
2350mod tests {
2351 use std::cell::{Cell, RefCell};
2352
2353 use waft_embedder::{Rect, TargetPlatform, valo};
2354 use waft_gestures::{K_SECONDARY_BUTTON, K_TERTIARY_BUTTON};
2355 use waft_widgets::{
2356 Align, Builder, Center, FocusHighlightStrategy, FocusNode, GlobalKey, MediaQueryData,
2357 Overlay, OverlayEntry, OverlayPortal, OverlayPortalController, Padding, Positioned,
2358 RepaintBoundary, Row, SizedBox, WidgetStatesController,
2359 };
2360
2361 use waft_widgets::testing::{TestPointer, WidgetTester, find, test_widgets};
2362
2363 use super::*;
2364 use crate::colors::Colors;
2365 use crate::material::RenderInkFeatures;
2366 use crate::no_splash::NoSplash;
2367 use crate::test_support::{PaintInspection, path_like};
2368 use crate::theme_data::ThemeData;
2369 use waft_rendering::testing::{CanvasMethod, RecordedCall, count_calls};
2370
2371 type Log = Rc<RefCell<Vec<String>>>;
2372
2373 fn logger(log: &Log, entry: &'static str) -> Listener {
2374 let log = Rc::clone(log);
2375 Listener::new(move |_app| log.borrow_mut().push(entry.to_string()))
2376 }
2377
2378 fn logged<T: 'static>(log: &Log, entry: &'static str) -> ValueChanged<T> {
2379 let log = Rc::clone(log);
2380 Rc::new(move |_app, _details| log.borrow_mut().push(entry.to_string()))
2381 }
2382
2383 fn take(log: &Log) -> Vec<String> {
2384 std::mem::take(&mut log.borrow_mut())
2385 }
2386
2387 fn ltr<K>(child: impl IntoWidget<K>) -> WidgetRef {
2388 Directionality::new(TextDirection::Ltr, child).into_widget()
2389 }
2390
2391 fn material_ltr(child: WidgetRef) -> WidgetRef {
2393 Material::new()
2394 .child(Directionality::new(TextDirection::Ltr, child))
2395 .into_widget()
2396 }
2397
2398 fn centered_square(child: impl IntoWidget<waft_widgets::StatelessKind>) -> WidgetRef {
2400 Center::new()
2401 .child(SizedBox::square(Some(100.0)).child(child))
2402 .into_widget()
2403 }
2404
2405 fn top_left_square(child: impl IntoWidget<waft_widgets::StatelessKind>) -> WidgetRef {
2407 Align::new()
2408 .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
2409 .child(SizedBox::square(Some(100.0)).child(child))
2410 .into_widget()
2411 }
2412
2413 fn paints_rect(tester: &WidgetTester, color: u32, rect: Rect) -> bool {
2415 waft_rendering::testing::paints(
2416 tester.ink_list().ops(),
2417 &[waft_rendering::testing::PaintCall::rect_at(
2418 rect,
2419 Some(Color::new(color)),
2420 )],
2421 )
2422 .is_ok()
2423 }
2424
2425 fn paths(drawn: &[RecordedCall]) -> Vec<(u32, Rect)> {
2426 drawn
2427 .iter()
2428 .filter_map(|call| path_like(call).map(|(color, bounds)| (color.value(), bounds)))
2429 .collect()
2430 }
2431
2432 fn highlights(tester: &WidgetTester) -> Vec<(u32, Rect)> {
2436 let render = tester.first::<RenderInkFeatures>();
2437 let app = tester.cell.borrow();
2438 render
2439 .debug_ink_features(&app)
2440 .unwrap_or_default()
2441 .into_iter()
2442 .filter_map(|feature| feature.downcast::<InkHighlight>(&app))
2443 .map(|highlight| {
2444 let reference_box = crate::material::InkFeature::reference_box(highlight, &app);
2445 let origin = reference_box.local_to_global(&app, Offset::ZERO, None);
2446 (
2447 highlight.debug_paint_color(&app).value(),
2448 origin & reference_box.size(&app),
2449 )
2450 })
2451 .collect()
2452 }
2453
2454 const CENTER_RECT: Rect = Rect::from_ltrb(350.0, 250.0, 450.0, 350.0);
2455 const TOP_LEFT_RECT: Rect = Rect::from_ltrb(0.0, 0.0, 100.0, 100.0);
2456
2457 fn center_of_view() -> Offset {
2458 WidgetTester::SIZE.center(Offset::ZERO)
2459 }
2460
2461 fn set_highlight_strategy(tester: &WidgetTester, strategy: FocusHighlightStrategy) {
2462 let mut app = tester.cell.borrow_mut();
2463 FocusManager::instance(&mut app).set_highlight_strategy(&mut app, strategy);
2464 }
2465
2466 fn hover(tester: &mut WidgetTester, at: Offset) -> TestPointer {
2467 let mut mouse = TestPointer::mouse(1, 0);
2468 tester.add_pointer(&mut mouse, Offset::ZERO);
2469 tester.move_to(&mut mouse, at, false);
2470 tester.pump_and_settle();
2471 mouse
2472 }
2473
2474 fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
2475 FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
2476 }
2477
2478 #[test]
2479 fn ink_well_gestures_control_test() {
2480 test_widgets(|tester| {
2481 let log: Log = Rc::default();
2482 tester.pump_widget(ltr(Material::new().child(
2483 Center::new().child(
2484 InkWell::new()
2485 .on_tap(logger(&log, "tap"))
2486 .on_double_tap(logger(&log, "double-tap"))
2487 .on_long_press(logger(&log, "long-press"))
2488 .on_long_press_up(logger(&log, "long-press-up"))
2489 .on_tap_down(logged(&log, "tap-down"))
2490 .on_tap_up(logged(&log, "tap-up"))
2491 .on_tap_cancel(logger(&log, "tap-cancel")),
2492 ),
2493 )));
2494
2495 tester.tap_at(center_of_view(), 1);
2496 tester.pump_by(Duration::from_secs(1));
2497 assert_eq!(take(&log), ["tap-down", "tap-up", "tap"]);
2498
2499 tester.tap_at(center_of_view(), 2);
2500 tester.pump_by(Duration::from_millis(100));
2501 tester.tap_at(center_of_view(), 3);
2502 assert_eq!(take(&log), ["double-tap"]);
2503
2504 tester.long_press_at(center_of_view(), 4);
2505 assert_eq!(
2506 take(&log),
2507 ["tap-down", "tap-cancel", "long-press", "long-press-up"]
2508 );
2509
2510 let mut gesture = TestPointer::touch(5);
2511 tester.down(&mut gesture, center_of_view());
2512 tester.pump_by(Duration::from_millis(100));
2513 assert_eq!(*log.borrow(), ["tap-down"]);
2514 tester.up(&gesture);
2515 tester.pump_by(Duration::from_secs(1));
2516 assert_eq!(take(&log), ["tap-down", "tap-up", "tap"]);
2517
2518 let mut gesture = TestPointer::touch(6);
2519 tester.down(&mut gesture, center_of_view());
2520 tester.pump_by(Duration::from_millis(100));
2521 tester.move_to(
2522 &mut gesture,
2523 center_of_view() + Offset::new(0.0, 200.0),
2524 true,
2525 );
2526 tester.cancel(&gesture);
2527 assert_eq!(take(&log), ["tap-down", "tap-cancel"]);
2528 });
2529 }
2530
2531 #[test]
2532 fn ink_well_highlight_should_not_survive_after_on_tap_down_on_double_tap_sequence() {
2533 test_widgets(|tester| {
2534 let log: Log = Rc::default();
2535 tester.pump_widget(ltr(Material::new().child(
2536 Center::new().child(
2537 InkWell::new()
2538 .on_tap(logger(&log, "tap"))
2539 .on_double_tap(logger(&log, "double-tap"))
2540 .on_tap_down(logged(&log, "tap-down"))
2541 .on_tap_cancel(logger(&log, "tap-cancel")),
2542 ),
2543 )));
2544 let location = tester.get_center(find::by_type::<InkWell>().evaluate(tester)[0]);
2545
2546 let mut gesture = TestPointer::touch(1);
2547 tester.down(&mut gesture, location);
2548 tester.pump_by(Duration::from_millis(100));
2549 assert_eq!(*log.borrow(), ["tap-down"]);
2550 tester.up(&gesture);
2551 tester.pump_by(Duration::from_millis(100));
2552
2553 tester.tap_at(location, 2);
2554 tester.pump_by(Duration::from_millis(100));
2555 assert_eq!(take(&log), ["tap-down", "double-tap"]);
2556
2557 tester.pump_and_settle();
2558 assert_eq!(
2559 count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect),
2560 0
2561 );
2562 });
2563 }
2564
2565 #[test]
2566 fn ink_well_splash_should_not_survive_after_on_tap_down_on_tap_down_on_tap_cancel_on_double_tap_sequence()
2567 {
2568 test_widgets(|tester| {
2569 let log: Log = Rc::default();
2570 tester.pump_widget(ltr(Material::new().child(
2571 Center::new().child(
2572 InkWell::new()
2573 .on_tap(logger(&log, "tap"))
2574 .on_double_tap(logger(&log, "double-tap"))
2575 .on_tap_down(logged(&log, "tap-down"))
2576 .on_tap_cancel(logger(&log, "tap-cancel")),
2577 ),
2578 )));
2579 let location = tester.get_center(find::by_type::<InkWell>().evaluate(tester)[0]);
2580
2581 let mut first = TestPointer::touch(1);
2582 tester.down(&mut first, location);
2583 tester.pump_by(Duration::from_millis(100));
2584 assert_eq!(*log.borrow(), ["tap-down"]);
2585 tester.up(&first);
2586 tester.pump_by(Duration::from_millis(100));
2587
2588 let mut second = TestPointer::touch(2);
2589 tester.down(&mut second, location);
2590 tester.pump_by(Duration::from_millis(100));
2591 assert_eq!(*log.borrow(), ["tap-down", "tap-down"]);
2592 tester.up(&second);
2593 tester.pump_by(Duration::from_millis(100));
2594 assert_eq!(
2595 take(&log),
2596 ["tap-down", "tap-down", "tap-cancel", "double-tap"]
2597 );
2598
2599 tester.pump_and_settle();
2600 assert_eq!(
2601 count_calls(tester.ink_list().ops(), CanvasMethod::DrawCircle),
2602 0
2603 );
2604 });
2605 }
2606
2607 #[test]
2608 fn ink_well_only_on_tap_down_enables_gestures() {
2609 test_widgets(|tester| {
2611 let down_tapped = Rc::new(Cell::new(false));
2612 tester.pump_widget(ltr(Material::new().child(Center::new().child(
2613 InkWell::new().on_tap_down({
2614 let down_tapped = Rc::clone(&down_tapped);
2615 Rc::new(move |_app, _details| down_tapped.set(true))
2616 }),
2617 ))));
2618 tester.tap_at(center_of_view(), 1);
2619 assert!(down_tapped.get());
2620 });
2621 }
2622
2623 #[test]
2626 fn ink_well_invokes_activation_actions_when_expected() {
2627 test_widgets(|tester| {
2628 let log: Log = Rc::default();
2629 let inner: Rc<Cell<Option<BuildContext>>> = Rc::default();
2630 tester.pump_widget(ltr(Material::new().child(
2631 Center::new().child(
2632 InkWell::new()
2633 .autofocus(true)
2634 .on_tap(logger(&log, "tap"))
2635 .child(Builder::new({
2636 let inner = Rc::clone(&inner);
2637 move |_app, context| {
2638 inner.set(Some(context));
2639 SizedBox::shrink().into_widget()
2640 }
2641 })),
2642 ),
2643 )));
2644 let context = inner.get().expect("built");
2645 Actions::invoke(&mut tester.cell.borrow_mut(), context, &ActivateIntent);
2646 tester.pump();
2647 assert_eq!(take(&log), ["tap"]);
2648 Actions::invoke(
2649 &mut tester.cell.borrow_mut(),
2650 context,
2651 &ButtonActivateIntent,
2652 );
2653 tester.pump();
2654 assert_eq!(take(&log), ["tap"]);
2655 });
2656 }
2657
2658 #[test]
2659 fn ink_well_on_long_press_up_callback_is_triggered() {
2660 test_widgets(|tester| {
2661 let was_called = Rc::new(Cell::new(false));
2662 tester.pump_widget(material_ltr(
2663 InkWell::new()
2664 .on_long_press(Listener::new(|_app| {}))
2665 .on_long_press_up({
2666 let was_called = Rc::clone(&was_called);
2667 Listener::new(move |_app| was_called.set(true))
2668 })
2669 .child(SizedBox::new().width(100.0).height(100.0))
2670 .into_widget(),
2671 ));
2672 let mut gesture = TestPointer::touch(1);
2673 tester.down(&mut gesture, Offset::new(50.0, 50.0));
2674 tester.pump_by(Duration::from_secs(1));
2675 tester.up(&gesture);
2676 tester.pump_and_settle();
2677 assert!(was_called.get());
2678 });
2679 }
2680
2681 #[test]
2682 fn long_press_and_tap_on_disabled_should_not_throw() {
2683 test_widgets(|tester| {
2684 tester.pump_widget(material_ltr(
2685 Center::new().child(InkWell::new()).into_widget(),
2686 ));
2687 tester.tap_at(center_of_view(), 1);
2688 tester.pump_by(Duration::from_secs(1));
2689 tester.long_press_at(center_of_view(), 1);
2690 tester.pump_by(Duration::from_secs(1));
2691 });
2692 }
2693
2694 fn colored_ink_well() -> InkWell {
2695 InkWell::new()
2696 .hover_color(Color::new(0xff00ff00))
2697 .splash_color(Color::new(0xffff0000))
2698 .focus_color(Color::new(0xff0000ff))
2699 .highlight_color(Color::new(0xf00fffff))
2700 .on_tap(Listener::new(|_app| {}))
2701 .on_long_press(Listener::new(|_app| {}))
2702 .on_long_press_up(Listener::new(|_app| {}))
2703 .on_hover(Rc::new(|_app, _hover| {}))
2704 }
2705
2706 fn overlay_ink_well() -> InkWell {
2707 InkWell::new()
2708 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2709 |states| {
2710 if states.contains(&WidgetState::Hovered) {
2711 return Some(Color::new(0xff00ff00));
2712 }
2713 if states.contains(&WidgetState::Focused) {
2714 return Some(Color::new(0xff0000ff));
2715 }
2716 if states.contains(&WidgetState::Pressed) {
2717 return Some(Color::new(0xf00fffff));
2718 }
2719 Some(Color::new(0xffbadbad)) },
2721 ))
2722 .on_tap(Listener::new(|_app| {}))
2723 .on_long_press(Listener::new(|_app| {}))
2724 .on_long_press_up(Listener::new(|_app| {}))
2725 .on_hover(Rc::new(|_app, _hover| {}))
2726 }
2727
2728 #[test]
2729 fn ink_well_changes_color_on_hover() {
2730 test_widgets(|tester| {
2731 tester.pump_widget(material_ltr(centered_square(colored_ink_well())));
2732 hover(tester, center_of_view());
2733 assert!(paints_rect(tester, 0xff00ff00, CENTER_RECT));
2734 });
2735 }
2736
2737 #[test]
2738 fn ink_well_changes_color_on_hover_with_overlay_color() {
2739 test_widgets(|tester| {
2742 tester.pump_widget(material_ltr(centered_square(overlay_ink_well())));
2743 hover(tester, center_of_view());
2744 assert!(paints_rect(tester, 0xff00ff00, CENTER_RECT));
2745 });
2746 }
2747
2748 #[test]
2749 fn ink_response_changes_color_on_focus() {
2750 test_widgets(|tester| {
2751 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
2752 let focus_node = focus_node(tester);
2753 tester.pump_widget(material_ltr(centered_square(
2754 colored_ink_well().focus_node(focus_node.clone()),
2755 )));
2756 tester.pump_and_settle();
2757 assert!(count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect) == 0);
2758 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2759 tester.pump_and_settle();
2760 assert!(paints_rect(tester, 0xff0000ff, CENTER_RECT));
2761 });
2762 }
2763
2764 #[test]
2765 fn ink_response_changes_color_on_focus_with_overlay_color() {
2766 test_widgets(|tester| {
2767 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
2768 let focus_node = focus_node(tester);
2769 tester.pump_widget(material_ltr(centered_square(
2770 overlay_ink_well().focus_node(focus_node.clone()),
2771 )));
2772 tester.pump_and_settle();
2773 assert!(count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect) == 0);
2774 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2775 tester.pump_and_settle();
2776 assert!(paints_rect(tester, 0xff0000ff, CENTER_RECT));
2777 });
2778 }
2779
2780 #[test]
2781 fn ink_well_changes_color_on_pressed_with_overlay_color() {
2782 test_widgets(|tester| {
2783 let pressed_color = Color::new(0xffdd00ff);
2784 tester.pump_widget(material_ltr(top_left_square(
2785 InkWell::new()
2786 .splash_factory(NoSplash::splash_factory())
2787 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2788 move |states| {
2789 if states.contains(&WidgetState::Pressed) {
2790 return Some(pressed_color);
2791 }
2792 Some(Color::new(0xffbadbad)) },
2794 ))
2795 .on_tap(Listener::new(|_app| {})),
2796 )));
2797 tester.pump_and_settle();
2798 let mut gesture = TestPointer::touch(1);
2799 tester.down(&mut gesture, TOP_LEFT_RECT.center());
2800 assert!(
2801 highlights(tester).contains(&(pressed_color.with_alpha(0).value(), TOP_LEFT_RECT))
2802 );
2803 tester.pump_and_settle(); assert!(paints_rect(tester, pressed_color.value(), TOP_LEFT_RECT));
2805 tester.up(&gesture);
2806 });
2807 }
2808
2809 const SELECTED_HOVERED_COLOR: u32 = 0xff00ff00;
2810 const SELECTED_FOCUSED_COLOR: u32 = 0xff0000ff;
2811 const SELECTED_PRESSED_COLOR: u32 = 0xff00ffff;
2812
2813 fn selected_boilerplate(tester: &WidgetTester, focus_node: Option<FocusNodeRef>) -> WidgetRef {
2815 let states = WidgetStates::from([WidgetState::Selected]);
2816 let states_controller =
2817 WidgetStatesController::new(&mut tester.cell.borrow_mut(), Some(states));
2818 let mut ink_well = InkWell::new()
2819 .splash_factory(NoSplash::splash_factory())
2820 .states_controller(states_controller)
2821 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2822 |states| {
2823 if states.contains(&WidgetState::Selected) {
2824 if states.contains(&WidgetState::Pressed) {
2825 return Some(Color::new(SELECTED_PRESSED_COLOR));
2826 }
2827 if states.contains(&WidgetState::Hovered) {
2828 return Some(Color::new(SELECTED_HOVERED_COLOR));
2829 }
2830 if states.contains(&WidgetState::Focused) {
2831 return Some(Color::new(SELECTED_FOCUSED_COLOR));
2832 }
2833 Some(Color::new(0xffbadbad)) } else {
2835 Some(Color::new(0xff000000))
2836 }
2837 },
2838 ))
2839 .on_tap(Listener::new(|_app| {}));
2840 if let Some(focus_node) = focus_node {
2841 ink_well = ink_well.focus_node(focus_node);
2842 }
2843 material_ltr(top_left_square(ink_well))
2844 }
2845
2846 #[test]
2847 fn ink_well_overlay_color_resolution_respects_selected_when_focused() {
2848 test_widgets(|tester| {
2849 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
2850 let focus_node = focus_node(tester);
2851 let widget = selected_boilerplate(tester, Some(focus_node.clone()));
2852 tester.pump_widget(widget);
2853 tester.pump_and_settle();
2854 assert!(count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect) == 0);
2855 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2856 tester.pump_and_settle();
2857 assert!(paints_rect(tester, SELECTED_FOCUSED_COLOR, TOP_LEFT_RECT));
2858 });
2859 }
2860
2861 #[test]
2862 fn ink_well_overlay_color_resolution_respects_selected_when_hovered() {
2863 test_widgets(|tester| {
2864 let widget = selected_boilerplate(tester, None);
2865 tester.pump_widget(widget);
2866 tester.pump_and_settle();
2867 hover(tester, TOP_LEFT_RECT.center());
2868 assert!(paints_rect(tester, SELECTED_HOVERED_COLOR, TOP_LEFT_RECT));
2869 });
2870 }
2871
2872 #[test]
2873 fn ink_well_overlay_color_resolution_respects_selected_when_pressed() {
2874 test_widgets(|tester| {
2875 let widget = selected_boilerplate(tester, None);
2876 tester.pump_widget(widget);
2877 tester.pump_and_settle();
2878 let mut gesture = TestPointer::touch(1);
2879 tester.down(&mut gesture, TOP_LEFT_RECT.center());
2880 assert!(highlights(tester).contains(&(
2881 Color::new(SELECTED_PRESSED_COLOR).with_alpha(0).value(),
2882 TOP_LEFT_RECT
2883 )));
2884 tester.pump_and_settle(); assert!(paints_rect(tester, SELECTED_PRESSED_COLOR, TOP_LEFT_RECT));
2886 tester.up(&gesture);
2887 });
2888 }
2889
2890 fn m2(tester: &WidgetTester, child: WidgetRef) -> WidgetRef {
2892 let data = ThemeData::builder()
2893 .use_material3(false)
2894 .build(&tester.cell.borrow());
2895 Theme::new(data, child).into_widget()
2896 }
2897
2898 fn assert_splash_color(tester: &mut WidgetTester, ink_well: InkWell) {
2899 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTouch);
2900 let widget = m2(tester, material_ltr(centered_square(ink_well)));
2901 tester.pump_widget(widget);
2902 tester.pump_and_settle();
2903 let mut gesture = TestPointer::touch(1);
2904 tester.down(&mut gesture, center_of_view());
2905 tester.pump_by(Duration::from_millis(200)); tester.pump_by(Duration::from_millis(16));
2909 let circles = paths(&tester.ink_calls());
2910 assert!(
2911 circles.iter().any(|(color, bounds)| *color == 0xffff0000
2912 && bounds.center() == Offset::new(50.0, 50.0)),
2913 "{circles:?}"
2914 );
2915 tester.up(&gesture);
2916 }
2917
2918 #[test]
2919 fn ink_response_splash_color_matches_splash_color_parameter() {
2920 test_widgets(|tester| assert_splash_color(tester, colored_ink_well()));
2921 }
2922
2923 #[test]
2924 fn ink_response_splash_color_matches_resolved_overlay_color_for_pressed() {
2925 test_widgets(|tester| {
2926 assert_splash_color(
2927 tester,
2928 InkWell::new()
2929 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
2930 |states| {
2931 if states.contains(&WidgetState::Hovered) {
2932 return Some(Color::new(0xff00ff00));
2933 }
2934 if states.contains(&WidgetState::Focused) {
2935 return Some(Color::new(0xff0000ff));
2936 }
2937 if states.contains(&WidgetState::Pressed) {
2938 return Some(Color::new(0xffff0000));
2939 }
2940 Some(Color::new(0xffbadbad)) },
2942 ))
2943 .on_tap(Listener::new(|_app| {}))
2944 .on_long_press(Listener::new(|_app| {}))
2945 .on_long_press_up(Listener::new(|_app| {}))
2946 .on_hover(Rc::new(|_app, _hover| {})),
2947 )
2948 });
2949 }
2950
2951 #[test]
2952 fn ink_response_uses_radius_for_focus_highlight() {
2953 test_widgets(|tester| {
2954 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
2955 let focus_node = focus_node(tester);
2956 tester.pump_widget(material_ltr(
2957 Center::new()
2958 .child(
2959 SizedBox::square(Some(100.0)).child(
2960 InkResponse::new()
2961 .focus_node(focus_node.clone())
2962 .radius(20.0)
2963 .focus_color(Color::new(0xff0000ff))
2964 .on_tap(Listener::new(|_app| {})),
2965 ),
2966 )
2967 .into_widget(),
2968 ));
2969 tester.pump_and_settle();
2970 assert!(paths(&tester.ink_calls()).is_empty());
2971 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2972 tester.pump_and_settle();
2973 let circles = paths(&tester.ink_calls());
2974 assert_eq!(circles.len(), 1);
2975 let (color, bounds) = circles[0];
2976 assert_eq!(color, 0xff0000ff);
2977 assert_eq!(bounds.width(), 40.0, "radius 20");
2978 });
2979 }
2980
2981 #[test]
2982 fn ink_well_uses_border_radius_for_focus_highlight() {
2983 test_widgets(|tester| {
2984 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
2985 let focus_node = focus_node(tester);
2986 tester.pump_widget(material_ltr(centered_square(
2987 InkWell::new()
2988 .focus_node(focus_node.clone())
2989 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(10.0)))
2990 .focus_color(Color::new(0xff0000ff))
2991 .on_tap(Listener::new(|_app| {})),
2992 )));
2993 tester.pump_and_settle();
2994 assert!(paths(&tester.ink_calls()).is_empty());
2995
2996 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
2997 tester.pump_and_settle();
2998 assert_eq!(paths(&tester.ink_calls()), [(0xff0000ff, CENTER_RECT)]);
2999 });
3000 }
3001
3002 #[test]
3003 fn ink_well_uses_border_radius_for_hover_highlight() {
3004 test_widgets(|tester| {
3005 tester.pump_widget(material_ltr(centered_square(
3006 InkWell::new()
3007 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(10.0)))
3008 .hover_color(Color::new(0xff00ff00))
3009 .on_tap(Listener::new(|_app| {})),
3010 )));
3011 tester.pump_and_settle();
3012 assert!(paths(&tester.ink_calls()).is_empty());
3013
3014 let mut mouse = TestPointer::mouse(1, 0);
3016 tester.add_pointer(&mut mouse, center_of_view());
3017 tester.pump_and_settle();
3018 assert_eq!(paths(&tester.ink_calls()), [(0xff00ff00, CENTER_RECT)]);
3019 });
3020 }
3021
3022 #[test]
3023 fn ink_response_does_not_change_color_on_focus_when_on_touch_device() {
3024 test_widgets(|tester| {
3025 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTouch);
3026 let focus_node = focus_node(tester);
3027 tester.pump_widget(material_ltr(centered_square(
3028 colored_ink_well().focus_node(focus_node.clone()),
3029 )));
3030 tester.pump_and_settle();
3031 assert!(count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect) == 0);
3032 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3033 tester.pump_and_settle();
3034 assert!(count_calls(tester.ink_list().ops(), CanvasMethod::DrawRect) == 0);
3035 });
3036 }
3037
3038 fn active_cursor(tester: &WidgetTester) -> MouseCursorRef {
3039 let mut app = tester.cell.borrow_mut();
3040 let tracker = waft_rendering::RendererBinding::instance(&mut app).mouse_tracker(&app);
3041 tracker
3042 .debug_device_active_cursor(&app, 1)
3043 .expect("the mouse is over the view")
3044 }
3045
3046 #[test]
3047 fn ink_well_mouse_cursor_changes_cursor_on_hover() {
3048 test_widgets(|tester| {
3049 use waft_services::SystemMouseCursors;
3050 let in_region = |child: WidgetRef| {
3051 material_ltr(
3052 MouseRegion::new()
3053 .cursor(SystemMouseCursors::FORBIDDEN.into())
3054 .child(child)
3055 .into_widget(),
3056 )
3057 };
3058 let expect = |tester: &mut WidgetTester, child: WidgetRef, cursor: MouseCursorRef| {
3059 tester.pump_widget(in_region(child));
3060 assert!(*active_cursor(tester) == *cursor);
3061 };
3062 let basic: MouseCursorRef = SystemMouseCursors::BASIC.into();
3063 tester.pump_widget(in_region(SizedBox::shrink().into_widget()));
3066 let mut mouse = TestPointer::mouse(1, 0);
3067 tester.add_pointer(&mut mouse, Offset::new(1.0, 1.0));
3068
3069 expect(
3071 tester,
3072 InkWell::new()
3073 .mouse_cursor(SystemMouseCursors::CELL.into())
3074 .on_tap(Listener::new(|_app| {}))
3075 .into_widget(),
3076 SystemMouseCursors::CELL.into(),
3077 );
3078 expect(
3080 tester,
3081 InkWell::new()
3082 .on_tap(Listener::new(|_app| {}))
3083 .into_widget(),
3084 basic.clone(),
3085 );
3086 expect(tester, InkWell::new().into_widget(), basic.clone());
3088 expect(
3090 tester,
3091 InkResponse::new()
3092 .on_tap(Listener::new(|_app| {}))
3093 .into_widget(),
3094 basic.clone(),
3095 );
3096 expect(tester, InkResponse::new().into_widget(), basic);
3098 });
3099 }
3100
3101 #[derive(Default)]
3103 struct FeedbackTester {
3104 haptics: RefCell<Vec<waft_embedder::HapticFeedbackType>>,
3105 }
3106
3107 impl waft_embedder::Haptics for FeedbackTester {
3108 fn feedback(&self, kind: waft_embedder::HapticFeedbackType) {
3109 self.haptics.borrow_mut().push(kind);
3110 }
3111 }
3112
3113 fn feedback_case(enable_feedback: bool) -> usize {
3116 let feedback = Rc::new(FeedbackTester::default());
3117 let platform = waft_test::TestPlatform::new()
3118 .on(TargetPlatform::Android)
3119 .with_haptics(Rc::clone(&feedback) as Rc<dyn waft_embedder::Haptics>);
3120 let mut tester = WidgetTester::with_platform(platform);
3121 let tester = &mut tester;
3122 tester.pump_widget(material_ltr(
3123 Center::new()
3124 .child(
3125 InkWell::new()
3126 .on_tap(Listener::new(|_app| {}))
3127 .on_long_press(Listener::new(|_app| {}))
3128 .on_long_press_up(Listener::new(|_app| {}))
3129 .enable_feedback(enable_feedback),
3130 )
3131 .into_widget(),
3132 ));
3133 tester.tap_at(center_of_view(), 1);
3134 tester.pump_by(Duration::from_secs(1));
3135 assert!(feedback.haptics.borrow().is_empty());
3136 tester.long_press_at(center_of_view(), 1);
3137 tester.pump_by(Duration::from_secs(1));
3138 feedback.haptics.borrow().len()
3139 }
3140
3141 #[test]
3142 fn feedback_enabled_by_default() {
3143 test_widgets(|_| assert_eq!(feedback_case(true), 1));
3144 }
3145
3146 #[test]
3147 fn feedback_disabled() {
3148 test_widgets(|_| assert_eq!(feedback_case(false), 0));
3149 }
3150
3151 fn focus_case(
3152 tester: &mut WidgetTester,
3153 navigation_mode: Option<waft_widgets::NavigationMode>,
3154 ) -> bool {
3155 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTouch);
3156 let focus_node = focus_node(tester);
3157 let frame = |ink_well: InkWell| {
3158 let child = ltr(ink_well
3159 .focus_node(focus_node.clone())
3160 .child(SizedBox::new()));
3161 let child = match navigation_mode {
3162 Some(mode) => waft_widgets::MediaQuery::new(
3163 MediaQueryData::default().navigation_mode(mode),
3164 child,
3165 )
3166 .into_widget(),
3167 None => child,
3168 };
3169 Material::new().child(child).into_widget()
3170 };
3171 tester.pump_widget(frame(
3172 InkWell::new()
3173 .autofocus(true)
3174 .on_tap(Listener::new(|_app| {}))
3175 .on_long_press(Listener::new(|_app| {}))
3176 .on_long_press_up(Listener::new(|_app| {}))
3177 .on_hover(Rc::new(|_app, _hover| {})),
3178 ));
3179 tester.pump_and_settle();
3180 assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
3181 tester.pump_widget(frame(InkWell::new()));
3182 tester.pump_and_settle();
3183 focus_node.has_primary_focus(&tester.cell.borrow())
3184 }
3185
3186 #[test]
3187 fn ink_response_does_not_focus_when_disabled() {
3188 test_widgets(|tester| assert!(!focus_case(tester, None)));
3189 }
3190
3191 #[test]
3192 fn ink_response_accepts_focus_when_disabled_in_directional_navigation_mode() {
3193 test_widgets(|tester| {
3194 assert!(focus_case(
3195 tester,
3196 Some(waft_widgets::NavigationMode::Directional)
3197 ))
3198 });
3199 }
3200
3201 #[test]
3202 fn when_ink_wells_are_nested_only_the_inner_one_is_triggered_by_tap_splash() {
3203 test_widgets(|tester| {
3204 let inner_key = GlobalKey::new();
3205 let padded_ink_well = |key: Option<&GlobalKey>, child: WidgetRef| {
3206 let mut ink_well = InkWell::new()
3207 .on_tap(Listener::new(|_app| {}))
3208 .child(Padding::new(waft_painting::EdgeInsets::all(50.0)).child(child));
3209 if let Some(key) = key {
3210 ink_well = ink_well.key(key.clone().into());
3211 }
3212 ink_well.into_widget()
3213 };
3214 let tree = padded_ink_well(
3215 None,
3216 padded_ink_well(
3217 None,
3218 padded_ink_well(
3219 Some(&inner_key),
3220 SizedBox::new().width(50.0).height(50.0).into_widget(),
3221 ),
3222 ),
3223 );
3224 let widget = m2(
3225 tester,
3226 material_ltr(Center::new().child(tree).into_widget()),
3227 );
3228 tester.pump_widget(widget);
3229 let inner = tester.get_center(&inner_key);
3230 let circles = |tester: &WidgetTester| paths(&tester.ink_calls()).len();
3231
3232 let mut gesture = TestPointer::touch(1);
3234 tester.down(&mut gesture, inner);
3235 tester.pump_by(Duration::from_millis(200));
3236 tester.pump_by(Duration::from_millis(16)); assert_eq!(circles(tester), 1);
3238
3239 tester.up(&gesture);
3241 tester.pump_and_settle();
3242 assert!(tester.ink_calls().is_empty());
3243
3244 tester.down(&mut gesture, inner);
3246 tester.pump_by(Duration::from_millis(200));
3247 tester.pump_by(Duration::from_millis(16)); assert_eq!(circles(tester), 1);
3249
3250 tester.cancel(&gesture);
3252 tester.pump_and_settle();
3253 assert!(tester.ink_calls().is_empty());
3254
3255 tester.down(&mut gesture, inner);
3257 tester.pump_by(Duration::from_millis(200));
3258 tester.pump_by(Duration::from_millis(16)); assert_eq!(circles(tester), 1);
3260
3261 let mut gesture2 = TestPointer::touch(2);
3263 tester.down(&mut gesture2, inner);
3264 tester.pump_by(Duration::from_millis(200));
3265 tester.pump_by(Duration::from_millis(16)); assert_eq!(circles(tester), 1);
3267 tester.up(&gesture2);
3268 });
3269 }
3270
3271 #[test]
3272 fn disabled_and_hovered_inkwell_responds_to_mouse_exit() {
3273 test_widgets(|tester| {
3274 let on_hover_count = Rc::new(Cell::new(0));
3275 let hover_value = Rc::new(Cell::new(None));
3276 let build_frame = |enabled: bool| {
3277 let mut ink_well = InkWell::new().on_hover({
3278 let on_hover_count = Rc::clone(&on_hover_count);
3279 let hover_value = Rc::clone(&hover_value);
3280 Rc::new(move |_app, value| {
3281 on_hover_count.set(on_hover_count.get() + 1);
3282 hover_value.set(Some(value));
3283 })
3284 });
3285 if enabled {
3286 ink_well = ink_well.on_tap(Listener::new(|_app| {}));
3287 }
3288 material_ltr(centered_square(ink_well))
3289 };
3290
3291 tester.pump_widget(build_frame(true));
3292 let mut mouse = TestPointer::mouse(1, 0);
3293 tester.add_pointer(&mut mouse, Offset::ZERO);
3294
3295 tester.move_to(&mut mouse, center_of_view(), false);
3296 tester.pump_and_settle();
3297 assert_eq!(on_hover_count.get(), 1);
3298 assert_eq!(hover_value.get(), Some(true));
3299
3300 tester.pump_widget(build_frame(false));
3301 tester.pump_and_settle();
3302 tester.move_to(&mut mouse, Offset::ZERO, false);
3303 assert_eq!(on_hover_count.get(), 2);
3306 assert_eq!(hover_value.get(), Some(false));
3307
3308 tester.move_to(&mut mouse, center_of_view(), false);
3309 tester.pump_and_settle();
3310 assert_eq!(on_hover_count.get(), 2);
3313 assert_eq!(hover_value.get(), Some(false));
3314
3315 tester.pump_widget(build_frame(true));
3316 tester.pump_and_settle();
3317 assert_eq!(on_hover_count.get(), 2);
3320 assert_eq!(hover_value.get(), Some(false));
3321
3322 tester.move_to(&mut mouse, center_of_view() - Offset::new(1.0, 1.0), false);
3323 tester.pump_and_settle();
3324 assert_eq!(on_hover_count.get(), 2);
3326 assert_eq!(hover_value.get(), Some(false));
3327 });
3328 }
3329
3330 #[test]
3331 fn hovered_ink_well_draws_a_transparent_highlight_when_disabled() {
3332 test_widgets(|tester| {
3333 let build_frame = |enabled: bool| {
3334 let mut ink_well = InkWell::new()
3335 .on_hover(Rc::new(|_app, _value| {}))
3336 .hover_color(Color::new(0xff00ff00));
3337 if enabled {
3338 ink_well = ink_well.on_tap(Listener::new(|_app| {}));
3339 }
3340 material_ltr(centered_square(ink_well))
3341 };
3342
3343 tester.pump_widget(build_frame(true));
3344 hover(tester, center_of_view());
3346 assert!(paints_rect(tester, 0xff00ff00, CENTER_RECT));
3347
3348 tester.pump_widget(build_frame(false));
3350 tester.pump_and_settle();
3351 assert!(highlights(tester).contains(&(0x0000ff00, CENTER_RECT)));
3352 });
3353 }
3354
3355 #[test]
3356 fn ink_well_disposes_states_controller() {
3357 test_widgets(|tester| {
3358 let tap_count = Rc::new(Cell::new(0));
3359 let build_frame = |states_controller: Option<Ref<MaterialStatesController>>| {
3360 let mut ink_well = InkWell::new()
3361 .on_tap({
3362 let tap_count = Rc::clone(&tap_count);
3363 Listener::new(move |_app| tap_count.set(tap_count.get() + 1))
3364 })
3365 .child(SizedBox::new().width(100.0).height(20.0));
3366 if let Some(states_controller) = states_controller {
3367 ink_well = ink_well.states_controller(states_controller);
3368 }
3369 material_ltr(Center::new().child(ink_well).into_widget())
3370 };
3371
3372 let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
3373 let pressed_count = Rc::new(Cell::new(0));
3374 controller.add_listener(
3375 &mut tester.cell.borrow_mut(),
3376 Listener::new({
3377 let pressed_count = Rc::clone(&pressed_count);
3378 {
3379 let controller = controller.clone();
3380 move |app| {
3381 if app.get(&controller).value().contains(&WidgetState::Pressed) {
3382 pressed_count.set(pressed_count.get() + 1);
3383 }
3384 }
3385 }
3386 }),
3387 );
3388
3389 tester.pump_widget(build_frame(Some(controller.clone())));
3390 tester.tap_at(center_of_view(), 1);
3391 tester.pump_and_settle();
3392 assert_eq!(tap_count.get(), 1);
3393 assert_eq!(pressed_count.get(), 1);
3394
3395 tester.pump_widget(build_frame(None));
3396 tester.tap_at(center_of_view(), 1);
3397 tester.pump_and_settle();
3398 assert_eq!(tap_count.get(), 2);
3399 assert_eq!(pressed_count.get(), 1);
3400
3401 tester.pump_widget(build_frame(Some(controller.clone())));
3402 tester.tap_at(center_of_view(), 1);
3403 tester.pump_and_settle();
3404 assert_eq!(tap_count.get(), 3);
3405 assert_eq!(pressed_count.get(), 2);
3406 });
3407 }
3408
3409 #[test]
3410 fn ink_well_overlay_color_opacity_fades_from_0xff_when_hover_ends() {
3411 test_widgets(|tester| {
3413 tester.pump_widget(material_ltr(centered_square(
3414 InkWell::new()
3415 .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
3416 |states| {
3417 states
3418 .contains(&WidgetState::Hovered)
3419 .then(|| Color::new(0xff00ff00))
3420 },
3421 ))
3422 .on_tap(Listener::new(|_app| {}))
3423 .on_long_press(Listener::new(|_app| {}))
3424 .on_long_press_up(Listener::new(|_app| {}))
3425 .on_hover(Rc::new(|_app, _hover| {})),
3426 )));
3427 let mut mouse = hover(tester, center_of_view());
3428 tester.move_to(&mut mouse, Offset::new(10.0, 10.0), false); tester.pump(); assert!(paints_rect(tester, 0xff00ff00, CENTER_RECT));
3432 tester.pump_by(Duration::from_millis(25));
3434 assert!(
3435 paints_rect(tester, 0x8000ff00, CENTER_RECT),
3436 "{:?}",
3437 tester.ink_calls()
3438 );
3439 });
3440 }
3441
3442 #[test]
3443 fn ink_well_secondary_tap_test() {
3444 test_widgets(|tester| {
3445 let log: Log = Rc::default();
3446 tester.pump_widget(ltr(Material::new().child(
3447 Center::new().child(
3448 InkWell::new()
3449 .on_secondary_tap(logger(&log, "secondary-tap"))
3450 .on_secondary_tap_down(logged(&log, "secondary-tap-down"))
3451 .on_secondary_tap_up(logged(&log, "secondary-tap-up"))
3452 .on_secondary_tap_cancel(logger(&log, "secondary-tap-cancel")),
3453 ),
3454 )));
3455
3456 let mut mouse = TestPointer::mouse(1, K_SECONDARY_BUTTON);
3457 tester.down(&mut mouse, center_of_view());
3458 tester.up(&mouse);
3459 assert_eq!(
3460 take(&log),
3461 ["secondary-tap-down", "secondary-tap-up", "secondary-tap"]
3462 );
3463
3464 let mut mouse = TestPointer::mouse(2, K_SECONDARY_BUTTON);
3465 tester.down(&mut mouse, center_of_view());
3466 tester.move_to(&mut mouse, Offset::new(100.0, 100.0), true);
3467 tester.up(&mouse);
3468 assert_eq!(take(&log), ["secondary-tap-down", "secondary-tap-cancel"]);
3469 });
3470 }
3471
3472 #[test]
3474 fn ink_well_secondary_tap_should_not_draw_a_splash_when_no_secondary_callbacks_are_defined() {
3475 test_widgets(|tester| {
3476 tester.pump_widget(ltr(Material::new().child(
3477 Center::new().child(InkWell::new().on_tap(Listener::new(|_app| {}))),
3478 )));
3479 let mut mouse = TestPointer::mouse(1, K_SECONDARY_BUTTON);
3480 tester.down(&mut mouse, center_of_view());
3481 tester.pump_by(Duration::from_millis(200));
3482
3483 assert!(paths(&tester.ink_calls()).is_empty());
3485 tester.up(&mouse);
3486 });
3487 }
3488
3489 #[test]
3490 fn ink_well_tertiary_tap_test() {
3491 test_widgets(|tester| {
3492 let log: Log = Rc::default();
3493 tester.pump_widget(ltr(Material::new().child(
3494 Center::new().child(
3495 InkWell::new()
3496 .on_tertiary_tap_down(logged(&log, "tertiary-tap-down"))
3497 .on_tertiary_tap_up(logged(&log, "tertiary-tap-up"))
3498 .on_tertiary_tap_cancel(logger(&log, "tertiary-tap-cancel")),
3499 ),
3500 )));
3501
3502 let mut mouse = TestPointer::mouse(1, K_TERTIARY_BUTTON);
3503 tester.down(&mut mouse, center_of_view());
3504 tester.up(&mouse);
3505 assert_eq!(take(&log), ["tertiary-tap-down", "tertiary-tap-up"]);
3506
3507 let mut mouse = TestPointer::mouse(2, K_TERTIARY_BUTTON);
3508 tester.down(&mut mouse, center_of_view());
3509 tester.move_to(&mut mouse, Offset::new(100.0, 100.0), true);
3510 tester.up(&mouse);
3511 assert_eq!(take(&log), ["tertiary-tap-down", "tertiary-tap-cancel"]);
3512 });
3513 }
3514
3515 #[test]
3516 fn ink_well_tertiary_tap_highlights_only_when_a_tertiary_callback_is_defined() {
3517 test_widgets(|tester| {
3518 let log: Rc<RefCell<Vec<bool>>> = Rc::default();
3519 let build_frame = |with_tertiary_tap_down: bool, with_tertiary_tap_up: bool| {
3520 let mut ink_well = InkWell::new()
3521 .on_tap(Listener::new(|_app| {}))
3522 .on_highlight_changed({
3523 let log = Rc::clone(&log);
3524 Rc::new(move |_app, value| log.borrow_mut().push(value))
3525 });
3526 if with_tertiary_tap_down {
3527 ink_well = ink_well.on_tertiary_tap_down(Rc::new(|_app, _details| {}));
3528 }
3529 if with_tertiary_tap_up {
3530 ink_well = ink_well.on_tertiary_tap_up(Rc::new(|_app, _details| {}));
3531 }
3532 ltr(Material::new().child(
3533 Center::new().child(SizedBox::new().width(100.0).height(100.0).child(ink_well)),
3534 ))
3535 };
3536
3537 for (with_tertiary_tap_down, with_tertiary_tap_up) in
3540 [(false, true), (true, false), (true, true)]
3541 {
3542 tester.pump_widget(build_frame(with_tertiary_tap_down, with_tertiary_tap_up));
3543 let mut mouse = TestPointer::mouse(1, K_TERTIARY_BUTTON);
3544 tester.down(&mut mouse, center_of_view());
3545 tester.pump_by(Duration::from_millis(200));
3546 assert_eq!(std::mem::take(&mut *log.borrow_mut()), [true]);
3547
3548 tester.up(&mouse);
3549 tester.pump_by(Duration::from_millis(200));
3550 assert_eq!(std::mem::take(&mut *log.borrow_mut()), [false]);
3551 }
3552
3553 tester.pump_widget(build_frame(false, false));
3555 let mut mouse = TestPointer::mouse(1, K_TERTIARY_BUTTON);
3556 tester.down(&mut mouse, center_of_view());
3557 tester.pump_by(Duration::from_millis(200));
3558 assert!(log.borrow().is_empty());
3559 tester.up(&mouse);
3560 });
3561 }
3562
3563 #[test]
3564 fn try_out_hover_duration_property() {
3565 test_widgets(|tester| {
3566 let log: Log = Rc::default();
3567 tester.pump_widget(ltr(Material::new().child(
3568 Center::new().child(
3569 InkWell::new()
3570 .hover_duration(Duration::from_millis(1000))
3571 .on_tap(logger(&log, "tap")),
3572 ),
3573 )));
3574 tester.tap_at(center_of_view(), 1);
3575 tester.pump_by(Duration::from_secs(1));
3576 assert_eq!(take(&log), ["tap"]);
3577 });
3578 }
3579
3580 #[test]
3582 fn ink_well_activation_action_does_not_end_immediately() {
3583 test_widgets(|tester| {
3585 let controller = MaterialStatesController::new(&mut tester.cell.borrow_mut(), None);
3586 let inner: Rc<Cell<Option<BuildContext>>> = Rc::default();
3587 tester.pump_widget(ltr(Material::new().child(
3588 Center::new().child(
3589 InkWell::new()
3590 .autofocus(true)
3591 .on_tap(Listener::new(|_app| {}))
3592 .states_controller(controller.clone())
3593 .child(Builder::new({
3594 let inner = Rc::clone(&inner);
3595 move |_app, context| {
3596 inner.set(Some(context));
3597 SizedBox::new().width(10.0).height(10.0).into_widget()
3598 }
3599 })),
3600 ),
3601 )));
3602
3603 let context = inner.get().expect("built");
3605 Actions::invoke(
3606 &mut tester.cell.borrow_mut(),
3607 context,
3608 &ButtonActivateIntent,
3609 );
3610
3611 tester.pump_by(Duration::from_millis(99));
3613 assert!(
3614 tester
3615 .cell
3616 .borrow()
3617 .get(&controller)
3618 .value()
3619 .contains(&WidgetState::Pressed)
3620 );
3621
3622 tester.pump_and_settle();
3623 assert!(
3624 !tester
3625 .cell
3626 .borrow()
3627 .get(&controller)
3628 .value()
3629 .contains(&WidgetState::Pressed)
3630 );
3631 });
3632 }
3633
3634 fn zero_area_size(tester: &mut WidgetTester, response: WidgetRef) -> waft_embedder::Size {
3635 let key = GlobalKey::new();
3636 tester.pump_widget(material_ltr(
3637 Center::new()
3638 .child(SizedBox::shrink().key(key.clone().into()).child(response))
3639 .into_widget(),
3640 ));
3641 tester
3642 .render_object(&key)
3643 .as_box()
3644 .expect("a box")
3645 .size(&tester.cell.borrow())
3646 }
3647
3648 #[test]
3649 fn ink_response_does_not_crash_in_zero_area() {
3650 test_widgets(|tester| {
3651 assert_eq!(
3652 zero_area_size(tester, InkResponse::new().into_widget()),
3653 waft_embedder::Size::ZERO
3654 )
3655 });
3656 }
3657
3658 #[test]
3659 fn ink_well_does_not_crash_at_zero_area() {
3660 test_widgets(|tester| {
3661 assert_eq!(
3662 zero_area_size(tester, InkWell::new().into_widget()),
3663 waft_embedder::Size::ZERO
3664 )
3665 });
3666 }
3667
3668 fn ink_ops(tester: &WidgetTester) -> Vec<valo::Op> {
3671 tester.ink_list().ops().to_vec()
3672 }
3673
3674 fn op_argb(color: valo::Color) -> u32 {
3675 let channel = |value: f32| (value * 255.0).round() as u32;
3676 (channel(color.a) << 24)
3677 | (channel(color.r) << 16)
3678 | (channel(color.g) << 8)
3679 | channel(color.b)
3680 }
3681
3682 fn to_rect(rect: valo::Rect) -> Rect {
3683 Rect::from_ltwh(
3684 f64::from(rect.x),
3685 f64::from(rect.y),
3686 f64::from(rect.width),
3687 f64::from(rect.height),
3688 )
3689 }
3690
3691 fn circles(ops: &[valo::Op]) -> Vec<(u32, f64)> {
3693 ops.iter()
3694 .filter_map(|op| match op {
3695 valo::Op::DrawPath { path, paint, .. } => path
3696 .as_oval()
3697 .map(|oval| (op_argb(paint.color), f64::from(oval.width) / 2.0)),
3698 _ => None,
3699 })
3700 .collect()
3701 }
3702
3703 fn rrects(ops: &[valo::Op]) -> Vec<(u32, Rect, [[f32; 2]; 4])> {
3705 ops.iter()
3706 .filter_map(|op| match op {
3707 valo::Op::DrawPath { path, paint, .. } => path
3708 .as_round_rect()
3709 .map(|(rect, radii)| (op_argb(paint.color), to_rect(rect), radii)),
3710 _ => None,
3711 })
3712 .collect()
3713 }
3714
3715 fn clip_paths(ops: &[valo::Op]) -> Vec<std::sync::Arc<valo::Path>> {
3721 ops.iter()
3722 .filter_map(|op| match op {
3723 valo::Op::ClipPath {
3724 path,
3725 is_axis_aligned_rect: false,
3726 ..
3727 } => Some(std::sync::Arc::clone(path)),
3728 _ => None,
3729 })
3730 .collect()
3731 }
3732
3733 fn rrect_path(rect: Rect, radius: f64) -> std::sync::Arc<valo::Path> {
3735 let mut builder = valo::PathBuilder::new();
3736 builder.rrect_radii(
3737 valo::Rect::new(
3738 rect.left as f32,
3739 rect.top as f32,
3740 rect.width() as f32,
3741 rect.height() as f32,
3742 ),
3743 [radius as f32; 4],
3744 );
3745 builder.build()
3746 }
3747
3748 fn covers_same_area_as(
3756 actual: &valo::Path,
3757 expected: &valo::Path,
3758 area: Rect,
3759 sample_size: usize,
3760 ) -> bool {
3761 (0..sample_size).all(|i| {
3762 (0..sample_size).all(|j| {
3763 let x = area.left + area.width() * i as f64 / sample_size as f64;
3764 let y = area.top + area.height() * j as f64 / sample_size as f64;
3765 let point = valo::Point::new(x as f32, y as f32);
3766 actual.contains(point, valo::FillRule::NonZero)
3767 == expected.contains(point, valo::FillRule::NonZero)
3768 })
3769 })
3770 }
3771
3772 fn clips_covering_rrect(
3776 clips: &[std::sync::Arc<valo::Path>],
3777 rect: Rect,
3778 radius: f64,
3779 ) -> usize {
3780 let expected = rrect_path(rect, radius);
3781 clips
3782 .iter()
3783 .filter(|clip| covers_same_area_as(clip, &expected, rect.inflate(20.0), 100))
3784 .count()
3785 }
3786
3787 fn mouse_region<K>(child: impl IntoWidget<K>) -> WidgetRef {
3788 MouseRegion::new().child(child).into_widget()
3789 }
3790
3791 fn top_left_mouse_square<K>(child: impl IntoWidget<K>) -> WidgetRef {
3793 Align::new()
3794 .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
3795 .child(SizedBox::square(Some(100.0)).child(mouse_region(child)))
3796 .into_widget()
3797 }
3798
3799 fn circle_border() -> waft_painting::CircleBorder {
3800 waft_painting::CircleBorder::default()
3801 }
3802
3803 fn rounded(radius: f64) -> waft_painting::RoundedRectangleBorder {
3804 waft_painting::RoundedRectangleBorder::new(
3805 waft_painting::BorderSide::NONE,
3806 BorderRadius::all(waft_embedder::Radius::circular(radius)).into(),
3807 )
3808 }
3809
3810 #[test]
3811 fn ink_well_custom_border_clips_for_focus_highlight() {
3812 test_widgets(|tester| {
3813 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
3814 let focus_node = focus_node(tester);
3815 tester.pump_widget(material_ltr(top_left_mouse_square(
3816 InkWell::new()
3817 .focus_node(focus_node.clone())
3818 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(10.0)))
3819 .custom_border(circle_border())
3820 .hover_color(Color::new(0xff00ff00))
3821 .on_tap(Listener::new(|_app| {})),
3822 )));
3823 tester.pump_and_settle();
3824 let ops = ink_ops(tester);
3825 assert_eq!(clip_paths(&ops).len(), 0);
3826 assert_eq!(rrects(&ops).len(), 0);
3827
3828 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3829 tester.pump_and_settle();
3830 let ops = ink_ops(tester);
3831 assert_eq!(clip_paths(&ops).len(), 1);
3832 assert_eq!(rrects(&ops).len(), 1);
3833
3834 assert_eq!(
3838 clips_covering_rrect(&clip_paths(&ops), TOP_LEFT_RECT, 50.0),
3839 1
3840 );
3841 assert_eq!(
3842 clips_covering_rrect(&clip_paths(&ops), TOP_LEFT_RECT, 20.0),
3843 0
3844 );
3845 });
3846 }
3847
3848 #[test]
3849 fn ink_well_custom_border_clips_for_hover_highlight() {
3850 test_widgets(|tester| {
3851 tester.pump_widget(material_ltr(top_left_mouse_square(
3852 InkWell::new()
3853 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(10.0)))
3854 .custom_border(circle_border())
3855 .hover_color(Color::new(0xff00ff00))
3856 .on_tap(Listener::new(|_app| {})),
3857 )));
3858 tester.pump_and_settle();
3859 let ops = ink_ops(tester);
3860 assert_eq!(clip_paths(&ops).len(), 0);
3861 assert_eq!(rrects(&ops).len(), 0);
3862
3863 let mut mouse = TestPointer::mouse(1, 0);
3865 tester.add_pointer(&mut mouse, TOP_LEFT_RECT.center());
3866 tester.pump_and_settle();
3867 let ops = ink_ops(tester);
3868 assert_eq!(clip_paths(&ops).len(), 1);
3869 assert_eq!(rrects(&ops).len(), 1);
3870
3871 assert_eq!(
3873 clips_covering_rrect(&clip_paths(&ops), TOP_LEFT_RECT, 50.0),
3874 1
3875 );
3876 });
3877 }
3878
3879 #[test]
3880 fn ink_response_radius_can_be_updated() {
3881 test_widgets(|tester| {
3882 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
3883 let focus_node = focus_node(tester);
3884 let boilerplate = |radius: f64| {
3885 material_ltr(centered_square(
3886 InkResponse::new()
3887 .focus_node(focus_node.clone())
3888 .radius(radius)
3889 .focus_color(Color::new(0xff0000ff))
3890 .on_tap(Listener::new(|_app| {})),
3891 ))
3892 };
3893
3894 tester.pump_widget(boilerplate(10.0));
3895 tester.pump_and_settle();
3896 assert_eq!(circles(&ink_ops(tester)).len(), 0);
3897
3898 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3899 tester.pump_and_settle();
3900 assert_eq!(circles(&ink_ops(tester)), [(0xff0000ff, 10.0)]);
3901
3902 tester.pump_widget(boilerplate(20.0));
3903 tester.pump_and_settle();
3904 assert_eq!(circles(&ink_ops(tester)), [(0xff0000ff, 20.0)]);
3905 });
3906 }
3907
3908 #[test]
3909 fn ink_response_highlight_shape_can_be_updated() {
3910 test_widgets(|tester| {
3911 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
3912 let focus_node = focus_node(tester);
3913 let boilerplate = |shape: BoxShape| {
3914 material_ltr(centered_square(
3915 InkResponse::new()
3916 .focus_node(focus_node.clone())
3917 .highlight_shape(shape)
3918 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(10.0)))
3919 .focus_color(Color::new(0xff0000ff))
3920 .on_tap(Listener::new(|_app| {})),
3921 ))
3922 };
3923
3924 tester.pump_widget(boilerplate(BoxShape::Circle));
3925 tester.pump_and_settle();
3926 let ops = ink_ops(tester);
3927 assert_eq!(circles(&ops).len(), 0);
3928 assert_eq!(rrects(&ops).len(), 0);
3929
3930 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3931 tester.pump_and_settle();
3932 let ops = ink_ops(tester);
3933 assert_eq!(circles(&ops).len(), 1);
3934 assert_eq!(rrects(&ops).len(), 0);
3935
3936 tester.pump_widget(boilerplate(BoxShape::Rectangle));
3937 tester.pump_and_settle();
3938 let ops = ink_ops(tester);
3939 assert_eq!(circles(&ops).len(), 0);
3940 assert_eq!(rrects(&ops).len(), 1);
3941 });
3942 }
3943
3944 #[test]
3945 fn ink_well_border_radius_can_be_updated() {
3946 test_widgets(|tester| {
3947 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
3948 let focus_node = focus_node(tester);
3949 let boilerplate = |radius: f64| {
3950 material_ltr(centered_square(
3951 InkWell::new()
3952 .focus_node(focus_node.clone())
3953 .border_radius(BorderRadius::all(waft_embedder::Radius::circular(radius)))
3954 .focus_color(Color::new(0xff0000ff))
3955 .on_tap(Listener::new(|_app| {})),
3956 ))
3957 };
3958
3959 tester.pump_widget(boilerplate(10.0));
3960 tester.pump_and_settle();
3961 assert_eq!(rrects(&ink_ops(tester)).len(), 0);
3962
3963 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3964 tester.pump_and_settle();
3965 assert_eq!(
3966 rrects(&ink_ops(tester)),
3967 [(0xff0000ff, CENTER_RECT, [[10.0; 2]; 4])]
3968 );
3969
3970 tester.pump_widget(boilerplate(30.0));
3971 tester.pump_and_settle();
3972 assert_eq!(
3973 rrects(&ink_ops(tester)),
3974 [(0xff0000ff, CENTER_RECT, [[30.0; 2]; 4])]
3975 );
3976 });
3977 }
3978
3979 #[test]
3980 fn ink_well_custom_border_can_be_updated() {
3981 test_widgets(|tester| {
3982 set_highlight_strategy(tester, FocusHighlightStrategy::AlwaysTraditional);
3983 let focus_node = focus_node(tester);
3984 let boilerplate = |radius: f64| {
3985 material_ltr(top_left_mouse_square(
3986 InkWell::new()
3987 .focus_node(focus_node.clone())
3988 .custom_border(rounded(radius))
3989 .hover_color(Color::new(0xff00ff00))
3990 .on_tap(Listener::new(|_app| {})),
3991 ))
3992 };
3993
3994 tester.pump_widget(boilerplate(20.0));
3995 tester.pump_and_settle();
3996 assert_eq!(clip_paths(&ink_ops(tester)).len(), 0);
3997
3998 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
3999 tester.pump_and_settle();
4000 let clips = clip_paths(&ink_ops(tester));
4001 assert_eq!(clips.len(), 1);
4002 assert_eq!(clips_covering_rrect(&clips, TOP_LEFT_RECT, 20.0), 1);
4003
4004 tester.pump_widget(boilerplate(40.0));
4005 tester.pump_and_settle();
4006 let clips = clip_paths(&ink_ops(tester));
4007 assert!(clips_covering_rrect(&clips, TOP_LEFT_RECT, 40.0) >= 1);
4008 });
4009 }
4010
4011 #[test]
4012 fn ink_well_splash_custom_border_can_be_updated() {
4013 test_widgets(|tester| {
4015 let focus_node = focus_node(tester);
4016 let boilerplate = |tester: &WidgetTester, radius: f64| {
4017 m2(
4018 tester,
4019 material_ltr(top_left_mouse_square(
4020 InkWell::new()
4021 .focus_node(focus_node.clone())
4022 .custom_border(rounded(radius))
4023 .on_tap(Listener::new(|_app| {})),
4024 )),
4025 )
4026 };
4027
4028 let widget = boilerplate(tester, 20.0);
4029 tester.pump_widget(widget);
4030 tester.pump_and_settle();
4031 assert_eq!(clip_paths(&ink_ops(tester)).len(), 0);
4032
4033 let mut gesture = TestPointer::touch(1);
4034 tester.down(&mut gesture, TOP_LEFT_RECT.center());
4035 tester.pump_by(Duration::from_millis(200)); let clips = clip_paths(&ink_ops(tester));
4037 assert_eq!(clips.len(), 2); assert!(clips_covering_rrect(&clips, TOP_LEFT_RECT, 20.0) >= 2);
4041
4042 let widget = boilerplate(tester, 40.0);
4043 tester.pump_widget(widget);
4044 tester.pump_and_settle();
4045
4046 let clips = clip_paths(&ink_ops(tester));
4048 assert!(clips_covering_rrect(&clips, TOP_LEFT_RECT, 40.0) >= 2);
4049
4050 tester.up(&gesture);
4051 });
4052 }
4053
4054 fn padded_ink_well(key: Option<&GlobalKey>, child: Option<WidgetRef>) -> WidgetRef {
4056 let mut padding = Padding::new(waft_painting::EdgeInsets::all(50.0));
4057 if let Some(child) = child {
4058 padding = padding.child(child);
4059 }
4060 let mut ink_well = InkWell::new()
4061 .on_tap(Listener::new(|_app| {}))
4062 .child(padding);
4063 if let Some(key) = key {
4064 ink_well = ink_well.key(key.clone().into());
4065 }
4066 ink_well.into_widget()
4067 }
4068
4069 fn pump_splash(tester: &mut WidgetTester, duration: Duration) {
4072 tester.pump_by(duration);
4073 tester.pump_by(Duration::from_millis(16)); }
4075
4076 fn circle_count(tester: &WidgetTester) -> usize {
4077 circles(&ink_ops(tester)).len()
4078 }
4079
4080 fn top_left_of(tester: &WidgetTester, key: &GlobalKey) -> Offset {
4081 let render = tester.render_object(key).as_box().expect("a render box");
4082 let app = tester.cell.borrow();
4083 render.local_to_global(&app, Offset::ZERO, None)
4084 }
4085
4086 fn m2_top_left(tester: &WidgetTester, width: f64, height: f64, child: WidgetRef) -> WidgetRef {
4089 m2(
4090 tester,
4091 material_ltr(
4092 Align::new()
4093 .alignment(waft_painting::AlignmentGeometry::TOP_LEFT)
4094 .child(SizedBox::new().width(width).height(height).child(child))
4095 .into_widget(),
4096 ),
4097 )
4098 }
4099
4100 #[test]
4101 fn reparenting_parent_should_allow_both_inkwells_to_show_splash_afterwards() {
4102 test_widgets(|tester| {
4103 let middle_key = GlobalKey::new();
4104 let inner_key = GlobalKey::new();
4105 let widget = m2_top_left(
4106 tester,
4107 200.0,
4108 100.0,
4109 Row::new()
4110 .children([
4111 padded_ink_well(
4112 Some(&middle_key),
4113 Some(padded_ink_well(Some(&inner_key), None)),
4114 ),
4115 SizedBox::new().into_widget(),
4116 ])
4117 .into_widget(),
4118 );
4119 tester.pump_widget(widget);
4120
4121 let mut gesture1 = TestPointer::touch(1);
4123 let inner = tester.get_center(&inner_key);
4124 tester.down(&mut gesture1, inner);
4125 pump_splash(tester, Duration::from_millis(200));
4126 assert_eq!(circle_count(tester), 1);
4127
4128 let widget = m2_top_left(
4130 tester,
4131 200.0,
4132 100.0,
4133 Row::new()
4134 .children([
4135 padded_ink_well(Some(&inner_key), None),
4136 padded_ink_well(Some(&middle_key), None),
4137 ])
4138 .into_widget(),
4139 );
4140 tester.pump_widget(widget);
4141
4142 tester.up(&gesture1);
4144 tester.pump_and_settle();
4145 assert!(ink_ops(tester).is_empty(), "{:?}", ink_ops(tester));
4146
4147 let middle = tester.get_center(&middle_key);
4149 tester.down(&mut gesture1, middle);
4150 pump_splash(tester, Duration::from_millis(200));
4151 assert_eq!(circle_count(tester), 1);
4152
4153 let mut gesture2 = TestPointer::touch(2);
4155 let inner = tester.get_center(&inner_key);
4156 tester.down(&mut gesture2, inner);
4157 pump_splash(tester, Duration::from_millis(200));
4158 assert_eq!(circle_count(tester), 2);
4159
4160 tester.up(&gesture1);
4162 tester.up(&gesture2);
4163 tester.pump_and_settle();
4164 });
4165 }
4166
4167 #[test]
4168 fn parent_inkwell_does_not_block_child_inkwells_from_splashes() {
4169 test_widgets(|tester| {
4170 let middle_key = GlobalKey::new();
4171 let inner_key = GlobalKey::new();
4172 let tree = padded_ink_well(
4173 None,
4174 Some(padded_ink_well(
4175 Some(&middle_key),
4176 Some(padded_ink_well(
4177 Some(&inner_key),
4178 Some(SizedBox::new().width(50.0).height(50.0).into_widget()),
4179 )),
4180 )),
4181 );
4182 let widget = m2(
4183 tester,
4184 material_ltr(Center::new().child(tree).into_widget()),
4185 );
4186 tester.pump_widget(widget);
4187
4188 let mut gesture1 = TestPointer::touch(1);
4190 let middle = top_left_of(tester, &middle_key) + Offset::new(1.0, 1.0);
4191 tester.down(&mut gesture1, middle);
4192 pump_splash(tester, Duration::from_millis(200));
4193 assert_eq!(circle_count(tester), 1);
4194
4195 let mut gesture2 = TestPointer::touch(2);
4197 let inner = tester.get_center(&inner_key);
4198 tester.down(&mut gesture2, inner);
4199 pump_splash(tester, Duration::from_millis(200));
4200 assert_eq!(circle_count(tester), 2);
4201
4202 tester.up(&gesture1);
4204 tester.up(&gesture2);
4205 tester.pump_and_settle();
4206 });
4207 }
4208
4209 #[test]
4210 fn parent_inkwell_can_count_the_number_of_pressed_children_to_prevent_splash() {
4211 test_widgets(|tester| {
4212 let parent_key = GlobalKey::new();
4213 let left_key = GlobalKey::new();
4214 let right_key = GlobalKey::new();
4215 let child_well = |key: &GlobalKey| {
4216 SizedBox::square(Some(50.0))
4217 .child(
4218 InkWell::new()
4219 .key(key.clone().into())
4220 .on_tap(Listener::new(|_app| {})),
4221 )
4222 .into_widget()
4223 };
4224 let parent = InkWell::new()
4225 .key(parent_key.clone().into())
4226 .on_tap(Listener::new(|_app| {}))
4227 .child(Center::new().child(
4228 SizedBox::new().width(100.0).height(50.0).child(
4229 Row::new().children([child_well(&left_key), child_well(&right_key)]),
4230 ),
4231 ));
4232 let widget = m2(tester, material_ltr(centered_square(parent)));
4233 tester.pump_widget(widget);
4234
4235 let parent_position = top_left_of(tester, &parent_key) + Offset::new(1.0, 1.0);
4236
4237 let mut gesture1 = TestPointer::touch(1);
4239 let left = tester.get_center(&left_key);
4240 tester.down(&mut gesture1, left);
4241 pump_splash(tester, Duration::from_millis(200));
4242 assert_eq!(circle_count(tester), 1);
4243
4244 let mut gesture2 = TestPointer::touch(2);
4246 let right = tester.get_center(&right_key);
4247 tester.down(&mut gesture2, right);
4248 pump_splash(tester, Duration::from_millis(200));
4249 assert_eq!(circle_count(tester), 2);
4250
4251 let mut gesture3 = TestPointer::touch(3);
4253 tester.down(&mut gesture3, parent_position);
4254 pump_splash(tester, Duration::from_millis(200));
4255 assert_eq!(circle_count(tester), 2);
4256 tester.up(&gesture3);
4257
4258 tester.up(&gesture1);
4260 tester.pump_and_settle();
4261 assert_eq!(circle_count(tester), 1);
4262
4263 tester.down(&mut gesture3, parent_position);
4265 pump_splash(tester, Duration::from_millis(200));
4266 assert_eq!(circle_count(tester), 1);
4267 tester.up(&gesture3);
4268
4269 tester.up(&gesture2);
4271 tester.pump_and_settle();
4272 assert_eq!(circle_count(tester), 0);
4273
4274 tester.down(&mut gesture3, parent_position);
4276 pump_splash(tester, Duration::from_millis(200));
4277 assert_eq!(circle_count(tester), 1);
4278 tester.up(&gesture3);
4279 });
4280 }
4281
4282 #[test]
4283 fn when_ink_wells_are_reparented_the_old_parent_can_display_splash_while_the_new_parent_can_not()
4284 {
4285 test_widgets(|tester| {
4286 let inner_key = GlobalKey::new();
4287 let left_key = GlobalKey::new();
4288 let right_key = GlobalKey::new();
4289 let inner = || {
4290 InkWell::new()
4291 .key(inner_key.clone().into())
4292 .on_tap(Listener::new(|_app| {}))
4293 .into_widget()
4294 };
4295 let double_ink_well_row =
4296 |tester: &WidgetTester,
4297 left_width: f64,
4298 right_width: f64,
4299 left_child: Option<WidgetRef>,
4300 right_child: Option<WidgetRef>| {
4301 let side = |key: &GlobalKey, width: f64, child: Option<WidgetRef>| {
4302 let mut inner_box = SizedBox::new().width(left_width).height(50.0);
4303 if let Some(child) = child {
4304 inner_box = inner_box.child(child);
4305 }
4306 SizedBox::new()
4307 .width(width)
4308 .height(100.0)
4309 .child(
4310 InkWell::new()
4311 .key(key.clone().into())
4312 .on_tap(Listener::new(|_app| {}))
4313 .child(Center::new().child(inner_box)),
4314 )
4315 .into_widget()
4316 };
4317 m2_top_left(
4318 tester,
4319 left_width + right_width,
4320 100.0,
4321 Row::new()
4322 .children([
4323 side(&left_key, left_width, left_child),
4324 side(&right_key, right_width, right_child),
4325 ])
4326 .into_widget(),
4327 )
4328 };
4329
4330 let widget = double_ink_well_row(tester, 110.0, 90.0, Some(inner()), None);
4331 tester.pump_widget(widget);
4332
4333 let mut gesture = TestPointer::touch(1);
4335 tester.down(&mut gesture, Offset::new(100.0, 50.0));
4336 pump_splash(tester, Duration::from_millis(200));
4337 assert_eq!(circle_count(tester), 1);
4338
4339 let widget = double_ink_well_row(tester, 90.0, 110.0, None, Some(inner()));
4341 tester.pump_widget(widget);
4342 assert_eq!(circle_count(tester), 0);
4343
4344 let mut gesture2 = TestPointer::touch(2);
4346 tester.down(&mut gesture2, Offset::new(100.0, 50.0));
4347 pump_splash(tester, Duration::from_millis(200));
4348 assert_eq!(circle_count(tester), 1);
4349
4350 tester.up(&gesture);
4351 tester.up(&gesture2);
4352 tester.pump_and_settle();
4353
4354 tester.down(&mut gesture, Offset::new(100.0, 50.0));
4356 pump_splash(tester, Duration::from_millis(200));
4357 assert_eq!(circle_count(tester), 1);
4358
4359 tester.down(&mut gesture2, Offset::new(50.0, 50.0));
4361 pump_splash(tester, Duration::from_millis(200));
4362 assert_eq!(circle_count(tester), 2);
4363
4364 tester.up(&gesture);
4365 tester.up(&gesture2);
4366 });
4367 }
4368
4369 #[test]
4370 fn ink_wells_splash_starts_before_tap_is_confirmed_and_disappears_after_tap_is_canceled() {
4371 test_widgets(|tester| {
4372 let inner_key = GlobalKey::new();
4373 let tree = GestureDetector::new()
4374 .on_horizontal_drag_start(Rc::new(|_app, _details| {}))
4375 .child(centered_square(
4376 InkWell::new().on_tap(Listener::new(|_app| {})).child(
4377 Center::new().child(
4378 SizedBox::square(Some(50.0)).child(
4379 InkWell::new()
4380 .key(inner_key.clone().into())
4381 .on_tap(Listener::new(|_app| {})),
4382 ),
4383 ),
4384 ),
4385 ));
4386 let widget = m2(tester, material_ltr(tree.into_widget()));
4387 tester.pump_widget(widget);
4388
4389 let mut gesture = TestPointer::touch(1);
4391 let inner = tester.get_center(&inner_key);
4392 tester.down(&mut gesture, inner);
4393 pump_splash(tester, Duration::from_millis(200));
4394 assert_eq!(circle_count(tester), 1);
4395
4396 let moved = inner + Offset::new(0.0, -100.0);
4398 tester.move_to(&mut gesture, moved, true);
4399 tester.pump_and_settle();
4400 assert!(ink_ops(tester).is_empty(), "{:?}", ink_ops(tester));
4401
4402 tester.up(&gesture);
4404 tester.pump_and_settle();
4405 assert!(ink_ops(tester).is_empty(), "{:?}", ink_ops(tester));
4406
4407 tester.down(&mut gesture, inner);
4409 pump_splash(tester, Duration::from_millis(200));
4410 assert_eq!(circle_count(tester), 1);
4411 });
4412 }
4413
4414 #[test]
4415 fn the_ink_well_widget_on_overlay_portal_does_not_throw() {
4416 test_widgets(|tester| {
4417 let controller = {
4418 let mut app = tester.cell.borrow_mut();
4419 let controller = OverlayPortalController::new(&mut app, None);
4420 controller.show(&mut app);
4421 controller
4422 };
4423 let overlay_entry = OverlayEntry::new(
4424 &mut tester.cell.borrow_mut(),
4425 Rc::new(move |_app: &mut App, _context| {
4426 Center::new()
4427 .child(
4428 SizedBox::square(Some(100.0)).child(
4429 Material::new()
4433 .color(Colors::BLACK)
4434 .child(OverlayPortal::new(
4435 controller.clone(),
4436 |_app, _context| {
4437 Positioned::new(
4438 InkWell::new()
4439 .splash_color(Colors::RED.primary())
4440 .on_tap(Listener::new(|_app| {}))
4441 .child(SizedBox::square(Some(100.0))),
4442 )
4443 .right(0.0)
4444 .bottom(0.0)
4445 .into_widget()
4446 },
4447 )),
4448 ),
4449 )
4450 .into_widget()
4451 }),
4452 false,
4453 false,
4454 false,
4455 );
4456 tester.pump_widget(
4457 Center::new()
4458 .child(
4459 RepaintBoundary::new().child(
4460 SizedBox::square(Some(200.0)).child(ltr(
4461 Overlay::new().initial_entries([overlay_entry.clone()])
4462 )),
4463 ),
4464 )
4465 .into_widget(),
4466 );
4467
4468 let ink_well = find::by_type::<InkWell>().evaluate(tester)[0];
4469 let center = { tester.get_center(ink_well) };
4470 let mut gesture = TestPointer::touch(1);
4471 tester.down(&mut gesture, center);
4472 tester.pump(); tester.pump_by(Duration::from_secs(2));
4474
4475 tester.up(&gesture);
4476 overlay_entry.remove(&mut tester.cell.borrow_mut());
4477 overlay_entry.dispose(&mut tester.cell.borrow_mut());
4478 });
4479 }
4480}