1use std::any::{Any, TypeId};
4use std::cell::Cell;
5use std::collections::HashMap;
6use std::fmt::{self, Debug};
7use std::marker::PhantomData;
8use std::rc::Rc;
9use std::time::Duration;
10
11use waft_animation::{AnimationBehavior, AnimationController, Curve, Curves};
12use waft_embedder::{
13 AutofillConfiguration, BoxHeightStyle, BoxWidthStyle, Brightness, Clip, Color, FontWeight,
14 Locale, Matrix4, Offset, PointerDeviceKind, Radius, Rect, Size, SmartDashesType,
15 SmartQuotesType, TargetPlatform, TextAffinity, TextAlign, TextBaseline, TextCapitalization,
16 TextDecoration, TextDirection, TextHeightBehavior, TextInputAction, TextInputConfiguration,
17 TextInputType, TextPosition, TextRange, TextSelection, ViewId, clamp_double,
18};
19use waft_foundation::{
20 App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticsProperty,
21 EnumProperty, Handle, HandleId, IntProperty, K_IS_WEB, Listenable, ListenableHandle,
22 ListenableObject, Listener, OptionRetained, Retained, Task, Timer, ValueListenable,
23 ValueListenableHandle, ValueNotifier, describe_identity,
24};
25use waft_gestures::{DragStartBehavior, PointerDownEvent, PointerUpEvent};
26use waft_painting::{
27 AxisDirection, EdgeInsets, InlineSpanRef, RenderComparison, StrutStyle, TextScaler, TextSpan,
28 TextStyle, TextWidthBasis,
29};
30use waft_physics::{Simulation, Tolerance};
31use waft_rendering::{
32 AnyLayer, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, CompositionCallback,
33 HitTestBehavior, LayerLink, LineBoundary, PaintingContext, RenderBox, RenderBoxData,
34 RenderEditable, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
35 RenderObjectWithChildMixin, RenderProxyBoxMixin, RenderProxyBoxWithHitTestBehavior,
36 RevealedOffset, ScrollDirection, VerticalCaretMovementRun, ViewportOffsetRef,
37};
38use waft_scheduler::{
39 FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
40};
41use waft_services::{
42 AnyAutofillClient, AnyTextSelectionDelegate, AutofillClient, AutofillHints, CharacterBoundary,
43 Clipboard, ClipboardData, DefaultProcessTextService, DocumentBoundary,
44 FilteringTextInputFormatter, KeyboardInsertedContent, LiveText, MouseCursorRef,
45 ParagraphBoundary, ProcessTextAction, ProcessTextService, SelectionChangedCause, SelectionRect,
46 SpellCheckResults, SuggestionSpan, SystemMouseCursors, TextBoundary, TextEditingValue,
47 TextInput, TextInputClient, TextInputConnection, TextInputFormatter, TextInputFormatterRef,
48 TextInputStyle, TextSelectionDelegate,
49};
50
51use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
52use crate::framework::{
53 BuildContext, GlobalKey, IntoWidget, KeyRef, MultiChildRenderObjectWidget, RenderObjectWidget,
54 SingleChildRenderObjectWidget, State, StateData, StatefulWidget, WidgetRef,
55};
56use crate::state_accessors;
57use crate::view::View;
58use crate::widgets::actions::{
59 Action, ActionData, ActionRef, Actions, AnyAction, CallbackAction, ContextAction,
60 DismissIntent, DoNothingAction, Intent, OnInvokeCallback,
61};
62use crate::widgets::app_lifecycle_listener::AppLifecycleListener;
63use crate::widgets::autofill::{AutofillGroup, AutofillGroupState};
64use crate::widgets::automatic_keep_alive::{
65 AutomaticKeepAliveClientMixin, AutomaticKeepAliveClientMixinData,
66};
67use crate::widgets::basic::CompositedTransformTarget;
68use crate::widgets::basic::WidgetBuilder;
69use crate::widgets::basic::{Builder, Directionality, MouseRegion};
70use crate::widgets::constants::K_MIN_INTERACTIVE_DIMENSION;
71use crate::widgets::context_menu_button_item::{ContextMenuButtonItem, ContextMenuButtonType};
72use crate::widgets::default_text_editing_shortcuts::intent_for_macos_selector;
73use crate::widgets::focus_manager::{FocusManager, FocusNodeRef, UnfocusDisposition};
74use crate::widgets::focus_scope::{Focus, FocusScope};
75use crate::widgets::focus_traversal::{DirectionalFocusAction, DirectionalFocusIntent};
76use crate::widgets::magnifier::TextMagnifierConfiguration;
77use crate::widgets::media_query::{MediaQuery, Orientation};
78use crate::widgets::notification_listener::NotificationListener;
79use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
80use crate::widgets::scroll_controller::{
81 ScrollController, ScrollControllerLeaf, ScrollControllerRef,
82};
83use crate::widgets::scroll_notification::ScrollNotification;
84use crate::widgets::scroll_physics::{ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef};
85use crate::widgets::scrollable::{Scrollable, ScrollableState, ViewportBuilder};
86use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
87use crate::widgets::spell_check::{
88 SpellCheckConfiguration, build_text_span_with_spell_check_suggestions,
89};
90use crate::widgets::tap_region::{TapRegionGroupId, TextFieldTapRegion};
91use crate::widgets::text::{DefaultTextHeightBehavior, apply_text_spacing_overrides};
92use crate::widgets::text_editing_intents::{
93 CopySelectionTextIntent, DeleteCharacterIntent, DeleteToLineBreakIntent,
94 DeleteToNextWordBoundaryIntent, DirectionalCaretMovementIntent, DirectionalTextEditingIntent,
95 DoNothingAndStopPropagationTextIntent, EditableTextTapOutsideIntent,
96 EditableTextTapUpOutsideIntent, ExpandSelectionToDocumentBoundaryIntent,
97 ExpandSelectionToLineBreakIntent, ExtendSelectionByCharacterIntent,
98 ExtendSelectionToDocumentBoundaryIntent, ExtendSelectionToLineBreakIntent,
99 ExtendSelectionToNextParagraphBoundaryIntent,
100 ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent,
101 ExtendSelectionToNextWordBoundaryIntent,
102 ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
103 ExtendSelectionVerticallyToAdjacentLineIntent, ExtendSelectionVerticallyToAdjacentPageIntent,
104 PasteTextIntent, ReplaceTextIntent, ScrollToDocumentBoundaryIntent, SelectAllTextIntent,
105 TransposeCharactersIntent, UpdateSelectionIntent,
106};
107use crate::widgets::text_selection::{
108 ClipboardStatus, ClipboardStatusNotifier, LiveTextInputStatus, LiveTextInputStatusNotifier,
109 TextSelectionControls, TextSelectionHandleType, TextSelectionOverlay,
110};
111use crate::widgets::text_selection_toolbar_anchors::TextSelectionToolbarAnchors;
112use crate::widgets::ticker_provider::{
113 TickerMode, TickerProviderStateMixin, TickerProviderStateMixinData,
114};
115use crate::widgets::undo_history::{UndoHistory, UndoHistoryController};
116use crate::widgets::widget_span::WidgetSpan;
117use waft_foundation::Ref;
118
119#[derive(Debug)]
122pub struct TextEditingControllerData {
123 value: TextEditingValue,
124}
125
126impl TextEditingControllerData {
127 pub fn new(value: TextEditingValue) -> TextEditingControllerData {
129 TextEditingControllerData { value }
130 }
131}
132
133#[macro_export]
136macro_rules! text_editing_controller_accessors {
137 () => {
138 fn text_editing_controller_data(
139 self: ::waft_foundation::Handle<Self>,
140 app: &::waft_foundation::App,
141 ) -> &$crate::TextEditingControllerData {
142 &app.get(self).text_editing_controller
143 }
144
145 fn text_editing_controller_data_mut(
146 self: ::waft_foundation::Handle<Self>,
147 app: &mut ::waft_foundation::App,
148 ) -> &mut $crate::TextEditingControllerData {
149 &mut app.get_mut(self).text_editing_controller
150 }
151 };
152}
153
154pub trait TextEditingControllerLeaf: ChangeNotifier + Sized + 'static {
161 fn text_editing_controller_data(self: Handle<Self>, app: &App) -> &TextEditingControllerData;
164
165 fn text_editing_controller_data_mut(
167 self: Handle<Self>,
168 app: &mut App,
169 ) -> &mut TextEditingControllerData;
170
171 fn build_text_span(
176 self: Handle<Self>,
177 app: &App,
178 context: BuildContext,
179 style: Option<TextStyle>,
180 with_composing: bool,
181 ) -> TextSpan {
182 TextEditingController::build_text_span(
183 self.as_controller(),
184 app,
185 context,
186 style,
187 with_composing,
188 )
189 }
190
191 fn text_value(self: Handle<Self>, app: &App) -> &str {
195 &self.text_editing_controller_data(app).value.text
196 }
197
198 fn set_text(self: Handle<Self>, app: &mut App, new_text: impl Into<String>) {
200 self.as_controller().set_text(app, new_text);
201 }
202
203 fn value(self: Handle<Self>, app: &App) -> &TextEditingValue {
205 &self.text_editing_controller_data(app).value
206 }
207
208 fn set_value(self: Handle<Self>, app: &mut App, new_value: TextEditingValue) {
210 self.as_controller().set_value(app, new_value);
211 }
212
213 fn selection(self: Handle<Self>, app: &App) -> TextSelection {
215 self.as_controller().selection(app)
216 }
217
218 fn set_selection(self: Handle<Self>, app: &mut App, new_selection: TextSelection) {
220 self.as_controller().set_selection(app, new_selection);
221 }
222
223 fn clear(self: Handle<Self>, app: &mut App) {
225 self.as_controller().clear(app);
226 }
227
228 fn clear_composing(self: Handle<Self>, app: &mut App) {
230 self.as_controller().clear_composing(app);
231 }
232
233 fn as_controller(self: Handle<Self>) -> AnyTextEditingController {
236 AnyTextEditingController {
237 id: self.id(),
238 vtable: const { &TextEditingControllerVTable::of::<Self>() },
239 }
240 }
241}
242
243pub struct TextEditingController {
261 change_notifier: ChangeNotifierData,
262 text_editing_controller: TextEditingControllerData,
263}
264
265impl Debug for TextEditingController {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 f.debug_struct("TextEditingController")
268 .field("value", &self.text_editing_controller.value)
269 .finish()
270 }
271}
272
273impl TextEditingController {
274 pub fn new(app: &mut App) -> Ref<TextEditingController> {
295 TextEditingController::from_value(app, None)
296 }
297
298 pub fn text(self: Ref<Self>, app: &mut App, text: impl Into<String>) -> Ref<Self> {
300 app.get_mut(&self).text_editing_controller.value = TextEditingValue::new().text(text);
301 self
302 }
303
304 pub fn from_value(
306 app: &mut App,
307 value: Option<TextEditingValue>,
308 ) -> Ref<TextEditingController> {
309 let value = value.unwrap_or(TextEditingValue::EMPTY);
310 debug_assert!(
311 !value.composing.is_valid() || value.is_composing_range_valid(),
312 "New TextEditingValue {value:?} has an invalid non-empty composing range \
313 {:?}. It is recommended to use a valid composing range, \
314 even for readonly text fields.",
315 value.composing
316 );
317 app.create(TextEditingController {
318 change_notifier: ChangeNotifierData::new(),
319 text_editing_controller: TextEditingControllerData::new(value),
320 })
321 }
322
323 pub fn build_text_span(
325 controller: AnyTextEditingController,
326 app: &App,
327 _context: BuildContext,
328 style: Option<TextStyle>,
329 with_composing: bool,
330 ) -> TextSpan {
331 let value = controller.value(app).clone();
332 debug_assert!(
333 !value.composing.is_valid() || !with_composing || value.is_composing_range_valid()
334 );
335 let composing_region_out_of_range = !value.is_composing_range_valid() || !with_composing;
339 if composing_region_out_of_range {
340 return match style {
341 Some(style) => TextSpan::new().style(style).text(value.text),
342 None => TextSpan::new().text(value.text),
343 };
344 }
345 let composing_style = style
346 .as_ref()
347 .map(|s| {
348 s.merge(Some(
349 &TextStyle::new().decoration(TextDecoration::UNDERLINE),
350 ))
351 })
352 .unwrap_or_else(|| TextStyle::new().decoration(TextDecoration::UNDERLINE));
353 let mut span = TextSpan::new();
354 if let Some(style) = style {
355 span = span.style(style);
356 }
357 span.children(vec![
358 TextSpan::new()
359 .text(value.composing.text_before(&value.text))
360 .into_span(),
361 TextSpan::new()
362 .style(composing_style)
363 .text(value.composing.text_inside(&value.text))
364 .into_span(),
365 TextSpan::new()
366 .text(value.composing.text_after(&value.text))
367 .into_span(),
368 ])
369 }
370}
371
372impl TextEditingController {
373 pub fn dispose(self: Handle<Self>, app: &mut App) {
375 ChangeNotifierData::dispose(app, self);
376 }
377}
378
379impl ChangeNotifier for TextEditingController {
380 fn change_notifier_data(&self) -> &ChangeNotifierData {
381 &self.change_notifier
382 }
383
384 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
385 &mut self.change_notifier
386 }
387}
388
389impl TextEditingControllerLeaf for TextEditingController {
390 crate::text_editing_controller_accessors!();
391}
392
393type BuildTextSpanFn = fn(&App, HandleId, BuildContext, Option<TextStyle>, bool) -> TextSpan;
395
396struct TextEditingControllerVTable {
398 type_name: fn() -> &'static str,
399 add_listener: fn(&mut App, HandleId, Listener),
400 remove_listener: fn(&mut App, HandleId, &Listener),
401 notify_listeners: fn(&mut App, HandleId),
402 dispose_change_notifier: fn(&mut App, HandleId),
403 data: fn(&App, HandleId) -> &TextEditingControllerData,
404 data_mut: fn(&mut App, HandleId) -> &mut TextEditingControllerData,
405 build_text_span: BuildTextSpanFn,
406}
407
408impl TextEditingControllerVTable {
409 const fn of<C: TextEditingControllerLeaf>() -> TextEditingControllerVTable {
411 TextEditingControllerVTable {
412 type_name: std::any::type_name::<C>,
413 add_listener: |app, id, listener| {
414 ListenableObject::add_listener(Handle::<C>::from_id(id), app, listener);
415 },
416 remove_listener: |app, id, listener| {
417 ListenableObject::remove_listener(Handle::<C>::from_id(id), app, listener);
418 },
419 notify_listeners: |app, id| Handle::<C>::from_id(id).notify_listeners(app),
420 dispose_change_notifier: |app, id| {
421 ChangeNotifierData::dispose(app, Handle::<C>::from_id(id));
422 },
423 data: |app, id| C::text_editing_controller_data(Handle::from_id(id), app),
424 data_mut: |app, id| C::text_editing_controller_data_mut(Handle::from_id(id), app),
425 build_text_span: |app, id, context, style, with_composing| {
426 C::build_text_span(Handle::from_id(id), app, context, style, with_composing)
427 },
428 }
429 }
430}
431
432#[derive(Clone, Copy)]
437pub struct AnyTextEditingController {
438 id: HandleId,
439 vtable: &'static TextEditingControllerVTable,
440}
441
442pub type TextEditingControllerRef = Retained<AnyTextEditingController>;
444
445waft_foundation::erased_handle!(AnyTextEditingController: TextEditingControllerLeaf => TextEditingControllerLeaf::as_controller);
446
447impl AnyTextEditingController {
448 pub fn identity_hash(self) -> u64 {
450 self.id.identity_hash()
451 }
452
453 pub fn to_string(self, app: &App) -> String {
456 format!(
457 "{}({})",
458 describe_identity(
459 waft_foundation::bare_type_name((self.vtable.type_name)()),
460 self.id.identity_hash(),
461 ),
462 self.value(app)
463 )
464 }
465
466 fn data(self, app: &App) -> &TextEditingControllerData {
467 (self.vtable.data)(app, self.id)
468 }
469
470 fn data_mut(self, app: &mut App) -> &mut TextEditingControllerData {
471 (self.vtable.data_mut)(app, self.id)
472 }
473
474 pub fn text_value(self, app: &App) -> &str {
476 &self.data(app).value.text
477 }
478
479 pub fn set_text(self, app: &mut App, new_text: impl Into<String>) {
487 let value = self
488 .value(app)
489 .clone()
490 .copy_with()
491 .text(new_text)
492 .selection(TextSelection::collapsed(-1, TextAffinity::Downstream))
493 .composing(TextRange::EMPTY);
494 self.set_value(app, value);
495 }
496
497 pub fn value(self, app: &App) -> &TextEditingValue {
499 &self.data(app).value
500 }
501
502 pub fn set_value(self, app: &mut App, new_value: TextEditingValue) {
505 debug_assert!(
506 !new_value.composing.is_valid() || new_value.is_composing_range_valid(),
507 "New TextEditingValue {new_value:?} has an invalid non-empty composing range \
508 {:?}. It is recommended to use a valid composing range, \
509 even for readonly text fields.",
510 new_value.composing
511 );
512 if self.data(app).value == new_value {
513 return;
514 }
515 self.data_mut(app).value = new_value;
516 (self.vtable.notify_listeners)(app, self.id);
517 }
518
519 pub fn build_text_span(
521 self,
522 app: &App,
523 context: BuildContext,
524 style: Option<TextStyle>,
525 with_composing: bool,
526 ) -> TextSpan {
527 (self.vtable.build_text_span)(app, self.id, context, style, with_composing)
528 }
529
530 pub fn selection(self, app: &App) -> TextSelection {
535 self.data(app).value.selection
536 }
537
538 pub fn set_selection(self, app: &mut App, new_selection: TextSelection) {
543 let text_len = utf16_len(self.text_value(app));
544 if text_len < new_selection.end() || text_len < new_selection.start() {
545 panic!("invalid text selection: {new_selection:?}");
546 }
547 let value = self.value(app).clone();
548 let new_composing = if is_selection_within_composing_range(&value, new_selection) {
549 value.composing
550 } else {
551 TextRange::EMPTY
552 };
553 self.set_value(
554 app,
555 value
556 .copy_with()
557 .selection(new_selection)
558 .composing(new_composing),
559 );
560 }
561
562 pub fn clear(self, app: &mut App) {
567 self.set_value(
568 app,
569 TextEditingValue::new()
570 .selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
571 );
572 }
573
574 pub fn clear_composing(self, app: &mut App) {
580 let value = self.value(app).clone();
581 self.set_value(app, value.copy_with().composing(TextRange::EMPTY));
582 }
583
584 pub fn dispose(self, app: &mut App) {
586 (self.vtable.dispose_change_notifier)(app, self.id);
587 }
588
589 pub fn describe(self, app: &App) -> String {
591 let name = (self.vtable.type_name)();
592 let short = name.rsplit("::").next().unwrap_or(name);
593 format!("{short}#{:?}({:?})", self.id, self.value(app))
594 }
595}
596
597impl Debug for AnyTextEditingController {
598 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599 write!(f, "AnyTextEditingController({:?})", self.id)
600 }
601}
602
603impl AnyTextEditingController {
604 pub fn add_listener(self, app: &mut App, listener: Listener) {
606 (self.vtable.add_listener)(app, self.id, listener);
607 }
608
609 pub fn remove_listener(self, app: &mut App, listener: &Listener) {
611 (self.vtable.remove_listener)(app, self.id, listener);
612 }
613}
614
615impl ListenableHandle for AnyTextEditingController {
616 fn add_listener_to(self, app: &mut App, listener: Listener) {
617 AnyTextEditingController::add_listener(self, app, listener);
618 }
619
620 fn remove_listener_from(self, app: &mut App, listener: &Listener) {
621 AnyTextEditingController::remove_listener(self, app, listener);
622 }
623}
624
625impl ValueListenableHandle<TextEditingValue> for AnyTextEditingController {
626 fn value_of(self, app: &App) -> &TextEditingValue {
627 &self.data(app).value
628 }
629}
630
631fn is_selection_within_composing_range(value: &TextEditingValue, selection: TextSelection) -> bool {
632 selection.start() >= value.composing.start && selection.end() <= value.composing.end
633}
634
635fn utf16_len(text: &str) -> i32 {
636 text.encode_utf16().count() as i32
637}
638
639fn option_rc_eq<T: ?Sized>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool {
640 match (a, b) {
641 (None, None) => true,
642 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
643 _ => false,
644 }
645}
646
647#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
657pub struct ToolbarOptions {
658 pub copy: bool,
660 pub cut: bool,
662 pub paste: bool,
664 pub select_all: bool,
666}
667
668impl ToolbarOptions {
669 pub const fn new() -> ToolbarOptions {
673 ToolbarOptions {
674 copy: false,
675 cut: false,
676 paste: false,
677 select_all: false,
678 }
679 }
680
681 pub const EMPTY: ToolbarOptions = ToolbarOptions::new();
683
684 pub const fn copy(mut self, copy: bool) -> ToolbarOptions {
686 self.copy = copy;
687 self
688 }
689
690 pub const fn cut(mut self, cut: bool) -> ToolbarOptions {
692 self.cut = cut;
693 self
694 }
695
696 pub const fn paste(mut self, paste: bool) -> ToolbarOptions {
698 self.paste = paste;
699 self
700 }
701
702 pub const fn select_all(mut self, select_all: bool) -> ToolbarOptions {
704 self.select_all = select_all;
705 self
706 }
707}
708
709impl Default for ToolbarOptions {
710 fn default() -> ToolbarOptions {
711 ToolbarOptions::new()
712 }
713}
714
715pub const K_DEFAULT_CONTENT_INSERTION_MIME_TYPES: &[&str] = &[
719 "image/png",
720 "image/bmp",
721 "image/jpg",
722 "image/tiff",
723 "image/gif",
724 "image/jpeg",
725 "image/webp",
726];
727
728struct CompositionCallbackWidget {
729 composite_callback: CompositionCallback,
730 enabled: bool,
731 child: WidgetRef,
732}
733
734impl Debug for CompositionCallbackWidget {
735 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 f.debug_struct("_CompositionCallback")
737 .field("enabled", &self.enabled)
738 .field("child", &self.child)
739 .finish_non_exhaustive()
740 }
741}
742
743impl CompositionCallbackWidget {
744 fn new(composite_callback: CompositionCallback, enabled: bool, child: WidgetRef) -> Self {
745 CompositionCallbackWidget {
746 composite_callback,
747 enabled,
748 child,
749 }
750 }
751}
752
753impl RenderObjectWidget for CompositionCallbackWidget {
754 type RenderObject = RenderCompositionCallback;
755
756 fn key(&self) -> Option<&KeyRef> {
757 None
758 }
759
760 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
761 RenderCompositionCallback::new(app, self.composite_callback.clone(), self.enabled)
762 .as_object()
763 }
764
765 fn update_render_object(
766 &self,
767 app: &mut App,
768 _context: BuildContext,
769 render_object: RenderHandle<RenderCompositionCallback>,
770 ) {
771 debug_assert!(Rc::ptr_eq(
773 &render_object.get(app).composite_callback,
774 &self.composite_callback
775 ));
776 render_object.set_enabled(app, self.enabled);
777 }
778}
779
780impl SingleChildRenderObjectWidget for CompositionCallbackWidget {
781 fn child(&self) -> Option<&WidgetRef> {
782 Some(&self.child)
783 }
784}
785
786type CancelCompositionCallback = Box<dyn FnOnce(&mut App)>;
788
789struct RenderCompositionCallback {
790 render_object: RenderObjectData,
791 render_box: RenderBoxData,
792 child: RenderObjectWithChildData<AnyRenderBox>,
793 composite_callback: CompositionCallback,
794 cancel_callback: Option<CancelCompositionCallback>,
795 enabled: bool,
796}
797
798impl RenderCompositionCallback {
799 fn new(
800 app: &mut App,
801 composite_callback: CompositionCallback,
802 enabled: bool,
803 ) -> RenderHandle<Self> {
804 RenderHandle::new_box(
805 app,
806 RenderCompositionCallback {
807 render_object: RenderObjectData::new(),
808 render_box: RenderBoxData::new(),
809 child: RenderObjectWithChildData::new(),
810 composite_callback,
811 cancel_callback: None,
812 enabled,
813 },
814 )
815 }
816
817 fn set_enabled(self: RenderHandle<Self>, app: &mut App, new_value: bool) {
818 self.get_mut(app).enabled = new_value;
819 if !new_value {
820 if let Some(cancel) = self.get_mut(app).cancel_callback.take() {
821 cancel(app);
822 }
823 } else if self.get(app).cancel_callback.is_none() {
824 self.as_object().mark_needs_paint(app);
825 }
826 }
827}
828
829impl RenderObjectWithChildMixin for RenderCompositionCallback {
830 type ChildType = AnyRenderBox;
831
832 fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
833 &self.get(app).child
834 }
835
836 fn child_data_mut(
837 self: RenderHandle<Self>,
838 app: &mut App,
839 ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
840 &mut self.get_mut(app).child
841 }
842}
843
844impl RenderProxyBoxMixin for RenderCompositionCallback {}
845
846impl RenderProxyBoxWithHitTestBehavior for RenderCompositionCallback {
847 fn behavior(self: RenderHandle<Self>, _app: &App) -> HitTestBehavior {
848 HitTestBehavior::DeferToChild
849 }
850}
851
852impl RenderObject for RenderCompositionCallback {
853 waft_rendering::render_object_accessors!();
854
855 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
856 RenderProxyBoxMixin::perform_layout(self, app);
857 }
858
859 fn paint(
860 self: RenderHandle<Self>,
861 app: &mut App,
862 context: &mut PaintingContext,
863 offset: Offset,
864 ) {
865 if self.get(app).enabled && self.get(app).cancel_callback.is_none() {
866 let callback = self.get(app).composite_callback.clone();
867 let cancel = context.add_composition_callback(app, callback);
868 self.get_mut(app).cancel_callback = Some(cancel);
869 }
870 RenderProxyBoxMixin::paint(self, app, context, offset);
871 }
872
873 fn visit_children(
874 self: RenderHandle<Self>,
875 app: &App,
876 visitor: &mut dyn FnMut(AnyRenderObject),
877 ) {
878 if let Some(child) = self.child(app) {
879 visitor(child.as_object());
880 }
881 }
882
883 fn dispose(self: RenderHandle<Self>, app: &mut App) {
887 if let Some(cancel) = self.get_mut(app).cancel_callback.take() {
888 cancel(app);
889 }
890 waft_rendering::RenderObjectBase::dispose(self, app);
891 }
892}
893
894impl RenderBox for RenderCompositionCallback {
895 waft_rendering::render_box_accessors!();
896
897 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
898 RenderProxyBoxMixin::setup_parent_data(self, app, child);
899 }
900
901 fn apply_paint_transform(
902 self: RenderHandle<Self>,
903 app: &App,
904 child: AnyRenderObject,
905 transform: &mut Matrix4,
906 ) {
907 RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
908 }
909
910 fn hit_test(
911 self: RenderHandle<Self>,
912 app: &mut App,
913 result: &mut BoxHitTestResult<'_>,
914 position: Offset,
915 ) -> bool {
916 RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
917 }
918
919 fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
920 RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
921 }
922
923 fn hit_test_children(
924 self: RenderHandle<Self>,
925 app: &mut App,
926 result: &mut BoxHitTestResult<'_>,
927 position: Offset,
928 ) -> bool {
929 RenderProxyBoxMixin::hit_test_children(self, app, result, position)
930 }
931
932 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
933 RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
934 }
935
936 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
937 RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
938 }
939
940 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
941 RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
942 }
943
944 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
945 RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
946 }
947
948 fn compute_distance_to_actual_baseline(
949 self: RenderHandle<Self>,
950 app: &mut App,
951 baseline: TextBaseline,
952 ) -> Option<f64> {
953 RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
954 }
955
956 fn compute_dry_baseline(
957 self: RenderHandle<Self>,
958 app: &mut App,
959 constraints: BoxConstraints,
960 baseline: TextBaseline,
961 ) -> Option<f64> {
962 RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
963 }
964
965 fn compute_dry_layout(
966 self: RenderHandle<Self>,
967 app: &mut App,
968 constraints: BoxConstraints,
969 ) -> Size {
970 RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
971 }
972}
973
974#[derive(Clone)]
980#[allow(clippy::type_complexity)]
981pub struct ContentInsertionConfiguration {
982 pub on_content_inserted: Rc<dyn Fn(&mut App, KeyboardInsertedContent)>,
985 pub allowed_mime_types: Vec<String>,
988}
989
990impl ContentInsertionConfiguration {
991 pub fn new(
996 on_content_inserted: impl Fn(&mut App, KeyboardInsertedContent) + 'static,
997 ) -> ContentInsertionConfiguration {
998 ContentInsertionConfiguration {
999 on_content_inserted: Rc::new(on_content_inserted),
1000 allowed_mime_types: K_DEFAULT_CONTENT_INSERTION_MIME_TYPES
1001 .iter()
1002 .map(|s| (*s).to_string())
1003 .collect(),
1004 }
1005 }
1006
1007 pub fn allowed_mime_types(mut self, allowed_mime_types: Vec<String>) -> Self {
1009 debug_assert!(
1010 !allowed_mime_types.is_empty(),
1011 "allowedMimeTypes cannot be an empty list"
1012 );
1013 self.allowed_mime_types = allowed_mime_types;
1014 self
1015 }
1016}
1017
1018pub type SelectionChangedCallback =
1021 Rc<dyn Fn(&mut App, TextSelection, Option<SelectionChangedCause>)>;
1022
1023pub type AppPrivateCommandCallback = Rc<dyn Fn(&mut App, &str)>;
1027
1028pub type EditableTextContextMenuBuilder =
1031 Rc<dyn Fn(&mut App, BuildContext, Handle<EditableTextState>) -> WidgetRef>;
1032
1033const K_CURSOR_BLINK_HALF_PERIOD: Duration = Duration::from_millis(500);
1034const K_OBSCURE_SHOW_LATEST_CHAR_CURSOR_TICKS: i32 = 3;
1035
1036pub struct DebugDeterministicCursor;
1038
1039impl waft_foundation::DebugFlag for DebugDeterministicCursor {}
1040
1041#[derive(Clone, Copy, Debug)]
1043struct KeyFrame {
1044 time: f64,
1045 value: f64,
1046}
1047
1048impl KeyFrame {
1049 const fn new(time: f64, value: f64) -> KeyFrame {
1050 KeyFrame { time, value }
1051 }
1052
1053 const IOS_BLINKING_CARET_KEY_FRAMES: &[KeyFrame] = &[
1054 KeyFrame::new(0.0, 1.0),
1055 KeyFrame::new(0.5, 1.0),
1056 KeyFrame::new(0.5375, 0.75),
1057 KeyFrame::new(0.575, 0.5),
1058 KeyFrame::new(0.6125, 0.25),
1059 KeyFrame::new(0.65, 0.0),
1060 KeyFrame::new(0.85, 0.0),
1061 KeyFrame::new(0.8875, 0.25),
1062 KeyFrame::new(0.925, 0.5),
1063 KeyFrame::new(0.9625, 0.75),
1064 KeyFrame::new(1.0, 1.0),
1065 ];
1066}
1067
1068struct DiscreteKeyFrameSimulation {
1070 key_frames: &'static [KeyFrame],
1071 max_duration: f64,
1072 last_key_frame_index: Cell<usize>,
1073 tolerance: Tolerance,
1074}
1075
1076impl DiscreteKeyFrameSimulation {
1077 fn ios_blinking_caret() -> DiscreteKeyFrameSimulation {
1078 DiscreteKeyFrameSimulation::new(KeyFrame::IOS_BLINKING_CARET_KEY_FRAMES, 1.0)
1079 }
1080
1081 fn new(key_frames: &'static [KeyFrame], max_duration: f64) -> DiscreteKeyFrameSimulation {
1082 debug_assert!(!key_frames.is_empty());
1083 debug_assert!(
1084 key_frames
1085 .last()
1086 .is_none_or(|frame| frame.time <= max_duration)
1087 );
1088 if cfg!(debug_assertions) {
1089 for i in 0..key_frames.len().saturating_sub(1) {
1090 debug_assert!(
1091 key_frames[i].time <= key_frames[i + 1].time,
1092 "The key frame sequence must be sorted by time."
1093 );
1094 }
1095 }
1096 DiscreteKeyFrameSimulation {
1097 key_frames,
1098 max_duration,
1099 last_key_frame_index: Cell::new(0),
1100 tolerance: Tolerance::default(),
1101 }
1102 }
1103}
1104
1105impl Debug for DiscreteKeyFrameSimulation {
1106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1107 f.debug_struct("DiscreteKeyFrameSimulation")
1108 .field("max_duration", &self.max_duration)
1109 .finish()
1110 }
1111}
1112
1113impl Simulation for DiscreteKeyFrameSimulation {
1114 fn dx(&self, _time: f64) -> f64 {
1115 0.0
1116 }
1117
1118 fn is_done(&self, time: f64) -> bool {
1119 time >= self.max_duration
1120 }
1121
1122 fn x(&self, time: f64) -> f64 {
1123 let length = self.key_frames.len();
1124 let last = self.last_key_frame_index.get();
1125 let (mut search_index, end_index) = if self.key_frames[last].time > time {
1126 (0, last)
1127 } else {
1128 (last, length)
1129 };
1130 while search_index < end_index.saturating_sub(1) {
1131 debug_assert!(self.key_frames[search_index].time <= time);
1132 let next = self.key_frames[search_index + 1];
1133 if time < next.time {
1134 break;
1135 }
1136 search_index += 1;
1137 }
1138 self.last_key_frame_index.set(search_index);
1139 self.key_frames[self.last_key_frame_index.get()].value
1140 }
1141
1142 fn tolerance(&self) -> Tolerance {
1143 self.tolerance
1144 }
1145
1146 fn set_tolerance(&mut self, tolerance: Tolerance) {
1147 self.tolerance = tolerance;
1148 }
1149}
1150
1151#[allow(clippy::type_complexity)]
1157pub struct EditableText {
1158 pub key: Option<KeyRef>,
1159 pub controller: TextEditingControllerRef,
1161 pub focus_node: FocusNodeRef,
1163 pub read_only: bool,
1164 pub obscuring_character: String,
1165 pub obscure_text: bool,
1166 pub autocorrect: Option<bool>,
1167 pub smart_dashes_type: Option<SmartDashesType>,
1168 pub smart_quotes_type: Option<SmartQuotesType>,
1169 pub enable_suggestions: bool,
1170 pub style: TextStyle,
1171 strut_style: Option<StrutStyle>,
1185 pub cursor_color: Color,
1186 pub background_cursor_color: Color,
1187 pub text_align: TextAlign,
1188 pub text_direction: Option<TextDirection>,
1189 pub locale: Option<Locale>,
1190 pub text_scale_factor: Option<f64>,
1191 pub text_scaler: Option<TextScaler>,
1192 pub max_lines: Option<i32>,
1193 pub min_lines: Option<i32>,
1194 pub expands: bool,
1195 pub force_line: bool,
1196 pub text_height_behavior: Option<TextHeightBehavior>,
1197 pub text_width_basis: TextWidthBasis,
1198 pub autofocus: bool,
1199 pub show_cursor: Option<bool>,
1200 pub show_selection_handles: bool,
1201 pub selection_color: Option<Color>,
1202 pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
1203 pub keyboard_type: Option<TextInputType>,
1204 pub text_input_action: Option<TextInputAction>,
1205 pub text_capitalization: TextCapitalization,
1206 pub on_changed: Option<Rc<dyn Fn(&mut App, String)>>,
1207 pub on_editing_complete: Option<Rc<dyn Fn(&mut App)>>,
1208 pub on_submitted: Option<Rc<dyn Fn(&mut App, String)>>,
1209 pub on_app_private_command: Option<AppPrivateCommandCallback>,
1210 pub on_selection_changed: Option<SelectionChangedCallback>,
1211 pub on_selection_handle_tapped: Option<Listener>,
1212 pub group_id: TypeId,
1213 pub on_tap_outside: Option<Rc<dyn Fn(&mut App, PointerDownEvent)>>,
1214 pub on_tap_up_outside: Option<Rc<dyn Fn(&mut App, PointerUpEvent)>>,
1215 pub input_formatters: Option<Vec<TextInputFormatterRef>>,
1216 pub mouse_cursor: Option<MouseCursorRef>,
1217 pub renderer_ignores_pointer: bool,
1218 pub cursor_width: f64,
1219 pub cursor_height: Option<f64>,
1220 pub cursor_radius: Option<Radius>,
1221 pub cursor_opacity_animates: bool,
1222 pub cursor_offset: Option<Offset>,
1223 pub paint_cursor_above_text: bool,
1224 pub selection_height_style: BoxHeightStyle,
1225 pub selection_width_style: BoxWidthStyle,
1226 pub scroll_padding: EdgeInsets,
1227 pub keyboard_appearance: Brightness,
1228 pub drag_start_behavior: DragStartBehavior,
1229 pub enable_interactive_selection: Option<bool>,
1230 pub select_all_on_focus: Option<bool>,
1231 pub scroll_controller: Option<ScrollControllerRef>,
1232 pub scroll_physics: Option<ScrollPhysicsRef>,
1233 pub autocorrection_text_rect_color: Option<Color>,
1234 pub toolbar_options: Option<ToolbarOptions>,
1235 pub autofill_hints: Vec<String>,
1236 pub autofill_client: Option<AnyAutofillClient>,
1237 pub clip_behavior: Clip,
1238 pub restoration_id: Option<String>,
1239 pub scroll_behavior: Option<ScrollBehaviorRef>,
1240 pub scribble_enabled: bool,
1241 pub stylus_handwriting_enabled: bool,
1242 pub enable_ime_personalized_learning: bool,
1243 pub content_insertion_configuration: Option<ContentInsertionConfiguration>,
1244 pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
1245 pub spell_check_configuration: Option<SpellCheckConfiguration>,
1246 pub magnifier_configuration: TextMagnifierConfiguration,
1247 pub undo_controller: Option<Ref<UndoHistoryController>>,
1248 pub hint_locales: Option<Vec<Locale>>,
1249 pub enable_inline_prediction: Option<bool>,
1250}
1251
1252impl EditableText {
1253 pub fn default_selection_height_style() -> BoxHeightStyle {
1255 if K_IS_WEB {
1256 BoxHeightStyle::Max
1257 } else {
1258 BoxHeightStyle::IncludeLineSpacingMiddle
1259 }
1260 }
1261
1262 pub fn default_selection_width_style() -> BoxWidthStyle {
1264 if K_IS_WEB {
1265 BoxWidthStyle::Tight
1266 } else {
1267 BoxWidthStyle::Max
1268 }
1269 }
1270
1271 pub const DEFAULT_STYLUS_HANDWRITING_ENABLED: bool = true;
1273
1274 pub fn debug_deterministic_cursor(app: &App) -> bool {
1277 app.debug_flag::<DebugDeterministicCursor>()
1278 }
1279
1280 pub fn set_debug_deterministic_cursor(app: &mut App, value: bool) {
1282 app.set_debug_flag::<DebugDeterministicCursor>(value);
1283 }
1284
1285 pub fn new(
1287 controller: TextEditingControllerRef,
1288 focus_node: FocusNodeRef,
1289 style: TextStyle,
1290 cursor_color: Color,
1291 background_cursor_color: Color,
1292 ) -> EditableText {
1293 let obscure_text = false;
1294 let read_only = false;
1295 let max_lines = Some(1);
1296 debug_assert!(!obscure_text || max_lines == Some(1));
1297 EditableText {
1298 key: None,
1299 controller,
1300 focus_node,
1301 read_only,
1302 obscuring_character: "\u{2022}".into(),
1303 obscure_text,
1304 autocorrect: None,
1305 smart_dashes_type: None,
1306 smart_quotes_type: None,
1307 enable_suggestions: true,
1308 style,
1309 strut_style: None,
1310 cursor_color,
1311 background_cursor_color,
1312 text_align: TextAlign::Start,
1313 text_direction: None,
1314 locale: None,
1315 text_scale_factor: None,
1316 text_scaler: None,
1317 max_lines,
1318 min_lines: None,
1319 expands: false,
1320 force_line: true,
1321 text_height_behavior: None,
1322 text_width_basis: TextWidthBasis::Parent,
1323 autofocus: false,
1324 show_cursor: None,
1325 show_selection_handles: false,
1326 selection_color: None,
1327 selection_controls: None,
1328 keyboard_type: None,
1329 text_input_action: None,
1330 text_capitalization: TextCapitalization::None,
1331 on_changed: None,
1332 on_editing_complete: None,
1333 on_submitted: None,
1334 on_app_private_command: None,
1335 on_selection_changed: None,
1336 on_selection_handle_tapped: None,
1337 group_id: TypeId::of::<EditableText>(),
1338 on_tap_outside: None,
1339 on_tap_up_outside: None,
1340 input_formatters: None,
1341 mouse_cursor: None,
1342 renderer_ignores_pointer: false,
1343 cursor_width: 2.0,
1344 cursor_height: None,
1345 cursor_radius: None,
1346 cursor_opacity_animates: false,
1347 cursor_offset: None,
1348 paint_cursor_above_text: false,
1349 selection_height_style: Self::default_selection_height_style(),
1350 selection_width_style: Self::default_selection_width_style(),
1351 scroll_padding: EdgeInsets::all(20.0),
1352 keyboard_appearance: Brightness::Light,
1353 drag_start_behavior: DragStartBehavior::Start,
1354 enable_interactive_selection: None,
1355 select_all_on_focus: None,
1356 scroll_controller: None,
1357 scroll_physics: None,
1358 autocorrection_text_rect_color: None,
1359 toolbar_options: None,
1360 autofill_hints: Vec::new(),
1361 autofill_client: None,
1362 clip_behavior: Clip::HardEdge,
1363 restoration_id: None,
1364 scroll_behavior: None,
1365 scribble_enabled: true,
1366 stylus_handwriting_enabled: Self::DEFAULT_STYLUS_HANDWRITING_ENABLED,
1367 enable_ime_personalized_learning: true,
1368 content_insertion_configuration: None,
1369 context_menu_builder: None,
1370 spell_check_configuration: None,
1371 magnifier_configuration: TextMagnifierConfiguration::DISABLED,
1372 undo_controller: None,
1373 hint_locales: None,
1374 enable_inline_prediction: None,
1375 }
1376 }
1377
1378 pub fn effective_strut_style(&self) -> StrutStyle {
1384 if let Some(strut_style) = &self.strut_style {
1385 return strut_style.inherit_from_text_style(Some(&self.style));
1386 }
1387 StrutStyle::from_text_style(&self.style)
1388 .force_strut_height(true)
1389 .build()
1390 }
1391
1392 pub fn key(mut self, key: KeyRef) -> Self {
1394 self.key = Some(key);
1395 self
1396 }
1397
1398 pub fn read_only(mut self, read_only: bool) -> Self {
1400 self.read_only = read_only;
1401 self
1402 }
1403
1404 pub fn obscuring_character(mut self, obscuring_character: impl Into<String>) -> Self {
1406 let obscuring_character = obscuring_character.into();
1407 debug_assert!(
1408 obscuring_character.chars().count() == 1,
1409 "obscuringCharacter must be a single character"
1410 );
1411 self.obscuring_character = obscuring_character;
1412 self
1413 }
1414
1415 pub fn obscure_text(mut self, obscure_text: bool) -> Self {
1417 debug_assert!(!obscure_text || self.max_lines == Some(1));
1418 self.obscure_text = obscure_text;
1419 self
1420 }
1421
1422 pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1424 self.autocorrect = Some(autocorrect);
1425 self
1426 }
1427
1428 pub fn smart_dashes_type(mut self, smart_dashes_type: SmartDashesType) -> Self {
1430 self.smart_dashes_type = Some(smart_dashes_type);
1431 self
1432 }
1433
1434 pub fn smart_quotes_type(mut self, smart_quotes_type: SmartQuotesType) -> Self {
1436 self.smart_quotes_type = Some(smart_quotes_type);
1437 self
1438 }
1439
1440 pub fn enable_suggestions(mut self, enable_suggestions: bool) -> Self {
1442 self.enable_suggestions = enable_suggestions;
1443 self
1444 }
1445
1446 pub fn strut_style(mut self, strut_style: StrutStyle) -> Self {
1448 self.strut_style = Some(strut_style);
1449 self
1450 }
1451
1452 pub fn text_align(mut self, text_align: TextAlign) -> Self {
1454 self.text_align = text_align;
1455 self
1456 }
1457
1458 pub fn text_direction(mut self, text_direction: TextDirection) -> Self {
1460 self.text_direction = Some(text_direction);
1461 self
1462 }
1463
1464 pub fn locale(mut self, locale: Locale) -> Self {
1466 self.locale = Some(locale);
1467 self
1468 }
1469
1470 pub fn text_scale_factor(mut self, text_scale_factor: f64) -> Self {
1472 self.text_scale_factor = Some(text_scale_factor);
1473 self
1474 }
1475
1476 pub fn text_scaler(mut self, text_scaler: TextScaler) -> Self {
1478 self.text_scaler = Some(text_scaler);
1479 self
1480 }
1481
1482 pub fn max_lines(mut self, max_lines: Option<i32>) -> Self {
1484 debug_assert!(
1485 max_lines.is_none_or(|lines| self.min_lines.is_none_or(|min| lines >= min)),
1486 "minLines can't be greater than maxLines"
1487 );
1488 debug_assert!(!self.expands || max_lines.is_none());
1489 debug_assert!(!self.obscure_text || max_lines == Some(1));
1490 self.max_lines = max_lines;
1491 self
1492 }
1493
1494 pub fn min_lines(mut self, min_lines: i32) -> Self {
1496 debug_assert!(min_lines > 0);
1497 debug_assert!(
1498 self.max_lines.is_none_or(|max| max >= min_lines),
1499 "minLines can't be greater than maxLines"
1500 );
1501 debug_assert!(!self.expands);
1502 self.min_lines = Some(min_lines);
1503 self
1504 }
1505
1506 pub fn expands(mut self, expands: bool) -> Self {
1508 debug_assert!(!expands || (self.max_lines.is_none() && self.min_lines.is_none()));
1509 self.expands = expands;
1510 self
1511 }
1512
1513 pub fn force_line(mut self, force_line: bool) -> Self {
1515 self.force_line = force_line;
1516 self
1517 }
1518
1519 pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> Self {
1521 self.text_height_behavior = Some(text_height_behavior);
1522 self
1523 }
1524
1525 pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> Self {
1527 self.text_width_basis = text_width_basis;
1528 self
1529 }
1530
1531 pub fn autofocus(mut self, autofocus: bool) -> Self {
1533 self.autofocus = autofocus;
1534 self
1535 }
1536
1537 pub fn show_cursor(mut self, show_cursor: bool) -> Self {
1539 self.show_cursor = Some(show_cursor);
1540 self
1541 }
1542
1543 pub fn show_selection_handles(mut self, show_selection_handles: bool) -> Self {
1545 self.show_selection_handles = show_selection_handles;
1546 self
1547 }
1548
1549 pub fn selection_color(mut self, selection_color: Color) -> Self {
1551 self.selection_color = Some(selection_color);
1552 self
1553 }
1554
1555 pub fn selection_controls(mut self, selection_controls: Rc<dyn TextSelectionControls>) -> Self {
1557 self.selection_controls = Some(selection_controls);
1558 self
1559 }
1560
1561 pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> Self {
1563 self.keyboard_type = Some(keyboard_type);
1564 self
1565 }
1566
1567 pub fn text_input_action(mut self, text_input_action: TextInputAction) -> Self {
1569 self.text_input_action = Some(text_input_action);
1570 self
1571 }
1572
1573 pub fn text_capitalization(mut self, text_capitalization: TextCapitalization) -> Self {
1575 self.text_capitalization = text_capitalization;
1576 self
1577 }
1578
1579 pub fn on_changed(mut self, on_changed: impl Fn(&mut App, String) + 'static) -> Self {
1581 self.on_changed = Some(Rc::new(on_changed));
1582 self
1583 }
1584
1585 pub fn on_editing_complete(mut self, on_editing_complete: impl Fn(&mut App) + 'static) -> Self {
1587 self.on_editing_complete = Some(Rc::new(on_editing_complete));
1588 self
1589 }
1590
1591 pub fn on_submitted(mut self, on_submitted: impl Fn(&mut App, String) + 'static) -> Self {
1593 self.on_submitted = Some(Rc::new(on_submitted));
1594 self
1595 }
1596
1597 pub fn on_app_private_command(
1599 mut self,
1600 on_app_private_command: impl Fn(&mut App, &str) + 'static,
1601 ) -> Self {
1602 self.on_app_private_command = Some(Rc::new(on_app_private_command));
1603 self
1604 }
1605
1606 pub fn on_selection_changed(
1608 mut self,
1609 on_selection_changed: impl Fn(&mut App, TextSelection, Option<SelectionChangedCause>) + 'static,
1610 ) -> Self {
1611 self.on_selection_changed = Some(Rc::new(on_selection_changed));
1612 self
1613 }
1614
1615 pub fn on_selection_handle_tapped(mut self, on_selection_handle_tapped: Listener) -> Self {
1617 self.on_selection_handle_tapped = Some(on_selection_handle_tapped);
1618 self
1619 }
1620
1621 pub fn group_id(mut self, group_id: TypeId) -> Self {
1623 self.group_id = group_id;
1624 self
1625 }
1626
1627 pub fn on_tap_outside(
1629 mut self,
1630 on_tap_outside: impl Fn(&mut App, PointerDownEvent) + 'static,
1631 ) -> Self {
1632 self.on_tap_outside = Some(Rc::new(on_tap_outside));
1633 self
1634 }
1635
1636 pub fn on_tap_up_outside(
1638 mut self,
1639 on_tap_up_outside: impl Fn(&mut App, PointerUpEvent) + 'static,
1640 ) -> Self {
1641 self.on_tap_up_outside = Some(Rc::new(on_tap_up_outside));
1642 self
1643 }
1644
1645 pub fn input_formatters(mut self, input_formatters: Vec<TextInputFormatterRef>) -> Self {
1647 self.input_formatters = Some(input_formatters);
1648 self
1649 }
1650
1651 pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Self {
1653 self.mouse_cursor = Some(mouse_cursor);
1654 self
1655 }
1656
1657 pub fn renderer_ignores_pointer(mut self, renderer_ignores_pointer: bool) -> Self {
1659 self.renderer_ignores_pointer = renderer_ignores_pointer;
1660 self
1661 }
1662
1663 pub fn cursor_width(mut self, cursor_width: f64) -> Self {
1665 self.cursor_width = cursor_width;
1666 self
1667 }
1668
1669 pub fn cursor_height(mut self, cursor_height: f64) -> Self {
1671 self.cursor_height = Some(cursor_height);
1672 self
1673 }
1674
1675 pub fn cursor_radius(mut self, cursor_radius: Radius) -> Self {
1677 self.cursor_radius = Some(cursor_radius);
1678 self
1679 }
1680
1681 pub fn cursor_opacity_animates(mut self, cursor_opacity_animates: bool) -> Self {
1683 self.cursor_opacity_animates = cursor_opacity_animates;
1684 self
1685 }
1686
1687 pub fn cursor_offset(mut self, cursor_offset: Offset) -> Self {
1689 self.cursor_offset = Some(cursor_offset);
1690 self
1691 }
1692
1693 pub fn paint_cursor_above_text(mut self, paint_cursor_above_text: bool) -> Self {
1695 self.paint_cursor_above_text = paint_cursor_above_text;
1696 self
1697 }
1698
1699 pub fn selection_height_style(mut self, selection_height_style: BoxHeightStyle) -> Self {
1701 self.selection_height_style = selection_height_style;
1702 self
1703 }
1704
1705 pub fn selection_width_style(mut self, selection_width_style: BoxWidthStyle) -> Self {
1707 self.selection_width_style = selection_width_style;
1708 self
1709 }
1710
1711 pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> Self {
1713 self.scroll_padding = scroll_padding;
1714 self
1715 }
1716
1717 pub fn keyboard_appearance(mut self, keyboard_appearance: Brightness) -> Self {
1719 self.keyboard_appearance = keyboard_appearance;
1720 self
1721 }
1722
1723 pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Self {
1725 self.drag_start_behavior = drag_start_behavior;
1726 self
1727 }
1728
1729 pub fn enable_interactive_selection(mut self, enable_interactive_selection: bool) -> Self {
1731 self.enable_interactive_selection = Some(enable_interactive_selection);
1732 self
1733 }
1734
1735 pub fn select_all_on_focus(mut self, select_all_on_focus: bool) -> Self {
1737 self.select_all_on_focus = Some(select_all_on_focus);
1738 self
1739 }
1740
1741 pub fn scroll_controller(mut self, scroll_controller: ScrollControllerRef) -> Self {
1743 self.scroll_controller = Some(scroll_controller);
1744 self
1745 }
1746
1747 pub fn scroll_physics(mut self, scroll_physics: ScrollPhysicsRef) -> Self {
1749 self.scroll_physics = Some(scroll_physics);
1750 self
1751 }
1752
1753 pub fn autocorrection_text_rect_color(mut self, autocorrection_text_rect_color: Color) -> Self {
1755 self.autocorrection_text_rect_color = Some(autocorrection_text_rect_color);
1756 self
1757 }
1758
1759 pub fn toolbar_options(mut self, toolbar_options: ToolbarOptions) -> Self {
1761 self.toolbar_options = Some(toolbar_options);
1762 self
1763 }
1764
1765 pub fn autofill_hints(mut self, autofill_hints: Vec<String>) -> Self {
1767 self.autofill_hints = autofill_hints;
1768 self
1769 }
1770
1771 pub fn autofill_client(mut self, autofill_client: AnyAutofillClient) -> Self {
1773 self.autofill_client = Some(autofill_client);
1774 self
1775 }
1776
1777 pub fn clip_behavior(mut self, clip_behavior: Clip) -> Self {
1779 self.clip_behavior = clip_behavior;
1780 self
1781 }
1782
1783 pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> Self {
1785 self.restoration_id = Some(restoration_id.into());
1786 self
1787 }
1788
1789 pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> Self {
1791 self.scroll_behavior = Some(scroll_behavior);
1792 self
1793 }
1794
1795 pub fn scribble_enabled(mut self, scribble_enabled: bool) -> Self {
1797 self.scribble_enabled = scribble_enabled;
1798 self
1799 }
1800
1801 pub fn stylus_handwriting_enabled(mut self, stylus_handwriting_enabled: bool) -> Self {
1803 self.stylus_handwriting_enabled = stylus_handwriting_enabled;
1804 self
1805 }
1806
1807 pub fn enable_ime_personalized_learning(
1809 mut self,
1810 enable_ime_personalized_learning: bool,
1811 ) -> Self {
1812 self.enable_ime_personalized_learning = enable_ime_personalized_learning;
1813 self
1814 }
1815
1816 pub fn content_insertion_configuration(
1818 mut self,
1819 content_insertion_configuration: ContentInsertionConfiguration,
1820 ) -> Self {
1821 self.content_insertion_configuration = Some(content_insertion_configuration);
1822 self
1823 }
1824
1825 pub fn context_menu_builder(
1827 mut self,
1828 context_menu_builder: EditableTextContextMenuBuilder,
1829 ) -> Self {
1830 self.context_menu_builder = Some(context_menu_builder);
1831 self
1832 }
1833
1834 pub fn spell_check_configuration(
1836 mut self,
1837 spell_check_configuration: SpellCheckConfiguration,
1838 ) -> Self {
1839 if cfg!(debug_assertions)
1840 && spell_check_configuration.spell_check_enabled()
1841 && spell_check_configuration.misspelled_text_style.is_none()
1842 {
1843 debug_assert!(
1844 false,
1845 "spellCheckConfiguration must specify a misspelledTextStyle if spell check behavior is desired"
1846 );
1847 }
1848 self.spell_check_configuration = Some(spell_check_configuration);
1849 self
1850 }
1851
1852 pub fn magnifier_configuration(
1854 mut self,
1855 magnifier_configuration: TextMagnifierConfiguration,
1856 ) -> Self {
1857 self.magnifier_configuration = magnifier_configuration;
1858 self
1859 }
1860
1861 pub fn undo_controller(mut self, undo_controller: Ref<UndoHistoryController>) -> Self {
1863 self.undo_controller = Some(undo_controller);
1864 self
1865 }
1866
1867 pub fn hint_locales(mut self, hint_locales: Vec<Locale>) -> Self {
1869 self.hint_locales = Some(hint_locales);
1870 self
1871 }
1872
1873 pub fn enable_inline_prediction(mut self, enable_inline_prediction: bool) -> Self {
1875 self.enable_inline_prediction = Some(enable_inline_prediction);
1876 self
1877 }
1878
1879 #[allow(clippy::too_many_arguments)]
1882 pub fn get_editable_button_items(
1883 clipboard_status: Option<ClipboardStatus>,
1884 on_copy: Option<Listener>,
1885 on_cut: Option<Listener>,
1886 on_paste: Option<Listener>,
1887 on_select_all: Option<Listener>,
1888 on_look_up: Option<Listener>,
1889 on_search_web: Option<Listener>,
1890 on_share: Option<Listener>,
1891 on_live_text_input: Option<Listener>,
1892 target_platform: TargetPlatform,
1893 ) -> Vec<ContextMenuButtonItem> {
1894 let mut result_button_item = Vec::new();
1895 if on_paste.is_none() || clipboard_status != Some(ClipboardStatus::Unknown) {
1896 let show_share_before_select_all = target_platform == TargetPlatform::Android;
1897 if let Some(on_cut) = on_cut {
1898 result_button_item.push(
1899 ContextMenuButtonItem::new(Some(on_cut)).r#type(ContextMenuButtonType::Cut),
1900 );
1901 }
1902 if let Some(on_copy) = on_copy {
1903 result_button_item.push(
1904 ContextMenuButtonItem::new(Some(on_copy)).r#type(ContextMenuButtonType::Copy),
1905 );
1906 }
1907 if let Some(on_paste) = on_paste {
1908 result_button_item.push(
1909 ContextMenuButtonItem::new(Some(on_paste)).r#type(ContextMenuButtonType::Paste),
1910 );
1911 }
1912 if let Some(on_share) = on_share.clone()
1913 && show_share_before_select_all
1914 {
1915 result_button_item.push(
1916 ContextMenuButtonItem::new(Some(on_share)).r#type(ContextMenuButtonType::Share),
1917 );
1918 }
1919 if let Some(on_select_all) = on_select_all {
1920 result_button_item.push(
1921 ContextMenuButtonItem::new(Some(on_select_all))
1922 .r#type(ContextMenuButtonType::SelectAll),
1923 );
1924 }
1925 if let Some(on_look_up) = on_look_up {
1926 result_button_item.push(
1927 ContextMenuButtonItem::new(Some(on_look_up))
1928 .r#type(ContextMenuButtonType::LookUp),
1929 );
1930 }
1931 if let Some(on_search_web) = on_search_web {
1932 result_button_item.push(
1933 ContextMenuButtonItem::new(Some(on_search_web))
1934 .r#type(ContextMenuButtonType::SearchWeb),
1935 );
1936 }
1937 if let Some(on_share) = on_share
1938 && !show_share_before_select_all
1939 {
1940 result_button_item.push(
1941 ContextMenuButtonItem::new(Some(on_share)).r#type(ContextMenuButtonType::Share),
1942 );
1943 }
1944 }
1945 if let Some(on_live_text_input) = on_live_text_input {
1946 result_button_item.push(
1947 ContextMenuButtonItem::new(Some(on_live_text_input))
1948 .r#type(ContextMenuButtonType::LiveTextInput),
1949 );
1950 }
1951 result_button_item
1952 }
1953
1954 fn user_selection_enabled(&self) -> bool {
1955 self.effective_enable_interactive_selection() && (!self.read_only || !self.obscure_text)
1956 }
1957
1958 pub fn effective_autocorrect(&self, app: &App) -> bool {
1960 self.autocorrect.unwrap_or_else(|| {
1961 infer_autocorrect(&self.autofill_hints, app.platform().target_platform())
1962 })
1963 }
1964
1965 pub fn effective_smart_dashes_type(&self) -> SmartDashesType {
1967 self.smart_dashes_type.unwrap_or(if self.obscure_text {
1968 SmartDashesType::Disabled
1969 } else {
1970 SmartDashesType::Enabled
1971 })
1972 }
1973
1974 pub fn effective_smart_quotes_type(&self) -> SmartQuotesType {
1976 self.smart_quotes_type.unwrap_or(if self.obscure_text {
1977 SmartQuotesType::Disabled
1978 } else {
1979 SmartQuotesType::Enabled
1980 })
1981 }
1982
1983 pub fn effective_enable_interactive_selection(&self) -> bool {
1985 self.enable_interactive_selection
1986 .unwrap_or(!self.read_only || !self.obscure_text)
1987 }
1988
1989 pub fn effective_select_all_on_focus(&self, app: &App) -> bool {
1991 self.select_all_on_focus
1992 .unwrap_or_else(|| default_select_all_on_focus(app.platform().target_platform()))
1993 }
1994
1995 pub fn effective_toolbar_options(&self) -> ToolbarOptions {
1997 if self.has_handle_controls() && self.toolbar_options.is_none() {
1998 return ToolbarOptions::EMPTY;
1999 }
2000 self.toolbar_options
2001 .unwrap_or_else(|| default_toolbar_options(self.read_only, self.obscure_text))
2002 }
2003
2004 fn has_handle_controls(&self) -> bool {
2006 self.selection_controls
2007 .as_ref()
2008 .is_some_and(|controls| controls.as_text_selection_handle_controls().is_some())
2009 }
2010
2011 pub fn effective_keyboard_type(&self, app: &App) -> TextInputType {
2013 self.keyboard_type.unwrap_or_else(|| {
2014 infer_keyboard_type(
2015 &self.autofill_hints,
2016 self.max_lines,
2017 app.platform().target_platform(),
2018 )
2019 })
2020 }
2021
2022 pub fn effective_input_formatters(&self) -> Vec<TextInputFormatterRef> {
2024 let given = self.input_formatters.iter().flatten().cloned();
2025 if self.max_lines == Some(1) {
2026 std::iter::once(FilteringTextInputFormatter::single_line_formatter())
2027 .chain(given)
2028 .collect()
2029 } else {
2030 given.collect()
2031 }
2032 }
2033
2034 pub fn effective_show_cursor(&self) -> bool {
2036 self.show_cursor.unwrap_or(!self.read_only)
2037 }
2038}
2039
2040impl Debug for EditableText {
2041 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2042 f.debug_struct("EditableText")
2043 .field("controller", &self.controller)
2044 .field("focus_node", &self.focus_node)
2045 .field("obscure_text", &self.obscure_text)
2046 .field("read_only", &self.read_only)
2047 .field("style", &self.style)
2048 .field("max_lines", &self.max_lines)
2049 .finish_non_exhaustive()
2050 }
2051}
2052
2053impl StatefulWidget for EditableText {
2054 type State = EditableTextState;
2055
2056 fn key(&self) -> Option<&KeyRef> {
2057 self.key.as_ref()
2058 }
2059
2060 fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2061 properties.add(DiagnosticsProperty::<String>::new(
2062 "controller",
2063 Some(self.controller.to_string(app)),
2064 ));
2065 properties.add(DiagnosticsProperty::<String>::new(
2066 "focusNode",
2067 Some(self.focus_node.to_string(app)),
2068 ));
2069 properties.add(
2070 DiagnosticsProperty::<bool>::new("obscureText", Some(self.obscure_text))
2071 .default_value(Some(false)),
2072 );
2073 properties.add(
2074 DiagnosticsProperty::<bool>::new("readOnly", Some(self.read_only))
2075 .default_value(Some(false)),
2076 );
2077 properties.add(
2078 DiagnosticsProperty::<bool>::new("autocorrect", self.autocorrect).default_value(None),
2079 );
2080 properties.add(
2081 EnumProperty::new(
2082 "smartDashesType",
2083 self.smart_dashes_type.unwrap_or(if self.obscure_text {
2084 SmartDashesType::Disabled
2085 } else {
2086 SmartDashesType::Enabled
2087 }),
2088 )
2089 .default_value(Some(if self.obscure_text {
2090 SmartDashesType::Disabled
2091 } else {
2092 SmartDashesType::Enabled
2093 })),
2094 );
2095 properties.add(
2096 EnumProperty::new(
2097 "smartQuotesType",
2098 self.smart_quotes_type.unwrap_or(if self.obscure_text {
2099 SmartQuotesType::Disabled
2100 } else {
2101 SmartQuotesType::Enabled
2102 }),
2103 )
2104 .default_value(Some(if self.obscure_text {
2105 SmartQuotesType::Disabled
2106 } else {
2107 SmartQuotesType::Enabled
2108 })),
2109 );
2110 properties.add(
2111 DiagnosticsProperty::<bool>::new("enableSuggestions", Some(self.enable_suggestions))
2112 .default_value(Some(true)),
2113 );
2114 waft_foundation::Diagnosticable::debug_fill_properties(&self.style, properties);
2115 properties.add(
2116 EnumProperty::<TextAlign>::new("textAlign", Some(self.text_align)).default_value(None),
2117 );
2118 properties.add(
2119 EnumProperty::<TextDirection>::new("textDirection", self.text_direction)
2120 .default_value(None),
2121 );
2122 properties.add(
2123 DiagnosticsProperty::<Locale>::new("locale", self.locale.clone()).default_value(None),
2124 );
2125 properties.add(
2126 DiagnosticsProperty::<TextScaler>::new("textScaler", self.text_scaler.clone())
2127 .default_value(None),
2128 );
2129 properties.add(IntProperty::<i32>::new("maxLines", self.max_lines).default_value(Some(1)));
2130 properties.add(IntProperty::<i32>::new("minLines", self.min_lines).default_value(None));
2131 properties.add(
2132 DiagnosticsProperty::<bool>::new("expands", Some(self.expands))
2133 .default_value(Some(false)),
2134 );
2135 properties.add(
2136 DiagnosticsProperty::<bool>::new("autofocus", Some(self.autofocus))
2137 .default_value(Some(false)),
2138 );
2139 properties.add(
2140 DiagnosticsProperty::<TextInputType>::new("keyboardType", self.keyboard_type)
2141 .default_value(None),
2142 );
2143 properties.add(
2144 DiagnosticsProperty::<String>::new(
2145 "scrollController",
2146 self.scroll_controller
2147 .as_ref()
2148 .map(|controller| controller.to_string(app)),
2149 )
2150 .default_value(None),
2151 );
2152 properties.add(
2153 DiagnosticsProperty::<String>::new(
2154 "scrollPhysics",
2155 self.scroll_physics
2156 .as_ref()
2157 .map(|physics| format!("{physics:?}")),
2158 )
2159 .default_value(None),
2160 );
2161 properties.add(
2162 DiagnosticsProperty::<String>::new(
2163 "autofillHints",
2164 Some(format!("[{}]", self.autofill_hints.join(", "))),
2165 )
2166 .default_value(None),
2167 );
2168 properties.add(
2169 DiagnosticsProperty::<String>::new(
2170 "textHeightBehavior",
2171 self.text_height_behavior
2172 .map(|behavior| behavior.to_string()),
2173 )
2174 .default_value(None),
2175 );
2176 properties.add(
2177 DiagnosticsProperty::<bool>::new("scribbleEnabled", Some(self.scribble_enabled))
2178 .default_value(Some(true)),
2179 );
2180 properties.add(
2181 DiagnosticsProperty::<bool>::new(
2182 "stylusHandwritingEnabled",
2183 Some(self.stylus_handwriting_enabled),
2184 )
2185 .default_value(Some(Self::DEFAULT_STYLUS_HANDWRITING_ENABLED)),
2186 );
2187 properties.add(
2188 DiagnosticsProperty::<bool>::new(
2189 "enableIMEPersonalizedLearning",
2190 Some(self.enable_ime_personalized_learning),
2191 )
2192 .default_value(Some(true)),
2193 );
2194 properties.add(
2195 DiagnosticsProperty::<bool>::new(
2196 "enableInlinePrediction",
2197 self.enable_inline_prediction,
2198 )
2199 .default_value(None),
2200 );
2201 properties.add(
2202 DiagnosticsProperty::<bool>::new(
2203 "enableInteractiveSelection",
2204 self.enable_interactive_selection,
2205 )
2206 .default_value(Some(true)),
2207 );
2208 properties.add(
2209 DiagnosticsProperty::<String>::new(
2210 "undoController",
2211 self.undo_controller
2212 .as_ref()
2213 .map(|controller| controller.handle().to_string(app)),
2214 )
2215 .default_value(None),
2216 );
2217 properties.add(
2218 DiagnosticsProperty::<String>::new(
2219 "spellCheckConfiguration",
2220 self.spell_check_configuration
2221 .as_ref()
2222 .map(|configuration| format!("{configuration:?}")),
2223 )
2224 .default_value(None),
2225 );
2226 let describe_mime_types = |mime_types: &[String]| format!("[{}]", mime_types.join(", "));
2227 let (content_commit_mime_types, content_commit_mime_types_default): (
2228 Vec<String>,
2229 Vec<String>,
2230 ) = match &self.content_insertion_configuration {
2231 Some(configuration) => (
2232 configuration.allowed_mime_types.clone(),
2233 K_DEFAULT_CONTENT_INSERTION_MIME_TYPES
2234 .iter()
2235 .map(|mime_type| mime_type.to_string())
2236 .collect(),
2237 ),
2238 None => (Vec::new(), Vec::new()),
2239 };
2240 properties.add(
2241 DiagnosticsProperty::<String>::new(
2242 "contentCommitMimeTypes",
2243 Some(describe_mime_types(&content_commit_mime_types)),
2244 )
2245 .default_value(Some(describe_mime_types(
2246 &content_commit_mime_types_default,
2247 ))),
2248 );
2249 properties.add(
2250 DiagnosticsProperty::<String>::new(
2251 "hintLocales",
2252 self.hint_locales.as_ref().map(|locales| {
2253 format!(
2254 "[{}]",
2255 locales
2256 .iter()
2257 .map(|locale| locale.to_string())
2258 .collect::<Vec<String>>()
2259 .join(", ")
2260 )
2261 }),
2262 )
2263 .default_value(None),
2264 );
2265 }
2266
2267 fn create_state(&self) -> EditableTextState {
2268 EditableTextState {
2269 state: StateData::new(),
2270 automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
2271 ticker_provider: TickerProviderStateMixinData::new(),
2272 cursor_timer: None,
2273 backing_cursor_blink_opacity_controller: None,
2274 cursor_visibility_notifier: None,
2275 clipboard_status: None,
2276 live_text_input_status: None,
2277 text_input_connection: None,
2278 view_id: None,
2279 composite_callback: None,
2280 last_known_remote_text_editing_value: None,
2281 scribble_cache_key: None,
2282 internal_scroll_controller: None,
2283 toolbar_layer_link: None,
2284 start_handle_layer_link: None,
2285 end_handle_layer_link: None,
2286 did_auto_focus: false,
2287 process_text_service: Rc::new(DefaultProcessTextService),
2288 process_text_actions: Vec::new(),
2289 spell_check_configuration: SpellCheckConfiguration::disabled(),
2290 spell_check_results: None,
2291 current_autofill_scope: None,
2292 app_lifecycle_listener: None,
2293 just_resumed: false,
2294 had_focus_on_tap_down: false,
2295 actions: None,
2296 vertical_movement_run: None,
2297 run_selection: None,
2298 editable_key: GlobalKey::new(),
2299 scrollable_key: GlobalKey::new(),
2300 style: TextStyle::new(),
2301 tickers_enabled: true,
2302 batch_edit_depth: 0,
2303 current_prompt_rect_range: None,
2304 obscure_show_char_ticks_pending: 0,
2305 obscure_latest_char_index: None,
2306 last_orientation: None,
2307 binding_observer: None,
2308 registered_as_observer: false,
2309 show_caret_on_screen_scheduled: false,
2310 last_bottom_view_inset: 0.0,
2311 has_focus: false,
2312 next_focus_change_is_internal: false,
2313 selection_overlay: None,
2314 render_editable: Cell::new(None),
2315 }
2316 }
2317}
2318
2319fn default_toolbar_options(read_only: bool, obscure_text: bool) -> ToolbarOptions {
2320 if obscure_text {
2321 if read_only {
2322 ToolbarOptions::EMPTY
2323 } else {
2324 ToolbarOptions::new().select_all(true).paste(true)
2325 }
2326 } else if read_only {
2327 ToolbarOptions::new().select_all(true).copy(true)
2328 } else {
2329 ToolbarOptions::new()
2330 .copy(true)
2331 .cut(true)
2332 .select_all(true)
2333 .paste(true)
2334 }
2335}
2336
2337fn find_render_editable(
2338 app: &App,
2339 object: AnyRenderObject,
2340) -> Option<RenderHandle<RenderEditable>> {
2341 if let Some(editable) = object.downcast::<RenderEditable>(app) {
2342 return Some(editable);
2343 }
2344 let mut found = None;
2345 object.visit_children(app, &mut |child| {
2346 if found.is_none() {
2347 found = find_render_editable(app, child);
2348 }
2349 });
2350 found
2351}
2352
2353fn infer_autocorrect(autofill_hints: &[String], platform: TargetPlatform) -> bool {
2354 if autofill_hints.is_empty() || K_IS_WEB {
2355 return true;
2356 }
2357 match platform {
2358 TargetPlatform::IOS => {
2359 let password_related_hint = autofill_hints.iter().any(|hint| {
2362 hint == AutofillHints::USERNAME
2363 || hint == AutofillHints::PASSWORD
2364 || hint == AutofillHints::NEW_PASSWORD
2365 });
2366 if password_related_hint {
2367 return false;
2370 }
2371 }
2372 TargetPlatform::MacOS
2373 | TargetPlatform::Android
2374 | TargetPlatform::Fuchsia
2375 | TargetPlatform::Linux
2376 | TargetPlatform::Windows => {}
2377 }
2378 true
2379}
2380
2381fn infer_keyboard_type(
2382 autofill_hints: &[String],
2383 max_lines: Option<i32>,
2384 platform: TargetPlatform,
2385) -> TextInputType {
2386 let Some(effective_hint) = autofill_hints.first() else {
2387 return if max_lines == Some(1) {
2388 TextInputType::TEXT
2389 } else {
2390 TextInputType::MULTILINE
2391 };
2392 };
2393 let effective_hint = effective_hint.as_str();
2394
2395 if !K_IS_WEB {
2400 match platform {
2401 TargetPlatform::IOS | TargetPlatform::MacOS => {
2402 if let Some(keyboard_type) = ios_keyboard_type(effective_hint) {
2403 return keyboard_type;
2404 }
2405 }
2406 TargetPlatform::Android
2407 | TargetPlatform::Fuchsia
2408 | TargetPlatform::Linux
2409 | TargetPlatform::Windows => {}
2410 }
2411 }
2412
2413 if max_lines != Some(1) {
2414 return TextInputType::MULTILINE;
2415 }
2416
2417 match effective_hint {
2418 AutofillHints::ADDRESS_CITY
2419 | AutofillHints::ADDRESS_CITY_AND_STATE
2420 | AutofillHints::ADDRESS_STATE => TextInputType::STREET_ADDRESS,
2421 AutofillHints::BIRTHDAY
2422 | AutofillHints::BIRTHDAY_DAY
2423 | AutofillHints::BIRTHDAY_MONTH
2424 | AutofillHints::BIRTHDAY_YEAR => TextInputType::DATETIME,
2425 AutofillHints::COUNTRY_CODE => TextInputType::NUMBER,
2426 AutofillHints::COUNTRY_NAME => TextInputType::TEXT,
2427 AutofillHints::CREDIT_CARD_EXPIRATION_DATE
2428 | AutofillHints::CREDIT_CARD_EXPIRATION_DAY
2429 | AutofillHints::CREDIT_CARD_EXPIRATION_MONTH
2430 | AutofillHints::CREDIT_CARD_EXPIRATION_YEAR => TextInputType::DATETIME,
2431 AutofillHints::CREDIT_CARD_FAMILY_NAME
2432 | AutofillHints::CREDIT_CARD_GIVEN_NAME
2433 | AutofillHints::CREDIT_CARD_MIDDLE_NAME
2434 | AutofillHints::CREDIT_CARD_NAME => TextInputType::NAME,
2435 AutofillHints::CREDIT_CARD_NUMBER | AutofillHints::CREDIT_CARD_SECURITY_CODE => {
2436 TextInputType::NUMBER
2437 }
2438 AutofillHints::CREDIT_CARD_TYPE => TextInputType::TEXT,
2439 AutofillHints::EMAIL => TextInputType::EMAIL_ADDRESS,
2440 AutofillHints::EMAIL_OTP_CODE => TextInputType::TEXT,
2441 AutofillHints::FAMILY_NAME => TextInputType::NAME,
2442 AutofillHints::FULL_STREET_ADDRESS => TextInputType::STREET_ADDRESS,
2443 AutofillHints::GENDER => TextInputType::TEXT,
2444 AutofillHints::GIVEN_NAME => TextInputType::NAME,
2445 AutofillHints::IMPP => TextInputType::URL,
2446 AutofillHints::JOB_TITLE | AutofillHints::LANGUAGE => TextInputType::TEXT,
2447 AutofillHints::LOCATION => TextInputType::STREET_ADDRESS,
2448 AutofillHints::MIDDLE_INITIAL
2449 | AutofillHints::MIDDLE_NAME
2450 | AutofillHints::NAME
2451 | AutofillHints::NAME_PREFIX
2452 | AutofillHints::NAME_SUFFIX => TextInputType::NAME,
2453 AutofillHints::NEW_PASSWORD
2454 | AutofillHints::NEW_USERNAME
2455 | AutofillHints::NICKNAME
2456 | AutofillHints::ONE_TIME_CODE
2457 | AutofillHints::ORGANIZATION_NAME
2458 | AutofillHints::PASSWORD
2459 | AutofillHints::PHOTO => TextInputType::TEXT,
2460 AutofillHints::POSTAL_ADDRESS | AutofillHints::POSTAL_ADDRESS_EXTENDED => {
2461 TextInputType::STREET_ADDRESS
2462 }
2463 AutofillHints::POSTAL_ADDRESS_EXTENDED_POSTAL_CODE | AutofillHints::POSTAL_CODE => {
2464 TextInputType::NUMBER
2465 }
2466 AutofillHints::STREET_ADDRESS_LEVEL1
2467 | AutofillHints::STREET_ADDRESS_LEVEL2
2468 | AutofillHints::STREET_ADDRESS_LEVEL3
2469 | AutofillHints::STREET_ADDRESS_LEVEL4
2470 | AutofillHints::STREET_ADDRESS_LINE1
2471 | AutofillHints::STREET_ADDRESS_LINE2
2472 | AutofillHints::STREET_ADDRESS_LINE3
2473 | AutofillHints::SUBLOCALITY => TextInputType::STREET_ADDRESS,
2474 AutofillHints::TELEPHONE_NUMBER
2475 | AutofillHints::TELEPHONE_NUMBER_AREA_CODE
2476 | AutofillHints::TELEPHONE_NUMBER_COUNTRY_CODE
2477 | AutofillHints::TELEPHONE_NUMBER_DEVICE
2478 | AutofillHints::TELEPHONE_NUMBER_EXTENSION
2479 | AutofillHints::TELEPHONE_NUMBER_LOCAL
2480 | AutofillHints::TELEPHONE_NUMBER_LOCAL_PREFIX
2481 | AutofillHints::TELEPHONE_NUMBER_LOCAL_SUFFIX
2482 | AutofillHints::TELEPHONE_NUMBER_NATIONAL => TextInputType::PHONE,
2483 AutofillHints::TRANSACTION_AMOUNT => TextInputType::number_with_options().decimal(true),
2484 AutofillHints::TRANSACTION_CURRENCY => TextInputType::TEXT,
2485 AutofillHints::URL => TextInputType::URL,
2486 AutofillHints::USERNAME => TextInputType::TEXT,
2487 _ => TextInputType::TEXT,
2488 }
2489}
2490
2491fn ios_keyboard_type(hint: &str) -> Option<TextInputType> {
2495 let keyboard_type = match hint {
2496 AutofillHints::ADDRESS_CITY => TextInputType::NAME,
2497 AutofillHints::ADDRESS_CITY_AND_STATE => TextInputType::NAME, AutofillHints::ADDRESS_STATE | AutofillHints::COUNTRY_NAME => TextInputType::NAME,
2499 AutofillHints::CREDIT_CARD_NUMBER => TextInputType::NUMBER, AutofillHints::EMAIL => TextInputType::EMAIL_ADDRESS,
2501 AutofillHints::EMAIL_OTP_CODE => TextInputType::TEXT,
2502 AutofillHints::FAMILY_NAME
2503 | AutofillHints::FULL_STREET_ADDRESS
2504 | AutofillHints::GIVEN_NAME => TextInputType::NAME,
2505 AutofillHints::JOB_TITLE => TextInputType::NAME, AutofillHints::LOCATION => TextInputType::NAME, AutofillHints::MIDDLE_NAME => TextInputType::NAME, AutofillHints::NAME => TextInputType::NAME,
2509 AutofillHints::NAME_PREFIX => TextInputType::NAME, AutofillHints::NAME_SUFFIX => TextInputType::NAME, AutofillHints::NEW_PASSWORD | AutofillHints::NEW_USERNAME => TextInputType::TEXT,
2512 AutofillHints::NICKNAME => TextInputType::NAME, AutofillHints::ONE_TIME_CODE => TextInputType::NUMBER,
2514 AutofillHints::ORGANIZATION_NAME => TextInputType::TEXT, AutofillHints::PASSWORD => TextInputType::TEXT,
2516 AutofillHints::POSTAL_CODE | AutofillHints::STREET_ADDRESS_LINE1 => TextInputType::NAME,
2517 AutofillHints::STREET_ADDRESS_LINE2 => TextInputType::NAME, AutofillHints::SUBLOCALITY => TextInputType::NAME, AutofillHints::TELEPHONE_NUMBER => TextInputType::NAME,
2520 AutofillHints::URL => TextInputType::URL, AutofillHints::USERNAME => TextInputType::TEXT,
2522 _ => return None,
2523 };
2524 Some(keyboard_type)
2525}
2526
2527fn default_select_all_on_focus(platform: TargetPlatform) -> bool {
2528 if K_IS_WEB {
2529 return true;
2530 }
2531 match platform {
2532 TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => true,
2533 TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => false,
2534 }
2535}
2536
2537fn is_password_input(
2538 obscure_text: bool,
2539 keyboard_type: TextInputType,
2540 autofill_hints: &[String],
2541) -> bool {
2542 obscure_text
2543 || keyboard_type == TextInputType::VISIBLE_PASSWORD
2544 || keyboard_type.password == Some(true)
2545 || autofill_hints
2546 .iter()
2547 .any(|hint| hint == AutofillHints::PASSWORD || hint == AutofillHints::NEW_PASSWORD)
2548}
2549
2550fn infer_spell_check_configuration(
2551 configuration: Option<&SpellCheckConfiguration>,
2552 obscure_text: bool,
2553 keyboard_type: TextInputType,
2554 autofill_hints: &[String],
2555) -> SpellCheckConfiguration {
2556 let disabled = is_password_input(obscure_text, keyboard_type, autofill_hints)
2557 || configuration.is_none()
2558 || configuration.is_some_and(|config| !config.spell_check_enabled());
2559 let service_configured = configuration
2560 .and_then(|config| config.spell_check_service.as_ref())
2561 .is_some();
2562 if disabled || !service_configured {
2563 return SpellCheckConfiguration::disabled();
2564 }
2565 configuration
2566 .cloned()
2567 .unwrap_or_else(SpellCheckConfiguration::disabled)
2568}
2569
2570pub struct EditableTextState {
2572 state: StateData<EditableText>,
2573 automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
2574 ticker_provider: TickerProviderStateMixinData,
2575 cursor_timer: Option<Timer>,
2576 backing_cursor_blink_opacity_controller: Option<Ref<AnimationController>>,
2577 cursor_visibility_notifier: Option<Ref<ValueNotifier<bool>>>,
2578 clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
2579 live_text_input_status: Option<Ref<LiveTextInputStatusNotifier>>,
2580 text_input_connection: Option<Ref<TextInputConnection>>,
2581 view_id: Option<ViewId>,
2584 composite_callback: Option<CompositionCallback>,
2586 last_known_remote_text_editing_value: Option<TextEditingValue>,
2587 scribble_cache_key: Option<ScribbleCacheKey>,
2588 internal_scroll_controller: Option<Ref<ScrollController>>,
2589 toolbar_layer_link: Option<Ref<LayerLink>>,
2590 start_handle_layer_link: Option<Ref<LayerLink>>,
2591 end_handle_layer_link: Option<Ref<LayerLink>>,
2592 did_auto_focus: bool,
2593 process_text_service: Rc<dyn ProcessTextService>,
2594 process_text_actions: Vec<ProcessTextAction>,
2595 spell_check_configuration: SpellCheckConfiguration,
2596 spell_check_results: Option<SpellCheckResults>,
2597 current_autofill_scope: Option<Handle<AutofillGroupState>>,
2598 app_lifecycle_listener: Option<Ref<AppLifecycleListener>>,
2599 just_resumed: bool,
2600 had_focus_on_tap_down: bool,
2601 actions: Option<HashMap<TypeId, ActionRef>>,
2602 vertical_movement_run: Option<VerticalCaretMovementRun>,
2605 run_selection: Option<TextSelection>,
2606 editable_key: GlobalKey,
2607 scrollable_key: GlobalKey,
2608 style: TextStyle,
2609 tickers_enabled: bool,
2610 batch_edit_depth: i32,
2611 current_prompt_rect_range: Option<TextRange>,
2612 obscure_show_char_ticks_pending: i32,
2613 obscure_latest_char_index: Option<i32>,
2614 last_orientation: Option<Orientation>,
2615 binding_observer: Option<WidgetsBindingObserverRef>,
2616 registered_as_observer: bool,
2617 show_caret_on_screen_scheduled: bool,
2618 last_bottom_view_inset: f64,
2619 has_focus: bool,
2620 next_focus_change_is_internal: bool,
2621 selection_overlay: Option<Ref<TextSelectionOverlay>>,
2622 render_editable: Cell<Option<RenderHandle<RenderEditable>>>,
2626}
2627
2628impl Debug for EditableTextState {
2629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2630 f.debug_struct("EditableTextState")
2631 .field("has_focus", &self.has_focus)
2632 .field("batch_edit_depth", &self.batch_edit_depth)
2633 .finish_non_exhaustive()
2634 }
2635}
2636
2637impl EditableTextState {
2638 pub fn clipboard_status(self: Handle<Self>, app: &App) -> Handle<ClipboardStatusNotifier> {
2640 app.get(self)
2641 .clipboard_status
2642 .handle()
2643 .expect("clipboardStatus is created in initState")
2644 }
2645
2646 pub fn render_editable(self: Handle<Self>, app: &App) -> RenderHandle<RenderEditable> {
2648 if let Some(render_editable) = app.get(self).render_editable.get() {
2649 return render_editable;
2650 }
2651 let object = self
2652 .context(app)
2653 .find_render_object(app)
2654 .expect("EditableText has a render object");
2655 let render_editable =
2656 find_render_editable(app, object).expect("EditableText should mount a RenderEditable");
2657 app.get(self).render_editable.set(Some(render_editable));
2658 render_editable
2659 }
2660
2661 pub fn get_glyph_heights(self: Handle<Self>, app: &mut App) -> (f64, f64) {
2663 let selection = self.value(app).selection;
2664 let render_editable = self.render_editable(app);
2665 let line_height = render_editable.preferred_line_height(app);
2666 let Some(span) = render_editable.text(app) else {
2667 return (line_height, line_height);
2668 };
2669 let prev_text = span.to_plain_text(true, true);
2670 let curr_text = self.value(app).text.clone();
2671 if prev_text != curr_text || !selection.is_valid() || selection.is_collapsed() {
2672 return (line_height, line_height);
2673 }
2674 let selected = selection.range().text_inside(&curr_text);
2675 let first_extent = selected
2676 .chars()
2677 .next()
2678 .map(|c| c.len_utf16() as i32)
2679 .unwrap_or(0);
2680 let last_extent = selected
2681 .chars()
2682 .next_back()
2683 .map(|c| c.len_utf16() as i32)
2684 .unwrap_or(0);
2685 let start_rect = render_editable.get_rect_for_composing_range(
2686 app,
2687 TextRange::new(selection.start(), selection.start() + first_extent),
2688 );
2689 let end_rect = render_editable.get_rect_for_composing_range(
2690 app,
2691 TextRange::new(selection.end() - last_extent, selection.end()),
2692 );
2693 (
2694 start_rect.map_or(line_height, |rect| rect.height()),
2695 end_rect.map_or(line_height, |rect| rect.height()),
2696 )
2697 }
2698
2699 pub fn context_menu_anchors(self: Handle<Self>, app: &mut App) -> TextSelectionToolbarAnchors {
2701 let render_editable = self.render_editable(app);
2702 if let Some(position) = render_editable.last_secondary_tap_down_position(app) {
2703 return TextSelectionToolbarAnchors::new(position);
2704 }
2705 let (start_glyph_height, end_glyph_height) = self.get_glyph_heights(app);
2706 let selection = self.value(app).selection;
2707 let points = render_editable.get_endpoints_for_selection(app, selection);
2708 TextSelectionToolbarAnchors::from_selection(
2709 app,
2710 render_editable.as_box(),
2711 start_glyph_height,
2712 end_glyph_height,
2713 &points,
2714 )
2715 }
2716
2717 pub fn context_menu_button_items(
2720 self: Handle<Self>,
2721 app: &mut App,
2722 ) -> Vec<ContextMenuButtonItem> {
2723 if let Some(items) = self.button_items_for_toolbar_options(app) {
2724 let mut items = items;
2725 items.extend(self.text_processing_action_button_items(app));
2726 return items;
2727 }
2728 let clipboard_status = self.clipboard_status(app).value(app);
2729 let platform = app.platform().target_platform();
2730 let mut items = EditableText::get_editable_button_items(
2731 Some(clipboard_status),
2732 self.copy_enabled(app)
2733 .then(|| Listener::handle_method(self, Self::copy_selection_from_toolbar)),
2734 self.cut_enabled(app)
2735 .then(|| Listener::handle_method(self, Self::cut_selection_from_toolbar)),
2736 self.paste_enabled(app)
2737 .then(|| Listener::handle_method(self, Self::paste_text_from_toolbar)),
2738 self.select_all_enabled(app)
2739 .then(|| Listener::handle_method(self, Self::select_all_from_toolbar)),
2740 self.look_up_enabled(app)
2741 .then(|| Listener::handle_method(self, Self::look_up_selection_from_toolbar)),
2742 self.search_web_enabled(app).then(|| {
2743 Listener::handle_method(self, Self::search_web_for_selection_from_toolbar)
2744 }),
2745 self.share_enabled(app)
2746 .then(|| Listener::handle_method(self, Self::share_selection_from_toolbar)),
2747 self.live_text_input_enabled(app)
2748 .then(|| Listener::handle_method(self, Self::start_live_text_input_from_toolbar)),
2749 platform,
2750 );
2751 items.extend(self.text_processing_action_button_items(app));
2752 items
2753 }
2754
2755 fn copy_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
2756 self.copy_selection(app, SelectionChangedCause::Toolbar);
2757 }
2758
2759 fn cut_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
2760 self.cut_selection(app, SelectionChangedCause::Toolbar);
2761 }
2762
2763 fn paste_text_from_toolbar(self: Handle<Self>, app: &mut App) {
2764 self.paste_text(app, SelectionChangedCause::Toolbar);
2765 }
2766
2767 fn select_all_from_toolbar(self: Handle<Self>, app: &mut App) {
2768 self.select_all(app, SelectionChangedCause::Toolbar);
2769 }
2770
2771 fn look_up_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
2772 self.look_up_selection(app, SelectionChangedCause::Toolbar);
2773 }
2774
2775 fn search_web_for_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
2776 self.search_web_for_selection(app, SelectionChangedCause::Toolbar);
2777 }
2778
2779 fn share_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
2780 self.share_selection(app, SelectionChangedCause::Toolbar);
2781 }
2782
2783 fn start_live_text_input_from_toolbar(self: Handle<Self>, app: &mut App) {
2784 self.start_live_text_input(app, SelectionChangedCause::Toolbar);
2785 }
2786
2787 pub fn look_up_selection(self: Handle<Self>, app: &mut App, _cause: SelectionChangedCause) {
2789 debug_assert!(!self.widget(app).obscure_text);
2790 if self.widget(app).obscure_text {
2791 return;
2792 }
2793 let value = self.value(app);
2794 let text = value.selection.range().text_inside(&value.text);
2795 if text.is_empty() {
2796 return;
2797 }
2798 if let Some(services) = app.platform().text_services() {
2799 services.look_up(text);
2800 }
2801 }
2802
2803 pub fn search_web_for_selection(
2805 self: Handle<Self>,
2806 app: &mut App,
2807 _cause: SelectionChangedCause,
2808 ) {
2809 debug_assert!(!self.widget(app).obscure_text);
2810 if self.widget(app).obscure_text {
2811 return;
2812 }
2813 let value = self.value(app);
2814 let text = value.selection.range().text_inside(&value.text);
2815 if !text.is_empty()
2816 && let Some(services) = app.platform().text_services()
2817 {
2818 services.search_web(text);
2819 }
2820 }
2821
2822 pub fn share_selection(self: Handle<Self>, app: &mut App, _cause: SelectionChangedCause) {
2824 debug_assert!(!self.widget(app).obscure_text);
2825 if self.widget(app).obscure_text {
2826 return;
2827 }
2828 let value = self.value(app);
2829 let text = value.selection.range().text_inside(&value.text);
2830 if !text.is_empty()
2831 && let Some(services) = app.platform().text_services()
2832 {
2833 services.share(text);
2834 }
2835 }
2836
2837 fn start_live_text_input(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
2838 if !self.live_text_input_enabled(app) {
2839 return;
2840 }
2841 if self.has_input_connection(app) {
2842 LiveText::start_live_text_input(app);
2843 }
2844 if cause == SelectionChangedCause::Toolbar {
2845 TextSelectionDelegate::hide_toolbar(self, app, true);
2846 }
2847 }
2848
2849 pub fn button_items_for_toolbar_options(
2851 self: Handle<Self>,
2852 app: &mut App,
2853 ) -> Option<Vec<ContextMenuButtonItem>> {
2854 let toolbar_options = self.widget(app).effective_toolbar_options();
2855 if toolbar_options == ToolbarOptions::EMPTY {
2856 return None;
2857 }
2858 let mut items = Vec::new();
2859 if toolbar_options.cut && self.cut_enabled(app) {
2860 items.push(
2861 ContextMenuButtonItem::new(Some(Listener::handle_method(
2862 self,
2863 Self::cut_selection_from_toolbar,
2864 )))
2865 .r#type(ContextMenuButtonType::Cut),
2866 );
2867 }
2868 if toolbar_options.copy && self.copy_enabled(app) {
2869 items.push(
2870 ContextMenuButtonItem::new(Some(Listener::handle_method(
2871 self,
2872 Self::copy_selection_from_toolbar,
2873 )))
2874 .r#type(ContextMenuButtonType::Copy),
2875 );
2876 }
2877 if toolbar_options.paste && self.paste_enabled(app) {
2878 items.push(
2879 ContextMenuButtonItem::new(Some(Listener::handle_method(
2880 self,
2881 Self::paste_text_from_toolbar,
2882 )))
2883 .r#type(ContextMenuButtonType::Paste),
2884 );
2885 }
2886 if toolbar_options.select_all && self.select_all_enabled(app) {
2887 items.push(
2888 ContextMenuButtonItem::new(Some(Listener::handle_method(
2889 self,
2890 Self::select_all_from_toolbar,
2891 )))
2892 .r#type(ContextMenuButtonType::SelectAll),
2893 );
2894 }
2895 Some(items)
2896 }
2897
2898 fn text_processing_action_button_items(
2899 self: Handle<Self>,
2900 app: &mut App,
2901 ) -> Vec<ContextMenuButtonItem> {
2902 let mut button_items = Vec::new();
2903 let value = self.value(app);
2904 let selection = value.selection;
2905 if self.widget(app).obscure_text || !selection.is_valid() || selection.is_collapsed() {
2906 return button_items;
2907 }
2908 let actions = app.get(self).process_text_actions.clone();
2909 let service = app.get(self).process_text_service.clone();
2910 let read_only = self.widget(app).read_only;
2911 let selected_text = selection.range().text_inside(&value.text).to_string();
2912 for action in actions {
2913 let selected_text = selected_text.clone();
2914 let service = Rc::clone(&service);
2915 let action_id = action.id.clone();
2916 button_items.push(
2917 ContextMenuButtonItem::new(Some(Listener::new(move |app| {
2918 if selected_text.is_empty() {
2919 return;
2920 }
2921 match service.process_text_action(app, &action_id, &selected_text, read_only) {
2922 Some(processed) if self.allow_paste(app) => {
2923 self.paste_text_content(
2924 app,
2925 SelectionChangedCause::Toolbar,
2926 &processed,
2927 );
2928 }
2929 _ => TextSelectionDelegate::hide_toolbar(self, app, true),
2930 }
2931 })))
2932 .label(action.label.clone()),
2933 );
2934 }
2935 button_items
2936 }
2937
2938 fn allow_paste(self: Handle<Self>, app: &App) -> bool {
2939 !self.widget(app).read_only && self.value(app).selection.is_valid()
2940 }
2941
2942 fn paste_text_content(
2943 self: Handle<Self>,
2944 app: &mut App,
2945 cause: SelectionChangedCause,
2946 text: &str,
2947 ) {
2948 if !self.allow_paste(app) {
2949 return;
2950 }
2951 let value = self.value(app);
2952 let last = value
2953 .selection
2954 .base_offset
2955 .max(value.selection.extent_offset);
2956 let collapsed = value
2957 .copy_with()
2958 .selection(TextSelection::collapsed(last, TextAffinity::Downstream));
2959 self.user_update_text_editing_value(app, collapsed.replaced(value.selection, text), cause);
2960 if cause == SelectionChangedCause::Toolbar {
2961 SchedulerBinding::add_post_frame_callback(
2962 app,
2963 FrameCallback::handle_method(self, Self::bring_selection_into_view_after_frame),
2964 View::maybe_id_of(app, self.context(app)),
2965 );
2966 TextSelectionDelegate::hide_toolbar(self, app, true);
2967 }
2968 }
2969
2970 pub fn spell_check_configuration(self: Handle<Self>, app: &App) -> SpellCheckConfiguration {
2972 app.get(self).spell_check_configuration.clone()
2973 }
2974
2975 pub fn spell_check_enabled(self: Handle<Self>, app: &App) -> bool {
2977 app.get(self)
2978 .spell_check_configuration
2979 .spell_check_enabled()
2980 }
2981
2982 pub fn current_autofill_scope(
2984 self: Handle<Self>,
2985 app: &App,
2986 ) -> Option<Handle<AutofillGroupState>> {
2987 app.get(self).current_autofill_scope
2988 }
2989
2990 fn spell_check_results_received(self: Handle<Self>, app: &App) -> bool {
2991 app.get(self)
2992 .spell_check_results
2993 .as_ref()
2994 .is_some_and(|results| !results.suggestion_spans.is_empty())
2995 }
2996
2997 pub fn cursor_currently_visible(self: Handle<Self>, app: &App) -> bool {
2999 app.get(self)
3000 .backing_cursor_blink_opacity_controller
3001 .handle()
3002 .is_some_and(|controller| controller.value(app) > 0.0)
3003 }
3004
3005 pub fn cursor_blink_interval() -> Duration {
3008 K_CURSOR_BLINK_HALF_PERIOD
3009 }
3010
3011 pub fn request_keyboard(self: Handle<Self>, app: &mut App) {
3013 if self.has_focus(app) {
3014 self.open_input_connection(app);
3015 } else {
3016 app.get_mut(self).next_focus_change_is_internal = true;
3017 let focus_node = self.widget(app).focus_node.handle();
3018 focus_node.request_focus(app, None);
3019 }
3020 }
3021
3022 pub fn selection_overlay(
3024 self: Handle<Self>,
3025 app: &App,
3026 ) -> Option<Handle<TextSelectionOverlay>> {
3027 app.get(self).selection_overlay.handle()
3028 }
3029
3030 fn web_context_menu_enabled() -> bool {
3031 K_IS_WEB
3032 }
3033
3034 fn create_selection_overlay(self: Handle<Self>, app: &mut App) -> Ref<TextSelectionOverlay> {
3035 let value = self.value(app);
3036 let context = self.context(app);
3037 let debug_required_for = context.widget(app).clone();
3038 let toolbar_layer_link = self.toolbar_layer_link(app);
3039 let start_handle_layer_link = self.start_handle_layer_link(app);
3040 let end_handle_layer_link = self.end_handle_layer_link(app);
3041 let render_object = self.render_editable(app);
3042 let selection_delegate = self.as_text_selection_delegate();
3043 let magnifier_configuration = self.widget(app).magnifier_configuration.clone();
3044 let clipboard_status = app
3045 .get(self)
3046 .clipboard_status
3047 .clone()
3048 .expect("clipboardStatus is created in initState");
3049 let drag_start_behavior = self.widget(app).drag_start_behavior;
3050 let selection_controls = self.widget(app).selection_controls.clone();
3051 let on_selection_handle_tapped = self.widget(app).on_selection_handle_tapped.clone();
3052 let context_menu_builder = self.widget(app).context_menu_builder.clone();
3053 let mut overlay = TextSelectionOverlay::new(
3054 app,
3055 value,
3056 context,
3057 toolbar_layer_link,
3058 start_handle_layer_link,
3059 end_handle_layer_link,
3060 render_object,
3061 selection_delegate,
3062 magnifier_configuration,
3063 )
3064 .clipboard_status(app, clipboard_status)
3065 .debug_required_for(app, debug_required_for)
3066 .drag_start_behavior(app, drag_start_behavior);
3067 if let Some(controls) = selection_controls {
3068 overlay = overlay.selection_controls(app, controls);
3069 }
3070 if let Some(on_tapped) = on_selection_handle_tapped {
3071 overlay = overlay.on_selection_handle_tapped(app, on_tapped);
3072 }
3073 if !Self::web_context_menu_enabled()
3074 && let Some(builder) = context_menu_builder
3075 {
3076 let this = self;
3077 let widget_builder: WidgetBuilder =
3078 Rc::new(move |app, context| builder(app, context, this));
3079 overlay = overlay.context_menu_builder(app, widget_builder);
3080 }
3081 overlay
3082 }
3083
3084 fn update_or_dispose_selection_overlay_if_needed(self: Handle<Self>, app: &mut App) {
3085 if let Some(overlay) = app.get(self).selection_overlay.handle() {
3086 if self.has_focus(app) {
3087 overlay.update(app, self.value(app));
3088 } else {
3089 overlay.dispose(app);
3090 app.get_mut(self).selection_overlay = None;
3091 }
3092 }
3093 }
3094
3095 fn get_offset_to_reveal_caret(self: Handle<Self>, app: &mut App, rect: Rect) -> RevealedOffset {
3096 let scroll_controller = self.scroll_controller(app);
3097 let position = scroll_controller.position(app);
3098 if !position.allow_implicit_scrolling(app) {
3099 return RevealedOffset::new(scroll_controller.offset(app), rect);
3100 }
3101
3102 let editable_size = self.render_editable(app).size(app);
3103 let (additional_offset, unit_offset, reveal_rect) = if !self.is_multiline(app) {
3104 let additional = if rect.width() >= editable_size.width() {
3105 editable_size.width() / 2.0 - rect.center().dx()
3106 } else {
3107 clamp_double(0.0, rect.right - editable_size.width(), rect.left)
3108 };
3109 (additional, Offset::new(1.0, 0.0), rect)
3110 } else {
3111 let expanded = Rect::from_center(
3112 rect.center(),
3113 rect.width(),
3114 rect.height()
3115 .max(self.render_editable(app).preferred_line_height(app)),
3116 );
3117 let additional = if expanded.height() >= editable_size.height() {
3118 editable_size.height() / 2.0 - expanded.center().dy()
3119 } else {
3120 clamp_double(0.0, expanded.bottom - editable_size.height(), expanded.top)
3121 };
3122 (additional, Offset::new(0.0, 1.0), expanded)
3123 };
3124
3125 let target_offset = clamp_double(
3126 additional_offset + scroll_controller.offset(app),
3127 position.min_scroll_extent(app),
3128 position.max_scroll_extent(app),
3129 );
3130 let offset_delta = scroll_controller.offset(app) - target_offset;
3131 RevealedOffset::new(target_offset, reveal_rect.shift(unit_offset * offset_delta))
3132 }
3133
3134 fn bring_selection_into_view_after_frame(
3135 self: Handle<Self>,
3136 app: &mut App,
3137 _time_stamp: Duration,
3138 ) {
3139 if !self.mounted(app) {
3140 return;
3141 }
3142 self.bring_into_view(app, self.value(app).selection.extent());
3143 }
3144
3145 pub fn bring_into_view(self: Handle<Self>, app: &mut App, position: TextPosition) {
3148 let local_rect = self
3149 .render_editable(app)
3150 .get_local_rect_for_caret(app, position);
3151 let target_offset = self.get_offset_to_reveal_caret(app, local_rect);
3152 self.scroll_controller(app)
3153 .jump_to(app, target_offset.offset);
3154 self.render_editable(app).show_on_screen(
3155 app,
3156 None,
3157 Some(target_offset.rect),
3158 Duration::ZERO,
3159 Curves::ease(),
3160 );
3161 }
3162
3163 pub fn show_toolbar(self: Handle<Self>, app: &mut App) -> bool {
3165 if Self::web_context_menu_enabled() {
3166 return false;
3167 }
3168 let Some(overlay) = app.get(self).selection_overlay.handle() else {
3169 return false;
3170 };
3171 if overlay.toolbar_is_visible(app) {
3172 return false;
3173 }
3174 if let Some(status) = app.get(self).live_text_input_status.handle() {
3175 status.update(app);
3176 }
3177 self.clipboard_status(app).update(app);
3178 overlay.show_toolbar(app);
3179 true
3180 }
3181
3182 pub fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
3184 if hide_handles {
3185 if let Some(overlay) = app.get(self).selection_overlay.handle() {
3186 overlay.hide(app);
3187 }
3188 } else if let Some(overlay) = app.get(self).selection_overlay.handle()
3189 && overlay.toolbar_is_visible(app)
3190 {
3191 overlay.hide_toolbar(app);
3192 }
3193 }
3194
3195 pub fn toggle_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
3197 if app.get(self).selection_overlay.is_none() {
3198 let overlay = self.create_selection_overlay(app);
3199 app.get_mut(self).selection_overlay = Some(overlay);
3200 }
3201 let overlay = app
3202 .get(self)
3203 .selection_overlay
3204 .handle()
3205 .expect("created above");
3206 if overlay.toolbar_is_visible(app) {
3207 self.hide_toolbar(app, hide_handles);
3208 } else {
3209 let _ = self.show_toolbar(app);
3210 }
3211 }
3212
3213 pub fn show_spell_check_suggestions_toolbar(self: Handle<Self>, app: &mut App) -> bool {
3216 if !self.spell_check_enabled(app)
3217 || Self::web_context_menu_enabled()
3218 || self.widget(app).read_only
3219 || app.get(self).selection_overlay.is_none()
3220 || !self.spell_check_results_received(app)
3221 || self
3222 .find_suggestion_span_at_cursor_index(app, self.value(app).selection.extent_offset)
3223 .is_none()
3224 {
3225 return false;
3226 }
3227 debug_assert!(
3228 app.get(self)
3229 .spell_check_configuration
3230 .spell_check_suggestions_toolbar_builder
3231 .is_some(),
3232 "spellCheckSuggestionsToolbarBuilder must be defined in SpellCheckConfiguration to show a toolbar with spell check suggestions"
3233 );
3234 let Some(builder) = app
3235 .get(self)
3236 .spell_check_configuration
3237 .spell_check_suggestions_toolbar_builder
3238 .clone()
3239 else {
3240 return false;
3241 };
3242 let this = self;
3243 let overlay = app
3244 .get(self)
3245 .selection_overlay
3246 .handle()
3247 .expect("checked above");
3248 overlay.show_spell_check_suggestions_toolbar(
3249 app,
3250 Rc::new(move |app, context| builder(app, context, this)),
3251 );
3252 true
3253 }
3254
3255 pub fn show_magnifier(self: Handle<Self>, app: &mut App, position_to_show: Offset) {
3258 let Some(overlay) = app.get(self).selection_overlay.handle() else {
3259 return;
3260 };
3261 if overlay.magnifier_exists(app) {
3262 overlay.update_magnifier(app, position_to_show);
3263 } else {
3264 overlay.show_magnifier(app, position_to_show);
3265 }
3266 }
3267
3268 pub fn hide_magnifier(self: Handle<Self>, app: &mut App) {
3270 if let Some(overlay) = app.get(self).selection_overlay.handle() {
3271 overlay.hide_magnifier(app);
3272 }
3273 }
3274
3275 pub fn find_suggestion_span_at_cursor_index(
3278 self: Handle<Self>,
3279 app: &App,
3280 cursor_index: i32,
3281 ) -> Option<SuggestionSpan> {
3282 if !self.spell_check_results_received(app) {
3283 return None;
3284 }
3285 let results = app.get(self).spell_check_results.as_ref()?;
3286 if results.suggestion_spans.last()?.range.end < cursor_index {
3287 return None;
3288 }
3289 let suggestion_spans = &results.suggestion_spans;
3290 let mut left_index: i32 = 0;
3291 let mut right_index = suggestion_spans.len() as i32 - 1;
3292 while left_index <= right_index {
3293 let mid_index = (left_index + right_index).div_euclid(2) as usize;
3294 let current_span_start = suggestion_spans[mid_index].range.start;
3295 let current_span_end = suggestion_spans[mid_index].range.end;
3296 if cursor_index <= current_span_end && cursor_index >= current_span_start {
3297 return Some(suggestion_spans[mid_index].clone());
3298 } else if cursor_index <= current_span_start {
3299 right_index = mid_index as i32 - 1;
3300 } else {
3301 left_index = mid_index as i32 + 1;
3302 }
3303 }
3304 None
3305 }
3306
3307 fn post_frame_rebuild_toolbar(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
3308 if self.mounted(app)
3309 && let Some(overlay) = app.get(self).selection_overlay.handle()
3310 && overlay.toolbar_is_visible(app)
3311 {
3312 overlay.show_toolbar(app);
3313 }
3314 }
3315
3316 fn post_frame_update_for_scroll(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
3317 if let Some(overlay) = app.get(self).selection_overlay.handle() {
3318 overlay.update_for_scroll(app);
3319 }
3320 }
3321
3322 pub fn begin_batch_edit(self: Handle<Self>, app: &mut App) {
3324 app.get_mut(self).batch_edit_depth += 1;
3325 }
3326
3327 pub fn end_batch_edit(self: Handle<Self>, app: &mut App) {
3330 app.get_mut(self).batch_edit_depth -= 1;
3331 debug_assert!(
3332 app.get(self).batch_edit_depth >= 0,
3333 "Unbalanced call to endBatchEdit: beginBatchEdit must be called first."
3334 );
3335 self.update_remote_editing_value_if_needed(app);
3336 }
3337
3338 pub fn build_text_span(self: Handle<Self>, app: &mut App, context: BuildContext) -> TextSpan {
3340 let widget = self.widget(app);
3341 let obscure_text = widget.obscure_text;
3342 let obscuring_character = widget.obscuring_character.clone();
3343 let read_only = widget.read_only;
3344 let controller = widget.controller.handle();
3345 let style = app.get(self).style.clone();
3346 let value = self.value(app);
3347 if obscure_text {
3348 let mut text: Vec<u16> = obscuring_character
3349 .encode_utf16()
3350 .cycle()
3351 .take(value.text.encode_utf16().count())
3352 .collect();
3353 let mobile_platforms = [
3355 TargetPlatform::Android,
3356 TargetPlatform::Fuchsia,
3357 TargetPlatform::IOS,
3358 ];
3359 let platform = app.platform();
3360 let briefly_show_password = platform.briefly_show_password()
3361 && mobile_platforms.contains(&platform.target_platform());
3362 if briefly_show_password {
3363 let o = if app.get(self).obscure_show_char_ticks_pending > 0 {
3364 app.get(self).obscure_latest_char_index
3365 } else {
3366 None
3367 };
3368 if let Some(o) = o.and_then(|o| usize::try_from(o).ok())
3369 && o < text.len()
3370 {
3371 text[o] = value.text.encode_utf16().nth(o).expect("o < text.length");
3372 }
3373 }
3374 return TextSpan::new()
3375 .style(style)
3376 .text(String::from_utf16_lossy(&text));
3377 }
3378 let with_composing = !read_only && self.has_focus(app);
3379 if self.spell_check_results_received(app) {
3380 debug_assert!(
3381 !value.composing.is_valid() || !with_composing || value.is_composing_range_valid()
3382 );
3383 let composing_region_out_of_range =
3384 !value.is_composing_range_valid() || !with_composing;
3385 let misspelled = app
3386 .get(self)
3387 .spell_check_configuration
3388 .misspelled_text_style
3389 .clone()
3390 .expect("spell check results require misspelledTextStyle");
3391 let results = app
3392 .get(self)
3393 .spell_check_results
3394 .clone()
3395 .expect("spellCheckResultsReceived");
3396 return build_text_span_with_spell_check_suggestions(
3397 app,
3398 &value,
3399 composing_region_out_of_range,
3400 Some(&style),
3401 &misspelled,
3402 &results,
3403 );
3404 }
3405 controller.build_text_span(app, context, Some(style), with_composing)
3406 }
3407
3408 fn value(self: Handle<Self>, app: &App) -> TextEditingValue {
3409 self.widget(app).controller.value(app).clone()
3410 }
3411
3412 fn set_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
3413 self.widget(app).controller.set_value(app, value);
3414 }
3415
3416 fn is_multiline(self: Handle<Self>, app: &App) -> bool {
3417 self.widget(app).max_lines != Some(1)
3418 }
3419
3420 fn text_direction(self: Handle<Self>, app: &mut App, context: BuildContext) -> TextDirection {
3421 self.widget(app)
3422 .text_direction
3423 .unwrap_or_else(|| Directionality::of(app, context))
3424 }
3425
3426 fn stylus_handwriting_enabled(self: Handle<Self>, app: &App) -> bool {
3428 if !self.widget(app).scribble_enabled {
3431 return self.widget(app).scribble_enabled;
3432 }
3433 self.widget(app).stylus_handwriting_enabled
3434 }
3435
3436 fn has_input_connection(self: Handle<Self>, app: &mut App) -> bool {
3437 app.get(self)
3438 .text_input_connection
3439 .handle()
3440 .is_some_and(|connection| connection.attached(app))
3441 }
3442
3443 fn should_create_input_connection(self: Handle<Self>, app: &App) -> bool {
3444 K_IS_WEB
3445 || app.platform().target_platform() == TargetPlatform::MacOS
3446 || !self.widget(app).read_only
3447 }
3448
3449 fn scroll_controller(self: Handle<Self>, app: &mut App) -> ScrollControllerRef {
3450 if let Some(controller) = self.widget(app).scroll_controller.clone() {
3451 return controller;
3452 }
3453 if let Some(controller) = &app.get(self).internal_scroll_controller {
3454 return controller.erase();
3455 }
3456 let controller = ScrollController::default(app);
3457 app.get_mut(self).internal_scroll_controller = Some(controller.clone());
3458 controller.into_erased()
3459 }
3460
3461 fn cursor_visibility_notifier(self: Handle<Self>, app: &App) -> Handle<ValueNotifier<bool>> {
3462 app.get(self)
3463 .cursor_visibility_notifier
3464 .handle()
3465 .expect("created in initState")
3466 }
3467
3468 fn start_handle_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
3469 app.get(self)
3470 .start_handle_layer_link
3471 .clone()
3472 .expect("created in initState")
3473 }
3474
3475 fn end_handle_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
3476 app.get(self)
3477 .end_handle_layer_link
3478 .clone()
3479 .expect("created in initState")
3480 }
3481
3482 fn toolbar_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
3483 app.get(self)
3484 .toolbar_layer_link
3485 .clone()
3486 .expect("created in initState")
3487 }
3488
3489 fn cursor_blink_opacity_controller(
3490 self: Handle<Self>,
3491 app: &mut App,
3492 ) -> Handle<AnimationController> {
3493 if let Some(controller) = app
3494 .get(self)
3495 .backing_cursor_blink_opacity_controller
3496 .handle()
3497 {
3498 return controller;
3499 }
3500 let controller = AnimationController::new(
3501 app,
3502 None,
3503 None,
3504 None,
3505 0.0,
3506 1.0,
3507 AnimationBehavior::Normal,
3508 self,
3509 );
3510 controller.add_listener(
3511 app,
3512 Listener::handle_method(self, Self::on_cursor_color_tick),
3513 );
3514 let handle = controller.handle();
3515 app.get_mut(self).backing_cursor_blink_opacity_controller = Some(controller);
3516 handle
3517 }
3518
3519 fn observer(self: Handle<Self>, app: &mut App) -> WidgetsBindingObserverRef {
3520 if let Some(observer) = app.get(self).binding_observer.clone() {
3521 return observer;
3522 }
3523 let observer: WidgetsBindingObserverRef = Rc::new(self);
3524 app.get_mut(self).binding_observer = Some(observer.clone());
3525 observer
3526 }
3527
3528 fn effective_autofill_client(self: Handle<Self>, app: &App) -> AnyAutofillClient {
3529 self.widget(app)
3530 .autofill_client
3531 .unwrap_or_else(|| self.as_autofill_client())
3532 }
3533
3534 fn cursor_color(self: Handle<Self>, app: &mut App) -> Color {
3535 let cursor_color = self.widget(app).cursor_color;
3536 let opacity = cursor_color
3537 .a
3538 .min(self.cursor_blink_opacity_controller(app).value(app));
3539 cursor_color.with_alpha((255.0 * opacity).round() as i32)
3540 }
3541
3542 fn has_focus(self: Handle<Self>, app: &mut App) -> bool {
3545 self.widget(app).focus_node.has_focus(app)
3546 }
3547
3548 fn show_blinking_cursor(self: Handle<Self>, app: &mut App) -> bool {
3549 self.has_focus(app)
3550 && self.value(app).selection.is_collapsed()
3551 && self.widget(app).effective_show_cursor()
3552 && app.get(self).tickers_enabled
3553 }
3554
3555 fn init_process_text_actions(self: Handle<Self>, app: &mut App) {
3556 let actions = app.get(self).process_text_service.query_text_actions(app);
3557 app.get_mut(self).process_text_actions.clear();
3558 app.get_mut(self).process_text_actions.extend(actions);
3559 }
3560
3561 fn on_resume(self: Handle<Self>, app: &mut App) {
3562 app.get_mut(self).just_resumed = true;
3563 let manager = FocusManager::instance(app);
3564 manager.remove_listener(
3565 app,
3566 &Listener::handle_method(self, Self::reset_just_resumed),
3567 );
3568 manager.add_listener(app, Listener::handle_method(self, Self::reset_just_resumed));
3569 }
3570
3571 fn reset_just_resumed(self: Handle<Self>, app: &mut App) {
3572 app.get_mut(self).just_resumed = false;
3573 FocusManager::instance(app).remove_listener(
3574 app,
3575 &Listener::handle_method(self, Self::reset_just_resumed),
3576 );
3577 }
3578
3579 fn on_tap_outside(
3580 self: Handle<Self>,
3581 app: &mut App,
3582 context: BuildContext,
3583 event: PointerDownEvent,
3584 ) {
3585 app.get_mut(self).had_focus_on_tap_down = true;
3586 if let Some(on_tap_outside) = self.widget(app).on_tap_outside.clone() {
3587 on_tap_outside(app, event);
3588 } else {
3589 self.default_on_tap_outside(app, context, event);
3590 }
3591 }
3592
3593 fn on_tap_up_outside(
3594 self: Handle<Self>,
3595 app: &mut App,
3596 context: BuildContext,
3597 event: PointerUpEvent,
3598 ) {
3599 if !app.get(self).had_focus_on_tap_down {
3600 return;
3601 }
3602 app.get_mut(self).had_focus_on_tap_down = false;
3603 if let Some(on_tap_up_outside) = self.widget(app).on_tap_up_outside.clone() {
3604 on_tap_up_outside(app, event);
3605 } else {
3606 self.default_on_tap_up_outside(app, context, event);
3607 }
3608 }
3609
3610 fn default_on_tap_outside(
3611 self: Handle<Self>,
3612 app: &mut App,
3613 context: BuildContext,
3614 event: PointerDownEvent,
3615 ) {
3616 let focus_node = self.widget(app).focus_node.erase();
3617 Actions::invoke(
3618 app,
3619 context,
3620 &EditableTextTapOutsideIntent::new(focus_node, event),
3621 );
3622 }
3623
3624 fn default_on_tap_up_outside(
3625 self: Handle<Self>,
3626 app: &mut App,
3627 context: BuildContext,
3628 event: PointerUpEvent,
3629 ) {
3630 let focus_node = self.widget(app).focus_node.erase();
3631 Actions::invoke(
3632 app,
3633 context,
3634 &EditableTextTapUpOutsideIntent::new(focus_node, event),
3635 );
3636 }
3637
3638 fn invoke_tap_outside(app: &mut App, intent: &EditableTextTapOutsideIntent) {
3639 match app.platform().target_platform() {
3640 TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {
3641 match intent.pointer_down_event.kind {
3642 PointerDeviceKind::Touch => {
3643 if K_IS_WEB {
3644 intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
3645 }
3646 }
3647 PointerDeviceKind::Mouse
3648 | PointerDeviceKind::Stylus
3649 | PointerDeviceKind::InvertedStylus
3650 | PointerDeviceKind::Unknown => {
3651 intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
3652 }
3653 PointerDeviceKind::Trackpad => {
3654 unimplemented!("Unexpected pointer down event for trackpad");
3655 }
3656 }
3657 }
3658 TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
3659 intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
3660 }
3661 }
3662 }
3663
3664 fn character_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
3667 let text = self.value(app).text;
3668 if self.widget(app).obscure_text {
3669 Box::new(CodePointBoundary::new(text))
3670 } else {
3671 Box::new(CharacterBoundary::new(text))
3672 }
3673 }
3674
3675 fn next_word_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
3676 if self.widget(app).obscure_text {
3677 self.document_boundary(app)
3678 } else {
3679 self.render_editable(app)
3680 .word_boundaries(app)
3681 .move_by_word_boundary()
3682 }
3683 }
3684
3685 fn linebreak(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
3686 if self.widget(app).obscure_text {
3687 self.document_boundary(app)
3688 } else {
3689 Box::new(LineBoundary::new(self.render_editable(app)))
3690 }
3691 }
3692
3693 fn paragraph_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
3694 Box::new(ParagraphBoundary::new(&self.value(app).text))
3695 }
3696
3697 fn document_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
3698 Box::new(DocumentBoundary::new(self.value(app).text))
3699 }
3700
3701 fn move_beyond_text_boundary(
3705 self: Handle<Self>,
3706 app: &mut App,
3707 extent: TextPosition,
3708 forward: bool,
3709 text_boundary: &dyn TextBoundary,
3710 ) -> TextPosition {
3711 debug_assert!(extent.offset >= 0);
3712 let text_length = utf16_len(&self.value(app).text);
3713 let new_offset = if forward {
3714 text_boundary
3715 .get_trailing_text_boundary_at(app, extent.offset)
3716 .unwrap_or(text_length)
3717 } else {
3718 text_boundary
3722 .get_leading_text_boundary_at(app, extent.offset - 1)
3723 .unwrap_or(0)
3724 };
3725 TextPosition::new(new_offset)
3726 }
3727
3728 fn move_to_text_boundary(
3736 self: Handle<Self>,
3737 app: &mut App,
3738 extent: TextPosition,
3739 forward: bool,
3740 text_boundary: &dyn TextBoundary,
3741 ) -> TextPosition {
3742 debug_assert!(extent.offset >= 0);
3743 let caret_offset = match extent.affinity {
3744 TextAffinity::Upstream => {
3745 if extent.offset < 1 && !forward {
3746 debug_assert!(extent.offset == 0);
3747 return TextPosition::new(0);
3748 }
3749 (extent.offset - 1).max(0)
3752 }
3753 TextAffinity::Downstream => extent.offset,
3754 };
3755 let text_length = utf16_len(&self.value(app).text);
3762 if forward {
3763 TextPosition::with_affinity(
3764 text_boundary
3765 .get_trailing_text_boundary_at(app, caret_offset)
3766 .unwrap_or(text_length),
3767 TextAffinity::Upstream,
3768 )
3769 } else {
3770 TextPosition::new(
3771 text_boundary
3772 .get_leading_text_boundary_at(app, caret_offset)
3773 .unwrap_or(0),
3774 )
3775 }
3776 }
3777
3778 fn transpose_characters(self: Handle<Self>, app: &mut App) {
3786 let value = self.value(app);
3787 let text = value.text.clone();
3788 let selection = value.selection;
3789 let text_length = utf16_len(&text);
3790 let boundary = CharacterBoundary::new(text.clone());
3791 let single_character = boundary
3793 .get_trailing_text_boundary_at(app, 0)
3794 .is_none_or(|end| end >= text_length);
3795 if single_character || !selection.is_collapsed() || selection.base_offset == 0 {
3796 return;
3797 }
3798
3799 let at_end = selection.base_offset == text_length;
3802 let (start, middle, end) = if at_end {
3803 let middle = boundary
3804 .get_leading_text_boundary_at(app, text_length - 1)
3805 .unwrap_or(0);
3806 let start = boundary
3807 .get_leading_text_boundary_at(app, middle - 1)
3808 .unwrap_or(0);
3809 (start, middle, text_length)
3810 } else {
3811 let start = boundary
3812 .get_leading_text_boundary_at(app, selection.base_offset - 1)
3813 .unwrap_or(0);
3814 let end = boundary
3815 .get_trailing_text_boundary_at(app, selection.base_offset)
3816 .unwrap_or(text_length);
3817 (start, selection.base_offset, end)
3818 };
3819 let transposing = TextRange::new(start, end);
3820 let first = TextRange::new(start, middle).text_inside(&text);
3821 let second = TextRange::new(middle, end).text_inside(&text);
3822
3823 let value = TextEditingValue::new()
3824 .text(format!(
3825 "{}{second}{first}{}",
3826 transposing.text_before(&text),
3827 transposing.text_after(&text)
3828 ))
3829 .selection(TextSelection::collapsed(end, TextAffinity::Downstream));
3830 self.user_update_text_editing_value(app, value, SelectionChangedCause::Keyboard);
3831 }
3832
3833 fn replace_text(self: Handle<Self>, app: &mut App, intent: &ReplaceTextIntent) {
3834 let old_value = self.value(app);
3835 let new_value = intent
3836 .current_text_editing_value
3837 .replaced(intent.replacement_range, &intent.replacement_text);
3838 self.user_update_text_editing_value(app, new_value.clone(), intent.cause);
3839
3840 if new_value == old_value {
3844 self.did_change_text_editing_value(app);
3845 }
3846 }
3847
3848 fn scroll_to_document_boundary(
3851 self: Handle<Self>,
3852 app: &mut App,
3853 intent: &ScrollToDocumentBoundaryIntent,
3854 ) {
3855 if intent.forward {
3856 let offset = utf16_len(&self.value(app).text);
3857 self.bring_into_view(app, TextPosition::new(offset));
3858 } else {
3859 self.bring_into_view(app, TextPosition::new(0));
3860 }
3861 }
3862
3863 fn scroll(self: Handle<Self>, app: &mut App, intent: &ScrollIntent) {
3865 if intent.r#type != ScrollIncrementType::Page {
3866 return;
3867 }
3868
3869 let controller = self.scroll_controller(app);
3870 let position = controller.position(app);
3871 if self.widget(app).max_lines == Some(1) {
3872 let max = position.max_scroll_extent(app);
3873 controller.jump_to(app, max);
3874 return;
3875 }
3876
3877 if position.max_scroll_extent(app) == 0.0 && position.min_scroll_extent(app) == 0.0 {
3880 return;
3881 }
3882
3883 let key = app.get(self).scrollable_key.clone();
3884 let state = key
3885 .current_state::<ScrollableState>(app)
3886 .expect("EditableText mounts a Scrollable");
3887 let increment = ScrollAction::get_directional_increment(app, state, intent);
3888 let destination = (position.pixels(app) + increment).clamp(
3889 position.min_scroll_extent(app),
3890 position.max_scroll_extent(app),
3891 );
3892 if destination == position.pixels(app) {
3893 return;
3894 }
3895 controller.jump_to(app, destination);
3896 }
3897
3898 fn update_selection(self: Handle<Self>, app: &mut App, intent: &UpdateSelectionIntent) {
3899 debug_assert!(
3900 intent.new_selection.start() <= utf16_len(&intent.current_text_editing_value.text),
3901 "invalid selection: it must not exceed the current text length"
3902 );
3903 debug_assert!(
3904 intent.new_selection.end() <= utf16_len(&intent.current_text_editing_value.text),
3905 "invalid selection: it must not exceed the current text length"
3906 );
3907
3908 self.bring_into_view(app, intent.new_selection.extent());
3909 let value = intent
3910 .current_text_editing_value
3911 .clone()
3912 .copy_with()
3913 .selection(intent.new_selection);
3914 self.user_update_text_editing_value(app, value, intent.cause);
3915 }
3916
3917 fn text_editing_value_for_text_layout_metrics(
3921 self: Handle<Self>,
3922 app: &mut App,
3923 ) -> TextEditingValue {
3924 let key = app.get(self).editable_key.clone();
3925 let widget = key.current_widget(app).expect("Editable must be mounted");
3926 widget
3927 .as_any()
3928 .downcast_ref::<Editable>()
3929 .expect("Editable must be mounted")
3930 .value
3931 .clone()
3932 }
3933
3934 fn hide_toolbar_if_visible(self: Handle<Self>, app: &mut App) -> Option<Rc<dyn Any>> {
3935 if app
3936 .get(self)
3937 .selection_overlay
3938 .handle()
3939 .is_some_and(|overlay| overlay.toolbar_is_visible(app))
3940 {
3941 self.hide_toolbar(app, false);
3942 return None;
3943 }
3944 let context = self.context(app);
3945 Actions::invoke(app, context, &DismissIntent)
3946 }
3947
3948 fn stop_current_vertical_run_if_selection_changes(self: Handle<Self>, app: &mut App) {
3953 let Some(run_selection) = app.get(self).run_selection else {
3954 debug_assert!(app.get(self).vertical_movement_run.is_none());
3955 return;
3956 };
3957 app.get_mut(self).run_selection = Some(self.value(app).selection);
3958 let current_selection = self.widget(app).controller.selection(app);
3959 let continue_current_run = current_selection.is_valid()
3960 && current_selection.is_collapsed()
3961 && current_selection.base_offset == run_selection.base_offset
3962 && current_selection.extent_offset == run_selection.extent_offset;
3963 if !continue_current_run {
3964 app.get_mut(self).vertical_movement_run = None;
3965 app.get_mut(self).run_selection = None;
3966 }
3967 }
3968
3969 fn ensure_actions(
3971 self: Handle<Self>,
3972 app: &mut App,
3973 context: BuildContext,
3974 ) -> HashMap<TypeId, ActionRef> {
3975 if let Some(actions) = app.get(self).actions.clone() {
3976 return actions;
3977 }
3978 let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
3979
3980 let do_nothing = DoNothingAction::new(app);
3981 do_nothing.set_consumes_key(app, false);
3982 actions.insert(
3983 TypeId::of::<DoNothingAndStopPropagationTextIntent>(),
3984 do_nothing.into_erased(),
3985 );
3986
3987 let replace_text = CallbackAction::<ReplaceTextIntent>::new(
3988 app,
3989 Rc::new(move |app, intent| {
3990 self.replace_text(app, intent);
3991 None
3992 }),
3993 );
3994 actions.insert(
3995 TypeId::of::<ReplaceTextIntent>(),
3996 replace_text.into_erased(),
3997 );
3998
3999 let update_selection = CallbackAction::<UpdateSelectionIntent>::new(
4000 app,
4001 Rc::new(move |app, intent| {
4002 self.update_selection(app, intent);
4003 None
4004 }),
4005 );
4006 actions.insert(
4007 TypeId::of::<UpdateSelectionIntent>(),
4008 update_selection.into_erased(),
4009 );
4010
4011 let directional_focus = DirectionalFocusAction::for_text_field(app);
4012 actions.insert(
4013 TypeId::of::<DirectionalFocusIntent>(),
4014 directional_focus.into_erased(),
4015 );
4016
4017 let dismiss = CallbackAction::<DismissIntent>::new(
4018 app,
4019 Rc::new(move |app, _intent| self.hide_toolbar_if_visible(app)),
4020 );
4021 actions.insert(TypeId::of::<DismissIntent>(), dismiss.into_erased());
4022
4023 let delete_character = DeleteTextAction::<DeleteCharacterIntent>::new(
4025 app,
4026 self,
4027 EditableTextState::character_boundary,
4028 EditableTextState::move_beyond_text_boundary,
4029 );
4030 insert_overridable(
4031 app,
4032 &mut actions,
4033 context,
4034 TypeId::of::<DeleteCharacterIntent>(),
4035 delete_character.into_erased(),
4036 );
4037 let delete_word = DeleteTextAction::<DeleteToNextWordBoundaryIntent>::new(
4038 app,
4039 self,
4040 EditableTextState::next_word_boundary,
4041 EditableTextState::move_beyond_text_boundary,
4042 );
4043 insert_overridable(
4044 app,
4045 &mut actions,
4046 context,
4047 TypeId::of::<DeleteToNextWordBoundaryIntent>(),
4048 delete_word.into_erased(),
4049 );
4050 let delete_to_line_break = DeleteTextAction::<DeleteToLineBreakIntent>::new(
4051 app,
4052 self,
4053 EditableTextState::linebreak,
4054 EditableTextState::move_to_text_boundary,
4055 );
4056 insert_overridable(
4057 app,
4058 &mut actions,
4059 context,
4060 TypeId::of::<DeleteToLineBreakIntent>(),
4061 delete_to_line_break.into_erased(),
4062 );
4063
4064 let by_character = UpdateTextSelectionAction::<ExtendSelectionByCharacterIntent>::new(
4066 app,
4067 self,
4068 EditableTextState::character_boundary,
4069 EditableTextState::move_beyond_text_boundary,
4070 false,
4071 );
4072 insert_overridable(
4073 app,
4074 &mut actions,
4075 context,
4076 TypeId::of::<ExtendSelectionByCharacterIntent>(),
4077 by_character.into_erased(),
4078 );
4079 let by_word = UpdateTextSelectionAction::<ExtendSelectionToNextWordBoundaryIntent>::new(
4080 app,
4081 self,
4082 EditableTextState::next_word_boundary,
4083 EditableTextState::move_beyond_text_boundary,
4084 true,
4085 );
4086 insert_overridable(
4087 app,
4088 &mut actions,
4089 context,
4090 TypeId::of::<ExtendSelectionToNextWordBoundaryIntent>(),
4091 by_word.into_erased(),
4092 );
4093 let by_paragraph =
4094 UpdateTextSelectionAction::<ExtendSelectionToNextParagraphBoundaryIntent>::new(
4095 app,
4096 self,
4097 EditableTextState::paragraph_boundary,
4098 EditableTextState::move_beyond_text_boundary,
4099 true,
4100 );
4101 insert_overridable(
4102 app,
4103 &mut actions,
4104 context,
4105 TypeId::of::<ExtendSelectionToNextParagraphBoundaryIntent>(),
4106 by_paragraph.into_erased(),
4107 );
4108 let to_line_break = UpdateTextSelectionAction::<ExtendSelectionToLineBreakIntent>::new(
4109 app,
4110 self,
4111 EditableTextState::linebreak,
4112 EditableTextState::move_to_text_boundary,
4113 true,
4114 );
4115 insert_overridable(
4116 app,
4117 &mut actions,
4118 context,
4119 TypeId::of::<ExtendSelectionToLineBreakIntent>(),
4120 to_line_break.into_erased(),
4121 );
4122 let by_line = UpdateTextSelectionVerticallyAction::<
4123 ExtendSelectionVerticallyToAdjacentLineIntent,
4124 >::new(app, self, false);
4125 insert_overridable(
4126 app,
4127 &mut actions,
4128 context,
4129 TypeId::of::<ExtendSelectionVerticallyToAdjacentLineIntent>(),
4130 by_line.into_erased(),
4131 );
4132 let by_page = UpdateTextSelectionVerticallyAction::<
4133 ExtendSelectionVerticallyToAdjacentPageIntent,
4134 >::new(app, self, true);
4135 insert_overridable(
4136 app,
4137 &mut actions,
4138 context,
4139 TypeId::of::<ExtendSelectionVerticallyToAdjacentPageIntent>(),
4140 by_page.into_erased(),
4141 );
4142 let by_paragraph_or_caret = UpdateTextSelectionAction::<
4143 ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent,
4144 >::new(
4145 app,
4146 self,
4147 EditableTextState::paragraph_boundary,
4148 EditableTextState::move_beyond_text_boundary,
4149 true,
4150 );
4151 insert_overridable(
4152 app,
4153 &mut actions,
4154 context,
4155 TypeId::of::<ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent>(),
4156 by_paragraph_or_caret.into_erased(),
4157 );
4158 let to_document = UpdateTextSelectionAction::<ExtendSelectionToDocumentBoundaryIntent>::new(
4159 app,
4160 self,
4161 EditableTextState::document_boundary,
4162 EditableTextState::move_beyond_text_boundary,
4163 true,
4164 );
4165 insert_overridable(
4166 app,
4167 &mut actions,
4168 context,
4169 TypeId::of::<ExtendSelectionToDocumentBoundaryIntent>(),
4170 to_document.into_erased(),
4171 );
4172 let by_word_or_caret = UpdateTextSelectionAction::<
4173 ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
4174 >::new(
4175 app,
4176 self,
4177 EditableTextState::next_word_boundary,
4178 EditableTextState::move_beyond_text_boundary,
4179 true,
4180 );
4181 insert_overridable(
4182 app,
4183 &mut actions,
4184 context,
4185 TypeId::of::<ExtendSelectionToNextWordBoundaryOrCaretLocationIntent>(),
4186 by_word_or_caret.into_erased(),
4187 );
4188
4189 let scroll_to_boundary =
4190 WebComposingDisablingCallbackAction::<ScrollToDocumentBoundaryIntent>::new(
4191 app,
4192 self,
4193 Rc::new(move |app, intent| {
4194 self.scroll_to_document_boundary(app, intent);
4195 None
4196 }),
4197 );
4198 insert_overridable(
4199 app,
4200 &mut actions,
4201 context,
4202 TypeId::of::<ScrollToDocumentBoundaryIntent>(),
4203 scroll_to_boundary.into_erased(),
4204 );
4205
4206 let scroll = CallbackAction::<ScrollIntent>::new(
4207 app,
4208 Rc::new(move |app, intent| {
4209 self.scroll(app, intent);
4210 None
4211 }),
4212 );
4213 actions.insert(TypeId::of::<ScrollIntent>(), scroll.into_erased());
4214
4215 let expand_to_line_break =
4217 UpdateTextSelectionAction::<ExpandSelectionToLineBreakIntent>::new(
4218 app,
4219 self,
4220 EditableTextState::linebreak,
4221 EditableTextState::move_to_text_boundary,
4222 true,
4223 )
4224 .expanding(app, false);
4225 insert_overridable(
4226 app,
4227 &mut actions,
4228 context,
4229 TypeId::of::<ExpandSelectionToLineBreakIntent>(),
4230 expand_to_line_break.into_erased(),
4231 );
4232 let expand_to_document =
4233 UpdateTextSelectionAction::<ExpandSelectionToDocumentBoundaryIntent>::new(
4234 app,
4235 self,
4236 EditableTextState::document_boundary,
4237 EditableTextState::move_to_text_boundary,
4238 true,
4239 )
4240 .expanding(app, true);
4241 insert_overridable(
4242 app,
4243 &mut actions,
4244 context,
4245 TypeId::of::<ExpandSelectionToDocumentBoundaryIntent>(),
4246 expand_to_document.into_erased(),
4247 );
4248
4249 let select_all = SelectAllAction::new(app, self);
4251 insert_overridable(
4252 app,
4253 &mut actions,
4254 context,
4255 TypeId::of::<SelectAllTextIntent>(),
4256 select_all.into_erased(),
4257 );
4258 let copy = CopySelectionAction::new(app, self);
4259 insert_overridable(
4260 app,
4261 &mut actions,
4262 context,
4263 TypeId::of::<CopySelectionTextIntent>(),
4264 copy.into_erased(),
4265 );
4266 let paste = PasteSelectionAction::new(app, self);
4267 insert_overridable(
4268 app,
4269 &mut actions,
4270 context,
4271 TypeId::of::<PasteTextIntent>(),
4272 paste.into_erased(),
4273 );
4274
4275 let transpose = CallbackAction::<TransposeCharactersIntent>::new(
4276 app,
4277 Rc::new(move |app, _intent| {
4278 self.transpose_characters(app);
4279 None
4280 }),
4281 );
4282 insert_overridable(
4283 app,
4284 &mut actions,
4285 context,
4286 TypeId::of::<TransposeCharactersIntent>(),
4287 transpose.into_erased(),
4288 );
4289
4290 let tap_outside = CallbackAction::<EditableTextTapOutsideIntent>::new(
4291 app,
4292 Rc::new(|app, intent| {
4293 Self::invoke_tap_outside(app, intent);
4294 None
4295 }),
4296 );
4297 insert_overridable(
4298 app,
4299 &mut actions,
4300 context,
4301 TypeId::of::<EditableTextTapOutsideIntent>(),
4302 tap_outside.into_erased(),
4303 );
4304 let tap_up_outside = CallbackAction::<EditableTextTapUpOutsideIntent>::new(
4305 app,
4306 Rc::new(|_app, _intent| None),
4307 );
4308 insert_overridable(
4309 app,
4310 &mut actions,
4311 context,
4312 TypeId::of::<EditableTextTapUpOutsideIntent>(),
4313 tap_up_outside.into_erased(),
4314 );
4315
4316 app.get_mut(self).actions = Some(actions.clone());
4317 actions
4318 }
4319
4320 fn on_changed_clipboard_status(self: Handle<Self>, app: &mut App) {
4321 self.set_state(app, |_| {});
4322 }
4323
4324 fn on_changed_live_text_input_status(self: Handle<Self>, app: &mut App) {
4325 self.set_state(app, |_| {});
4326 }
4327
4328 fn did_change_text_editing_value(self: Handle<Self>, app: &mut App) {
4329 if self.has_focus(app) && !self.value(app).selection.is_valid() {
4330 let controller = self.widget(app).controller.handle();
4331 controller.remove_listener(
4332 app,
4333 &Listener::handle_method(self, Self::did_change_text_editing_value),
4334 );
4335 if let Some(selection) = self.adjusted_selection_when_focused(app) {
4336 controller.set_selection(app, selection);
4337 }
4338 controller.add_listener(
4339 app,
4340 Listener::handle_method(self, Self::did_change_text_editing_value),
4341 );
4342 }
4343 self.update_remote_editing_value_if_needed(app);
4344 self.start_or_stop_cursor_timer_if_needed(app);
4345 self.update_or_dispose_selection_overlay_if_needed(app);
4346 self.set_state(app, |_| {});
4349 self.stop_current_vertical_run_if_selection_changes(app);
4350 }
4351
4352 fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
4353 let has_focus = self.widget(app).focus_node.has_focus(app);
4354 app.get_mut(self).has_focus = has_focus;
4355 self.open_or_close_input_connection_if_needed(app);
4356 self.start_or_stop_cursor_timer_if_needed(app);
4357 self.update_or_dispose_selection_overlay_if_needed(app);
4358 if has_focus {
4359 let observer = self.observer(app);
4361 if !app.get(self).registered_as_observer {
4362 WidgetsBinding::instance(app).add_observer(app, observer);
4363 app.get_mut(self).registered_as_observer = true;
4364 }
4365 app.get_mut(self).last_bottom_view_inset = self.bottom_view_inset(app);
4366 if !self.widget(app).read_only {
4367 self.schedule_show_caret_on_screen(app, true);
4368 }
4369 let updated = self.adjusted_selection_when_focused(app);
4370 if let Some(selection) = updated {
4371 self.handle_selection_changed(app, selection, None);
4372 }
4373 } else if app.get(self).registered_as_observer {
4374 let observer = self.observer(app);
4375 WidgetsBinding::instance(app).remove_observer(app, &observer);
4376 app.get_mut(self).registered_as_observer = false;
4377 self.set_state(app, |state| {
4378 state.current_prompt_rect_range = None;
4379 });
4380 }
4381 AutomaticKeepAliveClientMixin::update_keep_alive(self, app);
4382 }
4383
4384 fn adjusted_selection_when_focused(self: Handle<Self>, app: &mut App) -> Option<TextSelection> {
4385 let widget = self.widget(app);
4386 let should_select_all = widget.effective_select_all_on_focus(app)
4387 && widget.effective_enable_interactive_selection()
4388 && !self.is_multiline(app)
4389 && !app.get(self).next_focus_change_is_internal
4390 && !app.get(self).just_resumed;
4391 app.get_mut(self).just_resumed = false;
4392 app.get_mut(self).next_focus_change_is_internal = false;
4393 let value = self.value(app);
4394 if should_select_all {
4395 Some(TextSelection::new(0, utf16_len(&value.text)))
4396 } else if !value.selection.is_valid() {
4397 Some(TextSelection::collapsed(
4398 utf16_len(&value.text),
4399 TextAffinity::Downstream,
4400 ))
4401 } else {
4402 None
4403 }
4404 }
4405
4406 fn update_remote_editing_value_if_needed(self: Handle<Self>, app: &mut App) {
4407 if app.get(self).batch_edit_depth > 0 || !self.has_input_connection(app) {
4408 return;
4409 }
4410 let local_value = self.value(app);
4411 if app.get(self).last_known_remote_text_editing_value.as_ref() == Some(&local_value) {
4412 return;
4413 }
4414 let connection = app
4415 .get(self)
4416 .text_input_connection
4417 .handle()
4418 .expect("attached");
4419 connection.set_editing_state(app, local_value.clone());
4420 app.get_mut(self).last_known_remote_text_editing_value = Some(local_value);
4421 }
4422
4423 fn get_text_input_style(
4424 self: Handle<Self>,
4425 app: &mut App,
4426 context: BuildContext,
4427 ) -> TextInputStyle {
4428 let style = app.get(self).style.clone();
4429 let text_direction = self.text_direction(app, context);
4430 let text_align = self.widget(app).text_align;
4431 let letter_spacing =
4432 MediaQuery::maybe_letter_spacing_override_of(app, context).or(style.letter_spacing);
4433 let word_spacing =
4434 MediaQuery::maybe_word_spacing_override_of(app, context).or(style.word_spacing);
4435 let mut input_style = TextInputStyle::new(text_direction, text_align);
4436 input_style.font_family = style.font_family.clone();
4437 input_style.font_size = style.font_size;
4438 input_style.font_weight = style.font_weight;
4439 input_style.letter_spacing = letter_spacing;
4440 input_style.word_spacing = word_spacing;
4441 input_style
4442 }
4443
4444 fn open_input_connection(self: Handle<Self>, app: &mut App) {
4445 if !self.should_create_input_connection(app) {
4446 return;
4447 }
4448 if !self.has_input_connection(app) {
4449 let local_value = self.value(app);
4450 let config = self
4451 .effective_autofill_client(app)
4452 .text_input_configuration(app);
4453 let connection = TextInput::attach(app, self.as_text_input_client(), config);
4454 app.get_mut(self).text_input_connection = Some(connection.clone());
4455 self.update_size_and_transform(app);
4456 self.schedule_periodic_post_frame_callbacks(app, Duration::ZERO);
4457 if let Some(context) = self.mounted(app).then(|| self.context(app)) {
4458 let style = self.get_text_input_style(app, context);
4459 connection.update_style(app, style);
4460 }
4461 connection.set_editing_state(app, local_value.clone());
4462 connection.show(app);
4463 app.get_mut(self).last_known_remote_text_editing_value = Some(local_value);
4464 } else if let Some(connection) = app.get(self).text_input_connection.handle() {
4465 connection.show(app);
4466 }
4467 }
4468
4469 fn close_input_connection_if_needed(self: Handle<Self>, app: &mut App) {
4470 if self.has_input_connection(app) {
4471 if let Some(connection) = app.get(self).text_input_connection.handle() {
4472 connection.close(app);
4473 }
4474 app.get_mut(self).text_input_connection = None;
4475 app.get_mut(self).last_known_remote_text_editing_value = None;
4476 app.get_mut(self).scribble_cache_key = None;
4477 }
4478 }
4479
4480 fn open_or_close_input_connection_if_needed(self: Handle<Self>, app: &mut App) {
4481 let has_focus = self.has_focus(app);
4482 let focus_node = self.widget(app).focus_node.handle();
4483 if has_focus && focus_node.consume_keyboard_token(app) {
4484 self.open_input_connection(app);
4485 } else if !has_focus {
4486 self.close_input_connection_if_needed(app);
4487 let controller = self.widget(app).controller.handle();
4488 controller.clear_composing(app);
4489 }
4490 }
4491
4492 fn check_needs_adjust_affinity(
4493 self: Handle<Self>,
4494 app: &App,
4495 value: &TextEditingValue,
4496 ) -> bool {
4497 let current = self.value(app);
4498 value.text == current.text
4499 && value.selection.is_collapsed() == current.selection.is_collapsed()
4500 && value.selection.start() == current.selection.start()
4501 && value.selection.affinity != current.selection.affinity
4502 }
4503
4504 fn format_and_set_value(
4505 self: Handle<Self>,
4506 app: &mut App,
4507 mut value: TextEditingValue,
4508 cause: Option<SelectionChangedCause>,
4509 user_interaction: bool,
4510 ) {
4511 let old_value = self.value(app);
4512 let text_changed = old_value.text != value.text;
4513 let text_committed = !old_value.composing.is_collapsed() && value.composing.is_collapsed();
4514 let selection_changed = old_value.selection != value.selection;
4515 if text_changed || text_committed {
4516 let current = self.value(app);
4517 for formatter in self.widget(app).effective_input_formatters() {
4518 value = formatter.format_edit_update(¤t, &value);
4519 }
4520 }
4521 let old_selection = self.value(app).selection;
4522 self.begin_batch_edit(app);
4523 self.set_value(app, value.clone());
4524 if selection_changed
4525 || (user_interaction
4526 && matches!(
4527 cause,
4528 Some(SelectionChangedCause::LongPress | SelectionChangedCause::Keyboard)
4529 ))
4530 {
4531 self.handle_selection_changed(app, value.selection, cause);
4532 self.bring_into_view_by_selection_state(app, old_selection, value.selection, cause);
4533 }
4534 let current_text = self.value(app).text.clone();
4535 if old_value.text != current_text
4536 && let Some(on_changed) = self.widget(app).on_changed.clone()
4537 {
4538 on_changed(app, current_text);
4539 }
4540 self.end_batch_edit(app);
4541 }
4542
4543 fn bring_into_view_by_selection_state(
4544 self: Handle<Self>,
4545 app: &mut App,
4546 old_selection: TextSelection,
4547 new_selection: TextSelection,
4548 cause: Option<SelectionChangedCause>,
4549 ) {
4550 match app.platform().target_platform() {
4551 TargetPlatform::IOS | TargetPlatform::MacOS => {
4552 if matches!(
4553 cause,
4554 Some(SelectionChangedCause::LongPress | SelectionChangedCause::Drag)
4555 ) {
4556 self.bring_into_view(app, new_selection.extent());
4557 }
4558 }
4559 TargetPlatform::Linux
4560 | TargetPlatform::Windows
4561 | TargetPlatform::Fuchsia
4562 | TargetPlatform::Android => {
4563 if cause == Some(SelectionChangedCause::Drag) {
4564 if old_selection.base_offset != new_selection.base_offset {
4565 self.bring_into_view(app, new_selection.base());
4566 } else if old_selection.extent_offset != new_selection.extent_offset {
4567 self.bring_into_view(app, new_selection.extent());
4568 }
4569 }
4570 }
4571 }
4572 }
4573
4574 fn handle_selection_changed(
4575 self: Handle<Self>,
4576 app: &mut App,
4577 selection: TextSelection,
4578 cause: Option<SelectionChangedCause>,
4579 ) {
4580 let text = self.widget(app).controller.value(app).text.clone();
4581 if utf16_len(&text) < selection.end() || utf16_len(&text) < selection.start() {
4582 return;
4583 }
4584 self.widget(app).controller.set_selection(app, selection);
4585 match cause {
4586 None
4587 | Some(SelectionChangedCause::DoubleTap)
4588 | Some(SelectionChangedCause::Drag)
4589 | Some(SelectionChangedCause::ForcePress)
4590 | Some(SelectionChangedCause::LongPress)
4591 | Some(SelectionChangedCause::StylusHandwriting)
4592 | Some(SelectionChangedCause::Tap)
4593 | Some(SelectionChangedCause::Toolbar) => {
4594 self.request_keyboard(app);
4595 }
4596 Some(SelectionChangedCause::Keyboard) => {}
4597 }
4598 if self.widget(app).selection_controls.is_none()
4599 && self.widget(app).context_menu_builder.is_none()
4600 {
4601 if let Some(overlay) = app.get(self).selection_overlay.handle() {
4602 overlay.dispose(app);
4603 }
4604 app.get_mut(self).selection_overlay = None;
4605 } else {
4606 if app.get(self).selection_overlay.is_none() {
4607 let overlay = self.create_selection_overlay(app);
4608 app.get_mut(self).selection_overlay = Some(overlay);
4609 } else if let Some(overlay) = app.get(self).selection_overlay.handle() {
4610 overlay.update(app, self.value(app));
4611 }
4612 if let Some(overlay) = app.get(self).selection_overlay.handle() {
4613 overlay.set_handles_visible(app, self.widget(app).show_selection_handles);
4614 overlay.show_handles(app);
4615 }
4616 }
4617 if let Some(on_selection_changed) = self.widget(app).on_selection_changed.clone() {
4618 on_selection_changed(app, selection, cause);
4619 }
4620 if self.show_blinking_cursor(app) && app.get(self).cursor_timer.is_some() {
4621 self.stop_cursor_blink(app, false);
4622 self.start_cursor_blink(app);
4623 }
4624 }
4625
4626 fn bottom_view_inset(self: Handle<Self>, app: &mut App) -> f64 {
4629 let context = self.context(app);
4630 View::maybe_of(app, context).map_or(0.0, |view| view.metrics().view_insets.bottom)
4631 }
4632
4633 const CARET_ANIMATION_DURATION: Duration = Duration::from_millis(100);
4635
4636 fn caret_animation_curve() -> Rc<dyn Curve> {
4637 Curves::fast_out_slow_in()
4638 }
4639
4640 fn schedule_show_caret_on_screen(self: Handle<Self>, app: &mut App, with_animation: bool) {
4641 if app.get(self).show_caret_on_screen_scheduled {
4642 return;
4643 }
4644 app.get_mut(self).show_caret_on_screen_scheduled = true;
4645 let view = View::maybe_id_of(app, self.context(app));
4646 SchedulerBinding::add_post_frame_callback(
4647 app,
4648 FrameCallback::new(move |app, _| self.show_caret_on_screen(app, with_animation)),
4649 view,
4650 );
4651 }
4652
4653 fn show_caret_on_screen(self: Handle<Self>, app: &mut App, with_animation: bool) {
4655 if !app.contains(self) || !self.mounted(app) {
4658 return;
4659 }
4660 app.get_mut(self).show_caret_on_screen_scheduled = false;
4661 let render_editable = self.render_editable(app);
4662 let Some(caret_selection) = render_editable
4663 .selection(app)
4664 .filter(|selection| selection.is_valid())
4665 else {
4666 return;
4667 };
4668 if !self.scroll_controller(app).has_clients(app) {
4669 return;
4670 }
4671
4672 let line_height = render_editable.preferred_line_height(app);
4673
4674 let scroll_padding = self.widget(app).scroll_padding;
4677 let mut bottom_spacing = scroll_padding.bottom;
4678 let selection_controls = app
4679 .get(self)
4680 .selection_overlay
4681 .as_ref()
4682 .and_then(|overlay| app.get(overlay).selection_controls.clone());
4683 if let Some(selection_controls) = selection_controls {
4684 let handle_height = selection_controls.get_handle_size(line_height).height();
4685 let interactive_handle_height = handle_height.max(K_MIN_INTERACTIVE_DIMENSION);
4686 let anchor = selection_controls
4687 .get_handle_anchor(TextSelectionHandleType::Collapsed, line_height);
4688 let handle_center = handle_height / 2.0 - anchor.dy();
4689 bottom_spacing = (handle_center + interactive_handle_height / 2.0).max(bottom_spacing);
4690 }
4691
4692 let caret_padding = scroll_padding.copy_with(None, None, None, Some(bottom_spacing));
4693
4694 let caret_rect = render_editable.get_local_rect_for_caret(app, caret_selection.extent());
4695 let target_offset = self.get_offset_to_reveal_caret(app, caret_rect);
4696
4697 let selection = self.value(app).selection;
4698 let rect_to_reveal = if selection.is_collapsed() {
4699 target_offset.rect
4700 } else {
4701 let selection_boxes = render_editable.get_boxes_for_selection(app, selection);
4702 match (selection_boxes.first(), selection_boxes.last()) {
4706 (Some(first), Some(last)) => {
4707 if selection.base_offset < selection.extent_offset {
4708 last.to_rect()
4709 } else {
4710 first.to_rect()
4711 }
4712 }
4713 _ => target_offset.rect,
4714 }
4715 };
4716
4717 if with_animation {
4718 self.scroll_controller(app).animate_to(
4719 app,
4720 target_offset.offset,
4721 Self::CARET_ANIMATION_DURATION,
4722 Self::caret_animation_curve(),
4723 );
4724 render_editable.show_on_screen(
4725 app,
4726 None,
4727 Some(caret_padding.inflate_rect(rect_to_reveal)),
4728 Self::CARET_ANIMATION_DURATION,
4729 Self::caret_animation_curve(),
4730 );
4731 } else {
4732 self.scroll_controller(app)
4733 .jump_to(app, target_offset.offset);
4734 render_editable.show_on_screen(
4735 app,
4736 None,
4737 Some(caret_padding.inflate_rect(rect_to_reveal)),
4738 Duration::ZERO,
4739 Curves::ease(),
4740 );
4741 }
4742 }
4743
4744 fn finalize_editing(
4745 self: Handle<Self>,
4746 app: &mut App,
4747 action: TextInputAction,
4748 should_unfocus: bool,
4749 ) {
4750 if let Some(on_editing_complete) = self.widget(app).on_editing_complete.clone() {
4751 on_editing_complete(app);
4752 } else {
4753 self.widget(app).controller.clear_composing(app);
4754 if should_unfocus {
4755 let focus = self.widget(app).focus_node.handle();
4756 match action {
4757 TextInputAction::Next => {
4758 focus.next_focus(app);
4759 }
4760 TextInputAction::Previous => {
4761 focus.previous_focus(app);
4762 }
4763 _ => {
4764 focus.unfocus(
4765 app,
4766 crate::widgets::focus_manager::UnfocusDisposition::Scope,
4767 );
4768 }
4769 }
4770 }
4771 }
4772 let on_submitted = self.widget(app).on_submitted.clone();
4773 if let Some(on_submitted) = on_submitted {
4774 let text = self.value(app).text;
4775 on_submitted(app, text);
4776 }
4777 }
4778
4779 fn on_cursor_color_tick(self: Handle<Self>, app: &mut App) {
4780 let cursor_color = self.cursor_color(app);
4781 self.render_editable(app)
4782 .set_cursor_color(app, Some(cursor_color));
4783 let show_cursor = self.widget(app).effective_show_cursor();
4784 let visible = show_cursor
4785 && (EditableText::debug_deterministic_cursor(app)
4786 || self.cursor_blink_opacity_controller(app).value(app) > 0.0);
4787 self.cursor_visibility_notifier(app).set_value(app, visible);
4788 }
4789
4790 fn start_cursor_blink(self: Handle<Self>, app: &mut App) {
4791 if cfg!(debug_assertions) {
4792 let timer_active = app
4793 .get(self)
4794 .cursor_timer
4795 .is_some_and(|timer| timer.is_active(app));
4796 let animating = app
4797 .get(self)
4798 .backing_cursor_blink_opacity_controller
4799 .handle()
4800 .is_some_and(|controller| controller.is_animating(app));
4801 debug_assert!(!timer_active || !animating);
4802 }
4803 if !self.widget(app).effective_show_cursor() || !app.get(self).tickers_enabled {
4804 return;
4805 }
4806 if let Some(timer) = app.get(self).cursor_timer {
4807 timer.cancel(app);
4808 }
4809 self.cursor_blink_opacity_controller(app)
4810 .set_value(app, 1.0);
4811 if EditableText::debug_deterministic_cursor(app) {
4812 return;
4813 }
4814 if self.widget(app).cursor_opacity_animates {
4815 let future = self.cursor_blink_opacity_controller(app).animate_with(
4816 app,
4817 Box::new(DiscreteKeyFrameSimulation::ios_blinking_caret()),
4818 );
4819 future.when_complete(app, Listener::handle_method(self, Self::on_cursor_tick));
4820 } else {
4821 let timer = Timer::new(
4822 app,
4823 K_CURSOR_BLINK_HALF_PERIOD,
4824 Listener::handle_method(self, Self::on_cursor_tick),
4825 );
4826 app.get_mut(self).cursor_timer = Some(timer);
4827 }
4828 }
4829
4830 fn on_cursor_tick(self: Handle<Self>, app: &mut App) {
4831 if app.get(self).obscure_show_char_ticks_pending > 0 {
4832 app.get_mut(self).obscure_show_char_ticks_pending =
4833 if app.platform().briefly_show_password() {
4834 app.get(self).obscure_show_char_ticks_pending - 1
4835 } else {
4836 0
4837 };
4838 if app.get(self).obscure_show_char_ticks_pending == 0 {
4839 self.set_state(app, |_| {});
4840 }
4841 }
4842 if self.widget(app).cursor_opacity_animates {
4843 if let Some(timer) = app.get(self).cursor_timer {
4844 timer.cancel(app);
4845 }
4846 let this = self;
4849 let timer = Timer::new(
4850 app,
4851 Duration::ZERO,
4852 Listener::new(move |app| {
4853 let future = this.cursor_blink_opacity_controller(app).animate_with(
4854 app,
4855 Box::new(DiscreteKeyFrameSimulation::ios_blinking_caret()),
4856 );
4857 future.when_complete(app, Listener::handle_method(this, Self::on_cursor_tick));
4858 }),
4859 );
4860 app.get_mut(self).cursor_timer = Some(timer);
4861 } else {
4862 let timer_active = app
4865 .get(self)
4866 .cursor_timer
4867 .is_some_and(|timer| timer.is_active(app));
4868 if !timer_active && app.get(self).tickers_enabled {
4869 let timer = Timer::new(
4870 app,
4871 K_CURSOR_BLINK_HALF_PERIOD,
4872 Listener::handle_method(self, Self::on_cursor_tick),
4873 );
4874 app.get_mut(self).cursor_timer = Some(timer);
4875 }
4876 let controller = self.cursor_blink_opacity_controller(app);
4877 let next = if controller.value(app) == 0.0 {
4878 1.0
4879 } else {
4880 0.0
4881 };
4882 controller.set_value(app, next);
4883 }
4884 }
4885
4886 fn stop_cursor_blink(self: Handle<Self>, app: &mut App, reset_char_ticks: bool) {
4887 self.cursor_blink_opacity_controller(app)
4888 .set_value(app, 0.0);
4889 if let Some(timer) = app.get(self).cursor_timer {
4890 timer.cancel(app);
4891 }
4892 app.get_mut(self).cursor_timer = None;
4893 if reset_char_ticks {
4894 app.get_mut(self).obscure_show_char_ticks_pending = 0;
4895 }
4896 }
4897
4898 fn start_or_stop_cursor_timer_if_needed(self: Handle<Self>, app: &mut App) {
4899 if !self.show_blinking_cursor(app) {
4900 self.stop_cursor_blink(app, true);
4901 } else if app.get(self).cursor_timer.is_none() {
4902 self.start_cursor_blink(app);
4903 }
4904 }
4905
4906 fn effective_text_scaler(
4907 self: Handle<Self>,
4908 app: &mut App,
4909 context: BuildContext,
4910 ) -> TextScaler {
4911 match (
4912 self.widget(app).text_scaler.clone(),
4913 self.widget(app).text_scale_factor,
4914 ) {
4915 (Some(scaler), _) => scaler,
4916 (None, Some(factor)) => TextScaler::linear(factor),
4917 (None, None) => MediaQuery::text_scaler_of(app, context),
4918 }
4919 }
4920
4921 fn apply_autofocus(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
4922 if !self.mounted(app) || !self.render_editable(app).has_size(app) {
4923 return;
4924 }
4925 app.get_mut(self).next_focus_change_is_internal = true;
4926 let focus_node = self.widget(app).focus_node.handle();
4927 let context = self.context(app);
4928 FocusScope::of(app, context, true).autofocus(app, focus_node);
4929 }
4930
4931 fn post_frame_open_connection(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
4932 if self.mounted(app) {
4933 self.open_input_connection(app);
4934 }
4935 }
4936
4937 fn post_frame_update_style(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
4938 if !self.mounted(app) || !self.has_input_connection(app) {
4939 return;
4940 }
4941 let context = self.context(app);
4942 if let Some(connection) = app.get(self).text_input_connection.handle() {
4943 let style = self.get_text_input_style(app, context);
4944 connection.update_style(app, style);
4945 }
4946 }
4947
4948 fn composite_callback(self: Handle<Self>, app: &mut App, _layer: AnyLayer) {
4949 if !self.render_editable(app).as_object().attached(app) || !self.has_input_connection(app) {
4953 return;
4954 }
4955 debug_assert!(self.mounted(app));
4956 self.update_size_and_transform(app);
4957 }
4958
4959 fn update_size_and_transform(self: Handle<Self>, app: &mut App) {
4962 let render_editable = self.render_editable(app);
4963 let size = render_editable.size(app);
4964 let transform = render_editable.as_object().get_transform_to(app, None);
4965 let connection = self.text_input_connection(app);
4966 connection.set_editable_size_and_transform(app, size, transform);
4967 }
4968
4969 fn schedule_periodic_post_frame_callbacks(
4970 self: Handle<Self>,
4971 app: &mut App,
4972 _duration: Duration,
4973 ) {
4974 if !self.has_input_connection(app) {
4975 return;
4976 }
4977 self.update_selection_rects(app, false);
4978 self.update_composing_rect_if_needed(app);
4979 self.update_caret_rect_if_needed(app);
4980 SchedulerBinding::add_post_frame_callback(
4981 app,
4982 FrameCallback::handle_method(self, Self::schedule_periodic_post_frame_callbacks),
4983 View::maybe_id_of(app, self.context(app)),
4984 );
4985 }
4986
4987 fn update_selection_rects(self: Handle<Self>, app: &mut App, force: bool) {
4988 if !self.stylus_handwriting_enabled(app)
4989 || app.platform().target_platform() != TargetPlatform::IOS
4990 {
4991 return;
4992 }
4993
4994 let scroll_direction = self
4995 .scroll_controller(app)
4996 .position(app)
4997 .user_scroll_direction(app);
4998 if scroll_direction != ScrollDirection::Idle {
4999 return;
5000 }
5001
5002 let render_editable = self.render_editable(app);
5003 let Some(inline_span) = render_editable.text(app) else {
5004 return;
5005 };
5006 let context = self.context(app);
5007 let text_height_behavior = self
5008 .widget(app)
5009 .text_height_behavior
5010 .or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
5011 let new_cache_key = ScribbleCacheKey {
5012 inline_span: inline_span.clone(),
5013 text_align: self.widget(app).text_align,
5014 text_direction: self.text_direction(app, context),
5015 text_scaler: self.effective_text_scaler(app, context),
5016 text_height_behavior,
5017 locale: self.widget(app).locale.clone(),
5018 size: render_editable.size(app),
5019 };
5020
5021 let comparison = if force {
5022 RenderComparison::Layout
5023 } else {
5024 app.get(self)
5025 .scribble_cache_key
5026 .as_ref()
5027 .map_or(RenderComparison::Layout, |key| key.compare(&new_cache_key))
5028 };
5029 if comparison < RenderComparison::Layout {
5030 return;
5031 }
5032 app.get_mut(self).scribble_cache_key = Some(new_cache_key);
5033
5034 let mut rects = Vec::new();
5035 let mut grapheme_start = 0;
5036 let plain_text = inline_span.to_plain_text(false, true);
5039 let characters = CharacterBoundary::new(plain_text);
5040 while let Some(grapheme_end) = characters.get_trailing_text_boundary_at(app, grapheme_start)
5041 {
5042 let boxes = render_editable
5043 .get_boxes_for_selection(app, TextSelection::new(grapheme_start, grapheme_end));
5044
5045 if let Some(text_box) = boxes.first() {
5046 let paint_bounds = render_editable.as_object().paint_bounds(app);
5047 if paint_bounds.bottom <= text_box.top {
5050 break;
5051 }
5052 if paint_bounds.left <= text_box.right
5054 && text_box.left <= paint_bounds.right
5055 && paint_bounds.top <= text_box.bottom
5056 {
5057 rects.push(SelectionRect::new(
5059 grapheme_start,
5060 text_box.to_rect(),
5061 text_box.direction,
5062 ));
5063 }
5064 }
5065 grapheme_start = grapheme_end;
5066 }
5067 self.text_input_connection(app)
5068 .set_selection_rects(app, rects);
5069 }
5070
5071 fn update_composing_rect_if_needed(self: Handle<Self>, app: &mut App) {
5079 let composing_range = self.value(app).composing;
5080 debug_assert!(self.mounted(app));
5081 let render_editable = self.render_editable(app);
5082 let composing_rect = render_editable.get_rect_for_composing_range(app, composing_range);
5083 let composing_rect = composing_rect.unwrap_or_else(|| {
5085 let offset = if composing_range.is_valid() {
5086 composing_range.start
5087 } else {
5088 0
5089 };
5090 render_editable.get_local_rect_for_caret(app, TextPosition::new(offset))
5091 });
5092 self.text_input_connection(app)
5093 .set_composing_rect(app, composing_rect);
5094 }
5095
5096 fn update_caret_rect_if_needed(self: Handle<Self>, app: &mut App) {
5109 let render_editable = self.render_editable(app);
5110 let Some(selection) = render_editable.selection(app) else {
5111 return;
5112 };
5113 if !selection.is_valid() {
5114 return;
5115 }
5116 let current_text_position = TextPosition::new(selection.start());
5117 let caret_rect = render_editable.get_local_rect_for_caret(app, current_text_position);
5118 self.text_input_connection(app)
5119 .set_caret_rect(app, caret_rect);
5120 }
5121
5122 fn text_input_connection(self: Handle<Self>, app: &App) -> Handle<TextInputConnection> {
5124 app.get(self)
5125 .text_input_connection
5126 .handle()
5127 .expect("EditableText has an input connection")
5128 }
5129
5130 fn build_editable(
5131 self: Handle<Self>,
5132 app: &mut App,
5133 context: BuildContext,
5134 offset: ViewportOffsetRef,
5135 ) -> WidgetRef {
5136 let line_height_scale_factor =
5137 MediaQuery::maybe_line_height_scale_factor_override_of(app, context);
5138 let letter_spacing = MediaQuery::maybe_letter_spacing_override_of(app, context);
5139 let word_spacing = MediaQuery::maybe_word_spacing_override_of(app, context);
5140 let inline_span = apply_text_spacing_overrides(
5141 line_height_scale_factor,
5142 letter_spacing,
5143 word_spacing,
5144 self.build_text_span(app, context),
5145 )
5146 .into_span();
5147 let mut strut_style = self.widget(app).effective_strut_style();
5148 if let Some(height) = line_height_scale_factor {
5149 strut_style = strut_style.merge(Some(&StrutStyle::new().height(height)));
5150 }
5151 let value = self.value(app);
5152 let cursor_color = self.cursor_color(app);
5153 let background_cursor_color = self.widget(app).background_cursor_color;
5154 let show_cursor = app
5155 .get(self)
5156 .cursor_visibility_notifier
5157 .clone()
5158 .expect("created in initState");
5159 let force_line = self.widget(app).force_line;
5160 let read_only = self.widget(app).read_only;
5161 let has_focus = self.has_focus(app);
5162 let max_lines = self.widget(app).max_lines;
5163 let min_lines = self.widget(app).min_lines;
5164 let expands = self.widget(app).expands;
5165 let selection_color = self.widget(app).selection_color;
5166 let text_scaler = self.effective_text_scaler(app, context);
5167 let text_align = self.widget(app).text_align;
5168 let text_direction = self.text_direction(app, context);
5169 let locale = self.widget(app).locale.clone();
5170 let obscuring_character = self.widget(app).obscuring_character.clone();
5171 let obscure_text = self.widget(app).obscure_text;
5172 let text_height_behavior = self
5173 .widget(app)
5174 .text_height_behavior
5175 .or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
5176 let text_width_basis = self.widget(app).text_width_basis;
5177 let renderer_ignores_pointer = self.widget(app).renderer_ignores_pointer;
5178 let cursor_width = self.widget(app).cursor_width;
5179 let cursor_height = self.widget(app).cursor_height;
5180 let cursor_radius = self.widget(app).cursor_radius;
5181 let cursor_offset = self.widget(app).cursor_offset.unwrap_or(Offset::ZERO);
5182 let selection_height_style = self.widget(app).selection_height_style;
5183 let selection_width_style = self.widget(app).selection_width_style;
5184 let paint_cursor_above_text = self.widget(app).paint_cursor_above_text;
5185 let enable_interactive_selection = self.widget(app).user_selection_enabled();
5186 let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
5187 let prompt_rect_range = app.get(self).current_prompt_rect_range;
5188 let prompt_rect_color = self.widget(app).autocorrection_text_rect_color;
5189 let clip_behavior = self.widget(app).clip_behavior;
5190 let editable = Editable {
5192 key: Some(app.get(self).editable_key.clone().into()),
5193 children: WidgetSpan::extract_from_inline_span(&*inline_span, &text_scaler),
5194 inline_span,
5195 value,
5196 start_handle_layer_link: self.start_handle_layer_link(app),
5197 end_handle_layer_link: self.end_handle_layer_link(app),
5198 cursor_color: Some(cursor_color),
5199 background_cursor_color: Some(background_cursor_color),
5200 show_cursor,
5201 force_line,
5202 read_only,
5203 has_focus,
5204 max_lines,
5205 min_lines,
5206 expands,
5207 selection_color,
5208 text_scaler,
5209 text_align,
5210 text_direction,
5211 locale,
5212 obscuring_character,
5213 obscure_text,
5214 text_height_behavior,
5215 text_width_basis,
5216 strut_style,
5217 offset,
5218 renderer_ignores_pointer,
5219 cursor_width,
5220 cursor_height,
5221 cursor_radius,
5222 cursor_offset,
5223 paint_cursor_above_text,
5224 selection_height_style,
5225 selection_width_style,
5226 enable_interactive_selection,
5227 text_selection_delegate: self.as_text_selection_delegate(),
5228 device_pixel_ratio,
5229 prompt_rect_range,
5230 prompt_rect_color,
5231 clip_behavior,
5232 }
5233 .into_widget();
5234 CompositedTransformTarget::new(self.toolbar_layer_link(app))
5235 .child(editable)
5236 .into_widget()
5237 }
5238}
5239
5240impl State for EditableTextState {
5241 type Widget = EditableText;
5242
5243 state_accessors!();
5244
5245 fn init_state(self: Handle<Self>, app: &mut App) {
5246 app.get_mut(self).composite_callback = Some(Rc::new(move |app, layer| {
5247 self.composite_callback(app, layer)
5248 }));
5249 let clipboard_status = if K_IS_WEB {
5250 ClipboardStatusNotifier::web(app)
5251 } else {
5252 ClipboardStatusNotifier::new(app)
5253 };
5254 let live_text = if K_IS_WEB {
5255 None
5256 } else {
5257 Some(LiveTextInputStatusNotifier::new(app))
5258 };
5259 let cursor_visibility =
5260 app.create(ValueNotifier::new(self.widget(app).effective_show_cursor()));
5261 let toolbar_link = LayerLink::new(app);
5262 let start_link = LayerLink::new(app);
5263 let end_link = LayerLink::new(app);
5264 let live_text_handle = live_text.handle();
5265 let clipboard_status_handle = clipboard_status.handle();
5266 app.get_mut(self).clipboard_status = Some(clipboard_status);
5267 app.get_mut(self).live_text_input_status = live_text;
5268 app.get_mut(self).cursor_visibility_notifier = Some(cursor_visibility);
5269 app.get_mut(self).toolbar_layer_link = Some(toolbar_link);
5270 app.get_mut(self).start_handle_layer_link = Some(start_link);
5271 app.get_mut(self).end_handle_layer_link = Some(end_link);
5272 if let Some(live_text) = live_text_handle {
5273 live_text.add_listener(
5274 app,
5275 Listener::handle_method(self, Self::on_changed_live_text_input_status),
5276 );
5277 }
5278 clipboard_status_handle.add_listener(
5279 app,
5280 Listener::handle_method(self, Self::on_changed_clipboard_status),
5281 );
5282 let controller = self.widget(app).controller.handle();
5283 controller.add_listener(
5284 app,
5285 Listener::handle_method(self, Self::did_change_text_editing_value),
5286 );
5287 let focus_node = self.widget(app).focus_node.handle();
5288 focus_node.add_listener(
5289 app,
5290 Listener::handle_method(self, Self::handle_focus_changed),
5291 );
5292 let widget = self.widget(app);
5293 let inferred = infer_spell_check_configuration(
5294 widget.spell_check_configuration.as_ref(),
5295 widget.obscure_text,
5296 widget.effective_keyboard_type(app),
5297 &widget.autofill_hints,
5298 );
5299 app.get_mut(self).spell_check_configuration = inferred;
5300 let listener = AppLifecycleListener::new(app).on_resume(
5301 app,
5302 Rc::new({
5303 let this = self;
5304 move |app| this.on_resume(app)
5305 }),
5306 );
5307 app.get_mut(self).app_lifecycle_listener = Some(listener);
5308 self.init_process_text_actions(app);
5309 AutomaticKeepAliveClientMixin::init_state(self, app);
5310 }
5311
5312 fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
5313 let context = self.context(app);
5314 let bold = MediaQuery::bold_text_of(app, context);
5315 let style = self.widget(app).style.clone();
5316 app.get_mut(self).style = if bold {
5317 style.merge(Some(&TextStyle::new().font_weight(FontWeight::BOLD)))
5318 } else {
5319 style
5320 };
5321 let new_autofill_group = AutofillGroup::maybe_of(app, context);
5322 if app.get(self).current_autofill_scope != new_autofill_group {
5323 if let Some(scope) = app.get(self).current_autofill_scope {
5324 let autofill_id = self.as_autofill_client().autofill_id(app);
5325 scope.unregister(app, &autofill_id);
5326 }
5327 app.get_mut(self).current_autofill_scope = new_autofill_group;
5328 if let Some(scope) = new_autofill_group {
5329 let client = self.effective_autofill_client(app);
5330 scope.register(app, client);
5331 }
5332 }
5333 if !app.get(self).did_auto_focus && self.widget(app).autofocus {
5334 app.get_mut(self).did_auto_focus = true;
5335 SchedulerBinding::add_post_frame_callback(
5336 app,
5337 FrameCallback::handle_method(self, Self::apply_autofocus),
5338 View::maybe_id_of(app, self.context(app)),
5339 );
5340 }
5341 let new_ticker_enabled = TickerMode::values_of(app, context).enabled;
5342 if app.get(self).tickers_enabled != new_ticker_enabled {
5343 app.get_mut(self).tickers_enabled = new_ticker_enabled;
5344 if self.show_blinking_cursor(app) {
5345 self.start_cursor_blink(app);
5346 } else if !new_ticker_enabled && app.get(self).cursor_timer.is_some() {
5347 self.stop_cursor_blink(app, true);
5348 }
5349 }
5350 let view_id = View::maybe_of(app, context).map(|view| view.id());
5353 let view_changed = app.get(self).view_id != view_id;
5354 app.get_mut(self).view_id = view_id;
5355 if let Some(connection) = app.get(self).text_input_connection.handle()
5356 && self.has_input_connection(app)
5357 {
5358 if view_changed {
5359 let config = self
5360 .effective_autofill_client(app)
5361 .text_input_configuration(app);
5362 connection.update_config(app, config);
5363 }
5364 SchedulerBinding::add_post_frame_callback(
5365 app,
5366 FrameCallback::handle_method(self, Self::post_frame_update_style),
5367 View::maybe_id_of(app, self.context(app)),
5368 );
5369 }
5370 let platform = app.platform().target_platform();
5371 if platform != TargetPlatform::IOS && platform != TargetPlatform::Android {
5372 return;
5373 }
5374 let orientation = MediaQuery::orientation_of(app, context);
5375 if app.get(self).last_orientation.is_none() {
5376 app.get_mut(self).last_orientation = Some(orientation);
5377 return;
5378 }
5379 if app.get(self).last_orientation != Some(orientation) {
5380 app.get_mut(self).last_orientation = Some(orientation);
5381 }
5382 }
5383
5384 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &EditableText) {
5385 if self.widget(app).controller != old_widget.controller {
5386 old_widget.controller.remove_listener(
5387 app,
5388 &Listener::handle_method(self, Self::did_change_text_editing_value),
5389 );
5390 let controller = self.widget(app).controller.handle();
5391 controller.add_listener(
5392 app,
5393 Listener::handle_method(self, Self::did_change_text_editing_value),
5394 );
5395 self.update_remote_editing_value_if_needed(app);
5396 }
5397 if self.widget(app).focus_node != old_widget.focus_node {
5398 old_widget.focus_node.remove_listener(
5399 app,
5400 &Listener::handle_method(self, Self::handle_focus_changed),
5401 );
5402 let focus_node = self.widget(app).focus_node.handle();
5403 focus_node.add_listener(
5404 app,
5405 Listener::handle_method(self, Self::handle_focus_changed),
5406 );
5407 AutomaticKeepAliveClientMixin::update_keep_alive(self, app);
5408 }
5409 if self.widget(app).autofill_client != old_widget.autofill_client
5410 && let Some(scope) = app.get(self).current_autofill_scope
5411 {
5412 let old_id = old_widget
5413 .autofill_client
5414 .map(|client| client.autofill_id(app))
5415 .unwrap_or_else(|| self.as_autofill_client().autofill_id(app));
5416 scope.unregister(app, &old_id);
5417 let client = self.effective_autofill_client(app);
5418 scope.register(app, client);
5419 }
5420 if !self.should_create_input_connection(app) {
5421 self.close_input_connection_if_needed(app);
5422 } else if old_widget.read_only && self.has_focus(app) {
5423 SchedulerBinding::add_post_frame_callback(
5424 app,
5425 FrameCallback::handle_method(self, Self::post_frame_open_connection),
5426 View::maybe_id_of(app, self.context(app)),
5427 );
5428 }
5429 if self.has_input_connection(app) {
5430 let obscure_changed = old_widget.obscure_text != self.widget(app).obscure_text;
5431 if obscure_changed
5432 || old_widget.effective_keyboard_type(app)
5433 != self.widget(app).effective_keyboard_type(app)
5434 {
5435 if obscure_changed {
5436 app.get_mut(self).obscure_show_char_ticks_pending = 0;
5437 app.get_mut(self).obscure_latest_char_index = None;
5438 }
5439 if let Some(connection) = app.get(self).text_input_connection.handle() {
5440 let config = self
5441 .effective_autofill_client(app)
5442 .text_input_configuration(app);
5443 connection.update_config(app, config);
5444 }
5445 }
5446 }
5447 let widget = self.widget(app);
5448 if old_widget
5449 .spell_check_configuration
5450 .as_ref()
5451 .map(|c| c.spell_check_enabled())
5452 != widget
5453 .spell_check_configuration
5454 .as_ref()
5455 .map(|c| c.spell_check_enabled())
5456 || old_widget.obscure_text != widget.obscure_text
5457 || old_widget.effective_keyboard_type(app) != widget.effective_keyboard_type(app)
5458 || old_widget.autofill_hints != widget.autofill_hints
5459 {
5460 let inferred = infer_spell_check_configuration(
5461 widget.spell_check_configuration.as_ref(),
5462 widget.obscure_text,
5463 widget.effective_keyboard_type(app),
5464 &widget.autofill_hints,
5465 );
5466 app.get_mut(self).spell_check_configuration = inferred;
5467 if !self.spell_check_enabled(app) {
5468 app.get_mut(self).spell_check_results = None;
5469 }
5470 }
5471 if self.widget(app).style != old_widget.style {
5472 let context = self.context(app);
5473 let bold = MediaQuery::bold_text_of(app, context);
5474 let style = self.widget(app).style.clone();
5475 app.get_mut(self).style = if bold {
5476 style.merge(Some(&TextStyle::new().font_weight(FontWeight::BOLD)))
5477 } else {
5478 style
5479 };
5480 if self.has_input_connection(app) {
5481 SchedulerBinding::add_post_frame_callback(
5482 app,
5483 FrameCallback::handle_method(self, Self::post_frame_update_style),
5484 View::maybe_id_of(app, self.context(app)),
5485 );
5486 }
5487 }
5488 if self.widget(app).effective_show_cursor() != old_widget.effective_show_cursor() {
5489 self.start_or_stop_cursor_timer_if_needed(app);
5490 }
5491 let selection_overlay = app.get(self).selection_overlay.handle();
5492 if let Some(overlay) = selection_overlay
5493 && overlay.toolbar_is_visible(app)
5494 && !option_rc_eq(
5495 &self.widget(app).context_menu_builder,
5496 &old_widget.context_menu_builder,
5497 )
5498 && self.widget(app).context_menu_builder.is_none()
5499 == old_widget.context_menu_builder.is_none()
5500 {
5501 SchedulerBinding::add_post_frame_callback(
5502 app,
5503 FrameCallback::handle_method(self, Self::post_frame_rebuild_toolbar),
5504 View::maybe_id_of(app, self.context(app)),
5505 );
5506 }
5507 if app.get(self).selection_overlay.is_some()
5508 && (self.widget(app).context_menu_builder.is_none()
5509 != old_widget.context_menu_builder.is_none()
5510 || !option_rc_eq(
5511 &self.widget(app).selection_controls,
5512 &old_widget.selection_controls,
5513 )
5514 || self.widget(app).on_selection_handle_tapped
5515 != old_widget.on_selection_handle_tapped
5516 || self.widget(app).drag_start_behavior != old_widget.drag_start_behavior
5517 || !self
5518 .widget(app)
5519 .magnifier_configuration
5520 .same_configuration(&old_widget.magnifier_configuration))
5521 {
5522 let overlay = app
5523 .get(self)
5524 .selection_overlay
5525 .handle()
5526 .expect("checked above");
5527 let should_show_toolbar = overlay.toolbar_is_visible(app);
5528 let should_show_handles = overlay.handles_visible_value(app);
5529 overlay.dispose(app);
5530 let created = self.create_selection_overlay(app);
5531 app.get_mut(self).selection_overlay = Some(created);
5532 if should_show_toolbar || should_show_handles {
5533 let this = self;
5534 SchedulerBinding::add_post_frame_callback(
5535 app,
5536 FrameCallback::new(move |app, _| {
5537 if let Some(overlay) = app.get(this).selection_overlay.handle() {
5538 if should_show_toolbar {
5539 overlay.show_toolbar(app);
5540 }
5541 if should_show_handles {
5542 overlay.show_handles(app);
5543 }
5544 }
5545 }),
5546 View::maybe_id_of(app, self.context(app)),
5547 );
5548 }
5549 } else if self.widget(app).controller.selection(app) != old_widget.controller.selection(app)
5550 && let Some(overlay) = app.get(self).selection_overlay.handle()
5551 {
5552 overlay.update(app, self.value(app));
5553 }
5554 if let Some(overlay) = app.get(self).selection_overlay.handle() {
5555 overlay.set_handles_visible(app, self.widget(app).show_selection_handles);
5556 }
5557 #[allow(deprecated)]
5558 let can_paste = if self.widget(app).has_handle_controls() {
5559 self.paste_enabled(app)
5560 } else {
5561 self.widget(app)
5562 .selection_controls
5563 .as_ref()
5564 .is_some_and(|controls| controls.can_paste(app, self.as_text_selection_delegate()))
5565 };
5566 if self.widget(app).effective_enable_interactive_selection()
5567 && self.paste_enabled(app)
5568 && can_paste
5569 {
5570 self.clipboard_status(app).update(app);
5571 }
5572 }
5573
5574 fn activate(self: Handle<Self>, app: &mut App) {
5575 TickerProviderStateMixin::activate(self, app);
5576 }
5577
5578 fn deactivate(self: Handle<Self>, app: &mut App) {
5579 AutomaticKeepAliveClientMixin::deactivate(self, app);
5580 }
5581
5582 fn dispose(self: Handle<Self>, app: &mut App) {
5583 if let Some(controller) = app.get(self).internal_scroll_controller.handle() {
5584 controller.dispose(app);
5585 }
5586 if let Some(scope) = app.get(self).current_autofill_scope {
5587 let autofill_id = self.as_autofill_client().autofill_id(app);
5588 scope.unregister(app, &autofill_id);
5589 }
5590 let editing_controller = self.widget(app).controller.handle();
5591 editing_controller.remove_listener(
5592 app,
5593 &Listener::handle_method(self, Self::did_change_text_editing_value),
5594 );
5595 self.close_input_connection_if_needed(app);
5596 debug_assert!(!self.has_input_connection(app));
5597 if let Some(timer) = app.get(self).cursor_timer {
5598 timer.cancel(app);
5599 }
5600 app.get_mut(self).cursor_timer = None;
5601 if let Some(controller) = app
5602 .get(self)
5603 .backing_cursor_blink_opacity_controller
5604 .handle()
5605 {
5606 controller.dispose(app);
5607 }
5608 app.get_mut(self).backing_cursor_blink_opacity_controller = None;
5609 if let Some(overlay) = app.get(self).selection_overlay.handle() {
5610 overlay.dispose(app);
5611 }
5612 app.get_mut(self).selection_overlay = None;
5613 let focus_node = self.widget(app).focus_node.handle();
5614 focus_node.remove_listener(
5615 app,
5616 &Listener::handle_method(self, Self::handle_focus_changed),
5617 );
5618 if app.get(self).registered_as_observer {
5619 let observer = self.observer(app);
5620 WidgetsBinding::instance(app).remove_observer(app, &observer);
5621 app.get_mut(self).registered_as_observer = false;
5622 }
5623 if let Some(live_text) = app.get(self).live_text_input_status.handle() {
5624 live_text.remove_listener(
5625 app,
5626 &Listener::handle_method(self, Self::on_changed_live_text_input_status),
5627 );
5628 live_text.dispose(app);
5629 }
5630 if let Some(clipboard) = app.get(self).clipboard_status.handle() {
5631 clipboard.remove_listener(
5632 app,
5633 &Listener::handle_method(self, Self::on_changed_clipboard_status),
5634 );
5635 clipboard.dispose(app);
5636 }
5637 if let Some(notifier) = app.get(self).cursor_visibility_notifier.handle() {
5638 notifier.dispose(app);
5639 }
5640 if let Some(listener) = app.get(self).app_lifecycle_listener.handle() {
5641 listener.dispose(app);
5642 }
5643 FocusManager::instance(app).remove_listener(
5644 app,
5645 &Listener::handle_method(self, Self::reset_just_resumed),
5646 );
5647 debug_assert!(
5648 app.get(self).batch_edit_depth <= 0,
5649 "unfinished batch edits: {}",
5650 app.get(self).batch_edit_depth
5651 );
5652 TickerProviderStateMixin::dispose(self, app);
5653 }
5654
5655 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
5656 let _ = AutomaticKeepAliveClientMixin::build(self, app);
5657 let is_multiline = self.is_multiline(app);
5658 let platform = app.platform().target_platform();
5659 let physics = self.widget(app).scroll_physics.clone().or_else(|| {
5660 if !is_multiline && platform == TargetPlatform::IOS {
5661 Some(Rc::new(NeverUserScrollableScrollPhysics::new()))
5662 } else {
5663 None
5664 }
5665 });
5666 let scroll_behavior = self.widget(app).scroll_behavior.clone().unwrap_or_else(|| {
5667 ScrollBehaviorRef::new(
5668 ScrollConfiguration::of(app, context)
5669 .copy_with()
5670 .scrollbars(is_multiline)
5671 .overscroll(false),
5672 )
5673 });
5674 let restoration_id = self.widget(app).restoration_id.clone();
5675 let drag_start_behavior = self.widget(app).drag_start_behavior;
5676 let controller = self.scroll_controller(app);
5677 let focus_node = self.widget(app).focus_node.clone();
5678 let state = self;
5679 let viewport_builder: ViewportBuilder =
5680 Rc::new(move |app, context, offset| state.build_editable(app, context, offset));
5681 let mut scrollable = Scrollable::new(viewport_builder)
5682 .key(app.get(self).scrollable_key.clone().into())
5683 .axis_direction(if is_multiline {
5684 AxisDirection::Down
5685 } else {
5686 AxisDirection::Right
5687 })
5688 .controller(controller.into_erased())
5689 .drag_start_behavior(drag_start_behavior)
5690 .scroll_behavior(scroll_behavior);
5691 if let Some(physics) = physics {
5692 scrollable = scrollable.physics(physics);
5693 }
5694 if let Some(restoration_id) = restoration_id {
5695 scrollable = scrollable.restoration_id(restoration_id);
5696 }
5697 let state = self;
5698 let scrollable = NotificationListener::<dyn ScrollNotification>::new(scrollable)
5699 .on_notification(move |app: &mut App, _: &dyn ScrollNotification| {
5700 app.get_mut(state).scribble_cache_key = None;
5701 false
5702 })
5703 .into_widget();
5704 let focused = Focus::new(scrollable)
5705 .focus_node(focus_node.erase())
5706 .include_semantics(false);
5707 let editing_controller = self.widget(app).controller.clone();
5708 let undo_controller = self.widget(app).undo_controller.clone();
5709 let state = self;
5710 let mut history = UndoHistory::new(
5711 editing_controller,
5712 move |app, value| {
5713 state.user_update_text_editing_value(app, value, SelectionChangedCause::Keyboard);
5714 },
5715 focus_node,
5716 focused,
5717 )
5718 .should_change_undo_stack(move |old_value, new_value| {
5719 if !new_value.selection.is_valid() {
5720 return false;
5721 }
5722 let Some(old_value) = old_value else {
5723 return true;
5724 };
5725 match platform {
5726 TargetPlatform::IOS
5727 | TargetPlatform::MacOS
5728 | TargetPlatform::Fuchsia
5729 | TargetPlatform::Linux
5730 | TargetPlatform::Windows => {
5731 if !new_value.composing.is_collapsed() {
5732 return false;
5733 }
5734 }
5735 TargetPlatform::Android => {}
5736 }
5737 old_value.text != new_value.text || old_value.composing != new_value.composing
5738 })
5739 .undo_stack_modifier(move |value| {
5740 if platform == TargetPlatform::Android {
5741 value.copy_with().composing(TextRange::EMPTY)
5742 } else {
5743 value
5744 }
5745 });
5746 if let Some(undo_controller) = undo_controller {
5747 history = history.controller(undo_controller);
5748 }
5749 let cursor = self
5750 .widget(app)
5751 .mouse_cursor
5752 .clone()
5753 .unwrap_or_else(|| SystemMouseCursors::TEXT.into());
5754 let focused = MouseRegion::new()
5755 .cursor(cursor)
5756 .child(history.into_widget())
5757 .into_widget();
5758 let actions = self.ensure_actions(app, context);
5759 let has_focus = self.has_focus(app);
5760 let group_id = self.widget(app).group_id;
5761 let state = self;
5762 let composite_callback = app
5763 .get(self)
5764 .composite_callback
5765 .clone()
5766 .expect("set in init_state");
5767 let enabled = self.has_input_connection(app);
5768 let child = Actions::new(
5769 actions,
5770 Builder::new(move |_app, tap_context| {
5771 let mut region = TextFieldTapRegion::new(focused.clone())
5772 .group_id(TapRegionGroupId::Type(group_id));
5773 if has_focus {
5774 #[allow(clippy::redundant_locals)]
5775 let tap_context = tap_context;
5776 region = region.on_tap_outside(Rc::new(move |app, event| {
5777 state.on_tap_outside(app, tap_context, event);
5778 }));
5779 }
5780 region = region.on_tap_up_outside(Rc::new(move |app, event| {
5781 state.on_tap_up_outside(app, tap_context, event);
5782 }));
5783 if cfg!(debug_assertions) {
5784 region = region.debug_label("EditableText");
5785 }
5786 region.into_widget()
5787 }),
5788 )
5789 .into_widget();
5790 CompositionCallbackWidget::new(composite_callback, enabled, child).into_widget()
5791 }
5792}
5793
5794impl AutomaticKeepAliveClientMixin for EditableTextState {
5795 fn automatic_keep_alive_client_data(
5796 self: Handle<Self>,
5797 app: &App,
5798 ) -> &AutomaticKeepAliveClientMixinData {
5799 &app.get(self).automatic_keep_alive_client
5800 }
5801
5802 fn automatic_keep_alive_client_data_mut(
5803 self: Handle<Self>,
5804 app: &mut App,
5805 ) -> &mut AutomaticKeepAliveClientMixinData {
5806 &mut app.get_mut(self).automatic_keep_alive_client
5807 }
5808
5809 fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
5810 app.get(self).has_focus
5811 }
5812}
5813
5814impl TickerProviderStateMixin for EditableTextState {
5815 fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
5816 &app.get(self).ticker_provider
5817 }
5818
5819 fn ticker_provider_data_mut(
5820 self: Handle<Self>,
5821 app: &mut App,
5822 ) -> &mut TickerProviderStateMixinData {
5823 &mut app.get_mut(self).ticker_provider
5824 }
5825}
5826
5827impl TickerProviderObject for EditableTextState {
5828 fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
5829 TickerProviderStateMixin::create_ticker(self, app, on_tick)
5830 }
5831}
5832
5833impl WidgetsBindingObserverObject for EditableTextState {
5834 fn did_change_metrics(self: Handle<Self>, app: &mut App) {
5835 if !self.mounted(app) {
5836 return;
5837 }
5838 let context = self.context(app);
5839 let bottom_view_inset = self.bottom_view_inset(app);
5840 let last_bottom_view_inset = app.get(self).last_bottom_view_inset;
5841 if last_bottom_view_inset != bottom_view_inset {
5842 SchedulerBinding::add_post_frame_callback(
5843 app,
5844 FrameCallback::handle_method(self, Self::post_frame_update_for_scroll),
5845 View::maybe_id_of(app, context),
5846 );
5847 if last_bottom_view_inset < bottom_view_inset {
5848 self.schedule_show_caret_on_screen(app, false);
5851 }
5852 }
5853 app.get_mut(self).last_bottom_view_inset = bottom_view_inset;
5854 }
5855}
5856
5857impl TextInputClient for EditableTextState {
5858 fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue> {
5859 Some(self.value(app))
5860 }
5861
5862 fn update_editing_value(self: Handle<Self>, app: &mut App, mut value: TextEditingValue) {
5863 if !self.should_create_input_connection(app) {
5864 return;
5865 }
5866 if self.check_needs_adjust_affinity(app, &value) {
5867 value = value.copy_with().selection(
5868 value
5869 .selection
5870 .copy_with()
5871 .affinity(self.value(app).selection.affinity),
5872 );
5873 }
5874 if self.widget(app).read_only {
5875 value = self.value(app).copy_with().selection(value.selection);
5876 }
5877 app.get_mut(self).last_known_remote_text_editing_value = Some(value.clone());
5878 if value == self.value(app) {
5879 return;
5880 }
5881 let current = self.value(app);
5882 if value.text == current.text && value.composing == current.composing {
5883 self.handle_selection_changed(
5884 app,
5885 value.selection,
5886 Some(SelectionChangedCause::Keyboard),
5887 );
5888 } else {
5889 app.get_mut(self).current_prompt_rect_range = None;
5890 let current = self.value(app);
5891 let reveal_obscured_input = self.has_input_connection(app)
5892 && self.widget(app).obscure_text
5893 && app.platform().briefly_show_password()
5894 && utf16_len(&value.text) == utf16_len(¤t.text) + 1;
5895 app.get_mut(self).obscure_show_char_ticks_pending = if reveal_obscured_input {
5896 K_OBSCURE_SHOW_LATEST_CHAR_CURSOR_TICKS
5897 } else {
5898 0
5899 };
5900 app.get_mut(self).obscure_latest_char_index = if reveal_obscured_input {
5901 Some(current.selection.base_offset)
5902 } else {
5903 None
5904 };
5905 self.format_and_set_value(app, value, Some(SelectionChangedCause::Keyboard), false);
5906 }
5907 if self.show_blinking_cursor(app) && app.get(self).cursor_timer.is_some() {
5908 self.stop_cursor_blink(app, false);
5910 self.start_cursor_blink(app);
5911 }
5912
5913 self.schedule_show_caret_on_screen(app, true);
5918 }
5919
5920 fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
5921 match action {
5922 TextInputAction::Newline => {
5923 if !self.is_multiline(app) {
5924 self.finalize_editing(app, action, true);
5925 }
5926 }
5927 TextInputAction::Done
5928 | TextInputAction::Go
5929 | TextInputAction::Next
5930 | TextInputAction::Previous
5931 | TextInputAction::Search
5932 | TextInputAction::Send => {
5933 self.finalize_editing(app, action, true);
5934 }
5935 TextInputAction::ContinueAction
5936 | TextInputAction::EmergencyCall
5937 | TextInputAction::Join
5938 | TextInputAction::None
5939 | TextInputAction::Route
5940 | TextInputAction::Unspecified => {
5941 self.finalize_editing(app, action, false);
5942 }
5943 }
5944 }
5945
5946 fn perform_private_command(self: Handle<Self>, app: &mut App, action: &str) {
5947 if let Some(callback) = self.widget(app).on_app_private_command.clone() {
5948 callback(app, action);
5949 }
5950 }
5951
5952 fn connection_closed(self: Handle<Self>, app: &mut App) {
5953 if self.has_input_connection(app) {
5954 if let Some(connection) = app.get(self).text_input_connection.handle() {
5955 connection.connection_closed_received(app);
5956 }
5957 app.get_mut(self).text_input_connection = None;
5958 app.get_mut(self).last_known_remote_text_editing_value = None;
5959 let focus_node = self.widget(app).focus_node.handle();
5960 focus_node.unfocus(
5961 app,
5962 crate::widgets::focus_manager::UnfocusDisposition::Scope,
5963 );
5964 }
5965 }
5966
5967 fn show_autocorrection_prompt_rect(self: Handle<Self>, app: &mut App, start: i32, end: i32) {
5968 self.set_state(app, |state| {
5969 state.current_prompt_rect_range = Some(TextRange::new(start, end));
5970 });
5971 }
5972
5973 fn show_toolbar(self: Handle<Self>, app: &mut App) {
5974 let _ = EditableTextState::show_toolbar(self, app);
5975 }
5976
5977 fn perform_selector(self: Handle<Self>, app: &mut App, selector_name: &str) {
5978 let Some(intent) = intent_for_macos_selector(selector_name) else {
5979 return;
5980 };
5981 let Some(primary_context) = FocusManager::instance(app)
5982 .primary_focus(app)
5983 .and_then(|focus| focus.context(app))
5984 else {
5985 return;
5986 };
5987 Actions::invoke(app, primary_context, &*intent);
5988 }
5989}
5990
5991impl AutofillClient for EditableTextState {
5992 fn autofill_id(self: Handle<Self>, _app: &App) -> String {
5993 format!("{:?}", self.id())
5994 }
5995
5996 fn text_input_configuration(self: Handle<Self>, app: &App) -> TextInputConfiguration {
5997 let view_id = app.get(self).view_id;
5998 let widget = self.widget(app);
5999 let input_action = widget
6000 .text_input_action
6001 .unwrap_or(if widget.max_lines != Some(1) {
6002 TextInputAction::Newline
6003 } else {
6004 TextInputAction::Done
6005 });
6006 let autofill_configuration = AutofillConfiguration::new(
6007 format!("{:?}", self.id()),
6008 widget.autofill_hints.clone(),
6009 self.value(app),
6010 );
6011 let mut config = TextInputConfiguration::builder()
6012 .input_type(widget.effective_keyboard_type(app))
6013 .read_only(widget.read_only)
6014 .obscure_text(widget.obscure_text)
6015 .autocorrect(widget.effective_autocorrect(app))
6016 .enable_suggestions(widget.enable_suggestions)
6017 .enable_interactive_selection(widget.effective_enable_interactive_selection())
6018 .input_action(input_action)
6019 .text_capitalization(widget.text_capitalization)
6020 .keyboard_appearance(widget.keyboard_appearance)
6021 .enable_ime_personalized_learning(widget.enable_ime_personalized_learning)
6022 .smart_dashes_type(widget.effective_smart_dashes_type())
6023 .smart_quotes_type(widget.effective_smart_quotes_type())
6024 .build();
6025 config.autofill_configuration = autofill_configuration;
6026 config.allowed_mime_types = widget
6027 .content_insertion_configuration
6028 .as_ref()
6029 .map(|c| c.allowed_mime_types.clone())
6030 .unwrap_or_default();
6031 config.hint_locales = widget.hint_locales.clone().unwrap_or_default();
6032 config.enable_inline_prediction = widget.enable_inline_prediction;
6033 config.view_id = view_id.map(|view| view.0 as i32);
6034 config
6035 }
6036
6037 fn autofill(self: Handle<Self>, app: &mut App, new_editing_value: TextEditingValue) {
6038 self.update_editing_value(app, new_editing_value);
6039 }
6040}
6041
6042impl TextSelectionDelegate for EditableTextState {
6043 fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue {
6044 self.value(app)
6045 }
6046
6047 fn user_update_text_editing_value(
6048 self: Handle<Self>,
6049 app: &mut App,
6050 value: TextEditingValue,
6051 cause: SelectionChangedCause,
6052 ) {
6053 let current = self.value(app);
6061 let should_show_caret = (if self.widget(app).read_only {
6062 current.selection != value.selection
6063 } else {
6064 current != value
6065 }) && cause != SelectionChangedCause::Drag;
6066
6067 if should_show_caret {
6068 self.schedule_show_caret_on_screen(app, true);
6069 }
6070
6071 if value == self.value(app) {
6075 if !self.has_focus(app) {
6076 app.get_mut(self).next_focus_change_is_internal = true;
6077 let focus_node = self.widget(app).focus_node.handle();
6078 focus_node.request_focus(app, None);
6079 if app.get(self).selection_overlay.is_none() {
6080 let overlay = self.create_selection_overlay(app);
6081 app.get_mut(self).selection_overlay = Some(overlay);
6082 }
6083 }
6084 return;
6085 }
6086 self.format_and_set_value(app, value, Some(cause), true);
6087 }
6088
6089 fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
6090 EditableTextState::hide_toolbar(self, app, hide_handles);
6091 }
6092
6093 fn bring_into_view(self: Handle<Self>, app: &mut App, position: TextPosition) {
6094 EditableTextState::bring_into_view(self, app, position);
6095 }
6096
6097 fn cut_enabled(self: Handle<Self>, app: &App) -> bool {
6098 let widget = self.widget(app);
6099 if !widget.has_handle_controls() {
6100 return widget.effective_toolbar_options().cut
6101 && !widget.read_only
6102 && !widget.obscure_text;
6103 }
6104 !widget.read_only && !widget.obscure_text && !self.value(app).selection.is_collapsed()
6105 }
6106
6107 fn copy_enabled(self: Handle<Self>, app: &App) -> bool {
6108 let widget = self.widget(app);
6109 if !widget.has_handle_controls() {
6110 return widget.effective_toolbar_options().copy && !widget.obscure_text;
6111 }
6112 !widget.obscure_text && !self.value(app).selection.is_collapsed()
6113 }
6114
6115 fn paste_enabled(self: Handle<Self>, app: &App) -> bool {
6116 let widget = self.widget(app);
6117 if !widget.has_handle_controls() {
6118 return widget.effective_toolbar_options().paste && !widget.read_only;
6119 }
6120 !widget.read_only && self.clipboard_status(app).value(app) == ClipboardStatus::Pasteable
6121 }
6122
6123 fn select_all_enabled(self: Handle<Self>, app: &App) -> bool {
6124 let widget = self.widget(app);
6125 if !widget.has_handle_controls() {
6126 return widget.effective_toolbar_options().select_all
6127 && (!widget.read_only || !widget.obscure_text)
6128 && widget.effective_enable_interactive_selection();
6129 }
6130
6131 if !widget.effective_enable_interactive_selection()
6132 || (widget.read_only && widget.obscure_text)
6133 {
6134 return false;
6135 }
6136
6137 let value = self.value(app);
6138 match app.platform().target_platform() {
6139 TargetPlatform::MacOS => false,
6140 TargetPlatform::IOS => !value.text.is_empty() && value.selection.is_collapsed(),
6141 TargetPlatform::Android
6142 | TargetPlatform::Fuchsia
6143 | TargetPlatform::Linux
6144 | TargetPlatform::Windows => {
6145 !value.text.is_empty()
6146 && !(value.selection.start() == 0
6147 && value.selection.end() == value.text.encode_utf16().count() as i32)
6148 }
6149 }
6150 }
6151
6152 fn look_up_enabled(self: Handle<Self>, app: &App) -> bool {
6153 if app.platform().target_platform() != TargetPlatform::IOS {
6154 return false;
6155 }
6156 let value = self.value(app);
6157 !self.widget(app).obscure_text
6158 && !value.selection.is_collapsed()
6159 && !value
6160 .selection
6161 .range()
6162 .text_inside(&value.text)
6163 .trim()
6164 .is_empty()
6165 }
6166
6167 fn search_web_enabled(self: Handle<Self>, app: &App) -> bool {
6168 self.look_up_enabled(app)
6169 }
6170
6171 fn share_enabled(self: Handle<Self>, app: &App) -> bool {
6172 match app.platform().target_platform() {
6173 TargetPlatform::Android | TargetPlatform::IOS => {
6174 let value = self.value(app);
6175 !self.widget(app).obscure_text
6176 && !value.selection.is_collapsed()
6177 && !value
6178 .selection
6179 .range()
6180 .text_inside(&value.text)
6181 .trim()
6182 .is_empty()
6183 }
6184 _ => false,
6185 }
6186 }
6187
6188 fn live_text_input_enabled(self: Handle<Self>, app: &App) -> bool {
6189 let Some(status) = app.get(self).live_text_input_status.handle() else {
6190 return false;
6191 };
6192 status.value(app) == LiveTextInputStatus::Enabled
6193 && !self.widget(app).obscure_text
6194 && !self.widget(app).read_only
6195 && self.value(app).selection.is_collapsed()
6196 }
6197
6198 fn copy_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
6199 let value = self.value(app);
6200 if value.selection.is_collapsed() || self.widget(app).obscure_text {
6201 return;
6202 }
6203 let text = value.text.clone();
6204 Clipboard::set_data(
6205 app,
6206 ClipboardData::new(value.selection.range().text_inside(&text).to_string()),
6207 );
6208 if cause == SelectionChangedCause::Toolbar {
6209 self.bring_into_view(app, self.value(app).selection.extent());
6210 TextSelectionDelegate::hide_toolbar(self, app, false);
6211
6212 match app.platform().target_platform() {
6213 TargetPlatform::IOS
6214 | TargetPlatform::MacOS
6215 | TargetPlatform::Linux
6216 | TargetPlatform::Windows => {}
6217 TargetPlatform::Android | TargetPlatform::Fuchsia => {
6218 let value = self.value(app);
6219 let collapsed = value.copy_with().selection(TextSelection::collapsed(
6220 value.selection.end(),
6221 TextAffinity::Downstream,
6222 ));
6223 self.user_update_text_editing_value(
6224 app,
6225 collapsed,
6226 SelectionChangedCause::Toolbar,
6227 );
6228 }
6229 }
6230 }
6231 self.clipboard_status(app).update(app);
6232 }
6233
6234 fn cut_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
6235 if self.widget(app).read_only || self.widget(app).obscure_text {
6236 return;
6237 }
6238 let value = self.value(app);
6239 if value.selection.is_collapsed() {
6240 return;
6241 }
6242 let text = value.selection.range().text_inside(&value.text).to_string();
6243 Clipboard::set_data(app, ClipboardData::new(text));
6244 let next = value.replaced(value.selection, "");
6245 self.user_update_text_editing_value(app, next, cause);
6246 if cause == SelectionChangedCause::Toolbar {
6247 SchedulerBinding::add_post_frame_callback(
6248 app,
6249 FrameCallback::handle_method(self, Self::bring_selection_into_view_after_frame),
6250 View::maybe_id_of(app, self.context(app)),
6251 );
6252 TextSelectionDelegate::hide_toolbar(self, app, true);
6253 }
6254 self.clipboard_status(app).update(app);
6255 }
6256
6257 fn paste_text(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) -> Task<()> {
6258 if !self.allow_paste(app) {
6259 return Task::ready(());
6260 }
6261 let data = Clipboard::get_data(app, Clipboard::K_TEXT_PLAIN);
6262 app.spawn(async move |cx| {
6263 let Some(text) = data.await.and_then(|data| data.text) else {
6264 return;
6265 };
6266 cx.update(|app| {
6267 if self.mounted(app) {
6268 self.paste_text_content(app, cause, &text);
6269 }
6270 });
6271 })
6272 }
6273
6274 fn select_all(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
6275 if self.widget(app).read_only && self.widget(app).obscure_text {
6276 return;
6277 }
6278 let value = self.value(app);
6279 let next = value
6280 .copy_with()
6281 .selection(TextSelection::new(0, utf16_len(&value.text)));
6282 self.user_update_text_editing_value(app, next, cause);
6283
6284 if cause == SelectionChangedCause::Toolbar {
6285 match app.platform().target_platform() {
6286 TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {}
6287 TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
6288 TextSelectionDelegate::hide_toolbar(self, app, true);
6289 }
6290 }
6291 match app.platform().target_platform() {
6292 TargetPlatform::Android
6293 | TargetPlatform::Fuchsia
6294 | TargetPlatform::Linux
6295 | TargetPlatform::Windows => {
6296 self.bring_into_view(app, self.value(app).selection.extent());
6297 }
6298 TargetPlatform::MacOS | TargetPlatform::IOS => {}
6299 }
6300 }
6301 }
6302}
6303
6304struct Editable {
6307 key: Option<KeyRef>,
6308 children: Vec<WidgetRef>,
6311 inline_span: InlineSpanRef,
6312 value: TextEditingValue,
6313 start_handle_layer_link: Ref<LayerLink>,
6314 end_handle_layer_link: Ref<LayerLink>,
6315 cursor_color: Option<Color>,
6316 background_cursor_color: Option<Color>,
6317 show_cursor: Ref<ValueNotifier<bool>>,
6318 force_line: bool,
6319 read_only: bool,
6320 has_focus: bool,
6321 max_lines: Option<i32>,
6322 min_lines: Option<i32>,
6323 expands: bool,
6324 selection_color: Option<Color>,
6325 text_scaler: TextScaler,
6326 text_align: TextAlign,
6327 text_direction: TextDirection,
6328 locale: Option<Locale>,
6329 obscuring_character: String,
6330 obscure_text: bool,
6331 text_height_behavior: Option<TextHeightBehavior>,
6332 text_width_basis: TextWidthBasis,
6333 strut_style: StrutStyle,
6334 offset: ViewportOffsetRef,
6335 renderer_ignores_pointer: bool,
6336 cursor_width: f64,
6337 cursor_height: Option<f64>,
6338 cursor_radius: Option<Radius>,
6339 cursor_offset: Offset,
6340 paint_cursor_above_text: bool,
6341 selection_height_style: BoxHeightStyle,
6342 selection_width_style: BoxWidthStyle,
6343 enable_interactive_selection: bool,
6344 text_selection_delegate: AnyTextSelectionDelegate,
6345 device_pixel_ratio: f64,
6346 prompt_rect_range: Option<TextRange>,
6347 prompt_rect_color: Option<Color>,
6348 clip_behavior: Clip,
6349}
6350
6351impl Debug for Editable {
6352 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6353 f.debug_struct("Editable")
6354 .field("has_focus", &self.has_focus)
6355 .field("read_only", &self.read_only)
6356 .finish_non_exhaustive()
6357 }
6358}
6359
6360impl Editable {
6361 fn apply_to_render_object(&self, app: &mut App, render_object: RenderHandle<RenderEditable>) {
6362 render_object.set_text(app, Some(self.inline_span.clone()));
6363 render_object.set_cursor_color(app, self.cursor_color);
6364 render_object.set_start_handle_layer_link(app, self.start_handle_layer_link.clone());
6365 render_object.set_end_handle_layer_link(app, self.end_handle_layer_link.clone());
6366 render_object.set_background_cursor_color(app, self.background_cursor_color);
6367 render_object.set_show_cursor(app, self.show_cursor.clone());
6368 render_object.set_force_line(app, self.force_line);
6369 render_object.set_read_only(app, self.read_only);
6370 render_object.set_has_focus(app, self.has_focus);
6371 render_object.set_max_lines(app, self.max_lines);
6372 render_object.set_min_lines(app, self.min_lines);
6373 render_object.set_expands(app, self.expands);
6374 render_object.set_selection_color(app, self.selection_color);
6375 render_object.set_text_scaler(app, self.text_scaler.clone());
6376 render_object.set_text_align(app, self.text_align);
6377 render_object.set_text_direction(app, self.text_direction);
6378 render_object.set_selection(app, Some(self.value.selection));
6379 render_object.set_offset(app, self.offset.clone());
6380 render_object.get_mut(app).ignore_pointer = self.renderer_ignores_pointer;
6381 render_object.set_text_height_behavior(app, self.text_height_behavior);
6382 render_object.set_text_width_basis(app, self.text_width_basis);
6383 render_object.set_strut_style(app, Some(self.strut_style.clone()));
6384 render_object.set_obscuring_character(app, self.obscuring_character.clone());
6385 render_object.set_obscure_text(app, self.obscure_text);
6386 render_object.set_cursor_width(app, self.cursor_width);
6387 render_object.set_cursor_height(app, self.cursor_height);
6388 render_object.set_cursor_radius(app, self.cursor_radius);
6389 render_object.set_cursor_offset(app, self.cursor_offset);
6390 render_object.set_selection_height_style(app, self.selection_height_style);
6391 render_object.set_selection_width_style(app, self.selection_width_style);
6392 render_object
6393 .set_enable_interactive_selection(app, Some(self.enable_interactive_selection));
6394 render_object.set_text_selection_delegate(app, self.text_selection_delegate);
6395 render_object.set_device_pixel_ratio(app, self.device_pixel_ratio);
6396 render_object.set_paint_cursor_above_text(app, self.paint_cursor_above_text);
6397 render_object.set_prompt_rect_color(app, self.prompt_rect_color);
6398 render_object.set_clip_behavior(app, self.clip_behavior);
6399 render_object.set_prompt_rect_range(app, self.prompt_rect_range);
6400 let _ = &self.locale;
6401 }
6402}
6403
6404impl RenderObjectWidget for Editable {
6405 type RenderObject = RenderEditable;
6406
6407 fn key(&self) -> Option<&KeyRef> {
6408 self.key.as_ref()
6409 }
6410
6411 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
6412 let render_object = RenderEditable::new(
6413 app,
6414 self.text_direction,
6415 self.start_handle_layer_link.clone(),
6416 self.end_handle_layer_link.clone(),
6417 self.offset.clone(),
6418 self.text_selection_delegate,
6419 );
6420 self.apply_to_render_object(app, render_object);
6421 render_object.as_object()
6422 }
6423
6424 fn update_render_object(
6425 &self,
6426 app: &mut App,
6427 _context: BuildContext,
6428 render_object: RenderHandle<RenderEditable>,
6429 ) {
6430 self.apply_to_render_object(app, render_object);
6431 }
6432}
6433
6434impl MultiChildRenderObjectWidget for Editable {
6435 fn children(&self) -> &[WidgetRef] {
6436 &self.children
6437 }
6438}
6439
6440struct NeverUserScrollableScrollPhysics {
6442 pub parent: Option<ScrollPhysicsRef>,
6443}
6444
6445impl NeverUserScrollableScrollPhysics {
6446 fn new() -> NeverUserScrollableScrollPhysics {
6447 NeverUserScrollableScrollPhysics { parent: None }
6448 }
6449}
6450
6451impl ScrollPhysics for NeverUserScrollableScrollPhysics {
6452 fn as_any(&self) -> &dyn Any {
6453 self
6454 }
6455
6456 fn parent(&self) -> Option<&ScrollPhysicsRef> {
6457 self.parent.as_ref()
6458 }
6459
6460 fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
6461 Rc::new(NeverUserScrollableScrollPhysics {
6462 parent: ScrollPhysicsBase::build_parent(self, ancestor),
6463 })
6464 }
6465
6466 fn allow_user_scrolling(&self) -> bool {
6467 false
6468 }
6469}
6470
6471impl Debug for NeverUserScrollableScrollPhysics {
6472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6473 f.debug_struct("NeverUserScrollableScrollPhysics")
6474 .field("parent", &self.parent)
6475 .finish()
6476 }
6477}
6478
6479struct ScribbleCacheKey {
6481 text_align: TextAlign,
6482 text_direction: TextDirection,
6483 text_scaler: TextScaler,
6484 text_height_behavior: Option<TextHeightBehavior>,
6485 locale: Option<Locale>,
6486 size: Size,
6487 inline_span: InlineSpanRef,
6488}
6489
6490impl ScribbleCacheKey {
6491 fn compare(&self, other: &ScribbleCacheKey) -> RenderComparison {
6492 if std::ptr::eq(self, other) {
6493 return RenderComparison::Identical;
6494 }
6495 let needs_layout = self.text_align != other.text_align
6496 || self.text_direction != other.text_direction
6497 || self.text_scaler != other.text_scaler
6498 || self.text_height_behavior.unwrap_or_default()
6499 != other.text_height_behavior.unwrap_or_default()
6500 || self.locale != other.locale
6501 || self.size != other.size;
6502 if needs_layout {
6503 RenderComparison::Layout
6504 } else {
6505 self.inline_span.compare_to(&*other.inline_span)
6506 }
6507 }
6508}
6509
6510type ApplyTextBoundary =
6515 fn(Handle<EditableTextState>, &mut App, TextPosition, bool, &dyn TextBoundary) -> TextPosition;
6516
6517type GetTextBoundary = fn(Handle<EditableTextState>, &mut App) -> Box<dyn TextBoundary>;
6521
6522fn insert_overridable(
6524 app: &mut App,
6525 actions: &mut HashMap<TypeId, ActionRef>,
6526 context: BuildContext,
6527 intent: TypeId,
6528 action: ActionRef,
6529) {
6530 actions.insert(intent, AnyAction::overridable(app, action, context));
6531}
6532
6533fn code_unit_at(text: &str, index: i32) -> Option<i32> {
6535 if index < 0 {
6536 return None;
6537 }
6538 text.encode_utf16().nth(index as usize).map(i32::from)
6539}
6540
6541#[derive(Clone, Debug)]
6546struct CodePointBoundary {
6547 text: Vec<u16>,
6548}
6549
6550impl CodePointBoundary {
6551 fn new(text: impl AsRef<str>) -> CodePointBoundary {
6552 CodePointBoundary {
6553 text: text.as_ref().encode_utf16().collect(),
6554 }
6555 }
6556
6557 fn len(&self) -> i32 {
6558 self.text.len() as i32
6559 }
6560
6561 fn breaks_surrogate_pair(&self, position: i32) -> bool {
6563 debug_assert!(position > 0 && position < self.len() && self.len() > 1);
6564 let high = self.text[position as usize - 1];
6565 let low = self.text[position as usize];
6566 (0xD800..0xDC00).contains(&high) && (0xDC00..0xE000).contains(&low)
6567 }
6568}
6569
6570impl TextBoundary for CodePointBoundary {
6571 fn get_leading_text_boundary_at(&self, _app: &mut App, position: i32) -> Option<i32> {
6572 if self.text.is_empty() || position < 0 {
6573 return None;
6574 }
6575 if position == 0 {
6576 return Some(0);
6577 }
6578 if position >= self.len() {
6579 return Some(self.len());
6580 }
6581 if self.len() <= 1 {
6582 return Some(position);
6583 }
6584 Some(if self.breaks_surrogate_pair(position) {
6585 position - 1
6586 } else {
6587 position
6588 })
6589 }
6590
6591 fn get_trailing_text_boundary_at(&self, _app: &mut App, position: i32) -> Option<i32> {
6592 if self.text.is_empty() || position >= self.len() {
6593 return None;
6594 }
6595 if position < 0 {
6596 return Some(0);
6597 }
6598 if position == self.len() - 1 {
6599 return Some(self.len());
6600 }
6601 if self.len() <= 1 {
6602 return Some(position);
6603 }
6604 Some(if self.breaks_surrogate_pair(position + 1) {
6605 position + 2
6606 } else {
6607 position + 1
6608 })
6609 }
6610}
6611
6612struct DeleteTextAction<T: DirectionalTextEditingIntent> {
6618 action: ActionData,
6619 state: Handle<EditableTextState>,
6620 get_text_boundary: GetTextBoundary,
6621 apply_text_boundary: ApplyTextBoundary,
6622 intent: PhantomData<T>,
6623}
6624
6625impl<T: DirectionalTextEditingIntent> DeleteTextAction<T> {
6626 fn new(
6627 app: &mut App,
6628 state: Handle<EditableTextState>,
6629 get_text_boundary: GetTextBoundary,
6630 apply_text_boundary: ApplyTextBoundary,
6631 ) -> Ref<DeleteTextAction<T>> {
6632 app.create(DeleteTextAction {
6633 action: ActionData::new(),
6634 state,
6635 get_text_boundary,
6636 apply_text_boundary,
6637 intent: PhantomData,
6638 })
6639 }
6640
6641 fn hide_toolbar_if_text_changed(self: Handle<Self>, app: &mut App, intent: &ReplaceTextIntent) {
6642 let state = app.get(self).state;
6643 let visible = app
6644 .get(state)
6645 .selection_overlay
6646 .as_ref()
6647 .is_some_and(|overlay| overlay.toolbar_is_visible(app));
6648 if !visible {
6649 return;
6650 }
6651 let old_value = intent.current_text_editing_value.clone();
6652 let new_value = old_value.replaced(intent.replacement_range, &intent.replacement_text);
6653 if old_value.text != new_value.text {
6654 state.hide_toolbar(app, false);
6657 }
6658 }
6659}
6660
6661impl<T: DirectionalTextEditingIntent> Action for DeleteTextAction<T> {
6662 type Intent = T;
6663 crate::action_accessors!();
6664 crate::context_action_overrides!();
6665}
6666
6667impl<T: DirectionalTextEditingIntent> ContextAction for DeleteTextAction<T> {
6668 fn is_enabled(
6669 self: Handle<Self>,
6670 app: &mut App,
6671 _intent: &T,
6672 _context: Option<BuildContext>,
6673 ) -> bool {
6674 let state = app.get(self).state;
6675 !state.widget(app).read_only && state.value(app).selection.is_valid()
6676 }
6677
6678 fn invoke(
6679 self: Handle<Self>,
6680 app: &mut App,
6681 intent: &T,
6682 context: Option<BuildContext>,
6683 ) -> Option<Rc<dyn Any>> {
6684 let state = app.get(self).state;
6685 let selection = state.value(app).selection;
6686 if !selection.is_valid() {
6687 return None;
6688 }
6689 let context = context.expect("a delete needs a context");
6690 let text_length = utf16_len(&state.value(app).text);
6691 let atomic_boundary = state.character_boundary(app);
6693 if !selection.is_collapsed() {
6694 let range = TextRange::new(
6695 atomic_boundary
6696 .get_leading_text_boundary_at(app, selection.start())
6697 .unwrap_or(text_length),
6698 atomic_boundary
6699 .get_trailing_text_boundary_at(app, selection.end() - 1)
6700 .unwrap_or(0),
6701 );
6702 let replace_text_intent = ReplaceTextIntent::new(
6703 state.value(app),
6704 String::new(),
6705 range,
6706 SelectionChangedCause::Keyboard,
6707 );
6708 self.hide_toolbar_if_text_changed(app, &replace_text_intent);
6709 return Actions::invoke(app, context, &replace_text_intent);
6710 }
6711
6712 let boundary = (app.get(self).get_text_boundary)(state, app);
6713 let apply = app.get(self).apply_text_boundary;
6714 let target = apply(state, app, selection.base(), intent.forward(), &*boundary).offset;
6715
6716 let range_to_delete = TextSelection::new(
6717 if intent.forward() {
6718 atomic_boundary
6719 .get_leading_text_boundary_at(app, selection.base_offset)
6720 .unwrap_or(text_length)
6721 } else {
6722 atomic_boundary
6723 .get_trailing_text_boundary_at(app, selection.base_offset - 1)
6724 .unwrap_or(0)
6725 },
6726 target,
6727 );
6728 let replace_text_intent = ReplaceTextIntent::new(
6729 state.value(app),
6730 String::new(),
6731 range_to_delete.range(),
6732 SelectionChangedCause::Keyboard,
6733 );
6734 self.hide_toolbar_if_text_changed(app, &replace_text_intent);
6735 Actions::invoke(app, context, &replace_text_intent)
6736 }
6737}
6738
6739struct UpdateTextSelectionAction<T: DirectionalCaretMovementIntent> {
6743 action: ActionData,
6744 state: Handle<EditableTextState>,
6745 ignore_non_collapsed_selection: bool,
6746 is_expand: bool,
6747 extent_at_index: bool,
6748 get_text_boundary: GetTextBoundary,
6749 apply_text_boundary: ApplyTextBoundary,
6750 intent: PhantomData<T>,
6751}
6752
6753const NEWLINE_CODE_UNIT: i32 = 10;
6755
6756impl<T: DirectionalCaretMovementIntent> UpdateTextSelectionAction<T> {
6757 fn new(
6758 app: &mut App,
6759 state: Handle<EditableTextState>,
6760 get_text_boundary: GetTextBoundary,
6761 apply_text_boundary: ApplyTextBoundary,
6762 ignore_non_collapsed_selection: bool,
6763 ) -> Ref<UpdateTextSelectionAction<T>> {
6764 app.create(UpdateTextSelectionAction {
6765 action: ActionData::new(),
6766 state,
6767 ignore_non_collapsed_selection,
6768 is_expand: false,
6769 extent_at_index: false,
6770 get_text_boundary,
6771 apply_text_boundary,
6772 intent: PhantomData,
6773 })
6774 }
6775
6776 fn expanding(
6778 self: Ref<Self>,
6779 app: &mut App,
6780 extent_at_index: bool,
6781 ) -> Ref<UpdateTextSelectionAction<T>> {
6782 app.get_mut(&self).is_expand = true;
6783 app.get_mut(&self).extent_at_index = extent_at_index;
6784 self
6785 }
6786
6787 fn is_at_wordwrap_upstream(self: Handle<Self>, app: &mut App, position: TextPosition) -> bool {
6790 let state = app.get(self).state;
6791 let end = TextPosition::with_affinity(
6792 state
6793 .render_editable(app)
6794 .get_line_at_offset(app, position)
6795 .end(),
6796 TextAffinity::Upstream,
6797 );
6798 let text = state.value(app).text;
6799 end == position
6800 && end.offset != utf16_len(&text)
6801 && code_unit_at(&text, position.offset) != Some(NEWLINE_CODE_UNIT)
6802 }
6803
6804 fn is_at_wordwrap_downstream(
6807 self: Handle<Self>,
6808 app: &mut App,
6809 position: TextPosition,
6810 ) -> bool {
6811 let state = app.get(self).state;
6812 let start = TextPosition::new(
6813 state
6814 .render_editable(app)
6815 .get_line_at_offset(app, position)
6816 .start(),
6817 );
6818 let text = state.value(app).text;
6819 start == position
6820 && start.offset != 0
6821 && code_unit_at(&text, position.offset - 1) != Some(NEWLINE_CODE_UNIT)
6822 }
6823}
6824
6825impl<T: DirectionalCaretMovementIntent> Action for UpdateTextSelectionAction<T> {
6826 type Intent = T;
6827 crate::action_accessors!();
6828 crate::context_action_overrides!();
6829}
6830
6831impl<T: DirectionalCaretMovementIntent> ContextAction for UpdateTextSelectionAction<T> {
6832 fn is_enabled(
6833 self: Handle<Self>,
6834 app: &mut App,
6835 _intent: &T,
6836 _context: Option<BuildContext>,
6837 ) -> bool {
6838 let state = app.get(self).state;
6839 if K_IS_WEB
6840 && state.widget(app).user_selection_enabled()
6841 && state.value(app).composing.is_valid()
6842 {
6843 return false;
6844 }
6845 state.value(app).selection.is_valid()
6846 }
6847
6848 fn invoke(
6849 self: Handle<Self>,
6850 app: &mut App,
6851 intent: &T,
6852 context: Option<BuildContext>,
6853 ) -> Option<Rc<dyn Any>> {
6854 let state = app.get(self).state;
6855 let selection = state.value(app).selection;
6856 debug_assert!(selection.is_valid());
6857 let context = context.expect("a selection move needs a context");
6858
6859 let collapse_selection =
6860 intent.collapse_selection() || !state.widget(app).user_selection_enabled();
6861 if !selection.is_collapsed()
6862 && !app.get(self).ignore_non_collapsed_selection
6863 && collapse_selection
6864 {
6865 let offset = if intent.forward() {
6866 selection.end()
6867 } else {
6868 selection.start()
6869 };
6870 return Actions::invoke(
6871 app,
6872 context,
6873 &UpdateSelectionIntent::new(
6874 state.value(app),
6875 TextSelection::collapsed(offset, TextAffinity::Downstream),
6876 SelectionChangedCause::Keyboard,
6877 ),
6878 );
6879 }
6880
6881 let mut extent = selection.extent();
6882 if intent.continues_at_wrap() {
6885 if intent.forward() && self.is_at_wordwrap_upstream(app, extent) {
6886 extent = TextPosition::new(extent.offset);
6887 } else if !intent.forward() && self.is_at_wordwrap_downstream(app, extent) {
6888 extent = TextPosition::with_affinity(extent.offset, TextAffinity::Upstream);
6889 }
6890 }
6891
6892 let is_expand = app.get(self).is_expand;
6893 let extent_at_index = app.get(self).extent_at_index;
6894 let should_target_base = is_expand
6895 && if intent.forward() {
6896 selection.base_offset > selection.extent_offset
6897 } else {
6898 selection.base_offset < selection.extent_offset
6899 };
6900 let boundary = (app.get(self).get_text_boundary)(state, app);
6901 let apply = app.get(self).apply_text_boundary;
6902 let new_extent = apply(
6903 state,
6904 app,
6905 if should_target_base {
6906 selection.base()
6907 } else {
6908 extent
6909 },
6910 intent.forward(),
6911 &*boundary,
6912 );
6913 let new_selection =
6914 if collapse_selection || (!is_expand && new_extent.offset == selection.base_offset) {
6915 TextSelection::from_position(new_extent)
6916 } else if is_expand {
6917 selection.expand_to(new_extent, extent_at_index || selection.is_collapsed())
6918 } else {
6919 selection.extend_to(new_extent)
6920 };
6921
6922 let should_collapse_to_base = intent.collapse_at_reversal()
6923 && (selection.base_offset - selection.extent_offset)
6924 * (selection.base_offset - new_selection.extent_offset)
6925 < 0;
6926 let new_range = if should_collapse_to_base {
6927 TextSelection::from_position(selection.base())
6928 } else {
6929 new_selection
6930 };
6931 Actions::invoke(
6932 app,
6933 context,
6934 &UpdateSelectionIntent::new(
6935 state.value(app),
6936 new_range,
6937 SelectionChangedCause::Keyboard,
6938 ),
6939 )
6940 }
6941}
6942
6943struct UpdateTextSelectionVerticallyAction<T: DirectionalCaretMovementIntent> {
6947 action: ActionData,
6948 state: Handle<EditableTextState>,
6949 by_page: bool,
6950 intent: PhantomData<T>,
6951}
6952
6953impl<T: DirectionalCaretMovementIntent> UpdateTextSelectionVerticallyAction<T> {
6954 fn new(
6955 app: &mut App,
6956 state: Handle<EditableTextState>,
6957 by_page: bool,
6958 ) -> Ref<UpdateTextSelectionVerticallyAction<T>> {
6959 app.create(UpdateTextSelectionVerticallyAction {
6960 action: ActionData::new(),
6961 state,
6962 by_page,
6963 intent: PhantomData,
6964 })
6965 }
6966}
6967
6968impl<T: DirectionalCaretMovementIntent> Action for UpdateTextSelectionVerticallyAction<T> {
6969 type Intent = T;
6970 crate::action_accessors!();
6971 crate::context_action_overrides!();
6972}
6973
6974impl<T: DirectionalCaretMovementIntent> ContextAction for UpdateTextSelectionVerticallyAction<T> {
6975 fn is_enabled(
6976 self: Handle<Self>,
6977 app: &mut App,
6978 _intent: &T,
6979 _context: Option<BuildContext>,
6980 ) -> bool {
6981 let state = app.get(self).state;
6982 if K_IS_WEB
6983 && state.widget(app).user_selection_enabled()
6984 && state.value(app).composing.is_valid()
6985 {
6986 return false;
6987 }
6988 state.value(app).selection.is_valid()
6989 }
6990
6991 fn invoke(
6992 self: Handle<Self>,
6993 app: &mut App,
6994 intent: &T,
6995 context: Option<BuildContext>,
6996 ) -> Option<Rc<dyn Any>> {
6997 let state = app.get(self).state;
6998 debug_assert!(state.value(app).selection.is_valid());
6999 let context = context.expect("a vertical move needs a context");
7000
7001 let collapse_selection =
7002 intent.collapse_selection() || !state.widget(app).user_selection_enabled();
7003 let value = state.text_editing_value_for_text_layout_metrics(app);
7004 if !value.selection.is_valid() {
7005 return None;
7006 }
7007
7008 let mut taken = app.get_mut(state).vertical_movement_run.take();
7009 if taken.as_mut().is_some_and(|run| !run.is_valid(app)) {
7010 taken = None;
7011 app.get_mut(state).run_selection = None;
7012 }
7013
7014 let mut current_run = match taken {
7015 Some(run) => run,
7016 None => {
7017 let render_editable = state.render_editable(app);
7018 let extent = render_editable
7019 .selection(app)
7020 .expect("the render editable has a selection")
7021 .extent();
7022 render_editable.start_vertical_caret_movement(app, extent)
7023 }
7024 };
7025
7026 let should_move = if app.get(self).by_page {
7027 let height = state.render_editable(app).size(app).height();
7028 let offset = if intent.forward() { 1.0 } else { -1.0 } * height;
7029 current_run.move_by_offset(app, offset)
7030 } else if intent.forward() {
7031 current_run.move_next(app)
7032 } else {
7033 current_run.move_previous(app)
7034 };
7035 let new_extent = if should_move {
7036 current_run.current()
7037 } else if intent.forward() {
7038 TextPosition::new(utf16_len(&value.text))
7039 } else {
7040 TextPosition::new(0)
7041 };
7042 let new_selection = if collapse_selection {
7043 TextSelection::from_position(new_extent)
7044 } else {
7045 value.selection.extend_to(new_extent)
7046 };
7047
7048 Actions::invoke(
7049 app,
7050 context,
7051 &UpdateSelectionIntent::new(value, new_selection, SelectionChangedCause::Keyboard),
7052 );
7053 if state.value(app).selection == new_selection {
7054 app.get_mut(state).vertical_movement_run = Some(current_run);
7055 app.get_mut(state).run_selection = Some(new_selection);
7056 }
7057 None
7058 }
7059}
7060
7061struct WebComposingDisablingCallbackAction<T: Intent> {
7065 action: ActionData,
7066 state: Handle<EditableTextState>,
7067 on_invoke: OnInvokeCallback<T>,
7068}
7069
7070impl<T: Intent> WebComposingDisablingCallbackAction<T> {
7071 fn new(
7072 app: &mut App,
7073 state: Handle<EditableTextState>,
7074 on_invoke: OnInvokeCallback<T>,
7075 ) -> Ref<WebComposingDisablingCallbackAction<T>> {
7076 app.create(WebComposingDisablingCallbackAction {
7077 action: ActionData::new(),
7078 state,
7079 on_invoke,
7080 })
7081 }
7082}
7083
7084impl<T: Intent> Action for WebComposingDisablingCallbackAction<T> {
7085 type Intent = T;
7086 crate::action_accessors!();
7087
7088 fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &T) -> bool {
7089 let state = app.get(self).state;
7090 !(K_IS_WEB
7092 && state.widget(app).user_selection_enabled()
7093 && state.value(app).composing.is_valid())
7094 }
7095
7096 fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
7097 let on_invoke = Rc::clone(&app.get(self).on_invoke);
7098 on_invoke(app, intent)
7099 }
7100}
7101
7102struct SelectAllAction {
7104 action: ActionData,
7105 state: Handle<EditableTextState>,
7106}
7107
7108impl SelectAllAction {
7109 fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<SelectAllAction> {
7110 app.create(SelectAllAction {
7111 action: ActionData::new(),
7112 state,
7113 })
7114 }
7115}
7116
7117impl Action for SelectAllAction {
7118 type Intent = SelectAllTextIntent;
7119 crate::action_accessors!();
7120 crate::context_action_overrides!();
7121}
7122
7123impl ContextAction for SelectAllAction {
7124 fn invoke(
7125 self: Handle<Self>,
7126 app: &mut App,
7127 intent: &SelectAllTextIntent,
7128 context: Option<BuildContext>,
7129 ) -> Option<Rc<dyn Any>> {
7130 let state = app.get(self).state;
7131 if !state.widget(app).user_selection_enabled() {
7132 return None;
7133 }
7134 let context = context.expect("a select all needs a context");
7135 let value = state.value(app);
7136 let selection = TextSelection::new(0, utf16_len(&value.text));
7137 Actions::invoke(
7138 app,
7139 context,
7140 &UpdateSelectionIntent::new(value, selection, intent.cause),
7141 )
7142 }
7143}
7144
7145struct CopySelectionAction {
7147 action: ActionData,
7148 state: Handle<EditableTextState>,
7149}
7150
7151impl CopySelectionAction {
7152 fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<CopySelectionAction> {
7153 app.create(CopySelectionAction {
7154 action: ActionData::new(),
7155 state,
7156 })
7157 }
7158}
7159
7160impl Action for CopySelectionAction {
7161 type Intent = CopySelectionTextIntent;
7162 crate::action_accessors!();
7163 crate::context_action_overrides!();
7164}
7165
7166impl ContextAction for CopySelectionAction {
7167 fn invoke(
7168 self: Handle<Self>,
7169 app: &mut App,
7170 intent: &CopySelectionTextIntent,
7171 _context: Option<BuildContext>,
7172 ) -> Option<Rc<dyn Any>> {
7173 let state = app.get(self).state;
7174 let selection = state.value(app).selection;
7175 if !selection.is_valid() || selection.is_collapsed() {
7176 return None;
7177 }
7178 if !state.widget(app).user_selection_enabled() {
7179 return None;
7180 }
7181 if intent.collapse_selection() {
7182 state.cut_selection(app, intent.cause());
7183 } else {
7184 state.copy_selection(app, intent.cause());
7185 }
7186 None
7187 }
7188}
7189
7190struct PasteSelectionAction {
7192 action: ActionData,
7193 state: Handle<EditableTextState>,
7194}
7195
7196impl PasteSelectionAction {
7197 fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<PasteSelectionAction> {
7198 app.create(PasteSelectionAction {
7199 action: ActionData::new(),
7200 state,
7201 })
7202 }
7203}
7204
7205impl Action for PasteSelectionAction {
7206 type Intent = PasteTextIntent;
7207 crate::action_accessors!();
7208 crate::context_action_overrides!();
7209}
7210
7211impl ContextAction for PasteSelectionAction {
7212 fn invoke(
7213 self: Handle<Self>,
7214 app: &mut App,
7215 intent: &PasteTextIntent,
7216 _context: Option<BuildContext>,
7217 ) -> Option<Rc<dyn Any>> {
7218 let state = app.get(self).state;
7219 if !state.widget(app).user_selection_enabled() {
7220 return None;
7221 }
7222 state.paste_text(app, intent.cause);
7223 None
7224 }
7225}
7226
7227#[cfg(test)]
7228mod tests {
7229 use super::*;
7230 use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf};
7231 use waft_foundation::AppCell;
7232
7233 fn field(app: &mut App) -> EditableText {
7234 let controller = TextEditingController::new(app);
7235 let focus_node = FocusNode::new(app);
7236 let color = Color::from_argb(255, 0, 0, 0);
7237 EditableText::new(
7238 controller.erase(),
7239 focus_node.into_erased(),
7240 TextStyle::new(),
7241 color,
7242 color,
7243 )
7244 }
7245
7246 #[test]
7247 fn a_multiline_field_keeps_its_newlines() {
7248 let cell = AppCell::new();
7249 let mut app = cell.borrow_mut();
7250 let digits = FilteringTextInputFormatter::digits_only();
7251 let multiline = field(&mut app)
7252 .input_formatters(vec![digits.clone()])
7253 .max_lines(None);
7254 assert_eq!(multiline.effective_input_formatters().len(), 1);
7255 let single = field(&mut app).max_lines(None).max_lines(Some(1));
7256 assert_eq!(single.effective_input_formatters().len(), 1);
7257 let single = field(&mut app).input_formatters(vec![digits]);
7258 assert_eq!(single.effective_input_formatters().len(), 2);
7259 }
7260
7261 #[test]
7262 fn a_later_setter_keeps_what_an_earlier_one_set() {
7263 let cell = AppCell::new();
7264 let mut app = cell.borrow_mut();
7265 let multiline = field(&mut app)
7266 .keyboard_type(TextInputType::NUMBER)
7267 .autocorrect(false)
7268 .show_cursor(true)
7269 .enable_interactive_selection(false)
7270 .toolbar_options(ToolbarOptions::EMPTY)
7271 .max_lines(None)
7272 .read_only(true)
7273 .autofill_hints(vec![AutofillHints::EMAIL.into()]);
7274 assert_eq!(
7275 multiline.effective_keyboard_type(&app),
7276 TextInputType::NUMBER
7277 );
7278 assert!(!multiline.effective_autocorrect(&app));
7279 assert!(multiline.effective_show_cursor());
7280 assert!(!multiline.effective_enable_interactive_selection());
7281 assert_eq!(multiline.effective_toolbar_options(), ToolbarOptions::EMPTY);
7282 let obscured = field(&mut app)
7283 .smart_dashes_type(SmartDashesType::Enabled)
7284 .smart_quotes_type(SmartQuotesType::Enabled)
7285 .obscure_text(true);
7286 assert_eq!(
7287 obscured.effective_smart_dashes_type(),
7288 SmartDashesType::Enabled
7289 );
7290 assert_eq!(
7291 obscured.effective_smart_quotes_type(),
7292 SmartQuotesType::Enabled
7293 );
7294 }
7295
7296 #[test]
7297 fn values_left_unset_follow_the_other_settings() {
7298 let cell = AppCell::new();
7299 let mut app = cell.borrow_mut();
7300 let read_only = field(&mut app).read_only(true);
7301 assert!(!read_only.effective_show_cursor());
7302 assert_eq!(
7303 read_only.effective_toolbar_options(),
7304 ToolbarOptions::new().select_all(true).copy(true)
7305 );
7306 let multiline = field(&mut app).max_lines(None);
7307 assert_eq!(
7308 multiline.effective_keyboard_type(&app),
7309 TextInputType::MULTILINE
7310 );
7311 let email = field(&mut app).autofill_hints(vec![AutofillHints::EMAIL.into()]);
7312 assert_eq!(
7313 email.effective_keyboard_type(&app),
7314 TextInputType::EMAIL_ADDRESS
7315 );
7316 let obscured = field(&mut app).obscure_text(true).read_only(true);
7317 assert_eq!(
7318 obscured.effective_smart_dashes_type(),
7319 SmartDashesType::Disabled
7320 );
7321 assert!(!obscured.effective_enable_interactive_selection());
7322 assert_eq!(obscured.effective_toolbar_options(), ToolbarOptions::EMPTY);
7323 }
7324
7325 #[test]
7326 fn controller_starts_empty() {
7327 let cell = AppCell::new();
7328 let mut app = cell.borrow_mut();
7329 let controller = TextEditingController::new(&mut app);
7330 assert_eq!(controller.text_value(&app), "");
7331 assert!(!controller.selection(&app).is_valid());
7332 }
7333
7334 #[test]
7335 fn controller_set_text_clears_selection() {
7336 let cell = AppCell::new();
7337 let mut app = cell.borrow_mut();
7338 let controller = TextEditingController::new(&mut app);
7339 controller.set_text(&mut app, "hi");
7340 assert_eq!(controller.text_value(&app), "hi");
7341 assert!(!controller.selection(&app).is_valid());
7342 }
7343
7344 #[test]
7345 fn controller_from_value_keeps_composing() {
7346 let cell = AppCell::new();
7347 let mut app = cell.borrow_mut();
7348 let controller = TextEditingController::from_value(
7349 &mut app,
7350 Some(
7351 TextEditingValue::new()
7352 .text("abc")
7353 .selection(TextSelection::collapsed(3, TextAffinity::Downstream))
7354 .composing(TextRange::new(0, 3)),
7355 ),
7356 );
7357 assert!(controller.value(&app).is_composing_range_valid());
7358 assert_eq!(controller.value(&app).composing, TextRange::new(0, 3));
7359 }
7360
7361 use waft_painting::PaintingBinding;
7362
7363 use std::cell::RefCell;
7364
7365 use crate::test_harness::Harness;
7366 use crate::testing::{
7367 TargetPlatformVariant, WidgetTester, find, test_widgets, test_widgets_variant,
7368 };
7369 use crate::widgets::basic::{Center, SizedBox};
7370 use crate::widgets::media_query::MediaQueryData;
7371
7372 fn install_fonts(app: &mut App) {
7373 let binding = PaintingBinding::instance(app);
7374 if !binding.has_fonts(app) {
7375 binding.install_fonts(app, |fonts| {
7376 fonts.add_source(valo_system_fonts::SystemFonts::load());
7377 });
7378 }
7379 }
7380
7381 fn find_editable(app: &App, object: AnyRenderObject) -> Option<RenderHandle<RenderEditable>> {
7382 if let Some(editable) = object.downcast::<RenderEditable>(app) {
7383 return Some(editable);
7384 }
7385 let mut found = None;
7386 object.visit_children(app, &mut |child| {
7387 if found.is_none() {
7388 found = find_editable(app, child);
7389 }
7390 });
7391 found
7392 }
7393
7394 fn app_with_clipboard(clipboard: &Rc<waft_test::MockClipboard>) -> Rc<AppCell> {
7396 let clipboard: Rc<dyn waft_embedder::Clipboard> = Rc::clone(clipboard) as _;
7397 let platform = waft_test::TestPlatform::new().with_clipboard(clipboard);
7398 let cell = AppCell::with_platform(Rc::new(platform));
7399 install_fonts(&mut cell.borrow_mut());
7400 cell
7401 }
7402
7403 fn awaited<T: 'static>(cell: &Rc<AppCell>, task: Task<T>) -> Option<T> {
7405 let answer = Rc::new(RefCell::new(None));
7406 let out = Rc::clone(&answer);
7407 cell.borrow()
7408 .spawn(async move |_cx| *out.borrow_mut() = Some(task.await));
7409 cell.checkpoint();
7410 answer.take()
7411 }
7412
7413 fn clipboard_text(cell: &Rc<AppCell>) -> Option<String> {
7415 let data = Clipboard::get_data(&mut cell.borrow_mut(), Clipboard::K_TEXT_PLAIN);
7416 awaited(cell, data)
7417 .expect("the clipboard answered")
7418 .and_then(|data| data.text)
7419 }
7420
7421 struct BoxesController {
7424 change_notifier: ChangeNotifierData,
7425 text_editing_controller: TextEditingControllerData,
7426 }
7427
7428 impl ChangeNotifier for BoxesController {
7429 fn change_notifier_data(&self) -> &ChangeNotifierData {
7430 &self.change_notifier
7431 }
7432
7433 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
7434 &mut self.change_notifier
7435 }
7436 }
7437
7438 impl TextEditingControllerLeaf for BoxesController {
7439 crate::text_editing_controller_accessors!();
7440
7441 fn build_text_span(
7442 self: Handle<Self>,
7443 app: &App,
7444 _context: BuildContext,
7445 style: Option<TextStyle>,
7446 _with_composing: bool,
7447 ) -> TextSpan {
7448 let mut children = Vec::new();
7449 for (index, part) in self.text_value(app).split('\u{FFFC}').enumerate() {
7450 if index > 0 {
7451 let boxed = crate::widgets::basic::SizedBox::new()
7452 .width(30.0)
7453 .height(20.0);
7454 children.push(WidgetSpan::new(boxed).into_span());
7455 }
7456 children.push(TextSpan::new().text(part).into_span());
7457 }
7458 let span = TextSpan::new().children(children);
7459 match style {
7460 Some(style) => span.style(style),
7461 None => span,
7462 }
7463 }
7464 }
7465
7466 #[test]
7467 fn a_controller_of_its_own_puts_a_widget_inside_the_text() {
7468 use waft_rendering::ContainerRenderObjectMixin;
7469
7470 let cell = AppCell::new();
7471 let mut app = cell.borrow_mut();
7472 PaintingBinding::instance(&mut app).install_flutter_test_fonts(&mut app);
7475 let controller = app.create(BoxesController {
7476 change_notifier: ChangeNotifierData::new(),
7477 text_editing_controller: TextEditingControllerData::new(
7478 TextEditingValue::new().text("ab\u{FFFC}cd"),
7479 ),
7480 });
7481 let focus_node = FocusNode::new(&mut app);
7482 let color = Color::from_argb(255, 0, 0, 0);
7483 let editable = EditableText::new(
7484 controller.erase(),
7485 focus_node.into_erased(),
7486 TextStyle::new().font_size(14.0),
7487 color,
7488 color,
7489 );
7490 let tree = MediaQuery::new(
7491 MediaQueryData::new(),
7492 Directionality::new(TextDirection::Ltr, editable),
7493 )
7494 .into_widget();
7495 let harness = Harness::mount(&mut app, tree);
7496 harness.pump(&mut app);
7497
7498 let editable =
7499 find_editable(&app, harness.render_root(&app).as_object()).expect("a RenderEditable");
7500 assert_eq!(editable.child_count(&app), 1, "one inline widget");
7501 let inline = editable.first_child(&app).expect("the inline widget");
7502 let offset = inline
7503 .as_object()
7504 .parent_data_of::<waft_rendering::TextParentData>(&app)
7505 .offset()
7506 .expect("laid out");
7507 assert!(offset.dx() > 0.0, "after \"ab\"");
7508 assert_eq!(inline.size(&app), Size::new(30.0, 20.0));
7509 let line_height = editable.preferred_line_height(&mut app);
7513 assert_eq!(editable.size(&app).height(), line_height);
7514 assert!(line_height < inline.size(&app).height());
7515 }
7516
7517 #[test]
7520 fn cut_and_copy_do_nothing_in_obscured_mode_even_if_explicitly_called() {
7521 let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
7522 let cell = app_with_clipboard(&mock_clipboard);
7523 let key = crate::framework::GlobalKey::new();
7524 let (harness, state) = {
7525 let mut app = cell.borrow_mut();
7526 let controller = TextEditingController::new(&mut app).text(&mut app, "blah blah");
7527 let focus_node = FocusNode::new(&mut app);
7528 let editable = EditableText::new(
7529 controller.erase(),
7530 focus_node.into_erased(),
7531 TextStyle::new(),
7532 Color::from_argb(255, 255, 0, 0),
7533 Color::from_argb(255, 128, 128, 128),
7534 )
7535 .obscure_text(true)
7536 .key(key.clone().into());
7537 let tree = MediaQuery::new(
7538 MediaQueryData::new(),
7539 Directionality::new(TextDirection::Ltr, editable),
7540 )
7541 .into_widget();
7542 let harness = Harness::mount(&mut app, tree);
7543 harness.pump(&mut app);
7544 let state = key
7545 .current_state::<EditableTextState>(&app)
7546 .expect("the field is mounted");
7547 (harness, state)
7548 };
7549 {
7550 let app = cell.borrow();
7551 assert!(state.select_all_enabled(&app));
7552 assert!(state.paste_enabled(&app));
7553 assert!(!state.cut_enabled(&app));
7554 assert!(!state.copy_enabled(&app));
7555 }
7556
7557 {
7559 let mut app = cell.borrow_mut();
7560 state.select_all(&mut app, SelectionChangedCause::Toolbar);
7561 harness.pump(&mut app);
7562 }
7563 let written = Clipboard::set_data(&mut cell.borrow_mut(), ClipboardData::new(""));
7564 awaited(&cell, written).expect("the clipboard was written");
7565 state.cut_selection(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
7566 assert_eq!(clipboard_text(&cell).as_deref(), Some(""));
7567
7568 {
7569 let mut app = cell.borrow_mut();
7570 state.select_all(&mut app, SelectionChangedCause::Toolbar);
7571 harness.pump(&mut app);
7572 }
7573 let written = Clipboard::set_data(&mut cell.borrow_mut(), ClipboardData::new(""));
7574 awaited(&cell, written).expect("the clipboard was written");
7575 state.copy_selection(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
7576 assert_eq!(clipboard_text(&cell).as_deref(), Some(""));
7577 }
7578
7579 #[test]
7581 fn should_not_scroll_on_paste_if_caret_already_visible() {
7582 let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
7583 let cell = app_with_clipboard(&mock_clipboard);
7584 let key = crate::framework::GlobalKey::new();
7585 let (harness, state, controller, focus_node, scroll_controller) = {
7586 let mut app = cell.borrow_mut();
7587 let scroll_controller = ScrollController::default(&mut app);
7588 let controller = TextEditingController::new(&mut app).text(
7589 &mut app,
7590 format!("Lorem ipsum please paste here: \n{}", ".\n".repeat(50)),
7591 );
7592 let focus_node = FocusNode::new(&mut app);
7593 let editable = EditableText::new(
7594 controller.erase(),
7595 focus_node.erase(),
7596 TextStyle::new().font_size(36.0),
7597 Color::from_argb(255, 255, 0, 0),
7598 Color::from_argb(255, 128, 128, 128),
7599 )
7600 .scroll_controller(scroll_controller.erase())
7601 .max_lines(None)
7602 .key(key.clone().into());
7603 let tree = MediaQuery::new(
7604 MediaQueryData::new(),
7605 Directionality::new(
7606 TextDirection::Ltr,
7607 Center::new().child(SizedBox::square(Some(600.0)).child(editable)),
7608 ),
7609 )
7610 .into_widget();
7611 let harness = Harness::mount(&mut app, tree);
7612 harness.pump(&mut app);
7613 let state = key
7614 .current_state::<EditableTextState>(&app)
7615 .expect("the field is mounted");
7616 (harness, state, controller, focus_node, scroll_controller)
7617 };
7618
7619 let written = Clipboard::set_data(
7620 &mut cell.borrow_mut(),
7621 ClipboardData::new("Fairly long text to be pasted"),
7622 );
7623 awaited(&cell, written).expect("the clipboard was written");
7624 {
7625 let mut app = cell.borrow_mut();
7626 focus_node.request_focus(&mut app, None);
7627 assert_eq!(scroll_controller.as_controller().offset(&app), 0.0);
7628 controller.set_selection(
7629 &mut app,
7630 TextSelection::collapsed(31, TextAffinity::Downstream),
7631 );
7632 }
7633 let pasted = state.paste_text(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
7634 awaited(&cell, pasted).expect("the paste completed");
7635 harness.pump(&mut cell.borrow_mut());
7636
7637 assert_eq!(
7639 scroll_controller.as_controller().offset(&cell.borrow()),
7640 0.0
7641 );
7642 }
7643
7644 #[test]
7647 fn a_user_edit_scrolls_the_caret_on_screen() {
7648 test_widgets(|tester| {
7649 let key = crate::framework::GlobalKey::new();
7650 let (controller, focus_node, scroll_controller) = tester.update(|app| {
7651 (
7652 TextEditingController::new(app),
7653 FocusNode::new(app),
7654 ScrollController::default(app),
7655 )
7656 });
7657 let editable = EditableText::new(
7658 controller.erase(),
7659 focus_node.erase(),
7660 TextStyle::new().font_size(20.0),
7661 Color::from_argb(255, 255, 0, 0),
7662 Color::from_argb(255, 128, 128, 128),
7663 )
7664 .scroll_controller(scroll_controller.erase())
7665 .max_lines(None)
7666 .key(key.clone().into());
7667 let tree = MediaQuery::new(
7668 MediaQueryData::new(),
7669 Directionality::new(
7670 TextDirection::Ltr,
7671 Center::new().child(SizedBox::square(Some(200.0)).child(editable)),
7672 ),
7673 )
7674 .into_widget();
7675 tester.pump_widget(tree);
7676 let state = key
7677 .current_state::<EditableTextState>(&tester.cell.borrow_mut())
7678 .expect("the field is mounted");
7679 focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
7680 tester.pump_by(Duration::from_millis(16));
7681 assert_eq!(
7682 scroll_controller
7683 .as_controller()
7684 .offset(&tester.cell.borrow()),
7685 0.0
7686 );
7687
7688 let text = "line\n".repeat(20);
7689 let end = utf16_len(&text);
7690 TextSelectionDelegate::user_update_text_editing_value(
7691 state,
7692 &mut tester.cell.borrow_mut(),
7693 TextEditingValue::new()
7694 .text(text)
7695 .selection(TextSelection::collapsed(end, TextAffinity::Downstream)),
7696 SelectionChangedCause::Keyboard,
7697 );
7698 for ms in [16, 16, 52, 100, 100] {
7700 tester.pump_by(Duration::from_millis(ms));
7701 }
7702
7703 let app = tester.cell.borrow();
7704 let position = scroll_controller.as_controller().position(&app);
7705 assert!(position.max_scroll_extent(&app) > 0.0);
7706 assert_eq!(
7707 scroll_controller.as_controller().offset(&app),
7708 position.max_scroll_extent(&app)
7709 );
7710 });
7711 }
7712
7713 fn focused_field(
7716 clipboard: &Rc<waft_test::MockClipboard>,
7717 text: &str,
7718 ) -> (Rc<AppCell>, Harness, Ref<TextEditingController>) {
7719 let cell = app_with_clipboard(clipboard);
7720 let (harness, controller) = {
7721 let mut app = cell.borrow_mut();
7722 let controller = TextEditingController::new(&mut app).text(&mut app, text);
7723 let focus_node = FocusNode::new(&mut app);
7724 let editable = EditableText::new(
7725 controller.erase(),
7726 focus_node.erase(),
7727 TextStyle::new(),
7728 Color::from_argb(255, 255, 0, 0),
7729 Color::from_argb(255, 128, 128, 128),
7730 );
7731 let tree = MediaQuery::new(
7732 MediaQueryData::new(),
7733 Directionality::new(TextDirection::Ltr, editable),
7734 )
7735 .into_widget();
7736 let harness = Harness::mount(&mut app, tree);
7737 harness.pump(&mut app);
7738 focus_node.request_focus(&mut app, None);
7739 (harness, controller)
7740 };
7741 cell.checkpoint();
7743 let mut app = cell.borrow_mut();
7744 harness.pump(&mut app);
7745 controller.set_selection(&mut app, TextSelection::new(0, utf16_len(text)));
7746 drop(app);
7747 (cell, harness, controller)
7748 }
7749
7750 #[test]
7751 fn the_users_copy_writes_the_focused_fields_selection_through_its_request() {
7752 let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
7753 let (cell, _harness, _controller) = focused_field(&mock_clipboard, "copied");
7754 let copied = waft_test::MockClipboard::new();
7755 let into = copied.clone();
7756 let request = waft_embedder::CopyRequest::new(move |items, options| {
7757 waft_embedder::Clipboard::write(&into, items, options)
7758 });
7759
7760 let mut app = cell.borrow_mut();
7761 let binding = crate::WidgetsBinding::instance(&mut app);
7762 binding.handle_clipboard_event(&mut app, waft_embedder::ClipboardEvent::Copy(request));
7763 drop(app);
7764 cell.checkpoint();
7765
7766 assert_eq!(copied.clipboard_data().as_deref(), Some("copied"));
7767 assert_eq!(mock_clipboard.clipboard_data(), None);
7768 }
7769
7770 #[test]
7771 fn the_users_paste_reaches_the_focused_field_with_what_was_pasted() {
7772 let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
7773 mock_clipboard.set_clipboard_data(Some("on the clipboard".to_owned()));
7774 let (cell, _harness, controller) = focused_field(&mock_clipboard, "replaced");
7775 let pasted = waft_test::MockClipboard::new();
7776 pasted.set_clipboard_data(Some("pasted".to_owned()));
7777 let listing = cell
7778 .borrow()
7779 .spawn(async move |_cx| waft_embedder::Clipboard::items(&pasted).await);
7780 let items = awaited(&cell, listing).expect("a mock clipboard lists at once");
7781
7782 let mut app = cell.borrow_mut();
7783 let binding = crate::WidgetsBinding::instance(&mut app);
7784 binding.handle_clipboard_event(&mut app, waft_embedder::ClipboardEvent::Paste(items));
7785 drop(app);
7786 cell.checkpoint();
7787
7788 assert_eq!(controller.value(&cell.borrow()).text, "pasted");
7789 }
7790
7791 #[test]
7792 fn an_edit_command_from_the_platforms_menu_reaches_the_focused_field() {
7793 let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
7794 let (cell, _harness, controller) = focused_field(&mock_clipboard, "deleted");
7795
7796 let mut app = cell.borrow_mut();
7797 let binding = crate::WidgetsBinding::instance(&mut app);
7798 binding.handle_edit_command(&mut app, waft_embedder::EditCommand::Delete);
7799 drop(app);
7800 cell.checkpoint();
7801
7802 assert_eq!(controller.value(&cell.borrow()).text, "");
7803 }
7804
7805 #[test]
7806 fn editable_text_builds_a_render_editable() {
7807 let cell = AppCell::new();
7808 let mut app = cell.borrow_mut();
7809 install_fonts(&mut app);
7810 let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
7811 let focus_node = FocusNode::new(&mut app);
7812 let editable = EditableText::new(
7813 controller.erase(),
7814 focus_node.into_erased(),
7815 TextStyle::new(),
7816 Color::from_argb(255, 0, 0, 0),
7817 Color::from_argb(255, 128, 128, 128),
7818 );
7819 let tree = MediaQuery::new(
7820 MediaQueryData::new(),
7821 Directionality::new(TextDirection::Ltr, editable),
7822 )
7823 .into_widget();
7824 let harness = Harness::mount(&mut app, tree);
7825 harness.pump(&mut app);
7826 let root = harness.render_root(&app).as_object();
7827 let render_editable =
7828 find_editable(&app, root).expect("EditableText should mount a RenderEditable");
7829 let size = render_editable.size(&app);
7830 assert!(
7831 size.width() > 0.0 && size.height() > 0.0,
7832 "RenderEditable should have a size, got {size:?}"
7833 );
7834 }
7835
7836 #[test]
7837 fn a_focused_field_leaves_the_tree_without_its_callbacks_outliving_it() {
7838 use crate::{ListenableBuilder, SizedBox, primary_focus};
7839 use waft_foundation::ValueNotifier;
7840
7841 test_widgets(|tester| {
7842 let (shown, tree) = {
7843 let mut app = tester.cell.borrow_mut();
7844 let shown = app.create(ValueNotifier::new(true));
7845 let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
7846 let focus_node = FocusNode::new(&mut app);
7847 let visible = shown.handle();
7848 let field = ListenableBuilder::new(Rc::new(shown.clone()), move |app, _, _| {
7849 if !*app.get(visible).value() {
7850 return SizedBox::shrink().into_widget();
7851 }
7852 EditableText::new(
7853 controller.erase(),
7854 focus_node.erase(),
7855 TextStyle::new(),
7856 Color::from_argb(255, 0, 0, 0),
7857 Color::from_argb(255, 128, 128, 128),
7858 )
7859 .autofocus(true)
7860 .into_widget()
7861 });
7862 (shown, Directionality::new(TextDirection::Ltr, field))
7863 };
7864 tester.pump_widget(tree);
7865 let pump = |tester: &mut WidgetTester| {
7866 for _ in 0..5 {
7867 tester.pump_by(Duration::from_millis(20));
7868 }
7869 };
7870 pump(tester);
7871 assert!(
7872 primary_focus(&mut tester.cell.borrow_mut()).is_some(),
7873 "the field took the focus and opened its input connection"
7874 );
7875 shown.set_value(&mut tester.cell.borrow_mut(), false);
7876 pump(tester);
7877 });
7878 }
7879
7880 #[test]
7884 fn a_field_removed_before_its_keyboard_callbacks_run_does_not_crash() {
7885 use crate::{ListenableBuilder, SizedBox, primary_focus};
7886 use waft_embedder::ViewPadding;
7887 use waft_foundation::ValueNotifier;
7888
7889 test_widgets(|tester| {
7890 tester.view().set_physical_size(Size::new(300.0, 600.0));
7891 tester.view().set_device_pixel_ratio(1.0);
7892 let (shown, tree) = {
7893 let mut app = tester.cell.borrow_mut();
7894 let shown = app.create(ValueNotifier::new(true));
7895 let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
7896 let focus_node = FocusNode::new(&mut app);
7897 let visible = shown.handle();
7898 let field = ListenableBuilder::new(Rc::new(shown.clone()), move |app, _, _| {
7899 if !*app.get(visible).value() {
7900 return SizedBox::shrink().into_widget();
7901 }
7902 EditableText::new(
7903 controller.erase(),
7904 focus_node.erase(),
7905 TextStyle::new(),
7906 Color::from_argb(255, 0, 0, 0),
7907 Color::from_argb(255, 128, 128, 128),
7908 )
7909 .autofocus(true)
7910 .into_widget()
7911 });
7912 (shown, Directionality::new(TextDirection::Ltr, field))
7913 };
7914 tester.pump_widget(tree);
7915 let pump = |tester: &mut WidgetTester| {
7916 for _ in 0..5 {
7917 tester.pump_by(Duration::from_millis(20));
7918 }
7919 };
7920 pump(tester);
7921 assert!(
7922 primary_focus(&mut tester.cell.borrow_mut()).is_some(),
7923 "the field took the focus and listens for the keyboard"
7924 );
7925
7926 tester.view().set_view_insets(ViewPadding {
7927 bottom: 250.0,
7928 ..ViewPadding::ZERO
7929 });
7930 shown.set_value(&mut tester.cell.borrow_mut(), false);
7931 pump(tester);
7932 });
7933 }
7934
7935 struct ObscuredField {
7937 state: Handle<EditableTextState>,
7938 obscure_text: Rc<Cell<bool>>,
7940 rebuild: Ref<waft_foundation::ValueNotifier<u32>>,
7942 }
7943
7944 impl ObscuredField {
7945 fn pump(tester: &mut WidgetTester) -> ObscuredField {
7948 use crate::ListenableBuilder;
7949 use crate::framework::GlobalKey;
7950 use waft_foundation::ValueNotifier;
7951
7952 let key = GlobalKey::new();
7953 let obscure_text = Rc::new(Cell::new(true));
7954 let (rebuild, tree) = {
7955 let mut app = tester.cell.borrow_mut();
7956 let rebuild = app.create(ValueNotifier::new(0));
7957 let controller = TextEditingController::new(&mut app);
7958 let focus_node = FocusNode::new(&mut app);
7959 let field_key = key.clone();
7960 let obscured = Rc::clone(&obscure_text);
7961 let field = ListenableBuilder::new(Rc::new(rebuild.clone()), move |_, _, _| {
7962 EditableText::new(
7963 controller.erase(),
7964 focus_node.erase(),
7965 TextStyle::new(),
7966 Color::from_argb(255, 0, 0, 255),
7967 Color::from_argb(255, 128, 128, 128),
7968 )
7969 .obscure_text(obscured.get())
7970 .key(field_key.clone().into())
7971 .into_widget()
7972 });
7973 let tree = MediaQuery::new(
7974 MediaQueryData::new(),
7975 Directionality::new(TextDirection::Ltr, field),
7976 )
7977 .into_widget();
7978 (rebuild, tree)
7979 };
7980 tester.pump_widget(tree);
7981 let state = key
7982 .current_state::<EditableTextState>(&tester.cell.borrow())
7983 .expect("the field is mounted");
7984 ObscuredField {
7985 state,
7986 obscure_text,
7987 rebuild,
7988 }
7989 }
7990
7991 fn set_obscure_text(&self, tester: &WidgetTester, obscure_text: bool) {
7993 self.obscure_text.set(obscure_text);
7994 let mut app = tester.cell.borrow_mut();
7995 let next = *app.get(&self.rebuild).value() + 1;
7996 self.rebuild.set_value(&mut app, next);
7997 }
7998
7999 fn shown_text(&self, tester: &WidgetTester) -> String {
8001 let mut app = tester.cell.borrow_mut();
8002 let render_editable = self.state.render_editable(&app);
8003 render_editable.plain_text(&mut app)
8004 }
8005 }
8006
8007 fn selection_rects_sent(tester: &WidgetTester) -> Vec<Vec<SelectionRect>> {
8009 tester
8010 .view()
8011 .test_host()
8012 .text_input_calls()
8013 .into_iter()
8014 .filter_map(|call| match call {
8015 waft_test::TextInputCall::SetSelectionRects(rects) => Some(rects),
8016 _ => None,
8017 })
8018 .collect()
8019 }
8020
8021 const HALF_A_BLINK: Duration = Duration::from_millis(500);
8022
8023 fn mobile() -> TargetPlatformVariant {
8025 TargetPlatformVariant::new([
8026 TargetPlatform::IOS,
8027 TargetPlatform::Android,
8028 TargetPlatform::Fuchsia,
8029 ])
8030 }
8031
8032 #[test]
8033 fn password_briefly_shows_last_character_when_entered_on_mobile() {
8034 test_widgets_variant(mobile(), |tester| {
8035 let field = ObscuredField::pump(tester);
8036
8037 tester.enter_text(find::by_type::<EditableText>(), "AA");
8038 tester.pump();
8039 tester.enter_text(find::by_type::<EditableText>(), "AAA");
8040 tester.pump();
8041
8042 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}A");
8043 tester.pump_by(HALF_A_BLINK);
8044 tester.pump_by(HALF_A_BLINK);
8045 tester.pump_by(HALF_A_BLINK);
8046 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
8047 });
8048 }
8049
8050 #[test]
8053 fn selection_rects_are_sent_on_ios_once_the_text_is_laid_out() {
8054 let tester = &mut WidgetTester::on(TargetPlatform::IOS);
8055 let field = ObscuredField::pump(tester);
8056 field.set_obscure_text(tester, false);
8057 tester.enter_text(find::by_type::<EditableText>(), "Text1");
8058 tester.pump();
8059
8060 let sent = selection_rects_sent(tester);
8061 let rects: Vec<(i32, Rect)> = sent
8062 .last()
8063 .expect("the rects of the laid out text")
8064 .iter()
8065 .map(|rect| (rect.position, rect.bounds))
8066 .collect();
8067 assert_eq!(
8068 rects,
8069 [
8070 (0, Rect::from_ltrb(0.0, 0.0, 14.0, 14.0)),
8071 (1, Rect::from_ltrb(14.0, 0.0, 28.0, 14.0)),
8072 (2, Rect::from_ltrb(28.0, 0.0, 42.0, 14.0)),
8073 (3, Rect::from_ltrb(42.0, 0.0, 56.0, 14.0)),
8074 (4, Rect::from_ltrb(56.0, 0.0, 70.0, 14.0)),
8075 ]
8076 );
8077 tester.pump();
8078 assert_eq!(selection_rects_sent(tester).len(), sent.len(), "sent once");
8079
8080 let tester = &mut WidgetTester::on(TargetPlatform::Android);
8081 let _field = ObscuredField::pump(tester);
8082 tester.enter_text(find::by_type::<EditableText>(), "Text1");
8083 tester.pump();
8084 assert!(selection_rects_sent(tester).is_empty(), "iOS alone");
8085 }
8086
8087 #[test]
8089 fn password_briefly_does_not_show_last_character_when_disabled_by_system() {
8090 test_widgets(|tester| {
8091 let field = ObscuredField::pump(tester);
8092
8093 tester.enter_text(find::by_type::<EditableText>(), "AA");
8094 tester.pump();
8095 tester.enter_text(find::by_type::<EditableText>(), "AAA");
8096 tester.pump();
8097
8098 tester.platform().set_briefly_show_password(false);
8099 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}A");
8100 tester.pump_by(HALF_A_BLINK);
8101 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
8102 tester.pump_by(HALF_A_BLINK);
8103 tester.pump_by(HALF_A_BLINK);
8104 tester.pump_by(HALF_A_BLINK);
8105 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
8106 });
8107 }
8108
8109 #[test]
8110 fn prevent_last_character_visibility_in_obscure_text_when_obscure_text_is_toggled_on_mobile() {
8111 test_widgets_variant(mobile(), |tester| {
8112 let field = ObscuredField::pump(tester);
8113 tester.show_keyboard(find::by_type::<EditableText>());
8114
8115 tester.enter_text(find::by_type::<EditableText>(), "H");
8116 tester.pump();
8117 tester.enter_text(find::by_type::<EditableText>(), "HH");
8118 tester.pump();
8119
8120 assert_eq!(field.shown_text(tester), "\u{2022}H");
8121 tester.pump_by(HALF_A_BLINK);
8122 tester.pump_by(HALF_A_BLINK);
8123 tester.pump_by(HALF_A_BLINK);
8124 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}");
8125
8126 tester.enter_text(find::by_type::<EditableText>(), "HHH");
8127 tester.pump();
8128
8129 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}H");
8130
8131 field.set_obscure_text(tester, false);
8132 tester.pump();
8133 assert_eq!(field.shown_text(tester), "HHH");
8134
8135 field.set_obscure_text(tester, true);
8136 tester.pump();
8137 assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
8138 });
8139 }
8140
8141 #[test]
8142 fn editable_text_respects_the_media_query_spacing_overrides_on_its_strut() {
8143 let cell = AppCell::new();
8144 let mut app = cell.borrow_mut();
8145 install_fonts(&mut app);
8146 let controller = TextEditingController::new(&mut app);
8147 let focus_node = FocusNode::new(&mut app);
8148 let color = Color::from_argb(255, 0, 0, 0);
8149 let editable_text = EditableText::new(
8150 controller.erase(),
8151 focus_node.into_erased(),
8152 TextStyle::new().font_weight(FontWeight::NORMAL),
8153 color,
8154 color,
8155 )
8156 .strut_style(StrutStyle::new().height(0.9));
8157 let tree = MediaQuery::new(
8158 MediaQueryData::new()
8159 .line_height_scale_factor_override(2.0)
8160 .letter_spacing_override(2.0)
8161 .word_spacing_override(2.0),
8162 Directionality::new(TextDirection::Ltr, editable_text),
8163 )
8164 .into_widget();
8165 let harness = Harness::mount(&mut app, tree);
8166 harness.pump(&mut app);
8167 controller.set_text(&mut app, "foo");
8168 harness.pump(&mut app);
8169
8170 let editable =
8171 find_editable(&app, harness.render_root(&app).as_object()).expect("a RenderEditable");
8172 let style = editable
8173 .text(&app)
8174 .expect("an editable has text")
8175 .style()
8176 .cloned()
8177 .expect("a style");
8178 assert_eq!(style.height, Some(2.0));
8179 assert_eq!(style.letter_spacing, Some(2.0));
8180 assert_eq!(style.word_spacing, Some(2.0));
8181 assert_eq!(
8182 editable
8183 .strut_style(&app)
8184 .and_then(|strut_style| strut_style.height),
8185 Some(2.0)
8186 );
8187 }
8188}