1use std::any::{Any, TypeId};
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_animation::{AnimationBehavior, AnimationController, AnimationRef};
15use waft_embedder::{
16 AppLifecycleState, Offset, PointerDeviceKind, Rect, Size, TargetPlatform, TextAffinity,
17 TextDirection, TextEditingValue, TextPosition, TextRange, TextSelection,
18};
19use waft_foundation::{
20 App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, K_IS_WEB, Listener, OptionRetained,
21 Task, ValueChanged, ValueNotifier,
22};
23use waft_gestures::{
24 BaseTapAndDragGestureRecognizer, DeviceGestureSettings, DragEndDetails, DragGestureRecognizer,
25 DragStartBehavior, DragStartDetails, DragUpdateDetails, ForcePressDetails,
26 ForcePressGestureRecognizer, GestureCancelCallback, GestureForcePressEndCallback,
27 GestureForcePressStartCallback, GestureLongPressCancelCallback, GestureLongPressEndCallback,
28 GestureLongPressMoveUpdateCallback, GestureLongPressStartCallback, GestureTapCallback,
29 GestureTapDownCallback, GestureTapDragDownCallback, GestureTapDragEndCallback,
30 GestureTapDragStartCallback, GestureTapDragUpCallback, GestureTapDragUpdateCallback,
31 LongPressEndDetails, LongPressGestureRecognizer, LongPressMoveUpdateDetails,
32 LongPressStartDetails, PanGestureRecognizer, TapAndHorizontalDragGestureRecognizer,
33 TapAndPanGestureRecognizer, TapDownDetails, TapDragDownDetails, TapDragEndDetails,
34 TapDragStartDetails, TapDragUpDetails, TapDragUpdateDetails, TapGestureRecognizer,
35 TapStatusTracker,
36};
37use waft_painting::{
38 AlignmentGeometry, Axis, AxisDirection, EdgeInsetsGeometry, axis_direction_to_axis,
39 transform_rect,
40};
41use waft_rendering::{
42 AnyRenderBox, BoxParentData, ContainerBoxParentData, ContainerParentData, HitTestBehavior,
43 LayerLink, ParentData, RelativeRect, RenderBox, RenderEditable, RenderHandle,
44 TextSelectionPoint,
45};
46use waft_scheduler::{
47 FrameCallback, SchedulerBinding, SchedulerPhase, Ticker, TickerCallback, TickerProviderObject,
48};
49use waft_services::{
50 AnyTextSelectionDelegate, Clipboard, HapticFeedback, HardwareKeyboard, LogicalKeyboardKey,
51 SelectionChangedCause, ServicesBinding, TextSelectionDelegate, is_line_terminator,
52};
53
54use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
55use crate::framework::{
56 BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
57};
58use crate::view::View;
59use crate::widgets::basic::{
60 Align, CompositedTransformFollower, Directionality, ExcludeSemantics, Padding, SizedBox,
61 WidgetBuilder,
62};
63use crate::widgets::constants::K_MIN_INTERACTIVE_DIMENSION;
64use crate::widgets::editable_text::EditableTextState;
65use crate::widgets::feedback::Feedback;
66use crate::widgets::gesture_detector::{
67 GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
68 RawGestureDetector,
69};
70use crate::widgets::inherited_theme::{CapturedThemes, InheritedTheme};
71use crate::widgets::magnifier::{MagnifierController, MagnifierInfo, TextMagnifierConfiguration};
72use crate::widgets::navigator::Navigator;
73use crate::widgets::overlay::{Overlay, OverlayEntry};
74use crate::widgets::scrollable::Scrollable;
75use crate::widgets::tap_region::TextFieldTapRegion;
76use crate::widgets::ticker_provider::{
77 SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData,
78};
79use crate::widgets::transitions::FadeTransition;
80use waft_foundation::ListenableObject;
81use waft_foundation::Ref;
82
83pub use waft_rendering::TextSelectionHandleType;
84
85pub type ToolbarBuilder = Rc<dyn Fn(&mut App, BuildContext, WidgetRef) -> WidgetRef>;
94
95#[derive(Debug)]
101pub struct ToolbarItemsParentData {
102 box_parent_data: BoxParentData,
103 container_parent_data: ContainerParentData<AnyRenderBox>,
104 pub should_paint: bool,
109}
110
111impl ToolbarItemsParentData {
112 pub const fn new() -> ToolbarItemsParentData {
114 ToolbarItemsParentData {
115 box_parent_data: BoxParentData::new(),
116 container_parent_data: ContainerParentData::new(),
117 should_paint: false,
118 }
119 }
120}
121
122impl Default for ToolbarItemsParentData {
123 fn default() -> ToolbarItemsParentData {
124 ToolbarItemsParentData::new()
125 }
126}
127
128impl ParentData for ToolbarItemsParentData {
129 fn detach(&mut self) {
130 waft_rendering::ContainerParentDataMixin::detach(self);
131 }
132
133 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
134 if id == TypeId::of::<ToolbarItemsParentData>() {
135 return Some(self);
136 }
137 self.box_parent_data.provide(id)
138 }
139
140 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
141 if id == TypeId::of::<ToolbarItemsParentData>() {
142 return Some(self);
143 }
144 self.box_parent_data.provide_mut(id)
145 }
146}
147
148impl waft_rendering::ContainerParentDataMixin for ToolbarItemsParentData {
149 type ChildType = AnyRenderBox;
150
151 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
152 &self.container_parent_data
153 }
154
155 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
156 &mut self.container_parent_data
157 }
158}
159
160impl ContainerBoxParentData for ToolbarItemsParentData {
161 fn box_parent_data(&self) -> &BoxParentData {
162 &self.box_parent_data
163 }
164
165 fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
166 &mut self.box_parent_data
167 }
168}
169
170impl fmt::Display for ToolbarItemsParentData {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 write!(
173 f,
174 "{}; shouldPaint={}",
175 self.box_parent_data, self.should_paint
176 )
177 }
178}
179
180#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
182pub enum ClipboardStatus {
183 Pasteable,
185 Unknown,
189 NotPasteable,
191}
192
193#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
199pub enum LiveTextInputStatus {
200 Enabled,
202 Unknown,
206 Disabled,
208}
209
210pub struct ClipboardStatusNotifier {
218 change_notifier: ChangeNotifierData,
219 value: ClipboardStatus,
220 disposed: bool,
221 observer: Option<WidgetsBindingObserverRef>,
222 web: bool,
225}
226
227impl Debug for ClipboardStatusNotifier {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.debug_struct("ClipboardStatusNotifier")
230 .field("value", &self.value)
231 .finish()
232 }
233}
234
235impl ClipboardStatusNotifier {
236 pub fn new(app: &mut App) -> Ref<ClipboardStatusNotifier> {
238 Self::from_value(app, ClipboardStatus::Unknown)
239 }
240
241 pub fn from_value(app: &mut App, value: ClipboardStatus) -> Ref<ClipboardStatusNotifier> {
243 app.create(ClipboardStatusNotifier {
244 change_notifier: ChangeNotifierData::new(),
245 value,
246 disposed: false,
247 observer: None,
248 web: false,
249 })
250 }
251
252 pub fn web(app: &mut App) -> Ref<ClipboardStatusNotifier> {
255 app.create(ClipboardStatusNotifier {
256 change_notifier: ChangeNotifierData::new(),
257 value: ClipboardStatus::Pasteable,
258 disposed: false,
259 observer: None,
260 web: true,
261 })
262 }
263
264 fn clipboard_listener(self: Handle<Self>) -> Listener {
266 Listener::handle_method(self, Self::clipboard_changed)
267 }
268
269 fn clipboard_changed(self: Handle<Self>, app: &mut App) {
271 self.update(app);
272 }
273
274 fn stop_listening_to_the_clipboard(self: Handle<Self>, app: &mut App) {
275 let clipboard = ServicesBinding::instance(app).clipboard(app);
276 clipboard.remove_listener(app, &Self::clipboard_listener(self));
277 }
278
279 fn observer(self: Handle<Self>, app: &mut App) -> WidgetsBindingObserverRef {
280 if let Some(observer) = app.get(self).observer.clone() {
281 return observer;
282 }
283 let observer: WidgetsBindingObserverRef = Rc::new(self);
284 app.get_mut(self).observer = Some(observer.clone());
285 observer
286 }
287
288 pub fn value(self: Handle<Self>, app: &App) -> ClipboardStatus {
290 app.get(self).value
291 }
292
293 pub fn set_value(self: Handle<Self>, app: &mut App, new_value: ClipboardStatus) {
295 if app.get(self).value == new_value {
296 return;
297 }
298 app.get_mut(self).value = new_value;
299 self.notify_listeners(app);
300 }
301
302 pub fn update(self: Handle<Self>, app: &mut App) -> Task<()> {
304 if app.get(self).disposed || app.get(self).web {
305 return Task::ready(());
306 }
307
308 let has_strings = Clipboard::has_strings(app);
309 app.spawn(async move |cx| {
310 let next_status = if has_strings.await {
311 ClipboardStatus::Pasteable
312 } else {
313 ClipboardStatus::NotPasteable
314 };
315 cx.update(|app| {
316 if !app.contains(self) || app.get(self).disposed {
317 return;
318 }
319 self.set_value(app, next_status);
320 });
321 })
322 }
323
324 pub fn dispose(self: Handle<Self>, app: &mut App) {
326 if let Some(observer) = app.get(self).observer.clone() {
327 WidgetsBinding::instance(app).remove_observer(app, &observer);
328 }
329 self.stop_listening_to_the_clipboard(app);
330 app.get_mut(self).disposed = true;
331 ChangeNotifierData::dispose(app, self);
332 }
333}
334
335impl ChangeNotifier for ClipboardStatusNotifier {
336 fn change_notifier_data(&self) -> &ChangeNotifierData {
337 &self.change_notifier
338 }
339
340 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
341 &mut self.change_notifier
342 }
343
344 fn will_add_listener(self: Handle<Self>, app: &mut App) {
345 if !app.get(self).change_notifier.has_listeners() {
346 let observer = self.observer(app);
347 WidgetsBinding::instance(app).add_observer(app, observer);
348 let clipboard = ServicesBinding::instance(app).clipboard(app);
349 clipboard.add_listener(app, Self::clipboard_listener(self));
350 }
351 if app.get(self).value == ClipboardStatus::Unknown {
352 self.update(app);
353 }
354 }
355
356 fn did_remove_listener(self: Handle<Self>, app: &mut App) {
357 if app.get(self).disposed || app.get(self).change_notifier.has_listeners() {
358 return;
359 }
360 if let Some(observer) = app.get(self).observer.clone() {
361 WidgetsBinding::instance(app).remove_observer(app, &observer);
362 }
363 self.stop_listening_to_the_clipboard(app);
364 }
365}
366
367impl WidgetsBindingObserverObject for ClipboardStatusNotifier {
368 fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
369 match state {
370 AppLifecycleState::Resumed => {
371 self.update(app);
372 }
373 AppLifecycleState::Detached
374 | AppLifecycleState::Inactive
375 | AppLifecycleState::Hidden
376 | AppLifecycleState::Paused => {
377 }
379 }
380 }
381}
382
383pub struct LiveTextInputStatusNotifier {
394 change_notifier: ChangeNotifierData,
395 value: LiveTextInputStatus,
396 disposed: bool,
397 observer: Option<WidgetsBindingObserverRef>,
398}
399
400impl Debug for LiveTextInputStatusNotifier {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.debug_struct("LiveTextInputStatusNotifier")
403 .field("value", &self.value)
404 .finish()
405 }
406}
407
408impl LiveTextInputStatusNotifier {
409 pub fn new(app: &mut App) -> Ref<LiveTextInputStatusNotifier> {
411 Self::from_value(app, LiveTextInputStatus::Unknown)
412 }
413
414 pub fn from_value(
416 app: &mut App,
417 value: LiveTextInputStatus,
418 ) -> Ref<LiveTextInputStatusNotifier> {
419 app.create(LiveTextInputStatusNotifier {
420 change_notifier: ChangeNotifierData::new(),
421 value,
422 disposed: false,
423 observer: None,
424 })
425 }
426
427 fn observer(self: Handle<Self>, app: &mut App) -> WidgetsBindingObserverRef {
428 if let Some(observer) = app.get(self).observer.clone() {
429 return observer;
430 }
431 let observer: WidgetsBindingObserverRef = Rc::new(self);
432 app.get_mut(self).observer = Some(observer.clone());
433 observer
434 }
435
436 pub fn value(self: Handle<Self>, app: &App) -> LiveTextInputStatus {
438 app.get(self).value
439 }
440
441 pub fn set_value(self: Handle<Self>, app: &mut App, new_value: LiveTextInputStatus) {
443 if app.get(self).value == new_value {
444 return;
445 }
446 app.get_mut(self).value = new_value;
447 self.notify_listeners(app);
448 }
449
450 pub fn update(self: Handle<Self>, app: &mut App) {
452 if app.get(self).disposed {
453 return;
454 }
455
456 let next_status = if waft_services::LiveText::is_live_text_input_available(app) {
457 LiveTextInputStatus::Enabled
458 } else {
459 LiveTextInputStatus::Disabled
460 };
461 if app.get(self).disposed || next_status == app.get(self).value {
462 return;
463 }
464 self.set_value(app, next_status);
465 }
466
467 pub fn dispose(self: Handle<Self>, app: &mut App) {
469 if let Some(observer) = app.get(self).observer.clone() {
470 WidgetsBinding::instance(app).remove_observer(app, &observer);
471 }
472 app.get_mut(self).disposed = true;
473 ChangeNotifierData::dispose(app, self);
474 }
475}
476
477impl ChangeNotifier for LiveTextInputStatusNotifier {
478 fn change_notifier_data(&self) -> &ChangeNotifierData {
479 &self.change_notifier
480 }
481
482 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
483 &mut self.change_notifier
484 }
485
486 fn will_add_listener(self: Handle<Self>, app: &mut App) {
487 if !app.get(self).change_notifier.has_listeners() {
488 let observer = self.observer(app);
489 WidgetsBinding::instance(app).add_observer(app, observer);
490 }
491 if app.get(self).value == LiveTextInputStatus::Unknown {
492 self.update(app);
493 }
494 }
495
496 fn did_remove_listener(self: Handle<Self>, app: &mut App) {
497 if app.get(self).disposed || app.get(self).change_notifier.has_listeners() {
498 return;
499 }
500 if let Some(observer) = app.get(self).observer.clone() {
501 WidgetsBinding::instance(app).remove_observer(app, &observer);
502 }
503 }
504}
505
506impl WidgetsBindingObserverObject for LiveTextInputStatusNotifier {
507 fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
508 match state {
509 AppLifecycleState::Resumed => self.update(app),
510 AppLifecycleState::Detached
511 | AppLifecycleState::Inactive
512 | AppLifecycleState::Paused
513 | AppLifecycleState::Hidden => {
514 }
516 }
517 }
518}
519
520pub trait TextSelectionControls {
551 fn build_handle(
561 &self,
562 app: &mut App,
563 context: BuildContext,
564 handle_type: TextSelectionHandleType,
565 text_line_height: f64,
566 on_tap: Option<Listener>,
567 ) -> WidgetRef;
568
569 fn get_handle_anchor(
573 &self,
574 handle_type: TextSelectionHandleType,
575 text_line_height: f64,
576 ) -> Offset;
577
578 #[deprecated(note = "Use `contextMenuBuilder` instead. \
592 This feature was deprecated after v3.3.0-0.5.pre.")]
593 #[allow(clippy::too_many_arguments)]
594 fn build_toolbar(
595 &self,
596 app: &mut App,
597 context: BuildContext,
598 global_editable_region: Rect,
599 text_line_height: f64,
600 selection_midpoint: Offset,
601 endpoints: &[TextSelectionPoint],
602 delegate: AnyTextSelectionDelegate,
603 clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
604 last_secondary_tap_down_position: Option<Offset>,
605 ) -> WidgetRef;
606
607 fn get_handle_size(&self, text_line_height: f64) -> Size;
609
610 fn as_text_selection_handle_controls(&self) -> Option<&dyn TextSelectionHandleControls> {
616 None
617 }
618
619 #[deprecated(note = "Use `contextMenuBuilder` instead. \
628 This feature was deprecated after v3.3.0-0.5.pre.")]
629 fn can_cut(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
630 delegate.cut_enabled(app) && !delegate.text_editing_value(app).selection.is_collapsed()
631 }
632
633 #[deprecated(note = "Use `contextMenuBuilder` instead. \
641 This feature was deprecated after v3.3.0-0.5.pre.")]
642 fn can_copy(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
643 delegate.copy_enabled(app) && !delegate.text_editing_value(app).selection.is_collapsed()
644 }
645
646 #[deprecated(note = "Use `contextMenuBuilder` instead. \
656 This feature was deprecated after v3.3.0-0.5.pre.")]
657 fn can_paste(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
658 delegate.paste_enabled(app)
659 }
660
661 #[deprecated(note = "Use `contextMenuBuilder` instead. \
668 This feature was deprecated after v3.3.0-0.5.pre.")]
669 fn can_select_all(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
670 delegate.select_all_enabled(app)
671 && !delegate.text_editing_value(app).text.is_empty()
672 && delegate.text_editing_value(app).selection.is_collapsed()
673 }
674
675 #[deprecated(note = "Use `contextMenuBuilder` instead. \
680 This feature was deprecated after v3.3.0-0.5.pre.")]
681 fn handle_cut(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
682 delegate.cut_selection(app, SelectionChangedCause::Toolbar);
683 }
684
685 #[deprecated(note = "Use `contextMenuBuilder` instead. \
690 This feature was deprecated after v3.3.0-0.5.pre.")]
691 fn handle_copy(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
692 delegate.copy_selection(app, SelectionChangedCause::Toolbar);
693 }
694
695 #[deprecated(note = "Use `contextMenuBuilder` instead. \
700 This feature was deprecated after v3.3.0-0.5.pre.")]
701 fn handle_paste(&self, app: &mut App, delegate: AnyTextSelectionDelegate) -> Task<()> {
702 delegate.paste_text(app, SelectionChangedCause::Toolbar)
703 }
704
705 #[deprecated(note = "Use `contextMenuBuilder` instead. \
713 This feature was deprecated after v3.3.0-0.5.pre.")]
714 fn handle_select_all(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
715 delegate.select_all(app, SelectionChangedCause::Toolbar);
716 }
717}
718
719pub trait TextSelectionHandleControls: TextSelectionControls {
728 #[deprecated(note = "Use `contextMenuBuilder` instead. \
730 This feature was deprecated after v3.3.0-0.5.pre.")]
731 #[allow(clippy::too_many_arguments)]
732 fn build_toolbar(
733 &self,
734 app: &mut App,
735 context: BuildContext,
736 global_editable_region: Rect,
737 text_line_height: f64,
738 selection_midpoint: Offset,
739 endpoints: &[TextSelectionPoint],
740 delegate: AnyTextSelectionDelegate,
741 clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
742 last_secondary_tap_down_position: Option<Offset>,
743 ) -> WidgetRef {
744 let _ = (
745 app,
746 context,
747 global_editable_region,
748 text_line_height,
749 selection_midpoint,
750 endpoints,
751 delegate,
752 clipboard_status,
753 last_secondary_tap_down_position,
754 );
755 SizedBox::shrink().into_widget()
756 }
757
758 #[deprecated(note = "Use `contextMenuBuilder` instead. \
759 This feature was deprecated after v3.3.0-0.5.pre.")]
760 fn can_cut(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
761 let _ = (app, delegate);
762 false
763 }
764
765 #[deprecated(note = "Use `contextMenuBuilder` instead. \
766 This feature was deprecated after v3.3.0-0.5.pre.")]
767 fn can_copy(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
768 let _ = (app, delegate);
769 false
770 }
771
772 #[deprecated(note = "Use `contextMenuBuilder` instead. \
773 This feature was deprecated after v3.3.0-0.5.pre.")]
774 fn can_paste(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
775 let _ = (app, delegate);
776 false
777 }
778
779 #[deprecated(note = "Use `contextMenuBuilder` instead. \
780 This feature was deprecated after v3.3.0-0.5.pre.")]
781 fn can_select_all(&self, app: &App, delegate: AnyTextSelectionDelegate) -> bool {
782 let _ = (app, delegate);
783 false
784 }
785
786 #[deprecated(note = "Use `contextMenuBuilder` instead. \
787 This feature was deprecated after v3.3.0-0.5.pre.")]
788 fn handle_cut(
789 &self,
790 app: &mut App,
791 delegate: AnyTextSelectionDelegate,
792 clipboard_status: Option<Handle<ClipboardStatusNotifier>>,
793 ) {
794 let _ = (app, delegate, clipboard_status);
795 }
796
797 #[deprecated(note = "Use `contextMenuBuilder` instead. \
798 This feature was deprecated after v3.3.0-0.5.pre.")]
799 fn handle_copy(
800 &self,
801 app: &mut App,
802 delegate: AnyTextSelectionDelegate,
803 clipboard_status: Option<Handle<ClipboardStatusNotifier>>,
804 ) {
805 let _ = (app, delegate, clipboard_status);
806 }
807
808 #[deprecated(note = "Use `contextMenuBuilder` instead. \
809 This feature was deprecated after v3.3.0-0.5.pre.")]
810 fn handle_paste(&self, app: &mut App, delegate: AnyTextSelectionDelegate) -> Task<()> {
811 let _ = (app, delegate);
812 Task::ready(())
813 }
814
815 #[deprecated(note = "Use `contextMenuBuilder` instead. \
816 This feature was deprecated after v3.3.0-0.5.pre.")]
817 fn handle_select_all(&self, app: &mut App, delegate: AnyTextSelectionDelegate) {
818 let _ = (app, delegate);
819 }
820}
821
822pub struct TextSelectionOverlay {
826 pub context: BuildContext,
828 pub render_object: RenderHandle<RenderEditable>,
830 pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
832 pub selection_delegate: AnyTextSelectionDelegate,
834 selection_overlay: Ref<SelectionOverlay>,
835 pub context_menu_builder: Option<WidgetBuilder>,
837 value: TextEditingValue,
838 effective_start_handle_visibility: Ref<ValueNotifier<bool>>,
839 effective_end_handle_visibility: Ref<ValueNotifier<bool>>,
840 effective_toolbar_visibility: Ref<ValueNotifier<bool>>,
841 handles_visible: bool,
842 debug_required_for: Option<WidgetRef>,
843 drag_start_behavior: DragStartBehavior,
844 on_selection_handle_tapped: Option<Listener>,
845 clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
846 end_handle_drag_position: f64,
847 end_handle_drag_target: f64,
848 start_handle_drag_position: f64,
849 start_handle_drag_target: f64,
850 drag_start_selection: Option<TextSelection>,
851}
852
853impl TextSelectionOverlay {
854 #[allow(clippy::too_many_arguments)]
858 pub fn new(
859 app: &mut App,
860 value: TextEditingValue,
861 context: BuildContext,
862 toolbar_layer_link: Ref<LayerLink>,
863 start_handle_layer_link: Ref<LayerLink>,
864 end_handle_layer_link: Ref<LayerLink>,
865 render_object: RenderHandle<RenderEditable>,
866 selection_delegate: AnyTextSelectionDelegate,
867 magnifier_configuration: TextMagnifierConfiguration,
868 ) -> Ref<Self> {
869 let effective_start = app.create(ValueNotifier::new(false));
870 let effective_end = app.create(ValueNotifier::new(false));
871 let effective_toolbar = app.create(ValueNotifier::new(false));
872 let selection_overlay = SelectionOverlay::new(
873 app,
874 context,
875 TextSelectionHandleType::Collapsed,
876 0.0,
877 TextSelectionHandleType::Collapsed,
878 0.0,
879 Vec::new(),
880 None,
881 Some(selection_delegate),
882 None,
883 start_handle_layer_link,
884 end_handle_layer_link,
885 toolbar_layer_link,
886 )
887 .start_handles_visible(app, effective_start.clone())
888 .end_handles_visible(app, effective_end.clone())
889 .toolbar_visible(app, effective_toolbar.clone())
890 .magnifier_configuration(app, magnifier_configuration);
891 selection_overlay
892 .set_toolbar_location(app, render_object.last_secondary_tap_down_position(app));
893
894 let this = app.create(TextSelectionOverlay {
895 context,
896 render_object,
897 selection_controls: None,
898 selection_delegate,
899 selection_overlay,
900 context_menu_builder: None,
901 value,
902 effective_start_handle_visibility: effective_start,
903 effective_end_handle_visibility: effective_end,
904 effective_toolbar_visibility: effective_toolbar,
905 handles_visible: false,
906 debug_required_for: None,
907 drag_start_behavior: DragStartBehavior::Start,
908 on_selection_handle_tapped: None,
909 clipboard_status: None,
910 end_handle_drag_position: 0.0,
911 end_handle_drag_target: 0.0,
912 start_handle_drag_position: 0.0,
913 start_handle_drag_target: 0.0,
914 drag_start_selection: None,
915 });
916 let selection_overlay = this.selection_overlay(app);
917 let overlay = this.clone();
918 let this = this.handle();
919
920 selection_overlay.set_on_start_handle_drag_start(
921 app,
922 Rc::new(move |app, details| {
923 this.handle_selection_start_handle_drag_start(app, details);
924 }),
925 );
926 selection_overlay.set_on_start_handle_drag_update(
927 app,
928 Rc::new(move |app, details| {
929 this.handle_selection_start_handle_drag_update(app, details);
930 }),
931 );
932 selection_overlay.set_on_start_handle_drag_end(
933 app,
934 Rc::new(move |app, details| {
935 this.handle_any_drag_end(app, details);
936 }),
937 );
938 selection_overlay.set_on_end_handle_drag_start(
939 app,
940 Rc::new(move |app, details| {
941 this.handle_selection_end_handle_drag_start(app, details);
942 }),
943 );
944 selection_overlay.set_on_end_handle_drag_update(
945 app,
946 Rc::new(move |app, details| {
947 this.handle_selection_end_handle_drag_update(app, details);
948 }),
949 );
950 selection_overlay.set_on_end_handle_drag_end(
951 app,
952 Rc::new(move |app, details| {
953 this.handle_any_drag_end(app, details);
954 }),
955 );
956
957 let start_in_viewport = render_object.selection_start_in_viewport(app);
958 let end_in_viewport = render_object.selection_end_in_viewport(app);
959 start_in_viewport.add_listener(
960 app,
961 Listener::handle_method(this, Self::update_text_selection_overlay_visibilities),
962 );
963 end_in_viewport.add_listener(
964 app,
965 Listener::handle_method(this, Self::update_text_selection_overlay_visibilities),
966 );
967 this.update_text_selection_overlay_visibilities(app);
968 overlay
969 }
970
971 fn selection_overlay(self: Handle<Self>, app: &App) -> Handle<SelectionOverlay> {
972 app.get(self).selection_overlay.handle()
973 }
974
975 pub fn debug_required_for(self: Ref<Self>, app: &mut App, widget: WidgetRef) -> Ref<Self> {
977 app.get_mut(&self).debug_required_for = Some(widget.clone());
978 let inner = self.selection_overlay(app);
979 app.get_mut(inner).debug_required_for = Some(widget);
980 self
981 }
982
983 pub fn selection_controls(
985 self: Ref<Self>,
986 app: &mut App,
987 controls: Rc<dyn TextSelectionControls>,
988 ) -> Ref<Self> {
989 app.get_mut(&self).selection_controls = Some(Rc::clone(&controls));
990 let inner = self.selection_overlay(app);
991 app.get_mut(inner).selection_controls = Some(controls);
992 self
993 }
994
995 pub fn handles_visible(self: Ref<Self>, app: &mut App, visible: bool) -> Ref<Self> {
997 self.set_handles_visible(app, visible);
998 self
999 }
1000
1001 pub fn drag_start_behavior(
1003 self: Ref<Self>,
1004 app: &mut App,
1005 drag_start_behavior: DragStartBehavior,
1006 ) -> Ref<Self> {
1007 app.get_mut(&self).drag_start_behavior = drag_start_behavior;
1008 let inner = self.selection_overlay(app);
1009 app.get_mut(inner).drag_start_behavior = drag_start_behavior;
1010 self
1011 }
1012
1013 pub fn on_selection_handle_tapped(
1015 self: Ref<Self>,
1016 app: &mut App,
1017 on_selection_handle_tapped: Listener,
1018 ) -> Ref<Self> {
1019 app.get_mut(&self).on_selection_handle_tapped = Some(on_selection_handle_tapped.clone());
1020 let inner = self.selection_overlay(app);
1021 app.get_mut(inner).on_selection_handle_tapped = Some(on_selection_handle_tapped);
1022 self
1023 }
1024
1025 pub fn clipboard_status(
1027 self: Ref<Self>,
1028 app: &mut App,
1029 clipboard_status: Ref<ClipboardStatusNotifier>,
1030 ) -> Ref<Self> {
1031 app.get_mut(&self).clipboard_status = Some(clipboard_status.clone());
1032 let inner = self.selection_overlay(app);
1033 app.get_mut(inner).clipboard_status = Some(clipboard_status);
1034 self
1035 }
1036
1037 pub fn context_menu_builder(
1039 self: Ref<Self>,
1040 app: &mut App,
1041 context_menu_builder: WidgetBuilder,
1042 ) -> Ref<Self> {
1043 app.get_mut(&self).context_menu_builder = Some(context_menu_builder);
1044 self
1045 }
1046
1047 pub fn value(self: Handle<Self>, app: &App) -> TextEditingValue {
1049 app.get(self).value.clone()
1050 }
1051
1052 fn selection(self: Handle<Self>, app: &App) -> TextSelection {
1053 app.get(self).value.selection
1054 }
1055
1056 fn update_text_selection_overlay_visibilities(self: Handle<Self>, app: &mut App) {
1057 let handles_visible = app.get(self).handles_visible;
1058 let render_object = app.get(self).render_object;
1059 let start_in_view = *render_object.selection_start_in_viewport(app).value(app);
1060 let end_in_view = *render_object.selection_end_in_viewport(app).value(app);
1061 let start = app.get(self).effective_start_handle_visibility.handle();
1062 let end = app.get(self).effective_end_handle_visibility.handle();
1063 let toolbar = app.get(self).effective_toolbar_visibility.handle();
1064 start.set_value(app, handles_visible && start_in_view);
1065 end.set_value(app, handles_visible && end_in_view);
1066 toolbar.set_value(app, start_in_view || end_in_view);
1067 }
1068
1069 pub fn handles_visible_value(self: Handle<Self>, app: &App) -> bool {
1071 app.get(self).handles_visible
1072 }
1073
1074 pub fn set_handles_visible(self: Handle<Self>, app: &mut App, visible: bool) {
1076 if app.get(self).handles_visible == visible {
1077 return;
1078 }
1079 app.get_mut(self).handles_visible = visible;
1080 self.update_text_selection_overlay_visibilities(app);
1081 }
1082
1083 pub fn show_handles(self: Handle<Self>, app: &mut App) {
1085 self.update_selection_overlay(app);
1086 let overlay = self.selection_overlay(app);
1087 overlay.show_handles(app);
1088 }
1089
1090 pub fn hide_handles(self: Handle<Self>, app: &mut App) {
1092 let overlay = self.selection_overlay(app);
1093 overlay.hide_handles(app);
1094 }
1095
1096 pub fn show_toolbar(self: Handle<Self>, app: &mut App) {
1100 debug_assert!(
1101 SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
1102 "showToolbar must not be called during the build or layout phase.",
1103 );
1104 self.update_selection_overlay(app);
1105 let overlay = self.selection_overlay(app);
1106 let context = app.get(self).context;
1107 if app
1108 .get(self)
1109 .selection_controls
1110 .as_ref()
1111 .is_some_and(|controls| controls.as_text_selection_handle_controls().is_none())
1112 {
1113 overlay.show_toolbar(app, None, None);
1114 return;
1115 }
1116
1117 let Some(builder) = app.get(self).context_menu_builder.clone() else {
1118 return;
1119 };
1120
1121 debug_assert!(context.mounted(app));
1122 overlay.show_toolbar(app, Some(context), Some(builder));
1123 }
1124
1125 pub fn show_spell_check_suggestions_toolbar(
1128 self: Handle<Self>,
1129 app: &mut App,
1130 spell_check_suggestions_toolbar_builder: WidgetBuilder,
1131 ) {
1132 self.update_selection_overlay(app);
1133 let context = app.get(self).context;
1134 debug_assert!(context.mounted(app));
1135 let overlay = self.selection_overlay(app);
1136 overlay.show_spell_check_suggestions_toolbar(
1137 app,
1138 Some(context),
1139 spell_check_suggestions_toolbar_builder,
1140 );
1141 self.hide_handles(app);
1142 }
1143
1144 pub fn show_magnifier(self: Handle<Self>, app: &mut App, position_to_show: Offset) {
1146 let render_object = app.get(self).render_object;
1147 let position = render_object.get_position_for_point(app, position_to_show);
1148 self.update_selection_overlay(app);
1149 let info = self.build_magnifier(app, render_object, position_to_show, position);
1150 let overlay = self.selection_overlay(app);
1151 overlay.show_magnifier(app, info);
1152 }
1153
1154 pub fn update_magnifier(self: Handle<Self>, app: &mut App, position_to_show: Offset) {
1156 let render_object = app.get(self).render_object;
1157 let position = render_object.get_position_for_point(app, position_to_show);
1158 self.update_selection_overlay(app);
1159 let info = self.build_magnifier(app, render_object, position_to_show, position);
1160 let overlay = self.selection_overlay(app);
1161 overlay.update_magnifier(app, info);
1162 }
1163
1164 pub fn hide_magnifier(self: Handle<Self>, app: &mut App) {
1166 let overlay = self.selection_overlay(app);
1167 overlay.hide_magnifier(app);
1168 }
1169
1170 pub fn update(self: Handle<Self>, app: &mut App, new_value: TextEditingValue) {
1172 if app.get(self).value == new_value {
1173 return;
1174 }
1175 app.get_mut(self).value = new_value;
1176 self.update_selection_overlay(app);
1177 let overlay = self.selection_overlay(app);
1178 overlay.mark_needs_build(app);
1179 }
1180
1181 fn update_selection_overlay(self: Handle<Self>, app: &mut App) {
1182 let render_object = app.get(self).render_object;
1183 let selection = self.selection(app);
1184 let endpoints = render_object.get_endpoints_for_selection(app, selection);
1185 debug_assert!(!endpoints.is_empty());
1186
1187 let (start_handle_type, end_handle_type) = if selection.is_collapsed() {
1188 (
1189 TextSelectionHandleType::Collapsed,
1190 TextSelectionHandleType::Collapsed,
1191 )
1192 } else {
1193 let text_direction = render_object.text_direction(app);
1194 let prefer_field_direction = app.platform().target_platform() == TargetPlatform::IOS;
1195 let (start_handle_direction, end_handle_direction) =
1196 if prefer_field_direction || endpoints.len() < 2 {
1197 (text_direction, text_direction)
1198 } else {
1199 (
1200 endpoints[0].direction.unwrap_or(text_direction),
1201 endpoints[endpoints.len() - 1]
1202 .direction
1203 .unwrap_or(text_direction),
1204 )
1205 };
1206 (
1207 match start_handle_direction {
1208 TextDirection::Ltr => TextSelectionHandleType::Left,
1209 TextDirection::Rtl => TextSelectionHandleType::Right,
1210 },
1211 match end_handle_direction {
1212 TextDirection::Ltr => TextSelectionHandleType::Right,
1213 TextDirection::Rtl => TextSelectionHandleType::Left,
1214 },
1215 )
1216 };
1217
1218 let line_height_at_start = self.start_glyph_height(app);
1219 let line_height_at_end = self.end_glyph_height(app);
1220 let overlay = self.selection_overlay(app);
1221 overlay.set_start_handle_type(app, start_handle_type);
1222 overlay.set_line_height_at_start(app, line_height_at_start);
1223 overlay.set_end_handle_type(app, end_handle_type);
1224 overlay.set_line_height_at_end(app, line_height_at_end);
1225 overlay.set_selection_endpoints(app, endpoints);
1226 overlay.set_toolbar_location(app, render_object.last_secondary_tap_down_position(app));
1227 }
1228
1229 pub fn update_for_scroll(self: Handle<Self>, app: &mut App) {
1231 self.update_selection_overlay(app);
1232 let overlay = self.selection_overlay(app);
1233 overlay.mark_needs_build(app);
1234 }
1235
1236 pub fn handles_are_visible(self: Handle<Self>, app: &App) -> bool {
1238 let overlay = self.selection_overlay(app);
1239 overlay.has_handles(app) && app.get(self).handles_visible
1240 }
1241
1242 pub fn toolbar_is_visible(self: Handle<Self>, app: &App) -> bool {
1244 let overlay = self.selection_overlay(app);
1245 overlay.toolbar_is_visible(app)
1246 }
1247
1248 pub fn magnifier_is_visible(self: Handle<Self>, app: &App) -> bool {
1250 let overlay = self.selection_overlay(app);
1251 overlay.magnifier_is_visible(app)
1252 }
1253
1254 pub fn magnifier_exists(self: Handle<Self>, app: &App) -> bool {
1256 let overlay = self.selection_overlay(app);
1257 overlay.magnifier_exists(app)
1258 }
1259
1260 pub fn spell_check_toolbar_is_visible(self: Handle<Self>, app: &App) -> bool {
1262 let overlay = self.selection_overlay(app);
1263 overlay.spell_check_toolbar_is_shown(app)
1264 }
1265
1266 pub fn hide(self: Handle<Self>, app: &mut App) {
1268 let overlay = self.selection_overlay(app);
1269 overlay.hide(app);
1270 }
1271
1272 pub fn hide_toolbar(self: Handle<Self>, app: &mut App) {
1274 let overlay = self.selection_overlay(app);
1275 overlay.hide_toolbar(app);
1276 }
1277
1278 pub fn dispose(self: Handle<Self>, app: &mut App) {
1280 let overlay = self.selection_overlay(app);
1281 overlay.dispose(app);
1282 let render_object = app.get(self).render_object;
1283 if app.contains(render_object.handle()) {
1286 let start_in_viewport = render_object.selection_start_in_viewport(app);
1287 let end_in_viewport = render_object.selection_end_in_viewport(app);
1288 start_in_viewport.remove_listener(
1289 app,
1290 &Listener::handle_method(self, Self::update_text_selection_overlay_visibilities),
1291 );
1292 end_in_viewport.remove_listener(
1293 app,
1294 &Listener::handle_method(self, Self::update_text_selection_overlay_visibilities),
1295 );
1296 }
1297 let toolbar = app.get(self).effective_toolbar_visibility.handle();
1298 let start = app.get(self).effective_start_handle_visibility.handle();
1299 let end = app.get(self).effective_end_handle_visibility.handle();
1300 toolbar.dispose(app);
1301 start.dispose(app);
1302 end.dispose(app);
1303 self.hide_toolbar(app);
1304 }
1305
1306 fn start_glyph_height(self: Handle<Self>, app: &mut App) -> f64 {
1307 let delegate = app.get(self).selection_delegate;
1308 let curr_text = delegate.text_editing_value(app).text;
1309 let render_object = app.get(self).render_object;
1310 let selection = self.selection(app);
1311 let mut start_handle_rect = None;
1312 if render_object.plain_text(app) == curr_text
1313 && selection.is_valid()
1314 && !selection.is_collapsed()
1315 {
1316 let selected = selection.range().text_inside(&curr_text);
1317 if let Some(first) = selected.chars().next() {
1318 let extent = first.len_utf16() as i32;
1319 start_handle_rect = render_object.get_rect_for_composing_range(
1320 app,
1321 TextRange::new(selection.start(), selection.start() + extent),
1322 );
1323 }
1324 }
1325 start_handle_rect
1326 .map(|rect| rect.height())
1327 .unwrap_or_else(|| render_object.preferred_line_height(app))
1328 }
1329
1330 fn end_glyph_height(self: Handle<Self>, app: &mut App) -> f64 {
1331 let delegate = app.get(self).selection_delegate;
1332 let curr_text = delegate.text_editing_value(app).text;
1333 let render_object = app.get(self).render_object;
1334 let selection = self.selection(app);
1335 let mut end_handle_rect = None;
1336 if render_object.plain_text(app) == curr_text
1337 && selection.is_valid()
1338 && !selection.is_collapsed()
1339 {
1340 let selected = selection.range().text_inside(&curr_text);
1341 if let Some(last) = selected.chars().next_back() {
1342 let extent = last.len_utf16() as i32;
1343 end_handle_rect = render_object.get_rect_for_composing_range(
1344 app,
1345 TextRange::new(selection.end() - extent, selection.end()),
1346 );
1347 }
1348 }
1349 end_handle_rect
1350 .map(|rect| rect.height())
1351 .unwrap_or_else(|| render_object.preferred_line_height(app))
1352 }
1353
1354 fn build_magnifier(
1355 self: Handle<Self>,
1356 app: &mut App,
1357 render_editable: RenderHandle<RenderEditable>,
1358 global_gesture_position: Offset,
1359 current_text_position: TextPosition,
1360 ) -> MagnifierInfo {
1361 let line_at_offset = render_editable.get_line_at_offset(app, current_text_position);
1362 let position_at_end_of_line =
1363 TextPosition::with_affinity(line_at_offset.extent_offset, TextAffinity::Upstream);
1364 let position_at_beginning_of_line = TextPosition::new(line_at_offset.base_offset);
1365 let local_line_boundaries = Rect::from_points(
1366 render_editable
1367 .get_local_rect_for_caret(app, position_at_beginning_of_line)
1368 .top_center(),
1369 render_editable
1370 .get_local_rect_for_caret(app, position_at_end_of_line)
1371 .bottom_center(),
1372 );
1373 let context = app.get(self).context;
1374 let overlay_state = Overlay::of(app, context, true);
1375 let overlay = overlay_state
1376 .context(app)
1377 .find_render_object(app)
1378 .and_then(|object| object.as_box());
1379 let transform_to_overlay = render_editable
1380 .as_object()
1381 .get_transform_to(app, overlay.map(|box_| box_.as_object()));
1382 let overlay_line_boundaries = transform_rect(&transform_to_overlay, local_line_boundaries);
1383 let local_caret_rect = render_editable.get_local_rect_for_caret(app, current_text_position);
1384 let overlay_caret_rect = transform_rect(&transform_to_overlay, local_caret_rect);
1385 let overlay_gesture_position = overlay
1386 .map(|box_| box_.global_to_local(app, global_gesture_position, None))
1387 .unwrap_or(global_gesture_position);
1388 MagnifierInfo::new(
1389 overlay_gesture_position,
1390 overlay_caret_rect,
1391 transform_rect(
1392 &transform_to_overlay,
1393 render_editable.as_object().paint_bounds(app),
1394 ),
1395 overlay_line_boundaries,
1396 )
1397 }
1398
1399 fn handle_selection_end_handle_drag_start(
1400 self: Handle<Self>,
1401 app: &mut App,
1402 details: DragStartDetails,
1403 ) {
1404 let render_object = app.get(self).render_object;
1405 if !render_object.attached(app) {
1406 return;
1407 }
1408 app.get_mut(self).end_handle_drag_position = details.global_position.dy();
1409 let overlay = self.selection_overlay(app);
1410 let endpoints = overlay.selection_endpoints(app);
1411 let Some(last) = endpoints.last() else {
1412 return;
1413 };
1414 let center_of_line_local = last.point.dy() - render_object.preferred_line_height(app) / 2.0;
1415 let center_of_line_global = render_object
1416 .as_box()
1417 .local_to_global(app, Offset::new(0.0, center_of_line_local), None)
1418 .dy();
1419 app.get_mut(self).end_handle_drag_target =
1420 center_of_line_global - details.global_position.dy();
1421 let position = render_object.get_position_for_point(
1422 app,
1423 Offset::new(details.global_position.dx(), center_of_line_global),
1424 );
1425 if matches!(
1426 app.platform().target_platform(),
1427 TargetPlatform::IOS | TargetPlatform::MacOS
1428 ) && app.get(self).drag_start_selection.is_none()
1429 {
1430 app.get_mut(self).drag_start_selection = Some(self.selection(app));
1431 }
1432 let info = self.build_magnifier(app, render_object, details.global_position, position);
1433 overlay.show_magnifier(app, info);
1434 }
1435
1436 fn handle_dy(self: Handle<Self>, app: &mut App, drag_dy: f64, handle_dy: f64) -> Option<f64> {
1437 let preferred_line_height = app.get(self).render_object.preferred_line_height(app);
1438 debug_assert!(
1439 preferred_line_height.is_finite(),
1440 "Preferred line height is expected to always be finite."
1441 );
1442 if preferred_line_height <= 0.0 || !drag_dy.is_finite() || !handle_dy.is_finite() {
1443 return None;
1444 }
1445 let distance_dragged = drag_dy - handle_dy;
1446 let drag_direction = if distance_dragged < 0.0 { -1.0 } else { 1.0 };
1447 let lines_dragged =
1448 drag_direction * (distance_dragged.abs() / preferred_line_height).floor();
1449 Some(handle_dy + lines_dragged * preferred_line_height)
1450 }
1451
1452 fn handle_selection_end_handle_drag_update(
1453 self: Handle<Self>,
1454 app: &mut App,
1455 details: DragUpdateDetails,
1456 ) {
1457 let render_object = app.get(self).render_object;
1458 if !render_object.attached(app) {
1459 return;
1460 }
1461 let local_position =
1462 render_object
1463 .as_box()
1464 .global_to_local(app, details.global_position, None);
1465 let current = app.get(self).end_handle_drag_position;
1466 let Some(next_end_handle_drag_position_local) = self.handle_dy(
1467 app,
1468 local_position.dy(),
1469 render_object
1470 .as_box()
1471 .global_to_local(app, Offset::new(0.0, current), None)
1472 .dy(),
1473 ) else {
1474 return;
1475 };
1476 app.get_mut(self).end_handle_drag_position = render_object
1477 .as_box()
1478 .local_to_global(
1479 app,
1480 Offset::new(0.0, next_end_handle_drag_position_local),
1481 None,
1482 )
1483 .dy();
1484 let handle_target_global = Offset::new(
1485 details.global_position.dx(),
1486 app.get(self).end_handle_drag_position + app.get(self).end_handle_drag_target,
1487 );
1488 let position = render_object.get_position_for_point(app, handle_target_global);
1489 let overlay = self.selection_overlay(app);
1490 match app.platform().target_platform() {
1491 TargetPlatform::IOS | TargetPlatform::MacOS => {
1492 let drag_start = app
1493 .get(self)
1494 .drag_start_selection
1495 .expect("drag start selection is set on Apple platforms");
1496 if drag_start.is_collapsed() {
1497 let info =
1498 self.build_magnifier(app, render_object, details.global_position, position);
1499 overlay.update_magnifier(app, info);
1500 self.handle_selection_handle_changed(
1501 app,
1502 TextSelection::from_position(position),
1503 );
1504 return;
1505 }
1506 let normalized = drag_start.extent_offset >= drag_start.base_offset;
1507 let new_selection = TextSelection::new(
1508 if normalized {
1509 drag_start.base_offset
1510 } else {
1511 drag_start.extent_offset
1512 },
1513 position.offset,
1514 );
1515 self.handle_selection_handle_changed(app, new_selection);
1516 let info = self.build_magnifier(
1517 app,
1518 render_object,
1519 details.global_position,
1520 new_selection.extent(),
1521 );
1522 overlay.update_magnifier(app, info);
1523 }
1524 TargetPlatform::Android
1525 | TargetPlatform::Fuchsia
1526 | TargetPlatform::Linux
1527 | TargetPlatform::Windows => {
1528 if self.selection(app).is_collapsed() {
1529 let info =
1530 self.build_magnifier(app, render_object, details.global_position, position);
1531 overlay.update_magnifier(app, info);
1532 self.handle_selection_handle_changed(
1533 app,
1534 TextSelection::from_position(position),
1535 );
1536 return;
1537 }
1538 let selection = self.selection(app);
1539 let new_selection = TextSelection::new(selection.base_offset, position.offset);
1540 if new_selection.base_offset >= new_selection.extent_offset {
1541 return;
1542 }
1543 self.handle_selection_handle_changed(app, new_selection);
1544 let info = self.build_magnifier(
1545 app,
1546 render_object,
1547 details.global_position,
1548 new_selection.extent(),
1549 );
1550 overlay.update_magnifier(app, info);
1551 }
1552 }
1553 }
1554
1555 fn handle_selection_start_handle_drag_start(
1556 self: Handle<Self>,
1557 app: &mut App,
1558 details: DragStartDetails,
1559 ) {
1560 let render_object = app.get(self).render_object;
1561 if !render_object.attached(app) {
1562 return;
1563 }
1564 app.get_mut(self).start_handle_drag_position = details.global_position.dy();
1565 let overlay = self.selection_overlay(app);
1566 let endpoints = overlay.selection_endpoints(app);
1567 let Some(first) = endpoints.first() else {
1568 return;
1569 };
1570 let center_of_line_local =
1571 first.point.dy() - render_object.preferred_line_height(app) / 2.0;
1572 let center_of_line_global = render_object
1573 .as_box()
1574 .local_to_global(app, Offset::new(0.0, center_of_line_local), None)
1575 .dy();
1576 app.get_mut(self).start_handle_drag_target =
1577 center_of_line_global - details.global_position.dy();
1578 let position = render_object.get_position_for_point(
1579 app,
1580 Offset::new(details.global_position.dx(), center_of_line_global),
1581 );
1582 if matches!(
1583 app.platform().target_platform(),
1584 TargetPlatform::IOS | TargetPlatform::MacOS
1585 ) && app.get(self).drag_start_selection.is_none()
1586 {
1587 app.get_mut(self).drag_start_selection = Some(self.selection(app));
1588 }
1589 let info = self.build_magnifier(app, render_object, details.global_position, position);
1590 overlay.show_magnifier(app, info);
1591 }
1592
1593 fn handle_selection_start_handle_drag_update(
1594 self: Handle<Self>,
1595 app: &mut App,
1596 details: DragUpdateDetails,
1597 ) {
1598 let render_object = app.get(self).render_object;
1599 if !render_object.attached(app) {
1600 return;
1601 }
1602 let local_position =
1603 render_object
1604 .as_box()
1605 .global_to_local(app, details.global_position, None);
1606 let current = app.get(self).start_handle_drag_position;
1607 let Some(next_start_handle_drag_position_local) = self.handle_dy(
1608 app,
1609 local_position.dy(),
1610 render_object
1611 .as_box()
1612 .global_to_local(app, Offset::new(0.0, current), None)
1613 .dy(),
1614 ) else {
1615 return;
1616 };
1617 app.get_mut(self).start_handle_drag_position = render_object
1618 .as_box()
1619 .local_to_global(
1620 app,
1621 Offset::new(0.0, next_start_handle_drag_position_local),
1622 None,
1623 )
1624 .dy();
1625 let handle_target_global = Offset::new(
1626 details.global_position.dx(),
1627 app.get(self).start_handle_drag_position + app.get(self).start_handle_drag_target,
1628 );
1629 let position = render_object.get_position_for_point(app, handle_target_global);
1630 let overlay = self.selection_overlay(app);
1631 match app.platform().target_platform() {
1632 TargetPlatform::IOS | TargetPlatform::MacOS => {
1633 let drag_start = app
1634 .get(self)
1635 .drag_start_selection
1636 .expect("drag start selection is set on Apple platforms");
1637 if drag_start.is_collapsed() {
1638 let info =
1639 self.build_magnifier(app, render_object, details.global_position, position);
1640 overlay.update_magnifier(app, info);
1641 self.handle_selection_handle_changed(
1642 app,
1643 TextSelection::from_position(position),
1644 );
1645 return;
1646 }
1647 let normalized = drag_start.extent_offset >= drag_start.base_offset;
1648 let new_selection = TextSelection::new(
1649 if normalized {
1650 drag_start.extent_offset
1651 } else {
1652 drag_start.base_offset
1653 },
1654 position.offset,
1655 );
1656 let magnifier_position =
1657 if new_selection.extent().offset < new_selection.base().offset {
1658 new_selection.extent()
1659 } else {
1660 new_selection.base()
1661 };
1662 let info = self.build_magnifier(
1663 app,
1664 render_object,
1665 details.global_position,
1666 magnifier_position,
1667 );
1668 overlay.update_magnifier(app, info);
1669 self.handle_selection_handle_changed(app, new_selection);
1670 }
1671 TargetPlatform::Android
1672 | TargetPlatform::Fuchsia
1673 | TargetPlatform::Linux
1674 | TargetPlatform::Windows => {
1675 if self.selection(app).is_collapsed() {
1676 let info =
1677 self.build_magnifier(app, render_object, details.global_position, position);
1678 overlay.update_magnifier(app, info);
1679 self.handle_selection_handle_changed(
1680 app,
1681 TextSelection::from_position(position),
1682 );
1683 return;
1684 }
1685 let selection = self.selection(app);
1686 let new_selection = TextSelection::new(position.offset, selection.extent_offset);
1687 if new_selection.base_offset >= new_selection.extent_offset {
1688 return;
1689 }
1690 let magnifier_position =
1691 if new_selection.extent().offset < new_selection.base().offset {
1692 new_selection.extent()
1693 } else {
1694 new_selection.base()
1695 };
1696 let info = self.build_magnifier(
1697 app,
1698 render_object,
1699 details.global_position,
1700 magnifier_position,
1701 );
1702 overlay.update_magnifier(app, info);
1703 self.handle_selection_handle_changed(app, new_selection);
1704 }
1705 }
1706 }
1707
1708 fn handle_any_drag_end(self: Handle<Self>, app: &mut App, _details: DragEndDetails) {
1709 let context = app.get(self).context;
1710 if !context.mounted(app) {
1711 return;
1712 }
1713 app.get_mut(self).drag_start_selection = None;
1714 let overlay = self.selection_overlay(app);
1715 let dragging_handles =
1716 overlay.is_dragging_start_handle(app) || overlay.is_dragging_end_handle(app);
1717 if !self.has_handle_controls(app) {
1718 if !dragging_handles {
1719 overlay.hide_magnifier(app);
1720 if !self.selection(app).is_collapsed() {
1721 overlay.show_toolbar(app, None, None);
1722 }
1723 }
1724 return;
1725 }
1726 if !dragging_handles {
1727 overlay.hide_magnifier(app);
1728 if !self.selection(app).is_collapsed() {
1729 let builder = app.get(self).context_menu_builder.clone();
1730 overlay.show_toolbar(app, Some(context), builder);
1731 }
1732 }
1733 }
1734
1735 fn has_handle_controls(self: Handle<Self>, app: &App) -> bool {
1737 app.get(self)
1738 .selection_controls
1739 .as_ref()
1740 .is_some_and(|controls| controls.as_text_selection_handle_controls().is_some())
1741 }
1742
1743 fn handle_selection_handle_changed(
1744 self: Handle<Self>,
1745 app: &mut App,
1746 new_selection: TextSelection,
1747 ) {
1748 let delegate = app.get(self).selection_delegate;
1749 let value = app.get(self).value.copy_with().selection(new_selection);
1750 delegate.user_update_text_editing_value(app, value, SelectionChangedCause::Drag);
1751 }
1752}
1753
1754struct SelectionHandles {
1756 start: Ref<OverlayEntry>,
1757 end: Ref<OverlayEntry>,
1758}
1759
1760pub struct SelectionOverlay {
1765 pub context: BuildContext,
1767 pub debug_required_for: Option<WidgetRef>,
1769 start_handle_type: TextSelectionHandleType,
1770 line_height_at_start: f64,
1771 pub start_handles_visible: Option<Ref<ValueNotifier<bool>>>,
1773 pub on_start_handle_drag_start: Option<ValueChanged<DragStartDetails>>,
1775 pub on_start_handle_drag_update: Option<ValueChanged<DragUpdateDetails>>,
1777 pub on_start_handle_drag_end: Option<ValueChanged<DragEndDetails>>,
1779 end_handle_type: TextSelectionHandleType,
1780 line_height_at_end: f64,
1781 pub end_handles_visible: Option<Ref<ValueNotifier<bool>>>,
1783 pub on_end_handle_drag_start: Option<ValueChanged<DragStartDetails>>,
1785 pub on_end_handle_drag_update: Option<ValueChanged<DragUpdateDetails>>,
1787 pub on_end_handle_drag_end: Option<ValueChanged<DragEndDetails>>,
1789 pub toolbar_visible: Option<Ref<ValueNotifier<bool>>>,
1791 selection_endpoints: Vec<TextSelectionPoint>,
1792 pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
1794 pub selection_delegate: Option<AnyTextSelectionDelegate>,
1796 pub clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
1798 pub start_handle_layer_link: Ref<LayerLink>,
1800 pub end_handle_layer_link: Ref<LayerLink>,
1802 pub toolbar_layer_link: Ref<LayerLink>,
1804 pub drag_start_behavior: DragStartBehavior,
1806 pub on_selection_handle_tapped: Option<Listener>,
1808 toolbar_location: Option<Offset>,
1809 pub magnifier_configuration: TextMagnifierConfiguration,
1811 magnifier_info: Ref<ValueNotifier<MagnifierInfo>>,
1812 magnifier_controller: Ref<MagnifierController>,
1813 start_handle_drag_in_progress: bool,
1814 is_dragging_start_handle: bool,
1815 end_handle_drag_in_progress: bool,
1816 is_dragging_end_handle: bool,
1817 handles: Option<SelectionHandles>,
1818 toolbar: Option<Ref<OverlayEntry>>,
1819 context_menu: Option<Ref<OverlayEntry>>,
1820 context_menu_builder: Option<WidgetBuilder>,
1821 spell_check_toolbar: Option<Ref<OverlayEntry>>,
1822 spell_check_toolbar_builder: Option<WidgetBuilder>,
1823 build_scheduled: bool,
1824}
1825
1826impl SelectionOverlay {
1827 pub const FADE_DURATION: Duration = Duration::from_millis(150);
1829
1830 #[allow(clippy::too_many_arguments)]
1834 pub fn new(
1835 app: &mut App,
1836 context: BuildContext,
1837 start_handle_type: TextSelectionHandleType,
1838 line_height_at_start: f64,
1839 end_handle_type: TextSelectionHandleType,
1840 line_height_at_end: f64,
1841 selection_endpoints: Vec<TextSelectionPoint>,
1842 selection_controls: Option<Rc<dyn TextSelectionControls>>,
1843 selection_delegate: Option<AnyTextSelectionDelegate>,
1844 clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
1845 start_handle_layer_link: Ref<LayerLink>,
1846 end_handle_layer_link: Ref<LayerLink>,
1847 toolbar_layer_link: Ref<LayerLink>,
1848 ) -> Ref<Self> {
1849 let magnifier_info = app.create(ValueNotifier::new(MagnifierInfo::EMPTY));
1850 let magnifier_controller = MagnifierController::new(app);
1851 app.create(SelectionOverlay {
1852 context,
1853 debug_required_for: None,
1854 start_handle_type,
1855 line_height_at_start,
1856 start_handles_visible: None,
1857 on_start_handle_drag_start: None,
1858 on_start_handle_drag_update: None,
1859 on_start_handle_drag_end: None,
1860 end_handle_type,
1861 line_height_at_end,
1862 end_handles_visible: None,
1863 on_end_handle_drag_start: None,
1864 on_end_handle_drag_update: None,
1865 on_end_handle_drag_end: None,
1866 toolbar_visible: None,
1867 selection_endpoints,
1868 selection_controls,
1869 selection_delegate,
1870 clipboard_status,
1871 start_handle_layer_link,
1872 end_handle_layer_link,
1873 toolbar_layer_link,
1874 drag_start_behavior: DragStartBehavior::Start,
1875 on_selection_handle_tapped: None,
1876 toolbar_location: None,
1877 magnifier_configuration: TextMagnifierConfiguration::DISABLED,
1878 magnifier_info,
1879 magnifier_controller,
1880 start_handle_drag_in_progress: false,
1881 is_dragging_start_handle: false,
1882 end_handle_drag_in_progress: false,
1883 is_dragging_end_handle: false,
1884 handles: None,
1885 toolbar: None,
1886 context_menu: None,
1887 context_menu_builder: None,
1888 spell_check_toolbar: None,
1889 spell_check_toolbar_builder: None,
1890 build_scheduled: false,
1891 })
1892 }
1893
1894 pub fn start_handles_visible(
1896 self: Ref<Self>,
1897 app: &mut App,
1898 start_handles_visible: Ref<ValueNotifier<bool>>,
1899 ) -> Ref<Self> {
1900 app.get_mut(&self).start_handles_visible = Some(start_handles_visible);
1901 self
1902 }
1903
1904 pub fn end_handles_visible(
1906 self: Ref<Self>,
1907 app: &mut App,
1908 end_handles_visible: Ref<ValueNotifier<bool>>,
1909 ) -> Ref<Self> {
1910 app.get_mut(&self).end_handles_visible = Some(end_handles_visible);
1911 self
1912 }
1913
1914 pub fn toolbar_visible(
1916 self: Ref<Self>,
1917 app: &mut App,
1918 toolbar_visible: Ref<ValueNotifier<bool>>,
1919 ) -> Ref<Self> {
1920 app.get_mut(&self).toolbar_visible = Some(toolbar_visible);
1921 self
1922 }
1923
1924 pub fn magnifier_configuration(
1926 self: Ref<Self>,
1927 app: &mut App,
1928 magnifier_configuration: TextMagnifierConfiguration,
1929 ) -> Ref<Self> {
1930 app.get_mut(&self).magnifier_configuration = magnifier_configuration;
1931 self
1932 }
1933
1934 pub fn toolbar_location(self: Ref<Self>, app: &mut App, toolbar_location: Offset) -> Ref<Self> {
1936 self.set_toolbar_location(app, Some(toolbar_location));
1937 self
1938 }
1939
1940 pub fn drag_start_behavior(
1942 self: Ref<Self>,
1943 app: &mut App,
1944 drag_start_behavior: DragStartBehavior,
1945 ) -> Ref<Self> {
1946 app.get_mut(&self).drag_start_behavior = drag_start_behavior;
1947 self
1948 }
1949
1950 pub fn on_selection_handle_tapped(
1952 self: Ref<Self>,
1953 app: &mut App,
1954 on_selection_handle_tapped: Listener,
1955 ) -> Ref<Self> {
1956 app.get_mut(&self).on_selection_handle_tapped = Some(on_selection_handle_tapped);
1957 self
1958 }
1959
1960 pub fn debug_required_for(self: Ref<Self>, app: &mut App, widget: WidgetRef) -> Ref<Self> {
1962 app.get_mut(&self).debug_required_for = Some(widget);
1963 self
1964 }
1965
1966 pub(crate) fn set_on_start_handle_drag_start(
1967 self: Handle<Self>,
1968 app: &mut App,
1969 callback: ValueChanged<DragStartDetails>,
1970 ) {
1971 app.get_mut(self).on_start_handle_drag_start = Some(callback);
1972 }
1973
1974 pub(crate) fn set_on_start_handle_drag_update(
1975 self: Handle<Self>,
1976 app: &mut App,
1977 callback: ValueChanged<DragUpdateDetails>,
1978 ) {
1979 app.get_mut(self).on_start_handle_drag_update = Some(callback);
1980 }
1981
1982 pub(crate) fn set_on_start_handle_drag_end(
1983 self: Handle<Self>,
1984 app: &mut App,
1985 callback: ValueChanged<DragEndDetails>,
1986 ) {
1987 app.get_mut(self).on_start_handle_drag_end = Some(callback);
1988 }
1989
1990 pub(crate) fn set_on_end_handle_drag_start(
1991 self: Handle<Self>,
1992 app: &mut App,
1993 callback: ValueChanged<DragStartDetails>,
1994 ) {
1995 app.get_mut(self).on_end_handle_drag_start = Some(callback);
1996 }
1997
1998 pub(crate) fn set_on_end_handle_drag_update(
1999 self: Handle<Self>,
2000 app: &mut App,
2001 callback: ValueChanged<DragUpdateDetails>,
2002 ) {
2003 app.get_mut(self).on_end_handle_drag_update = Some(callback);
2004 }
2005
2006 pub(crate) fn set_on_end_handle_drag_end(
2007 self: Handle<Self>,
2008 app: &mut App,
2009 callback: ValueChanged<DragEndDetails>,
2010 ) {
2011 app.get_mut(self).on_end_handle_drag_end = Some(callback);
2012 }
2013
2014 pub fn toolbar_is_visible(self: Handle<Self>, app: &App) -> bool {
2016 let this = app.get(self);
2017 if this
2018 .selection_controls
2019 .as_ref()
2020 .is_some_and(|controls| controls.as_text_selection_handle_controls().is_some())
2021 {
2022 this.context_menu.is_some() || this.spell_check_toolbar.is_some()
2023 } else {
2024 this.toolbar.is_some() || this.spell_check_toolbar.is_some()
2025 }
2026 }
2027
2028 pub fn magnifier_is_visible(self: Handle<Self>, app: &App) -> bool {
2030 app.get(self).magnifier_controller.shown(app)
2031 }
2032
2033 pub fn magnifier_exists(self: Handle<Self>, app: &App) -> bool {
2035 app.get(self)
2036 .magnifier_controller
2037 .overlay_entry(app)
2038 .is_some()
2039 }
2040
2041 pub(crate) fn spell_check_toolbar_is_shown(self: Handle<Self>, app: &App) -> bool {
2042 app.get(self).spell_check_toolbar.is_some()
2043 }
2044
2045 pub(crate) fn has_handles(self: Handle<Self>, app: &App) -> bool {
2046 app.get(self).handles.is_some()
2047 }
2048
2049 pub fn show_magnifier(
2051 self: Handle<Self>,
2052 app: &mut App,
2053 initial_magnifier_info: MagnifierInfo,
2054 ) {
2055 let controller = app.get(self).magnifier_controller.handle();
2056 if controller.overlay_entry(app).is_some() {
2057 return;
2058 }
2059 if self.toolbar_is_visible(app) {
2060 self.hide_toolbar(app);
2061 }
2062 let info = app.get(self).magnifier_info.clone();
2063 info.set_value(app, initial_magnifier_info);
2064 let context = app.get(self).context;
2065 let configuration = app.get(self).magnifier_configuration.clone();
2066 let kept_controller = app.get(self).magnifier_controller.clone();
2067 let built = (configuration.magnifier_builder())(app, context, kept_controller, info);
2068 let Some(built) = built else {
2069 return;
2070 };
2071 let below = if configuration.should_display_handles_in_magnifier {
2072 None
2073 } else {
2074 app.get(self)
2075 .handles
2076 .as_ref()
2077 .map(|handles| handles.start.handle())
2078 };
2079 controller.show(
2080 app,
2081 context,
2082 Rc::new(move |_app, _context| built.clone()),
2083 below,
2084 );
2085 }
2086
2087 pub fn hide_magnifier(self: Handle<Self>, app: &mut App) {
2089 let controller = app.get(self).magnifier_controller.handle();
2090 if controller.overlay_entry(app).is_none() {
2091 return;
2092 }
2093 controller.hide(app, true);
2094 }
2095
2096 pub fn start_handle_type(self: Handle<Self>, app: &App) -> TextSelectionHandleType {
2098 app.get(self).start_handle_type
2099 }
2100
2101 pub fn set_start_handle_type(
2103 self: Handle<Self>,
2104 app: &mut App,
2105 value: TextSelectionHandleType,
2106 ) {
2107 if app.get(self).start_handle_type == value {
2108 return;
2109 }
2110 app.get_mut(self).start_handle_type = value;
2111 self.mark_needs_build(app);
2112 }
2113
2114 pub fn line_height_at_start(self: Handle<Self>, app: &App) -> f64 {
2116 app.get(self).line_height_at_start
2117 }
2118
2119 pub fn set_line_height_at_start(self: Handle<Self>, app: &mut App, value: f64) {
2121 if app.get(self).line_height_at_start == value {
2122 return;
2123 }
2124 app.get_mut(self).line_height_at_start = value;
2125 self.mark_needs_build(app);
2126 }
2127
2128 pub fn is_dragging_start_handle(self: Handle<Self>, app: &App) -> bool {
2130 app.get(self).is_dragging_start_handle || app.get(self).start_handle_drag_in_progress
2131 }
2132
2133 fn can_drag_start_handle(self: Handle<Self>, app: &App) -> bool {
2134 !app.get(self).is_dragging_end_handle
2135 || (!matches!(
2136 app.platform().target_platform(),
2137 TargetPlatform::IOS | TargetPlatform::MacOS
2138 ) && !K_IS_WEB)
2139 }
2140
2141 fn handle_start_handle_drag_start(
2143 self: Handle<Self>,
2144 app: &mut App,
2145 details: DragStartDetails,
2146 ) {
2147 debug_assert!(!app.get(self).is_dragging_start_handle);
2148 if app.get(self).handles.is_none() {
2149 app.get_mut(self).is_dragging_start_handle = false;
2150 return;
2151 }
2152 app.get_mut(self).start_handle_drag_in_progress = true;
2153 if !self.can_drag_start_handle(app) {
2154 return;
2155 }
2156 app.get_mut(self).is_dragging_start_handle = details.kind == Some(PointerDeviceKind::Touch);
2157 if let Some(callback) = app.get(self).on_start_handle_drag_start.clone() {
2158 callback(app, details);
2159 }
2160 }
2161
2162 fn handle_start_handle_drag_update(
2164 self: Handle<Self>,
2165 app: &mut App,
2166 details: DragUpdateDetails,
2167 ) {
2168 if app.get(self).handles.is_none() {
2169 app.get_mut(self).is_dragging_start_handle = false;
2170 return;
2171 }
2172 if !self.can_drag_start_handle(app) {
2173 return;
2174 }
2175 if !app.get(self).is_dragging_start_handle {
2176 app.get_mut(self).is_dragging_start_handle =
2177 details.kind == Some(PointerDeviceKind::Touch);
2178 let start_details = DragStartDetails::new(
2179 details.global_position,
2180 Some(details.local_position),
2181 details.source_time_stamp,
2182 details.kind,
2183 );
2184 if let Some(callback) = app.get(self).on_start_handle_drag_start.clone() {
2185 callback(app, start_details);
2186 }
2187 }
2188 if let Some(callback) = app.get(self).on_start_handle_drag_update.clone() {
2189 callback(app, details);
2190 }
2191 }
2192
2193 fn handle_start_handle_drag_end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
2195 app.get_mut(self).is_dragging_start_handle = false;
2196 if app.get(self).handles.is_none() {
2197 return;
2198 }
2199 app.get_mut(self).start_handle_drag_in_progress = false;
2200 if !self.can_drag_start_handle(app) {
2201 return;
2202 }
2203 if let Some(callback) = app.get(self).on_start_handle_drag_end.clone() {
2204 callback(app, details);
2205 }
2206 }
2207
2208 pub fn end_handle_type(self: Handle<Self>, app: &App) -> TextSelectionHandleType {
2210 app.get(self).end_handle_type
2211 }
2212
2213 pub fn set_end_handle_type(self: Handle<Self>, app: &mut App, value: TextSelectionHandleType) {
2215 if app.get(self).end_handle_type == value {
2216 return;
2217 }
2218 app.get_mut(self).end_handle_type = value;
2219 self.mark_needs_build(app);
2220 }
2221
2222 pub fn line_height_at_end(self: Handle<Self>, app: &App) -> f64 {
2224 app.get(self).line_height_at_end
2225 }
2226
2227 pub fn set_line_height_at_end(self: Handle<Self>, app: &mut App, value: f64) {
2229 if app.get(self).line_height_at_end == value {
2230 return;
2231 }
2232 app.get_mut(self).line_height_at_end = value;
2233 self.mark_needs_build(app);
2234 }
2235
2236 pub fn is_dragging_end_handle(self: Handle<Self>, app: &App) -> bool {
2238 app.get(self).is_dragging_end_handle || app.get(self).end_handle_drag_in_progress
2239 }
2240
2241 fn can_drag_end_handle(self: Handle<Self>, app: &App) -> bool {
2242 !app.get(self).is_dragging_start_handle
2243 || (!matches!(
2244 app.platform().target_platform(),
2245 TargetPlatform::IOS | TargetPlatform::MacOS
2246 ) && !K_IS_WEB)
2247 }
2248
2249 fn handle_end_handle_drag_start(self: Handle<Self>, app: &mut App, details: DragStartDetails) {
2251 debug_assert!(!app.get(self).is_dragging_end_handle);
2252 if app.get(self).handles.is_none() {
2253 app.get_mut(self).is_dragging_end_handle = false;
2254 return;
2255 }
2256 app.get_mut(self).end_handle_drag_in_progress = true;
2257 if !self.can_drag_end_handle(app) {
2258 return;
2259 }
2260 app.get_mut(self).is_dragging_end_handle = details.kind == Some(PointerDeviceKind::Touch);
2261 if let Some(callback) = app.get(self).on_end_handle_drag_start.clone() {
2262 callback(app, details);
2263 }
2264 }
2265
2266 fn handle_end_handle_drag_update(
2268 self: Handle<Self>,
2269 app: &mut App,
2270 details: DragUpdateDetails,
2271 ) {
2272 if app.get(self).handles.is_none() {
2273 app.get_mut(self).is_dragging_end_handle = false;
2274 return;
2275 }
2276 if !self.can_drag_end_handle(app) {
2277 return;
2278 }
2279 if !app.get(self).is_dragging_end_handle {
2280 app.get_mut(self).is_dragging_end_handle =
2281 details.kind == Some(PointerDeviceKind::Touch);
2282 let start_details = DragStartDetails::new(
2283 details.global_position,
2284 Some(details.local_position),
2285 details.source_time_stamp,
2286 details.kind,
2287 );
2288 if let Some(callback) = app.get(self).on_end_handle_drag_start.clone() {
2289 callback(app, start_details);
2290 }
2291 }
2292 if let Some(callback) = app.get(self).on_end_handle_drag_update.clone() {
2293 callback(app, details);
2294 }
2295 }
2296
2297 fn handle_end_handle_drag_end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
2299 app.get_mut(self).is_dragging_end_handle = false;
2300 if app.get(self).handles.is_none() {
2301 return;
2302 }
2303 app.get_mut(self).end_handle_drag_in_progress = false;
2304 if !self.can_drag_end_handle(app) {
2305 return;
2306 }
2307 if let Some(callback) = app.get(self).on_end_handle_drag_end.clone() {
2308 callback(app, details);
2309 }
2310 }
2311
2312 pub fn selection_endpoints(self: Handle<Self>, app: &App) -> Vec<TextSelectionPoint> {
2314 app.get(self).selection_endpoints.clone()
2315 }
2316
2317 pub fn set_selection_endpoints(
2319 self: Handle<Self>,
2320 app: &mut App,
2321 value: Vec<TextSelectionPoint>,
2322 ) {
2323 if app.get(self).selection_endpoints != value {
2324 self.mark_needs_build(app);
2325 if (app.get(self).is_dragging_end_handle || app.get(self).is_dragging_start_handle)
2326 && app.platform().target_platform() == TargetPlatform::Android
2327 {
2328 HapticFeedback::selection_click(app);
2329 }
2330 }
2331 app.get_mut(self).selection_endpoints = value;
2332 }
2333
2334 pub fn toolbar_location_value(self: Handle<Self>, app: &App) -> Option<Offset> {
2336 app.get(self).toolbar_location
2337 }
2338
2339 pub fn set_toolbar_location(self: Handle<Self>, app: &mut App, value: Option<Offset>) {
2341 if app.get(self).toolbar_location == value {
2342 return;
2343 }
2344 app.get_mut(self).toolbar_location = value;
2345 self.mark_needs_build(app);
2346 }
2347
2348 pub fn show_handles(self: Handle<Self>, app: &mut App) {
2350 if app.get(self).handles.is_some() {
2351 return;
2352 }
2353 let context = app.get(self).context;
2354 let overlay = Overlay::of(app, context, true);
2355
2356 let overlay_context = overlay.context(app);
2357 let captured_themes = Rc::new(<dyn InheritedTheme>::capture(
2358 app,
2359 context,
2360 Some(overlay_context),
2361 ));
2362
2363 let this = self;
2364 let start_themes = Rc::clone(&captured_themes);
2365 let start = OverlayEntry::new(
2366 app,
2367 Rc::new(move |app, context| start_themes.wrap(this.build_start_handle(app, context))),
2368 false,
2369 false,
2370 false,
2371 );
2372 let end = OverlayEntry::new(
2373 app,
2374 Rc::new(move |app, context| captured_themes.wrap(this.build_end_handle(app, context))),
2375 false,
2376 false,
2377 false,
2378 );
2379 app.get_mut(self).handles = Some(SelectionHandles {
2380 start: start.clone(),
2381 end: end.clone(),
2382 });
2383 overlay.insert_all(app, vec![start, end], None, None);
2384 }
2385
2386 pub fn hide_handles(self: Handle<Self>, app: &mut App) {
2388 let Some(handles) = app.get_mut(self).handles.take() else {
2389 return;
2390 };
2391 handles.start.remove(app);
2392 handles.start.dispose(app);
2393 handles.end.remove(app);
2394 handles.end.dispose(app);
2395 }
2396
2397 pub fn show_toolbar(
2399 self: Handle<Self>,
2400 app: &mut App,
2401 context: Option<BuildContext>,
2402 context_menu_builder: Option<WidgetBuilder>,
2403 ) {
2404 let Some(context_menu_builder) = context_menu_builder else {
2405 if app.get(self).toolbar.is_some() {
2406 return;
2407 }
2408 let this = self;
2409 let toolbar = OverlayEntry::new(
2410 app,
2411 Rc::new(move |app, context| this.build_toolbar(app, context)),
2412 false,
2413 false,
2414 false,
2415 );
2416 app.get_mut(self).toolbar = Some(toolbar.clone());
2417 let overlay_context = app.get(self).context;
2418 let above = app
2419 .get(self)
2420 .handles
2421 .as_ref()
2422 .map(|handles| handles.end.handle());
2423 Overlay::of(app, overlay_context, true).insert(app, toolbar, None, above);
2424 return;
2425 };
2426 let Some(context) = context else {
2427 return;
2428 };
2429 if app.get(self).context_menu.is_some() {
2430 app.get_mut(self).context_menu_builder = Some(context_menu_builder);
2431 if let Some(entry) = app.get(self).context_menu.handle() {
2432 entry.mark_needs_build(app);
2433 }
2434 return;
2435 }
2436 app.get_mut(self).context_menu_builder = Some(Rc::clone(&context_menu_builder));
2437 let this = self;
2438 let field_context = context;
2439 let entry = OverlayEntry::new(
2440 app,
2441 Rc::new(move |app, overlay_context| {
2442 let child = app
2443 .get(this)
2444 .context_menu_builder
2445 .clone()
2446 .map(|builder| builder(app, overlay_context))
2447 .unwrap_or_else(|| SizedBox::shrink().into_widget());
2448 let visibility = app.get(this).toolbar_visible.clone();
2449 let layer_link = app.get(this).toolbar_layer_link.clone();
2450 let offset = field_context
2451 .find_render_object(app)
2452 .and_then(|object| object.as_box())
2453 .map(|box_| -box_.local_to_global(app, Offset::ZERO, None))
2454 .unwrap_or(Offset::ZERO);
2455 let mut wrapper = SelectionToolbarWrapper::new(layer_link, offset, child);
2456 if let Some(visibility) = visibility {
2457 wrapper = wrapper.visibility(visibility);
2458 }
2459 capture_to_navigator(app, overlay_context).wrap(wrapper.into_widget())
2462 }),
2463 false,
2464 false,
2465 false,
2466 );
2467 app.get_mut(self).context_menu = Some(entry.clone());
2468 Overlay::of(app, context, true).insert(app, entry, None, None);
2469 }
2470
2471 pub fn show_spell_check_suggestions_toolbar(
2473 self: Handle<Self>,
2474 app: &mut App,
2475 context: Option<BuildContext>,
2476 builder: WidgetBuilder,
2477 ) {
2478 let Some(context) = context else {
2479 return;
2480 };
2481 app.get_mut(self).spell_check_toolbar_builder = Some(Rc::clone(&builder));
2482 if app.get(self).spell_check_toolbar.is_some() {
2483 if let Some(entry) = app.get(self).spell_check_toolbar.handle() {
2484 entry.mark_needs_build(app);
2485 }
2486 return;
2487 }
2488 let this = self;
2489 let field_context = context;
2490 let entry = OverlayEntry::new(
2491 app,
2492 Rc::new(move |app, overlay_context| {
2493 let child = app
2494 .get(this)
2495 .spell_check_toolbar_builder
2496 .clone()
2497 .map(|builder| builder(app, overlay_context))
2498 .unwrap_or_else(|| SizedBox::shrink().into_widget());
2499 let layer_link = app.get(this).toolbar_layer_link.clone();
2500 let offset = field_context
2501 .find_render_object(app)
2502 .and_then(|object| object.as_box())
2503 .map(|box_| -box_.local_to_global(app, Offset::ZERO, None))
2504 .unwrap_or(Offset::ZERO);
2505 capture_to_navigator(app, overlay_context)
2506 .wrap(SelectionToolbarWrapper::new(layer_link, offset, child).into_widget())
2507 }),
2508 false,
2509 false,
2510 false,
2511 );
2512 app.get_mut(self).spell_check_toolbar = Some(entry.clone());
2513 Overlay::of(app, context, true).insert(app, entry, None, None);
2514 }
2515
2516 pub fn mark_needs_build(self: Handle<Self>, app: &mut App) {
2518 if app.get(self).handles.is_none() && app.get(self).toolbar.is_none() {
2519 return;
2520 }
2521 if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
2522 if app.get(self).build_scheduled {
2523 return;
2524 }
2525 app.get_mut(self).build_scheduled = true;
2526 SchedulerBinding::add_post_frame_callback(
2527 app,
2528 FrameCallback::handle_method(self, Self::mark_needs_build_after_frame),
2529 View::maybe_id_of(app, app.get(self).context),
2530 );
2531 } else {
2532 self.rebuild_overlay_entries(app);
2533 }
2534 }
2535
2536 fn mark_needs_build_after_frame(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
2537 app.get_mut(self).build_scheduled = false;
2538 self.rebuild_overlay_entries(app);
2539 }
2540
2541 fn rebuild_overlay_entries(self: Handle<Self>, app: &mut App) {
2542 if let Some(handles) = app.get(self).handles.as_ref() {
2543 let (start, end) = (handles.start.handle(), handles.end.handle());
2544 start.mark_needs_build(app);
2545 end.mark_needs_build(app);
2546 }
2547 if let Some(toolbar) = app.get(self).toolbar.handle() {
2548 toolbar.mark_needs_build(app);
2549 }
2550 if let Some(entry) = app.get(self).context_menu.handle() {
2551 entry.mark_needs_build(app);
2552 } else if let Some(entry) = app.get(self).spell_check_toolbar.handle() {
2553 entry.mark_needs_build(app);
2554 }
2555 }
2556
2557 pub fn hide(self: Handle<Self>, app: &mut App) {
2559 let controller = app.get(self).magnifier_controller.handle();
2560 controller.hide(app, true);
2561 self.hide_handles(app);
2562 if app.get(self).toolbar.is_some()
2563 || app.get(self).context_menu.is_some()
2564 || app.get(self).spell_check_toolbar.is_some()
2565 {
2566 self.hide_toolbar(app);
2567 }
2568 }
2569
2570 pub fn hide_toolbar(self: Handle<Self>, app: &mut App) {
2572 if let Some(entry) = app.get_mut(self).context_menu.take() {
2573 entry.remove(app);
2574 entry.dispose(app);
2575 }
2576 app.get_mut(self).context_menu_builder = None;
2577 if let Some(entry) = app.get_mut(self).spell_check_toolbar.take() {
2578 entry.remove(app);
2579 entry.dispose(app);
2580 }
2581 app.get_mut(self).spell_check_toolbar_builder = None;
2582 let Some(toolbar) = app.get_mut(self).toolbar.take() else {
2583 return;
2584 };
2585 toolbar.remove(app);
2586 toolbar.dispose(app);
2587 }
2588
2589 pub fn dispose(self: Handle<Self>, app: &mut App) {
2591 self.hide(app);
2592 let magnifier_info = app.get(self).magnifier_info.handle();
2593 magnifier_info.dispose(app);
2594 }
2595
2596 fn build_start_handle(self: Handle<Self>, app: &App, _context: BuildContext) -> WidgetRef {
2597 let overlay = self.keep(app);
2599 let this = app.get(self);
2600 let handle = match this.selection_controls.clone() {
2601 Some(selection_controls)
2602 if !(this.start_handle_type == TextSelectionHandleType::Collapsed
2603 && this.is_dragging_end_handle) =>
2604 {
2605 SelectionHandleOverlay::new(
2606 this.start_handle_type,
2607 this.start_handle_layer_link.clone(),
2608 selection_controls,
2609 this.line_height_at_start,
2610 )
2611 .on_selection_handle_tapped(this.on_selection_handle_tapped.clone())
2612 .on_selection_handle_drag_start({
2613 let overlay = overlay.clone();
2614 Rc::new(move |app, details| {
2615 overlay.handle_start_handle_drag_start(app, details);
2616 })
2617 })
2618 .on_selection_handle_drag_update({
2619 let overlay = overlay.clone();
2620 Rc::new(move |app, details| {
2621 overlay.handle_start_handle_drag_update(app, details);
2622 })
2623 })
2624 .on_selection_handle_drag_end({
2625 let overlay = overlay.clone();
2626 Rc::new(move |app, details| {
2627 overlay.handle_start_handle_drag_end(app, details);
2628 })
2629 })
2630 .visibility(this.start_handles_visible.clone())
2631 .drag_start_behavior(this.drag_start_behavior)
2632 .into_widget()
2633 }
2634 _ => SizedBox::shrink().into_widget(),
2637 };
2638 TextFieldTapRegion::new(ExcludeSemantics::new().child(handle)).into_widget()
2639 }
2640
2641 fn build_end_handle(self: Handle<Self>, app: &App, _context: BuildContext) -> WidgetRef {
2642 let overlay = self.keep(app);
2644 let this = app.get(self);
2645 let collapsed = this.end_handle_type == TextSelectionHandleType::Collapsed;
2646 let handle = match this.selection_controls.clone() {
2647 Some(selection_controls)
2648 if !((collapsed && this.is_dragging_start_handle)
2649 || (collapsed
2650 && !this.is_dragging_start_handle
2651 && !this.is_dragging_end_handle)) =>
2652 {
2653 SelectionHandleOverlay::new(
2654 this.end_handle_type,
2655 this.end_handle_layer_link.clone(),
2656 selection_controls,
2657 this.line_height_at_end,
2658 )
2659 .on_selection_handle_tapped(this.on_selection_handle_tapped.clone())
2660 .on_selection_handle_drag_start({
2661 let overlay = overlay.clone();
2662 Rc::new(move |app, details| {
2663 overlay.handle_end_handle_drag_start(app, details);
2664 })
2665 })
2666 .on_selection_handle_drag_update({
2667 let overlay = overlay.clone();
2668 Rc::new(move |app, details| {
2669 overlay.handle_end_handle_drag_update(app, details);
2670 })
2671 })
2672 .on_selection_handle_drag_end({
2673 let overlay = overlay.clone();
2674 Rc::new(move |app, details| {
2675 overlay.handle_end_handle_drag_end(app, details);
2676 })
2677 })
2678 .visibility(this.end_handles_visible.clone())
2679 .drag_start_behavior(this.drag_start_behavior)
2680 .into_widget()
2681 }
2682 _ => SizedBox::shrink().into_widget(),
2685 };
2686 TextFieldTapRegion::new(ExcludeSemantics::new().child(handle)).into_widget()
2687 }
2688
2689 #[allow(deprecated)]
2690 fn build_toolbar(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2691 let Some(controls) = app.get(self).selection_controls.clone() else {
2692 return TextFieldTapRegion::new(SizedBox::shrink()).into_widget();
2693 };
2694 let Some(delegate) = app.get(self).selection_delegate else {
2695 debug_assert!(
2696 false,
2697 "If not using contextMenuBuilder, must pass selectionDelegate."
2698 );
2699 return TextFieldTapRegion::new(SizedBox::shrink()).into_widget();
2700 };
2701 let overlay_context = app.get(self).context;
2702 let Some(render_box) = overlay_context
2703 .find_render_object(app)
2704 .and_then(|object| object.as_box())
2705 else {
2706 return TextFieldTapRegion::new(SizedBox::shrink()).into_widget();
2707 };
2708 let editing_region = Rect::from_points(
2709 render_box.local_to_global(app, Offset::ZERO, None),
2710 render_box.local_to_global(app, render_box.size(app).bottom_right(Offset::ZERO), None),
2711 );
2712 let endpoints = app.get(self).selection_endpoints.clone();
2713 if endpoints.is_empty() {
2714 return TextFieldTapRegion::new(SizedBox::shrink()).into_widget();
2715 }
2716 let line_height_at_end = app.get(self).line_height_at_end;
2717 let line_height_at_start = app.get(self).line_height_at_start;
2718 let is_multiline = endpoints[endpoints.len() - 1].point.dy() - endpoints[0].point.dy()
2719 > line_height_at_end / 2.0;
2720 let mid_x = if is_multiline {
2721 editing_region.width() / 2.0
2722 } else {
2723 (endpoints[0].point.dx() + endpoints[endpoints.len() - 1].point.dx()) / 2.0
2724 };
2725 let midpoint = Offset::new(mid_x, endpoints[0].point.dy() - line_height_at_start);
2726 let clipboard_status = app.get(self).clipboard_status.clone();
2727 let toolbar_location = app.get(self).toolbar_location;
2728 let toolbar = controls.build_toolbar(
2729 app,
2730 context,
2731 editing_region,
2732 line_height_at_start,
2733 midpoint,
2734 &endpoints,
2735 delegate,
2736 clipboard_status,
2737 toolbar_location,
2738 );
2739 TextFieldTapRegion::new(toolbar).into_widget()
2740 }
2741
2742 pub fn update_magnifier(self: Handle<Self>, app: &mut App, magnifier_info: MagnifierInfo) {
2744 let controller = app.get(self).magnifier_controller.handle();
2745 if controller.overlay_entry(app).is_none() {
2746 return;
2747 }
2748 let info = app.get(self).magnifier_info.handle();
2749 info.set_value(app, magnifier_info);
2750 }
2751}
2752
2753#[derive(Clone)]
2760pub(crate) struct SelectionToolbarWrapper {
2761 pub key: Option<KeyRef>,
2762 pub visibility: Option<Ref<ValueNotifier<bool>>>,
2763 pub layer_link: Ref<LayerLink>,
2764 pub offset: Offset,
2765 pub child: WidgetRef,
2766}
2767
2768impl SelectionToolbarWrapper {
2769 #[cfg_attr(debug_assertions, track_caller)]
2770 pub fn new<K>(
2771 layer_link: Ref<LayerLink>,
2772 offset: Offset,
2773 child: impl IntoWidget<K>,
2774 ) -> SelectionToolbarWrapper {
2775 SelectionToolbarWrapper {
2776 key: None,
2777 visibility: None,
2778 layer_link,
2779 offset,
2780 child: child.into_widget(),
2781 }
2782 }
2783
2784 pub fn visibility(mut self, visibility: Ref<ValueNotifier<bool>>) -> SelectionToolbarWrapper {
2785 self.visibility = Some(visibility);
2786 self
2787 }
2788}
2789
2790impl Debug for SelectionToolbarWrapper {
2791 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2792 f.debug_struct("SelectionToolbarWrapper")
2793 .finish_non_exhaustive()
2794 }
2795}
2796
2797impl StatefulWidget for SelectionToolbarWrapper {
2798 type State = SelectionToolbarWrapperState;
2799
2800 fn key(&self) -> Option<&KeyRef> {
2801 self.key.as_ref()
2802 }
2803
2804 fn create_state(&self) -> SelectionToolbarWrapperState {
2805 SelectionToolbarWrapperState {
2806 state: StateData::new(),
2807 controller: None,
2808 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
2809 }
2810 }
2811}
2812
2813pub(crate) struct SelectionToolbarWrapperState {
2815 state: StateData<SelectionToolbarWrapper>,
2816 controller: Option<Ref<AnimationController>>,
2817 single_ticker_provider: SingleTickerProviderStateMixinData,
2818}
2819
2820impl SelectionToolbarWrapperState {
2821 fn opacity(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
2823 app.get(self)
2824 .controller
2825 .as_ref()
2826 .expect("the controller is created in initState")
2827 .erase()
2828 }
2829
2830 fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
2831 app.get(self)
2832 .controller
2833 .handle()
2834 .expect("the controller is created in initState")
2835 }
2836
2837 fn toolbar_visibility_changed(self: Handle<Self>, app: &mut App) {
2838 let visible = self
2839 .widget(app)
2840 .visibility
2841 .as_ref()
2842 .map(|visibility| *visibility.value(app))
2843 .unwrap_or(true);
2844 let controller = self.controller(app);
2845 if visible {
2846 controller.forward(app, None);
2847 } else {
2848 controller.reverse(app, None);
2849 }
2850 }
2851}
2852
2853impl SingleTickerProviderStateMixin for SelectionToolbarWrapperState {
2854 fn single_ticker_provider_data(
2855 self: Handle<Self>,
2856 app: &App,
2857 ) -> &SingleTickerProviderStateMixinData {
2858 &app.get(self).single_ticker_provider
2859 }
2860
2861 fn single_ticker_provider_data_mut(
2862 self: Handle<Self>,
2863 app: &mut App,
2864 ) -> &mut SingleTickerProviderStateMixinData {
2865 &mut app.get_mut(self).single_ticker_provider
2866 }
2867}
2868
2869impl TickerProviderObject for SelectionToolbarWrapperState {
2870 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
2871 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
2872 }
2873}
2874
2875impl State for SelectionToolbarWrapperState {
2876 type Widget = SelectionToolbarWrapper;
2877 crate::state_accessors!();
2878
2879 fn init_state(self: Handle<Self>, app: &mut App) {
2880 let controller = AnimationController::new(
2881 app,
2882 None,
2883 Some(SelectionOverlay::FADE_DURATION),
2884 None,
2885 0.0,
2886 1.0,
2887 AnimationBehavior::Normal,
2888 self,
2889 );
2890 app.get_mut(self).controller = Some(controller);
2891 self.toolbar_visibility_changed(app);
2892 if let Some(visibility) = self.widget(app).visibility.handle() {
2893 visibility.add_listener(
2894 app,
2895 Listener::handle_method(self, Self::toolbar_visibility_changed),
2896 );
2897 }
2898 }
2899
2900 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectionToolbarWrapper) {
2901 if old_widget.visibility == self.widget(app).visibility {
2902 return;
2903 }
2904 if let Some(visibility) = old_widget.visibility.handle() {
2905 visibility.remove_listener(
2906 app,
2907 &Listener::handle_method(self, Self::toolbar_visibility_changed),
2908 );
2909 }
2910 self.toolbar_visibility_changed(app);
2911 if let Some(visibility) = self.widget(app).visibility.handle() {
2912 visibility.add_listener(
2913 app,
2914 Listener::handle_method(self, Self::toolbar_visibility_changed),
2915 );
2916 }
2917 }
2918
2919 fn activate(self: Handle<Self>, app: &mut App) {
2920 SingleTickerProviderStateMixin::activate(self, app);
2921 }
2922
2923 fn dispose(self: Handle<Self>, app: &mut App) {
2924 if let Some(visibility) = self.widget(app).visibility.handle() {
2925 visibility.remove_listener(
2926 app,
2927 &Listener::handle_method(self, Self::toolbar_visibility_changed),
2928 );
2929 }
2930 let controller = self.controller(app);
2931 controller.dispose(app);
2932 SingleTickerProviderStateMixin::dispose(self, app);
2933 }
2934
2935 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2936 let opacity = self.opacity(app);
2937 let widget = self.widget(app);
2938 let (layer_link, offset, child) = (
2939 widget.layer_link.clone(),
2940 widget.offset,
2941 widget.child.clone(),
2942 );
2943 let text_direction = Directionality::of(app, context);
2944 TextFieldTapRegion::new(Directionality::new(
2945 text_direction,
2946 FadeTransition::new(opacity).child(
2947 CompositedTransformFollower::new(layer_link)
2948 .show_when_unlinked(false)
2949 .offset(offset)
2950 .child(child),
2951 ),
2952 ))
2953 .into_widget()
2954 }
2955}
2956
2957#[derive(Clone)]
2961struct SelectionHandleOverlay {
2962 handle_layer_link: Ref<LayerLink>,
2963 on_selection_handle_tapped: Option<Listener>,
2964 on_selection_handle_drag_start: Option<ValueChanged<DragStartDetails>>,
2965 on_selection_handle_drag_update: Option<ValueChanged<DragUpdateDetails>>,
2966 on_selection_handle_drag_end: Option<ValueChanged<DragEndDetails>>,
2967 selection_controls: Rc<dyn TextSelectionControls>,
2968 visibility: Option<Ref<ValueNotifier<bool>>>,
2969 preferred_line_height: f64,
2970 handle_type: TextSelectionHandleType,
2971 drag_start_behavior: DragStartBehavior,
2972}
2973
2974impl SelectionHandleOverlay {
2975 fn new(
2977 handle_type: TextSelectionHandleType,
2978 handle_layer_link: Ref<LayerLink>,
2979 selection_controls: Rc<dyn TextSelectionControls>,
2980 preferred_line_height: f64,
2981 ) -> SelectionHandleOverlay {
2982 SelectionHandleOverlay {
2983 handle_layer_link,
2984 on_selection_handle_tapped: None,
2985 on_selection_handle_drag_start: None,
2986 on_selection_handle_drag_update: None,
2987 on_selection_handle_drag_end: None,
2988 selection_controls,
2989 visibility: None,
2990 preferred_line_height,
2991 handle_type,
2992 drag_start_behavior: DragStartBehavior::Start,
2993 }
2994 }
2995
2996 fn on_selection_handle_tapped(mut self, on_selection_handle_tapped: Option<Listener>) -> Self {
2998 self.on_selection_handle_tapped = on_selection_handle_tapped;
2999 self
3000 }
3001
3002 fn on_selection_handle_drag_start(
3004 mut self,
3005 on_selection_handle_drag_start: ValueChanged<DragStartDetails>,
3006 ) -> Self {
3007 self.on_selection_handle_drag_start = Some(on_selection_handle_drag_start);
3008 self
3009 }
3010
3011 fn on_selection_handle_drag_update(
3013 mut self,
3014 on_selection_handle_drag_update: ValueChanged<DragUpdateDetails>,
3015 ) -> Self {
3016 self.on_selection_handle_drag_update = Some(on_selection_handle_drag_update);
3017 self
3018 }
3019
3020 fn on_selection_handle_drag_end(
3022 mut self,
3023 on_selection_handle_drag_end: ValueChanged<DragEndDetails>,
3024 ) -> Self {
3025 self.on_selection_handle_drag_end = Some(on_selection_handle_drag_end);
3026 self
3027 }
3028
3029 fn visibility(mut self, visibility: Option<Ref<ValueNotifier<bool>>>) -> Self {
3031 self.visibility = visibility;
3032 self
3033 }
3034
3035 fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Self {
3037 self.drag_start_behavior = drag_start_behavior;
3038 self
3039 }
3040}
3041
3042impl Debug for SelectionHandleOverlay {
3043 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3044 f.debug_struct("SelectionHandleOverlay")
3045 .field("type", &self.handle_type)
3046 .field("preferred_line_height", &self.preferred_line_height)
3047 .finish_non_exhaustive()
3048 }
3049}
3050
3051impl StatefulWidget for SelectionHandleOverlay {
3052 type State = SelectionHandleOverlayState;
3053
3054 fn key(&self) -> Option<&KeyRef> {
3055 None
3056 }
3057
3058 fn create_state(&self) -> SelectionHandleOverlayState {
3059 SelectionHandleOverlayState {
3060 state: StateData::new(),
3061 controller: None,
3062 single_ticker_provider: SingleTickerProviderStateMixinData::new(),
3063 }
3064 }
3065}
3066
3067struct SelectionHandleOverlayState {
3069 state: StateData<SelectionHandleOverlay>,
3070 controller: Option<Ref<AnimationController>>,
3071 single_ticker_provider: SingleTickerProviderStateMixinData,
3072}
3073
3074impl SelectionHandleOverlayState {
3075 fn controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
3076 app.get(self)
3077 .controller
3078 .handle()
3079 .expect("the controller is created in initState")
3080 }
3081
3082 fn opacity(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
3084 app.get(self)
3085 .controller
3086 .as_ref()
3087 .expect("the controller is created in initState")
3088 .erase()
3089 }
3090
3091 fn handle_visibility_changed(self: Handle<Self>, app: &mut App) {
3092 let visible = self
3093 .widget(app)
3094 .visibility
3095 .as_ref()
3096 .map(|visibility| *visibility.value(app))
3097 .unwrap_or(true);
3098 let controller = self.controller(app);
3099 if visible {
3100 controller.forward(app, None);
3101 } else {
3102 controller.reverse(app, None);
3103 }
3104 }
3105
3106 fn get_handle_rect(
3113 self: Handle<Self>,
3114 app: &App,
3115 _handle_type: TextSelectionHandleType,
3116 preferred_line_height: f64,
3117 ) -> Rect {
3118 let handle_size = self
3119 .widget(app)
3120 .selection_controls
3121 .get_handle_size(preferred_line_height);
3122 Rect::from_ltwh(0.0, 0.0, handle_size.width(), handle_size.height())
3123 }
3124}
3125
3126impl SingleTickerProviderStateMixin for SelectionHandleOverlayState {
3127 fn single_ticker_provider_data(
3128 self: Handle<Self>,
3129 app: &App,
3130 ) -> &SingleTickerProviderStateMixinData {
3131 &app.get(self).single_ticker_provider
3132 }
3133
3134 fn single_ticker_provider_data_mut(
3135 self: Handle<Self>,
3136 app: &mut App,
3137 ) -> &mut SingleTickerProviderStateMixinData {
3138 &mut app.get_mut(self).single_ticker_provider
3139 }
3140}
3141
3142impl TickerProviderObject for SelectionHandleOverlayState {
3143 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
3144 SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
3145 }
3146}
3147
3148impl State for SelectionHandleOverlayState {
3149 type Widget = SelectionHandleOverlay;
3150 crate::state_accessors!();
3151
3152 fn init_state(self: Handle<Self>, app: &mut App) {
3153 let controller = AnimationController::new(
3154 app,
3155 None,
3156 Some(SelectionOverlay::FADE_DURATION),
3157 None,
3158 0.0,
3159 1.0,
3160 AnimationBehavior::Normal,
3161 self,
3162 );
3163 app.get_mut(self).controller = Some(controller);
3164
3165 self.handle_visibility_changed(app);
3166 if let Some(visibility) = self.widget(app).visibility.handle() {
3167 visibility.add_listener(
3168 app,
3169 Listener::handle_method(self, Self::handle_visibility_changed),
3170 );
3171 }
3172 }
3173
3174 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SelectionHandleOverlay) {
3175 if let Some(visibility) = old_widget.visibility.handle() {
3176 visibility.remove_listener(
3177 app,
3178 &Listener::handle_method(self, Self::handle_visibility_changed),
3179 );
3180 }
3181 self.handle_visibility_changed(app);
3182 if let Some(visibility) = self.widget(app).visibility.handle() {
3183 visibility.add_listener(
3184 app,
3185 Listener::handle_method(self, Self::handle_visibility_changed),
3186 );
3187 }
3188 }
3189
3190 fn activate(self: Handle<Self>, app: &mut App) {
3191 SingleTickerProviderStateMixin::activate(self, app);
3192 }
3193
3194 fn dispose(self: Handle<Self>, app: &mut App) {
3195 if let Some(visibility) = self.widget(app).visibility.handle() {
3196 visibility.remove_listener(
3197 app,
3198 &Listener::handle_method(self, Self::handle_visibility_changed),
3199 );
3200 }
3201 let controller = self.controller(app);
3202 controller.dispose(app);
3203 SingleTickerProviderStateMixin::dispose(self, app);
3204 }
3205
3206 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
3207 let widget = self.widget(app).clone();
3208 let handle_rect =
3209 self.get_handle_rect(app, widget.handle_type, widget.preferred_line_height);
3210
3211 let interactive_rect = if handle_rect.is_empty() {
3214 handle_rect
3215 } else {
3216 handle_rect.expand_to_include(Rect::from_circle(
3217 handle_rect.center(),
3218 K_MIN_INTERACTIVE_DIMENSION / 2.0,
3219 ))
3220 };
3221 let padding = if interactive_rect.is_empty() {
3222 RelativeRect::FILL
3223 } else {
3224 RelativeRect::from_ltrb(
3225 ((interactive_rect.width() - handle_rect.width()) / 2.0).max(0.0),
3226 ((interactive_rect.height() - handle_rect.height()) / 2.0).max(0.0),
3227 ((interactive_rect.width() - handle_rect.width()) / 2.0).max(0.0),
3228 ((interactive_rect.height() - handle_rect.height()) / 2.0).max(0.0),
3229 )
3230 };
3231
3232 let handle_anchor = widget
3233 .selection_controls
3234 .get_handle_anchor(widget.handle_type, widget.preferred_line_height);
3235
3236 let eagerly_accept_drag_when_collapsed = widget.handle_type
3240 == TextSelectionHandleType::Collapsed
3241 && app.platform().target_platform() == TargetPlatform::IOS;
3242
3243 let configured = widget.clone();
3244 let pan = GestureRecognizerFactoryWithHandlers::<PanGestureRecognizer>::new(
3245 |app| {
3246 let recognizer = PanGestureRecognizer::new(app);
3247 recognizer.supported_devices(
3249 app,
3250 [
3251 PointerDeviceKind::Touch,
3252 PointerDeviceKind::Stylus,
3253 PointerDeviceKind::Unknown,
3254 ],
3255 );
3256 recognizer
3257 },
3258 move |app, instance| {
3259 DragGestureRecognizer::set_drag_start_behavior(
3260 instance,
3261 app,
3262 configured.drag_start_behavior,
3263 );
3264 instance.set_gesture_settings(
3265 app,
3266 eagerly_accept_drag_when_collapsed
3267 .then(|| DeviceGestureSettings::new(Some(1.0))),
3268 );
3269 instance.set_on_start(app, configured.on_selection_handle_drag_start.clone());
3270 instance.set_on_update(app, configured.on_selection_handle_drag_update.clone());
3271 instance.set_on_end(app, configured.on_selection_handle_drag_end.clone());
3272 },
3273 )
3274 .into_factory();
3275
3276 let handle = widget.selection_controls.build_handle(
3277 app,
3278 context,
3279 widget.handle_type,
3280 widget.preferred_line_height,
3281 widget.on_selection_handle_tapped.clone(),
3282 );
3283
3284 CompositedTransformFollower::new(widget.handle_layer_link.clone())
3285 .offset(-handle_anchor - Offset::new(padding.left, padding.top))
3287 .show_when_unlinked(false)
3288 .child(
3289 FadeTransition::new(self.opacity(app)).child(
3290 SizedBox::new()
3291 .width(interactive_rect.width())
3292 .height(interactive_rect.height())
3293 .child(
3294 Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
3295 RawGestureDetector::new()
3296 .behavior(HitTestBehavior::Translucent)
3297 .gestures(vec![(TypeId::of::<PanGestureRecognizer>(), pan)])
3298 .child(
3299 Padding::new(EdgeInsetsGeometry::only(
3300 padding.left,
3301 padding.top,
3302 padding.right,
3303 padding.bottom,
3304 ))
3305 .child(handle),
3306 ),
3307 ),
3308 ),
3309 ),
3310 )
3311 .into_widget()
3312 }
3313}
3314
3315pub trait TextSelectionGestureDetectorBuilderDelegate: Sized + 'static {
3318 fn editable_text_key(self: Handle<Self>, app: &App) -> GlobalKey;
3321
3322 fn force_press_enabled(self: Handle<Self>, app: &App) -> bool;
3324
3325 fn selection_enabled(self: Handle<Self>, app: &App) -> bool;
3327
3328 fn as_text_selection_gesture_detector_builder_delegate(
3330 self: Handle<Self>,
3331 ) -> AnyTextSelectionGestureDetectorBuilderDelegate {
3332 AnyTextSelectionGestureDetectorBuilderDelegate {
3333 id: self.id(),
3334 vtable: const { &TextSelectionGestureDetectorBuilderDelegateVTable::of::<Self>() },
3335 }
3336 }
3337}
3338
3339struct TextSelectionGestureDetectorBuilderDelegateVTable {
3340 editable_text_key: fn(&App, HandleId) -> GlobalKey,
3341 force_press_enabled: fn(&App, HandleId) -> bool,
3342 selection_enabled: fn(&App, HandleId) -> bool,
3343}
3344
3345impl TextSelectionGestureDetectorBuilderDelegateVTable {
3346 const fn of<D: TextSelectionGestureDetectorBuilderDelegate>()
3347 -> TextSelectionGestureDetectorBuilderDelegateVTable {
3348 TextSelectionGestureDetectorBuilderDelegateVTable {
3349 editable_text_key: |app, id| D::editable_text_key(resolve_builder_delegate(id), app),
3350 force_press_enabled: |app, id| {
3351 D::force_press_enabled(resolve_builder_delegate(id), app)
3352 },
3353 selection_enabled: |app, id| D::selection_enabled(resolve_builder_delegate(id), app),
3354 }
3355 }
3356}
3357
3358fn resolve_builder_delegate<T: 'static>(id: HandleId) -> Handle<T> {
3359 Handle::from_id(id)
3360}
3361
3362#[derive(Clone, Copy)]
3364pub struct AnyTextSelectionGestureDetectorBuilderDelegate {
3365 id: HandleId,
3366 vtable: &'static TextSelectionGestureDetectorBuilderDelegateVTable,
3367}
3368
3369impl AnyTextSelectionGestureDetectorBuilderDelegate {
3370 pub fn editable_text_key(self, app: &App) -> GlobalKey {
3371 (self.vtable.editable_text_key)(app, self.id)
3372 }
3373
3374 pub fn force_press_enabled(self, app: &App) -> bool {
3375 (self.vtable.force_press_enabled)(app, self.id)
3376 }
3377
3378 pub fn selection_enabled(self, app: &App) -> bool {
3379 (self.vtable.selection_enabled)(app, self.id)
3380 }
3381}
3382
3383pub struct TextSelectionGestureDetectorBuilderData {
3385 pub delegate: AnyTextSelectionGestureDetectorBuilderDelegate,
3387 should_show_selection_toolbar: bool,
3388 should_show_selection_handles: bool,
3389 is_shift_pressed: bool,
3390 drag_start_scroll_offset: f64,
3391 drag_start_viewport_offset: f64,
3392 drag_start_selection: Option<TextSelection>,
3393 long_press_started_without_focus: bool,
3394}
3395
3396impl TextSelectionGestureDetectorBuilderData {
3397 pub fn new(
3399 delegate: AnyTextSelectionGestureDetectorBuilderDelegate,
3400 ) -> TextSelectionGestureDetectorBuilderData {
3401 TextSelectionGestureDetectorBuilderData {
3402 delegate,
3403 should_show_selection_toolbar: true,
3404 should_show_selection_handles: true,
3405 is_shift_pressed: false,
3406 drag_start_scroll_offset: 0.0,
3407 drag_start_viewport_offset: 0.0,
3408 drag_start_selection: None,
3409 long_press_started_without_focus: false,
3410 }
3411 }
3412}
3413
3414#[macro_export]
3416macro_rules! text_selection_gesture_detector_builder_accessors {
3417 ($field:ident) => {
3418 fn builder_data(
3419 self: ::waft_foundation::Handle<Self>,
3420 app: &::waft_foundation::App,
3421 ) -> &$crate::TextSelectionGestureDetectorBuilderData {
3422 &app.get(self).$field
3423 }
3424 fn builder_data_mut(
3425 self: ::waft_foundation::Handle<Self>,
3426 app: &mut ::waft_foundation::App,
3427 ) -> &mut $crate::TextSelectionGestureDetectorBuilderData {
3428 &mut app.get_mut(self).$field
3429 }
3430 };
3431}
3432
3433pub trait TextSelectionGestureDetectorBuilder: Sized + 'static {
3435 fn builder_data(self: Handle<Self>, app: &App) -> &TextSelectionGestureDetectorBuilderData;
3437 fn builder_data_mut(
3439 self: Handle<Self>,
3440 app: &mut App,
3441 ) -> &mut TextSelectionGestureDetectorBuilderData;
3442
3443 fn on_tap_track_start(self: Handle<Self>, app: &mut App) {
3445 TextSelectionGestureDetectorBuilderBase::on_tap_track_start(self, app);
3446 }
3447
3448 fn on_tap_track_reset(self: Handle<Self>, app: &mut App) {
3450 TextSelectionGestureDetectorBuilderBase::on_tap_track_reset(self, app);
3451 }
3452
3453 fn on_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
3455 TextSelectionGestureDetectorBuilderBase::on_tap_down(self, app, details);
3456 }
3457
3458 fn on_force_press_start(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
3460 TextSelectionGestureDetectorBuilderBase::on_force_press_start(self, app, details);
3461 }
3462
3463 fn on_force_press_end(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
3465 TextSelectionGestureDetectorBuilderBase::on_force_press_end(self, app, details);
3466 }
3467
3468 fn on_user_tap_always_called(self: Handle<Self>, app: &App) -> bool {
3471 TextSelectionGestureDetectorBuilderBase::on_user_tap_always_called(self, app)
3472 }
3473
3474 fn on_user_tap(self: Handle<Self>, app: &mut App) {
3476 TextSelectionGestureDetectorBuilderBase::on_user_tap(self, app);
3477 }
3478
3479 fn on_single_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
3481 TextSelectionGestureDetectorBuilderBase::on_single_tap_up(self, app, details);
3482 }
3483
3484 fn on_single_tap_cancel(self: Handle<Self>, app: &mut App) {
3486 TextSelectionGestureDetectorBuilderBase::on_single_tap_cancel(self, app);
3487 }
3488
3489 fn on_single_long_tap_start(self: Handle<Self>, app: &mut App, details: LongPressStartDetails) {
3491 TextSelectionGestureDetectorBuilderBase::on_single_long_tap_start(self, app, details);
3492 }
3493
3494 fn on_single_long_tap_move_update(
3496 self: Handle<Self>,
3497 app: &mut App,
3498 details: LongPressMoveUpdateDetails,
3499 ) {
3500 TextSelectionGestureDetectorBuilderBase::on_single_long_tap_move_update(self, app, details);
3501 }
3502
3503 fn on_single_long_tap_end(self: Handle<Self>, app: &mut App, details: LongPressEndDetails) {
3505 TextSelectionGestureDetectorBuilderBase::on_single_long_tap_end(self, app, details);
3506 }
3507
3508 fn on_single_long_tap_cancel(self: Handle<Self>, app: &mut App) {
3510 TextSelectionGestureDetectorBuilderBase::on_single_long_tap_cancel(self, app);
3511 }
3512
3513 fn on_secondary_tap(self: Handle<Self>, app: &mut App) {
3515 TextSelectionGestureDetectorBuilderBase::on_secondary_tap(self, app);
3516 }
3517
3518 fn on_secondary_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
3520 TextSelectionGestureDetectorBuilderBase::on_secondary_tap_down(self, app, details);
3521 }
3522
3523 fn on_double_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
3525 TextSelectionGestureDetectorBuilderBase::on_double_tap_down(self, app, details);
3526 }
3527
3528 fn on_triple_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
3530 TextSelectionGestureDetectorBuilderBase::on_triple_tap_down(self, app, details);
3531 }
3532
3533 fn on_drag_selection_start(self: Handle<Self>, app: &mut App, details: TapDragStartDetails) {
3535 TextSelectionGestureDetectorBuilderBase::on_drag_selection_start(self, app, details);
3536 }
3537
3538 fn on_drag_selection_update(self: Handle<Self>, app: &mut App, details: TapDragUpdateDetails) {
3540 TextSelectionGestureDetectorBuilderBase::on_drag_selection_update(self, app, details);
3541 }
3542
3543 fn on_drag_selection_end(self: Handle<Self>, app: &mut App, details: TapDragEndDetails) {
3545 TextSelectionGestureDetectorBuilderBase::on_drag_selection_end(self, app, details);
3546 }
3547
3548 fn build_gesture_detector(
3551 self: Handle<Self>,
3552 app: &mut App,
3553 key: Option<KeyRef>,
3554 behavior: Option<HitTestBehavior>,
3555 child: WidgetRef,
3556 ) -> TextSelectionGestureDetector {
3557 TextSelectionGestureDetectorBuilderBase::build_gesture_detector(
3558 self, app, key, behavior, child,
3559 )
3560 }
3561}
3562
3563pub trait TextSelectionGestureDetectorBuilderBase: TextSelectionGestureDetectorBuilder {
3565 fn show_magnifier_if_supported_by_platform(
3568 self: Handle<Self>,
3569 app: &mut App,
3570 position_to_show: Offset,
3571 ) {
3572 match app.platform().target_platform() {
3573 TargetPlatform::Android | TargetPlatform::IOS => {
3574 self.editable_text(app)
3575 .show_magnifier(app, position_to_show);
3576 }
3577 TargetPlatform::Fuchsia
3578 | TargetPlatform::Linux
3579 | TargetPlatform::MacOS
3580 | TargetPlatform::Windows => {}
3581 }
3582 }
3583
3584 fn hide_magnifier_if_supported_by_platform(self: Handle<Self>, app: &mut App) {
3586 if !self.is_editable_text_mounted(app) {
3587 return;
3588 }
3589 match app.platform().target_platform() {
3590 TargetPlatform::Android | TargetPlatform::IOS => {
3591 self.editable_text(app).hide_magnifier(app);
3592 }
3593 TargetPlatform::Fuchsia
3594 | TargetPlatform::Linux
3595 | TargetPlatform::MacOS
3596 | TargetPlatform::Windows => {}
3597 }
3598 }
3599
3600 fn last_secondary_tap_was_on_selection(self: Handle<Self>, app: &mut App) -> bool {
3602 let render_editable = self.render_editable(app);
3603 debug_assert!(
3604 render_editable
3605 .last_secondary_tap_down_position(app)
3606 .is_some()
3607 );
3608 let Some(selection) = render_editable.selection(app) else {
3609 return false;
3610 };
3611 let position = render_editable.get_position_for_point(
3612 app,
3613 render_editable
3614 .last_secondary_tap_down_position(app)
3615 .expect("lastSecondaryTapDownPosition"),
3616 );
3617 selection.start() <= position.offset && selection.end() >= position.offset
3618 }
3619
3620 fn position_was_on_selection_exclusive(
3621 self: Handle<Self>,
3622 app: &mut App,
3623 text_position: TextPosition,
3624 ) -> bool {
3625 let Some(selection) = self.render_editable(app).selection(app) else {
3626 return false;
3627 };
3628 selection.start() < text_position.offset && selection.end() > text_position.offset
3629 }
3630
3631 fn position_was_on_selection_inclusive(
3632 self: Handle<Self>,
3633 app: &mut App,
3634 text_position: TextPosition,
3635 ) -> bool {
3636 let Some(selection) = self.render_editable(app).selection(app) else {
3637 return false;
3638 };
3639 selection.start() <= text_position.offset && selection.end() >= text_position.offset
3640 }
3641
3642 fn expand_selection(
3643 self: Handle<Self>,
3644 app: &mut App,
3645 offset: Offset,
3646 cause: SelectionChangedCause,
3647 from_selection: Option<TextSelection>,
3648 ) {
3649 let render_editable = self.render_editable(app);
3650 debug_assert!(render_editable.selection(app).is_some());
3651 let tapped_position = render_editable.get_position_for_point(app, offset);
3652 let selection = from_selection.unwrap_or_else(|| {
3653 render_editable
3654 .selection(app)
3655 .expect("expand_selection needs a selection")
3656 });
3657 let base_is_closer = (tapped_position.offset - selection.base_offset).abs()
3658 < (tapped_position.offset - selection.extent_offset).abs();
3659 let next_selection = selection
3660 .copy_with()
3661 .base_offset(if base_is_closer {
3662 selection.extent_offset
3663 } else {
3664 selection.base_offset
3665 })
3666 .extent_offset(tapped_position.offset);
3667 let editable = self.editable_text(app);
3668 let value = editable
3669 .text_editing_value(app)
3670 .copy_with()
3671 .selection(next_selection);
3672 editable.user_update_text_editing_value(app, value, cause);
3673 }
3674
3675 fn extend_selection(
3676 self: Handle<Self>,
3677 app: &mut App,
3678 offset: Offset,
3679 cause: SelectionChangedCause,
3680 ) {
3681 let render_editable = self.render_editable(app);
3682 debug_assert!(render_editable.selection(app).is_some());
3683 let tapped_position = render_editable.get_position_for_point(app, offset);
3684 let selection = render_editable
3685 .selection(app)
3686 .expect("extend_selection needs a selection");
3687 let next_selection = selection.copy_with().extent_offset(tapped_position.offset);
3688 let editable = self.editable_text(app);
3689 let value = editable
3690 .text_editing_value(app)
3691 .copy_with()
3692 .selection(next_selection);
3693 editable.user_update_text_editing_value(app, value, cause);
3694 }
3695
3696 fn should_show_selection_toolbar(self: Handle<Self>, app: &App) -> bool {
3698 self.builder_data(app).should_show_selection_toolbar
3699 }
3700
3701 fn should_show_selection_handles(self: Handle<Self>, app: &App) -> bool {
3703 self.builder_data(app).should_show_selection_handles
3704 }
3705
3706 fn editable_text(self: Handle<Self>, app: &mut App) -> Handle<EditableTextState> {
3709 let key = self.builder_data(app).delegate.editable_text_key(app);
3710 key.current_state::<EditableTextState>(app)
3711 .expect("editableTextKey.currentState")
3712 }
3713
3714 fn render_editable(self: Handle<Self>, app: &mut App) -> RenderHandle<RenderEditable> {
3717 self.editable_text(app).render_editable(app)
3718 }
3719
3720 fn is_editable_text_mounted(self: Handle<Self>, app: &mut App) -> bool {
3723 let key = self.builder_data(app).delegate.editable_text_key(app);
3724 key.current_context(app)
3725 .is_some_and(|context| context.mounted(app))
3726 }
3727
3728 fn scroll_position(self: Handle<Self>, app: &mut App) -> f64 {
3729 let key = self.builder_data(app).delegate.editable_text_key(app);
3730 let Some(context) = key.current_context(app) else {
3731 return 0.0;
3732 };
3733 Scrollable::maybe_of(app, context, None)
3734 .map(|scrollable| scrollable.position(app).pixels(app))
3735 .unwrap_or(0.0)
3736 }
3737
3738 fn scroll_direction(self: Handle<Self>, app: &mut App) -> Option<AxisDirection> {
3739 let key = self.builder_data(app).delegate.editable_text_key(app);
3740 let context = key.current_context(app)?;
3741 Some(
3742 Scrollable::maybe_of(app, context, None)?
3743 .widget(app)
3744 .axis_direction,
3745 )
3746 }
3747
3748 fn on_tap_track_start(self: Handle<Self>, app: &mut App) {
3750 let pressed = HardwareKeyboard::instance(app).logical_keys_pressed(app);
3751 let is_shift = pressed.contains(&LogicalKeyboardKey::SHIFT_LEFT)
3752 || pressed.contains(&LogicalKeyboardKey::SHIFT_RIGHT);
3753 self.builder_data_mut(app).is_shift_pressed = is_shift;
3754 }
3755
3756 fn on_tap_track_reset(self: Handle<Self>, app: &mut App) {
3758 self.builder_data_mut(app).is_shift_pressed = false;
3759 }
3760
3761 fn on_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
3763 if !self.builder_data(app).delegate.selection_enabled(app) {
3764 return;
3765 }
3766 let render_editable = self.render_editable(app);
3767 render_editable.handle_tap_down(
3768 app,
3769 &TapDownDetails::new(details.global_position, None, details.kind),
3770 );
3771 let kind = details.kind;
3772 let should_show = kind.is_none()
3773 || kind == Some(PointerDeviceKind::Touch)
3774 || kind == Some(PointerDeviceKind::Stylus);
3775 self.builder_data_mut(app).should_show_selection_toolbar = should_show;
3776 self.builder_data_mut(app).should_show_selection_handles = should_show;
3777
3778 let is_shift_pressed = self.builder_data(app).is_shift_pressed;
3779 let is_shift_pressed_valid = is_shift_pressed
3780 && self
3781 .render_editable(app)
3782 .selection(app)
3783 .is_some_and(|selection| selection.is_valid());
3784 match app.platform().target_platform() {
3785 TargetPlatform::Android => {}
3786 TargetPlatform::Fuchsia | TargetPlatform::IOS => {}
3787 TargetPlatform::MacOS => {
3788 self.editable_text(app).hide_toolbar(app, true);
3789 if is_shift_pressed_valid {
3790 let from_selection = if self.render_editable(app).has_focus(app) {
3791 None
3792 } else {
3793 Some(TextSelection::collapsed(0, TextAffinity::Downstream))
3794 };
3795 self.expand_selection(
3796 app,
3797 details.global_position,
3798 SelectionChangedCause::Tap,
3799 from_selection,
3800 );
3801 return;
3802 }
3803 self.render_editable(app)
3804 .select_position(app, SelectionChangedCause::Tap);
3805 }
3806 TargetPlatform::Linux | TargetPlatform::Windows => {
3807 self.editable_text(app).hide_toolbar(app, true);
3808 if is_shift_pressed_valid {
3809 self.extend_selection(app, details.global_position, SelectionChangedCause::Tap);
3810 return;
3811 }
3812 self.render_editable(app)
3813 .select_position(app, SelectionChangedCause::Tap);
3814 }
3815 }
3816 }
3817
3818 fn on_force_press_start(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
3820 debug_assert!(self.builder_data(app).delegate.force_press_enabled(app));
3821 self.builder_data_mut(app).should_show_selection_toolbar = true;
3822 if !self.builder_data(app).delegate.selection_enabled(app) {
3823 return;
3824 }
3825 self.render_editable(app).select_words_in_range(
3826 app,
3827 details.global_position,
3828 None,
3829 SelectionChangedCause::ForcePress,
3830 );
3831 let _ = self.editable_text(app).show_toolbar(app);
3832 }
3833
3834 fn on_force_press_end(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
3836 debug_assert!(self.builder_data(app).delegate.force_press_enabled(app));
3837 self.render_editable(app).select_words_in_range(
3838 app,
3839 details.global_position,
3840 None,
3841 SelectionChangedCause::ForcePress,
3842 );
3843 if self.should_show_selection_toolbar(app) {
3844 let _ = self.editable_text(app).show_toolbar(app);
3845 }
3846 }
3847
3848 fn on_user_tap_always_called(self: Handle<Self>, _app: &App) -> bool {
3851 false
3852 }
3853
3854 fn on_user_tap(self: Handle<Self>, _app: &mut App) {}
3856
3857 fn on_single_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
3859 if !self.builder_data(app).delegate.selection_enabled(app) {
3860 self.editable_text(app).request_keyboard(app);
3861 return;
3862 }
3863 let is_shift_pressed = self.builder_data(app).is_shift_pressed;
3864 let is_shift_pressed_valid = is_shift_pressed
3865 && self
3866 .render_editable(app)
3867 .selection(app)
3868 .is_some_and(|selection| selection.is_valid());
3869 match app.platform().target_platform() {
3870 TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {}
3871 TargetPlatform::Android => {
3872 self.editable_text(app).hide_toolbar(app, false);
3873 if is_shift_pressed_valid {
3874 self.extend_selection(app, details.global_position, SelectionChangedCause::Tap);
3875 return;
3876 }
3877 self.render_editable(app)
3878 .select_position(app, SelectionChangedCause::Tap);
3879 let _ = self
3880 .editable_text(app)
3881 .show_spell_check_suggestions_toolbar(app);
3882 }
3883 TargetPlatform::Fuchsia => {
3884 self.editable_text(app).hide_toolbar(app, false);
3885 if is_shift_pressed_valid {
3886 self.extend_selection(app, details.global_position, SelectionChangedCause::Tap);
3887 return;
3888 }
3889 self.render_editable(app)
3890 .select_position(app, SelectionChangedCause::Tap);
3891 }
3892 TargetPlatform::IOS => {
3893 if is_shift_pressed_valid {
3894 let from_selection = if self.render_editable(app).has_focus(app) {
3895 None
3896 } else {
3897 Some(TextSelection::collapsed(0, TextAffinity::Downstream))
3898 };
3899 self.expand_selection(
3900 app,
3901 details.global_position,
3902 SelectionChangedCause::Tap,
3903 from_selection,
3904 );
3905 return;
3906 }
3907 match details.kind {
3908 PointerDeviceKind::Mouse
3909 | PointerDeviceKind::Trackpad
3910 | PointerDeviceKind::Stylus
3911 | PointerDeviceKind::InvertedStylus => {
3912 self.render_editable(app)
3913 .select_position(app, SelectionChangedCause::Tap);
3914 self.editable_text(app).hide_toolbar(app, true);
3915 }
3916 PointerDeviceKind::Touch | PointerDeviceKind::Unknown => {
3917 let render_editable = self.render_editable(app);
3918 let previous_selection =
3919 render_editable.selection(app).unwrap_or_else(|| {
3920 self.editable_text(app).text_editing_value(app).selection
3921 });
3922 let text_position =
3923 render_editable.get_position_for_point(app, details.global_position);
3924 let is_affinity_the_same =
3925 text_position.affinity == previous_selection.affinity;
3926 let word_at_cursor_index_is_misspelled = self
3927 .editable_text(app)
3928 .find_suggestion_span_at_cursor_index(app, text_position.offset)
3929 .is_some();
3930 if word_at_cursor_index_is_misspelled {
3931 self.render_editable(app)
3932 .select_word(app, SelectionChangedCause::Tap);
3933 if previous_selection
3934 != self.editable_text(app).text_editing_value(app).selection
3935 {
3936 let _ = self
3937 .editable_text(app)
3938 .show_spell_check_suggestions_toolbar(app);
3939 } else {
3940 self.editable_text(app).toggle_toolbar(app, false);
3941 }
3942 } else if ((self.position_was_on_selection_exclusive(app, text_position)
3943 && !previous_selection.is_collapsed())
3944 || (self.position_was_on_selection_inclusive(app, text_position)
3945 && previous_selection.is_collapsed()
3946 && is_affinity_the_same
3947 && !self.render_editable(app).read_only(app)))
3948 && self.render_editable(app).has_focus(app)
3949 {
3950 self.editable_text(app).toggle_toolbar(app, false);
3951 } else {
3952 self.render_editable(app)
3953 .select_word_edge(app, SelectionChangedCause::Tap);
3954 if previous_selection
3955 == self.editable_text(app).text_editing_value(app).selection
3956 && self.render_editable(app).has_focus(app)
3957 && !self.render_editable(app).read_only(app)
3958 {
3959 self.editable_text(app).toggle_toolbar(app, false);
3960 } else {
3961 self.editable_text(app).hide_toolbar(app, false);
3962 }
3963 }
3964 }
3965 }
3966 }
3967 }
3968 self.editable_text(app).request_keyboard(app);
3969 }
3970
3971 fn on_single_tap_cancel(self: Handle<Self>, _app: &mut App) {}
3973
3974 fn on_single_long_tap_start(self: Handle<Self>, app: &mut App, details: LongPressStartDetails) {
3976 if !self.builder_data(app).delegate.selection_enabled(app) {
3977 return;
3978 }
3979 match app.platform().target_platform() {
3980 TargetPlatform::IOS | TargetPlatform::MacOS => {
3981 if !self.render_editable(app).has_focus(app) {
3982 self.builder_data_mut(app).long_press_started_without_focus = true;
3983 self.render_editable(app)
3984 .select_word(app, SelectionChangedCause::LongPress);
3985 } else if self.render_editable(app).read_only(app) {
3986 self.render_editable(app)
3987 .select_word(app, SelectionChangedCause::LongPress);
3988 let context = self.editable_text(app).context(app);
3989 if self.editable_text(app).mounted(app) {
3990 Feedback::for_long_press(app, context);
3991 }
3992 } else {
3993 self.render_editable(app).select_position_at(
3994 app,
3995 details.global_position,
3996 None,
3997 SelectionChangedCause::LongPress,
3998 );
3999 }
4000 }
4001 TargetPlatform::Android
4002 | TargetPlatform::Fuchsia
4003 | TargetPlatform::Linux
4004 | TargetPlatform::Windows => {
4005 self.render_editable(app)
4006 .select_word(app, SelectionChangedCause::LongPress);
4007 let context = self.editable_text(app).context(app);
4008 if self.editable_text(app).mounted(app) {
4009 Feedback::for_long_press(app, context);
4010 }
4011 }
4012 }
4013 self.show_magnifier_if_supported_by_platform(app, details.global_position);
4014 let pixels = self.render_editable(app).offset(app).pixels(app);
4015 self.builder_data_mut(app).drag_start_viewport_offset = pixels;
4016 self.builder_data_mut(app).drag_start_scroll_offset = self.scroll_position(app);
4017 }
4018
4019 fn on_single_long_tap_move_update(
4021 self: Handle<Self>,
4022 app: &mut App,
4023 details: LongPressMoveUpdateDetails,
4024 ) {
4025 if !self.builder_data(app).delegate.selection_enabled(app) {
4026 return;
4027 }
4028 let drag_start_viewport = self.builder_data(app).drag_start_viewport_offset;
4029 let drag_start_scroll = self.builder_data(app).drag_start_scroll_offset;
4030 let render_editable = self.render_editable(app);
4031 let editable_offset = if render_editable.max_lines(app) == Some(1) {
4032 Offset::new(
4033 render_editable.offset(app).pixels(app) - drag_start_viewport,
4034 0.0,
4035 )
4036 } else {
4037 Offset::new(
4038 0.0,
4039 render_editable.offset(app).pixels(app) - drag_start_viewport,
4040 )
4041 };
4042 let scroll_position = self.scroll_position(app);
4043 let scrollable_offset =
4044 match axis_direction_to_axis(self.scroll_direction(app).unwrap_or(AxisDirection::Left))
4045 {
4046 Axis::Horizontal => Offset::new(scroll_position - drag_start_scroll, 0.0),
4047 Axis::Vertical => Offset::new(0.0, scroll_position - drag_start_scroll),
4048 };
4049 match app.platform().target_platform() {
4050 TargetPlatform::IOS | TargetPlatform::MacOS => {
4051 if self.builder_data(app).long_press_started_without_focus
4052 || self.render_editable(app).read_only(app)
4053 {
4054 self.render_editable(app).select_words_in_range(
4055 app,
4056 details.global_position
4057 - details.offset_from_origin
4058 - editable_offset
4059 - scrollable_offset,
4060 Some(details.global_position),
4061 SelectionChangedCause::LongPress,
4062 );
4063 } else {
4064 self.render_editable(app).select_position_at(
4065 app,
4066 details.global_position,
4067 None,
4068 SelectionChangedCause::LongPress,
4069 );
4070 }
4071 }
4072 TargetPlatform::Android
4073 | TargetPlatform::Fuchsia
4074 | TargetPlatform::Linux
4075 | TargetPlatform::Windows => {
4076 self.render_editable(app).select_words_in_range(
4077 app,
4078 details.global_position
4079 - details.offset_from_origin
4080 - editable_offset
4081 - scrollable_offset,
4082 Some(details.global_position),
4083 SelectionChangedCause::LongPress,
4084 );
4085 }
4086 }
4087 self.show_magnifier_if_supported_by_platform(app, details.global_position);
4088 }
4089
4090 fn on_single_long_tap_end(self: Handle<Self>, app: &mut App, _details: LongPressEndDetails) {
4092 self.on_single_long_tap_end_or_cancel(app);
4093 if self.should_show_selection_toolbar(app) {
4094 let _ = self.editable_text(app).show_toolbar(app);
4095 }
4096 }
4097
4098 fn on_single_long_tap_cancel(self: Handle<Self>, app: &mut App) {
4100 self.on_single_long_tap_end_or_cancel(app);
4101 }
4102
4103 fn on_secondary_tap(self: Handle<Self>, app: &mut App) {
4105 if !self.builder_data(app).delegate.selection_enabled(app) {
4106 return;
4107 }
4108 match app.platform().target_platform() {
4109 TargetPlatform::IOS | TargetPlatform::MacOS => {
4110 if !self.last_secondary_tap_was_on_selection(app)
4111 || !self.render_editable(app).has_focus(app)
4112 {
4113 self.render_editable(app)
4114 .select_word(app, SelectionChangedCause::Tap);
4115 }
4116 if self.should_show_selection_toolbar(app) {
4117 self.editable_text(app).hide_toolbar(app, true);
4118 let _ = self.editable_text(app).show_toolbar(app);
4119 }
4120 }
4121 TargetPlatform::Android
4122 | TargetPlatform::Fuchsia
4123 | TargetPlatform::Linux
4124 | TargetPlatform::Windows => {
4125 if !self.render_editable(app).has_focus(app) {
4126 self.render_editable(app)
4127 .select_position(app, SelectionChangedCause::Tap);
4128 }
4129 self.editable_text(app).toggle_toolbar(app, true);
4130 }
4131 }
4132 }
4133
4134 fn on_secondary_tap_down(self: Handle<Self>, app: &mut App, details: TapDownDetails) {
4136 self.render_editable(app).handle_secondary_tap_down(
4137 app,
4138 &TapDownDetails::new(details.global_position, None, details.kind),
4139 );
4140 self.builder_data_mut(app).should_show_selection_toolbar = true;
4141 self.builder_data_mut(app).should_show_selection_handles = details.kind.is_none()
4142 || details.kind == Some(PointerDeviceKind::Touch)
4143 || details.kind == Some(PointerDeviceKind::Stylus);
4144 }
4145
4146 fn on_double_tap_down(self: Handle<Self>, app: &mut App, _details: TapDragDownDetails) {
4148 if self.builder_data(app).delegate.selection_enabled(app) {
4149 self.render_editable(app)
4150 .select_word(app, SelectionChangedCause::DoubleTap);
4151 if self.should_show_selection_toolbar(app) {
4152 let _ = self.editable_text(app).show_toolbar(app);
4153 }
4154 }
4155 }
4156
4157 fn on_single_long_tap_end_or_cancel(self: Handle<Self>, app: &mut App) {
4158 self.hide_magnifier_if_supported_by_platform(app);
4159 self.builder_data_mut(app).long_press_started_without_focus = false;
4160 self.builder_data_mut(app).drag_start_viewport_offset = 0.0;
4161 self.builder_data_mut(app).drag_start_scroll_offset = 0.0;
4162 }
4163
4164 fn select_paragraphs_in_range(
4165 self: Handle<Self>,
4166 app: &mut App,
4167 from: Offset,
4168 to: Option<Offset>,
4169 cause: Option<SelectionChangedCause>,
4170 ) {
4171 let text = self.editable_text(app).text_editing_value(app).text;
4172 select_text_boundaries_in_range(self, app, BoundaryKind::Paragraph(&text), from, to, cause);
4173 }
4174
4175 fn select_lines_in_range(
4176 self: Handle<Self>,
4177 app: &mut App,
4178 from: Offset,
4179 to: Option<Offset>,
4180 cause: Option<SelectionChangedCause>,
4181 ) {
4182 select_text_boundaries_in_range(self, app, BoundaryKind::Line, from, to, cause);
4183 }
4184
4185 fn on_triple_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
4187 if !self.builder_data(app).delegate.selection_enabled(app) {
4188 return;
4189 }
4190 if self.render_editable(app).max_lines(app) == Some(1) {
4191 self.editable_text(app)
4192 .select_all(app, SelectionChangedCause::Tap);
4193 } else {
4194 match app.platform().target_platform() {
4195 TargetPlatform::Android
4196 | TargetPlatform::Fuchsia
4197 | TargetPlatform::IOS
4198 | TargetPlatform::MacOS
4199 | TargetPlatform::Windows => {
4200 self.select_paragraphs_in_range(
4201 app,
4202 details.global_position,
4203 None,
4204 Some(SelectionChangedCause::Tap),
4205 );
4206 }
4207 TargetPlatform::Linux => {
4208 self.select_lines_in_range(
4209 app,
4210 details.global_position,
4211 None,
4212 Some(SelectionChangedCause::Tap),
4213 );
4214 }
4215 }
4216 }
4217 if self.should_show_selection_toolbar(app) {
4218 let _ = self.editable_text(app).show_toolbar(app);
4219 }
4220 }
4221
4222 fn on_drag_selection_start(self: Handle<Self>, app: &mut App, details: TapDragStartDetails) {
4224 if !self.builder_data(app).delegate.selection_enabled(app) {
4225 return;
4226 }
4227 let kind = details.kind;
4228 let should_show = kind.is_none()
4229 || kind == Some(PointerDeviceKind::Touch)
4230 || kind == Some(PointerDeviceKind::Stylus);
4231 self.builder_data_mut(app).should_show_selection_toolbar = should_show;
4232 self.builder_data_mut(app).should_show_selection_handles = should_show;
4233 self.builder_data_mut(app).drag_start_selection = self.render_editable(app).selection(app);
4234 self.builder_data_mut(app).drag_start_scroll_offset = self.scroll_position(app);
4235 self.builder_data_mut(app).drag_start_viewport_offset =
4236 self.render_editable(app).offset(app).pixels(app);
4237
4238 if TextSelectionGestureDetectorState::get_effective_consecutive_tap_count(
4239 app,
4240 details.consecutive_tap_count,
4241 ) > 1
4242 {
4243 return;
4244 }
4245
4246 let selection = self.render_editable(app).selection(app);
4247 if self.builder_data(app).is_shift_pressed && selection.is_some_and(|s| s.is_valid()) {
4248 match app.platform().target_platform() {
4249 TargetPlatform::IOS | TargetPlatform::MacOS => {
4250 self.expand_selection(
4251 app,
4252 details.global_position,
4253 SelectionChangedCause::Drag,
4254 None,
4255 );
4256 }
4257 TargetPlatform::Android
4258 | TargetPlatform::Fuchsia
4259 | TargetPlatform::Linux
4260 | TargetPlatform::Windows => {
4261 self.extend_selection(
4262 app,
4263 details.global_position,
4264 SelectionChangedCause::Drag,
4265 );
4266 }
4267 }
4268 } else {
4269 match app.platform().target_platform() {
4270 TargetPlatform::IOS => match details.kind {
4271 Some(PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad) => {
4272 self.render_editable(app).select_position_at(
4273 app,
4274 details.global_position,
4275 None,
4276 SelectionChangedCause::Drag,
4277 );
4278 }
4279 Some(
4280 PointerDeviceKind::Stylus
4281 | PointerDeviceKind::InvertedStylus
4282 | PointerDeviceKind::Touch
4283 | PointerDeviceKind::Unknown,
4284 )
4285 | None => {}
4286 },
4287 TargetPlatform::Android | TargetPlatform::Fuchsia => match details.kind {
4288 Some(PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad) => {
4289 self.render_editable(app).select_position_at(
4290 app,
4291 details.global_position,
4292 None,
4293 SelectionChangedCause::Drag,
4294 );
4295 }
4296 Some(
4297 PointerDeviceKind::Stylus
4298 | PointerDeviceKind::InvertedStylus
4299 | PointerDeviceKind::Touch
4300 | PointerDeviceKind::Unknown,
4301 ) if self.render_editable(app).has_focus(app) => {
4302 self.render_editable(app).select_position_at(
4303 app,
4304 details.global_position,
4305 None,
4306 SelectionChangedCause::Drag,
4307 );
4308 self.show_magnifier_if_supported_by_platform(app, details.global_position);
4309 }
4310 _ => {}
4311 },
4312 TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
4313 self.render_editable(app).select_position_at(
4314 app,
4315 details.global_position,
4316 None,
4317 SelectionChangedCause::Drag,
4318 );
4319 }
4320 }
4321 }
4322 }
4323
4324 fn on_drag_selection_update(self: Handle<Self>, app: &mut App, details: TapDragUpdateDetails) {
4326 if !self.builder_data(app).delegate.selection_enabled(app) {
4327 return;
4328 }
4329 if !self.builder_data(app).is_shift_pressed {
4330 let drag_start_viewport = self.builder_data(app).drag_start_viewport_offset;
4331 let drag_start_scroll = self.builder_data(app).drag_start_scroll_offset;
4332 let render_editable = self.render_editable(app);
4333 let editable_offset = if render_editable.max_lines(app) == Some(1) {
4334 Offset::new(
4335 render_editable.offset(app).pixels(app) - drag_start_viewport,
4336 0.0,
4337 )
4338 } else {
4339 Offset::new(
4340 0.0,
4341 render_editable.offset(app).pixels(app) - drag_start_viewport,
4342 )
4343 };
4344 let scroll_position = self.scroll_position(app);
4345 let scrollable_offset = match axis_direction_to_axis(
4346 self.scroll_direction(app).unwrap_or(AxisDirection::Left),
4347 ) {
4348 Axis::Horizontal => Offset::new(scroll_position - drag_start_scroll, 0.0),
4349 Axis::Vertical => Offset::new(0.0, scroll_position - drag_start_scroll),
4350 };
4351 let drag_start_global_position = details.global_position - details.offset_from_origin;
4352 let consecutive =
4353 TextSelectionGestureDetectorState::get_effective_consecutive_tap_count(
4354 app,
4355 details.consecutive_tap_count,
4356 );
4357 if consecutive == 2 {
4358 self.render_editable(app).select_words_in_range(
4359 app,
4360 drag_start_global_position - editable_offset - scrollable_offset,
4361 Some(details.global_position),
4362 SelectionChangedCause::Drag,
4363 );
4364 match details.kind {
4365 Some(
4366 PointerDeviceKind::Stylus
4367 | PointerDeviceKind::InvertedStylus
4368 | PointerDeviceKind::Touch
4369 | PointerDeviceKind::Unknown,
4370 ) => {
4371 self.show_magnifier_if_supported_by_platform(app, details.global_position);
4372 }
4373 Some(PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad) | None => {}
4374 }
4375 return;
4376 }
4377 if consecutive == 3 {
4378 match app.platform().target_platform() {
4379 TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
4380 match details.kind {
4381 Some(PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad) => {
4382 self.select_paragraphs_in_range(
4383 app,
4384 drag_start_global_position
4385 - editable_offset
4386 - scrollable_offset,
4387 Some(details.global_position),
4388 Some(SelectionChangedCause::Drag),
4389 );
4390 }
4391 Some(
4392 PointerDeviceKind::Stylus
4393 | PointerDeviceKind::InvertedStylus
4394 | PointerDeviceKind::Touch
4395 | PointerDeviceKind::Unknown,
4396 )
4397 | None => {}
4398 }
4399 return;
4400 }
4401 TargetPlatform::Linux => {
4402 self.select_lines_in_range(
4403 app,
4404 drag_start_global_position - editable_offset - scrollable_offset,
4405 Some(details.global_position),
4406 Some(SelectionChangedCause::Drag),
4407 );
4408 return;
4409 }
4410 TargetPlatform::Windows | TargetPlatform::MacOS => {
4411 self.select_paragraphs_in_range(
4412 app,
4413 drag_start_global_position - editable_offset - scrollable_offset,
4414 Some(details.global_position),
4415 Some(SelectionChangedCause::Drag),
4416 );
4417 return;
4418 }
4419 }
4420 }
4421 match app.platform().target_platform() {
4422 TargetPlatform::IOS => match details.kind {
4423 Some(PointerDeviceKind::Mouse | PointerDeviceKind::Trackpad) => {
4424 self.render_editable(app).select_position_at(
4425 app,
4426 drag_start_global_position - editable_offset - scrollable_offset,
4427 Some(details.global_position),
4428 SelectionChangedCause::Drag,
4429 );
4430 }
4431 Some(
4432 PointerDeviceKind::Stylus
4433 | PointerDeviceKind::InvertedStylus
4434 | PointerDeviceKind::Touch
4435 | PointerDeviceKind::Unknown,
4436 )
4437 | None => {}
4438 },
4439 TargetPlatform::Android | TargetPlatform::Fuchsia => match details.kind {
4440 Some(
4441 PointerDeviceKind::Mouse
4442 | PointerDeviceKind::Trackpad
4443 | PointerDeviceKind::Stylus
4444 | PointerDeviceKind::InvertedStylus,
4445 ) => {
4446 self.render_editable(app).select_position_at(
4447 app,
4448 drag_start_global_position - editable_offset - scrollable_offset,
4449 Some(details.global_position),
4450 SelectionChangedCause::Drag,
4451 );
4452 }
4453 Some(PointerDeviceKind::Touch | PointerDeviceKind::Unknown)
4454 if self.render_editable(app).has_focus(app) =>
4455 {
4456 self.render_editable(app).select_position_at(
4457 app,
4458 details.global_position,
4459 None,
4460 SelectionChangedCause::Drag,
4461 );
4462 self.show_magnifier_if_supported_by_platform(app, details.global_position);
4463 }
4464 _ => {}
4465 },
4466 TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
4467 self.render_editable(app).select_position_at(
4468 app,
4469 drag_start_global_position - editable_offset - scrollable_offset,
4470 Some(details.global_position),
4471 SelectionChangedCause::Drag,
4472 );
4473 }
4474 }
4475 return;
4476 }
4477
4478 let drag_start = self.builder_data(app).drag_start_selection;
4479 let platform = app.platform().target_platform();
4480 if drag_start.is_some_and(|s| s.is_collapsed())
4481 || (platform != TargetPlatform::IOS && platform != TargetPlatform::MacOS)
4482 {
4483 self.extend_selection(app, details.global_position, SelectionChangedCause::Drag);
4484 return;
4485 }
4486 let drag_start = drag_start.expect("shift-drag keeps the start selection");
4487 let selection = self.editable_text(app).text_editing_value(app).selection;
4488 let next_extent = self
4489 .render_editable(app)
4490 .get_position_for_point(app, details.global_position);
4491 let is_shift_tap_drag_selection_forward = drag_start.base_offset < drag_start.extent_offset;
4492 let is_inverted = if is_shift_tap_drag_selection_forward {
4493 next_extent.offset < drag_start.base_offset
4494 } else {
4495 next_extent.offset > drag_start.base_offset
4496 };
4497 if is_inverted && selection.base_offset == drag_start.base_offset {
4498 let editable = self.editable_text(app);
4499 let value = editable
4500 .text_editing_value(app)
4501 .copy_with()
4502 .selection(TextSelection::new(
4503 drag_start.extent_offset,
4504 next_extent.offset,
4505 ));
4506 editable.user_update_text_editing_value(app, value, SelectionChangedCause::Drag);
4507 } else if !is_inverted
4508 && next_extent.offset != drag_start.base_offset
4509 && selection.base_offset != drag_start.base_offset
4510 {
4511 let editable = self.editable_text(app);
4512 let value = editable
4513 .text_editing_value(app)
4514 .copy_with()
4515 .selection(TextSelection::new(
4516 drag_start.base_offset,
4517 next_extent.offset,
4518 ));
4519 editable.user_update_text_editing_value(app, value, SelectionChangedCause::Drag);
4520 } else {
4521 self.extend_selection(app, details.global_position, SelectionChangedCause::Drag);
4522 }
4523 }
4524
4525 fn on_drag_selection_end(self: Handle<Self>, app: &mut App, details: TapDragEndDetails) {
4527 if self.should_show_selection_toolbar(app)
4528 && TextSelectionGestureDetectorState::get_effective_consecutive_tap_count(
4529 app,
4530 details.consecutive_tap_count,
4531 ) == 2
4532 {
4533 let _ = self.editable_text(app).show_toolbar(app);
4534 }
4535 if self.builder_data(app).is_shift_pressed {
4536 self.builder_data_mut(app).drag_start_selection = None;
4537 }
4538 self.hide_magnifier_if_supported_by_platform(app);
4539 }
4540
4541 fn build_gesture_detector(
4544 self: Handle<Self>,
4545 app: &mut App,
4546 key: Option<KeyRef>,
4547 behavior: Option<HitTestBehavior>,
4548 child: WidgetRef,
4549 ) -> TextSelectionGestureDetector {
4550 let this = self.keep(app);
4552 let force_press = self.builder_data(app).delegate.force_press_enabled(app);
4553 let mut detector = TextSelectionGestureDetector::new(child)
4554 .on_tap_track_start(Listener::new({
4555 let this = this.clone();
4556 move |app| {
4557 TextSelectionGestureDetectorBuilder::on_tap_track_start(this.handle(), app)
4558 }
4559 }))
4560 .on_tap_track_reset(Listener::new({
4561 let this = this.clone();
4562 move |app| {
4563 TextSelectionGestureDetectorBuilder::on_tap_track_reset(this.handle(), app)
4564 }
4565 }))
4566 .on_tap_down(Rc::new({
4567 let this = this.clone();
4568 move |app, details| {
4569 TextSelectionGestureDetectorBuilder::on_tap_down(this.handle(), app, details)
4570 }
4571 }))
4572 .on_secondary_tap(Listener::new({
4573 let this = this.clone();
4574 move |app| TextSelectionGestureDetectorBuilder::on_secondary_tap(this.handle(), app)
4575 }))
4576 .on_secondary_tap_down(Rc::new({
4577 let this = this.clone();
4578 move |app, details| {
4579 TextSelectionGestureDetectorBuilder::on_secondary_tap_down(
4580 this.handle(),
4581 app,
4582 details,
4583 )
4584 }
4585 }))
4586 .on_single_tap_up(Rc::new({
4587 let this = this.clone();
4588 move |app, details| {
4589 TextSelectionGestureDetectorBuilder::on_single_tap_up(
4590 this.handle(),
4591 app,
4592 details,
4593 )
4594 }
4595 }))
4596 .on_single_tap_cancel(Listener::new({
4597 let this = this.clone();
4598 move |app| {
4599 TextSelectionGestureDetectorBuilder::on_single_tap_cancel(this.handle(), app)
4600 }
4601 }))
4602 .on_user_tap(Listener::new({
4603 let this = this.clone();
4604 move |app| TextSelectionGestureDetectorBuilder::on_user_tap(this.handle(), app)
4605 }))
4606 .on_single_long_tap_start(Rc::new({
4607 let this = this.clone();
4608 move |app, details| {
4609 TextSelectionGestureDetectorBuilder::on_single_long_tap_start(
4610 this.handle(),
4611 app,
4612 details,
4613 )
4614 }
4615 }))
4616 .on_single_long_tap_move_update(Rc::new({
4617 let this = this.clone();
4618 move |app, details| {
4619 TextSelectionGestureDetectorBuilder::on_single_long_tap_move_update(
4620 this.handle(),
4621 app,
4622 details,
4623 )
4624 }
4625 }))
4626 .on_single_long_tap_end(Rc::new({
4627 let this = this.clone();
4628 move |app, details| {
4629 TextSelectionGestureDetectorBuilder::on_single_long_tap_end(
4630 this.handle(),
4631 app,
4632 details,
4633 )
4634 }
4635 }))
4636 .on_single_long_tap_cancel(Listener::new({
4637 let this = this.clone();
4638 move |app| {
4639 TextSelectionGestureDetectorBuilder::on_single_long_tap_cancel(
4640 this.handle(),
4641 app,
4642 )
4643 }
4644 }))
4645 .on_double_tap_down(Rc::new({
4646 let this = this.clone();
4647 move |app, details| {
4648 TextSelectionGestureDetectorBuilder::on_double_tap_down(
4649 this.handle(),
4650 app,
4651 details,
4652 )
4653 }
4654 }))
4655 .on_triple_tap_down(Rc::new({
4656 let this = this.clone();
4657 move |app, details| {
4658 TextSelectionGestureDetectorBuilder::on_triple_tap_down(
4659 this.handle(),
4660 app,
4661 details,
4662 )
4663 }
4664 }))
4665 .on_drag_selection_start(Rc::new({
4666 let this = this.clone();
4667 move |app, details| {
4668 TextSelectionGestureDetectorBuilder::on_drag_selection_start(
4669 this.handle(),
4670 app,
4671 details,
4672 )
4673 }
4674 }))
4675 .on_drag_selection_update(Rc::new({
4676 let this = this.clone();
4677 move |app, details| {
4678 TextSelectionGestureDetectorBuilder::on_drag_selection_update(
4679 this.handle(),
4680 app,
4681 details,
4682 )
4683 }
4684 }))
4685 .on_drag_selection_end(Rc::new({
4686 let this = this.clone();
4687 move |app, details| {
4688 TextSelectionGestureDetectorBuilder::on_drag_selection_end(
4689 this.handle(),
4690 app,
4691 details,
4692 )
4693 }
4694 }))
4695 .on_user_tap_always_called(
4696 TextSelectionGestureDetectorBuilder::on_user_tap_always_called(self, app),
4697 );
4698 if force_press {
4699 detector = detector
4700 .on_force_press_start(Rc::new({
4701 let this = this.clone();
4702 move |app, details| {
4703 TextSelectionGestureDetectorBuilder::on_force_press_start(
4704 this.handle(),
4705 app,
4706 details,
4707 )
4708 }
4709 }))
4710 .on_force_press_end(Rc::new({
4711 let this = this.clone();
4712 move |app, details| {
4713 TextSelectionGestureDetectorBuilder::on_force_press_end(
4714 this.handle(),
4715 app,
4716 details,
4717 )
4718 }
4719 }));
4720 }
4721 if let Some(key) = key {
4722 detector = detector.key(key);
4723 }
4724 if let Some(behavior) = behavior {
4725 detector = detector.behavior(behavior);
4726 }
4727 detector
4728 }
4729}
4730
4731impl<T: TextSelectionGestureDetectorBuilder> TextSelectionGestureDetectorBuilderBase for T {}
4732
4733#[derive(Clone, Copy)]
4734enum BoundaryKind<'a> {
4735 Paragraph(&'a str),
4736 Line,
4737}
4738
4739impl BoundaryKind<'_> {
4740 fn leading(
4741 self,
4742 app: &mut App,
4743 render_editable: RenderHandle<RenderEditable>,
4744 position: i32,
4745 ) -> Option<i32> {
4746 match self {
4747 BoundaryKind::Paragraph(text) => paragraph_leading(text, position),
4748 BoundaryKind::Line => {
4749 let range =
4750 render_editable.get_line_at_offset(app, TextPosition::new(position.max(0)));
4751 Some(range.start())
4752 }
4753 }
4754 }
4755
4756 fn trailing(
4757 self,
4758 app: &mut App,
4759 render_editable: RenderHandle<RenderEditable>,
4760 position: i32,
4761 ) -> Option<i32> {
4762 match self {
4763 BoundaryKind::Paragraph(text) => paragraph_trailing(text, position),
4764 BoundaryKind::Line => {
4765 let range =
4766 render_editable.get_line_at_offset(app, TextPosition::new(position.max(0)));
4767 Some(range.end())
4768 }
4769 }
4770 }
4771}
4772
4773fn move_to_text_boundary<T: TextSelectionGestureDetectorBuilder>(
4774 this: Handle<T>,
4775 app: &mut App,
4776 extent: TextPosition,
4777 boundary: BoundaryKind<'_>,
4778) -> TextRange {
4779 debug_assert!(extent.offset >= 0);
4780 let text_len = utf16_len_for_boundary(&this.editable_text(app).text_editing_value(app).text);
4781 let render_editable = this.render_editable(app);
4782 let start_offset = if extent.offset == text_len {
4783 extent.offset - 1
4784 } else {
4785 extent.offset
4786 };
4787 let start = boundary
4788 .leading(app, render_editable, start_offset)
4789 .unwrap_or(0);
4790 let end = boundary
4791 .trailing(app, render_editable, extent.offset)
4792 .unwrap_or(text_len);
4793 TextRange::new(start, end)
4794}
4795
4796fn select_text_boundaries_in_range<T: TextSelectionGestureDetectorBuilder>(
4797 this: Handle<T>,
4798 app: &mut App,
4799 boundary: BoundaryKind<'_>,
4800 from: Offset,
4801 to: Option<Offset>,
4802 cause: Option<SelectionChangedCause>,
4803) {
4804 let from_position = this.render_editable(app).get_position_for_point(app, from);
4805 let from_range = move_to_text_boundary(this, app, from_position, boundary);
4806 let to_position = match to {
4807 None => from_position,
4808 Some(to) => this.render_editable(app).get_position_for_point(app, to),
4809 };
4810 let to_range = if to_position == from_position {
4811 from_range
4812 } else {
4813 move_to_text_boundary(this, app, to_position, boundary)
4814 };
4815 let is_from_boundary_before_to_boundary = from_range.start < to_range.end;
4816 let new_selection = if is_from_boundary_before_to_boundary {
4817 TextSelection::new(from_range.start, to_range.end)
4818 } else {
4819 TextSelection::new(from_range.end, to_range.start)
4820 };
4821 let editable = this.editable_text(app);
4822 let value = editable
4823 .text_editing_value(app)
4824 .copy_with()
4825 .selection(new_selection);
4826 if let Some(cause) = cause {
4827 editable.user_update_text_editing_value(app, value, cause);
4828 } else {
4829 editable.user_update_text_editing_value(app, value, SelectionChangedCause::Tap);
4830 }
4831}
4832
4833fn utf16_len_for_boundary(text: &str) -> i32 {
4834 text.encode_utf16().count() as i32
4835}
4836
4837fn paragraph_leading(text: &str, position: i32) -> Option<i32> {
4838 let units: Vec<u16> = text.encode_utf16().collect();
4839 if position < 0 || units.is_empty() {
4840 return None;
4841 }
4842 if position >= units.len() as i32 {
4843 return Some(units.len() as i32);
4844 }
4845 if position == 0 {
4846 return Some(0);
4847 }
4848 let mut index = position;
4849 if index > 1 && units[index as usize] == 0x0A && units[index as usize - 1] == 0x0D {
4850 index -= 2;
4851 } else if is_line_terminator(units[index as usize] as i32) {
4852 index -= 1;
4853 }
4854 while index > 0 {
4855 if is_line_terminator(units[index as usize] as i32) {
4856 return Some(index + 1);
4857 }
4858 index -= 1;
4859 }
4860 Some(index.max(0))
4861}
4862
4863fn paragraph_trailing(text: &str, position: i32) -> Option<i32> {
4864 let units: Vec<u16> = text.encode_utf16().collect();
4865 if position >= units.len() as i32 || units.is_empty() {
4866 return None;
4867 }
4868 if position < 0 {
4869 return Some(0);
4870 }
4871 let mut index = position;
4872 while !is_line_terminator(units[index as usize] as i32) {
4873 index += 1;
4874 if index == units.len() as i32 {
4875 return Some(index);
4876 }
4877 }
4878 Some(
4879 if index < units.len() as i32 - 1
4880 && units[index as usize] == 0x0D
4881 && units[index as usize + 1] == 0x0A
4882 {
4883 index + 2
4884 } else {
4885 index + 1
4886 },
4887 )
4888}
4889
4890#[derive(Clone)]
4892pub struct TextSelectionGestureDetector {
4893 pub key: Option<KeyRef>,
4894 pub on_tap_track_start: Option<Listener>,
4895 pub on_tap_track_reset: Option<Listener>,
4896 pub on_tap_down: Option<GestureTapDragDownCallback>,
4897 pub on_force_press_start: Option<GestureForcePressStartCallback>,
4898 pub on_force_press_end: Option<GestureForcePressEndCallback>,
4899 pub on_secondary_tap: Option<GestureTapCallback>,
4900 pub on_secondary_tap_down: Option<GestureTapDownCallback>,
4901 pub on_single_tap_up: Option<GestureTapDragUpCallback>,
4902 pub on_single_tap_cancel: Option<GestureCancelCallback>,
4903 pub on_user_tap: Option<GestureTapCallback>,
4904 pub on_single_long_tap_start: Option<GestureLongPressStartCallback>,
4905 pub on_single_long_tap_move_update: Option<GestureLongPressMoveUpdateCallback>,
4906 pub on_single_long_tap_end: Option<GestureLongPressEndCallback>,
4907 pub on_single_long_tap_cancel: Option<GestureLongPressCancelCallback>,
4908 pub on_double_tap_down: Option<GestureTapDragDownCallback>,
4909 pub on_triple_tap_down: Option<GestureTapDragDownCallback>,
4910 pub on_drag_selection_start: Option<GestureTapDragStartCallback>,
4911 pub on_drag_selection_update: Option<GestureTapDragUpdateCallback>,
4912 pub on_drag_selection_end: Option<GestureTapDragEndCallback>,
4913 pub on_user_tap_always_called: bool,
4914 pub behavior: Option<HitTestBehavior>,
4915 pub child: WidgetRef,
4916}
4917
4918impl Debug for TextSelectionGestureDetector {
4919 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4920 f.debug_struct("TextSelectionGestureDetector")
4921 .field("onUserTapAlwaysCalled", &self.on_user_tap_always_called)
4922 .field("behavior", &self.behavior)
4923 .finish_non_exhaustive()
4924 }
4925}
4926
4927impl TextSelectionGestureDetector {
4928 #[cfg_attr(debug_assertions, track_caller)]
4930 pub fn new<K>(child: impl IntoWidget<K>) -> TextSelectionGestureDetector {
4931 TextSelectionGestureDetector {
4932 key: None,
4933 on_tap_track_start: None,
4934 on_tap_track_reset: None,
4935 on_tap_down: None,
4936 on_force_press_start: None,
4937 on_force_press_end: None,
4938 on_secondary_tap: None,
4939 on_secondary_tap_down: None,
4940 on_single_tap_up: None,
4941 on_single_tap_cancel: None,
4942 on_user_tap: None,
4943 on_single_long_tap_start: None,
4944 on_single_long_tap_move_update: None,
4945 on_single_long_tap_end: None,
4946 on_single_long_tap_cancel: None,
4947 on_double_tap_down: None,
4948 on_triple_tap_down: None,
4949 on_drag_selection_start: None,
4950 on_drag_selection_update: None,
4951 on_drag_selection_end: None,
4952 on_user_tap_always_called: false,
4953 behavior: None,
4954 child: child.into_widget(),
4955 }
4956 }
4957
4958 pub fn key(mut self, key: KeyRef) -> TextSelectionGestureDetector {
4960 self.key = Some(key);
4961 self
4962 }
4963
4964 pub fn on_tap_track_start(mut self, callback: Listener) -> TextSelectionGestureDetector {
4966 self.on_tap_track_start = Some(callback);
4967 self
4968 }
4969
4970 pub fn on_tap_track_reset(mut self, callback: Listener) -> TextSelectionGestureDetector {
4972 self.on_tap_track_reset = Some(callback);
4973 self
4974 }
4975
4976 pub fn on_tap_down(
4978 mut self,
4979 callback: GestureTapDragDownCallback,
4980 ) -> TextSelectionGestureDetector {
4981 self.on_tap_down = Some(callback);
4982 self
4983 }
4984
4985 pub fn on_force_press_start(
4987 mut self,
4988 callback: GestureForcePressStartCallback,
4989 ) -> TextSelectionGestureDetector {
4990 self.on_force_press_start = Some(callback);
4991 self
4992 }
4993
4994 pub fn on_force_press_end(
4996 mut self,
4997 callback: GestureForcePressEndCallback,
4998 ) -> TextSelectionGestureDetector {
4999 self.on_force_press_end = Some(callback);
5000 self
5001 }
5002
5003 pub fn on_secondary_tap(
5005 mut self,
5006 callback: GestureTapCallback,
5007 ) -> TextSelectionGestureDetector {
5008 self.on_secondary_tap = Some(callback);
5009 self
5010 }
5011
5012 pub fn on_secondary_tap_down(
5014 mut self,
5015 callback: GestureTapDownCallback,
5016 ) -> TextSelectionGestureDetector {
5017 self.on_secondary_tap_down = Some(callback);
5018 self
5019 }
5020
5021 pub fn on_single_tap_up(
5023 mut self,
5024 callback: GestureTapDragUpCallback,
5025 ) -> TextSelectionGestureDetector {
5026 self.on_single_tap_up = Some(callback);
5027 self
5028 }
5029
5030 pub fn on_single_tap_cancel(
5032 mut self,
5033 callback: GestureCancelCallback,
5034 ) -> TextSelectionGestureDetector {
5035 self.on_single_tap_cancel = Some(callback);
5036 self
5037 }
5038
5039 pub fn on_user_tap(mut self, callback: GestureTapCallback) -> TextSelectionGestureDetector {
5041 self.on_user_tap = Some(callback);
5042 self
5043 }
5044
5045 pub fn on_single_long_tap_start(
5047 mut self,
5048 callback: GestureLongPressStartCallback,
5049 ) -> TextSelectionGestureDetector {
5050 self.on_single_long_tap_start = Some(callback);
5051 self
5052 }
5053
5054 pub fn on_single_long_tap_move_update(
5056 mut self,
5057 callback: GestureLongPressMoveUpdateCallback,
5058 ) -> TextSelectionGestureDetector {
5059 self.on_single_long_tap_move_update = Some(callback);
5060 self
5061 }
5062
5063 pub fn on_single_long_tap_end(
5065 mut self,
5066 callback: GestureLongPressEndCallback,
5067 ) -> TextSelectionGestureDetector {
5068 self.on_single_long_tap_end = Some(callback);
5069 self
5070 }
5071
5072 pub fn on_single_long_tap_cancel(
5074 mut self,
5075 callback: GestureLongPressCancelCallback,
5076 ) -> TextSelectionGestureDetector {
5077 self.on_single_long_tap_cancel = Some(callback);
5078 self
5079 }
5080
5081 pub fn on_double_tap_down(
5083 mut self,
5084 callback: GestureTapDragDownCallback,
5085 ) -> TextSelectionGestureDetector {
5086 self.on_double_tap_down = Some(callback);
5087 self
5088 }
5089
5090 pub fn on_triple_tap_down(
5092 mut self,
5093 callback: GestureTapDragDownCallback,
5094 ) -> TextSelectionGestureDetector {
5095 self.on_triple_tap_down = Some(callback);
5096 self
5097 }
5098
5099 pub fn on_drag_selection_start(
5101 mut self,
5102 callback: GestureTapDragStartCallback,
5103 ) -> TextSelectionGestureDetector {
5104 self.on_drag_selection_start = Some(callback);
5105 self
5106 }
5107
5108 pub fn on_drag_selection_update(
5110 mut self,
5111 callback: GestureTapDragUpdateCallback,
5112 ) -> TextSelectionGestureDetector {
5113 self.on_drag_selection_update = Some(callback);
5114 self
5115 }
5116
5117 pub fn on_drag_selection_end(
5119 mut self,
5120 callback: GestureTapDragEndCallback,
5121 ) -> TextSelectionGestureDetector {
5122 self.on_drag_selection_end = Some(callback);
5123 self
5124 }
5125
5126 pub fn on_user_tap_always_called(mut self, value: bool) -> TextSelectionGestureDetector {
5128 self.on_user_tap_always_called = value;
5129 self
5130 }
5131
5132 pub fn behavior(mut self, behavior: HitTestBehavior) -> TextSelectionGestureDetector {
5134 self.behavior = Some(behavior);
5135 self
5136 }
5137}
5138
5139impl StatefulWidget for TextSelectionGestureDetector {
5140 type State = TextSelectionGestureDetectorState;
5141
5142 fn key(&self) -> Option<&KeyRef> {
5143 self.key.as_ref()
5144 }
5145
5146 fn create_state(&self) -> TextSelectionGestureDetectorState {
5147 TextSelectionGestureDetectorState {
5148 state: StateData::new(),
5149 }
5150 }
5151}
5152
5153pub struct TextSelectionGestureDetectorState {
5155 state: StateData<TextSelectionGestureDetector>,
5156}
5157
5158impl Debug for TextSelectionGestureDetectorState {
5159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5160 f.debug_struct("TextSelectionGestureDetectorState")
5161 .finish_non_exhaustive()
5162 }
5163}
5164
5165fn force_press_start_cb(
5166 this: Handle<TextSelectionGestureDetectorState>,
5167) -> GestureForcePressStartCallback {
5168 Rc::new(move |app, details| this.force_press_started(app, details))
5169}
5170
5171fn force_press_end_cb(
5172 this: Handle<TextSelectionGestureDetectorState>,
5173) -> GestureForcePressEndCallback {
5174 Rc::new(move |app, details| this.force_press_ended(app, details))
5175}
5176
5177impl TextSelectionGestureDetectorState {
5178 pub fn get_effective_consecutive_tap_count(app: &App, raw_count: i32) -> i32 {
5181 match app.platform().target_platform() {
5182 TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::Linux => {
5183 if raw_count <= 3 {
5184 raw_count
5185 } else if raw_count % 3 == 0 {
5186 3
5187 } else {
5188 raw_count % 3
5189 }
5190 }
5191 TargetPlatform::IOS | TargetPlatform::MacOS => raw_count.min(3),
5192 TargetPlatform::Windows => {
5193 if raw_count < 2 {
5194 raw_count
5195 } else {
5196 2 + raw_count % 2
5197 }
5198 }
5199 }
5200 }
5201
5202 fn handle_tap_track_start(self: Handle<Self>, app: &mut App) {
5203 if let Some(callback) = self.widget(app).on_tap_track_start.clone() {
5204 callback.call(app);
5205 }
5206 }
5207
5208 fn handle_tap_track_reset(self: Handle<Self>, app: &mut App) {
5209 if let Some(callback) = self.widget(app).on_tap_track_reset.clone() {
5210 callback.call(app);
5211 }
5212 }
5213
5214 fn handle_tap_down(self: Handle<Self>, app: &mut App, details: TapDragDownDetails) {
5215 if let Some(callback) = self.widget(app).on_tap_down.clone() {
5216 callback(app, details.clone());
5217 }
5218 if Self::get_effective_consecutive_tap_count(app, details.consecutive_tap_count) == 2 {
5219 if let Some(callback) = self.widget(app).on_double_tap_down.clone() {
5220 callback(app, details);
5221 }
5222 return;
5223 }
5224 if Self::get_effective_consecutive_tap_count(app, details.consecutive_tap_count) == 3
5225 && let Some(callback) = self.widget(app).on_triple_tap_down.clone()
5226 {
5227 callback(app, details);
5228 }
5229 }
5230
5231 fn handle_tap_up(self: Handle<Self>, app: &mut App, details: TapDragUpDetails) {
5232 if Self::get_effective_consecutive_tap_count(app, details.consecutive_tap_count) == 1 {
5233 if let Some(callback) = self.widget(app).on_single_tap_up.clone() {
5234 callback(app, details);
5235 }
5236 if let Some(callback) = self.widget(app).on_user_tap.clone() {
5237 callback.call(app);
5238 }
5239 } else if self.widget(app).on_user_tap_always_called
5240 && let Some(callback) = self.widget(app).on_user_tap.clone()
5241 {
5242 callback.call(app);
5243 }
5244 }
5245
5246 fn handle_tap_cancel(self: Handle<Self>, app: &mut App) {
5247 if let Some(callback) = self.widget(app).on_single_tap_cancel.clone() {
5248 callback.call(app);
5249 }
5250 }
5251
5252 fn handle_drag_start(self: Handle<Self>, app: &mut App, details: TapDragStartDetails) {
5253 if let Some(callback) = self.widget(app).on_drag_selection_start.clone() {
5254 callback(app, details);
5255 }
5256 }
5257
5258 fn handle_drag_update(self: Handle<Self>, app: &mut App, details: TapDragUpdateDetails) {
5259 if let Some(callback) = self.widget(app).on_drag_selection_update.clone() {
5260 callback(app, details);
5261 }
5262 }
5263
5264 fn handle_drag_end(self: Handle<Self>, app: &mut App, details: TapDragEndDetails) {
5265 if let Some(callback) = self.widget(app).on_drag_selection_end.clone() {
5266 callback(app, details);
5267 }
5268 }
5269
5270 fn force_press_started(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
5271 if let Some(callback) = self.widget(app).on_force_press_start.clone() {
5272 callback(app, details);
5273 }
5274 }
5275
5276 fn force_press_ended(self: Handle<Self>, app: &mut App, details: ForcePressDetails) {
5277 if let Some(callback) = self.widget(app).on_force_press_end.clone() {
5278 callback(app, details);
5279 }
5280 }
5281
5282 fn handle_long_press_start(self: Handle<Self>, app: &mut App, details: LongPressStartDetails) {
5283 if let Some(callback) = self.widget(app).on_single_long_tap_start.clone() {
5284 callback(app, details);
5285 }
5286 }
5287
5288 fn handle_long_press_move_update(
5289 self: Handle<Self>,
5290 app: &mut App,
5291 details: LongPressMoveUpdateDetails,
5292 ) {
5293 if let Some(callback) = self.widget(app).on_single_long_tap_move_update.clone() {
5294 callback(app, details);
5295 }
5296 }
5297
5298 fn handle_long_press_end(self: Handle<Self>, app: &mut App, details: LongPressEndDetails) {
5299 if let Some(callback) = self.widget(app).on_single_long_tap_end.clone() {
5300 callback(app, details);
5301 }
5302 }
5303
5304 fn handle_long_press_cancel(self: Handle<Self>, app: &mut App) {
5305 if let Some(callback) = self.widget(app).on_single_long_tap_cancel.clone() {
5306 callback.call(app);
5307 }
5308 }
5309}
5310
5311impl State for TextSelectionGestureDetectorState {
5312 type Widget = TextSelectionGestureDetector;
5313
5314 crate::state_accessors!();
5315
5316 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
5317 let mut gestures: GestureRecognizerFactories = Vec::new();
5318 let this = self;
5319 gestures.push((
5320 TypeId::of::<TapGestureRecognizer>(),
5321 GestureRecognizerFactoryWithHandlers::<TapGestureRecognizer>::new(
5322 TapGestureRecognizer::new,
5323 move |app, instance| {
5324 instance.set_on_secondary_tap(app, this.widget(app).on_secondary_tap.clone());
5325 instance.set_on_secondary_tap_down(
5326 app,
5327 this.widget(app).on_secondary_tap_down.clone(),
5328 );
5329 },
5330 )
5331 .into_factory(),
5332 ));
5333
5334 let widget = self.widget(app);
5335 if widget.on_single_long_tap_start.is_some()
5336 || widget.on_single_long_tap_move_update.is_some()
5337 || widget.on_single_long_tap_end.is_some()
5338 || widget.on_single_long_tap_cancel.is_some()
5339 {
5340 gestures.push((
5341 TypeId::of::<LongPressGestureRecognizer>(),
5342 GestureRecognizerFactoryWithHandlers::<LongPressGestureRecognizer>::new(
5343 |app| {
5344 LongPressGestureRecognizer::new(app)
5345 .supported_devices(app, [PointerDeviceKind::Touch])
5346 },
5347 move |app, instance| {
5348 instance.set_on_long_press_start(
5349 app,
5350 Some(Rc::new(move |app, details| {
5351 this.handle_long_press_start(app, details);
5352 })),
5353 );
5354 instance.set_on_long_press_move_update(
5355 app,
5356 Some(Rc::new(move |app, details| {
5357 this.handle_long_press_move_update(app, details);
5358 })),
5359 );
5360 instance.set_on_long_press_end(
5361 app,
5362 Some(Rc::new(move |app, details| {
5363 this.handle_long_press_end(app, details);
5364 })),
5365 );
5366 instance.set_on_long_press_cancel(
5367 app,
5368 Some(Listener::new(move |app| {
5369 this.handle_long_press_cancel(app);
5370 })),
5371 );
5372 },
5373 )
5374 .into_factory(),
5375 ));
5376 }
5377
5378 if widget.on_drag_selection_start.is_some()
5379 || widget.on_drag_selection_update.is_some()
5380 || widget.on_drag_selection_end.is_some()
5381 {
5382 match app.platform().target_platform() {
5383 TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
5384 let eager = app.platform().target_platform() != TargetPlatform::IOS;
5385 gestures.push(
5386 (
5387 TypeId::of::<TapAndHorizontalDragGestureRecognizer>(),
5388 GestureRecognizerFactoryWithHandlers::<
5389 TapAndHorizontalDragGestureRecognizer,
5390 >::new(
5391 TapAndHorizontalDragGestureRecognizer::new,
5392 move |app, instance| {
5393 instance.set_drag_start_behavior(app, DragStartBehavior::Down);
5394 instance.set_eager_victory_on_drag(app, eager);
5395 instance.set_on_tap_track_start(
5396 app,
5397 Some(Listener::new(move |app| {
5398 this.handle_tap_track_start(app);
5399 })),
5400 );
5401 instance.set_on_tap_track_reset(
5402 app,
5403 Some(Listener::new(move |app| {
5404 this.handle_tap_track_reset(app);
5405 })),
5406 );
5407 instance.set_on_tap_down(
5408 app,
5409 Some(Rc::new(move |app, details| {
5410 this.handle_tap_down(app, details);
5411 })),
5412 );
5413 instance.set_on_drag_start(
5414 app,
5415 Some(Rc::new(move |app, details| {
5416 this.handle_drag_start(app, details);
5417 })),
5418 );
5419 instance.set_on_drag_update(
5420 app,
5421 Some(Rc::new(move |app, details| {
5422 this.handle_drag_update(app, details);
5423 })),
5424 );
5425 instance.set_on_drag_end(
5426 app,
5427 Some(Rc::new(move |app, details| {
5428 this.handle_drag_end(app, details);
5429 })),
5430 );
5431 instance.set_on_tap_up(
5432 app,
5433 Some(Rc::new(move |app, details| {
5434 this.handle_tap_up(app, details);
5435 })),
5436 );
5437 instance.set_on_cancel(
5438 app,
5439 Some(Listener::new(move |app| {
5440 this.handle_tap_cancel(app);
5441 })),
5442 );
5443 },
5444 )
5445 .into_factory(),
5446 ),
5447 );
5448 }
5449 TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
5450 gestures.push((
5451 TypeId::of::<TapAndPanGestureRecognizer>(),
5452 GestureRecognizerFactoryWithHandlers::<TapAndPanGestureRecognizer>::new(
5453 TapAndPanGestureRecognizer::new,
5454 move |app, instance| {
5455 instance.set_drag_start_behavior(app, DragStartBehavior::Down);
5456 instance.set_on_tap_track_start(
5457 app,
5458 Some(Listener::new(move |app| {
5459 this.handle_tap_track_start(app);
5460 })),
5461 );
5462 instance.set_on_tap_track_reset(
5463 app,
5464 Some(Listener::new(move |app| {
5465 this.handle_tap_track_reset(app);
5466 })),
5467 );
5468 instance.set_on_tap_down(
5469 app,
5470 Some(Rc::new(move |app, details| {
5471 this.handle_tap_down(app, details);
5472 })),
5473 );
5474 instance.set_on_drag_start(
5475 app,
5476 Some(Rc::new(move |app, details| {
5477 this.handle_drag_start(app, details);
5478 })),
5479 );
5480 instance.set_on_drag_update(
5481 app,
5482 Some(Rc::new(move |app, details| {
5483 this.handle_drag_update(app, details);
5484 })),
5485 );
5486 instance.set_on_drag_end(
5487 app,
5488 Some(Rc::new(move |app, details| {
5489 this.handle_drag_end(app, details);
5490 })),
5491 );
5492 instance.set_on_tap_up(
5493 app,
5494 Some(Rc::new(move |app, details| {
5495 this.handle_tap_up(app, details);
5496 })),
5497 );
5498 instance.set_on_cancel(
5499 app,
5500 Some(Listener::new(move |app| {
5501 this.handle_tap_cancel(app);
5502 })),
5503 );
5504 },
5505 )
5506 .into_factory(),
5507 ));
5508 }
5509 }
5510 }
5511
5512 if widget.on_force_press_start.is_some() || widget.on_force_press_end.is_some() {
5513 let has_start = widget.on_force_press_start.is_some();
5514 let has_end = widget.on_force_press_end.is_some();
5515 gestures.push((
5516 TypeId::of::<ForcePressGestureRecognizer>(),
5517 GestureRecognizerFactoryWithHandlers::<ForcePressGestureRecognizer>::new(
5518 ForcePressGestureRecognizer::new,
5519 move |app, instance| {
5520 instance.set_on_start(app, has_start.then_some(force_press_start_cb(this)));
5521 instance.set_on_end(app, has_end.then_some(force_press_end_cb(this)));
5522 },
5523 )
5524 .into_factory(),
5525 ));
5526 }
5527
5528 let mut detector = RawGestureDetector::new().gestures(gestures);
5529 if let Some(behavior) = self.widget(app).behavior {
5530 detector = detector.behavior(behavior);
5531 }
5532 detector.child(self.widget(app).child.clone()).into_widget()
5533 }
5534}
5535
5536fn capture_to_navigator(app: &mut App, context: BuildContext) -> CapturedThemes {
5539 let to = Navigator::maybe_of(app, context, false).map(|navigator| navigator.context(app));
5540 <dyn InheritedTheme>::capture(app, context, to)
5541}
5542
5543#[cfg(test)]
5544mod tests {
5545 use super::*;
5546 use std::cell::RefCell;
5547 use std::rc::Rc;
5548 use waft_foundation::ListenableObject;
5549
5550 use waft_foundation::AppCell;
5551
5552 use crate::testing::{TestPointer, test_widgets};
5553 use crate::widgets::basic::{ColoredBox, SizedBox};
5554 use waft_embedder::Color;
5555
5556 #[test]
5557 fn text_selection_overlay_is_a_type() {
5558 let _ = std::any::type_name::<TextSelectionOverlay>();
5559 let _ = std::any::type_name::<SelectionOverlay>();
5560 }
5561
5562 fn completes(cell: &Rc<AppCell>, task: Task<()>) -> bool {
5564 let completed = Rc::new(std::cell::Cell::new(false));
5565 let out = Rc::clone(&completed);
5566 cell.borrow().spawn(async move |_cx| {
5567 task.await;
5568 out.set(true);
5569 });
5570 cell.checkpoint();
5571 completed.get()
5572 }
5573
5574 #[test]
5577 fn clipboard_status_notifier_update_sets_value_based_on_clipboard_contents() {
5578 use waft_test::{MockClipboard, TestPlatform};
5579
5580 let mock_clipboard = Rc::new(MockClipboard::new());
5581 let clipboard: Rc<dyn waft_embedder::Clipboard> = Rc::clone(&mock_clipboard) as _;
5582 let cell = AppCell::with_platform(Rc::new(TestPlatform::new().with_clipboard(clipboard)));
5583 let notifier = ClipboardStatusNotifier::new(&mut cell.borrow_mut());
5584 assert_eq!(notifier.value(&cell.borrow()), ClipboardStatus::Unknown);
5585
5586 let update = notifier.update(&mut cell.borrow_mut());
5587 assert!(completes(&cell, update));
5588 assert_eq!(
5589 notifier.value(&cell.borrow()),
5590 ClipboardStatus::NotPasteable
5591 );
5592
5593 mock_clipboard.set_clipboard_data(Some("pasteablestring".to_owned()));
5594 let update = notifier.update(&mut cell.borrow_mut());
5595 assert!(completes(&cell, update));
5596 assert_eq!(notifier.value(&cell.borrow()), ClipboardStatus::Pasteable);
5597 }
5598
5599 #[test]
5600 fn a_listened_clipboard_status_notifier_updates_when_the_app_resumes() {
5601 use waft_scheduler::SchedulerBinding;
5602 use waft_test::{MockClipboard, TestPlatform};
5603
5604 let mock_clipboard = Rc::new(MockClipboard::new());
5605 let clipboard: Rc<dyn waft_embedder::Clipboard> = Rc::clone(&mock_clipboard) as _;
5606 let cell = AppCell::with_platform(Rc::new(TestPlatform::new().with_clipboard(clipboard)));
5607 let notifier = ClipboardStatusNotifier::new(&mut cell.borrow_mut());
5608 notifier.add_listener(&mut cell.borrow_mut(), Listener::new(|_app| {}));
5609 cell.checkpoint();
5610 assert_eq!(
5611 notifier.value(&cell.borrow()),
5612 ClipboardStatus::NotPasteable
5613 );
5614
5615 mock_clipboard.set_clipboard_data(Some("pasteablestring".to_owned()));
5616 SchedulerBinding::handle_app_lifecycle_state_changed(
5617 &mut cell.borrow_mut(),
5618 AppLifecycleState::Resumed,
5619 );
5620 cell.checkpoint();
5621 assert_eq!(notifier.value(&cell.borrow()), ClipboardStatus::Pasteable);
5622 }
5623
5624 #[test]
5625 fn a_listened_clipboard_status_notifier_updates_when_the_clipboard_changes() {
5626 use waft_services::ServicesBinding;
5627 use waft_test::{MockClipboard, TestPlatform};
5628
5629 let mock_clipboard = MockClipboard::new();
5630 let clipboard: Rc<dyn waft_embedder::Clipboard> = Rc::new(mock_clipboard.clone());
5631 let cell = AppCell::with_platform(Rc::new(TestPlatform::new().with_clipboard(clipboard)));
5632 let notifier = ClipboardStatusNotifier::new(&mut cell.borrow_mut());
5633 let listener = Listener::new(|_app| {});
5634 notifier.add_listener(&mut cell.borrow_mut(), listener.clone());
5635 cell.checkpoint();
5636
5637 mock_clipboard.set_clipboard_data(Some("pasteablestring".to_owned()));
5638 let binding = ServicesBinding::instance(&mut cell.borrow_mut());
5639 binding.handle_clipboard_changed(&mut cell.borrow_mut());
5640 cell.checkpoint();
5641 assert_eq!(notifier.value(&cell.borrow()), ClipboardStatus::Pasteable);
5642
5643 notifier.remove_listener(&mut cell.borrow_mut(), &listener);
5644 mock_clipboard.set_clipboard_data(None);
5645 binding.handle_clipboard_changed(&mut cell.borrow_mut());
5646 cell.checkpoint();
5647 assert_eq!(
5648 notifier.value(&cell.borrow()),
5649 ClipboardStatus::Pasteable,
5650 "a notifier nobody listens to no longer looks"
5651 );
5652 }
5653
5654 #[test]
5655 fn clipboard_status_notifier_update_default_platform_is_not_pasteable() {
5656 let cell = AppCell::new();
5657 let notifier = ClipboardStatusNotifier::new(&mut cell.borrow_mut());
5658 assert_eq!(notifier.value(&cell.borrow()), ClipboardStatus::Unknown);
5659 let update = notifier.update(&mut cell.borrow_mut());
5660 assert!(completes(&cell, update));
5661 assert_eq!(
5662 notifier.value(&cell.borrow()),
5663 ClipboardStatus::NotPasteable
5664 );
5665 }
5666
5667 fn log_tap_down(log: Rc<RefCell<Vec<&'static str>>>) -> GestureTapDragDownCallback {
5668 Rc::new(move |_app, _details| {
5669 log.borrow_mut().push("onTapDown");
5670 })
5671 }
5672
5673 fn log_tap_up(log: Rc<RefCell<Vec<&'static str>>>) -> GestureTapDragUpCallback {
5674 Rc::new(move |_app, _details| {
5675 log.borrow_mut().push("onSingleTapUp");
5676 })
5677 }
5678
5679 fn log_drag_start(log: Rc<RefCell<Vec<&'static str>>>) -> GestureTapDragStartCallback {
5680 Rc::new(move |_app, _details| {
5681 log.borrow_mut().push("onDragSelectionStart");
5682 })
5683 }
5684
5685 fn log_drag_update(log: Rc<RefCell<Vec<&'static str>>>) -> GestureTapDragUpdateCallback {
5686 Rc::new(move |_app, _details| {
5687 log.borrow_mut().push("onDragSelectionUpdate");
5688 })
5689 }
5690
5691 fn log_drag_end(log: Rc<RefCell<Vec<&'static str>>>) -> GestureTapDragEndCallback {
5692 Rc::new(move |_app, _details| {
5693 log.borrow_mut().push("onDragSelectionEnd");
5694 })
5695 }
5696
5697 #[test]
5698 fn a_mouse_click_fires_tap_down_and_single_tap_up() {
5699 test_widgets(|tester| {
5700 let log = Rc::new(RefCell::new(Vec::new()));
5701 let down = log_tap_down(Rc::clone(&log));
5702 let up = log_tap_up(Rc::clone(&log));
5703 tester.pump_widget(
5704 TextSelectionGestureDetector::new(
5705 SizedBox::new()
5706 .width(300.0)
5707 .height(200.0)
5708 .child(ColoredBox::new(Color::new(0xFFFFFFFF))),
5709 )
5710 .on_tap_down(down)
5711 .on_single_tap_up(up)
5712 .on_drag_selection_start(log_drag_start(Rc::new(RefCell::new(Vec::new()))))
5713 .into_widget(),
5714 );
5715 let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_MOUSE_BUTTON);
5716 tester.down(&mut mouse, Offset::new(20.0, 20.0));
5717 tester.up(&mouse);
5718 assert_eq!(*log.borrow(), ["onTapDown", "onSingleTapUp"]);
5719 });
5720 }
5721
5722 #[test]
5723 fn a_mouse_drag_fires_start_update_and_end() {
5724 test_widgets(|tester| {
5725 let log = Rc::new(RefCell::new(Vec::new()));
5726 let start = log_drag_start(Rc::clone(&log));
5727 let update = log_drag_update(Rc::clone(&log));
5728 let end = log_drag_end(Rc::clone(&log));
5729 tester.pump_widget(
5730 TextSelectionGestureDetector::new(
5731 SizedBox::new()
5732 .width(300.0)
5733 .height(200.0)
5734 .child(ColoredBox::new(Color::new(0xFFFFFFFF))),
5735 )
5736 .on_drag_selection_start(start)
5737 .on_drag_selection_update(update)
5738 .on_drag_selection_end(end)
5739 .into_widget(),
5740 );
5741 let mut mouse = TestPointer::mouse(1, waft_gestures::K_PRIMARY_MOUSE_BUTTON);
5742 tester.down(&mut mouse, Offset::new(20.0, 20.0));
5743 tester.move_to(&mut mouse, Offset::new(40.0, 20.0), true);
5744 tester.move_to(&mut mouse, Offset::new(80.0, 20.0), true);
5745 tester.up(&mouse);
5746 let events = log.borrow().clone();
5747 assert!(
5748 events.first() == Some(&"onDragSelectionStart"),
5749 "{events:?}"
5750 );
5751 assert!(events.contains(&"onDragSelectionUpdate"), "{events:?}");
5752 assert_eq!(events.last(), Some(&"onDragSelectionEnd"));
5753 });
5754 }
5755
5756 struct NoSelectionControls;
5758
5759 #[allow(deprecated)]
5760 impl TextSelectionControls for NoSelectionControls {
5761 fn build_handle(
5762 &self,
5763 _app: &mut App,
5764 _context: BuildContext,
5765 _handle_type: TextSelectionHandleType,
5766 _text_line_height: f64,
5767 _on_tap: Option<Listener>,
5768 ) -> WidgetRef {
5769 SizedBox::shrink().into_widget()
5770 }
5771
5772 fn get_handle_anchor(
5773 &self,
5774 _handle_type: TextSelectionHandleType,
5775 _text_line_height: f64,
5776 ) -> Offset {
5777 Offset::ZERO
5778 }
5779
5780 fn build_toolbar(
5781 &self,
5782 _app: &mut App,
5783 _context: BuildContext,
5784 _global_editable_region: Rect,
5785 _text_line_height: f64,
5786 _selection_midpoint: Offset,
5787 _endpoints: &[TextSelectionPoint],
5788 _delegate: AnyTextSelectionDelegate,
5789 _clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
5790 _last_secondary_tap_down_position: Option<Offset>,
5791 ) -> WidgetRef {
5792 SizedBox::shrink().into_widget()
5793 }
5794
5795 fn get_handle_size(&self, _text_line_height: f64) -> Size {
5796 Size::ZERO
5797 }
5798 }
5799
5800 #[test]
5801 fn a_focused_field_with_selection_controls_leaves_the_tree_with_its_overlay() {
5802 use std::time::Duration;
5803
5804 use crate::{
5805 Directionality, EditableText, FocusNode, ListenableBuilder, Overlay,
5806 TextEditingController,
5807 };
5808 use waft_embedder::TextDirection;
5809 use waft_foundation::ValueNotifier;
5810 use waft_painting::TextStyle;
5811
5812 test_widgets(|tester| {
5813 let (shown, tree) = {
5814 let mut app = tester.cell.borrow_mut();
5815 let shown = app.create(ValueNotifier::new(true));
5816 let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
5817 let focus_node = FocusNode::new(&mut app);
5818 let visible = shown.handle();
5819 let field = ListenableBuilder::new(Rc::new(shown.clone()), move |app, _, _| {
5820 if !*app.get(visible).value() {
5821 return SizedBox::shrink().into_widget();
5822 }
5823 EditableText::new(
5824 controller.erase(),
5825 focus_node.erase(),
5826 TextStyle::new(),
5827 Color::from_argb(255, 0, 0, 0),
5828 Color::from_argb(255, 128, 128, 128),
5829 )
5830 .selection_controls(Rc::new(NoSelectionControls))
5831 .autofocus(true)
5832 .into_widget()
5833 });
5834 (
5835 shown,
5836 Directionality::new(TextDirection::Ltr, Overlay::wrap(field)),
5837 )
5838 };
5839 tester.pump_widget(tree);
5840 let pump = |tester: &mut crate::testing::WidgetTester| {
5841 for _ in 0..5 {
5842 tester.pump_by(Duration::from_millis(20));
5843 }
5844 };
5845 pump(tester);
5846 shown.set_value(&mut tester.cell.borrow_mut(), false);
5847 pump(tester);
5848 });
5849 }
5850
5851 struct RecordingControls {
5853 font_sizes: Rc<RefCell<Vec<Option<f64>>>>,
5854 }
5855
5856 #[allow(deprecated)]
5857 impl TextSelectionControls for RecordingControls {
5858 fn build_handle(
5859 &self,
5860 app: &mut App,
5861 context: BuildContext,
5862 _handle_type: TextSelectionHandleType,
5863 _text_line_height: f64,
5864 _on_tap: Option<Listener>,
5865 ) -> WidgetRef {
5866 let font_size = crate::DefaultTextStyle::of(app, context).style.font_size;
5867 self.font_sizes.borrow_mut().push(font_size);
5868 SizedBox::shrink().into_widget()
5869 }
5870
5871 fn get_handle_anchor(
5872 &self,
5873 _handle_type: TextSelectionHandleType,
5874 _text_line_height: f64,
5875 ) -> Offset {
5876 Offset::ZERO
5877 }
5878
5879 fn build_toolbar(
5880 &self,
5881 _app: &mut App,
5882 _context: BuildContext,
5883 _global_editable_region: Rect,
5884 _text_line_height: f64,
5885 _selection_midpoint: Offset,
5886 _endpoints: &[TextSelectionPoint],
5887 _delegate: AnyTextSelectionDelegate,
5888 _clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
5889 _last_secondary_tap_down_position: Option<Offset>,
5890 ) -> WidgetRef {
5891 SizedBox::shrink().into_widget()
5892 }
5893
5894 fn get_handle_size(&self, _text_line_height: f64) -> Size {
5895 Size::ZERO
5896 }
5897 }
5898
5899 #[test]
5903 fn the_selection_handles_carry_the_themes_of_the_context_that_shows_them() {
5904 test_widgets(|tester| {
5905 use crate::{DefaultTextStyle, Directionality, Overlay};
5906 use waft_embedder::TextDirection;
5907 use waft_painting::TextStyle;
5908
5909 let field_context: Rc<std::cell::Cell<Option<BuildContext>>> = Rc::default();
5910 let tree = {
5911 let field_context = Rc::clone(&field_context);
5912 Directionality::new(
5913 TextDirection::Ltr,
5914 Overlay::wrap(DefaultTextStyle::new(
5915 TextStyle::new().font_size(42.0),
5916 crate::Builder::new(move |_app, context| {
5917 field_context.set(Some(context));
5918 SizedBox::expand().into_widget()
5919 }),
5920 )),
5921 )
5922 .into_widget()
5923 };
5924 tester.pump_widget(tree);
5925 let mut app = tester.cell.borrow_mut();
5926 let context = field_context.get().expect("the field built");
5927 let font_sizes: Rc<RefCell<Vec<Option<f64>>>> = Rc::default();
5928 let links = (
5929 waft_rendering::LayerLink::new(&mut app),
5930 waft_rendering::LayerLink::new(&mut app),
5931 waft_rendering::LayerLink::new(&mut app),
5932 );
5933 let overlay = SelectionOverlay::new(
5934 &mut app,
5935 context,
5936 TextSelectionHandleType::Left,
5937 10.0,
5938 TextSelectionHandleType::Right,
5939 10.0,
5940 Vec::new(),
5941 Some(Rc::new(RecordingControls {
5942 font_sizes: Rc::clone(&font_sizes),
5943 })),
5944 None,
5945 None,
5946 links.0,
5947 links.1,
5948 links.2,
5949 );
5950 overlay.show_handles(&mut app);
5951 drop(app);
5952 tester.pump();
5953 let seen = font_sizes.borrow().clone();
5954 assert!(!seen.is_empty(), "a handle was built");
5955 assert!(seen.iter().all(|size| *size == Some(42.0)), "{seen:?}");
5956 });
5957 }
5958}