use std::any::{Any, TypeId};
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::marker::PhantomData;
use std::rc::Rc;
use std::time::Duration;
use waft_animation::{AnimationBehavior, AnimationController, Curve, Curves};
use waft_embedder::{
AutofillConfiguration, BoxHeightStyle, BoxWidthStyle, Brightness, Clip, Color, FontWeight,
Locale, Matrix4, Offset, PointerDeviceKind, Radius, Rect, Size, SmartDashesType,
SmartQuotesType, TargetPlatform, TextAffinity, TextAlign, TextBaseline, TextCapitalization,
TextDecoration, TextDirection, TextHeightBehavior, TextInputAction, TextInputConfiguration,
TextInputType, TextPosition, TextRange, TextSelection, ViewId, clamp_double,
};
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, K_IS_WEB, Listenable,
ListenableHandle, ListenableObject, Listener, OptionRetained, Retained, Task, Timer,
ValueListenable, ValueListenableHandle, ValueNotifier,
};
use waft_gestures::{DragStartBehavior, PointerDownEvent, PointerUpEvent};
use waft_painting::{
AxisDirection, EdgeInsets, InlineSpanRef, RenderComparison, StrutStyle, TextScaler, TextSpan,
TextStyle, TextWidthBasis,
};
use waft_physics::{Simulation, Tolerance};
use waft_rendering::{
AnyLayer, AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, CompositionCallback,
HitTestBehavior, LayerLink, LineBoundary, PaintingContext, RenderBox, RenderBoxData,
RenderEditable, RenderHandle, RenderObject, RenderObjectData, RenderObjectWithChildData,
RenderObjectWithChildMixin, RenderProxyBoxMixin, RenderProxyBoxWithHitTestBehavior,
RevealedOffset, ScrollDirection, VerticalCaretMovementRun, ViewportOffsetRef,
};
use waft_scheduler::{
FrameCallback, SchedulerBinding, Ticker, TickerCallback, TickerProviderObject,
};
use waft_services::{
AnyAutofillClient, AnyTextSelectionDelegate, AutofillClient, AutofillHints, CharacterBoundary,
Clipboard, ClipboardData, DefaultProcessTextService, DocumentBoundary,
FilteringTextInputFormatter, KeyboardInsertedContent, LiveText, MouseCursorRef,
ParagraphBoundary, ProcessTextAction, ProcessTextService, SelectionChangedCause, SelectionRect,
SpellCheckResults, SuggestionSpan, SystemMouseCursors, TextBoundary, TextEditingValue,
TextInput, TextInputClient, TextInputConnection, TextInputFormatter, TextInputFormatterRef,
TextInputStyle, TextSelectionDelegate,
};
use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
use crate::framework::{
BuildContext, GlobalKey, IntoWidget, KeyRef, MultiChildRenderObjectWidget, RenderObjectWidget,
SingleChildRenderObjectWidget, State, StateData, StatefulWidget, WidgetRef,
};
use crate::state_accessors;
use crate::view::View;
use crate::widgets::actions::{
Action, ActionData, ActionRef, Actions, AnyAction, CallbackAction, ContextAction,
DismissIntent, DoNothingAction, Intent, OnInvokeCallback,
};
use crate::widgets::app_lifecycle_listener::AppLifecycleListener;
use crate::widgets::autofill::{AutofillGroup, AutofillGroupState};
use crate::widgets::automatic_keep_alive::{
AutomaticKeepAliveClientMixin, AutomaticKeepAliveClientMixinData,
};
use crate::widgets::basic::CompositedTransformTarget;
use crate::widgets::basic::WidgetBuilder;
use crate::widgets::basic::{Builder, Directionality, MouseRegion};
use crate::widgets::constants::K_MIN_INTERACTIVE_DIMENSION;
use crate::widgets::context_menu_button_item::{ContextMenuButtonItem, ContextMenuButtonType};
use crate::widgets::default_text_editing_shortcuts::intent_for_macos_selector;
use crate::widgets::focus_manager::{FocusManager, FocusNodeRef, UnfocusDisposition};
use crate::widgets::focus_scope::{Focus, FocusScope};
use crate::widgets::focus_traversal::{DirectionalFocusAction, DirectionalFocusIntent};
use crate::widgets::magnifier::TextMagnifierConfiguration;
use crate::widgets::media_query::{MediaQuery, Orientation};
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
use crate::widgets::scroll_controller::{
ScrollController, ScrollControllerLeaf, ScrollControllerRef,
};
use crate::widgets::scroll_notification::ScrollNotification;
use crate::widgets::scroll_physics::{ScrollPhysics, ScrollPhysicsBase, ScrollPhysicsRef};
use crate::widgets::scrollable::{Scrollable, ScrollableState, ViewportBuilder};
use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
use crate::widgets::spell_check::{
SpellCheckConfiguration, build_text_span_with_spell_check_suggestions,
};
use crate::widgets::tap_region::{TapRegionGroupId, TextFieldTapRegion};
use crate::widgets::text::{DefaultTextHeightBehavior, apply_text_spacing_overrides};
use crate::widgets::text_editing_intents::{
CopySelectionTextIntent, DeleteCharacterIntent, DeleteToLineBreakIntent,
DeleteToNextWordBoundaryIntent, DirectionalCaretMovementIntent, DirectionalTextEditingIntent,
DoNothingAndStopPropagationTextIntent, EditableTextTapOutsideIntent,
EditableTextTapUpOutsideIntent, ExpandSelectionToDocumentBoundaryIntent,
ExpandSelectionToLineBreakIntent, ExtendSelectionByCharacterIntent,
ExtendSelectionToDocumentBoundaryIntent, ExtendSelectionToLineBreakIntent,
ExtendSelectionToNextParagraphBoundaryIntent,
ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent,
ExtendSelectionToNextWordBoundaryIntent,
ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
ExtendSelectionVerticallyToAdjacentLineIntent, ExtendSelectionVerticallyToAdjacentPageIntent,
PasteTextIntent, ReplaceTextIntent, ScrollToDocumentBoundaryIntent, SelectAllTextIntent,
TransposeCharactersIntent, UpdateSelectionIntent,
};
use crate::widgets::text_selection::{
ClipboardStatus, ClipboardStatusNotifier, LiveTextInputStatus, LiveTextInputStatusNotifier,
TextSelectionControls, TextSelectionHandleType, TextSelectionOverlay,
};
use crate::widgets::text_selection_toolbar_anchors::TextSelectionToolbarAnchors;
use crate::widgets::ticker_provider::{
TickerMode, TickerProviderStateMixin, TickerProviderStateMixinData,
};
use crate::widgets::undo_history::{UndoHistory, UndoHistoryController};
use crate::widgets::widget_span::WidgetSpan;
use waft_foundation::Ref;
#[derive(Debug)]
pub struct TextEditingControllerData {
value: TextEditingValue,
}
impl TextEditingControllerData {
pub fn new(value: TextEditingValue) -> TextEditingControllerData {
TextEditingControllerData { value }
}
}
#[macro_export]
macro_rules! text_editing_controller_accessors {
() => {
fn text_editing_controller_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::TextEditingControllerData {
&app.get(self).text_editing_controller
}
fn text_editing_controller_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::TextEditingControllerData {
&mut app.get_mut(self).text_editing_controller
}
};
}
pub trait TextEditingControllerLeaf: ChangeNotifier + Sized + 'static {
fn text_editing_controller_data(self: Handle<Self>, app: &App) -> &TextEditingControllerData;
fn text_editing_controller_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TextEditingControllerData;
fn build_text_span(
self: Handle<Self>,
app: &App,
context: BuildContext,
style: Option<TextStyle>,
with_composing: bool,
) -> TextSpan {
TextEditingController::build_text_span(
self.as_controller(),
app,
context,
style,
with_composing,
)
}
fn text_value(self: Handle<Self>, app: &App) -> &str {
&self.text_editing_controller_data(app).value.text
}
fn set_text(self: Handle<Self>, app: &mut App, new_text: impl Into<String>) {
self.as_controller().set_text(app, new_text);
}
fn value(self: Handle<Self>, app: &App) -> &TextEditingValue {
&self.text_editing_controller_data(app).value
}
fn set_value(self: Handle<Self>, app: &mut App, new_value: TextEditingValue) {
self.as_controller().set_value(app, new_value);
}
fn selection(self: Handle<Self>, app: &App) -> TextSelection {
self.as_controller().selection(app)
}
fn set_selection(self: Handle<Self>, app: &mut App, new_selection: TextSelection) {
self.as_controller().set_selection(app, new_selection);
}
fn clear(self: Handle<Self>, app: &mut App) {
self.as_controller().clear(app);
}
fn clear_composing(self: Handle<Self>, app: &mut App) {
self.as_controller().clear_composing(app);
}
fn as_controller(self: Handle<Self>) -> AnyTextEditingController {
AnyTextEditingController {
id: self.id(),
vtable: const { &TextEditingControllerVTable::of::<Self>() },
}
}
}
pub struct TextEditingController {
change_notifier: ChangeNotifierData,
text_editing_controller: TextEditingControllerData,
}
impl Debug for TextEditingController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TextEditingController")
.field("value", &self.text_editing_controller.value)
.finish()
}
}
impl TextEditingController {
pub fn new(app: &mut App) -> Ref<TextEditingController> {
TextEditingController::from_value(app, None)
}
pub fn text(self: Ref<Self>, app: &mut App, text: impl Into<String>) -> Ref<Self> {
app.get_mut(&self).text_editing_controller.value = TextEditingValue::new().text(text);
self
}
pub fn from_value(
app: &mut App,
value: Option<TextEditingValue>,
) -> Ref<TextEditingController> {
let value = value.unwrap_or(TextEditingValue::EMPTY);
debug_assert!(
!value.composing.is_valid() || value.is_composing_range_valid(),
"New TextEditingValue {value:?} has an invalid non-empty composing range \
{:?}. It is recommended to use a valid composing range, \
even for readonly text fields.",
value.composing
);
app.create(TextEditingController {
change_notifier: ChangeNotifierData::new(),
text_editing_controller: TextEditingControllerData::new(value),
})
}
pub fn build_text_span(
controller: AnyTextEditingController,
app: &App,
_context: BuildContext,
style: Option<TextStyle>,
with_composing: bool,
) -> TextSpan {
let value = controller.value(app).clone();
debug_assert!(
!value.composing.is_valid() || !with_composing || value.is_composing_range_valid()
);
let composing_region_out_of_range = !value.is_composing_range_valid() || !with_composing;
if composing_region_out_of_range {
return match style {
Some(style) => TextSpan::new().style(style).text(value.text),
None => TextSpan::new().text(value.text),
};
}
let composing_style = style
.as_ref()
.map(|s| {
s.merge(Some(
&TextStyle::new().decoration(TextDecoration::UNDERLINE),
))
})
.unwrap_or_else(|| TextStyle::new().decoration(TextDecoration::UNDERLINE));
let mut span = TextSpan::new();
if let Some(style) = style {
span = span.style(style);
}
span.children(vec![
TextSpan::new()
.text(value.composing.text_before(&value.text))
.into_span(),
TextSpan::new()
.style(composing_style)
.text(value.composing.text_inside(&value.text))
.into_span(),
TextSpan::new()
.text(value.composing.text_after(&value.text))
.into_span(),
])
}
}
impl TextEditingController {
pub fn dispose(self: Handle<Self>, app: &mut App) {
ChangeNotifierData::dispose(app, self);
}
}
impl ChangeNotifier for TextEditingController {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl TextEditingControllerLeaf for TextEditingController {
crate::text_editing_controller_accessors!();
}
type BuildTextSpanFn = fn(&App, HandleId, BuildContext, Option<TextStyle>, bool) -> TextSpan;
struct TextEditingControllerVTable {
type_name: fn() -> &'static str,
add_listener: fn(&mut App, HandleId, Listener),
remove_listener: fn(&mut App, HandleId, &Listener),
notify_listeners: fn(&mut App, HandleId),
dispose_change_notifier: fn(&mut App, HandleId),
data: fn(&App, HandleId) -> &TextEditingControllerData,
data_mut: fn(&mut App, HandleId) -> &mut TextEditingControllerData,
build_text_span: BuildTextSpanFn,
}
impl TextEditingControllerVTable {
const fn of<C: TextEditingControllerLeaf>() -> TextEditingControllerVTable {
TextEditingControllerVTable {
type_name: std::any::type_name::<C>,
add_listener: |app, id, listener| {
ListenableObject::add_listener(Handle::<C>::from_id(id), app, listener);
},
remove_listener: |app, id, listener| {
ListenableObject::remove_listener(Handle::<C>::from_id(id), app, listener);
},
notify_listeners: |app, id| Handle::<C>::from_id(id).notify_listeners(app),
dispose_change_notifier: |app, id| {
ChangeNotifierData::dispose(app, Handle::<C>::from_id(id));
},
data: |app, id| C::text_editing_controller_data(Handle::from_id(id), app),
data_mut: |app, id| C::text_editing_controller_data_mut(Handle::from_id(id), app),
build_text_span: |app, id, context, style, with_composing| {
C::build_text_span(Handle::from_id(id), app, context, style, with_composing)
},
}
}
}
#[derive(Clone, Copy)]
pub struct AnyTextEditingController {
id: HandleId,
vtable: &'static TextEditingControllerVTable,
}
pub type TextEditingControllerRef = Retained<AnyTextEditingController>;
waft_foundation::erased_handle!(AnyTextEditingController: TextEditingControllerLeaf => TextEditingControllerLeaf::as_controller);
impl AnyTextEditingController {
fn data(self, app: &App) -> &TextEditingControllerData {
(self.vtable.data)(app, self.id)
}
fn data_mut(self, app: &mut App) -> &mut TextEditingControllerData {
(self.vtable.data_mut)(app, self.id)
}
pub fn text_value(self, app: &App) -> &str {
&self.data(app).value.text
}
pub fn set_text(self, app: &mut App, new_text: impl Into<String>) {
let value = self
.value(app)
.clone()
.copy_with()
.text(new_text)
.selection(TextSelection::collapsed(-1, TextAffinity::Downstream))
.composing(TextRange::EMPTY);
self.set_value(app, value);
}
pub fn value(self, app: &App) -> &TextEditingValue {
&self.data(app).value
}
pub fn set_value(self, app: &mut App, new_value: TextEditingValue) {
debug_assert!(
!new_value.composing.is_valid() || new_value.is_composing_range_valid(),
"New TextEditingValue {new_value:?} has an invalid non-empty composing range \
{:?}. It is recommended to use a valid composing range, \
even for readonly text fields.",
new_value.composing
);
if self.data(app).value == new_value {
return;
}
self.data_mut(app).value = new_value;
(self.vtable.notify_listeners)(app, self.id);
}
pub fn build_text_span(
self,
app: &App,
context: BuildContext,
style: Option<TextStyle>,
with_composing: bool,
) -> TextSpan {
(self.vtable.build_text_span)(app, self.id, context, style, with_composing)
}
pub fn selection(self, app: &App) -> TextSelection {
self.data(app).value.selection
}
pub fn set_selection(self, app: &mut App, new_selection: TextSelection) {
let text_len = utf16_len(self.text_value(app));
if text_len < new_selection.end() || text_len < new_selection.start() {
panic!("invalid text selection: {new_selection:?}");
}
let value = self.value(app).clone();
let new_composing = if is_selection_within_composing_range(&value, new_selection) {
value.composing
} else {
TextRange::EMPTY
};
self.set_value(
app,
value
.copy_with()
.selection(new_selection)
.composing(new_composing),
);
}
pub fn clear(self, app: &mut App) {
self.set_value(
app,
TextEditingValue::new()
.selection(TextSelection::collapsed(0, TextAffinity::Downstream)),
);
}
pub fn clear_composing(self, app: &mut App) {
let value = self.value(app).clone();
self.set_value(app, value.copy_with().composing(TextRange::EMPTY));
}
pub fn dispose(self, app: &mut App) {
(self.vtable.dispose_change_notifier)(app, self.id);
}
pub fn describe(self, app: &App) -> String {
let name = (self.vtable.type_name)();
let short = name.rsplit("::").next().unwrap_or(name);
format!("{short}#{:?}({:?})", self.id, self.value(app))
}
}
impl Debug for AnyTextEditingController {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AnyTextEditingController({:?})", self.id)
}
}
impl AnyTextEditingController {
pub fn add_listener(self, app: &mut App, listener: Listener) {
(self.vtable.add_listener)(app, self.id, listener);
}
pub fn remove_listener(self, app: &mut App, listener: &Listener) {
(self.vtable.remove_listener)(app, self.id, listener);
}
}
impl ListenableHandle for AnyTextEditingController {
fn add_listener_to(self, app: &mut App, listener: Listener) {
AnyTextEditingController::add_listener(self, app, listener);
}
fn remove_listener_from(self, app: &mut App, listener: &Listener) {
AnyTextEditingController::remove_listener(self, app, listener);
}
}
impl ValueListenableHandle<TextEditingValue> for AnyTextEditingController {
fn value_of(self, app: &App) -> &TextEditingValue {
&self.data(app).value
}
}
fn is_selection_within_composing_range(value: &TextEditingValue, selection: TextSelection) -> bool {
selection.start() >= value.composing.start && selection.end() <= value.composing.end
}
fn utf16_len(text: &str) -> i32 {
text.encode_utf16().count() as i32
}
fn option_rc_eq<T: ?Sized>(a: &Option<Rc<T>>, b: &Option<Rc<T>>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ToolbarOptions {
pub copy: bool,
pub cut: bool,
pub paste: bool,
pub select_all: bool,
}
impl ToolbarOptions {
pub const fn new() -> ToolbarOptions {
ToolbarOptions {
copy: false,
cut: false,
paste: false,
select_all: false,
}
}
pub const EMPTY: ToolbarOptions = ToolbarOptions::new();
pub const fn copy(mut self, copy: bool) -> ToolbarOptions {
self.copy = copy;
self
}
pub const fn cut(mut self, cut: bool) -> ToolbarOptions {
self.cut = cut;
self
}
pub const fn paste(mut self, paste: bool) -> ToolbarOptions {
self.paste = paste;
self
}
pub const fn select_all(mut self, select_all: bool) -> ToolbarOptions {
self.select_all = select_all;
self
}
}
impl Default for ToolbarOptions {
fn default() -> ToolbarOptions {
ToolbarOptions::new()
}
}
pub const K_DEFAULT_CONTENT_INSERTION_MIME_TYPES: &[&str] = &[
"image/png",
"image/bmp",
"image/jpg",
"image/tiff",
"image/gif",
"image/jpeg",
"image/webp",
];
struct CompositionCallbackWidget {
composite_callback: CompositionCallback,
enabled: bool,
child: WidgetRef,
}
impl Debug for CompositionCallbackWidget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("_CompositionCallback")
.field("enabled", &self.enabled)
.field("child", &self.child)
.finish_non_exhaustive()
}
}
impl CompositionCallbackWidget {
fn new(composite_callback: CompositionCallback, enabled: bool, child: WidgetRef) -> Self {
CompositionCallbackWidget {
composite_callback,
enabled,
child,
}
}
}
impl RenderObjectWidget for CompositionCallbackWidget {
type RenderObject = RenderCompositionCallback;
fn key(&self) -> Option<&KeyRef> {
None
}
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
RenderCompositionCallback::new(app, self.composite_callback.clone(), self.enabled)
.as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderCompositionCallback>,
) {
debug_assert!(Rc::ptr_eq(
&render_object.get(app).composite_callback,
&self.composite_callback
));
render_object.set_enabled(app, self.enabled);
}
}
impl SingleChildRenderObjectWidget for CompositionCallbackWidget {
fn child(&self) -> Option<&WidgetRef> {
Some(&self.child)
}
}
type CancelCompositionCallback = Box<dyn FnOnce(&mut App)>;
struct RenderCompositionCallback {
render_object: RenderObjectData,
render_box: RenderBoxData,
child: RenderObjectWithChildData<AnyRenderBox>,
composite_callback: CompositionCallback,
cancel_callback: Option<CancelCompositionCallback>,
enabled: bool,
}
impl RenderCompositionCallback {
fn new(
app: &mut App,
composite_callback: CompositionCallback,
enabled: bool,
) -> RenderHandle<Self> {
RenderHandle::new_box(
app,
RenderCompositionCallback {
render_object: RenderObjectData::new(),
render_box: RenderBoxData::new(),
child: RenderObjectWithChildData::new(),
composite_callback,
cancel_callback: None,
enabled,
},
)
}
fn set_enabled(self: RenderHandle<Self>, app: &mut App, new_value: bool) {
self.get_mut(app).enabled = new_value;
if !new_value {
if let Some(cancel) = self.get_mut(app).cancel_callback.take() {
cancel(app);
}
} else if self.get(app).cancel_callback.is_none() {
self.as_object().mark_needs_paint(app);
}
}
}
impl RenderObjectWithChildMixin for RenderCompositionCallback {
type ChildType = AnyRenderBox;
fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
&self.get(app).child
}
fn child_data_mut(
self: RenderHandle<Self>,
app: &mut App,
) -> &mut RenderObjectWithChildData<AnyRenderBox> {
&mut self.get_mut(app).child
}
}
impl RenderProxyBoxMixin for RenderCompositionCallback {}
impl RenderProxyBoxWithHitTestBehavior for RenderCompositionCallback {
fn behavior(self: RenderHandle<Self>, _app: &App) -> HitTestBehavior {
HitTestBehavior::DeferToChild
}
}
impl RenderObject for RenderCompositionCallback {
waft_rendering::render_object_accessors!();
fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
RenderProxyBoxMixin::perform_layout(self, app);
}
fn paint(
self: RenderHandle<Self>,
app: &mut App,
context: &mut PaintingContext,
offset: Offset,
) {
if self.get(app).enabled && self.get(app).cancel_callback.is_none() {
let callback = self.get(app).composite_callback.clone();
let cancel = context.add_composition_callback(app, callback);
self.get_mut(app).cancel_callback = Some(cancel);
}
RenderProxyBoxMixin::paint(self, app, context, offset);
}
fn visit_children(
self: RenderHandle<Self>,
app: &App,
visitor: &mut dyn FnMut(AnyRenderObject),
) {
if let Some(child) = self.child(app) {
visitor(child.as_object());
}
}
fn dispose(self: RenderHandle<Self>, app: &mut App) {
if let Some(cancel) = self.get_mut(app).cancel_callback.take() {
cancel(app);
}
waft_rendering::RenderObjectBase::dispose(self, app);
}
}
impl RenderBox for RenderCompositionCallback {
waft_rendering::render_box_accessors!();
fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
RenderProxyBoxMixin::setup_parent_data(self, app, child);
}
fn apply_paint_transform(
self: RenderHandle<Self>,
app: &App,
child: AnyRenderObject,
transform: &mut Matrix4,
) {
RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
}
fn hit_test(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
RenderProxyBoxWithHitTestBehavior::hit_test(self, app, result, position)
}
fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
RenderProxyBoxWithHitTestBehavior::hit_test_self(self, app, position)
}
fn hit_test_children(
self: RenderHandle<Self>,
app: &mut App,
result: &mut BoxHitTestResult<'_>,
position: Offset,
) -> bool {
RenderProxyBoxMixin::hit_test_children(self, app, result, position)
}
fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
}
fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
}
fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
}
fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
}
fn compute_distance_to_actual_baseline(
self: RenderHandle<Self>,
app: &mut App,
baseline: TextBaseline,
) -> Option<f64> {
RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
}
fn compute_dry_baseline(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
baseline: TextBaseline,
) -> Option<f64> {
RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
}
fn compute_dry_layout(
self: RenderHandle<Self>,
app: &mut App,
constraints: BoxConstraints,
) -> Size {
RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
}
}
#[derive(Clone)]
#[allow(clippy::type_complexity)]
pub struct ContentInsertionConfiguration {
pub on_content_inserted: Rc<dyn Fn(&mut App, KeyboardInsertedContent)>,
pub allowed_mime_types: Vec<String>,
}
impl ContentInsertionConfiguration {
pub fn new(
on_content_inserted: impl Fn(&mut App, KeyboardInsertedContent) + 'static,
) -> ContentInsertionConfiguration {
ContentInsertionConfiguration {
on_content_inserted: Rc::new(on_content_inserted),
allowed_mime_types: K_DEFAULT_CONTENT_INSERTION_MIME_TYPES
.iter()
.map(|s| (*s).to_string())
.collect(),
}
}
pub fn allowed_mime_types(mut self, allowed_mime_types: Vec<String>) -> Self {
debug_assert!(
!allowed_mime_types.is_empty(),
"allowedMimeTypes cannot be an empty list"
);
self.allowed_mime_types = allowed_mime_types;
self
}
}
pub type SelectionChangedCallback =
Rc<dyn Fn(&mut App, TextSelection, Option<SelectionChangedCause>)>;
pub type AppPrivateCommandCallback = Rc<dyn Fn(&mut App, &str)>;
pub type EditableTextContextMenuBuilder =
Rc<dyn Fn(&mut App, BuildContext, Handle<EditableTextState>) -> WidgetRef>;
const K_CURSOR_BLINK_HALF_PERIOD: Duration = Duration::from_millis(500);
const K_OBSCURE_SHOW_LATEST_CHAR_CURSOR_TICKS: i32 = 3;
pub struct DebugDeterministicCursor;
impl waft_foundation::DebugFlag for DebugDeterministicCursor {}
#[derive(Clone, Copy, Debug)]
struct KeyFrame {
time: f64,
value: f64,
}
impl KeyFrame {
const fn new(time: f64, value: f64) -> KeyFrame {
KeyFrame { time, value }
}
const IOS_BLINKING_CARET_KEY_FRAMES: &[KeyFrame] = &[
KeyFrame::new(0.0, 1.0),
KeyFrame::new(0.5, 1.0),
KeyFrame::new(0.5375, 0.75),
KeyFrame::new(0.575, 0.5),
KeyFrame::new(0.6125, 0.25),
KeyFrame::new(0.65, 0.0),
KeyFrame::new(0.85, 0.0),
KeyFrame::new(0.8875, 0.25),
KeyFrame::new(0.925, 0.5),
KeyFrame::new(0.9625, 0.75),
KeyFrame::new(1.0, 1.0),
];
}
struct DiscreteKeyFrameSimulation {
key_frames: &'static [KeyFrame],
max_duration: f64,
last_key_frame_index: Cell<usize>,
tolerance: Tolerance,
}
impl DiscreteKeyFrameSimulation {
fn ios_blinking_caret() -> DiscreteKeyFrameSimulation {
DiscreteKeyFrameSimulation::new(KeyFrame::IOS_BLINKING_CARET_KEY_FRAMES, 1.0)
}
fn new(key_frames: &'static [KeyFrame], max_duration: f64) -> DiscreteKeyFrameSimulation {
debug_assert!(!key_frames.is_empty());
debug_assert!(
key_frames
.last()
.is_none_or(|frame| frame.time <= max_duration)
);
if cfg!(debug_assertions) {
for i in 0..key_frames.len().saturating_sub(1) {
debug_assert!(
key_frames[i].time <= key_frames[i + 1].time,
"The key frame sequence must be sorted by time."
);
}
}
DiscreteKeyFrameSimulation {
key_frames,
max_duration,
last_key_frame_index: Cell::new(0),
tolerance: Tolerance::default(),
}
}
}
impl Debug for DiscreteKeyFrameSimulation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DiscreteKeyFrameSimulation")
.field("max_duration", &self.max_duration)
.finish()
}
}
impl Simulation for DiscreteKeyFrameSimulation {
fn dx(&self, _time: f64) -> f64 {
0.0
}
fn is_done(&self, time: f64) -> bool {
time >= self.max_duration
}
fn x(&self, time: f64) -> f64 {
let length = self.key_frames.len();
let last = self.last_key_frame_index.get();
let (mut search_index, end_index) = if self.key_frames[last].time > time {
(0, last)
} else {
(last, length)
};
while search_index < end_index.saturating_sub(1) {
debug_assert!(self.key_frames[search_index].time <= time);
let next = self.key_frames[search_index + 1];
if time < next.time {
break;
}
search_index += 1;
}
self.last_key_frame_index.set(search_index);
self.key_frames[self.last_key_frame_index.get()].value
}
fn tolerance(&self) -> Tolerance {
self.tolerance
}
fn set_tolerance(&mut self, tolerance: Tolerance) {
self.tolerance = tolerance;
}
}
#[allow(clippy::type_complexity)]
pub struct EditableText {
pub key: Option<KeyRef>,
pub controller: TextEditingControllerRef,
pub focus_node: FocusNodeRef,
pub read_only: bool,
pub obscuring_character: String,
pub obscure_text: bool,
pub autocorrect: Option<bool>,
pub smart_dashes_type: Option<SmartDashesType>,
pub smart_quotes_type: Option<SmartQuotesType>,
pub enable_suggestions: bool,
pub style: TextStyle,
strut_style: Option<StrutStyle>,
pub cursor_color: Color,
pub background_cursor_color: Color,
pub text_align: TextAlign,
pub text_direction: Option<TextDirection>,
pub locale: Option<Locale>,
pub text_scale_factor: Option<f64>,
pub text_scaler: Option<TextScaler>,
pub max_lines: Option<i32>,
pub min_lines: Option<i32>,
pub expands: bool,
pub force_line: bool,
pub text_height_behavior: Option<TextHeightBehavior>,
pub text_width_basis: TextWidthBasis,
pub autofocus: bool,
pub show_cursor: Option<bool>,
pub show_selection_handles: bool,
pub selection_color: Option<Color>,
pub selection_controls: Option<Rc<dyn TextSelectionControls>>,
pub keyboard_type: Option<TextInputType>,
pub text_input_action: Option<TextInputAction>,
pub text_capitalization: TextCapitalization,
pub on_changed: Option<Rc<dyn Fn(&mut App, String)>>,
pub on_editing_complete: Option<Rc<dyn Fn(&mut App)>>,
pub on_submitted: Option<Rc<dyn Fn(&mut App, String)>>,
pub on_app_private_command: Option<AppPrivateCommandCallback>,
pub on_selection_changed: Option<SelectionChangedCallback>,
pub on_selection_handle_tapped: Option<Listener>,
pub group_id: TypeId,
pub on_tap_outside: Option<Rc<dyn Fn(&mut App, PointerDownEvent)>>,
pub on_tap_up_outside: Option<Rc<dyn Fn(&mut App, PointerUpEvent)>>,
pub input_formatters: Option<Vec<TextInputFormatterRef>>,
pub mouse_cursor: Option<MouseCursorRef>,
pub renderer_ignores_pointer: bool,
pub cursor_width: f64,
pub cursor_height: Option<f64>,
pub cursor_radius: Option<Radius>,
pub cursor_opacity_animates: bool,
pub cursor_offset: Option<Offset>,
pub paint_cursor_above_text: bool,
pub selection_height_style: BoxHeightStyle,
pub selection_width_style: BoxWidthStyle,
pub scroll_padding: EdgeInsets,
pub keyboard_appearance: Brightness,
pub drag_start_behavior: DragStartBehavior,
pub enable_interactive_selection: Option<bool>,
pub select_all_on_focus: Option<bool>,
pub scroll_controller: Option<ScrollControllerRef>,
pub scroll_physics: Option<ScrollPhysicsRef>,
pub autocorrection_text_rect_color: Option<Color>,
pub toolbar_options: Option<ToolbarOptions>,
pub autofill_hints: Vec<String>,
pub autofill_client: Option<AnyAutofillClient>,
pub clip_behavior: Clip,
pub restoration_id: Option<String>,
pub scroll_behavior: Option<ScrollBehaviorRef>,
pub scribble_enabled: bool,
pub stylus_handwriting_enabled: bool,
pub enable_ime_personalized_learning: bool,
pub content_insertion_configuration: Option<ContentInsertionConfiguration>,
pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
pub spell_check_configuration: Option<SpellCheckConfiguration>,
pub magnifier_configuration: TextMagnifierConfiguration,
pub undo_controller: Option<Ref<UndoHistoryController>>,
pub hint_locales: Option<Vec<Locale>>,
pub enable_inline_prediction: Option<bool>,
}
impl EditableText {
pub fn default_selection_height_style() -> BoxHeightStyle {
if K_IS_WEB {
BoxHeightStyle::Max
} else {
BoxHeightStyle::IncludeLineSpacingMiddle
}
}
pub fn default_selection_width_style() -> BoxWidthStyle {
if K_IS_WEB {
BoxWidthStyle::Tight
} else {
BoxWidthStyle::Max
}
}
pub const DEFAULT_STYLUS_HANDWRITING_ENABLED: bool = true;
pub fn debug_deterministic_cursor(app: &App) -> bool {
app.debug_flag::<DebugDeterministicCursor>()
}
pub fn set_debug_deterministic_cursor(app: &mut App, value: bool) {
app.set_debug_flag::<DebugDeterministicCursor>(value);
}
pub fn new(
controller: TextEditingControllerRef,
focus_node: FocusNodeRef,
style: TextStyle,
cursor_color: Color,
background_cursor_color: Color,
) -> EditableText {
let obscure_text = false;
let read_only = false;
let max_lines = Some(1);
debug_assert!(!obscure_text || max_lines == Some(1));
EditableText {
key: None,
controller,
focus_node,
read_only,
obscuring_character: "\u{2022}".into(),
obscure_text,
autocorrect: None,
smart_dashes_type: None,
smart_quotes_type: None,
enable_suggestions: true,
style,
strut_style: None,
cursor_color,
background_cursor_color,
text_align: TextAlign::Start,
text_direction: None,
locale: None,
text_scale_factor: None,
text_scaler: None,
max_lines,
min_lines: None,
expands: false,
force_line: true,
text_height_behavior: None,
text_width_basis: TextWidthBasis::Parent,
autofocus: false,
show_cursor: None,
show_selection_handles: false,
selection_color: None,
selection_controls: None,
keyboard_type: None,
text_input_action: None,
text_capitalization: TextCapitalization::None,
on_changed: None,
on_editing_complete: None,
on_submitted: None,
on_app_private_command: None,
on_selection_changed: None,
on_selection_handle_tapped: None,
group_id: TypeId::of::<EditableText>(),
on_tap_outside: None,
on_tap_up_outside: None,
input_formatters: None,
mouse_cursor: None,
renderer_ignores_pointer: false,
cursor_width: 2.0,
cursor_height: None,
cursor_radius: None,
cursor_opacity_animates: false,
cursor_offset: None,
paint_cursor_above_text: false,
selection_height_style: Self::default_selection_height_style(),
selection_width_style: Self::default_selection_width_style(),
scroll_padding: EdgeInsets::all(20.0),
keyboard_appearance: Brightness::Light,
drag_start_behavior: DragStartBehavior::Start,
enable_interactive_selection: None,
select_all_on_focus: None,
scroll_controller: None,
scroll_physics: None,
autocorrection_text_rect_color: None,
toolbar_options: None,
autofill_hints: Vec::new(),
autofill_client: None,
clip_behavior: Clip::HardEdge,
restoration_id: None,
scroll_behavior: None,
scribble_enabled: true,
stylus_handwriting_enabled: Self::DEFAULT_STYLUS_HANDWRITING_ENABLED,
enable_ime_personalized_learning: true,
content_insertion_configuration: None,
context_menu_builder: None,
spell_check_configuration: None,
magnifier_configuration: TextMagnifierConfiguration::DISABLED,
undo_controller: None,
hint_locales: None,
enable_inline_prediction: None,
}
}
pub fn effective_strut_style(&self) -> StrutStyle {
if let Some(strut_style) = &self.strut_style {
return strut_style.inherit_from_text_style(Some(&self.style));
}
StrutStyle::from_text_style(&self.style)
.force_strut_height(true)
.build()
}
pub fn key(mut self, key: KeyRef) -> Self {
self.key = Some(key);
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn obscuring_character(mut self, obscuring_character: impl Into<String>) -> Self {
let obscuring_character = obscuring_character.into();
debug_assert!(
obscuring_character.chars().count() == 1,
"obscuringCharacter must be a single character"
);
self.obscuring_character = obscuring_character;
self
}
pub fn obscure_text(mut self, obscure_text: bool) -> Self {
debug_assert!(!obscure_text || self.max_lines == Some(1));
self.obscure_text = obscure_text;
self
}
pub fn autocorrect(mut self, autocorrect: bool) -> Self {
self.autocorrect = Some(autocorrect);
self
}
pub fn smart_dashes_type(mut self, smart_dashes_type: SmartDashesType) -> Self {
self.smart_dashes_type = Some(smart_dashes_type);
self
}
pub fn smart_quotes_type(mut self, smart_quotes_type: SmartQuotesType) -> Self {
self.smart_quotes_type = Some(smart_quotes_type);
self
}
pub fn enable_suggestions(mut self, enable_suggestions: bool) -> Self {
self.enable_suggestions = enable_suggestions;
self
}
pub fn strut_style(mut self, strut_style: StrutStyle) -> Self {
self.strut_style = Some(strut_style);
self
}
pub fn text_align(mut self, text_align: TextAlign) -> Self {
self.text_align = text_align;
self
}
pub fn text_direction(mut self, text_direction: TextDirection) -> Self {
self.text_direction = Some(text_direction);
self
}
pub fn locale(mut self, locale: Locale) -> Self {
self.locale = Some(locale);
self
}
pub fn text_scale_factor(mut self, text_scale_factor: f64) -> Self {
self.text_scale_factor = Some(text_scale_factor);
self
}
pub fn text_scaler(mut self, text_scaler: TextScaler) -> Self {
self.text_scaler = Some(text_scaler);
self
}
pub fn max_lines(mut self, max_lines: Option<i32>) -> Self {
debug_assert!(
max_lines.is_none_or(|lines| self.min_lines.is_none_or(|min| lines >= min)),
"minLines can't be greater than maxLines"
);
debug_assert!(!self.expands || max_lines.is_none());
debug_assert!(!self.obscure_text || max_lines == Some(1));
self.max_lines = max_lines;
self
}
pub fn min_lines(mut self, min_lines: i32) -> Self {
debug_assert!(min_lines > 0);
debug_assert!(
self.max_lines.is_none_or(|max| max >= min_lines),
"minLines can't be greater than maxLines"
);
debug_assert!(!self.expands);
self.min_lines = Some(min_lines);
self
}
pub fn expands(mut self, expands: bool) -> Self {
debug_assert!(!expands || (self.max_lines.is_none() && self.min_lines.is_none()));
self.expands = expands;
self
}
pub fn force_line(mut self, force_line: bool) -> Self {
self.force_line = force_line;
self
}
pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> Self {
self.text_height_behavior = Some(text_height_behavior);
self
}
pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> Self {
self.text_width_basis = text_width_basis;
self
}
pub fn autofocus(mut self, autofocus: bool) -> Self {
self.autofocus = autofocus;
self
}
pub fn show_cursor(mut self, show_cursor: bool) -> Self {
self.show_cursor = Some(show_cursor);
self
}
pub fn show_selection_handles(mut self, show_selection_handles: bool) -> Self {
self.show_selection_handles = show_selection_handles;
self
}
pub fn selection_color(mut self, selection_color: Color) -> Self {
self.selection_color = Some(selection_color);
self
}
pub fn selection_controls(mut self, selection_controls: Rc<dyn TextSelectionControls>) -> Self {
self.selection_controls = Some(selection_controls);
self
}
pub fn keyboard_type(mut self, keyboard_type: TextInputType) -> Self {
self.keyboard_type = Some(keyboard_type);
self
}
pub fn text_input_action(mut self, text_input_action: TextInputAction) -> Self {
self.text_input_action = Some(text_input_action);
self
}
pub fn text_capitalization(mut self, text_capitalization: TextCapitalization) -> Self {
self.text_capitalization = text_capitalization;
self
}
pub fn on_changed(mut self, on_changed: impl Fn(&mut App, String) + 'static) -> Self {
self.on_changed = Some(Rc::new(on_changed));
self
}
pub fn on_editing_complete(mut self, on_editing_complete: impl Fn(&mut App) + 'static) -> Self {
self.on_editing_complete = Some(Rc::new(on_editing_complete));
self
}
pub fn on_submitted(mut self, on_submitted: impl Fn(&mut App, String) + 'static) -> Self {
self.on_submitted = Some(Rc::new(on_submitted));
self
}
pub fn on_app_private_command(
mut self,
on_app_private_command: impl Fn(&mut App, &str) + 'static,
) -> Self {
self.on_app_private_command = Some(Rc::new(on_app_private_command));
self
}
pub fn on_selection_changed(
mut self,
on_selection_changed: impl Fn(&mut App, TextSelection, Option<SelectionChangedCause>) + 'static,
) -> Self {
self.on_selection_changed = Some(Rc::new(on_selection_changed));
self
}
pub fn on_selection_handle_tapped(mut self, on_selection_handle_tapped: Listener) -> Self {
self.on_selection_handle_tapped = Some(on_selection_handle_tapped);
self
}
pub fn group_id(mut self, group_id: TypeId) -> Self {
self.group_id = group_id;
self
}
pub fn on_tap_outside(
mut self,
on_tap_outside: impl Fn(&mut App, PointerDownEvent) + 'static,
) -> Self {
self.on_tap_outside = Some(Rc::new(on_tap_outside));
self
}
pub fn on_tap_up_outside(
mut self,
on_tap_up_outside: impl Fn(&mut App, PointerUpEvent) + 'static,
) -> Self {
self.on_tap_up_outside = Some(Rc::new(on_tap_up_outside));
self
}
pub fn input_formatters(mut self, input_formatters: Vec<TextInputFormatterRef>) -> Self {
self.input_formatters = Some(input_formatters);
self
}
pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Self {
self.mouse_cursor = Some(mouse_cursor);
self
}
pub fn renderer_ignores_pointer(mut self, renderer_ignores_pointer: bool) -> Self {
self.renderer_ignores_pointer = renderer_ignores_pointer;
self
}
pub fn cursor_width(mut self, cursor_width: f64) -> Self {
self.cursor_width = cursor_width;
self
}
pub fn cursor_height(mut self, cursor_height: f64) -> Self {
self.cursor_height = Some(cursor_height);
self
}
pub fn cursor_radius(mut self, cursor_radius: Radius) -> Self {
self.cursor_radius = Some(cursor_radius);
self
}
pub fn cursor_opacity_animates(mut self, cursor_opacity_animates: bool) -> Self {
self.cursor_opacity_animates = cursor_opacity_animates;
self
}
pub fn cursor_offset(mut self, cursor_offset: Offset) -> Self {
self.cursor_offset = Some(cursor_offset);
self
}
pub fn paint_cursor_above_text(mut self, paint_cursor_above_text: bool) -> Self {
self.paint_cursor_above_text = paint_cursor_above_text;
self
}
pub fn selection_height_style(mut self, selection_height_style: BoxHeightStyle) -> Self {
self.selection_height_style = selection_height_style;
self
}
pub fn selection_width_style(mut self, selection_width_style: BoxWidthStyle) -> Self {
self.selection_width_style = selection_width_style;
self
}
pub fn scroll_padding(mut self, scroll_padding: EdgeInsets) -> Self {
self.scroll_padding = scroll_padding;
self
}
pub fn keyboard_appearance(mut self, keyboard_appearance: Brightness) -> Self {
self.keyboard_appearance = keyboard_appearance;
self
}
pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Self {
self.drag_start_behavior = drag_start_behavior;
self
}
pub fn enable_interactive_selection(mut self, enable_interactive_selection: bool) -> Self {
self.enable_interactive_selection = Some(enable_interactive_selection);
self
}
pub fn select_all_on_focus(mut self, select_all_on_focus: bool) -> Self {
self.select_all_on_focus = Some(select_all_on_focus);
self
}
pub fn scroll_controller(mut self, scroll_controller: ScrollControllerRef) -> Self {
self.scroll_controller = Some(scroll_controller);
self
}
pub fn scroll_physics(mut self, scroll_physics: ScrollPhysicsRef) -> Self {
self.scroll_physics = Some(scroll_physics);
self
}
pub fn autocorrection_text_rect_color(mut self, autocorrection_text_rect_color: Color) -> Self {
self.autocorrection_text_rect_color = Some(autocorrection_text_rect_color);
self
}
pub fn toolbar_options(mut self, toolbar_options: ToolbarOptions) -> Self {
self.toolbar_options = Some(toolbar_options);
self
}
pub fn autofill_hints(mut self, autofill_hints: Vec<String>) -> Self {
self.autofill_hints = autofill_hints;
self
}
pub fn autofill_client(mut self, autofill_client: AnyAutofillClient) -> Self {
self.autofill_client = Some(autofill_client);
self
}
pub fn clip_behavior(mut self, clip_behavior: Clip) -> Self {
self.clip_behavior = clip_behavior;
self
}
pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> Self {
self.restoration_id = Some(restoration_id.into());
self
}
pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> Self {
self.scroll_behavior = Some(scroll_behavior);
self
}
pub fn scribble_enabled(mut self, scribble_enabled: bool) -> Self {
self.scribble_enabled = scribble_enabled;
self
}
pub fn stylus_handwriting_enabled(mut self, stylus_handwriting_enabled: bool) -> Self {
self.stylus_handwriting_enabled = stylus_handwriting_enabled;
self
}
pub fn enable_ime_personalized_learning(
mut self,
enable_ime_personalized_learning: bool,
) -> Self {
self.enable_ime_personalized_learning = enable_ime_personalized_learning;
self
}
pub fn content_insertion_configuration(
mut self,
content_insertion_configuration: ContentInsertionConfiguration,
) -> Self {
self.content_insertion_configuration = Some(content_insertion_configuration);
self
}
pub fn context_menu_builder(
mut self,
context_menu_builder: EditableTextContextMenuBuilder,
) -> Self {
self.context_menu_builder = Some(context_menu_builder);
self
}
pub fn spell_check_configuration(
mut self,
spell_check_configuration: SpellCheckConfiguration,
) -> Self {
if cfg!(debug_assertions)
&& spell_check_configuration.spell_check_enabled()
&& spell_check_configuration.misspelled_text_style.is_none()
{
debug_assert!(
false,
"spellCheckConfiguration must specify a misspelledTextStyle if spell check behavior is desired"
);
}
self.spell_check_configuration = Some(spell_check_configuration);
self
}
pub fn magnifier_configuration(
mut self,
magnifier_configuration: TextMagnifierConfiguration,
) -> Self {
self.magnifier_configuration = magnifier_configuration;
self
}
pub fn undo_controller(mut self, undo_controller: Ref<UndoHistoryController>) -> Self {
self.undo_controller = Some(undo_controller);
self
}
pub fn hint_locales(mut self, hint_locales: Vec<Locale>) -> Self {
self.hint_locales = Some(hint_locales);
self
}
pub fn enable_inline_prediction(mut self, enable_inline_prediction: bool) -> Self {
self.enable_inline_prediction = Some(enable_inline_prediction);
self
}
#[allow(clippy::too_many_arguments)]
pub fn get_editable_button_items(
clipboard_status: Option<ClipboardStatus>,
on_copy: Option<Listener>,
on_cut: Option<Listener>,
on_paste: Option<Listener>,
on_select_all: Option<Listener>,
on_look_up: Option<Listener>,
on_search_web: Option<Listener>,
on_share: Option<Listener>,
on_live_text_input: Option<Listener>,
target_platform: TargetPlatform,
) -> Vec<ContextMenuButtonItem> {
let mut result_button_item = Vec::new();
if on_paste.is_none() || clipboard_status != Some(ClipboardStatus::Unknown) {
let show_share_before_select_all = target_platform == TargetPlatform::Android;
if let Some(on_cut) = on_cut {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_cut)).r#type(ContextMenuButtonType::Cut),
);
}
if let Some(on_copy) = on_copy {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_copy)).r#type(ContextMenuButtonType::Copy),
);
}
if let Some(on_paste) = on_paste {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_paste)).r#type(ContextMenuButtonType::Paste),
);
}
if let Some(on_share) = on_share.clone()
&& show_share_before_select_all
{
result_button_item.push(
ContextMenuButtonItem::new(Some(on_share)).r#type(ContextMenuButtonType::Share),
);
}
if let Some(on_select_all) = on_select_all {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_select_all))
.r#type(ContextMenuButtonType::SelectAll),
);
}
if let Some(on_look_up) = on_look_up {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_look_up))
.r#type(ContextMenuButtonType::LookUp),
);
}
if let Some(on_search_web) = on_search_web {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_search_web))
.r#type(ContextMenuButtonType::SearchWeb),
);
}
if let Some(on_share) = on_share
&& !show_share_before_select_all
{
result_button_item.push(
ContextMenuButtonItem::new(Some(on_share)).r#type(ContextMenuButtonType::Share),
);
}
}
if let Some(on_live_text_input) = on_live_text_input {
result_button_item.push(
ContextMenuButtonItem::new(Some(on_live_text_input))
.r#type(ContextMenuButtonType::LiveTextInput),
);
}
result_button_item
}
fn user_selection_enabled(&self) -> bool {
self.effective_enable_interactive_selection() && (!self.read_only || !self.obscure_text)
}
pub fn effective_autocorrect(&self, app: &App) -> bool {
self.autocorrect.unwrap_or_else(|| {
infer_autocorrect(&self.autofill_hints, app.platform().target_platform())
})
}
pub fn effective_smart_dashes_type(&self) -> SmartDashesType {
self.smart_dashes_type.unwrap_or(if self.obscure_text {
SmartDashesType::Disabled
} else {
SmartDashesType::Enabled
})
}
pub fn effective_smart_quotes_type(&self) -> SmartQuotesType {
self.smart_quotes_type.unwrap_or(if self.obscure_text {
SmartQuotesType::Disabled
} else {
SmartQuotesType::Enabled
})
}
pub fn effective_enable_interactive_selection(&self) -> bool {
self.enable_interactive_selection
.unwrap_or(!self.read_only || !self.obscure_text)
}
pub fn effective_select_all_on_focus(&self, app: &App) -> bool {
self.select_all_on_focus
.unwrap_or_else(|| default_select_all_on_focus(app.platform().target_platform()))
}
pub fn effective_toolbar_options(&self) -> ToolbarOptions {
if self.has_handle_controls() && self.toolbar_options.is_none() {
return ToolbarOptions::EMPTY;
}
self.toolbar_options
.unwrap_or_else(|| default_toolbar_options(self.read_only, self.obscure_text))
}
fn has_handle_controls(&self) -> bool {
self.selection_controls
.as_ref()
.is_some_and(|controls| controls.as_text_selection_handle_controls().is_some())
}
pub fn effective_keyboard_type(&self, app: &App) -> TextInputType {
self.keyboard_type.unwrap_or_else(|| {
infer_keyboard_type(
&self.autofill_hints,
self.max_lines,
app.platform().target_platform(),
)
})
}
pub fn effective_input_formatters(&self) -> Vec<TextInputFormatterRef> {
let given = self.input_formatters.iter().flatten().cloned();
if self.max_lines == Some(1) {
std::iter::once(FilteringTextInputFormatter::single_line_formatter())
.chain(given)
.collect()
} else {
given.collect()
}
}
pub fn effective_show_cursor(&self) -> bool {
self.show_cursor.unwrap_or(!self.read_only)
}
}
impl Debug for EditableText {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EditableText")
.field("controller", &self.controller)
.field("focus_node", &self.focus_node)
.field("obscure_text", &self.obscure_text)
.field("read_only", &self.read_only)
.field("style", &self.style)
.field("max_lines", &self.max_lines)
.finish_non_exhaustive()
}
}
impl StatefulWidget for EditableText {
type State = EditableTextState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> EditableTextState {
EditableTextState {
state: StateData::new(),
automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
ticker_provider: TickerProviderStateMixinData::new(),
cursor_timer: None,
backing_cursor_blink_opacity_controller: None,
cursor_visibility_notifier: None,
clipboard_status: None,
live_text_input_status: None,
text_input_connection: None,
view_id: None,
composite_callback: None,
last_known_remote_text_editing_value: None,
scribble_cache_key: None,
internal_scroll_controller: None,
toolbar_layer_link: None,
start_handle_layer_link: None,
end_handle_layer_link: None,
did_auto_focus: false,
process_text_service: Rc::new(DefaultProcessTextService),
process_text_actions: Vec::new(),
spell_check_configuration: SpellCheckConfiguration::disabled(),
spell_check_results: None,
current_autofill_scope: None,
app_lifecycle_listener: None,
just_resumed: false,
had_focus_on_tap_down: false,
actions: None,
vertical_movement_run: None,
run_selection: None,
editable_key: GlobalKey::new(),
scrollable_key: GlobalKey::new(),
style: TextStyle::new(),
tickers_enabled: true,
batch_edit_depth: 0,
current_prompt_rect_range: None,
obscure_show_char_ticks_pending: 0,
obscure_latest_char_index: None,
last_orientation: None,
binding_observer: None,
registered_as_observer: false,
show_caret_on_screen_scheduled: false,
last_bottom_view_inset: 0.0,
has_focus: false,
next_focus_change_is_internal: false,
selection_overlay: None,
render_editable: Cell::new(None),
}
}
}
fn default_toolbar_options(read_only: bool, obscure_text: bool) -> ToolbarOptions {
if obscure_text {
if read_only {
ToolbarOptions::EMPTY
} else {
ToolbarOptions::new().select_all(true).paste(true)
}
} else if read_only {
ToolbarOptions::new().select_all(true).copy(true)
} else {
ToolbarOptions::new()
.copy(true)
.cut(true)
.select_all(true)
.paste(true)
}
}
fn find_render_editable(
app: &App,
object: AnyRenderObject,
) -> Option<RenderHandle<RenderEditable>> {
if let Some(editable) = object.downcast::<RenderEditable>(app) {
return Some(editable);
}
let mut found = None;
object.visit_children(app, &mut |child| {
if found.is_none() {
found = find_render_editable(app, child);
}
});
found
}
fn infer_autocorrect(autofill_hints: &[String], platform: TargetPlatform) -> bool {
if autofill_hints.is_empty() || K_IS_WEB {
return true;
}
match platform {
TargetPlatform::IOS => {
let password_related_hint = autofill_hints.iter().any(|hint| {
hint == AutofillHints::USERNAME
|| hint == AutofillHints::PASSWORD
|| hint == AutofillHints::NEW_PASSWORD
});
if password_related_hint {
return false;
}
}
TargetPlatform::MacOS
| TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {}
}
true
}
fn infer_keyboard_type(
autofill_hints: &[String],
max_lines: Option<i32>,
platform: TargetPlatform,
) -> TextInputType {
let Some(effective_hint) = autofill_hints.first() else {
return if max_lines == Some(1) {
TextInputType::TEXT
} else {
TextInputType::MULTILINE
};
};
let effective_hint = effective_hint.as_str();
if !K_IS_WEB {
match platform {
TargetPlatform::IOS | TargetPlatform::MacOS => {
if let Some(keyboard_type) = ios_keyboard_type(effective_hint) {
return keyboard_type;
}
}
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {}
}
}
if max_lines != Some(1) {
return TextInputType::MULTILINE;
}
match effective_hint {
AutofillHints::ADDRESS_CITY
| AutofillHints::ADDRESS_CITY_AND_STATE
| AutofillHints::ADDRESS_STATE => TextInputType::STREET_ADDRESS,
AutofillHints::BIRTHDAY
| AutofillHints::BIRTHDAY_DAY
| AutofillHints::BIRTHDAY_MONTH
| AutofillHints::BIRTHDAY_YEAR => TextInputType::DATETIME,
AutofillHints::COUNTRY_CODE => TextInputType::NUMBER,
AutofillHints::COUNTRY_NAME => TextInputType::TEXT,
AutofillHints::CREDIT_CARD_EXPIRATION_DATE
| AutofillHints::CREDIT_CARD_EXPIRATION_DAY
| AutofillHints::CREDIT_CARD_EXPIRATION_MONTH
| AutofillHints::CREDIT_CARD_EXPIRATION_YEAR => TextInputType::DATETIME,
AutofillHints::CREDIT_CARD_FAMILY_NAME
| AutofillHints::CREDIT_CARD_GIVEN_NAME
| AutofillHints::CREDIT_CARD_MIDDLE_NAME
| AutofillHints::CREDIT_CARD_NAME => TextInputType::NAME,
AutofillHints::CREDIT_CARD_NUMBER | AutofillHints::CREDIT_CARD_SECURITY_CODE => {
TextInputType::NUMBER
}
AutofillHints::CREDIT_CARD_TYPE => TextInputType::TEXT,
AutofillHints::EMAIL => TextInputType::EMAIL_ADDRESS,
AutofillHints::EMAIL_OTP_CODE => TextInputType::TEXT,
AutofillHints::FAMILY_NAME => TextInputType::NAME,
AutofillHints::FULL_STREET_ADDRESS => TextInputType::STREET_ADDRESS,
AutofillHints::GENDER => TextInputType::TEXT,
AutofillHints::GIVEN_NAME => TextInputType::NAME,
AutofillHints::IMPP => TextInputType::URL,
AutofillHints::JOB_TITLE | AutofillHints::LANGUAGE => TextInputType::TEXT,
AutofillHints::LOCATION => TextInputType::STREET_ADDRESS,
AutofillHints::MIDDLE_INITIAL
| AutofillHints::MIDDLE_NAME
| AutofillHints::NAME
| AutofillHints::NAME_PREFIX
| AutofillHints::NAME_SUFFIX => TextInputType::NAME,
AutofillHints::NEW_PASSWORD
| AutofillHints::NEW_USERNAME
| AutofillHints::NICKNAME
| AutofillHints::ONE_TIME_CODE
| AutofillHints::ORGANIZATION_NAME
| AutofillHints::PASSWORD
| AutofillHints::PHOTO => TextInputType::TEXT,
AutofillHints::POSTAL_ADDRESS | AutofillHints::POSTAL_ADDRESS_EXTENDED => {
TextInputType::STREET_ADDRESS
}
AutofillHints::POSTAL_ADDRESS_EXTENDED_POSTAL_CODE | AutofillHints::POSTAL_CODE => {
TextInputType::NUMBER
}
AutofillHints::STREET_ADDRESS_LEVEL1
| AutofillHints::STREET_ADDRESS_LEVEL2
| AutofillHints::STREET_ADDRESS_LEVEL3
| AutofillHints::STREET_ADDRESS_LEVEL4
| AutofillHints::STREET_ADDRESS_LINE1
| AutofillHints::STREET_ADDRESS_LINE2
| AutofillHints::STREET_ADDRESS_LINE3
| AutofillHints::SUBLOCALITY => TextInputType::STREET_ADDRESS,
AutofillHints::TELEPHONE_NUMBER
| AutofillHints::TELEPHONE_NUMBER_AREA_CODE
| AutofillHints::TELEPHONE_NUMBER_COUNTRY_CODE
| AutofillHints::TELEPHONE_NUMBER_DEVICE
| AutofillHints::TELEPHONE_NUMBER_EXTENSION
| AutofillHints::TELEPHONE_NUMBER_LOCAL
| AutofillHints::TELEPHONE_NUMBER_LOCAL_PREFIX
| AutofillHints::TELEPHONE_NUMBER_LOCAL_SUFFIX
| AutofillHints::TELEPHONE_NUMBER_NATIONAL => TextInputType::PHONE,
AutofillHints::TRANSACTION_AMOUNT => TextInputType::number_with_options().decimal(true),
AutofillHints::TRANSACTION_CURRENCY => TextInputType::TEXT,
AutofillHints::URL => TextInputType::URL,
AutofillHints::USERNAME => TextInputType::TEXT,
_ => TextInputType::TEXT,
}
}
fn ios_keyboard_type(hint: &str) -> Option<TextInputType> {
let keyboard_type = match hint {
AutofillHints::ADDRESS_CITY => TextInputType::NAME,
AutofillHints::ADDRESS_CITY_AND_STATE => TextInputType::NAME, AutofillHints::ADDRESS_STATE | AutofillHints::COUNTRY_NAME => TextInputType::NAME,
AutofillHints::CREDIT_CARD_NUMBER => TextInputType::NUMBER, AutofillHints::EMAIL => TextInputType::EMAIL_ADDRESS,
AutofillHints::EMAIL_OTP_CODE => TextInputType::TEXT,
AutofillHints::FAMILY_NAME
| AutofillHints::FULL_STREET_ADDRESS
| AutofillHints::GIVEN_NAME => TextInputType::NAME,
AutofillHints::JOB_TITLE => TextInputType::NAME, AutofillHints::LOCATION => TextInputType::NAME, AutofillHints::MIDDLE_NAME => TextInputType::NAME, AutofillHints::NAME => TextInputType::NAME,
AutofillHints::NAME_PREFIX => TextInputType::NAME, AutofillHints::NAME_SUFFIX => TextInputType::NAME, AutofillHints::NEW_PASSWORD | AutofillHints::NEW_USERNAME => TextInputType::TEXT,
AutofillHints::NICKNAME => TextInputType::NAME, AutofillHints::ONE_TIME_CODE => TextInputType::NUMBER,
AutofillHints::ORGANIZATION_NAME => TextInputType::TEXT, AutofillHints::PASSWORD => TextInputType::TEXT,
AutofillHints::POSTAL_CODE | AutofillHints::STREET_ADDRESS_LINE1 => TextInputType::NAME,
AutofillHints::STREET_ADDRESS_LINE2 => TextInputType::NAME, AutofillHints::SUBLOCALITY => TextInputType::NAME, AutofillHints::TELEPHONE_NUMBER => TextInputType::NAME,
AutofillHints::URL => TextInputType::URL, AutofillHints::USERNAME => TextInputType::TEXT,
_ => return None,
};
Some(keyboard_type)
}
fn default_select_all_on_focus(platform: TargetPlatform) -> bool {
if K_IS_WEB {
return true;
}
match platform {
TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => true,
TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => false,
}
}
fn is_password_input(
obscure_text: bool,
keyboard_type: TextInputType,
autofill_hints: &[String],
) -> bool {
obscure_text
|| keyboard_type == TextInputType::VISIBLE_PASSWORD
|| keyboard_type.password == Some(true)
|| autofill_hints
.iter()
.any(|hint| hint == AutofillHints::PASSWORD || hint == AutofillHints::NEW_PASSWORD)
}
fn infer_spell_check_configuration(
configuration: Option<&SpellCheckConfiguration>,
obscure_text: bool,
keyboard_type: TextInputType,
autofill_hints: &[String],
) -> SpellCheckConfiguration {
let disabled = is_password_input(obscure_text, keyboard_type, autofill_hints)
|| configuration.is_none()
|| configuration.is_some_and(|config| !config.spell_check_enabled());
let service_configured = configuration
.and_then(|config| config.spell_check_service.as_ref())
.is_some();
if disabled || !service_configured {
return SpellCheckConfiguration::disabled();
}
configuration
.cloned()
.unwrap_or_else(SpellCheckConfiguration::disabled)
}
pub struct EditableTextState {
state: StateData<EditableText>,
automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
ticker_provider: TickerProviderStateMixinData,
cursor_timer: Option<Timer>,
backing_cursor_blink_opacity_controller: Option<Ref<AnimationController>>,
cursor_visibility_notifier: Option<Ref<ValueNotifier<bool>>>,
clipboard_status: Option<Ref<ClipboardStatusNotifier>>,
live_text_input_status: Option<Ref<LiveTextInputStatusNotifier>>,
text_input_connection: Option<Ref<TextInputConnection>>,
view_id: Option<ViewId>,
composite_callback: Option<CompositionCallback>,
last_known_remote_text_editing_value: Option<TextEditingValue>,
scribble_cache_key: Option<ScribbleCacheKey>,
internal_scroll_controller: Option<Ref<ScrollController>>,
toolbar_layer_link: Option<Ref<LayerLink>>,
start_handle_layer_link: Option<Ref<LayerLink>>,
end_handle_layer_link: Option<Ref<LayerLink>>,
did_auto_focus: bool,
process_text_service: Rc<dyn ProcessTextService>,
process_text_actions: Vec<ProcessTextAction>,
spell_check_configuration: SpellCheckConfiguration,
spell_check_results: Option<SpellCheckResults>,
current_autofill_scope: Option<Handle<AutofillGroupState>>,
app_lifecycle_listener: Option<Ref<AppLifecycleListener>>,
just_resumed: bool,
had_focus_on_tap_down: bool,
actions: Option<HashMap<TypeId, ActionRef>>,
vertical_movement_run: Option<VerticalCaretMovementRun>,
run_selection: Option<TextSelection>,
editable_key: GlobalKey,
scrollable_key: GlobalKey,
style: TextStyle,
tickers_enabled: bool,
batch_edit_depth: i32,
current_prompt_rect_range: Option<TextRange>,
obscure_show_char_ticks_pending: i32,
obscure_latest_char_index: Option<i32>,
last_orientation: Option<Orientation>,
binding_observer: Option<WidgetsBindingObserverRef>,
registered_as_observer: bool,
show_caret_on_screen_scheduled: bool,
last_bottom_view_inset: f64,
has_focus: bool,
next_focus_change_is_internal: bool,
selection_overlay: Option<Ref<TextSelectionOverlay>>,
render_editable: Cell<Option<RenderHandle<RenderEditable>>>,
}
impl Debug for EditableTextState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EditableTextState")
.field("has_focus", &self.has_focus)
.field("batch_edit_depth", &self.batch_edit_depth)
.finish_non_exhaustive()
}
}
impl EditableTextState {
pub fn clipboard_status(self: Handle<Self>, app: &App) -> Handle<ClipboardStatusNotifier> {
app.get(self)
.clipboard_status
.handle()
.expect("clipboardStatus is created in initState")
}
pub fn render_editable(self: Handle<Self>, app: &App) -> RenderHandle<RenderEditable> {
if let Some(render_editable) = app.get(self).render_editable.get() {
return render_editable;
}
let object = self
.context(app)
.find_render_object(app)
.expect("EditableText has a render object");
let render_editable =
find_render_editable(app, object).expect("EditableText should mount a RenderEditable");
app.get(self).render_editable.set(Some(render_editable));
render_editable
}
pub fn get_glyph_heights(self: Handle<Self>, app: &mut App) -> (f64, f64) {
let selection = self.value(app).selection;
let render_editable = self.render_editable(app);
let line_height = render_editable.preferred_line_height(app);
let Some(span) = render_editable.text(app) else {
return (line_height, line_height);
};
let prev_text = span.to_plain_text(true, true);
let curr_text = self.value(app).text.clone();
if prev_text != curr_text || !selection.is_valid() || selection.is_collapsed() {
return (line_height, line_height);
}
let selected = selection.range().text_inside(&curr_text);
let first_extent = selected
.chars()
.next()
.map(|c| c.len_utf16() as i32)
.unwrap_or(0);
let last_extent = selected
.chars()
.next_back()
.map(|c| c.len_utf16() as i32)
.unwrap_or(0);
let start_rect = render_editable.get_rect_for_composing_range(
app,
TextRange::new(selection.start(), selection.start() + first_extent),
);
let end_rect = render_editable.get_rect_for_composing_range(
app,
TextRange::new(selection.end() - last_extent, selection.end()),
);
(
start_rect.map_or(line_height, |rect| rect.height()),
end_rect.map_or(line_height, |rect| rect.height()),
)
}
pub fn context_menu_anchors(self: Handle<Self>, app: &mut App) -> TextSelectionToolbarAnchors {
let render_editable = self.render_editable(app);
if let Some(position) = render_editable.last_secondary_tap_down_position(app) {
return TextSelectionToolbarAnchors::new(position);
}
let (start_glyph_height, end_glyph_height) = self.get_glyph_heights(app);
let selection = self.value(app).selection;
let points = render_editable.get_endpoints_for_selection(app, selection);
TextSelectionToolbarAnchors::from_selection(
app,
render_editable.as_box(),
start_glyph_height,
end_glyph_height,
&points,
)
}
pub fn context_menu_button_items(
self: Handle<Self>,
app: &mut App,
) -> Vec<ContextMenuButtonItem> {
if let Some(items) = self.button_items_for_toolbar_options(app) {
let mut items = items;
items.extend(self.text_processing_action_button_items(app));
return items;
}
let clipboard_status = self.clipboard_status(app).value(app);
let platform = app.platform().target_platform();
let mut items = EditableText::get_editable_button_items(
Some(clipboard_status),
self.copy_enabled(app)
.then(|| Listener::handle_method(self, Self::copy_selection_from_toolbar)),
self.cut_enabled(app)
.then(|| Listener::handle_method(self, Self::cut_selection_from_toolbar)),
self.paste_enabled(app)
.then(|| Listener::handle_method(self, Self::paste_text_from_toolbar)),
self.select_all_enabled(app)
.then(|| Listener::handle_method(self, Self::select_all_from_toolbar)),
self.look_up_enabled(app)
.then(|| Listener::handle_method(self, Self::look_up_selection_from_toolbar)),
self.search_web_enabled(app).then(|| {
Listener::handle_method(self, Self::search_web_for_selection_from_toolbar)
}),
self.share_enabled(app)
.then(|| Listener::handle_method(self, Self::share_selection_from_toolbar)),
self.live_text_input_enabled(app)
.then(|| Listener::handle_method(self, Self::start_live_text_input_from_toolbar)),
platform,
);
items.extend(self.text_processing_action_button_items(app));
items
}
fn copy_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
self.copy_selection(app, SelectionChangedCause::Toolbar);
}
fn cut_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
self.cut_selection(app, SelectionChangedCause::Toolbar);
}
fn paste_text_from_toolbar(self: Handle<Self>, app: &mut App) {
self.paste_text(app, SelectionChangedCause::Toolbar);
}
fn select_all_from_toolbar(self: Handle<Self>, app: &mut App) {
self.select_all(app, SelectionChangedCause::Toolbar);
}
fn look_up_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
self.look_up_selection(app, SelectionChangedCause::Toolbar);
}
fn search_web_for_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
self.search_web_for_selection(app, SelectionChangedCause::Toolbar);
}
fn share_selection_from_toolbar(self: Handle<Self>, app: &mut App) {
self.share_selection(app, SelectionChangedCause::Toolbar);
}
fn start_live_text_input_from_toolbar(self: Handle<Self>, app: &mut App) {
self.start_live_text_input(app, SelectionChangedCause::Toolbar);
}
pub fn look_up_selection(self: Handle<Self>, app: &mut App, _cause: SelectionChangedCause) {
debug_assert!(!self.widget(app).obscure_text);
if self.widget(app).obscure_text {
return;
}
let value = self.value(app);
let text = value.selection.range().text_inside(&value.text);
if text.is_empty() {
return;
}
if let Some(services) = app.platform().text_services() {
services.look_up(text);
}
}
pub fn search_web_for_selection(
self: Handle<Self>,
app: &mut App,
_cause: SelectionChangedCause,
) {
debug_assert!(!self.widget(app).obscure_text);
if self.widget(app).obscure_text {
return;
}
let value = self.value(app);
let text = value.selection.range().text_inside(&value.text);
if !text.is_empty()
&& let Some(services) = app.platform().text_services()
{
services.search_web(text);
}
}
pub fn share_selection(self: Handle<Self>, app: &mut App, _cause: SelectionChangedCause) {
debug_assert!(!self.widget(app).obscure_text);
if self.widget(app).obscure_text {
return;
}
let value = self.value(app);
let text = value.selection.range().text_inside(&value.text);
if !text.is_empty()
&& let Some(services) = app.platform().text_services()
{
services.share(text);
}
}
fn start_live_text_input(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
if !self.live_text_input_enabled(app) {
return;
}
if self.has_input_connection(app) {
LiveText::start_live_text_input(app);
}
if cause == SelectionChangedCause::Toolbar {
TextSelectionDelegate::hide_toolbar(self, app, true);
}
}
pub fn button_items_for_toolbar_options(
self: Handle<Self>,
app: &mut App,
) -> Option<Vec<ContextMenuButtonItem>> {
let toolbar_options = self.widget(app).effective_toolbar_options();
if toolbar_options == ToolbarOptions::EMPTY {
return None;
}
let mut items = Vec::new();
if toolbar_options.cut && self.cut_enabled(app) {
items.push(
ContextMenuButtonItem::new(Some(Listener::handle_method(
self,
Self::cut_selection_from_toolbar,
)))
.r#type(ContextMenuButtonType::Cut),
);
}
if toolbar_options.copy && self.copy_enabled(app) {
items.push(
ContextMenuButtonItem::new(Some(Listener::handle_method(
self,
Self::copy_selection_from_toolbar,
)))
.r#type(ContextMenuButtonType::Copy),
);
}
if toolbar_options.paste && self.paste_enabled(app) {
items.push(
ContextMenuButtonItem::new(Some(Listener::handle_method(
self,
Self::paste_text_from_toolbar,
)))
.r#type(ContextMenuButtonType::Paste),
);
}
if toolbar_options.select_all && self.select_all_enabled(app) {
items.push(
ContextMenuButtonItem::new(Some(Listener::handle_method(
self,
Self::select_all_from_toolbar,
)))
.r#type(ContextMenuButtonType::SelectAll),
);
}
Some(items)
}
fn text_processing_action_button_items(
self: Handle<Self>,
app: &mut App,
) -> Vec<ContextMenuButtonItem> {
let mut button_items = Vec::new();
let value = self.value(app);
let selection = value.selection;
if self.widget(app).obscure_text || !selection.is_valid() || selection.is_collapsed() {
return button_items;
}
let actions = app.get(self).process_text_actions.clone();
let service = app.get(self).process_text_service.clone();
let read_only = self.widget(app).read_only;
let selected_text = selection.range().text_inside(&value.text).to_string();
for action in actions {
let selected_text = selected_text.clone();
let service = Rc::clone(&service);
let action_id = action.id.clone();
button_items.push(
ContextMenuButtonItem::new(Some(Listener::new(move |app| {
if selected_text.is_empty() {
return;
}
match service.process_text_action(app, &action_id, &selected_text, read_only) {
Some(processed) if self.allow_paste(app) => {
self.paste_text_content(
app,
SelectionChangedCause::Toolbar,
&processed,
);
}
_ => TextSelectionDelegate::hide_toolbar(self, app, true),
}
})))
.label(action.label.clone()),
);
}
button_items
}
fn allow_paste(self: Handle<Self>, app: &App) -> bool {
!self.widget(app).read_only && self.value(app).selection.is_valid()
}
fn paste_text_content(
self: Handle<Self>,
app: &mut App,
cause: SelectionChangedCause,
text: &str,
) {
if !self.allow_paste(app) {
return;
}
let value = self.value(app);
let last = value
.selection
.base_offset
.max(value.selection.extent_offset);
let collapsed = value
.copy_with()
.selection(TextSelection::collapsed(last, TextAffinity::Downstream));
self.user_update_text_editing_value(app, collapsed.replaced(value.selection, text), cause);
if cause == SelectionChangedCause::Toolbar {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::bring_selection_into_view_after_frame),
View::maybe_id_of(app, self.context(app)),
);
TextSelectionDelegate::hide_toolbar(self, app, true);
}
}
pub fn spell_check_configuration(self: Handle<Self>, app: &App) -> SpellCheckConfiguration {
app.get(self).spell_check_configuration.clone()
}
pub fn spell_check_enabled(self: Handle<Self>, app: &App) -> bool {
app.get(self)
.spell_check_configuration
.spell_check_enabled()
}
pub fn current_autofill_scope(
self: Handle<Self>,
app: &App,
) -> Option<Handle<AutofillGroupState>> {
app.get(self).current_autofill_scope
}
fn spell_check_results_received(self: Handle<Self>, app: &App) -> bool {
app.get(self)
.spell_check_results
.as_ref()
.is_some_and(|results| !results.suggestion_spans.is_empty())
}
pub fn cursor_currently_visible(self: Handle<Self>, app: &App) -> bool {
app.get(self)
.backing_cursor_blink_opacity_controller
.handle()
.is_some_and(|controller| controller.value(app) > 0.0)
}
pub fn cursor_blink_interval() -> Duration {
K_CURSOR_BLINK_HALF_PERIOD
}
pub fn request_keyboard(self: Handle<Self>, app: &mut App) {
if self.has_focus(app) {
self.open_input_connection(app);
} else {
app.get_mut(self).next_focus_change_is_internal = true;
let focus_node = self.widget(app).focus_node.handle();
focus_node.request_focus(app, None);
}
}
pub fn selection_overlay(
self: Handle<Self>,
app: &App,
) -> Option<Handle<TextSelectionOverlay>> {
app.get(self).selection_overlay.handle()
}
fn web_context_menu_enabled() -> bool {
K_IS_WEB
}
fn create_selection_overlay(self: Handle<Self>, app: &mut App) -> Ref<TextSelectionOverlay> {
let value = self.value(app);
let context = self.context(app);
let debug_required_for = context.widget(app).clone();
let toolbar_layer_link = self.toolbar_layer_link(app);
let start_handle_layer_link = self.start_handle_layer_link(app);
let end_handle_layer_link = self.end_handle_layer_link(app);
let render_object = self.render_editable(app);
let selection_delegate = self.as_text_selection_delegate();
let magnifier_configuration = self.widget(app).magnifier_configuration.clone();
let clipboard_status = app
.get(self)
.clipboard_status
.clone()
.expect("clipboardStatus is created in initState");
let drag_start_behavior = self.widget(app).drag_start_behavior;
let selection_controls = self.widget(app).selection_controls.clone();
let on_selection_handle_tapped = self.widget(app).on_selection_handle_tapped.clone();
let context_menu_builder = self.widget(app).context_menu_builder.clone();
let mut overlay = TextSelectionOverlay::new(
app,
value,
context,
toolbar_layer_link,
start_handle_layer_link,
end_handle_layer_link,
render_object,
selection_delegate,
magnifier_configuration,
)
.clipboard_status(app, clipboard_status)
.debug_required_for(app, debug_required_for)
.drag_start_behavior(app, drag_start_behavior);
if let Some(controls) = selection_controls {
overlay = overlay.selection_controls(app, controls);
}
if let Some(on_tapped) = on_selection_handle_tapped {
overlay = overlay.on_selection_handle_tapped(app, on_tapped);
}
if !Self::web_context_menu_enabled()
&& let Some(builder) = context_menu_builder
{
let this = self;
let widget_builder: WidgetBuilder =
Rc::new(move |app, context| builder(app, context, this));
overlay = overlay.context_menu_builder(app, widget_builder);
}
overlay
}
fn update_or_dispose_selection_overlay_if_needed(self: Handle<Self>, app: &mut App) {
if let Some(overlay) = app.get(self).selection_overlay.handle() {
if self.has_focus(app) {
overlay.update(app, self.value(app));
} else {
overlay.dispose(app);
app.get_mut(self).selection_overlay = None;
}
}
}
fn get_offset_to_reveal_caret(self: Handle<Self>, app: &mut App, rect: Rect) -> RevealedOffset {
let scroll_controller = self.scroll_controller(app);
let position = scroll_controller.position(app);
if !position.allow_implicit_scrolling(app) {
return RevealedOffset::new(scroll_controller.offset(app), rect);
}
let editable_size = self.render_editable(app).size(app);
let (additional_offset, unit_offset, reveal_rect) = if !self.is_multiline(app) {
let additional = if rect.width() >= editable_size.width() {
editable_size.width() / 2.0 - rect.center().dx()
} else {
clamp_double(0.0, rect.right - editable_size.width(), rect.left)
};
(additional, Offset::new(1.0, 0.0), rect)
} else {
let expanded = Rect::from_center(
rect.center(),
rect.width(),
rect.height()
.max(self.render_editable(app).preferred_line_height(app)),
);
let additional = if expanded.height() >= editable_size.height() {
editable_size.height() / 2.0 - expanded.center().dy()
} else {
clamp_double(0.0, expanded.bottom - editable_size.height(), expanded.top)
};
(additional, Offset::new(0.0, 1.0), expanded)
};
let target_offset = clamp_double(
additional_offset + scroll_controller.offset(app),
position.min_scroll_extent(app),
position.max_scroll_extent(app),
);
let offset_delta = scroll_controller.offset(app) - target_offset;
RevealedOffset::new(target_offset, reveal_rect.shift(unit_offset * offset_delta))
}
fn bring_selection_into_view_after_frame(
self: Handle<Self>,
app: &mut App,
_time_stamp: Duration,
) {
if !self.mounted(app) {
return;
}
self.bring_into_view(app, self.value(app).selection.extent());
}
pub fn bring_into_view(self: Handle<Self>, app: &mut App, position: TextPosition) {
let local_rect = self
.render_editable(app)
.get_local_rect_for_caret(app, position);
let target_offset = self.get_offset_to_reveal_caret(app, local_rect);
self.scroll_controller(app)
.jump_to(app, target_offset.offset);
self.render_editable(app).show_on_screen(
app,
None,
Some(target_offset.rect),
Duration::ZERO,
Curves::ease(),
);
}
pub fn show_toolbar(self: Handle<Self>, app: &mut App) -> bool {
if Self::web_context_menu_enabled() {
return false;
}
let Some(overlay) = app.get(self).selection_overlay.handle() else {
return false;
};
if overlay.toolbar_is_visible(app) {
return false;
}
if let Some(status) = app.get(self).live_text_input_status.handle() {
status.update(app);
}
self.clipboard_status(app).update(app);
overlay.show_toolbar(app);
true
}
pub fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
if hide_handles {
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.hide(app);
}
} else if let Some(overlay) = app.get(self).selection_overlay.handle()
&& overlay.toolbar_is_visible(app)
{
overlay.hide_toolbar(app);
}
}
pub fn toggle_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
if app.get(self).selection_overlay.is_none() {
let overlay = self.create_selection_overlay(app);
app.get_mut(self).selection_overlay = Some(overlay);
}
let overlay = app
.get(self)
.selection_overlay
.handle()
.expect("created above");
if overlay.toolbar_is_visible(app) {
self.hide_toolbar(app, hide_handles);
} else {
let _ = self.show_toolbar(app);
}
}
pub fn show_spell_check_suggestions_toolbar(self: Handle<Self>, app: &mut App) -> bool {
if !self.spell_check_enabled(app)
|| Self::web_context_menu_enabled()
|| self.widget(app).read_only
|| app.get(self).selection_overlay.is_none()
|| !self.spell_check_results_received(app)
|| self
.find_suggestion_span_at_cursor_index(app, self.value(app).selection.extent_offset)
.is_none()
{
return false;
}
debug_assert!(
app.get(self)
.spell_check_configuration
.spell_check_suggestions_toolbar_builder
.is_some(),
"spellCheckSuggestionsToolbarBuilder must be defined in SpellCheckConfiguration to show a toolbar with spell check suggestions"
);
let Some(builder) = app
.get(self)
.spell_check_configuration
.spell_check_suggestions_toolbar_builder
.clone()
else {
return false;
};
let this = self;
let overlay = app
.get(self)
.selection_overlay
.handle()
.expect("checked above");
overlay.show_spell_check_suggestions_toolbar(
app,
Rc::new(move |app, context| builder(app, context, this)),
);
true
}
pub fn show_magnifier(self: Handle<Self>, app: &mut App, position_to_show: Offset) {
let Some(overlay) = app.get(self).selection_overlay.handle() else {
return;
};
if overlay.magnifier_exists(app) {
overlay.update_magnifier(app, position_to_show);
} else {
overlay.show_magnifier(app, position_to_show);
}
}
pub fn hide_magnifier(self: Handle<Self>, app: &mut App) {
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.hide_magnifier(app);
}
}
pub fn find_suggestion_span_at_cursor_index(
self: Handle<Self>,
app: &App,
cursor_index: i32,
) -> Option<SuggestionSpan> {
if !self.spell_check_results_received(app) {
return None;
}
let results = app.get(self).spell_check_results.as_ref()?;
if results.suggestion_spans.last()?.range.end < cursor_index {
return None;
}
let suggestion_spans = &results.suggestion_spans;
let mut left_index: i32 = 0;
let mut right_index = suggestion_spans.len() as i32 - 1;
while left_index <= right_index {
let mid_index = (left_index + right_index).div_euclid(2) as usize;
let current_span_start = suggestion_spans[mid_index].range.start;
let current_span_end = suggestion_spans[mid_index].range.end;
if cursor_index <= current_span_end && cursor_index >= current_span_start {
return Some(suggestion_spans[mid_index].clone());
} else if cursor_index <= current_span_start {
right_index = mid_index as i32 - 1;
} else {
left_index = mid_index as i32 + 1;
}
}
None
}
fn post_frame_rebuild_toolbar(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
if self.mounted(app)
&& let Some(overlay) = app.get(self).selection_overlay.handle()
&& overlay.toolbar_is_visible(app)
{
overlay.show_toolbar(app);
}
}
fn post_frame_update_for_scroll(self: Handle<Self>, app: &mut App, _time_stamp: Duration) {
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.update_for_scroll(app);
}
}
pub fn begin_batch_edit(self: Handle<Self>, app: &mut App) {
app.get_mut(self).batch_edit_depth += 1;
}
pub fn end_batch_edit(self: Handle<Self>, app: &mut App) {
app.get_mut(self).batch_edit_depth -= 1;
debug_assert!(
app.get(self).batch_edit_depth >= 0,
"Unbalanced call to endBatchEdit: beginBatchEdit must be called first."
);
self.update_remote_editing_value_if_needed(app);
}
pub fn build_text_span(self: Handle<Self>, app: &mut App, context: BuildContext) -> TextSpan {
let widget = self.widget(app);
let obscure_text = widget.obscure_text;
let obscuring_character = widget.obscuring_character.clone();
let read_only = widget.read_only;
let controller = widget.controller.handle();
let style = app.get(self).style.clone();
let value = self.value(app);
if obscure_text {
let mut text: Vec<u16> = obscuring_character
.encode_utf16()
.cycle()
.take(value.text.encode_utf16().count())
.collect();
let mobile_platforms = [
TargetPlatform::Android,
TargetPlatform::Fuchsia,
TargetPlatform::IOS,
];
let platform = app.platform();
let briefly_show_password = platform.briefly_show_password()
&& mobile_platforms.contains(&platform.target_platform());
if briefly_show_password {
let o = if app.get(self).obscure_show_char_ticks_pending > 0 {
app.get(self).obscure_latest_char_index
} else {
None
};
if let Some(o) = o.and_then(|o| usize::try_from(o).ok())
&& o < text.len()
{
text[o] = value.text.encode_utf16().nth(o).expect("o < text.length");
}
}
return TextSpan::new()
.style(style)
.text(String::from_utf16_lossy(&text));
}
let with_composing = !read_only && self.has_focus(app);
if self.spell_check_results_received(app) {
debug_assert!(
!value.composing.is_valid() || !with_composing || value.is_composing_range_valid()
);
let composing_region_out_of_range =
!value.is_composing_range_valid() || !with_composing;
let misspelled = app
.get(self)
.spell_check_configuration
.misspelled_text_style
.clone()
.expect("spell check results require misspelledTextStyle");
let results = app
.get(self)
.spell_check_results
.clone()
.expect("spellCheckResultsReceived");
return build_text_span_with_spell_check_suggestions(
app,
&value,
composing_region_out_of_range,
Some(&style),
&misspelled,
&results,
);
}
controller.build_text_span(app, context, Some(style), with_composing)
}
fn value(self: Handle<Self>, app: &App) -> TextEditingValue {
self.widget(app).controller.value(app).clone()
}
fn set_value(self: Handle<Self>, app: &mut App, value: TextEditingValue) {
self.widget(app).controller.set_value(app, value);
}
fn is_multiline(self: Handle<Self>, app: &App) -> bool {
self.widget(app).max_lines != Some(1)
}
fn text_direction(self: Handle<Self>, app: &mut App, context: BuildContext) -> TextDirection {
self.widget(app)
.text_direction
.unwrap_or_else(|| Directionality::of(app, context))
}
fn stylus_handwriting_enabled(self: Handle<Self>, app: &App) -> bool {
if !self.widget(app).scribble_enabled {
return self.widget(app).scribble_enabled;
}
self.widget(app).stylus_handwriting_enabled
}
fn has_input_connection(self: Handle<Self>, app: &mut App) -> bool {
app.get(self)
.text_input_connection
.handle()
.is_some_and(|connection| connection.attached(app))
}
fn should_create_input_connection(self: Handle<Self>, app: &App) -> bool {
K_IS_WEB
|| app.platform().target_platform() == TargetPlatform::MacOS
|| !self.widget(app).read_only
}
fn scroll_controller(self: Handle<Self>, app: &mut App) -> ScrollControllerRef {
if let Some(controller) = self.widget(app).scroll_controller.clone() {
return controller;
}
if let Some(controller) = &app.get(self).internal_scroll_controller {
return controller.erase();
}
let controller = ScrollController::default(app);
app.get_mut(self).internal_scroll_controller = Some(controller.clone());
controller.into_erased()
}
fn cursor_visibility_notifier(self: Handle<Self>, app: &App) -> Handle<ValueNotifier<bool>> {
app.get(self)
.cursor_visibility_notifier
.handle()
.expect("created in initState")
}
fn start_handle_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
app.get(self)
.start_handle_layer_link
.clone()
.expect("created in initState")
}
fn end_handle_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
app.get(self)
.end_handle_layer_link
.clone()
.expect("created in initState")
}
fn toolbar_layer_link(self: Handle<Self>, app: &App) -> Ref<LayerLink> {
app.get(self)
.toolbar_layer_link
.clone()
.expect("created in initState")
}
fn cursor_blink_opacity_controller(
self: Handle<Self>,
app: &mut App,
) -> Handle<AnimationController> {
if let Some(controller) = app
.get(self)
.backing_cursor_blink_opacity_controller
.handle()
{
return controller;
}
let controller = AnimationController::new(
app,
None,
None,
None,
0.0,
1.0,
AnimationBehavior::Normal,
self,
);
controller.add_listener(
app,
Listener::handle_method(self, Self::on_cursor_color_tick),
);
let handle = controller.handle();
app.get_mut(self).backing_cursor_blink_opacity_controller = Some(controller);
handle
}
fn observer(self: Handle<Self>, app: &mut App) -> WidgetsBindingObserverRef {
if let Some(observer) = app.get(self).binding_observer.clone() {
return observer;
}
let observer: WidgetsBindingObserverRef = Rc::new(self);
app.get_mut(self).binding_observer = Some(observer.clone());
observer
}
fn effective_autofill_client(self: Handle<Self>, app: &App) -> AnyAutofillClient {
self.widget(app)
.autofill_client
.unwrap_or_else(|| self.as_autofill_client())
}
fn cursor_color(self: Handle<Self>, app: &mut App) -> Color {
let cursor_color = self.widget(app).cursor_color;
let opacity = cursor_color
.a
.min(self.cursor_blink_opacity_controller(app).value(app));
cursor_color.with_alpha((255.0 * opacity).round() as i32)
}
fn has_focus(self: Handle<Self>, app: &mut App) -> bool {
self.widget(app).focus_node.has_focus(app)
}
fn show_blinking_cursor(self: Handle<Self>, app: &mut App) -> bool {
self.has_focus(app)
&& self.value(app).selection.is_collapsed()
&& self.widget(app).effective_show_cursor()
&& app.get(self).tickers_enabled
}
fn init_process_text_actions(self: Handle<Self>, app: &mut App) {
let actions = app.get(self).process_text_service.query_text_actions(app);
app.get_mut(self).process_text_actions.clear();
app.get_mut(self).process_text_actions.extend(actions);
}
fn on_resume(self: Handle<Self>, app: &mut App) {
app.get_mut(self).just_resumed = true;
let manager = FocusManager::instance(app);
manager.remove_listener(
app,
&Listener::handle_method(self, Self::reset_just_resumed),
);
manager.add_listener(app, Listener::handle_method(self, Self::reset_just_resumed));
}
fn reset_just_resumed(self: Handle<Self>, app: &mut App) {
app.get_mut(self).just_resumed = false;
FocusManager::instance(app).remove_listener(
app,
&Listener::handle_method(self, Self::reset_just_resumed),
);
}
fn on_tap_outside(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: PointerDownEvent,
) {
app.get_mut(self).had_focus_on_tap_down = true;
if let Some(on_tap_outside) = self.widget(app).on_tap_outside.clone() {
on_tap_outside(app, event);
} else {
self.default_on_tap_outside(app, context, event);
}
}
fn on_tap_up_outside(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: PointerUpEvent,
) {
if !app.get(self).had_focus_on_tap_down {
return;
}
app.get_mut(self).had_focus_on_tap_down = false;
if let Some(on_tap_up_outside) = self.widget(app).on_tap_up_outside.clone() {
on_tap_up_outside(app, event);
} else {
self.default_on_tap_up_outside(app, context, event);
}
}
fn default_on_tap_outside(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: PointerDownEvent,
) {
let focus_node = self.widget(app).focus_node.erase();
Actions::invoke(
app,
context,
&EditableTextTapOutsideIntent::new(focus_node, event),
);
}
fn default_on_tap_up_outside(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
event: PointerUpEvent,
) {
let focus_node = self.widget(app).focus_node.erase();
Actions::invoke(
app,
context,
&EditableTextTapUpOutsideIntent::new(focus_node, event),
);
}
fn invoke_tap_outside(app: &mut App, intent: &EditableTextTapOutsideIntent) {
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {
match intent.pointer_down_event.kind {
PointerDeviceKind::Touch => {
if K_IS_WEB {
intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
}
}
PointerDeviceKind::Mouse
| PointerDeviceKind::Stylus
| PointerDeviceKind::InvertedStylus
| PointerDeviceKind::Unknown => {
intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
}
PointerDeviceKind::Trackpad => {
unimplemented!("Unexpected pointer down event for trackpad");
}
}
}
TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
intent.focus_node.unfocus(app, UnfocusDisposition::Scope);
}
}
}
fn character_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
let text = self.value(app).text;
if self.widget(app).obscure_text {
Box::new(CodePointBoundary::new(text))
} else {
Box::new(CharacterBoundary::new(text))
}
}
fn next_word_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
if self.widget(app).obscure_text {
self.document_boundary(app)
} else {
self.render_editable(app)
.word_boundaries(app)
.move_by_word_boundary()
}
}
fn linebreak(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
if self.widget(app).obscure_text {
self.document_boundary(app)
} else {
Box::new(LineBoundary::new(self.render_editable(app)))
}
}
fn paragraph_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
Box::new(ParagraphBoundary::new(&self.value(app).text))
}
fn document_boundary(self: Handle<Self>, app: &mut App) -> Box<dyn TextBoundary> {
Box::new(DocumentBoundary::new(self.value(app).text))
}
fn move_beyond_text_boundary(
self: Handle<Self>,
app: &mut App,
extent: TextPosition,
forward: bool,
text_boundary: &dyn TextBoundary,
) -> TextPosition {
debug_assert!(extent.offset >= 0);
let text_length = utf16_len(&self.value(app).text);
let new_offset = if forward {
text_boundary
.get_trailing_text_boundary_at(app, extent.offset)
.unwrap_or(text_length)
} else {
text_boundary
.get_leading_text_boundary_at(app, extent.offset - 1)
.unwrap_or(0)
};
TextPosition::new(new_offset)
}
fn move_to_text_boundary(
self: Handle<Self>,
app: &mut App,
extent: TextPosition,
forward: bool,
text_boundary: &dyn TextBoundary,
) -> TextPosition {
debug_assert!(extent.offset >= 0);
let caret_offset = match extent.affinity {
TextAffinity::Upstream => {
if extent.offset < 1 && !forward {
debug_assert!(extent.offset == 0);
return TextPosition::new(0);
}
(extent.offset - 1).max(0)
}
TextAffinity::Downstream => extent.offset,
};
let text_length = utf16_len(&self.value(app).text);
if forward {
TextPosition::with_affinity(
text_boundary
.get_trailing_text_boundary_at(app, caret_offset)
.unwrap_or(text_length),
TextAffinity::Upstream,
)
} else {
TextPosition::new(
text_boundary
.get_leading_text_boundary_at(app, caret_offset)
.unwrap_or(0),
)
}
}
fn transpose_characters(self: Handle<Self>, app: &mut App) {
let value = self.value(app);
let text = value.text.clone();
let selection = value.selection;
let text_length = utf16_len(&text);
let boundary = CharacterBoundary::new(text.clone());
let single_character = boundary
.get_trailing_text_boundary_at(app, 0)
.is_none_or(|end| end >= text_length);
if single_character || !selection.is_collapsed() || selection.base_offset == 0 {
return;
}
let at_end = selection.base_offset == text_length;
let (start, middle, end) = if at_end {
let middle = boundary
.get_leading_text_boundary_at(app, text_length - 1)
.unwrap_or(0);
let start = boundary
.get_leading_text_boundary_at(app, middle - 1)
.unwrap_or(0);
(start, middle, text_length)
} else {
let start = boundary
.get_leading_text_boundary_at(app, selection.base_offset - 1)
.unwrap_or(0);
let end = boundary
.get_trailing_text_boundary_at(app, selection.base_offset)
.unwrap_or(text_length);
(start, selection.base_offset, end)
};
let transposing = TextRange::new(start, end);
let first = TextRange::new(start, middle).text_inside(&text);
let second = TextRange::new(middle, end).text_inside(&text);
let value = TextEditingValue::new()
.text(format!(
"{}{second}{first}{}",
transposing.text_before(&text),
transposing.text_after(&text)
))
.selection(TextSelection::collapsed(end, TextAffinity::Downstream));
self.user_update_text_editing_value(app, value, SelectionChangedCause::Keyboard);
}
fn replace_text(self: Handle<Self>, app: &mut App, intent: &ReplaceTextIntent) {
let old_value = self.value(app);
let new_value = intent
.current_text_editing_value
.replaced(intent.replacement_range, &intent.replacement_text);
self.user_update_text_editing_value(app, new_value.clone(), intent.cause);
if new_value == old_value {
self.did_change_text_editing_value(app);
}
}
fn scroll_to_document_boundary(
self: Handle<Self>,
app: &mut App,
intent: &ScrollToDocumentBoundaryIntent,
) {
if intent.forward {
let offset = utf16_len(&self.value(app).text);
self.bring_into_view(app, TextPosition::new(offset));
} else {
self.bring_into_view(app, TextPosition::new(0));
}
}
fn scroll(self: Handle<Self>, app: &mut App, intent: &ScrollIntent) {
if intent.r#type != ScrollIncrementType::Page {
return;
}
let controller = self.scroll_controller(app);
let position = controller.position(app);
if self.widget(app).max_lines == Some(1) {
let max = position.max_scroll_extent(app);
controller.jump_to(app, max);
return;
}
if position.max_scroll_extent(app) == 0.0 && position.min_scroll_extent(app) == 0.0 {
return;
}
let key = app.get(self).scrollable_key.clone();
let state = key
.current_state::<ScrollableState>(app)
.expect("EditableText mounts a Scrollable");
let increment = ScrollAction::get_directional_increment(app, state, intent);
let destination = (position.pixels(app) + increment).clamp(
position.min_scroll_extent(app),
position.max_scroll_extent(app),
);
if destination == position.pixels(app) {
return;
}
controller.jump_to(app, destination);
}
fn update_selection(self: Handle<Self>, app: &mut App, intent: &UpdateSelectionIntent) {
debug_assert!(
intent.new_selection.start() <= utf16_len(&intent.current_text_editing_value.text),
"invalid selection: it must not exceed the current text length"
);
debug_assert!(
intent.new_selection.end() <= utf16_len(&intent.current_text_editing_value.text),
"invalid selection: it must not exceed the current text length"
);
self.bring_into_view(app, intent.new_selection.extent());
let value = intent
.current_text_editing_value
.clone()
.copy_with()
.selection(intent.new_selection);
self.user_update_text_editing_value(app, value, intent.cause);
}
fn text_editing_value_for_text_layout_metrics(
self: Handle<Self>,
app: &mut App,
) -> TextEditingValue {
let key = app.get(self).editable_key.clone();
let widget = key.current_widget(app).expect("Editable must be mounted");
widget
.as_any()
.downcast_ref::<Editable>()
.expect("Editable must be mounted")
.value
.clone()
}
fn hide_toolbar_if_visible(self: Handle<Self>, app: &mut App) -> Option<Rc<dyn Any>> {
if app
.get(self)
.selection_overlay
.handle()
.is_some_and(|overlay| overlay.toolbar_is_visible(app))
{
self.hide_toolbar(app, false);
return None;
}
let context = self.context(app);
Actions::invoke(app, context, &DismissIntent)
}
fn stop_current_vertical_run_if_selection_changes(self: Handle<Self>, app: &mut App) {
let Some(run_selection) = app.get(self).run_selection else {
debug_assert!(app.get(self).vertical_movement_run.is_none());
return;
};
app.get_mut(self).run_selection = Some(self.value(app).selection);
let current_selection = self.widget(app).controller.selection(app);
let continue_current_run = current_selection.is_valid()
&& current_selection.is_collapsed()
&& current_selection.base_offset == run_selection.base_offset
&& current_selection.extent_offset == run_selection.extent_offset;
if !continue_current_run {
app.get_mut(self).vertical_movement_run = None;
app.get_mut(self).run_selection = None;
}
}
fn ensure_actions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> HashMap<TypeId, ActionRef> {
if let Some(actions) = app.get(self).actions.clone() {
return actions;
}
let mut actions: HashMap<TypeId, ActionRef> = HashMap::new();
let do_nothing = DoNothingAction::new(app);
do_nothing.set_consumes_key(app, false);
actions.insert(
TypeId::of::<DoNothingAndStopPropagationTextIntent>(),
do_nothing.into_erased(),
);
let replace_text = CallbackAction::<ReplaceTextIntent>::new(
app,
Rc::new(move |app, intent| {
self.replace_text(app, intent);
None
}),
);
actions.insert(
TypeId::of::<ReplaceTextIntent>(),
replace_text.into_erased(),
);
let update_selection = CallbackAction::<UpdateSelectionIntent>::new(
app,
Rc::new(move |app, intent| {
self.update_selection(app, intent);
None
}),
);
actions.insert(
TypeId::of::<UpdateSelectionIntent>(),
update_selection.into_erased(),
);
let directional_focus = DirectionalFocusAction::for_text_field(app);
actions.insert(
TypeId::of::<DirectionalFocusIntent>(),
directional_focus.into_erased(),
);
let dismiss = CallbackAction::<DismissIntent>::new(
app,
Rc::new(move |app, _intent| self.hide_toolbar_if_visible(app)),
);
actions.insert(TypeId::of::<DismissIntent>(), dismiss.into_erased());
let delete_character = DeleteTextAction::<DeleteCharacterIntent>::new(
app,
self,
EditableTextState::character_boundary,
EditableTextState::move_beyond_text_boundary,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<DeleteCharacterIntent>(),
delete_character.into_erased(),
);
let delete_word = DeleteTextAction::<DeleteToNextWordBoundaryIntent>::new(
app,
self,
EditableTextState::next_word_boundary,
EditableTextState::move_beyond_text_boundary,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<DeleteToNextWordBoundaryIntent>(),
delete_word.into_erased(),
);
let delete_to_line_break = DeleteTextAction::<DeleteToLineBreakIntent>::new(
app,
self,
EditableTextState::linebreak,
EditableTextState::move_to_text_boundary,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<DeleteToLineBreakIntent>(),
delete_to_line_break.into_erased(),
);
let by_character = UpdateTextSelectionAction::<ExtendSelectionByCharacterIntent>::new(
app,
self,
EditableTextState::character_boundary,
EditableTextState::move_beyond_text_boundary,
false,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionByCharacterIntent>(),
by_character.into_erased(),
);
let by_word = UpdateTextSelectionAction::<ExtendSelectionToNextWordBoundaryIntent>::new(
app,
self,
EditableTextState::next_word_boundary,
EditableTextState::move_beyond_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToNextWordBoundaryIntent>(),
by_word.into_erased(),
);
let by_paragraph =
UpdateTextSelectionAction::<ExtendSelectionToNextParagraphBoundaryIntent>::new(
app,
self,
EditableTextState::paragraph_boundary,
EditableTextState::move_beyond_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToNextParagraphBoundaryIntent>(),
by_paragraph.into_erased(),
);
let to_line_break = UpdateTextSelectionAction::<ExtendSelectionToLineBreakIntent>::new(
app,
self,
EditableTextState::linebreak,
EditableTextState::move_to_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToLineBreakIntent>(),
to_line_break.into_erased(),
);
let by_line = UpdateTextSelectionVerticallyAction::<
ExtendSelectionVerticallyToAdjacentLineIntent,
>::new(app, self, false);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionVerticallyToAdjacentLineIntent>(),
by_line.into_erased(),
);
let by_page = UpdateTextSelectionVerticallyAction::<
ExtendSelectionVerticallyToAdjacentPageIntent,
>::new(app, self, true);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionVerticallyToAdjacentPageIntent>(),
by_page.into_erased(),
);
let by_paragraph_or_caret = UpdateTextSelectionAction::<
ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent,
>::new(
app,
self,
EditableTextState::paragraph_boundary,
EditableTextState::move_beyond_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent>(),
by_paragraph_or_caret.into_erased(),
);
let to_document = UpdateTextSelectionAction::<ExtendSelectionToDocumentBoundaryIntent>::new(
app,
self,
EditableTextState::document_boundary,
EditableTextState::move_beyond_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToDocumentBoundaryIntent>(),
to_document.into_erased(),
);
let by_word_or_caret = UpdateTextSelectionAction::<
ExtendSelectionToNextWordBoundaryOrCaretLocationIntent,
>::new(
app,
self,
EditableTextState::next_word_boundary,
EditableTextState::move_beyond_text_boundary,
true,
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExtendSelectionToNextWordBoundaryOrCaretLocationIntent>(),
by_word_or_caret.into_erased(),
);
let scroll_to_boundary =
WebComposingDisablingCallbackAction::<ScrollToDocumentBoundaryIntent>::new(
app,
self,
Rc::new(move |app, intent| {
self.scroll_to_document_boundary(app, intent);
None
}),
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ScrollToDocumentBoundaryIntent>(),
scroll_to_boundary.into_erased(),
);
let scroll = CallbackAction::<ScrollIntent>::new(
app,
Rc::new(move |app, intent| {
self.scroll(app, intent);
None
}),
);
actions.insert(TypeId::of::<ScrollIntent>(), scroll.into_erased());
let expand_to_line_break =
UpdateTextSelectionAction::<ExpandSelectionToLineBreakIntent>::new(
app,
self,
EditableTextState::linebreak,
EditableTextState::move_to_text_boundary,
true,
)
.expanding(app, false);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExpandSelectionToLineBreakIntent>(),
expand_to_line_break.into_erased(),
);
let expand_to_document =
UpdateTextSelectionAction::<ExpandSelectionToDocumentBoundaryIntent>::new(
app,
self,
EditableTextState::document_boundary,
EditableTextState::move_to_text_boundary,
true,
)
.expanding(app, true);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<ExpandSelectionToDocumentBoundaryIntent>(),
expand_to_document.into_erased(),
);
let select_all = SelectAllAction::new(app, self);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<SelectAllTextIntent>(),
select_all.into_erased(),
);
let copy = CopySelectionAction::new(app, self);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<CopySelectionTextIntent>(),
copy.into_erased(),
);
let paste = PasteSelectionAction::new(app, self);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<PasteTextIntent>(),
paste.into_erased(),
);
let transpose = CallbackAction::<TransposeCharactersIntent>::new(
app,
Rc::new(move |app, _intent| {
self.transpose_characters(app);
None
}),
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<TransposeCharactersIntent>(),
transpose.into_erased(),
);
let tap_outside = CallbackAction::<EditableTextTapOutsideIntent>::new(
app,
Rc::new(|app, intent| {
Self::invoke_tap_outside(app, intent);
None
}),
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<EditableTextTapOutsideIntent>(),
tap_outside.into_erased(),
);
let tap_up_outside = CallbackAction::<EditableTextTapUpOutsideIntent>::new(
app,
Rc::new(|_app, _intent| None),
);
insert_overridable(
app,
&mut actions,
context,
TypeId::of::<EditableTextTapUpOutsideIntent>(),
tap_up_outside.into_erased(),
);
app.get_mut(self).actions = Some(actions.clone());
actions
}
fn on_changed_clipboard_status(self: Handle<Self>, app: &mut App) {
self.set_state(app, |_| {});
}
fn on_changed_live_text_input_status(self: Handle<Self>, app: &mut App) {
self.set_state(app, |_| {});
}
fn did_change_text_editing_value(self: Handle<Self>, app: &mut App) {
if self.has_focus(app) && !self.value(app).selection.is_valid() {
let controller = self.widget(app).controller.handle();
controller.remove_listener(
app,
&Listener::handle_method(self, Self::did_change_text_editing_value),
);
if let Some(selection) = self.adjusted_selection_when_focused(app) {
controller.set_selection(app, selection);
}
controller.add_listener(
app,
Listener::handle_method(self, Self::did_change_text_editing_value),
);
}
self.update_remote_editing_value_if_needed(app);
self.start_or_stop_cursor_timer_if_needed(app);
self.update_or_dispose_selection_overlay_if_needed(app);
self.set_state(app, |_| {});
self.stop_current_vertical_run_if_selection_changes(app);
}
fn handle_focus_changed(self: Handle<Self>, app: &mut App) {
let has_focus = self.widget(app).focus_node.has_focus(app);
app.get_mut(self).has_focus = has_focus;
self.open_or_close_input_connection_if_needed(app);
self.start_or_stop_cursor_timer_if_needed(app);
self.update_or_dispose_selection_overlay_if_needed(app);
if has_focus {
let observer = self.observer(app);
if !app.get(self).registered_as_observer {
WidgetsBinding::instance(app).add_observer(app, observer);
app.get_mut(self).registered_as_observer = true;
}
app.get_mut(self).last_bottom_view_inset = self.bottom_view_inset(app);
if !self.widget(app).read_only {
self.schedule_show_caret_on_screen(app, true);
}
let updated = self.adjusted_selection_when_focused(app);
if let Some(selection) = updated {
self.handle_selection_changed(app, selection, None);
}
} else if app.get(self).registered_as_observer {
let observer = self.observer(app);
WidgetsBinding::instance(app).remove_observer(app, &observer);
app.get_mut(self).registered_as_observer = false;
self.set_state(app, |state| {
state.current_prompt_rect_range = None;
});
}
AutomaticKeepAliveClientMixin::update_keep_alive(self, app);
}
fn adjusted_selection_when_focused(self: Handle<Self>, app: &mut App) -> Option<TextSelection> {
let widget = self.widget(app);
let should_select_all = widget.effective_select_all_on_focus(app)
&& widget.effective_enable_interactive_selection()
&& !self.is_multiline(app)
&& !app.get(self).next_focus_change_is_internal
&& !app.get(self).just_resumed;
app.get_mut(self).just_resumed = false;
app.get_mut(self).next_focus_change_is_internal = false;
let value = self.value(app);
if should_select_all {
Some(TextSelection::new(0, utf16_len(&value.text)))
} else if !value.selection.is_valid() {
Some(TextSelection::collapsed(
utf16_len(&value.text),
TextAffinity::Downstream,
))
} else {
None
}
}
fn update_remote_editing_value_if_needed(self: Handle<Self>, app: &mut App) {
if app.get(self).batch_edit_depth > 0 || !self.has_input_connection(app) {
return;
}
let local_value = self.value(app);
if app.get(self).last_known_remote_text_editing_value.as_ref() == Some(&local_value) {
return;
}
let connection = app
.get(self)
.text_input_connection
.handle()
.expect("attached");
connection.set_editing_state(app, local_value.clone());
app.get_mut(self).last_known_remote_text_editing_value = Some(local_value);
}
fn get_text_input_style(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> TextInputStyle {
let style = app.get(self).style.clone();
let text_direction = self.text_direction(app, context);
let text_align = self.widget(app).text_align;
let letter_spacing =
MediaQuery::maybe_letter_spacing_override_of(app, context).or(style.letter_spacing);
let word_spacing =
MediaQuery::maybe_word_spacing_override_of(app, context).or(style.word_spacing);
let mut input_style = TextInputStyle::new(text_direction, text_align);
input_style.font_family = style.font_family.clone();
input_style.font_size = style.font_size;
input_style.font_weight = style.font_weight;
input_style.letter_spacing = letter_spacing;
input_style.word_spacing = word_spacing;
input_style
}
fn open_input_connection(self: Handle<Self>, app: &mut App) {
if !self.should_create_input_connection(app) {
return;
}
if !self.has_input_connection(app) {
let local_value = self.value(app);
let config = self
.effective_autofill_client(app)
.text_input_configuration(app);
let connection = TextInput::attach(app, self.as_text_input_client(), config);
app.get_mut(self).text_input_connection = Some(connection.clone());
self.update_size_and_transform(app);
self.schedule_periodic_post_frame_callbacks(app, Duration::ZERO);
if let Some(context) = self.mounted(app).then(|| self.context(app)) {
let style = self.get_text_input_style(app, context);
connection.update_style(app, style);
}
connection.set_editing_state(app, local_value.clone());
connection.show(app);
app.get_mut(self).last_known_remote_text_editing_value = Some(local_value);
} else if let Some(connection) = app.get(self).text_input_connection.handle() {
connection.show(app);
}
}
fn close_input_connection_if_needed(self: Handle<Self>, app: &mut App) {
if self.has_input_connection(app) {
if let Some(connection) = app.get(self).text_input_connection.handle() {
connection.close(app);
}
app.get_mut(self).text_input_connection = None;
app.get_mut(self).last_known_remote_text_editing_value = None;
app.get_mut(self).scribble_cache_key = None;
}
}
fn open_or_close_input_connection_if_needed(self: Handle<Self>, app: &mut App) {
let has_focus = self.has_focus(app);
let focus_node = self.widget(app).focus_node.handle();
if has_focus && focus_node.consume_keyboard_token(app) {
self.open_input_connection(app);
} else if !has_focus {
self.close_input_connection_if_needed(app);
let controller = self.widget(app).controller.handle();
controller.clear_composing(app);
}
}
fn check_needs_adjust_affinity(
self: Handle<Self>,
app: &App,
value: &TextEditingValue,
) -> bool {
let current = self.value(app);
value.text == current.text
&& value.selection.is_collapsed() == current.selection.is_collapsed()
&& value.selection.start() == current.selection.start()
&& value.selection.affinity != current.selection.affinity
}
fn format_and_set_value(
self: Handle<Self>,
app: &mut App,
mut value: TextEditingValue,
cause: Option<SelectionChangedCause>,
user_interaction: bool,
) {
let old_value = self.value(app);
let text_changed = old_value.text != value.text;
let text_committed = !old_value.composing.is_collapsed() && value.composing.is_collapsed();
let selection_changed = old_value.selection != value.selection;
if text_changed || text_committed {
let current = self.value(app);
for formatter in self.widget(app).effective_input_formatters() {
value = formatter.format_edit_update(¤t, &value);
}
}
let old_selection = self.value(app).selection;
self.begin_batch_edit(app);
self.set_value(app, value.clone());
if selection_changed
|| (user_interaction
&& matches!(
cause,
Some(SelectionChangedCause::LongPress | SelectionChangedCause::Keyboard)
))
{
self.handle_selection_changed(app, value.selection, cause);
self.bring_into_view_by_selection_state(app, old_selection, value.selection, cause);
}
let current_text = self.value(app).text.clone();
if old_value.text != current_text
&& let Some(on_changed) = self.widget(app).on_changed.clone()
{
on_changed(app, current_text);
}
self.end_batch_edit(app);
}
fn bring_into_view_by_selection_state(
self: Handle<Self>,
app: &mut App,
old_selection: TextSelection,
new_selection: TextSelection,
cause: Option<SelectionChangedCause>,
) {
match app.platform().target_platform() {
TargetPlatform::IOS | TargetPlatform::MacOS => {
if matches!(
cause,
Some(SelectionChangedCause::LongPress | SelectionChangedCause::Drag)
) {
self.bring_into_view(app, new_selection.extent());
}
}
TargetPlatform::Linux
| TargetPlatform::Windows
| TargetPlatform::Fuchsia
| TargetPlatform::Android => {
if cause == Some(SelectionChangedCause::Drag) {
if old_selection.base_offset != new_selection.base_offset {
self.bring_into_view(app, new_selection.base());
} else if old_selection.extent_offset != new_selection.extent_offset {
self.bring_into_view(app, new_selection.extent());
}
}
}
}
}
fn handle_selection_changed(
self: Handle<Self>,
app: &mut App,
selection: TextSelection,
cause: Option<SelectionChangedCause>,
) {
let text = self.widget(app).controller.value(app).text.clone();
if utf16_len(&text) < selection.end() || utf16_len(&text) < selection.start() {
return;
}
self.widget(app).controller.set_selection(app, selection);
match cause {
None
| Some(SelectionChangedCause::DoubleTap)
| Some(SelectionChangedCause::Drag)
| Some(SelectionChangedCause::ForcePress)
| Some(SelectionChangedCause::LongPress)
| Some(SelectionChangedCause::StylusHandwriting)
| Some(SelectionChangedCause::Tap)
| Some(SelectionChangedCause::Toolbar) => {
self.request_keyboard(app);
}
Some(SelectionChangedCause::Keyboard) => {}
}
if self.widget(app).selection_controls.is_none()
&& self.widget(app).context_menu_builder.is_none()
{
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.dispose(app);
}
app.get_mut(self).selection_overlay = None;
} else {
if app.get(self).selection_overlay.is_none() {
let overlay = self.create_selection_overlay(app);
app.get_mut(self).selection_overlay = Some(overlay);
} else if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.update(app, self.value(app));
}
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.set_handles_visible(app, self.widget(app).show_selection_handles);
overlay.show_handles(app);
}
}
if let Some(on_selection_changed) = self.widget(app).on_selection_changed.clone() {
on_selection_changed(app, selection, cause);
}
if self.show_blinking_cursor(app) && app.get(self).cursor_timer.is_some() {
self.stop_cursor_blink(app, false);
self.start_cursor_blink(app);
}
}
fn bottom_view_inset(self: Handle<Self>, app: &mut App) -> f64 {
let context = self.context(app);
View::maybe_of(app, context).map_or(0.0, |view| view.metrics().view_insets.bottom)
}
const CARET_ANIMATION_DURATION: Duration = Duration::from_millis(100);
fn caret_animation_curve() -> Rc<dyn Curve> {
Curves::fast_out_slow_in()
}
fn schedule_show_caret_on_screen(self: Handle<Self>, app: &mut App, with_animation: bool) {
if app.get(self).show_caret_on_screen_scheduled {
return;
}
app.get_mut(self).show_caret_on_screen_scheduled = true;
let view = View::maybe_id_of(app, self.context(app));
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| self.show_caret_on_screen(app, with_animation)),
view,
);
}
fn show_caret_on_screen(self: Handle<Self>, app: &mut App, with_animation: bool) {
if !app.contains(self) || !self.mounted(app) {
return;
}
app.get_mut(self).show_caret_on_screen_scheduled = false;
let render_editable = self.render_editable(app);
let Some(caret_selection) = render_editable
.selection(app)
.filter(|selection| selection.is_valid())
else {
return;
};
if !self.scroll_controller(app).has_clients(app) {
return;
}
let line_height = render_editable.preferred_line_height(app);
let scroll_padding = self.widget(app).scroll_padding;
let mut bottom_spacing = scroll_padding.bottom;
let selection_controls = app
.get(self)
.selection_overlay
.as_ref()
.and_then(|overlay| app.get(overlay).selection_controls.clone());
if let Some(selection_controls) = selection_controls {
let handle_height = selection_controls.get_handle_size(line_height).height();
let interactive_handle_height = handle_height.max(K_MIN_INTERACTIVE_DIMENSION);
let anchor = selection_controls
.get_handle_anchor(TextSelectionHandleType::Collapsed, line_height);
let handle_center = handle_height / 2.0 - anchor.dy();
bottom_spacing = (handle_center + interactive_handle_height / 2.0).max(bottom_spacing);
}
let caret_padding = scroll_padding.copy_with(None, None, None, Some(bottom_spacing));
let caret_rect = render_editable.get_local_rect_for_caret(app, caret_selection.extent());
let target_offset = self.get_offset_to_reveal_caret(app, caret_rect);
let selection = self.value(app).selection;
let rect_to_reveal = if selection.is_collapsed() {
target_offset.rect
} else {
let selection_boxes = render_editable.get_boxes_for_selection(app, selection);
match (selection_boxes.first(), selection_boxes.last()) {
(Some(first), Some(last)) => {
if selection.base_offset < selection.extent_offset {
last.to_rect()
} else {
first.to_rect()
}
}
_ => target_offset.rect,
}
};
if with_animation {
self.scroll_controller(app).animate_to(
app,
target_offset.offset,
Self::CARET_ANIMATION_DURATION,
Self::caret_animation_curve(),
);
render_editable.show_on_screen(
app,
None,
Some(caret_padding.inflate_rect(rect_to_reveal)),
Self::CARET_ANIMATION_DURATION,
Self::caret_animation_curve(),
);
} else {
self.scroll_controller(app)
.jump_to(app, target_offset.offset);
render_editable.show_on_screen(
app,
None,
Some(caret_padding.inflate_rect(rect_to_reveal)),
Duration::ZERO,
Curves::ease(),
);
}
}
fn finalize_editing(
self: Handle<Self>,
app: &mut App,
action: TextInputAction,
should_unfocus: bool,
) {
if let Some(on_editing_complete) = self.widget(app).on_editing_complete.clone() {
on_editing_complete(app);
} else {
self.widget(app).controller.clear_composing(app);
if should_unfocus {
let focus = self.widget(app).focus_node.handle();
match action {
TextInputAction::Next => {
focus.next_focus(app);
}
TextInputAction::Previous => {
focus.previous_focus(app);
}
_ => {
focus.unfocus(
app,
crate::widgets::focus_manager::UnfocusDisposition::Scope,
);
}
}
}
}
let on_submitted = self.widget(app).on_submitted.clone();
if let Some(on_submitted) = on_submitted {
let text = self.value(app).text;
on_submitted(app, text);
}
}
fn on_cursor_color_tick(self: Handle<Self>, app: &mut App) {
let cursor_color = self.cursor_color(app);
self.render_editable(app)
.set_cursor_color(app, Some(cursor_color));
let show_cursor = self.widget(app).effective_show_cursor();
let visible = show_cursor
&& (EditableText::debug_deterministic_cursor(app)
|| self.cursor_blink_opacity_controller(app).value(app) > 0.0);
self.cursor_visibility_notifier(app).set_value(app, visible);
}
fn start_cursor_blink(self: Handle<Self>, app: &mut App) {
if cfg!(debug_assertions) {
let timer_active = app
.get(self)
.cursor_timer
.is_some_and(|timer| timer.is_active(app));
let animating = app
.get(self)
.backing_cursor_blink_opacity_controller
.handle()
.is_some_and(|controller| controller.is_animating(app));
debug_assert!(!timer_active || !animating);
}
if !self.widget(app).effective_show_cursor() || !app.get(self).tickers_enabled {
return;
}
if let Some(timer) = app.get(self).cursor_timer {
timer.cancel(app);
}
self.cursor_blink_opacity_controller(app)
.set_value(app, 1.0);
if EditableText::debug_deterministic_cursor(app) {
return;
}
if self.widget(app).cursor_opacity_animates {
let future = self.cursor_blink_opacity_controller(app).animate_with(
app,
Box::new(DiscreteKeyFrameSimulation::ios_blinking_caret()),
);
future.when_complete(app, Listener::handle_method(self, Self::on_cursor_tick));
} else {
let timer = Timer::new(
app,
K_CURSOR_BLINK_HALF_PERIOD,
Listener::handle_method(self, Self::on_cursor_tick),
);
app.get_mut(self).cursor_timer = Some(timer);
}
}
fn on_cursor_tick(self: Handle<Self>, app: &mut App) {
if app.get(self).obscure_show_char_ticks_pending > 0 {
app.get_mut(self).obscure_show_char_ticks_pending =
if app.platform().briefly_show_password() {
app.get(self).obscure_show_char_ticks_pending - 1
} else {
0
};
if app.get(self).obscure_show_char_ticks_pending == 0 {
self.set_state(app, |_| {});
}
}
if self.widget(app).cursor_opacity_animates {
if let Some(timer) = app.get(self).cursor_timer {
timer.cancel(app);
}
let this = self;
let timer = Timer::new(
app,
Duration::ZERO,
Listener::new(move |app| {
let future = this.cursor_blink_opacity_controller(app).animate_with(
app,
Box::new(DiscreteKeyFrameSimulation::ios_blinking_caret()),
);
future.when_complete(app, Listener::handle_method(this, Self::on_cursor_tick));
}),
);
app.get_mut(self).cursor_timer = Some(timer);
} else {
let timer_active = app
.get(self)
.cursor_timer
.is_some_and(|timer| timer.is_active(app));
if !timer_active && app.get(self).tickers_enabled {
let timer = Timer::new(
app,
K_CURSOR_BLINK_HALF_PERIOD,
Listener::handle_method(self, Self::on_cursor_tick),
);
app.get_mut(self).cursor_timer = Some(timer);
}
let controller = self.cursor_blink_opacity_controller(app);
let next = if controller.value(app) == 0.0 {
1.0
} else {
0.0
};
controller.set_value(app, next);
}
}
fn stop_cursor_blink(self: Handle<Self>, app: &mut App, reset_char_ticks: bool) {
self.cursor_blink_opacity_controller(app)
.set_value(app, 0.0);
if let Some(timer) = app.get(self).cursor_timer {
timer.cancel(app);
}
app.get_mut(self).cursor_timer = None;
if reset_char_ticks {
app.get_mut(self).obscure_show_char_ticks_pending = 0;
}
}
fn start_or_stop_cursor_timer_if_needed(self: Handle<Self>, app: &mut App) {
if !self.show_blinking_cursor(app) {
self.stop_cursor_blink(app, true);
} else if app.get(self).cursor_timer.is_none() {
self.start_cursor_blink(app);
}
}
fn effective_text_scaler(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> TextScaler {
match (
self.widget(app).text_scaler.clone(),
self.widget(app).text_scale_factor,
) {
(Some(scaler), _) => scaler,
(None, Some(factor)) => TextScaler::linear(factor),
(None, None) => MediaQuery::text_scaler_of(app, context),
}
}
fn apply_autofocus(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
if !self.mounted(app) || !self.render_editable(app).has_size(app) {
return;
}
app.get_mut(self).next_focus_change_is_internal = true;
let focus_node = self.widget(app).focus_node.handle();
let context = self.context(app);
FocusScope::of(app, context, true).autofocus(app, focus_node);
}
fn post_frame_open_connection(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
if self.mounted(app) {
self.open_input_connection(app);
}
}
fn post_frame_update_style(self: Handle<Self>, app: &mut App, _elapsed: Duration) {
if !self.mounted(app) || !self.has_input_connection(app) {
return;
}
let context = self.context(app);
if let Some(connection) = app.get(self).text_input_connection.handle() {
let style = self.get_text_input_style(app, context);
connection.update_style(app, style);
}
}
fn composite_callback(self: Handle<Self>, app: &mut App, _layer: AnyLayer) {
if !self.render_editable(app).as_object().attached(app) || !self.has_input_connection(app) {
return;
}
debug_assert!(self.mounted(app));
self.update_size_and_transform(app);
}
fn update_size_and_transform(self: Handle<Self>, app: &mut App) {
let render_editable = self.render_editable(app);
let size = render_editable.size(app);
let transform = render_editable.as_object().get_transform_to(app, None);
let connection = self.text_input_connection(app);
connection.set_editable_size_and_transform(app, size, transform);
}
fn schedule_periodic_post_frame_callbacks(
self: Handle<Self>,
app: &mut App,
_duration: Duration,
) {
if !self.has_input_connection(app) {
return;
}
self.update_selection_rects(app, false);
self.update_composing_rect_if_needed(app);
self.update_caret_rect_if_needed(app);
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::schedule_periodic_post_frame_callbacks),
View::maybe_id_of(app, self.context(app)),
);
}
fn update_selection_rects(self: Handle<Self>, app: &mut App, force: bool) {
if !self.stylus_handwriting_enabled(app)
|| app.platform().target_platform() != TargetPlatform::IOS
{
return;
}
let scroll_direction = self
.scroll_controller(app)
.position(app)
.user_scroll_direction(app);
if scroll_direction != ScrollDirection::Idle {
return;
}
let render_editable = self.render_editable(app);
let Some(inline_span) = render_editable.text(app) else {
return;
};
let context = self.context(app);
let text_height_behavior = self
.widget(app)
.text_height_behavior
.or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
let new_cache_key = ScribbleCacheKey {
inline_span: inline_span.clone(),
text_align: self.widget(app).text_align,
text_direction: self.text_direction(app, context),
text_scaler: self.effective_text_scaler(app, context),
text_height_behavior,
locale: self.widget(app).locale.clone(),
size: render_editable.size(app),
};
let comparison = if force {
RenderComparison::Layout
} else {
app.get(self)
.scribble_cache_key
.as_ref()
.map_or(RenderComparison::Layout, |key| key.compare(&new_cache_key))
};
if comparison < RenderComparison::Layout {
return;
}
app.get_mut(self).scribble_cache_key = Some(new_cache_key);
let mut rects = Vec::new();
let mut grapheme_start = 0;
let plain_text = inline_span.to_plain_text(false, true);
let characters = CharacterBoundary::new(plain_text);
while let Some(grapheme_end) = characters.get_trailing_text_boundary_at(app, grapheme_start)
{
let boxes = render_editable
.get_boxes_for_selection(app, TextSelection::new(grapheme_start, grapheme_end));
if let Some(text_box) = boxes.first() {
let paint_bounds = render_editable.as_object().paint_bounds(app);
if paint_bounds.bottom <= text_box.top {
break;
}
if paint_bounds.left <= text_box.right
&& text_box.left <= paint_bounds.right
&& paint_bounds.top <= text_box.bottom
{
rects.push(SelectionRect::new(
grapheme_start,
text_box.to_rect(),
text_box.direction,
));
}
}
grapheme_start = grapheme_end;
}
self.text_input_connection(app)
.set_selection_rects(app, rects);
}
fn update_composing_rect_if_needed(self: Handle<Self>, app: &mut App) {
let composing_range = self.value(app).composing;
debug_assert!(self.mounted(app));
let render_editable = self.render_editable(app);
let composing_rect = render_editable.get_rect_for_composing_range(app, composing_range);
let composing_rect = composing_rect.unwrap_or_else(|| {
let offset = if composing_range.is_valid() {
composing_range.start
} else {
0
};
render_editable.get_local_rect_for_caret(app, TextPosition::new(offset))
});
self.text_input_connection(app)
.set_composing_rect(app, composing_rect);
}
fn update_caret_rect_if_needed(self: Handle<Self>, app: &mut App) {
let render_editable = self.render_editable(app);
let Some(selection) = render_editable.selection(app) else {
return;
};
if !selection.is_valid() {
return;
}
let current_text_position = TextPosition::new(selection.start());
let caret_rect = render_editable.get_local_rect_for_caret(app, current_text_position);
self.text_input_connection(app)
.set_caret_rect(app, caret_rect);
}
fn text_input_connection(self: Handle<Self>, app: &App) -> Handle<TextInputConnection> {
app.get(self)
.text_input_connection
.handle()
.expect("EditableText has an input connection")
}
fn build_editable(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
offset: ViewportOffsetRef,
) -> WidgetRef {
let line_height_scale_factor =
MediaQuery::maybe_line_height_scale_factor_override_of(app, context);
let letter_spacing = MediaQuery::maybe_letter_spacing_override_of(app, context);
let word_spacing = MediaQuery::maybe_word_spacing_override_of(app, context);
let inline_span = apply_text_spacing_overrides(
line_height_scale_factor,
letter_spacing,
word_spacing,
self.build_text_span(app, context),
)
.into_span();
let mut strut_style = self.widget(app).effective_strut_style();
if let Some(height) = line_height_scale_factor {
strut_style = strut_style.merge(Some(&StrutStyle::new().height(height)));
}
let value = self.value(app);
let cursor_color = self.cursor_color(app);
let background_cursor_color = self.widget(app).background_cursor_color;
let show_cursor = app
.get(self)
.cursor_visibility_notifier
.clone()
.expect("created in initState");
let force_line = self.widget(app).force_line;
let read_only = self.widget(app).read_only;
let has_focus = self.has_focus(app);
let max_lines = self.widget(app).max_lines;
let min_lines = self.widget(app).min_lines;
let expands = self.widget(app).expands;
let selection_color = self.widget(app).selection_color;
let text_scaler = self.effective_text_scaler(app, context);
let text_align = self.widget(app).text_align;
let text_direction = self.text_direction(app, context);
let locale = self.widget(app).locale.clone();
let obscuring_character = self.widget(app).obscuring_character.clone();
let obscure_text = self.widget(app).obscure_text;
let text_height_behavior = self
.widget(app)
.text_height_behavior
.or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
let text_width_basis = self.widget(app).text_width_basis;
let renderer_ignores_pointer = self.widget(app).renderer_ignores_pointer;
let cursor_width = self.widget(app).cursor_width;
let cursor_height = self.widget(app).cursor_height;
let cursor_radius = self.widget(app).cursor_radius;
let cursor_offset = self.widget(app).cursor_offset.unwrap_or(Offset::ZERO);
let selection_height_style = self.widget(app).selection_height_style;
let selection_width_style = self.widget(app).selection_width_style;
let paint_cursor_above_text = self.widget(app).paint_cursor_above_text;
let enable_interactive_selection = self.widget(app).user_selection_enabled();
let device_pixel_ratio = MediaQuery::device_pixel_ratio_of(app, context);
let prompt_rect_range = app.get(self).current_prompt_rect_range;
let prompt_rect_color = self.widget(app).autocorrection_text_rect_color;
let clip_behavior = self.widget(app).clip_behavior;
let editable = Editable {
key: Some(app.get(self).editable_key.clone().into()),
children: WidgetSpan::extract_from_inline_span(&*inline_span, &text_scaler),
inline_span,
value,
start_handle_layer_link: self.start_handle_layer_link(app),
end_handle_layer_link: self.end_handle_layer_link(app),
cursor_color: Some(cursor_color),
background_cursor_color: Some(background_cursor_color),
show_cursor,
force_line,
read_only,
has_focus,
max_lines,
min_lines,
expands,
selection_color,
text_scaler,
text_align,
text_direction,
locale,
obscuring_character,
obscure_text,
text_height_behavior,
text_width_basis,
strut_style,
offset,
renderer_ignores_pointer,
cursor_width,
cursor_height,
cursor_radius,
cursor_offset,
paint_cursor_above_text,
selection_height_style,
selection_width_style,
enable_interactive_selection,
text_selection_delegate: self.as_text_selection_delegate(),
device_pixel_ratio,
prompt_rect_range,
prompt_rect_color,
clip_behavior,
}
.into_widget();
CompositedTransformTarget::new(self.toolbar_layer_link(app))
.child(editable)
.into_widget()
}
}
impl State for EditableTextState {
type Widget = EditableText;
state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
app.get_mut(self).composite_callback = Some(Rc::new(move |app, layer| {
self.composite_callback(app, layer)
}));
let clipboard_status = if K_IS_WEB {
ClipboardStatusNotifier::web(app)
} else {
ClipboardStatusNotifier::new(app)
};
let live_text = if K_IS_WEB {
None
} else {
Some(LiveTextInputStatusNotifier::new(app))
};
let cursor_visibility =
app.create(ValueNotifier::new(self.widget(app).effective_show_cursor()));
let toolbar_link = LayerLink::new(app);
let start_link = LayerLink::new(app);
let end_link = LayerLink::new(app);
let live_text_handle = live_text.handle();
let clipboard_status_handle = clipboard_status.handle();
app.get_mut(self).clipboard_status = Some(clipboard_status);
app.get_mut(self).live_text_input_status = live_text;
app.get_mut(self).cursor_visibility_notifier = Some(cursor_visibility);
app.get_mut(self).toolbar_layer_link = Some(toolbar_link);
app.get_mut(self).start_handle_layer_link = Some(start_link);
app.get_mut(self).end_handle_layer_link = Some(end_link);
if let Some(live_text) = live_text_handle {
live_text.add_listener(
app,
Listener::handle_method(self, Self::on_changed_live_text_input_status),
);
}
clipboard_status_handle.add_listener(
app,
Listener::handle_method(self, Self::on_changed_clipboard_status),
);
let controller = self.widget(app).controller.handle();
controller.add_listener(
app,
Listener::handle_method(self, Self::did_change_text_editing_value),
);
let focus_node = self.widget(app).focus_node.handle();
focus_node.add_listener(
app,
Listener::handle_method(self, Self::handle_focus_changed),
);
let widget = self.widget(app);
let inferred = infer_spell_check_configuration(
widget.spell_check_configuration.as_ref(),
widget.obscure_text,
widget.effective_keyboard_type(app),
&widget.autofill_hints,
);
app.get_mut(self).spell_check_configuration = inferred;
let listener = AppLifecycleListener::new(app).on_resume(
app,
Rc::new({
let this = self;
move |app| this.on_resume(app)
}),
);
app.get_mut(self).app_lifecycle_listener = Some(listener);
self.init_process_text_actions(app);
AutomaticKeepAliveClientMixin::init_state(self, app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let context = self.context(app);
let bold = MediaQuery::bold_text_of(app, context);
let style = self.widget(app).style.clone();
app.get_mut(self).style = if bold {
style.merge(Some(&TextStyle::new().font_weight(FontWeight::BOLD)))
} else {
style
};
let new_autofill_group = AutofillGroup::maybe_of(app, context);
if app.get(self).current_autofill_scope != new_autofill_group {
if let Some(scope) = app.get(self).current_autofill_scope {
let autofill_id = self.as_autofill_client().autofill_id(app);
scope.unregister(app, &autofill_id);
}
app.get_mut(self).current_autofill_scope = new_autofill_group;
if let Some(scope) = new_autofill_group {
let client = self.effective_autofill_client(app);
scope.register(app, client);
}
}
if !app.get(self).did_auto_focus && self.widget(app).autofocus {
app.get_mut(self).did_auto_focus = true;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::apply_autofocus),
View::maybe_id_of(app, self.context(app)),
);
}
let new_ticker_enabled = TickerMode::values_of(app, context).enabled;
if app.get(self).tickers_enabled != new_ticker_enabled {
app.get_mut(self).tickers_enabled = new_ticker_enabled;
if self.show_blinking_cursor(app) {
self.start_cursor_blink(app);
} else if !new_ticker_enabled && app.get(self).cursor_timer.is_some() {
self.stop_cursor_blink(app, true);
}
}
let view_id = View::maybe_of(app, context).map(|view| view.id());
let view_changed = app.get(self).view_id != view_id;
app.get_mut(self).view_id = view_id;
if let Some(connection) = app.get(self).text_input_connection.handle()
&& self.has_input_connection(app)
{
if view_changed {
let config = self
.effective_autofill_client(app)
.text_input_configuration(app);
connection.update_config(app, config);
}
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::post_frame_update_style),
View::maybe_id_of(app, self.context(app)),
);
}
let platform = app.platform().target_platform();
if platform != TargetPlatform::IOS && platform != TargetPlatform::Android {
return;
}
let orientation = MediaQuery::orientation_of(app, context);
if app.get(self).last_orientation.is_none() {
app.get_mut(self).last_orientation = Some(orientation);
return;
}
if app.get(self).last_orientation != Some(orientation) {
app.get_mut(self).last_orientation = Some(orientation);
}
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &EditableText) {
if self.widget(app).controller != old_widget.controller {
old_widget.controller.remove_listener(
app,
&Listener::handle_method(self, Self::did_change_text_editing_value),
);
let controller = self.widget(app).controller.handle();
controller.add_listener(
app,
Listener::handle_method(self, Self::did_change_text_editing_value),
);
self.update_remote_editing_value_if_needed(app);
}
if self.widget(app).focus_node != old_widget.focus_node {
old_widget.focus_node.remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
let focus_node = self.widget(app).focus_node.handle();
focus_node.add_listener(
app,
Listener::handle_method(self, Self::handle_focus_changed),
);
AutomaticKeepAliveClientMixin::update_keep_alive(self, app);
}
if self.widget(app).autofill_client != old_widget.autofill_client
&& let Some(scope) = app.get(self).current_autofill_scope
{
let old_id = old_widget
.autofill_client
.map(|client| client.autofill_id(app))
.unwrap_or_else(|| self.as_autofill_client().autofill_id(app));
scope.unregister(app, &old_id);
let client = self.effective_autofill_client(app);
scope.register(app, client);
}
if !self.should_create_input_connection(app) {
self.close_input_connection_if_needed(app);
} else if old_widget.read_only && self.has_focus(app) {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::post_frame_open_connection),
View::maybe_id_of(app, self.context(app)),
);
}
if self.has_input_connection(app) {
let obscure_changed = old_widget.obscure_text != self.widget(app).obscure_text;
if obscure_changed
|| old_widget.effective_keyboard_type(app)
!= self.widget(app).effective_keyboard_type(app)
{
if obscure_changed {
app.get_mut(self).obscure_show_char_ticks_pending = 0;
app.get_mut(self).obscure_latest_char_index = None;
}
if let Some(connection) = app.get(self).text_input_connection.handle() {
let config = self
.effective_autofill_client(app)
.text_input_configuration(app);
connection.update_config(app, config);
}
}
}
let widget = self.widget(app);
if old_widget
.spell_check_configuration
.as_ref()
.map(|c| c.spell_check_enabled())
!= widget
.spell_check_configuration
.as_ref()
.map(|c| c.spell_check_enabled())
|| old_widget.obscure_text != widget.obscure_text
|| old_widget.effective_keyboard_type(app) != widget.effective_keyboard_type(app)
|| old_widget.autofill_hints != widget.autofill_hints
{
let inferred = infer_spell_check_configuration(
widget.spell_check_configuration.as_ref(),
widget.obscure_text,
widget.effective_keyboard_type(app),
&widget.autofill_hints,
);
app.get_mut(self).spell_check_configuration = inferred;
if !self.spell_check_enabled(app) {
app.get_mut(self).spell_check_results = None;
}
}
if self.widget(app).style != old_widget.style {
let context = self.context(app);
let bold = MediaQuery::bold_text_of(app, context);
let style = self.widget(app).style.clone();
app.get_mut(self).style = if bold {
style.merge(Some(&TextStyle::new().font_weight(FontWeight::BOLD)))
} else {
style
};
if self.has_input_connection(app) {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::post_frame_update_style),
View::maybe_id_of(app, self.context(app)),
);
}
}
if self.widget(app).effective_show_cursor() != old_widget.effective_show_cursor() {
self.start_or_stop_cursor_timer_if_needed(app);
}
let selection_overlay = app.get(self).selection_overlay.handle();
if let Some(overlay) = selection_overlay
&& overlay.toolbar_is_visible(app)
&& !option_rc_eq(
&self.widget(app).context_menu_builder,
&old_widget.context_menu_builder,
)
&& self.widget(app).context_menu_builder.is_none()
== old_widget.context_menu_builder.is_none()
{
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::post_frame_rebuild_toolbar),
View::maybe_id_of(app, self.context(app)),
);
}
if app.get(self).selection_overlay.is_some()
&& (self.widget(app).context_menu_builder.is_none()
!= old_widget.context_menu_builder.is_none()
|| !option_rc_eq(
&self.widget(app).selection_controls,
&old_widget.selection_controls,
)
|| self.widget(app).on_selection_handle_tapped
!= old_widget.on_selection_handle_tapped
|| self.widget(app).drag_start_behavior != old_widget.drag_start_behavior
|| !self
.widget(app)
.magnifier_configuration
.same_configuration(&old_widget.magnifier_configuration))
{
let overlay = app
.get(self)
.selection_overlay
.handle()
.expect("checked above");
let should_show_toolbar = overlay.toolbar_is_visible(app);
let should_show_handles = overlay.handles_visible_value(app);
overlay.dispose(app);
let created = self.create_selection_overlay(app);
app.get_mut(self).selection_overlay = Some(created);
if should_show_toolbar || should_show_handles {
let this = self;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _| {
if let Some(overlay) = app.get(this).selection_overlay.handle() {
if should_show_toolbar {
overlay.show_toolbar(app);
}
if should_show_handles {
overlay.show_handles(app);
}
}
}),
View::maybe_id_of(app, self.context(app)),
);
}
} else if self.widget(app).controller.selection(app) != old_widget.controller.selection(app)
&& let Some(overlay) = app.get(self).selection_overlay.handle()
{
overlay.update(app, self.value(app));
}
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.set_handles_visible(app, self.widget(app).show_selection_handles);
}
#[allow(deprecated)]
let can_paste = if self.widget(app).has_handle_controls() {
self.paste_enabled(app)
} else {
self.widget(app)
.selection_controls
.as_ref()
.is_some_and(|controls| controls.can_paste(app, self.as_text_selection_delegate()))
};
if self.widget(app).effective_enable_interactive_selection()
&& self.paste_enabled(app)
&& can_paste
{
self.clipboard_status(app).update(app);
}
}
fn activate(self: Handle<Self>, app: &mut App) {
TickerProviderStateMixin::activate(self, app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
AutomaticKeepAliveClientMixin::deactivate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(controller) = app.get(self).internal_scroll_controller.handle() {
controller.dispose(app);
}
if let Some(scope) = app.get(self).current_autofill_scope {
let autofill_id = self.as_autofill_client().autofill_id(app);
scope.unregister(app, &autofill_id);
}
let editing_controller = self.widget(app).controller.handle();
editing_controller.remove_listener(
app,
&Listener::handle_method(self, Self::did_change_text_editing_value),
);
self.close_input_connection_if_needed(app);
debug_assert!(!self.has_input_connection(app));
if let Some(timer) = app.get(self).cursor_timer {
timer.cancel(app);
}
app.get_mut(self).cursor_timer = None;
if let Some(controller) = app
.get(self)
.backing_cursor_blink_opacity_controller
.handle()
{
controller.dispose(app);
}
app.get_mut(self).backing_cursor_blink_opacity_controller = None;
if let Some(overlay) = app.get(self).selection_overlay.handle() {
overlay.dispose(app);
}
app.get_mut(self).selection_overlay = None;
let focus_node = self.widget(app).focus_node.handle();
focus_node.remove_listener(
app,
&Listener::handle_method(self, Self::handle_focus_changed),
);
if app.get(self).registered_as_observer {
let observer = self.observer(app);
WidgetsBinding::instance(app).remove_observer(app, &observer);
app.get_mut(self).registered_as_observer = false;
}
if let Some(live_text) = app.get(self).live_text_input_status.handle() {
live_text.remove_listener(
app,
&Listener::handle_method(self, Self::on_changed_live_text_input_status),
);
live_text.dispose(app);
}
if let Some(clipboard) = app.get(self).clipboard_status.handle() {
clipboard.remove_listener(
app,
&Listener::handle_method(self, Self::on_changed_clipboard_status),
);
clipboard.dispose(app);
}
if let Some(notifier) = app.get(self).cursor_visibility_notifier.handle() {
notifier.dispose(app);
}
if let Some(listener) = app.get(self).app_lifecycle_listener.handle() {
listener.dispose(app);
}
FocusManager::instance(app).remove_listener(
app,
&Listener::handle_method(self, Self::reset_just_resumed),
);
debug_assert!(
app.get(self).batch_edit_depth <= 0,
"unfinished batch edits: {}",
app.get(self).batch_edit_depth
);
TickerProviderStateMixin::dispose(self, app);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let _ = AutomaticKeepAliveClientMixin::build(self, app);
let is_multiline = self.is_multiline(app);
let platform = app.platform().target_platform();
let physics = self.widget(app).scroll_physics.clone().or_else(|| {
if !is_multiline && platform == TargetPlatform::IOS {
Some(Rc::new(NeverUserScrollableScrollPhysics::new()))
} else {
None
}
});
let scroll_behavior = self.widget(app).scroll_behavior.clone().unwrap_or_else(|| {
ScrollBehaviorRef::new(
ScrollConfiguration::of(app, context)
.copy_with()
.scrollbars(is_multiline)
.overscroll(false),
)
});
let restoration_id = self.widget(app).restoration_id.clone();
let drag_start_behavior = self.widget(app).drag_start_behavior;
let controller = self.scroll_controller(app);
let focus_node = self.widget(app).focus_node.clone();
let state = self;
let viewport_builder: ViewportBuilder =
Rc::new(move |app, context, offset| state.build_editable(app, context, offset));
let mut scrollable = Scrollable::new(viewport_builder)
.key(app.get(self).scrollable_key.clone().into())
.axis_direction(if is_multiline {
AxisDirection::Down
} else {
AxisDirection::Right
})
.controller(controller.into_erased())
.drag_start_behavior(drag_start_behavior)
.scroll_behavior(scroll_behavior);
if let Some(physics) = physics {
scrollable = scrollable.physics(physics);
}
if let Some(restoration_id) = restoration_id {
scrollable = scrollable.restoration_id(restoration_id);
}
let state = self;
let scrollable = NotificationListener::<dyn ScrollNotification>::new(scrollable)
.on_notification(move |app: &mut App, _: &dyn ScrollNotification| {
app.get_mut(state).scribble_cache_key = None;
false
})
.into_widget();
let focused = Focus::new(scrollable)
.focus_node(focus_node.erase())
.include_semantics(false);
let editing_controller = self.widget(app).controller.clone();
let undo_controller = self.widget(app).undo_controller.clone();
let state = self;
let mut history = UndoHistory::new(
editing_controller,
move |app, value| {
state.user_update_text_editing_value(app, value, SelectionChangedCause::Keyboard);
},
focus_node,
focused,
)
.should_change_undo_stack(move |old_value, new_value| {
if !new_value.selection.is_valid() {
return false;
}
let Some(old_value) = old_value else {
return true;
};
match platform {
TargetPlatform::IOS
| TargetPlatform::MacOS
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {
if !new_value.composing.is_collapsed() {
return false;
}
}
TargetPlatform::Android => {}
}
old_value.text != new_value.text || old_value.composing != new_value.composing
})
.undo_stack_modifier(move |value| {
if platform == TargetPlatform::Android {
value.copy_with().composing(TextRange::EMPTY)
} else {
value
}
});
if let Some(undo_controller) = undo_controller {
history = history.controller(undo_controller);
}
let cursor = self
.widget(app)
.mouse_cursor
.clone()
.unwrap_or_else(|| SystemMouseCursors::TEXT.into());
let focused = MouseRegion::new()
.cursor(cursor)
.child(history.into_widget())
.into_widget();
let actions = self.ensure_actions(app, context);
let has_focus = self.has_focus(app);
let group_id = self.widget(app).group_id;
let state = self;
let composite_callback = app
.get(self)
.composite_callback
.clone()
.expect("set in init_state");
let enabled = self.has_input_connection(app);
let child = Actions::new(
actions,
Builder::new(move |_app, tap_context| {
let mut region = TextFieldTapRegion::new(focused.clone())
.group_id(TapRegionGroupId::Type(group_id));
if has_focus {
#[allow(clippy::redundant_locals)]
let tap_context = tap_context;
region = region.on_tap_outside(Rc::new(move |app, event| {
state.on_tap_outside(app, tap_context, event);
}));
}
region = region.on_tap_up_outside(Rc::new(move |app, event| {
state.on_tap_up_outside(app, tap_context, event);
}));
if cfg!(debug_assertions) {
region = region.debug_label("EditableText");
}
region.into_widget()
}),
)
.into_widget();
CompositionCallbackWidget::new(composite_callback, enabled, child).into_widget()
}
}
impl AutomaticKeepAliveClientMixin for EditableTextState {
fn automatic_keep_alive_client_data(
self: Handle<Self>,
app: &App,
) -> &AutomaticKeepAliveClientMixinData {
&app.get(self).automatic_keep_alive_client
}
fn automatic_keep_alive_client_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut AutomaticKeepAliveClientMixinData {
&mut app.get_mut(self).automatic_keep_alive_client
}
fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
app.get(self).has_focus
}
}
impl TickerProviderStateMixin for EditableTextState {
fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
&app.get(self).ticker_provider
}
fn ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TickerProviderStateMixinData {
&mut app.get_mut(self).ticker_provider
}
}
impl TickerProviderObject for EditableTextState {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
TickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl WidgetsBindingObserverObject for EditableTextState {
fn did_change_metrics(self: Handle<Self>, app: &mut App) {
if !self.mounted(app) {
return;
}
let context = self.context(app);
let bottom_view_inset = self.bottom_view_inset(app);
let last_bottom_view_inset = app.get(self).last_bottom_view_inset;
if last_bottom_view_inset != bottom_view_inset {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::post_frame_update_for_scroll),
View::maybe_id_of(app, context),
);
if last_bottom_view_inset < bottom_view_inset {
self.schedule_show_caret_on_screen(app, false);
}
}
app.get_mut(self).last_bottom_view_inset = bottom_view_inset;
}
}
impl TextInputClient for EditableTextState {
fn current_text_editing_value(self: Handle<Self>, app: &App) -> Option<TextEditingValue> {
Some(self.value(app))
}
fn update_editing_value(self: Handle<Self>, app: &mut App, mut value: TextEditingValue) {
if !self.should_create_input_connection(app) {
return;
}
if self.check_needs_adjust_affinity(app, &value) {
value = value.copy_with().selection(
value
.selection
.copy_with()
.affinity(self.value(app).selection.affinity),
);
}
if self.widget(app).read_only {
value = self.value(app).copy_with().selection(value.selection);
}
app.get_mut(self).last_known_remote_text_editing_value = Some(value.clone());
if value == self.value(app) {
return;
}
let current = self.value(app);
if value.text == current.text && value.composing == current.composing {
self.handle_selection_changed(
app,
value.selection,
Some(SelectionChangedCause::Keyboard),
);
} else {
app.get_mut(self).current_prompt_rect_range = None;
let current = self.value(app);
let reveal_obscured_input = self.has_input_connection(app)
&& self.widget(app).obscure_text
&& app.platform().briefly_show_password()
&& utf16_len(&value.text) == utf16_len(¤t.text) + 1;
app.get_mut(self).obscure_show_char_ticks_pending = if reveal_obscured_input {
K_OBSCURE_SHOW_LATEST_CHAR_CURSOR_TICKS
} else {
0
};
app.get_mut(self).obscure_latest_char_index = if reveal_obscured_input {
Some(current.selection.base_offset)
} else {
None
};
self.format_and_set_value(app, value, Some(SelectionChangedCause::Keyboard), false);
}
if self.show_blinking_cursor(app) && app.get(self).cursor_timer.is_some() {
self.stop_cursor_blink(app, false);
self.start_cursor_blink(app);
}
self.schedule_show_caret_on_screen(app, true);
}
fn perform_action(self: Handle<Self>, app: &mut App, action: TextInputAction) {
match action {
TextInputAction::Newline => {
if !self.is_multiline(app) {
self.finalize_editing(app, action, true);
}
}
TextInputAction::Done
| TextInputAction::Go
| TextInputAction::Next
| TextInputAction::Previous
| TextInputAction::Search
| TextInputAction::Send => {
self.finalize_editing(app, action, true);
}
TextInputAction::ContinueAction
| TextInputAction::EmergencyCall
| TextInputAction::Join
| TextInputAction::None
| TextInputAction::Route
| TextInputAction::Unspecified => {
self.finalize_editing(app, action, false);
}
}
}
fn perform_private_command(self: Handle<Self>, app: &mut App, action: &str) {
if let Some(callback) = self.widget(app).on_app_private_command.clone() {
callback(app, action);
}
}
fn connection_closed(self: Handle<Self>, app: &mut App) {
if self.has_input_connection(app) {
if let Some(connection) = app.get(self).text_input_connection.handle() {
connection.connection_closed_received(app);
}
app.get_mut(self).text_input_connection = None;
app.get_mut(self).last_known_remote_text_editing_value = None;
let focus_node = self.widget(app).focus_node.handle();
focus_node.unfocus(
app,
crate::widgets::focus_manager::UnfocusDisposition::Scope,
);
}
}
fn show_autocorrection_prompt_rect(self: Handle<Self>, app: &mut App, start: i32, end: i32) {
self.set_state(app, |state| {
state.current_prompt_rect_range = Some(TextRange::new(start, end));
});
}
fn show_toolbar(self: Handle<Self>, app: &mut App) {
let _ = EditableTextState::show_toolbar(self, app);
}
fn perform_selector(self: Handle<Self>, app: &mut App, selector_name: &str) {
let Some(intent) = intent_for_macos_selector(selector_name) else {
return;
};
let Some(primary_context) = FocusManager::instance(app)
.primary_focus(app)
.and_then(|focus| focus.context(app))
else {
return;
};
Actions::invoke(app, primary_context, &*intent);
}
}
impl AutofillClient for EditableTextState {
fn autofill_id(self: Handle<Self>, _app: &App) -> String {
format!("{:?}", self.id())
}
fn text_input_configuration(self: Handle<Self>, app: &App) -> TextInputConfiguration {
let view_id = app.get(self).view_id;
let widget = self.widget(app);
let input_action = widget
.text_input_action
.unwrap_or(if widget.max_lines != Some(1) {
TextInputAction::Newline
} else {
TextInputAction::Done
});
let autofill_configuration = AutofillConfiguration::new(
format!("{:?}", self.id()),
widget.autofill_hints.clone(),
self.value(app),
);
let mut config = TextInputConfiguration::builder()
.input_type(widget.effective_keyboard_type(app))
.read_only(widget.read_only)
.obscure_text(widget.obscure_text)
.autocorrect(widget.effective_autocorrect(app))
.enable_suggestions(widget.enable_suggestions)
.enable_interactive_selection(widget.effective_enable_interactive_selection())
.input_action(input_action)
.text_capitalization(widget.text_capitalization)
.keyboard_appearance(widget.keyboard_appearance)
.enable_ime_personalized_learning(widget.enable_ime_personalized_learning)
.smart_dashes_type(widget.effective_smart_dashes_type())
.smart_quotes_type(widget.effective_smart_quotes_type())
.build();
config.autofill_configuration = autofill_configuration;
config.allowed_mime_types = widget
.content_insertion_configuration
.as_ref()
.map(|c| c.allowed_mime_types.clone())
.unwrap_or_default();
config.hint_locales = widget.hint_locales.clone().unwrap_or_default();
config.enable_inline_prediction = widget.enable_inline_prediction;
config.view_id = view_id.map(|view| view.0 as i32);
config
}
fn autofill(self: Handle<Self>, app: &mut App, new_editing_value: TextEditingValue) {
self.update_editing_value(app, new_editing_value);
}
}
impl TextSelectionDelegate for EditableTextState {
fn text_editing_value(self: Handle<Self>, app: &App) -> TextEditingValue {
self.value(app)
}
fn user_update_text_editing_value(
self: Handle<Self>,
app: &mut App,
value: TextEditingValue,
cause: SelectionChangedCause,
) {
let current = self.value(app);
let should_show_caret = (if self.widget(app).read_only {
current.selection != value.selection
} else {
current != value
}) && cause != SelectionChangedCause::Drag;
if should_show_caret {
self.schedule_show_caret_on_screen(app, true);
}
if value == self.value(app) {
if !self.has_focus(app) {
app.get_mut(self).next_focus_change_is_internal = true;
let focus_node = self.widget(app).focus_node.handle();
focus_node.request_focus(app, None);
if app.get(self).selection_overlay.is_none() {
let overlay = self.create_selection_overlay(app);
app.get_mut(self).selection_overlay = Some(overlay);
}
}
return;
}
self.format_and_set_value(app, value, Some(cause), true);
}
fn hide_toolbar(self: Handle<Self>, app: &mut App, hide_handles: bool) {
EditableTextState::hide_toolbar(self, app, hide_handles);
}
fn bring_into_view(self: Handle<Self>, app: &mut App, position: TextPosition) {
EditableTextState::bring_into_view(self, app, position);
}
fn cut_enabled(self: Handle<Self>, app: &App) -> bool {
let widget = self.widget(app);
if !widget.has_handle_controls() {
return widget.effective_toolbar_options().cut
&& !widget.read_only
&& !widget.obscure_text;
}
!widget.read_only && !widget.obscure_text && !self.value(app).selection.is_collapsed()
}
fn copy_enabled(self: Handle<Self>, app: &App) -> bool {
let widget = self.widget(app);
if !widget.has_handle_controls() {
return widget.effective_toolbar_options().copy && !widget.obscure_text;
}
!widget.obscure_text && !self.value(app).selection.is_collapsed()
}
fn paste_enabled(self: Handle<Self>, app: &App) -> bool {
let widget = self.widget(app);
if !widget.has_handle_controls() {
return widget.effective_toolbar_options().paste && !widget.read_only;
}
!widget.read_only && self.clipboard_status(app).value(app) == ClipboardStatus::Pasteable
}
fn select_all_enabled(self: Handle<Self>, app: &App) -> bool {
let widget = self.widget(app);
if !widget.has_handle_controls() {
return widget.effective_toolbar_options().select_all
&& (!widget.read_only || !widget.obscure_text)
&& widget.effective_enable_interactive_selection();
}
if !widget.effective_enable_interactive_selection()
|| (widget.read_only && widget.obscure_text)
{
return false;
}
let value = self.value(app);
match app.platform().target_platform() {
TargetPlatform::MacOS => false,
TargetPlatform::IOS => !value.text.is_empty() && value.selection.is_collapsed(),
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {
!value.text.is_empty()
&& !(value.selection.start() == 0
&& value.selection.end() == value.text.encode_utf16().count() as i32)
}
}
}
fn look_up_enabled(self: Handle<Self>, app: &App) -> bool {
if app.platform().target_platform() != TargetPlatform::IOS {
return false;
}
let value = self.value(app);
!self.widget(app).obscure_text
&& !value.selection.is_collapsed()
&& !value
.selection
.range()
.text_inside(&value.text)
.trim()
.is_empty()
}
fn search_web_enabled(self: Handle<Self>, app: &App) -> bool {
self.look_up_enabled(app)
}
fn share_enabled(self: Handle<Self>, app: &App) -> bool {
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::IOS => {
let value = self.value(app);
!self.widget(app).obscure_text
&& !value.selection.is_collapsed()
&& !value
.selection
.range()
.text_inside(&value.text)
.trim()
.is_empty()
}
_ => false,
}
}
fn live_text_input_enabled(self: Handle<Self>, app: &App) -> bool {
let Some(status) = app.get(self).live_text_input_status.handle() else {
return false;
};
status.value(app) == LiveTextInputStatus::Enabled
&& !self.widget(app).obscure_text
&& !self.widget(app).read_only
&& self.value(app).selection.is_collapsed()
}
fn copy_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
let value = self.value(app);
if value.selection.is_collapsed() || self.widget(app).obscure_text {
return;
}
let text = value.text.clone();
Clipboard::set_data(
app,
ClipboardData::new(value.selection.range().text_inside(&text).to_string()),
);
if cause == SelectionChangedCause::Toolbar {
self.bring_into_view(app, self.value(app).selection.extent());
TextSelectionDelegate::hide_toolbar(self, app, false);
match app.platform().target_platform() {
TargetPlatform::IOS
| TargetPlatform::MacOS
| TargetPlatform::Linux
| TargetPlatform::Windows => {}
TargetPlatform::Android | TargetPlatform::Fuchsia => {
let value = self.value(app);
let collapsed = value.copy_with().selection(TextSelection::collapsed(
value.selection.end(),
TextAffinity::Downstream,
));
self.user_update_text_editing_value(
app,
collapsed,
SelectionChangedCause::Toolbar,
);
}
}
}
self.clipboard_status(app).update(app);
}
fn cut_selection(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
if self.widget(app).read_only || self.widget(app).obscure_text {
return;
}
let value = self.value(app);
if value.selection.is_collapsed() {
return;
}
let text = value.selection.range().text_inside(&value.text).to_string();
Clipboard::set_data(app, ClipboardData::new(text));
let next = value.replaced(value.selection, "");
self.user_update_text_editing_value(app, next, cause);
if cause == SelectionChangedCause::Toolbar {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::handle_method(self, Self::bring_selection_into_view_after_frame),
View::maybe_id_of(app, self.context(app)),
);
TextSelectionDelegate::hide_toolbar(self, app, true);
}
self.clipboard_status(app).update(app);
}
fn paste_text(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) -> Task<()> {
if !self.allow_paste(app) {
return Task::ready(());
}
let data = Clipboard::get_data(app, Clipboard::K_TEXT_PLAIN);
app.spawn(async move |cx| {
let Some(text) = data.await.and_then(|data| data.text) else {
return;
};
cx.update(|app| {
if self.mounted(app) {
self.paste_text_content(app, cause, &text);
}
});
})
}
fn select_all(self: Handle<Self>, app: &mut App, cause: SelectionChangedCause) {
if self.widget(app).read_only && self.widget(app).obscure_text {
return;
}
let value = self.value(app);
let next = value
.copy_with()
.selection(TextSelection::new(0, utf16_len(&value.text)));
self.user_update_text_editing_value(app, next, cause);
if cause == SelectionChangedCause::Toolbar {
match app.platform().target_platform() {
TargetPlatform::Android | TargetPlatform::IOS | TargetPlatform::Fuchsia => {}
TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
TextSelectionDelegate::hide_toolbar(self, app, true);
}
}
match app.platform().target_platform() {
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {
self.bring_into_view(app, self.value(app).selection.extent());
}
TargetPlatform::MacOS | TargetPlatform::IOS => {}
}
}
}
}
struct Editable {
key: Option<KeyRef>,
children: Vec<WidgetRef>,
inline_span: InlineSpanRef,
value: TextEditingValue,
start_handle_layer_link: Ref<LayerLink>,
end_handle_layer_link: Ref<LayerLink>,
cursor_color: Option<Color>,
background_cursor_color: Option<Color>,
show_cursor: Ref<ValueNotifier<bool>>,
force_line: bool,
read_only: bool,
has_focus: bool,
max_lines: Option<i32>,
min_lines: Option<i32>,
expands: bool,
selection_color: Option<Color>,
text_scaler: TextScaler,
text_align: TextAlign,
text_direction: TextDirection,
locale: Option<Locale>,
obscuring_character: String,
obscure_text: bool,
text_height_behavior: Option<TextHeightBehavior>,
text_width_basis: TextWidthBasis,
strut_style: StrutStyle,
offset: ViewportOffsetRef,
renderer_ignores_pointer: bool,
cursor_width: f64,
cursor_height: Option<f64>,
cursor_radius: Option<Radius>,
cursor_offset: Offset,
paint_cursor_above_text: bool,
selection_height_style: BoxHeightStyle,
selection_width_style: BoxWidthStyle,
enable_interactive_selection: bool,
text_selection_delegate: AnyTextSelectionDelegate,
device_pixel_ratio: f64,
prompt_rect_range: Option<TextRange>,
prompt_rect_color: Option<Color>,
clip_behavior: Clip,
}
impl Debug for Editable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Editable")
.field("has_focus", &self.has_focus)
.field("read_only", &self.read_only)
.finish_non_exhaustive()
}
}
impl Editable {
fn apply_to_render_object(&self, app: &mut App, render_object: RenderHandle<RenderEditable>) {
render_object.set_text(app, Some(self.inline_span.clone()));
render_object.set_cursor_color(app, self.cursor_color);
render_object.set_start_handle_layer_link(app, self.start_handle_layer_link.clone());
render_object.set_end_handle_layer_link(app, self.end_handle_layer_link.clone());
render_object.set_background_cursor_color(app, self.background_cursor_color);
render_object.set_show_cursor(app, self.show_cursor.clone());
render_object.set_force_line(app, self.force_line);
render_object.set_read_only(app, self.read_only);
render_object.set_has_focus(app, self.has_focus);
render_object.set_max_lines(app, self.max_lines);
render_object.set_min_lines(app, self.min_lines);
render_object.set_expands(app, self.expands);
render_object.set_selection_color(app, self.selection_color);
render_object.set_text_scaler(app, self.text_scaler.clone());
render_object.set_text_align(app, self.text_align);
render_object.set_text_direction(app, self.text_direction);
render_object.set_selection(app, Some(self.value.selection));
render_object.set_offset(app, self.offset.clone());
render_object.get_mut(app).ignore_pointer = self.renderer_ignores_pointer;
render_object.set_text_height_behavior(app, self.text_height_behavior);
render_object.set_text_width_basis(app, self.text_width_basis);
render_object.set_strut_style(app, Some(self.strut_style.clone()));
render_object.set_obscuring_character(app, self.obscuring_character.clone());
render_object.set_obscure_text(app, self.obscure_text);
render_object.set_cursor_width(app, self.cursor_width);
render_object.set_cursor_height(app, self.cursor_height);
render_object.set_cursor_radius(app, self.cursor_radius);
render_object.set_cursor_offset(app, self.cursor_offset);
render_object.set_selection_height_style(app, self.selection_height_style);
render_object.set_selection_width_style(app, self.selection_width_style);
render_object
.set_enable_interactive_selection(app, Some(self.enable_interactive_selection));
render_object.set_text_selection_delegate(app, self.text_selection_delegate);
render_object.set_device_pixel_ratio(app, self.device_pixel_ratio);
render_object.set_paint_cursor_above_text(app, self.paint_cursor_above_text);
render_object.set_prompt_rect_color(app, self.prompt_rect_color);
render_object.set_clip_behavior(app, self.clip_behavior);
render_object.set_prompt_rect_range(app, self.prompt_rect_range);
let _ = &self.locale;
}
}
impl RenderObjectWidget for Editable {
type RenderObject = RenderEditable;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
let render_object = RenderEditable::new(
app,
self.text_direction,
self.start_handle_layer_link.clone(),
self.end_handle_layer_link.clone(),
self.offset.clone(),
self.text_selection_delegate,
);
self.apply_to_render_object(app, render_object);
render_object.as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderEditable>,
) {
self.apply_to_render_object(app, render_object);
}
}
impl MultiChildRenderObjectWidget for Editable {
fn children(&self) -> &[WidgetRef] {
&self.children
}
}
struct NeverUserScrollableScrollPhysics {
pub parent: Option<ScrollPhysicsRef>,
}
impl NeverUserScrollableScrollPhysics {
fn new() -> NeverUserScrollableScrollPhysics {
NeverUserScrollableScrollPhysics { parent: None }
}
}
impl ScrollPhysics for NeverUserScrollableScrollPhysics {
fn as_any(&self) -> &dyn Any {
self
}
fn parent(&self) -> Option<&ScrollPhysicsRef> {
self.parent.as_ref()
}
fn apply_to(&self, ancestor: Option<ScrollPhysicsRef>) -> ScrollPhysicsRef {
Rc::new(NeverUserScrollableScrollPhysics {
parent: ScrollPhysicsBase::build_parent(self, ancestor),
})
}
fn allow_user_scrolling(&self) -> bool {
false
}
}
impl Debug for NeverUserScrollableScrollPhysics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NeverUserScrollableScrollPhysics")
.field("parent", &self.parent)
.finish()
}
}
struct ScribbleCacheKey {
text_align: TextAlign,
text_direction: TextDirection,
text_scaler: TextScaler,
text_height_behavior: Option<TextHeightBehavior>,
locale: Option<Locale>,
size: Size,
inline_span: InlineSpanRef,
}
impl ScribbleCacheKey {
fn compare(&self, other: &ScribbleCacheKey) -> RenderComparison {
if std::ptr::eq(self, other) {
return RenderComparison::Identical;
}
let needs_layout = self.text_align != other.text_align
|| self.text_direction != other.text_direction
|| self.text_scaler != other.text_scaler
|| self.text_height_behavior.unwrap_or_default()
!= other.text_height_behavior.unwrap_or_default()
|| self.locale != other.locale
|| self.size != other.size;
if needs_layout {
RenderComparison::Layout
} else {
self.inline_span.compare_to(&*other.inline_span)
}
}
}
type ApplyTextBoundary =
fn(Handle<EditableTextState>, &mut App, TextPosition, bool, &dyn TextBoundary) -> TextPosition;
type GetTextBoundary = fn(Handle<EditableTextState>, &mut App) -> Box<dyn TextBoundary>;
fn insert_overridable(
app: &mut App,
actions: &mut HashMap<TypeId, ActionRef>,
context: BuildContext,
intent: TypeId,
action: ActionRef,
) {
actions.insert(intent, AnyAction::overridable(app, action, context));
}
fn code_unit_at(text: &str, index: i32) -> Option<i32> {
if index < 0 {
return None;
}
text.encode_utf16().nth(index as usize).map(i32::from)
}
#[derive(Clone, Debug)]
struct CodePointBoundary {
text: Vec<u16>,
}
impl CodePointBoundary {
fn new(text: impl AsRef<str>) -> CodePointBoundary {
CodePointBoundary {
text: text.as_ref().encode_utf16().collect(),
}
}
fn len(&self) -> i32 {
self.text.len() as i32
}
fn breaks_surrogate_pair(&self, position: i32) -> bool {
debug_assert!(position > 0 && position < self.len() && self.len() > 1);
let high = self.text[position as usize - 1];
let low = self.text[position as usize];
(0xD800..0xDC00).contains(&high) && (0xDC00..0xE000).contains(&low)
}
}
impl TextBoundary for CodePointBoundary {
fn get_leading_text_boundary_at(&self, _app: &mut App, position: i32) -> Option<i32> {
if self.text.is_empty() || position < 0 {
return None;
}
if position == 0 {
return Some(0);
}
if position >= self.len() {
return Some(self.len());
}
if self.len() <= 1 {
return Some(position);
}
Some(if self.breaks_surrogate_pair(position) {
position - 1
} else {
position
})
}
fn get_trailing_text_boundary_at(&self, _app: &mut App, position: i32) -> Option<i32> {
if self.text.is_empty() || position >= self.len() {
return None;
}
if position < 0 {
return Some(0);
}
if position == self.len() - 1 {
return Some(self.len());
}
if self.len() <= 1 {
return Some(position);
}
Some(if self.breaks_surrogate_pair(position + 1) {
position + 2
} else {
position + 1
})
}
}
struct DeleteTextAction<T: DirectionalTextEditingIntent> {
action: ActionData,
state: Handle<EditableTextState>,
get_text_boundary: GetTextBoundary,
apply_text_boundary: ApplyTextBoundary,
intent: PhantomData<T>,
}
impl<T: DirectionalTextEditingIntent> DeleteTextAction<T> {
fn new(
app: &mut App,
state: Handle<EditableTextState>,
get_text_boundary: GetTextBoundary,
apply_text_boundary: ApplyTextBoundary,
) -> Ref<DeleteTextAction<T>> {
app.create(DeleteTextAction {
action: ActionData::new(),
state,
get_text_boundary,
apply_text_boundary,
intent: PhantomData,
})
}
fn hide_toolbar_if_text_changed(self: Handle<Self>, app: &mut App, intent: &ReplaceTextIntent) {
let state = app.get(self).state;
let visible = app
.get(state)
.selection_overlay
.as_ref()
.is_some_and(|overlay| overlay.toolbar_is_visible(app));
if !visible {
return;
}
let old_value = intent.current_text_editing_value.clone();
let new_value = old_value.replaced(intent.replacement_range, &intent.replacement_text);
if old_value.text != new_value.text {
state.hide_toolbar(app, false);
}
}
}
impl<T: DirectionalTextEditingIntent> Action for DeleteTextAction<T> {
type Intent = T;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl<T: DirectionalTextEditingIntent> ContextAction for DeleteTextAction<T> {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
_intent: &T,
_context: Option<BuildContext>,
) -> bool {
let state = app.get(self).state;
!state.widget(app).read_only && state.value(app).selection.is_valid()
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
let selection = state.value(app).selection;
if !selection.is_valid() {
return None;
}
let context = context.expect("a delete needs a context");
let text_length = utf16_len(&state.value(app).text);
let atomic_boundary = state.character_boundary(app);
if !selection.is_collapsed() {
let range = TextRange::new(
atomic_boundary
.get_leading_text_boundary_at(app, selection.start())
.unwrap_or(text_length),
atomic_boundary
.get_trailing_text_boundary_at(app, selection.end() - 1)
.unwrap_or(0),
);
let replace_text_intent = ReplaceTextIntent::new(
state.value(app),
String::new(),
range,
SelectionChangedCause::Keyboard,
);
self.hide_toolbar_if_text_changed(app, &replace_text_intent);
return Actions::invoke(app, context, &replace_text_intent);
}
let boundary = (app.get(self).get_text_boundary)(state, app);
let apply = app.get(self).apply_text_boundary;
let target = apply(state, app, selection.base(), intent.forward(), &*boundary).offset;
let range_to_delete = TextSelection::new(
if intent.forward() {
atomic_boundary
.get_leading_text_boundary_at(app, selection.base_offset)
.unwrap_or(text_length)
} else {
atomic_boundary
.get_trailing_text_boundary_at(app, selection.base_offset - 1)
.unwrap_or(0)
},
target,
);
let replace_text_intent = ReplaceTextIntent::new(
state.value(app),
String::new(),
range_to_delete.range(),
SelectionChangedCause::Keyboard,
);
self.hide_toolbar_if_text_changed(app, &replace_text_intent);
Actions::invoke(app, context, &replace_text_intent)
}
}
struct UpdateTextSelectionAction<T: DirectionalCaretMovementIntent> {
action: ActionData,
state: Handle<EditableTextState>,
ignore_non_collapsed_selection: bool,
is_expand: bool,
extent_at_index: bool,
get_text_boundary: GetTextBoundary,
apply_text_boundary: ApplyTextBoundary,
intent: PhantomData<T>,
}
const NEWLINE_CODE_UNIT: i32 = 10;
impl<T: DirectionalCaretMovementIntent> UpdateTextSelectionAction<T> {
fn new(
app: &mut App,
state: Handle<EditableTextState>,
get_text_boundary: GetTextBoundary,
apply_text_boundary: ApplyTextBoundary,
ignore_non_collapsed_selection: bool,
) -> Ref<UpdateTextSelectionAction<T>> {
app.create(UpdateTextSelectionAction {
action: ActionData::new(),
state,
ignore_non_collapsed_selection,
is_expand: false,
extent_at_index: false,
get_text_boundary,
apply_text_boundary,
intent: PhantomData,
})
}
fn expanding(
self: Ref<Self>,
app: &mut App,
extent_at_index: bool,
) -> Ref<UpdateTextSelectionAction<T>> {
app.get_mut(&self).is_expand = true;
app.get_mut(&self).extent_at_index = extent_at_index;
self
}
fn is_at_wordwrap_upstream(self: Handle<Self>, app: &mut App, position: TextPosition) -> bool {
let state = app.get(self).state;
let end = TextPosition::with_affinity(
state
.render_editable(app)
.get_line_at_offset(app, position)
.end(),
TextAffinity::Upstream,
);
let text = state.value(app).text;
end == position
&& end.offset != utf16_len(&text)
&& code_unit_at(&text, position.offset) != Some(NEWLINE_CODE_UNIT)
}
fn is_at_wordwrap_downstream(
self: Handle<Self>,
app: &mut App,
position: TextPosition,
) -> bool {
let state = app.get(self).state;
let start = TextPosition::new(
state
.render_editable(app)
.get_line_at_offset(app, position)
.start(),
);
let text = state.value(app).text;
start == position
&& start.offset != 0
&& code_unit_at(&text, position.offset - 1) != Some(NEWLINE_CODE_UNIT)
}
}
impl<T: DirectionalCaretMovementIntent> Action for UpdateTextSelectionAction<T> {
type Intent = T;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl<T: DirectionalCaretMovementIntent> ContextAction for UpdateTextSelectionAction<T> {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
_intent: &T,
_context: Option<BuildContext>,
) -> bool {
let state = app.get(self).state;
if K_IS_WEB
&& state.widget(app).user_selection_enabled()
&& state.value(app).composing.is_valid()
{
return false;
}
state.value(app).selection.is_valid()
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
let selection = state.value(app).selection;
debug_assert!(selection.is_valid());
let context = context.expect("a selection move needs a context");
let collapse_selection =
intent.collapse_selection() || !state.widget(app).user_selection_enabled();
if !selection.is_collapsed()
&& !app.get(self).ignore_non_collapsed_selection
&& collapse_selection
{
let offset = if intent.forward() {
selection.end()
} else {
selection.start()
};
return Actions::invoke(
app,
context,
&UpdateSelectionIntent::new(
state.value(app),
TextSelection::collapsed(offset, TextAffinity::Downstream),
SelectionChangedCause::Keyboard,
),
);
}
let mut extent = selection.extent();
if intent.continues_at_wrap() {
if intent.forward() && self.is_at_wordwrap_upstream(app, extent) {
extent = TextPosition::new(extent.offset);
} else if !intent.forward() && self.is_at_wordwrap_downstream(app, extent) {
extent = TextPosition::with_affinity(extent.offset, TextAffinity::Upstream);
}
}
let is_expand = app.get(self).is_expand;
let extent_at_index = app.get(self).extent_at_index;
let should_target_base = is_expand
&& if intent.forward() {
selection.base_offset > selection.extent_offset
} else {
selection.base_offset < selection.extent_offset
};
let boundary = (app.get(self).get_text_boundary)(state, app);
let apply = app.get(self).apply_text_boundary;
let new_extent = apply(
state,
app,
if should_target_base {
selection.base()
} else {
extent
},
intent.forward(),
&*boundary,
);
let new_selection =
if collapse_selection || (!is_expand && new_extent.offset == selection.base_offset) {
TextSelection::from_position(new_extent)
} else if is_expand {
selection.expand_to(new_extent, extent_at_index || selection.is_collapsed())
} else {
selection.extend_to(new_extent)
};
let should_collapse_to_base = intent.collapse_at_reversal()
&& (selection.base_offset - selection.extent_offset)
* (selection.base_offset - new_selection.extent_offset)
< 0;
let new_range = if should_collapse_to_base {
TextSelection::from_position(selection.base())
} else {
new_selection
};
Actions::invoke(
app,
context,
&UpdateSelectionIntent::new(
state.value(app),
new_range,
SelectionChangedCause::Keyboard,
),
)
}
}
struct UpdateTextSelectionVerticallyAction<T: DirectionalCaretMovementIntent> {
action: ActionData,
state: Handle<EditableTextState>,
by_page: bool,
intent: PhantomData<T>,
}
impl<T: DirectionalCaretMovementIntent> UpdateTextSelectionVerticallyAction<T> {
fn new(
app: &mut App,
state: Handle<EditableTextState>,
by_page: bool,
) -> Ref<UpdateTextSelectionVerticallyAction<T>> {
app.create(UpdateTextSelectionVerticallyAction {
action: ActionData::new(),
state,
by_page,
intent: PhantomData,
})
}
}
impl<T: DirectionalCaretMovementIntent> Action for UpdateTextSelectionVerticallyAction<T> {
type Intent = T;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl<T: DirectionalCaretMovementIntent> ContextAction for UpdateTextSelectionVerticallyAction<T> {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
_intent: &T,
_context: Option<BuildContext>,
) -> bool {
let state = app.get(self).state;
if K_IS_WEB
&& state.widget(app).user_selection_enabled()
&& state.value(app).composing.is_valid()
{
return false;
}
state.value(app).selection.is_valid()
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
debug_assert!(state.value(app).selection.is_valid());
let context = context.expect("a vertical move needs a context");
let collapse_selection =
intent.collapse_selection() || !state.widget(app).user_selection_enabled();
let value = state.text_editing_value_for_text_layout_metrics(app);
if !value.selection.is_valid() {
return None;
}
let mut taken = app.get_mut(state).vertical_movement_run.take();
if taken.as_mut().is_some_and(|run| !run.is_valid(app)) {
taken = None;
app.get_mut(state).run_selection = None;
}
let mut current_run = match taken {
Some(run) => run,
None => {
let render_editable = state.render_editable(app);
let extent = render_editable
.selection(app)
.expect("the render editable has a selection")
.extent();
render_editable.start_vertical_caret_movement(app, extent)
}
};
let should_move = if app.get(self).by_page {
let height = state.render_editable(app).size(app).height();
let offset = if intent.forward() { 1.0 } else { -1.0 } * height;
current_run.move_by_offset(app, offset)
} else if intent.forward() {
current_run.move_next(app)
} else {
current_run.move_previous(app)
};
let new_extent = if should_move {
current_run.current()
} else if intent.forward() {
TextPosition::new(utf16_len(&value.text))
} else {
TextPosition::new(0)
};
let new_selection = if collapse_selection {
TextSelection::from_position(new_extent)
} else {
value.selection.extend_to(new_extent)
};
Actions::invoke(
app,
context,
&UpdateSelectionIntent::new(value, new_selection, SelectionChangedCause::Keyboard),
);
if state.value(app).selection == new_selection {
app.get_mut(state).vertical_movement_run = Some(current_run);
app.get_mut(state).run_selection = Some(new_selection);
}
None
}
}
struct WebComposingDisablingCallbackAction<T: Intent> {
action: ActionData,
state: Handle<EditableTextState>,
on_invoke: OnInvokeCallback<T>,
}
impl<T: Intent> WebComposingDisablingCallbackAction<T> {
fn new(
app: &mut App,
state: Handle<EditableTextState>,
on_invoke: OnInvokeCallback<T>,
) -> Ref<WebComposingDisablingCallbackAction<T>> {
app.create(WebComposingDisablingCallbackAction {
action: ActionData::new(),
state,
on_invoke,
})
}
}
impl<T: Intent> Action for WebComposingDisablingCallbackAction<T> {
type Intent = T;
crate::action_accessors!();
fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &T) -> bool {
let state = app.get(self).state;
!(K_IS_WEB
&& state.widget(app).user_selection_enabled()
&& state.value(app).composing.is_valid())
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
let on_invoke = Rc::clone(&app.get(self).on_invoke);
on_invoke(app, intent)
}
}
struct SelectAllAction {
action: ActionData,
state: Handle<EditableTextState>,
}
impl SelectAllAction {
fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<SelectAllAction> {
app.create(SelectAllAction {
action: ActionData::new(),
state,
})
}
}
impl Action for SelectAllAction {
type Intent = SelectAllTextIntent;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl ContextAction for SelectAllAction {
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &SelectAllTextIntent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
if !state.widget(app).user_selection_enabled() {
return None;
}
let context = context.expect("a select all needs a context");
let value = state.value(app);
let selection = TextSelection::new(0, utf16_len(&value.text));
Actions::invoke(
app,
context,
&UpdateSelectionIntent::new(value, selection, intent.cause),
)
}
}
struct CopySelectionAction {
action: ActionData,
state: Handle<EditableTextState>,
}
impl CopySelectionAction {
fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<CopySelectionAction> {
app.create(CopySelectionAction {
action: ActionData::new(),
state,
})
}
}
impl Action for CopySelectionAction {
type Intent = CopySelectionTextIntent;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl ContextAction for CopySelectionAction {
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &CopySelectionTextIntent,
_context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
let selection = state.value(app).selection;
if !selection.is_valid() || selection.is_collapsed() {
return None;
}
if !state.widget(app).user_selection_enabled() {
return None;
}
if intent.collapse_selection() {
state.cut_selection(app, intent.cause());
} else {
state.copy_selection(app, intent.cause());
}
None
}
}
struct PasteSelectionAction {
action: ActionData,
state: Handle<EditableTextState>,
}
impl PasteSelectionAction {
fn new(app: &mut App, state: Handle<EditableTextState>) -> Ref<PasteSelectionAction> {
app.create(PasteSelectionAction {
action: ActionData::new(),
state,
})
}
}
impl Action for PasteSelectionAction {
type Intent = PasteTextIntent;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl ContextAction for PasteSelectionAction {
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &PasteTextIntent,
_context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let state = app.get(self).state;
if !state.widget(app).user_selection_enabled() {
return None;
}
state.paste_text(app, intent.cause);
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::widgets::focus_manager::{FocusNode, FocusNodeLeaf};
use waft_foundation::AppCell;
fn field(app: &mut App) -> EditableText {
let controller = TextEditingController::new(app);
let focus_node = FocusNode::new(app);
let color = Color::from_argb(255, 0, 0, 0);
EditableText::new(
controller.erase(),
focus_node.into_erased(),
TextStyle::new(),
color,
color,
)
}
#[test]
fn a_multiline_field_keeps_its_newlines() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let digits = FilteringTextInputFormatter::digits_only();
let multiline = field(&mut app)
.input_formatters(vec![digits.clone()])
.max_lines(None);
assert_eq!(multiline.effective_input_formatters().len(), 1);
let single = field(&mut app).max_lines(None).max_lines(Some(1));
assert_eq!(single.effective_input_formatters().len(), 1);
let single = field(&mut app).input_formatters(vec![digits]);
assert_eq!(single.effective_input_formatters().len(), 2);
}
#[test]
fn a_later_setter_keeps_what_an_earlier_one_set() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let multiline = field(&mut app)
.keyboard_type(TextInputType::NUMBER)
.autocorrect(false)
.show_cursor(true)
.enable_interactive_selection(false)
.toolbar_options(ToolbarOptions::EMPTY)
.max_lines(None)
.read_only(true)
.autofill_hints(vec![AutofillHints::EMAIL.into()]);
assert_eq!(
multiline.effective_keyboard_type(&app),
TextInputType::NUMBER
);
assert!(!multiline.effective_autocorrect(&app));
assert!(multiline.effective_show_cursor());
assert!(!multiline.effective_enable_interactive_selection());
assert_eq!(multiline.effective_toolbar_options(), ToolbarOptions::EMPTY);
let obscured = field(&mut app)
.smart_dashes_type(SmartDashesType::Enabled)
.smart_quotes_type(SmartQuotesType::Enabled)
.obscure_text(true);
assert_eq!(
obscured.effective_smart_dashes_type(),
SmartDashesType::Enabled
);
assert_eq!(
obscured.effective_smart_quotes_type(),
SmartQuotesType::Enabled
);
}
#[test]
fn values_left_unset_follow_the_other_settings() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let read_only = field(&mut app).read_only(true);
assert!(!read_only.effective_show_cursor());
assert_eq!(
read_only.effective_toolbar_options(),
ToolbarOptions::new().select_all(true).copy(true)
);
let multiline = field(&mut app).max_lines(None);
assert_eq!(
multiline.effective_keyboard_type(&app),
TextInputType::MULTILINE
);
let email = field(&mut app).autofill_hints(vec![AutofillHints::EMAIL.into()]);
assert_eq!(
email.effective_keyboard_type(&app),
TextInputType::EMAIL_ADDRESS
);
let obscured = field(&mut app).obscure_text(true).read_only(true);
assert_eq!(
obscured.effective_smart_dashes_type(),
SmartDashesType::Disabled
);
assert!(!obscured.effective_enable_interactive_selection());
assert_eq!(obscured.effective_toolbar_options(), ToolbarOptions::EMPTY);
}
#[test]
fn controller_starts_empty() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = TextEditingController::new(&mut app);
assert_eq!(controller.text_value(&app), "");
assert!(!controller.selection(&app).is_valid());
}
#[test]
fn controller_set_text_clears_selection() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = TextEditingController::new(&mut app);
controller.set_text(&mut app, "hi");
assert_eq!(controller.text_value(&app), "hi");
assert!(!controller.selection(&app).is_valid());
}
#[test]
fn controller_from_value_keeps_composing() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let controller = TextEditingController::from_value(
&mut app,
Some(
TextEditingValue::new()
.text("abc")
.selection(TextSelection::collapsed(3, TextAffinity::Downstream))
.composing(TextRange::new(0, 3)),
),
);
assert!(controller.value(&app).is_composing_range_valid());
assert_eq!(controller.value(&app).composing, TextRange::new(0, 3));
}
use waft_painting::PaintingBinding;
use std::cell::RefCell;
use crate::test_harness::Harness;
use crate::testing::{
TargetPlatformVariant, WidgetTester, find, test_widgets, test_widgets_variant,
};
use crate::widgets::basic::{Center, SizedBox};
use crate::widgets::media_query::MediaQueryData;
fn install_fonts(app: &mut App) {
let binding = PaintingBinding::instance(app);
if !binding.has_fonts(app) {
binding.install_fonts(app, |fonts| {
fonts.add_source(valo_system_fonts::SystemFonts::load());
});
}
}
fn find_editable(app: &App, object: AnyRenderObject) -> Option<RenderHandle<RenderEditable>> {
if let Some(editable) = object.downcast::<RenderEditable>(app) {
return Some(editable);
}
let mut found = None;
object.visit_children(app, &mut |child| {
if found.is_none() {
found = find_editable(app, child);
}
});
found
}
fn app_with_clipboard(clipboard: &Rc<waft_test::MockClipboard>) -> Rc<AppCell> {
let clipboard: Rc<dyn waft_embedder::Clipboard> = Rc::clone(clipboard) as _;
let platform = waft_test::TestPlatform::new().with_clipboard(clipboard);
let cell = AppCell::with_platform(Rc::new(platform));
install_fonts(&mut cell.borrow_mut());
cell
}
fn awaited<T: 'static>(cell: &Rc<AppCell>, task: Task<T>) -> Option<T> {
let answer = Rc::new(RefCell::new(None));
let out = Rc::clone(&answer);
cell.borrow()
.spawn(async move |_cx| *out.borrow_mut() = Some(task.await));
cell.checkpoint();
answer.take()
}
fn clipboard_text(cell: &Rc<AppCell>) -> Option<String> {
let data = Clipboard::get_data(&mut cell.borrow_mut(), Clipboard::K_TEXT_PLAIN);
awaited(cell, data)
.expect("the clipboard answered")
.and_then(|data| data.text)
}
struct BoxesController {
change_notifier: ChangeNotifierData,
text_editing_controller: TextEditingControllerData,
}
impl ChangeNotifier for BoxesController {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl TextEditingControllerLeaf for BoxesController {
crate::text_editing_controller_accessors!();
fn build_text_span(
self: Handle<Self>,
app: &App,
_context: BuildContext,
style: Option<TextStyle>,
_with_composing: bool,
) -> TextSpan {
let mut children = Vec::new();
for (index, part) in self.text_value(app).split('\u{FFFC}').enumerate() {
if index > 0 {
let boxed = crate::widgets::basic::SizedBox::new()
.width(30.0)
.height(20.0);
children.push(WidgetSpan::new(boxed).into_span());
}
children.push(TextSpan::new().text(part).into_span());
}
let span = TextSpan::new().children(children);
match style {
Some(style) => span.style(style),
None => span,
}
}
}
#[test]
fn a_controller_of_its_own_puts_a_widget_inside_the_text() {
use waft_rendering::ContainerRenderObjectMixin;
let cell = AppCell::new();
let mut app = cell.borrow_mut();
install_fonts(&mut app);
let controller = app.create(BoxesController {
change_notifier: ChangeNotifierData::new(),
text_editing_controller: TextEditingControllerData::new(
TextEditingValue::new().text("ab\u{FFFC}cd"),
),
});
let focus_node = FocusNode::new(&mut app);
let color = Color::from_argb(255, 0, 0, 0);
let editable = EditableText::new(
controller.erase(),
focus_node.into_erased(),
TextStyle::new().font_size(14.0),
color,
color,
);
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(TextDirection::Ltr, editable),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
let editable =
find_editable(&app, harness.render_root(&app).as_object()).expect("a RenderEditable");
assert_eq!(editable.child_count(&app), 1, "one inline widget");
let inline = editable.first_child(&app).expect("the inline widget");
let offset = inline
.as_object()
.parent_data_of::<waft_rendering::TextParentData>(&app)
.offset()
.expect("laid out");
assert!(offset.dx() > 0.0, "after \"ab\"");
assert_eq!(inline.size(&app), Size::new(30.0, 20.0));
assert_eq!(editable.size(&app).height(), 14.0);
}
#[test]
fn cut_and_copy_do_nothing_in_obscured_mode_even_if_explicitly_called() {
let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
let cell = app_with_clipboard(&mock_clipboard);
let key = crate::framework::GlobalKey::new();
let (harness, state) = {
let mut app = cell.borrow_mut();
let controller = TextEditingController::new(&mut app).text(&mut app, "blah blah");
let focus_node = FocusNode::new(&mut app);
let editable = EditableText::new(
controller.erase(),
focus_node.into_erased(),
TextStyle::new(),
Color::from_argb(255, 255, 0, 0),
Color::from_argb(255, 128, 128, 128),
)
.obscure_text(true)
.key(key.clone().into());
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(TextDirection::Ltr, editable),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
let state = key
.current_state::<EditableTextState>(&app)
.expect("the field is mounted");
(harness, state)
};
{
let app = cell.borrow();
assert!(state.select_all_enabled(&app));
assert!(state.paste_enabled(&app));
assert!(!state.cut_enabled(&app));
assert!(!state.copy_enabled(&app));
}
{
let mut app = cell.borrow_mut();
state.select_all(&mut app, SelectionChangedCause::Toolbar);
harness.pump(&mut app);
}
let written = Clipboard::set_data(&mut cell.borrow_mut(), ClipboardData::new(""));
awaited(&cell, written).expect("the clipboard was written");
state.cut_selection(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
assert_eq!(clipboard_text(&cell).as_deref(), Some(""));
{
let mut app = cell.borrow_mut();
state.select_all(&mut app, SelectionChangedCause::Toolbar);
harness.pump(&mut app);
}
let written = Clipboard::set_data(&mut cell.borrow_mut(), ClipboardData::new(""));
awaited(&cell, written).expect("the clipboard was written");
state.copy_selection(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
assert_eq!(clipboard_text(&cell).as_deref(), Some(""));
}
#[test]
fn should_not_scroll_on_paste_if_caret_already_visible() {
let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
let cell = app_with_clipboard(&mock_clipboard);
let key = crate::framework::GlobalKey::new();
let (harness, state, controller, focus_node, scroll_controller) = {
let mut app = cell.borrow_mut();
let scroll_controller = ScrollController::default(&mut app);
let controller = TextEditingController::new(&mut app).text(
&mut app,
format!("Lorem ipsum please paste here: \n{}", ".\n".repeat(50)),
);
let focus_node = FocusNode::new(&mut app);
let editable = EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new().font_size(36.0),
Color::from_argb(255, 255, 0, 0),
Color::from_argb(255, 128, 128, 128),
)
.scroll_controller(scroll_controller.erase())
.max_lines(None)
.key(key.clone().into());
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(
TextDirection::Ltr,
Center::new().child(SizedBox::square(Some(600.0)).child(editable)),
),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
let state = key
.current_state::<EditableTextState>(&app)
.expect("the field is mounted");
(harness, state, controller, focus_node, scroll_controller)
};
let written = Clipboard::set_data(
&mut cell.borrow_mut(),
ClipboardData::new("Fairly long text to be pasted"),
);
awaited(&cell, written).expect("the clipboard was written");
{
let mut app = cell.borrow_mut();
focus_node.request_focus(&mut app, None);
assert_eq!(scroll_controller.as_controller().offset(&app), 0.0);
controller.set_selection(
&mut app,
TextSelection::collapsed(31, TextAffinity::Downstream),
);
}
let pasted = state.paste_text(&mut cell.borrow_mut(), SelectionChangedCause::Toolbar);
awaited(&cell, pasted).expect("the paste completed");
harness.pump(&mut cell.borrow_mut());
assert_eq!(
scroll_controller.as_controller().offset(&cell.borrow()),
0.0
);
}
#[test]
fn a_user_edit_scrolls_the_caret_on_screen() {
test_widgets(|tester| {
let key = crate::framework::GlobalKey::new();
let (controller, focus_node, scroll_controller) = tester.update(|app| {
(
TextEditingController::new(app),
FocusNode::new(app),
ScrollController::default(app),
)
});
let editable = EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new().font_size(20.0),
Color::from_argb(255, 255, 0, 0),
Color::from_argb(255, 128, 128, 128),
)
.scroll_controller(scroll_controller.erase())
.max_lines(None)
.key(key.clone().into());
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(
TextDirection::Ltr,
Center::new().child(SizedBox::square(Some(200.0)).child(editable)),
),
)
.into_widget();
tester.pump_widget(tree);
let state = key
.current_state::<EditableTextState>(&tester.cell.borrow_mut())
.expect("the field is mounted");
focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
tester.pump_by(Duration::from_millis(16));
assert_eq!(
scroll_controller
.as_controller()
.offset(&tester.cell.borrow()),
0.0
);
let text = "line\n".repeat(20);
let end = utf16_len(&text);
TextSelectionDelegate::user_update_text_editing_value(
state,
&mut tester.cell.borrow_mut(),
TextEditingValue::new()
.text(text)
.selection(TextSelection::collapsed(end, TextAffinity::Downstream)),
SelectionChangedCause::Keyboard,
);
for ms in [16, 16, 52, 100, 100] {
tester.pump_by(Duration::from_millis(ms));
}
let app = tester.cell.borrow();
let position = scroll_controller.as_controller().position(&app);
assert!(position.max_scroll_extent(&app) > 0.0);
assert_eq!(
scroll_controller.as_controller().offset(&app),
position.max_scroll_extent(&app)
);
});
}
fn focused_field(
clipboard: &Rc<waft_test::MockClipboard>,
text: &str,
) -> (Rc<AppCell>, Harness, Ref<TextEditingController>) {
let cell = app_with_clipboard(clipboard);
let (harness, controller) = {
let mut app = cell.borrow_mut();
let controller = TextEditingController::new(&mut app).text(&mut app, text);
let focus_node = FocusNode::new(&mut app);
let editable = EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new(),
Color::from_argb(255, 255, 0, 0),
Color::from_argb(255, 128, 128, 128),
);
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(TextDirection::Ltr, editable),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
focus_node.request_focus(&mut app, None);
(harness, controller)
};
cell.checkpoint();
let mut app = cell.borrow_mut();
harness.pump(&mut app);
controller.set_selection(&mut app, TextSelection::new(0, utf16_len(text)));
drop(app);
(cell, harness, controller)
}
#[test]
fn the_users_copy_writes_the_focused_fields_selection_through_its_request() {
let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
let (cell, _harness, _controller) = focused_field(&mock_clipboard, "copied");
let copied = waft_test::MockClipboard::new();
let into = copied.clone();
let request = waft_embedder::CopyRequest::new(move |items, options| {
waft_embedder::Clipboard::write(&into, items, options)
});
let mut app = cell.borrow_mut();
let binding = crate::WidgetsBinding::instance(&mut app);
binding.handle_clipboard_event(&mut app, waft_embedder::ClipboardEvent::Copy(request));
drop(app);
cell.checkpoint();
assert_eq!(copied.clipboard_data().as_deref(), Some("copied"));
assert_eq!(mock_clipboard.clipboard_data(), None);
}
#[test]
fn the_users_paste_reaches_the_focused_field_with_what_was_pasted() {
let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
mock_clipboard.set_clipboard_data(Some("on the clipboard".to_owned()));
let (cell, _harness, controller) = focused_field(&mock_clipboard, "replaced");
let pasted = waft_test::MockClipboard::new();
pasted.set_clipboard_data(Some("pasted".to_owned()));
let listing = cell
.borrow()
.spawn(async move |_cx| waft_embedder::Clipboard::items(&pasted).await);
let items = awaited(&cell, listing).expect("a mock clipboard lists at once");
let mut app = cell.borrow_mut();
let binding = crate::WidgetsBinding::instance(&mut app);
binding.handle_clipboard_event(&mut app, waft_embedder::ClipboardEvent::Paste(items));
drop(app);
cell.checkpoint();
assert_eq!(controller.value(&cell.borrow()).text, "pasted");
}
#[test]
fn an_edit_command_from_the_platforms_menu_reaches_the_focused_field() {
let mock_clipboard = Rc::new(waft_test::MockClipboard::new());
let (cell, _harness, controller) = focused_field(&mock_clipboard, "deleted");
let mut app = cell.borrow_mut();
let binding = crate::WidgetsBinding::instance(&mut app);
binding.handle_edit_command(&mut app, waft_embedder::EditCommand::Delete);
drop(app);
cell.checkpoint();
assert_eq!(controller.value(&cell.borrow()).text, "");
}
#[test]
fn editable_text_builds_a_render_editable() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
install_fonts(&mut app);
let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
let focus_node = FocusNode::new(&mut app);
let editable = EditableText::new(
controller.erase(),
focus_node.into_erased(),
TextStyle::new(),
Color::from_argb(255, 0, 0, 0),
Color::from_argb(255, 128, 128, 128),
);
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(TextDirection::Ltr, editable),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
let root = harness.render_root(&app).as_object();
let render_editable =
find_editable(&app, root).expect("EditableText should mount a RenderEditable");
let size = render_editable.size(&app);
assert!(
size.width() > 0.0 && size.height() > 0.0,
"RenderEditable should have a size, got {size:?}"
);
}
#[test]
fn a_focused_field_leaves_the_tree_without_its_callbacks_outliving_it() {
use crate::{ListenableBuilder, SizedBox, primary_focus};
use waft_foundation::ValueNotifier;
test_widgets(|tester| {
let (shown, tree) = {
let mut app = tester.cell.borrow_mut();
let shown = app.create(ValueNotifier::new(true));
let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
let focus_node = FocusNode::new(&mut app);
let visible = shown.handle();
let field = ListenableBuilder::new(Rc::new(shown.clone()), move |app, _, _| {
if !*app.get(visible).value() {
return SizedBox::shrink().into_widget();
}
EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new(),
Color::from_argb(255, 0, 0, 0),
Color::from_argb(255, 128, 128, 128),
)
.autofocus(true)
.into_widget()
});
(shown, Directionality::new(TextDirection::Ltr, field))
};
tester.pump_widget(tree);
let pump = |tester: &mut WidgetTester| {
for _ in 0..5 {
tester.pump_by(Duration::from_millis(20));
}
};
pump(tester);
assert!(
primary_focus(&mut tester.cell.borrow_mut()).is_some(),
"the field took the focus and opened its input connection"
);
shown.set_value(&mut tester.cell.borrow_mut(), false);
pump(tester);
});
}
#[test]
fn a_field_removed_before_its_keyboard_callbacks_run_does_not_crash() {
use crate::{ListenableBuilder, SizedBox, primary_focus};
use waft_embedder::ViewPadding;
use waft_foundation::ValueNotifier;
test_widgets(|tester| {
tester.view().set_physical_size(Size::new(300.0, 600.0));
tester.view().set_device_pixel_ratio(1.0);
let (shown, tree) = {
let mut app = tester.cell.borrow_mut();
let shown = app.create(ValueNotifier::new(true));
let controller = TextEditingController::new(&mut app).text(&mut app, "hello");
let focus_node = FocusNode::new(&mut app);
let visible = shown.handle();
let field = ListenableBuilder::new(Rc::new(shown.clone()), move |app, _, _| {
if !*app.get(visible).value() {
return SizedBox::shrink().into_widget();
}
EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new(),
Color::from_argb(255, 0, 0, 0),
Color::from_argb(255, 128, 128, 128),
)
.autofocus(true)
.into_widget()
});
(shown, Directionality::new(TextDirection::Ltr, field))
};
tester.pump_widget(tree);
let pump = |tester: &mut WidgetTester| {
for _ in 0..5 {
tester.pump_by(Duration::from_millis(20));
}
};
pump(tester);
assert!(
primary_focus(&mut tester.cell.borrow_mut()).is_some(),
"the field took the focus and listens for the keyboard"
);
tester.view().set_view_insets(ViewPadding {
bottom: 250.0,
..ViewPadding::ZERO
});
shown.set_value(&mut tester.cell.borrow_mut(), false);
pump(tester);
});
}
struct ObscuredField {
state: Handle<EditableTextState>,
obscure_text: Rc<Cell<bool>>,
rebuild: Ref<waft_foundation::ValueNotifier<u32>>,
}
impl ObscuredField {
fn pump(tester: &mut WidgetTester) -> ObscuredField {
use crate::ListenableBuilder;
use crate::framework::GlobalKey;
use waft_foundation::ValueNotifier;
let key = GlobalKey::new();
let obscure_text = Rc::new(Cell::new(true));
let (rebuild, tree) = {
let mut app = tester.cell.borrow_mut();
let rebuild = app.create(ValueNotifier::new(0));
let controller = TextEditingController::new(&mut app);
let focus_node = FocusNode::new(&mut app);
let field_key = key.clone();
let obscured = Rc::clone(&obscure_text);
let field = ListenableBuilder::new(Rc::new(rebuild.clone()), move |_, _, _| {
EditableText::new(
controller.erase(),
focus_node.erase(),
TextStyle::new(),
Color::from_argb(255, 0, 0, 255),
Color::from_argb(255, 128, 128, 128),
)
.obscure_text(obscured.get())
.key(field_key.clone().into())
.into_widget()
});
let tree = MediaQuery::new(
MediaQueryData::new(),
Directionality::new(TextDirection::Ltr, field),
)
.into_widget();
(rebuild, tree)
};
tester.pump_widget(tree);
let state = key
.current_state::<EditableTextState>(&tester.cell.borrow())
.expect("the field is mounted");
ObscuredField {
state,
obscure_text,
rebuild,
}
}
fn set_obscure_text(&self, tester: &WidgetTester, obscure_text: bool) {
self.obscure_text.set(obscure_text);
let mut app = tester.cell.borrow_mut();
let next = *app.get(&self.rebuild).value() + 1;
self.rebuild.set_value(&mut app, next);
}
fn shown_text(&self, tester: &WidgetTester) -> String {
let mut app = tester.cell.borrow_mut();
let render_editable = self.state.render_editable(&app);
render_editable.plain_text(&mut app)
}
}
fn selection_rects_sent(tester: &WidgetTester) -> Vec<Vec<SelectionRect>> {
tester
.view()
.test_host()
.text_input_calls()
.into_iter()
.filter_map(|call| match call {
waft_test::TextInputCall::SetSelectionRects(rects) => Some(rects),
_ => None,
})
.collect()
}
const HALF_A_BLINK: Duration = Duration::from_millis(500);
fn mobile() -> TargetPlatformVariant {
TargetPlatformVariant::new([
TargetPlatform::IOS,
TargetPlatform::Android,
TargetPlatform::Fuchsia,
])
}
#[test]
fn password_briefly_shows_last_character_when_entered_on_mobile() {
test_widgets_variant(mobile(), |tester| {
let field = ObscuredField::pump(tester);
tester.enter_text(find::by_type::<EditableText>(), "AA");
tester.pump();
tester.enter_text(find::by_type::<EditableText>(), "AAA");
tester.pump();
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}A");
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
});
}
#[test]
fn selection_rects_are_sent_on_ios_once_the_text_is_laid_out() {
let tester = &mut WidgetTester::on(TargetPlatform::IOS);
let field = ObscuredField::pump(tester);
field.set_obscure_text(tester, false);
tester.enter_text(find::by_type::<EditableText>(), "Text1");
tester.pump();
let sent = selection_rects_sent(tester);
let rects: Vec<(i32, Rect)> = sent
.last()
.expect("the rects of the laid out text")
.iter()
.map(|rect| (rect.position, rect.bounds))
.collect();
assert_eq!(
rects,
[
(0, Rect::from_ltrb(0.0, 0.0, 14.0, 14.0)),
(1, Rect::from_ltrb(14.0, 0.0, 28.0, 14.0)),
(2, Rect::from_ltrb(28.0, 0.0, 42.0, 14.0)),
(3, Rect::from_ltrb(42.0, 0.0, 56.0, 14.0)),
(4, Rect::from_ltrb(56.0, 0.0, 70.0, 14.0)),
]
);
tester.pump();
assert_eq!(selection_rects_sent(tester).len(), sent.len(), "sent once");
let tester = &mut WidgetTester::on(TargetPlatform::Android);
let _field = ObscuredField::pump(tester);
tester.enter_text(find::by_type::<EditableText>(), "Text1");
tester.pump();
assert!(selection_rects_sent(tester).is_empty(), "iOS alone");
}
#[test]
fn password_briefly_does_not_show_last_character_when_disabled_by_system() {
test_widgets(|tester| {
let field = ObscuredField::pump(tester);
tester.enter_text(find::by_type::<EditableText>(), "AA");
tester.pump();
tester.enter_text(find::by_type::<EditableText>(), "AAA");
tester.pump();
tester.platform().set_briefly_show_password(false);
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}A");
tester.pump_by(HALF_A_BLINK);
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
});
}
#[test]
fn prevent_last_character_visibility_in_obscure_text_when_obscure_text_is_toggled_on_mobile() {
test_widgets_variant(mobile(), |tester| {
let field = ObscuredField::pump(tester);
tester.show_keyboard(find::by_type::<EditableText>());
tester.enter_text(find::by_type::<EditableText>(), "H");
tester.pump();
tester.enter_text(find::by_type::<EditableText>(), "HH");
tester.pump();
assert_eq!(field.shown_text(tester), "\u{2022}H");
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
tester.pump_by(HALF_A_BLINK);
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}");
tester.enter_text(find::by_type::<EditableText>(), "HHH");
tester.pump();
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}H");
field.set_obscure_text(tester, false);
tester.pump();
assert_eq!(field.shown_text(tester), "HHH");
field.set_obscure_text(tester, true);
tester.pump();
assert_eq!(field.shown_text(tester), "\u{2022}\u{2022}\u{2022}");
});
}
#[test]
fn editable_text_respects_the_media_query_spacing_overrides_on_its_strut() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
install_fonts(&mut app);
let controller = TextEditingController::new(&mut app);
let focus_node = FocusNode::new(&mut app);
let color = Color::from_argb(255, 0, 0, 0);
let editable_text = EditableText::new(
controller.erase(),
focus_node.into_erased(),
TextStyle::new().font_weight(FontWeight::NORMAL),
color,
color,
)
.strut_style(StrutStyle::new().height(0.9));
let tree = MediaQuery::new(
MediaQueryData::new()
.line_height_scale_factor_override(2.0)
.letter_spacing_override(2.0)
.word_spacing_override(2.0),
Directionality::new(TextDirection::Ltr, editable_text),
)
.into_widget();
let harness = Harness::mount(&mut app, tree);
harness.pump(&mut app);
controller.set_text(&mut app, "foo");
harness.pump(&mut app);
let editable =
find_editable(&app, harness.render_root(&app).as_object()).expect("a RenderEditable");
let style = editable
.text(&app)
.expect("an editable has text")
.style()
.cloned()
.expect("a style");
assert_eq!(style.height, Some(2.0));
assert_eq!(style.letter_spacing, Some(2.0));
assert_eq!(style.word_spacing, Some(2.0));
assert_eq!(
editable
.strut_style(&app)
.and_then(|strut_style| strut_style.height),
Some(2.0)
);
}
}