waft_embedder/text_input.rs
1//! Flutter counterpart: `services/text_input.dart` (value types and
2//! [`TextInputConfiguration`]).
3//!
4//! Lives here because [`crate::View`], [`crate::ViewHost`]'s text input and
5//! [`crate::EmbedderClient`] name these types. The connection and client stay in `waft-services`.
6
7use std::fmt;
8
9use crate::text_editing::TextSelection;
10use crate::{
11 Brightness, Locale, Offset, Rect, TextAffinity, TextDirection, TextPosition, TextRange,
12};
13
14/// Indicates how to handle the intelligent replacement of dashes in text input.
15///
16/// See also:
17///
18/// * `TextField.smartDashesType`
19/// * `CupertinoTextField.smartDashesType`
20/// * `EditableText.smartDashesType`
21/// * [`SmartQuotesType`]
22/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub enum SmartDashesType {
25 /// Smart dashes is disabled.
26 ///
27 /// This corresponds to the
28 /// ["no" value of UITextSmartDashesType](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/no).
29 Disabled,
30
31 /// Smart dashes is enabled.
32 ///
33 /// This corresponds to the
34 /// ["yes" value of UITextSmartDashesType](https://developer.apple.com/documentation/uikit/uitextsmartdashestype/yes).
35 Enabled,
36}
37
38/// Indicates how to handle the intelligent replacement of quotes in text input.
39///
40/// See also:
41///
42/// * `TextField.smartQuotesType`
43/// * `CupertinoTextField.smartQuotesType`
44/// * `EditableText.smartQuotesType`
45/// * <https://developer.apple.com/documentation/uikit/uitextinputtraits>
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub enum SmartQuotesType {
48 /// Smart quotes is disabled.
49 ///
50 /// This corresponds to the
51 /// ["no" value of UITextSmartQuotesType](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/no).
52 Disabled,
53
54 /// Smart quotes is enabled.
55 ///
56 /// This corresponds to the
57 /// ["yes" value of UITextSmartQuotesType](https://developer.apple.com/documentation/uikit/uitextsmartquotestype/yes).
58 Enabled,
59}
60
61/// The type of information for which to optimize the text input control.
62///
63/// On Android, behavior may vary across device and keyboard provider.
64///
65/// This class stays as close to `Enum` interface as possible, and allows
66/// for additional flags for some input types. For example, numeric input
67/// can specify whether it supports decimal numbers and/or signed numbers.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub struct TextInputType {
70 /// Enum value index, corresponds to one of the [`VALUES`](Self::VALUES).
71 pub index: i32,
72 /// The number is signed, allowing a positive or negative sign at the start.
73 ///
74 /// This flag is only used for the [`NUMBER`](Self::NUMBER) input type, otherwise `None`.
75 /// Use `TextInputType::number_with_options().signed(true)` to set this.
76 pub signed: Option<bool>,
77 /// The number is decimal, allowing a decimal point to provide fractional.
78 ///
79 /// This flag is only used for the [`NUMBER`](Self::NUMBER) input type, otherwise `None`.
80 /// Use `TextInputType::number_with_options().decimal(true)` to set this.
81 pub decimal: Option<bool>,
82 /// The number is a password.
83 ///
84 /// This flag is only used for the [`NUMBER`](Self::NUMBER) input type, otherwise `None`.
85 /// Use `TextInputType::number_with_options().password(true)` to set this.
86 ///
87 /// On Android, this adds
88 /// [TYPE_NUMBER_VARIATION_PASSWORD](https://developer.android.com/reference/android/text/InputType#TYPE_NUMBER_VARIATION_PASSWORD)
89 /// to the input type. It has no effect on iOS, web, or desktop platforms.
90 pub password: Option<bool>,
91}
92
93impl TextInputType {
94 const fn named(index: i32) -> TextInputType {
95 TextInputType {
96 index,
97 signed: None,
98 decimal: None,
99 password: None,
100 }
101 }
102
103 /// Optimize for textual information.
104 ///
105 /// Requests the default platform keyboard.
106 pub const TEXT: TextInputType = TextInputType::named(0);
107
108 /// Optimize for multiline textual information.
109 ///
110 /// Requests the default platform keyboard, but accepts newlines when the
111 /// enter key is pressed. This is the input type used for all multiline text
112 /// fields.
113 pub const MULTILINE: TextInputType = TextInputType::named(1);
114
115 /// Optimize for unsigned numerical information without a decimal point.
116 ///
117 /// Requests a default keyboard with ready access to the number keys.
118 /// Additional options, such as decimal point and/or positive/negative
119 /// signs, can be requested using [`number_with_options`](Self::number_with_options).
120 pub const NUMBER: TextInputType = TextInputType::number_with_options();
121
122 /// Optimize for telephone numbers.
123 ///
124 /// Requests a keyboard with ready access to the number keys, "*", and "#".
125 pub const PHONE: TextInputType = TextInputType::named(3);
126
127 /// Optimize for date and time information.
128 ///
129 /// On iOS, requests the default keyboard.
130 ///
131 /// On Android, requests a keyboard with ready access to the number keys,
132 /// ":", and "-".
133 pub const DATETIME: TextInputType = TextInputType::named(4);
134
135 /// Optimize for email addresses.
136 ///
137 /// Requests a keyboard with ready access to the "@" and "." keys.
138 pub const EMAIL_ADDRESS: TextInputType = TextInputType::named(5);
139
140 /// Optimize for URLs.
141 ///
142 /// Requests a keyboard with ready access to the "/" and "." keys.
143 pub const URL: TextInputType = TextInputType::named(6);
144
145 /// Optimize for passwords that are visible to the user.
146 ///
147 /// Requests a keyboard with ready access to both letters and numbers.
148 pub const VISIBLE_PASSWORD: TextInputType = TextInputType::named(7);
149
150 /// Optimized for a person's name.
151 ///
152 /// On iOS, requests the
153 /// [UIKeyboardType.namePhonePad](https://developer.apple.com/documentation/uikit/uikeyboardtype/namephonepad)
154 /// keyboard, a keyboard optimized for entering a person’s name or phone number.
155 /// Does not support auto-capitalization.
156 ///
157 /// On Android, requests a keyboard optimized for
158 /// [TYPE_TEXT_VARIATION_PERSON_NAME](https://developer.android.com/reference/android/text/InputType#TYPE_TEXT_VARIATION_PERSON_NAME).
159 pub const NAME: TextInputType = TextInputType::named(8);
160
161 /// Optimized for postal mailing addresses.
162 ///
163 /// On iOS, requests the default keyboard.
164 ///
165 /// On Android, requests a keyboard optimized for
166 /// [TYPE_TEXT_VARIATION_POSTAL_ADDRESS](https://developer.android.com/reference/android/text/InputType#TYPE_TEXT_VARIATION_POSTAL_ADDRESS).
167 pub const STREET_ADDRESS: TextInputType = TextInputType::named(9);
168
169 /// Prevent the OS from showing the on-screen virtual keyboard.
170 pub const NONE: TextInputType = TextInputType::named(10);
171
172 /// Optimized for web searches.
173 ///
174 /// Requests a keyboard that includes keys useful for web searches as well as URLs.
175 ///
176 /// On iOS, requests a default keyboard with ready access to the "." key. In contrast to
177 /// [`URL`](Self::URL), a space bar is available.
178 ///
179 /// On Android this is remapped to the [`URL`](Self::URL) keyboard type as it always shows a space bar.
180 pub const WEB_SEARCH: TextInputType = TextInputType::named(11);
181
182 /// Optimized for social media.
183 ///
184 /// Requests a keyboard that includes keys useful for handles and tags.
185 ///
186 /// On iOS, requests a default keyboard with ready access to the "@" and "#" keys.
187 ///
188 /// On Android this is remapped to the [`EMAIL_ADDRESS`](Self::EMAIL_ADDRESS) keyboard type as it always shows the "@" key.
189 pub const TWITTER: TextInputType = TextInputType::named(12);
190
191 /// All possible enum values.
192 pub const VALUES: &[TextInputType] = &[
193 Self::TEXT,
194 Self::MULTILINE,
195 Self::NUMBER,
196 Self::PHONE,
197 Self::DATETIME,
198 Self::EMAIL_ADDRESS,
199 Self::URL,
200 Self::VISIBLE_PASSWORD,
201 Self::NAME,
202 Self::STREET_ADDRESS,
203 Self::NONE,
204 Self::WEB_SEARCH,
205 Self::TWITTER,
206 ];
207
208 const NAMES: &[&str] = &[
209 "text",
210 "multiline",
211 "number",
212 "phone",
213 "datetime",
214 "emailAddress",
215 "url",
216 "visiblePassword",
217 "name",
218 "address",
219 "none",
220 "webSearch",
221 "twitter",
222 ];
223
224 /// Optimize for numerical information.
225 ///
226 /// Requests a numeric keyboard with additional settings.
227 /// The [`signed`](Self::signed), [`decimal`](Self::decimal), and [`password`](Self::password)
228 /// parameters are optional.
229 pub const fn number_with_options() -> TextInputType {
230 TextInputType {
231 index: 2,
232 signed: Some(false),
233 decimal: Some(false),
234 password: Some(false),
235 }
236 }
237
238 /// Dart `TextInputType.numberWithOptions(signed:)`.
239 pub fn signed(mut self, signed: bool) -> TextInputType {
240 self.signed = Some(signed);
241 self
242 }
243
244 /// Dart `TextInputType.numberWithOptions(decimal:)`.
245 pub fn decimal(mut self, decimal: bool) -> TextInputType {
246 self.decimal = Some(decimal);
247 self
248 }
249
250 /// Dart `TextInputType.numberWithOptions(password:)`.
251 pub fn password(mut self, password: bool) -> TextInputType {
252 self.password = Some(password);
253 self
254 }
255
256 fn name(self) -> String {
257 format!("TextInputType.{}", Self::NAMES[self.index as usize])
258 }
259}
260
261impl fmt::Display for TextInputType {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 write!(
264 f,
265 "TextInputType(name: {}, signed: {:?}, decimal: {:?}, password: {:?})",
266 self.name(),
267 self.signed,
268 self.decimal,
269 self.password
270 )
271 }
272}
273
274/// An action the user has requested the text input control to perform.
275///
276/// Each action represents a logical meaning, and also configures the soft
277/// keyboard to display a certain kind of action button. The visual appearance
278/// of the action button might differ between versions of the same OS.
279///
280/// Despite the logical meaning of each action, choosing a particular
281/// [`TextInputAction`] does not necessarily cause any specific behavior to
282/// happen, other than changing the focus when appropriate. It is up to the
283/// developer to ensure that the behavior that occurs when an action button is
284/// pressed is appropriate for the action button chosen.
285///
286/// For example: If the user presses the keyboard action button on iOS when it
287/// reads "Emergency Call", the result should not be a focus change to the next
288/// TextField. This behavior is not logically appropriate for a button that says
289/// "Emergency Call".
290///
291/// See `EditableText` for more information about customizing action button
292/// behavior.
293///
294/// Most [`TextInputAction`]s are supported equally by both Android and iOS.
295/// However, there is not a complete, direct mapping between Android's IME input
296/// types and iOS's keyboard return types. Therefore, some [`TextInputAction`]s
297/// are inappropriate for one of the platforms. If a developer chooses an
298/// inappropriate [`TextInputAction`] when running in debug mode, an error will be
299/// thrown. If the same thing is done in release mode, then instead of sending
300/// the inappropriate value, Android will use "unspecified" on the platform
301/// side and iOS will use "default" on the platform side.
302///
303/// See also:
304///
305/// * `TextInput`, which configures the platform's keyboard setup.
306/// * `EditableText`, which invokes callbacks when the action button is pressed.
307//
308// This class has been cloned to `flutter_driver/lib/src/common/action.dart` as `TextInputAction`,
309// and must be kept in sync.
310#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
311pub enum TextInputAction {
312 /// Logical meaning: There is no relevant input action for the current input
313 /// source, e.g., `TextField`.
314 ///
315 /// Android: Corresponds to Android's "IME_ACTION_NONE". The keyboard setup
316 /// is decided by the OS. The keyboard will likely show a return key.
317 ///
318 /// iOS: iOS does not have a keyboard return type of "none." It is
319 /// inappropriate to choose this [`TextInputAction`] when running on iOS.
320 None,
321
322 /// Logical meaning: Let the OS decide which action is most appropriate.
323 ///
324 /// Android: Corresponds to Android's "IME_ACTION_UNSPECIFIED". The OS chooses
325 /// which keyboard action to display. The decision will likely be a done
326 /// button or a return key.
327 ///
328 /// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in
329 /// the action button is "return".
330 Unspecified,
331
332 /// Logical meaning: The user is done providing input to a group of inputs
333 /// (like a form). Some kind of finalization behavior should now take place.
334 ///
335 /// Android: Corresponds to Android's "IME_ACTION_DONE". The OS displays a
336 /// button that represents completion, e.g., a checkmark button.
337 ///
338 /// iOS: Corresponds to iOS's "UIReturnKeyDone". The title displayed in
339 /// the action button is "Done".
340 Done,
341
342 /// Logical meaning: The user has entered some text that represents a
343 /// destination, e.g., a restaurant name. The "go" button is intended to take
344 /// the user to a part of the app that corresponds to this destination.
345 ///
346 /// Android: Corresponds to Android's "IME_ACTION_GO". The OS displays a
347 /// button that represents taking "the user to the target of the text they
348 /// typed", e.g., a right-facing arrow button.
349 ///
350 /// iOS: Corresponds to iOS's "UIReturnKeyGo". The title displayed in the
351 /// action button is "Go".
352 Go,
353
354 /// Logical meaning: Execute a search query.
355 ///
356 /// Android: Corresponds to Android's "IME_ACTION_SEARCH". The OS displays a
357 /// button that represents a search, e.g., a magnifying glass button.
358 ///
359 /// iOS: Corresponds to iOS's "UIReturnKeySearch". The title displayed in
360 /// the action button is "Search".
361 Search,
362
363 /// Logical meaning: Sends something that the user has composed, e.g., an
364 /// email or a text message.
365 ///
366 /// Android: Corresponds to Android's "IME_ACTION_SEND". The OS displays a
367 /// button that represents sending something, e.g., a paper plane button.
368 ///
369 /// iOS: Corresponds to iOS's "UIReturnKeySend". The title displayed in the
370 /// action button is "Send".
371 Send,
372
373 /// Logical meaning: The user is done with the current input source and wants
374 /// to move to the next one.
375 ///
376 /// Moves the focus to the next focusable item in the same `FocusScope`.
377 ///
378 /// Android: Corresponds to Android's "IME_ACTION_NEXT". The OS displays a
379 /// button that represents moving forward, e.g., a right-facing arrow button.
380 ///
381 /// iOS: Corresponds to iOS's "UIReturnKeyNext". The title displayed in the
382 /// action button is "Next".
383 Next,
384
385 /// Logical meaning: The user wishes to return to the previous input source
386 /// in the group, e.g., a form with multiple `TextField`s.
387 ///
388 /// Moves the focus to the previous focusable item in the same `FocusScope`.
389 ///
390 /// Android: Corresponds to Android's "IME_ACTION_PREVIOUS". The OS displays a
391 /// button that represents moving backward, e.g., a left-facing arrow button.
392 ///
393 /// iOS: iOS does not have a keyboard return type of "previous." It is
394 /// inappropriate to choose this [`TextInputAction`] when running on iOS.
395 Previous,
396
397 /// Logical meaning: In iOS apps, it is common for a "Back" button and
398 /// "Continue" button to appear at the top of the screen. However, when the
399 /// keyboard is open, these buttons are often hidden off-screen. Therefore,
400 /// the purpose of the "Continue" return key on iOS is to make the "Continue"
401 /// button available when the user is entering text.
402 ///
403 /// Historical context aside, [`ContinueAction`](TextInputAction::ContinueAction) can be used any
404 /// time that the term "Continue" seems most appropriate for the given action.
405 ///
406 /// Android: Android does not have an IME input type of "continue." It is
407 /// inappropriate to choose this [`TextInputAction`] when running on Android.
408 ///
409 /// iOS: Corresponds to iOS's "UIReturnKeyContinue". The title displayed in the
410 /// action button is "Continue". This action is only available on iOS 9.0+.
411 ///
412 /// The reason that this value has "Action" post-fixed to it is because
413 /// "continue" is a reserved word in Dart, as well as many other languages.
414 ContinueAction,
415
416 /// Logical meaning: The user wants to join something, e.g., a wireless
417 /// network.
418 ///
419 /// Android: Android does not have an IME input type of "join." It is
420 /// inappropriate to choose this [`TextInputAction`] when running on Android.
421 ///
422 /// iOS: Corresponds to iOS's "UIReturnKeyJoin". The title displayed in the
423 /// action button is "Join".
424 Join,
425
426 /// Logical meaning: The user wants routing options, e.g., driving directions.
427 ///
428 /// Android: Android does not have an IME input type of "route." It is
429 /// inappropriate to choose this [`TextInputAction`] when running on Android.
430 ///
431 /// iOS: Corresponds to iOS's "UIReturnKeyRoute". The title displayed in the
432 /// action button is "Route".
433 Route,
434
435 /// Logical meaning: Initiate a call to emergency services.
436 ///
437 /// Android: Android does not have an IME input type of "emergencyCall." It is
438 /// inappropriate to choose this [`TextInputAction`] when running on Android.
439 ///
440 /// iOS: Corresponds to iOS's "UIReturnKeyEmergencyCall". The title displayed
441 /// in the action button is "Emergency Call".
442 EmergencyCall,
443
444 /// Logical meaning: Insert a newline character in the focused text input,
445 /// e.g., `TextField`.
446 ///
447 /// Android: Corresponds to Android's "IME_ACTION_NONE". The OS displays a
448 /// button that represents a new line, e.g., a carriage return button.
449 ///
450 /// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in
451 /// the action button is "return".
452 ///
453 /// The term [`Newline`](TextInputAction::Newline) exists in Flutter but not in Android
454 /// or iOS. The reason for introducing this term is so that developers can
455 /// achieve the common result of inserting new lines without needing to
456 /// understand the various IME actions on Android and return keys on iOS.
457 /// Thus, [`Newline`](TextInputAction::Newline) is a convenience term that alleviates the
458 /// need to understand the underlying platforms to achieve this common behavior.
459 Newline,
460}
461
462/// Configures how the platform keyboard will select an uppercase or
463/// lowercase keyboard.
464///
465/// Only supports text keyboards, other keyboard types will ignore this
466/// configuration. Capitalization is locale-aware.
467#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
468pub enum TextCapitalization {
469 /// Defaults to an uppercase keyboard for the first letter of each word.
470 ///
471 /// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_WORDS` on Android, and
472 /// `UITextAutocapitalizationTypeWords` on iOS.
473 Words,
474
475 /// Defaults to an uppercase keyboard for the first letter of each sentence.
476 ///
477 /// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_SENTENCES` on Android, and
478 /// `UITextAutocapitalizationTypeSentences` on iOS.
479 Sentences,
480
481 /// Defaults to an uppercase keyboard for each character.
482 ///
483 /// Corresponds to `InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS` on Android, and
484 /// `UITextAutocapitalizationTypeAllCharacters` on iOS.
485 Characters,
486
487 /// Defaults to a lowercase keyboard.
488 None,
489}
490
491/// A collection of autofill related information that represents an `AutofillClient`.
492///
493/// Typically used in [`TextInputConfiguration::autofill_configuration`].
494///
495/// Lives here with [`TextInputConfiguration`] because [`crate::View`] names that
496/// type. Flutter's file is `services/autofill.dart`.
497#[derive(Clone, Debug, PartialEq, Eq, Hash)]
498pub struct AutofillConfiguration {
499 /// Whether autofill should be enabled for the `AutofillClient`.
500 ///
501 /// To retrieve a disabled [`AutofillConfiguration`], use [`DISABLED`](Self::DISABLED).
502 pub enabled: bool,
503 /// A string that uniquely identifies the current `AutofillClient`.
504 ///
505 /// The identifier needs to be unique within the `AutofillScope` for the
506 /// `AutofillClient` to receive the correct autofill value.
507 pub unique_identifier: String,
508 /// A list of strings that helps the autofill service identify the type of the
509 /// `AutofillClient`.
510 ///
511 /// See `AutofillHints` (`services/autofill.dart`).
512 pub autofill_hints: Vec<String>,
513 /// The current [`TextEditingValue`] of the `AutofillClient`.
514 pub current_editing_value: TextEditingValue,
515 /// The optional hint text placed on the view that typically suggests what
516 /// sort of input the field accepts, for example "enter your password here".
517 ///
518 /// If the developer does not specify any [`autofill_hints`](Self::autofill_hints), the
519 /// [`hint_text`](Self::hint_text) can be a useful indication to the platform autofill service.
520 pub hint_text: Option<String>,
521}
522
523impl AutofillConfiguration {
524 /// An [`AutofillConfiguration`] that indicates the `AutofillClient` does not
525 /// wish to be autofilled.
526 pub const DISABLED: AutofillConfiguration = AutofillConfiguration {
527 enabled: false,
528 unique_identifier: String::new(),
529 autofill_hints: Vec::new(),
530 current_editing_value: TextEditingValue::EMPTY,
531 hint_text: None,
532 };
533
534 /// Creates autofill related configuration information that can be sent to the
535 /// platform.
536 pub fn new(
537 unique_identifier: impl Into<String>,
538 autofill_hints: Vec<String>,
539 current_editing_value: TextEditingValue,
540 ) -> AutofillConfiguration {
541 AutofillConfiguration {
542 enabled: true,
543 unique_identifier: unique_identifier.into(),
544 autofill_hints,
545 current_editing_value,
546 hint_text: None,
547 }
548 }
549
550 /// Dart `AutofillConfiguration(hintText:)`.
551 pub fn hint_text(mut self, hint_text: impl Into<String>) -> AutofillConfiguration {
552 self.hint_text = Some(hint_text.into());
553 self
554 }
555}
556
557impl fmt::Display for AutofillConfiguration {
558 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
559 write!(
560 f,
561 "AutofillConfiguration(enabled: {}, uniqueIdentifier: {}, autofillHints: {:?}, currentEditingValue: {}",
562 self.enabled, self.unique_identifier, self.autofill_hints, self.current_editing_value
563 )?;
564 if let Some(hint_text) = &self.hint_text {
565 write!(f, ", hintText: {hint_text}")?;
566 }
567 write!(f, ")")
568 }
569}
570
571/// Controls the visual appearance of the text input control.
572///
573/// Many [`TextInputAction`]s are common between Android and iOS. However, if an
574/// [`input_action`](Self::input_action) is provided that is not supported by the current
575/// platform in debug mode, an error will be thrown when the corresponding
576/// text input is attached. For example, providing iOS's "emergencyCall"
577/// action when running on an Android device will result in an error when in
578/// debug mode. In release mode, incompatible [`TextInputAction`]s are replaced
579/// either with "unspecified" on Android, or "default" on iOS. Appropriate
580/// [`input_action`](Self::input_action)s can be chosen by checking the current platform and then
581/// selecting the appropriate action.
582///
583/// See also:
584///
585/// * `TextInput.attach`
586/// * [`TextInputAction`]
587#[derive(Clone, Debug, PartialEq)]
588pub struct TextInputConfiguration {
589 /// The ID of the view that the text input belongs to.
590 pub view_id: Option<i32>,
591 /// The type of information for which to optimize the text input control.
592 pub input_type: TextInputType,
593 /// Whether the text field can be edited or not.
594 ///
595 /// Defaults to false.
596 pub read_only: bool,
597 /// Whether to hide the text being edited (e.g., for passwords).
598 ///
599 /// Defaults to false.
600 pub obscure_text: bool,
601 /// Whether to enable autocorrection.
602 ///
603 /// Defaults to true.
604 pub autocorrect: bool,
605 /// Whether to allow the platform to automatically format dashes.
606 pub smart_dashes_type: SmartDashesType,
607 /// Whether to allow the platform to automatically format quotes.
608 pub smart_quotes_type: SmartQuotesType,
609 /// Whether to show input suggestions as the user types.
610 ///
611 /// Defaults to true.
612 pub enable_suggestions: bool,
613 /// Whether a user can change its selection.
614 ///
615 /// Defaults to true.
616 pub enable_interactive_selection: bool,
617 /// What text to display in the text input control's action button.
618 pub action_label: Option<String>,
619 /// What kind of action to request for the action button on the IME.
620 pub input_action: TextInputAction,
621 /// Specifies how platforms may automatically capitalize text entered by the
622 /// user.
623 ///
624 /// Defaults to [`TextCapitalization::None`].
625 pub text_capitalization: TextCapitalization,
626 /// The appearance of the keyboard.
627 ///
628 /// This setting is only honored on iOS devices.
629 ///
630 /// Defaults to [`Brightness::Light`].
631 pub keyboard_appearance: Brightness,
632 /// The configuration to use for autofill.
633 pub autofill_configuration: AutofillConfiguration,
634 /// Whether to enable that the IME update personalized data such as typing
635 /// history and user dictionary data.
636 ///
637 /// Defaults to true.
638 pub enable_ime_personalized_learning: bool,
639 /// MIME types the field accepts for content insertion.
640 pub allowed_mime_types: Vec<String>,
641 /// Whether to enable that the engine sends text input updates to the
642 /// framework as `TextEditingDelta`s or as one [`TextEditingValue`].
643 ///
644 /// Defaults to false.
645 pub enable_delta_model: bool,
646 /// List of the languages that the user is expected to use.
647 ///
648 /// Pass an empty list to express the intention that a specific hint should not be set.
649 pub hint_locales: Vec<Locale>,
650 /// Whether to enable inline predictive text.
651 ///
652 /// This feature is specific to iOS 17 and later. `None` leaves the platform default.
653 pub enable_inline_prediction: Option<bool>,
654}
655
656impl TextInputConfiguration {
657 /// Starts configuration information for a text input control, with Dart's defaults.
658 /// Values left out are filled in by [`TextInputConfigurationBuilder::build`], as Dart's
659 /// constructor fills them.
660 pub fn builder() -> TextInputConfigurationBuilder {
661 TextInputConfigurationBuilder {
662 configuration: TextInputConfiguration {
663 view_id: None,
664 input_type: TextInputType::TEXT,
665 read_only: false,
666 obscure_text: false,
667 autocorrect: true,
668 smart_dashes_type: SmartDashesType::Enabled,
669 smart_quotes_type: SmartQuotesType::Enabled,
670 enable_suggestions: true,
671 enable_interactive_selection: true,
672 action_label: None,
673 input_action: TextInputAction::Done,
674 text_capitalization: TextCapitalization::None,
675 keyboard_appearance: Brightness::Light,
676 autofill_configuration: AutofillConfiguration::DISABLED,
677 enable_ime_personalized_learning: true,
678 allowed_mime_types: Vec::new(),
679 enable_delta_model: false,
680 hint_locales: Vec::new(),
681 enable_inline_prediction: None,
682 },
683 smart_dashes_type: None,
684 smart_quotes_type: None,
685 }
686 }
687
688 /// Dart `copyWith`: a builder holding this configuration's values, for fields to be
689 /// replaced.
690 pub fn copy_with(&self) -> TextInputConfigurationBuilder {
691 TextInputConfigurationBuilder {
692 configuration: self.clone(),
693 smart_dashes_type: Some(self.smart_dashes_type),
694 smart_quotes_type: Some(self.smart_quotes_type),
695 }
696 }
697}
698
699/// `TextInputConfigurationBuilder` collects a [`TextInputConfiguration`]'s values, as Dart's
700/// constructor takes them, and fills in the ones left out when it builds.
701#[derive(Clone, Debug)]
702pub struct TextInputConfigurationBuilder {
703 configuration: TextInputConfiguration,
704 smart_dashes_type: Option<SmartDashesType>,
705 smart_quotes_type: Option<SmartQuotesType>,
706}
707
708impl TextInputConfigurationBuilder {
709 /// Dart `TextInputConfiguration(viewId:)`.
710 pub fn view_id(mut self, view_id: i32) -> TextInputConfigurationBuilder {
711 self.configuration.view_id = Some(view_id);
712 self
713 }
714
715 /// Dart `TextInputConfiguration(inputType:)`.
716 pub fn input_type(mut self, input_type: TextInputType) -> TextInputConfigurationBuilder {
717 self.configuration.input_type = input_type;
718 self
719 }
720
721 /// Dart `TextInputConfiguration(readOnly:)`.
722 pub fn read_only(mut self, read_only: bool) -> TextInputConfigurationBuilder {
723 self.configuration.read_only = read_only;
724 self
725 }
726
727 /// Dart `TextInputConfiguration(obscureText:)`.
728 pub fn obscure_text(mut self, obscure_text: bool) -> TextInputConfigurationBuilder {
729 self.configuration.obscure_text = obscure_text;
730 self
731 }
732
733 /// Dart `TextInputConfiguration(autocorrect:)`.
734 pub fn autocorrect(mut self, autocorrect: bool) -> TextInputConfigurationBuilder {
735 self.configuration.autocorrect = autocorrect;
736 self
737 }
738
739 /// Dart `TextInputConfiguration(smartDashesType:)`.
740 pub fn smart_dashes_type(
741 mut self,
742 smart_dashes_type: SmartDashesType,
743 ) -> TextInputConfigurationBuilder {
744 self.smart_dashes_type = Some(smart_dashes_type);
745 self
746 }
747
748 /// Dart `TextInputConfiguration(smartQuotesType:)`.
749 pub fn smart_quotes_type(
750 mut self,
751 smart_quotes_type: SmartQuotesType,
752 ) -> TextInputConfigurationBuilder {
753 self.smart_quotes_type = Some(smart_quotes_type);
754 self
755 }
756
757 /// Dart `TextInputConfiguration(enableSuggestions:)`.
758 pub fn enable_suggestions(mut self, enable_suggestions: bool) -> TextInputConfigurationBuilder {
759 self.configuration.enable_suggestions = enable_suggestions;
760 self
761 }
762
763 /// Dart `TextInputConfiguration(enableInteractiveSelection:)`.
764 pub fn enable_interactive_selection(
765 mut self,
766 enable_interactive_selection: bool,
767 ) -> TextInputConfigurationBuilder {
768 self.configuration.enable_interactive_selection = enable_interactive_selection;
769 self
770 }
771
772 /// Dart `TextInputConfiguration(actionLabel:)`.
773 pub fn action_label(
774 mut self,
775 action_label: impl Into<String>,
776 ) -> TextInputConfigurationBuilder {
777 self.configuration.action_label = Some(action_label.into());
778 self
779 }
780
781 /// Dart `TextInputConfiguration(inputAction:)`.
782 pub fn input_action(mut self, input_action: TextInputAction) -> TextInputConfigurationBuilder {
783 self.configuration.input_action = input_action;
784 self
785 }
786
787 /// Dart `TextInputConfiguration(keyboardAppearance:)`.
788 pub fn keyboard_appearance(
789 mut self,
790 keyboard_appearance: Brightness,
791 ) -> TextInputConfigurationBuilder {
792 self.configuration.keyboard_appearance = keyboard_appearance;
793 self
794 }
795
796 /// Dart `TextInputConfiguration(textCapitalization:)`.
797 pub fn text_capitalization(
798 mut self,
799 text_capitalization: TextCapitalization,
800 ) -> TextInputConfigurationBuilder {
801 self.configuration.text_capitalization = text_capitalization;
802 self
803 }
804
805 /// Dart `TextInputConfiguration(autofillConfiguration:)`.
806 pub fn autofill_configuration(
807 mut self,
808 autofill_configuration: AutofillConfiguration,
809 ) -> TextInputConfigurationBuilder {
810 self.configuration.autofill_configuration = autofill_configuration;
811 self
812 }
813
814 /// Dart `TextInputConfiguration(enableIMEPersonalizedLearning:)`.
815 pub fn enable_ime_personalized_learning(
816 mut self,
817 enable_ime_personalized_learning: bool,
818 ) -> TextInputConfigurationBuilder {
819 self.configuration.enable_ime_personalized_learning = enable_ime_personalized_learning;
820 self
821 }
822
823 /// Dart `TextInputConfiguration(allowedMimeTypes:)`.
824 pub fn allowed_mime_types(
825 mut self,
826 allowed_mime_types: Vec<String>,
827 ) -> TextInputConfigurationBuilder {
828 self.configuration.allowed_mime_types = allowed_mime_types;
829 self
830 }
831
832 /// Dart `TextInputConfiguration(enableDeltaModel:)`.
833 pub fn enable_delta_model(mut self, enable_delta_model: bool) -> TextInputConfigurationBuilder {
834 self.configuration.enable_delta_model = enable_delta_model;
835 self
836 }
837
838 /// Dart `TextInputConfiguration(hintLocales:)`.
839 pub fn hint_locales(mut self, hint_locales: Vec<Locale>) -> TextInputConfigurationBuilder {
840 self.configuration.hint_locales = hint_locales;
841 self
842 }
843
844 /// Dart `TextInputConfiguration(enableInlinePrediction:)`.
845 pub fn enable_inline_prediction(
846 mut self,
847 enable_inline_prediction: bool,
848 ) -> TextInputConfigurationBuilder {
849 self.configuration.enable_inline_prediction = Some(enable_inline_prediction);
850 self
851 }
852
853 /// `build` makes the configuration, turning smart dashes and quotes off for obscured text
854 /// unless they were given, as Dart's constructor does.
855 pub fn build(self) -> TextInputConfiguration {
856 let mut configuration = self.configuration;
857 let obscure_text = configuration.obscure_text;
858 configuration.smart_dashes_type = self.smart_dashes_type.unwrap_or(if obscure_text {
859 SmartDashesType::Disabled
860 } else {
861 SmartDashesType::Enabled
862 });
863 configuration.smart_quotes_type = self.smart_quotes_type.unwrap_or(if obscure_text {
864 SmartQuotesType::Disabled
865 } else {
866 SmartQuotesType::Enabled
867 });
868 configuration
869 }
870}
871
872impl Default for TextInputConfiguration {
873 fn default() -> TextInputConfiguration {
874 TextInputConfiguration::builder().build()
875 }
876}
877
878impl fmt::Display for TextInputConfiguration {
879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880 let mut parts = vec![
881 format!("inputType: {}", self.input_type),
882 format!("readOnly: {}", self.read_only),
883 format!("obscureText: {}", self.obscure_text),
884 format!("autocorrect: {}", self.autocorrect),
885 format!("smartDashesType: {:?}", self.smart_dashes_type),
886 format!("smartQuotesType: {:?}", self.smart_quotes_type),
887 format!("enableSuggestions: {}", self.enable_suggestions),
888 format!(
889 "enableInteractiveSelection: {}",
890 self.enable_interactive_selection
891 ),
892 format!("inputAction: {:?}", self.input_action),
893 format!("keyboardAppearance: {:?}", self.keyboard_appearance),
894 format!("textCapitalization: {:?}", self.text_capitalization),
895 format!("autofillConfiguration: {}", self.autofill_configuration),
896 format!(
897 "enableIMEPersonalizedLearning: {}",
898 self.enable_ime_personalized_learning
899 ),
900 format!("allowedMimeTypes: {:?}", self.allowed_mime_types),
901 format!("enableDeltaModel: {}", self.enable_delta_model),
902 ];
903 if let Some(view_id) = self.view_id {
904 parts.insert(0, format!("viewId: {view_id}"));
905 }
906 if let Some(action_label) = &self.action_label {
907 parts.insert(
908 parts
909 .iter()
910 .position(|p| p.starts_with("inputAction:"))
911 .unwrap_or(parts.len()),
912 format!("actionLabel: {action_label}"),
913 );
914 }
915 if !self.hint_locales.is_empty() {
916 parts.push(format!("hintLocales: {:?}", self.hint_locales));
917 }
918 if let Some(enable_inline_prediction) = self.enable_inline_prediction {
919 parts.push(format!(
920 "enableInlinePrediction: {enable_inline_prediction}"
921 ));
922 }
923 write!(f, "TextInputConfiguration({})", parts.join(", "))
924 }
925}
926
927/// The state of a "floating cursor" drag on an iOS soft keyboard.
928///
929/// The "floating cursor" cursor-positioning mode is an iOS feature used to
930/// precisely position the caret in some editable text using certain touch
931/// gestures. As an example, when the user long-presses the spacebar on the iOS
932/// virtual keyboard, iOS enters floating cursor mode where the whole keyboard
933/// becomes a trackpad. In this mode, there are two visible cursors. One, the
934/// floating cursor, hovers over the text, following the user's horizontal
935/// movements exactly and snapping to lines vertically. The other, the
936/// placeholder cursor, is a "shadow" that also snaps to the actual location
937/// where the cursor will go horizontally when the user releases the trackpad.
938///
939/// The floating cursor renders over the text field, while the placeholder
940/// cursor is a faint shadow of the cursor rendered in the text field in the
941/// location between characters where the cursor will drop into when released.
942/// The placeholder cursor is a faint vertical bar, while the floating cursor
943/// has the same appearance as a normal cursor (a blue vertical bar).
944///
945/// This feature works out-of-the-box with Flutter. Support is built into
946/// `EditableText`.
947///
948/// See also:
949///
950/// * `EditableText.backgroundCursorColor`, which configures the color of the
951/// placeholder cursor while the floating cursor is being dragged.
952#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
953pub enum FloatingCursorDragState {
954 /// A user has just activated a floating cursor by long pressing on the
955 /// spacebar.
956 Start,
957
958 /// A user is dragging a floating cursor.
959 Update,
960
961 /// A user has lifted their finger off the screen after using a floating
962 /// cursor.
963 End,
964}
965
966/// The current state and position of the floating cursor.
967///
968/// See also:
969///
970/// * [`FloatingCursorDragState`], which explains the floating cursor feature in
971/// detail.
972#[derive(Clone, Copy, Debug, PartialEq)]
973pub struct RawFloatingCursorPoint {
974 /// The raw position of the floating cursor as determined by the iOS sdk.
975 pub offset: Option<Offset>,
976 /// Represents the starting location when initiating a floating cursor via long press.
977 /// This is a tuple where the first item is the local offset and the second item is the new caret position.
978 /// This is only non-null when a floating cursor is started.
979 pub start_location: Option<(Offset, TextPosition)>,
980 /// The state of the floating cursor.
981 pub state: FloatingCursorDragState,
982}
983
984impl RawFloatingCursorPoint {
985 /// Creates information for setting the position and state of a floating
986 /// cursor.
987 ///
988 /// [`state`](Self::state) must not be null and [`offset`](Self::offset) must not be null if the state is
989 /// [`FloatingCursorDragState::Update`].
990 pub fn new(state: FloatingCursorDragState) -> RawFloatingCursorPoint {
991 let point = RawFloatingCursorPoint {
992 offset: None,
993 start_location: None,
994 state,
995 };
996 if state == FloatingCursorDragState::Update {
997 point
998 } else {
999 point.assemble()
1000 }
1001 }
1002
1003 /// Dart `RawFloatingCursorPoint(offset:)`.
1004 pub fn offset(mut self, offset: Offset) -> RawFloatingCursorPoint {
1005 self.offset = Some(offset);
1006 self.assemble()
1007 }
1008
1009 /// Dart `RawFloatingCursorPoint(startLocation:)`.
1010 pub fn start_location(
1011 mut self,
1012 start_location: (Offset, TextPosition),
1013 ) -> RawFloatingCursorPoint {
1014 self.start_location = Some(start_location);
1015 self
1016 }
1017
1018 fn assemble(self) -> RawFloatingCursorPoint {
1019 debug_assert!(
1020 self.state != FloatingCursorDragState::Update || self.offset.is_some(),
1021 "offset must not be null if the state is Update"
1022 );
1023 self
1024 }
1025}
1026
1027/// The current text, selection, and composing state for editing a run of text.
1028#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1029pub struct TextEditingValue {
1030 /// The current text being edited.
1031 pub text: String,
1032 /// The range of text that is currently selected.
1033 ///
1034 /// When [`selection`](Self::selection) is a [`TextSelection`] that has the same non-negative
1035 /// `baseOffset` and `extentOffset`, the [`selection`](Self::selection) property represents the
1036 /// caret position.
1037 ///
1038 /// If the current [`selection`](Self::selection) has a negative `baseOffset` or `extentOffset`,
1039 /// then the text currently does not have a selection or a caret location, and
1040 /// most text editing operations that rely on the current selection (for
1041 /// instance, insert a character at the caret location) will do nothing.
1042 pub selection: TextSelection,
1043 /// The range of text that is still being composed.
1044 ///
1045 /// Composing regions are created by input methods (IMEs) to indicate the text
1046 /// within a certain range is provisional. For instance, the Android Gboard
1047 /// app's English keyboard puts the current word under the caret into a
1048 /// composing region to indicate the word is subject to autocorrect or
1049 /// prediction changes.
1050 ///
1051 /// Composing regions can also be used for performing multistage input, which
1052 /// is typically used by IMEs designed for phonetic keyboard to enter
1053 /// ideographic symbols. As an example, many CJK keyboards require the user to
1054 /// enter a Latin alphabet sequence and then convert it to CJK characters. On
1055 /// iOS, the default software keyboards do not have a dedicated view to show
1056 /// the unfinished Latin sequence, so it's displayed directly in the text
1057 /// field, inside of a composing region.
1058 ///
1059 /// On iOS 17 and later, the composing region can also be used
1060 /// to display inline text predictions. The user can accept the
1061 /// predicted text by tapping the Space bar.
1062 ///
1063 /// The composing region should typically only be changed by the IME, or the
1064 /// user via interacting with the IME.
1065 ///
1066 /// If the range represented by this property is [`TextRange::EMPTY`], then the
1067 /// text is not currently being composed.
1068 pub composing: TextRange,
1069}
1070
1071impl TextEditingValue {
1072 /// A value that corresponds to the empty string with no selection and no composing range.
1073 pub const EMPTY: TextEditingValue = TextEditingValue {
1074 text: String::new(),
1075 selection: TextSelection::collapsed(-1, TextAffinity::Downstream),
1076 composing: TextRange::EMPTY,
1077 };
1078
1079 /// Creates information for editing a run of text.
1080 ///
1081 /// The selection and composing range must be within the text. This is not
1082 /// checked during construction, and must be guaranteed by the caller.
1083 ///
1084 /// The default value of [`selection`](Self::selection) is `TextSelection::collapsed(-1, …)`.
1085 /// This indicates that there is no selection at all.
1086 pub fn new() -> TextEditingValue {
1087 TextEditingValue::EMPTY
1088 }
1089
1090 /// Dart `TextEditingValue(text:)`.
1091 pub fn text(mut self, text: impl Into<String>) -> TextEditingValue {
1092 self.text = text.into();
1093 self
1094 }
1095
1096 /// Dart `TextEditingValue(selection:)`.
1097 pub fn selection(mut self, selection: TextSelection) -> TextEditingValue {
1098 self.selection = selection;
1099 self
1100 }
1101
1102 /// Dart `TextEditingValue(composing:)`.
1103 pub fn composing(mut self, composing: TextRange) -> TextEditingValue {
1104 self.composing = composing;
1105 self
1106 }
1107
1108 /// Creates a copy of this value but with the given fields replaced with the new values.
1109 pub fn copy_with(&self) -> TextEditingValue {
1110 self.clone()
1111 }
1112
1113 /// Whether the [`composing`](Self::composing) range is a valid range within [`text`](Self::text).
1114 ///
1115 /// Returns true if and only if the [`composing`](Self::composing) range is normalized, its start
1116 /// is greater than or equal to 0, and its end is less than or equal to
1117 /// [`text`](Self::text)'s length.
1118 ///
1119 /// If this property is false while the [`composing`](Self::composing) range's `isValid` is true,
1120 /// it usually indicates the current [`composing`](Self::composing) range is invalid because of a
1121 /// programming error.
1122 pub fn is_composing_range_valid(&self) -> bool {
1123 self.composing.is_valid()
1124 && self.composing.is_normalized()
1125 && self.composing.end <= utf16_len(&self.text)
1126 }
1127
1128 /// Returns a new [`TextEditingValue`], which is this [`TextEditingValue`] with
1129 /// its [`text`](Self::text) partially replaced by the `replacement_string`.
1130 ///
1131 /// The `replacement_range` parameter specifies the range of the
1132 /// [`text`](Self::text) that needs to be replaced.
1133 ///
1134 /// The `replacement_string` parameter specifies the string to replace the
1135 /// given range of text with.
1136 ///
1137 /// This method also adjusts the selection range and the composing range of the
1138 /// resulting [`TextEditingValue`], such that they point to the same substrings
1139 /// as the corresponding ranges in the original [`TextEditingValue`]. For
1140 /// example, if the original [`TextEditingValue`] is "Hello world" with the word
1141 /// "world" selected, replacing "Hello" with a different string using this
1142 /// method will not change the selected word.
1143 ///
1144 /// This method does nothing if the given `replacement_range` is not
1145 /// [`TextRange::is_valid`].
1146 pub fn replaced(
1147 &self,
1148 replacement_range: impl Into<TextRange>,
1149 replacement_string: &str,
1150 ) -> TextEditingValue {
1151 let replacement_range = replacement_range.into();
1152 if !replacement_range.is_valid() {
1153 return self.clone();
1154 }
1155 debug_assert!(replacement_range.is_normalized());
1156 let new_text = format!(
1157 "{}{}{}",
1158 replacement_range.text_before(&self.text),
1159 replacement_string,
1160 replacement_range.text_after(&self.text),
1161 );
1162 if replacement_range.end - replacement_range.start == utf16_len(replacement_string) {
1163 return self.copy_with().text(new_text);
1164 }
1165
1166 let replacement_len = utf16_len(replacement_string);
1167 let adjust_index = |original_index: i32| {
1168 // The length added by adding the replacementString.
1169 let replaced_length = if original_index <= replacement_range.start
1170 && original_index < replacement_range.end
1171 {
1172 0
1173 } else {
1174 replacement_len
1175 };
1176 // The length removed by removing the replacementRange.
1177 let removed_length = original_index
1178 .clamp(replacement_range.start, replacement_range.end)
1179 - replacement_range.start;
1180 original_index + replaced_length - removed_length
1181 };
1182
1183 let adjusted_selection = TextSelection::new(
1184 adjust_index(self.selection.base_offset),
1185 adjust_index(self.selection.extent_offset),
1186 );
1187 let adjusted_composing = TextRange::new(
1188 adjust_index(self.composing.start),
1189 adjust_index(self.composing.end),
1190 );
1191 debug_assert!(text_range_is_valid(adjusted_selection.range(), &new_text));
1192 debug_assert!(text_range_is_valid(adjusted_composing, &new_text));
1193 TextEditingValue::new()
1194 .text(new_text)
1195 .selection(adjusted_selection)
1196 .composing(adjusted_composing)
1197 }
1198}
1199
1200impl Default for TextEditingValue {
1201 fn default() -> TextEditingValue {
1202 TextEditingValue::new()
1203 }
1204}
1205
1206impl fmt::Display for TextEditingValue {
1207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1208 write!(
1209 f,
1210 "TextEditingValue(text: \u{2524}{}\u{251C}, selection: {}, composing: {:?})",
1211 self.text, self.selection, self.composing
1212 )
1213 }
1214}
1215
1216/// Dart `String.length`: UTF-16 code units.
1217fn utf16_len(text: &str) -> i32 {
1218 text.encode_utf16().count() as i32
1219}
1220
1221/// Verify that the given range is within the text.
1222///
1223/// The verification can't be perform during the constructor of
1224/// [`TextEditingValue`], which are `const` and are allowed to retrieve
1225/// properties of [`TextRange`]s. [`TextEditingValue`] should perform this
1226/// wherever it is building other values (such as toJson) or is built in a
1227/// non-const way (such as fromJson).
1228fn text_range_is_valid(range: TextRange, text: &str) -> bool {
1229 if range.start == -1 && range.end == -1 {
1230 return true;
1231 }
1232 let len = utf16_len(text);
1233 debug_assert!(
1234 range.start >= 0 && range.start <= len,
1235 "Range start {} is out of text of length {len}",
1236 range.start
1237 );
1238 debug_assert!(
1239 range.end >= 0 && range.end <= len,
1240 "Range end {} is out of text of length {len}",
1241 range.end
1242 );
1243 true
1244}
1245
1246/// Represents a selection rect for a character and it's position in the text.
1247///
1248/// This is used to report the current text selection rect and position data
1249/// to the engine for Scribble support on iPadOS 14.
1250#[derive(Clone, Copy, Debug, PartialEq)]
1251pub struct SelectionRect {
1252 /// The position of this selection rect within the text String.
1253 pub position: i32,
1254 /// The rectangle representing the bounds of this selection rect within the
1255 /// currently focused `RenderEditable`'s coordinate space.
1256 pub bounds: Rect,
1257 /// The direction text flows within this selection rect.
1258 pub direction: TextDirection,
1259}
1260
1261impl SelectionRect {
1262 /// Constructor for creating a [`SelectionRect`] from a text `position` and
1263 /// `bounds`.
1264 pub const fn new(position: i32, bounds: Rect, direction: TextDirection) -> SelectionRect {
1265 SelectionRect {
1266 position,
1267 bounds,
1268 direction,
1269 }
1270 }
1271}
1272
1273impl std::fmt::Display for SelectionRect {
1274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1275 write!(f, "SelectionRect({}, {:?})", self.position, self.bounds)
1276 }
1277}
1278
1279#[cfg(test)]
1280mod tests {
1281 use super::*;
1282
1283 const TEST_TEXT: &str = "From a false proposition, anything follows.";
1284
1285 #[test]
1286 fn replaced_deletes_a_selection() {
1287 let selection = TextSelection::new(5, 13);
1288 assert_eq!(
1289 TextEditingValue::new()
1290 .text(TEST_TEXT)
1291 .selection(selection)
1292 .replaced(selection, ""),
1293 TextEditingValue::new()
1294 .text("From proposition, anything follows.")
1295 .selection(TextSelection::collapsed(5, TextAffinity::Downstream))
1296 );
1297 }
1298
1299 #[test]
1300 fn replaced_deletes_a_reversed_selection() {
1301 let selection = TextSelection::new(13, 5);
1302 assert_eq!(
1303 TextEditingValue::new()
1304 .text(TEST_TEXT)
1305 .selection(selection)
1306 .replaced(selection, ""),
1307 TextEditingValue::new()
1308 .text("From proposition, anything follows.")
1309 .selection(TextSelection::collapsed(5, TextAffinity::Downstream))
1310 );
1311 }
1312
1313 #[test]
1314 fn replaced_inserts_at_the_caret() {
1315 let selection = TextSelection::collapsed(5, TextAffinity::Downstream);
1316 assert_eq!(
1317 TextEditingValue::new()
1318 .text(TEST_TEXT)
1319 .selection(selection)
1320 .replaced(selection, "AA"),
1321 TextEditingValue::new()
1322 .text("From AAa false proposition, anything follows.")
1323 .selection(TextSelection::collapsed(7, TextAffinity::Downstream))
1324 );
1325 }
1326
1327 #[test]
1328 fn replaced_before_selection_shifts_the_range() {
1329 let selection = TextSelection::new(13, 5);
1330 assert_eq!(
1331 TextEditingValue::new()
1332 .text(TEST_TEXT)
1333 .selection(selection)
1334 .replaced(TextRange::new(4, 5), "AA"),
1335 TextEditingValue::new()
1336 .text("FromAAa false proposition, anything follows.")
1337 .selection(TextSelection::new(14, 6))
1338 );
1339 }
1340
1341 #[test]
1342 fn replaced_after_selection_leaves_the_range() {
1343 let selection = TextSelection::new(13, 5);
1344 assert_eq!(
1345 TextEditingValue::new()
1346 .text(TEST_TEXT)
1347 .selection(selection)
1348 .replaced(TextRange::new(13, 14), "AA"),
1349 TextEditingValue::new()
1350 .text("From a false AAroposition, anything follows.")
1351 .selection(selection)
1352 );
1353 }
1354
1355 #[test]
1356 fn replaced_inside_selection_start_boundary() {
1357 let selection = TextSelection::new(13, 5);
1358 assert_eq!(
1359 TextEditingValue::new()
1360 .text(TEST_TEXT)
1361 .selection(selection)
1362 .replaced(TextRange::new(5, 6), "AA"),
1363 TextEditingValue::new()
1364 .text("From AA false proposition, anything follows.")
1365 .selection(TextSelection::new(14, 5))
1366 );
1367 }
1368
1369 #[test]
1370 fn replaced_inside_selection_end_boundary() {
1371 let selection = TextSelection::new(13, 5);
1372 assert_eq!(
1373 TextEditingValue::new()
1374 .text(TEST_TEXT)
1375 .selection(selection)
1376 .replaced(TextRange::new(12, 13), "AA"),
1377 TextEditingValue::new()
1378 .text("From a falseAAproposition, anything follows.")
1379 .selection(TextSelection::new(14, 5))
1380 );
1381 }
1382
1383 #[test]
1384 fn replaced_deletes_after_selection() {
1385 let selection = TextSelection::new(13, 5);
1386 assert_eq!(
1387 TextEditingValue::new()
1388 .text(TEST_TEXT)
1389 .selection(selection)
1390 .replaced(TextRange::new(13, 14), ""),
1391 TextEditingValue::new()
1392 .text("From a false roposition, anything follows.")
1393 .selection(selection)
1394 );
1395 }
1396
1397 #[test]
1398 fn replaced_deletes_inside_selection_start_boundary() {
1399 let selection = TextSelection::new(13, 5);
1400 assert_eq!(
1401 TextEditingValue::new()
1402 .text(TEST_TEXT)
1403 .selection(selection)
1404 .replaced(TextRange::new(5, 6), ""),
1405 TextEditingValue::new()
1406 .text("From false proposition, anything follows.")
1407 .selection(TextSelection::new(12, 5))
1408 );
1409 }
1410
1411 #[test]
1412 fn replaced_deletes_inside_selection_end_boundary() {
1413 let selection = TextSelection::new(13, 5);
1414 assert_eq!(
1415 TextEditingValue::new()
1416 .text(TEST_TEXT)
1417 .selection(selection)
1418 .replaced(TextRange::new(12, 13), ""),
1419 TextEditingValue::new()
1420 .text("From a falseproposition, anything follows.")
1421 .selection(TextSelection::new(12, 5))
1422 );
1423 }
1424
1425 #[test]
1426 fn empty_prints_like_dart() {
1427 assert_eq!(
1428 TextEditingValue::EMPTY.to_string(),
1429 format!(
1430 "TextEditingValue(text: \u{2524}\u{251C}, selection: {}, composing: {:?})",
1431 TextSelection::collapsed(-1, TextAffinity::Downstream),
1432 TextRange::EMPTY
1433 )
1434 );
1435 }
1436
1437 #[test]
1438 fn number_with_options_defaults_match_dart() {
1439 assert_eq!(TextInputType::NUMBER.signed, Some(false));
1440 assert_eq!(
1441 TextInputType::number_with_options()
1442 .signed(true)
1443 .decimal(true),
1444 TextInputType {
1445 index: 2,
1446 signed: Some(true),
1447 decimal: Some(true),
1448 password: Some(false),
1449 }
1450 );
1451 }
1452
1453 #[test]
1454 fn obscure_text_disables_smart_punctuation_unless_overridden() {
1455 let obscured = TextInputConfiguration::builder().obscure_text(true).build();
1456 assert!(obscured.obscure_text);
1457 assert_eq!(obscured.smart_dashes_type, SmartDashesType::Disabled);
1458 assert_eq!(obscured.smart_quotes_type, SmartQuotesType::Disabled);
1459
1460 let given_first = TextInputConfiguration::builder()
1461 .smart_dashes_type(SmartDashesType::Enabled)
1462 .obscure_text(true)
1463 .build();
1464 assert_eq!(given_first.smart_dashes_type, SmartDashesType::Enabled);
1465 }
1466
1467 #[test]
1468 fn a_copy_keeps_the_smart_punctuation_it_was_made_with() {
1469 let copy = TextInputConfiguration::default()
1470 .copy_with()
1471 .obscure_text(true)
1472 .build();
1473 assert_eq!(copy.smart_dashes_type, SmartDashesType::Enabled);
1474 assert_eq!(copy.smart_quotes_type, SmartQuotesType::Enabled);
1475 }
1476
1477 #[test]
1478 fn autofill_disabled_is_the_configuration_default() {
1479 let configuration = TextInputConfiguration::default();
1480 assert!(!configuration.autofill_configuration.enabled);
1481 assert_eq!(
1482 AutofillConfiguration::new("id", vec!["email".into()], TextEditingValue::EMPTY)
1483 .hint_text("email")
1484 .hint_text,
1485 Some("email".into())
1486 );
1487 }
1488}