Skip to main content

wgpui_base/input/base/
state.rs

1//! A text input field that allows the user to enter text.
2//!
3//! Based on the `Input` example from the `gpui` crate.
4//! <https://github.com/zed-industries/zed/blob/main/crates/gpui/examples/input.rs>
5use ropey::{Rope, RopeSlice};
6use serde::Deserialize;
7use std::borrow::Cow;
8use std::cell::Cell;
9use std::ops::Range;
10use std::rc::Rc;
11use sum_tree::Bias;
12use unicode_segmentation::*;
13use wgpui::TextAlign;
14use wgpui::{
15    Action, App, AppContext, Bounds, ClipboardItem, Context, Edges, Entity, EntityInputHandler,
16    EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding,
17    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point,
18    Render, ScrollEvent, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _,
19    Subscription, UTF16Selection, WeakFocusHandle, Window, actions, div, point,
20    prelude::FluentBuilder as _, px,
21};
22use wgpui::{Autocapitalize, TextInputAction, TextInputConfiguration};
23
24use super::{
25    DiagnosticSet, DisplayMap, InputContextMenuCapabilities, InputEditorStyle,
26    InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep, WrappingIndent,
27    blink_cursor::BlinkCursor,
28    change::Change,
29    cursor::{CursorSelection, Selections},
30    element::{
31        EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, TextElement,
32        clamp_horizontal_scroll_offset,
33    },
34    kind::InputModeKind,
35    mask_pattern::normalize_number_input,
36    mode::LayoutMode,
37    undo_manager::{EditIntent, UndoManager},
38};
39use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
40use crate::input::blink_cursor::CURSOR_WIDTH;
41use crate::input::movement::MoveDirection;
42use crate::input::{
43    InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout,
44};
45use crate::overscroll::Overscroll;
46use crate::{AutoScroll, StepAction, TestSupportExt as _};
47
48pub(super) const EDITOR_ELEMENT_ID: &str = "input-state";
49
50/// Vertical clearance to retain when revealing a text position.
51pub(crate) enum ScrollPadding {
52    Minimal,
53    SurroundingLines,
54}
55
56#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
57#[action(namespace = input, no_json)]
58pub struct Enter {
59    /// Is confirm with secondary.
60    pub secondary: bool,
61    /// Whether the Shift modifier was held when Enter was pressed.
62    pub shift: bool,
63}
64
65impl Enter {
66    /// Returns true if `action` is a primary `Enter` action (`secondary: false`),
67    /// regardless of whether Shift was held.
68    pub fn is_primary(action: &dyn Action) -> bool {
69        action.partial_eq(&Enter {
70            secondary: false,
71            shift: false,
72        }) || action.partial_eq(&Enter {
73            secondary: false,
74            shift: true,
75        })
76    }
77}
78
79actions!(
80    input,
81    [
82        ActivateToken,
83        Backspace,
84        Delete,
85        DeleteToBeginningOfLine,
86        DeleteToEndOfLine,
87        DeleteToPreviousWordStart,
88        DeleteToNextWordEnd,
89        Indent,
90        Outdent,
91        IndentInline,
92        OutdentInline,
93        MoveUp,
94        MoveDown,
95        MoveLeft,
96        MoveRight,
97        MoveHome,
98        MoveEnd,
99        MovePageUp,
100        MovePageDown,
101        AddCursorAbove,
102        AddCursorBelow,
103        SelectAll,
104        SelectToStartOfLine,
105        SelectToEndOfLine,
106        SelectToStart,
107        SelectToEnd,
108        SelectToPreviousWordStart,
109        SelectToNextWordEnd,
110        ShowCharacterPalette,
111        Copy,
112        Cut,
113        Paste,
114        Undo,
115        Redo,
116        MoveToStartOfLine,
117        MoveToEndOfLine,
118        MoveToStart,
119        MoveToEnd,
120        MoveToPreviousWord,
121        MoveToNextWord,
122        Escape,
123        ToggleCodeActions,
124        ShowCompletions,
125        Search,
126        Replace,
127        GoToDefinition,
128    ]
129);
130
131#[derive(Clone)]
132pub enum InputEvent {
133    Change,
134    PressEnter { secondary: bool, shift: bool },
135    Focus,
136    Blur,
137}
138
139pub(super) const CONTEXT: &str = "Input";
140
141pub(crate) fn init(cx: &mut App) {
142    cx.bind_keys([
143        KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
144        KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
145        #[cfg(target_os = "macos")]
146        KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
147        KeyBinding::new("delete", Delete, Some(CONTEXT)),
148        KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
149        #[cfg(target_os = "macos")]
150        KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
151        #[cfg(target_os = "macos")]
152        KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
153        #[cfg(target_os = "macos")]
154        KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
155        #[cfg(not(target_os = "macos"))]
156        KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
157        #[cfg(target_os = "macos")]
158        KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
159        #[cfg(not(target_os = "macos"))]
160        KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
161        KeyBinding::new(
162            "enter",
163            Enter {
164                secondary: false,
165                shift: false,
166            },
167            Some(CONTEXT),
168        ),
169        KeyBinding::new(
170            "shift-enter",
171            Enter {
172                secondary: false,
173                shift: true,
174            },
175            Some(CONTEXT),
176        ),
177        KeyBinding::new(
178            if cx.platform_info().is_mac() {
179                "cmd-enter"
180            } else {
181                "ctrl-enter"
182            },
183            Enter {
184                secondary: true,
185                shift: false,
186            },
187            Some(CONTEXT),
188        ),
189        KeyBinding::new("escape", Escape, Some(CONTEXT)),
190        KeyBinding::new("up", MoveUp, Some(CONTEXT)),
191        KeyBinding::new("down", MoveDown, Some(CONTEXT)),
192        KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
193        KeyBinding::new("right", MoveRight, Some(CONTEXT)),
194        KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
195        KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
196        KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
197        KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
198        #[cfg(target_os = "macos")]
199        KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
200        #[cfg(not(target_os = "macos"))]
201        KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
202        #[cfg(target_os = "macos")]
203        KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
204        #[cfg(not(target_os = "macos"))]
205        KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
206        KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
207        KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
208        KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
209        KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
210        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
211        KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
212        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
213        KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
214        // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them.
215        #[cfg(target_os = "macos")]
216        KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
217        #[cfg(target_os = "macos")]
218        KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
219        #[cfg(target_os = "windows")]
220        KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
221        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
222        KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
223        #[cfg(target_os = "windows")]
224        KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
225        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
226        KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
227        KeyBinding::new("home", MoveHome, Some(CONTEXT)),
228        KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
229        #[cfg(not(target_os = "macos"))]
230        KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
231        #[cfg(not(target_os = "macos"))]
232        KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
233        #[cfg(not(target_os = "macos"))]
234        KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
235        #[cfg(not(target_os = "macos"))]
236        KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
237        KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
238        KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
239        #[cfg(target_os = "macos")]
240        KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
241        #[cfg(target_os = "macos")]
242        KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
243        #[cfg(target_os = "macos")]
244        KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
245        #[cfg(target_os = "macos")]
246        KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
247        #[cfg(any(target_os = "macos", target_os = "linux"))]
248        KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
249        #[cfg(not(target_os = "macos"))]
250        KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
251        #[cfg(any(target_os = "macos", target_os = "linux"))]
252        KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
253        #[cfg(not(target_os = "macos"))]
254        KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
255        #[cfg(target_os = "macos")]
256        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
257        #[cfg(target_os = "macos")]
258        KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
259        #[cfg(not(target_os = "macos"))]
260        KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
261        #[cfg(target_os = "macos")]
262        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
263        #[cfg(not(target_os = "macos"))]
264        KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
265        #[cfg(target_os = "macos")]
266        KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
267        #[cfg(not(target_os = "macos"))]
268        KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
269        #[cfg(target_os = "macos")]
270        KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
271        #[cfg(not(target_os = "macos"))]
272        KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
273        #[cfg(target_os = "macos")]
274        KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
275        #[cfg(target_os = "macos")]
276        KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
277        #[cfg(target_os = "macos")]
278        KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
279        #[cfg(target_os = "macos")]
280        KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
281        #[cfg(target_os = "macos")]
282        KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
283        #[cfg(target_os = "macos")]
284        KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
285        #[cfg(target_os = "macos")]
286        KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
287        #[cfg(target_os = "macos")]
288        KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
289        #[cfg(target_os = "macos")]
290        KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
291        #[cfg(target_os = "macos")]
292        KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
293        #[cfg(not(target_os = "macos"))]
294        KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
295        #[cfg(not(target_os = "macos"))]
296        KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
297        #[cfg(target_os = "macos")]
298        KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
299        #[cfg(target_os = "macos")]
300        KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
301        #[cfg(not(target_os = "macos"))]
302        KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
303        #[cfg(not(target_os = "macos"))]
304        KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
305        #[cfg(target_os = "macos")]
306        KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
307        #[cfg(not(target_os = "macos"))]
308        KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
309        #[cfg(target_os = "macos")]
310        KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
311        #[cfg(not(target_os = "macos"))]
312        KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
313        #[cfg(target_os = "macos")]
314        KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
315        #[cfg(not(target_os = "macos"))]
316        KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
317    ]);
318}
319
320/// A mouse position resolved for a columnar (block) selection.
321///
322/// A position past the end of a short row has no glyph to land on, so `offset` clips to
323/// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they
324/// say which column the pointer really reached, which is what a block spanning rows of
325/// different lengths has to be measured in.
326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
327pub(super) struct ColumnarPoint {
328    offset: usize,
329    columns_past_line_end: usize,
330}
331
332impl ColumnarPoint {
333    pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
334        Self {
335            offset,
336            columns_past_line_end,
337        }
338    }
339}
340
341/// The document and selections a paste was asked to replace, taken when the
342/// `Paste` action ran so a clipboard read that resolves later can tell
343/// whether it still applies. See [`InputBaseState::paste_target`].
344#[derive(Debug, PartialEq)]
345struct PasteTarget {
346    document_revision: u64,
347    selections: Vec<CursorSelection>,
348}
349
350/// Caret positioning geometry from the input's latest prepaint.
351///
352/// Unlike `last_layout` (published at paint time), this is stashed during
353/// prepaint so caret-anchored popups can position themselves from the
354/// current frame's geometry in their deferred prepaint, instead of the
355/// previous frame's paint.
356#[derive(Clone, Copy, Debug)]
357#[doc(hidden)]
358pub struct PrepaintCaretGeometry {
359    cursor_bounds: Bounds<Pixels>,
360    line_height: Pixels,
361    input_bounds: Bounds<Pixels>,
362    scroll_offset: Point<Pixels>,
363    /// A resize owns visibility while its requested repaint settles.
364    pub(super) resize_reveal_owned: bool,
365}
366
367impl PrepaintCaretGeometry {
368    pub(super) fn new(
369        cursor_bounds: Bounds<Pixels>,
370        line_height: Pixels,
371        input_bounds: Bounds<Pixels>,
372        scroll_offset: Point<Pixels>,
373    ) -> Self {
374        Self {
375            cursor_bounds,
376            line_height,
377            input_bounds,
378            scroll_offset,
379            resize_reveal_owned: false,
380        }
381    }
382
383    /// The active caret's bounds from the fresh prepaint layout.
384    pub fn cursor_bounds(&self) -> Bounds<Pixels> {
385        self.cursor_bounds
386    }
387
388    /// Line height from the fresh prepaint layout.
389    pub fn line_height(&self) -> Pixels {
390        self.line_height
391    }
392
393    /// The input container bounds from the fresh prepaint.
394    pub fn input_bounds(&self) -> Bounds<Pixels> {
395        self.input_bounds
396    }
397
398    /// The scroll offset that will be in effect after paint, clamped like
399    /// `InputBaseState::update_scroll_offset` clamps it.
400    pub fn scroll_offset(&self) -> Point<Pixels> {
401        self.scroll_offset
402    }
403}
404
405/// The shared text-editing engine behind [`crate::input::InputState`],
406/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
407///
408/// `M` is the mode marker: it carries no data and only decides which methods
409/// exist, so an ordinary input cannot reach the editor's language features.
410///
411/// The three states are type aliases of this one, which is why this name is
412/// public: an alias is only as usable as the type behind it, so hiding this
413/// would leave `InputState` unable to do anything. Prefer naming the aliases
414/// — write `InputState`, not `InputBaseState<InputMode>`.
415pub struct InputBaseState<M: InputModeKind> {
416    /// State only this mode needs. See [`InputModeKind::Extras`].
417    pub(crate) extras: M::Extras,
418    pub(super) focus_handle: FocusHandle,
419    selection_focus: Option<WeakFocusHandle>,
420    pub(super) mode: LayoutMode,
421    pub(super) text: Rope,
422    pub(super) display_map: DisplayMap,
423    pub(super) undo_manager: UndoManager,
424    pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
425    pub(super) pending_token: Option<super::InlineToken>,
426    pub(super) replaying_history: bool,
427    pub(super) validated_token_edit: bool,
428    pub(super) document_revision: u64,
429    pub(super) token_presentation: super::InlineTokenPresentation,
430    pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
431    /// Real per-frame bounds of the placed token elements, keyed by token
432    /// start offset; used for hover payloads and stale-hover reconciliation.
433    pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
434    /// The currently hovered token: its entered span, last measured bounds,
435    /// and UTF-16 range as of entry. Retained so hover exit can still be
436    /// delivered when the token is removed, replaced, scrolled out, or
437    /// disabled.
438    pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
439    pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
440    /// The start offset of a pressed token, with the document revision and
441    /// pointer position at the press.
442    pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
443    pub(super) search_session: super::SearchSession,
444    /// Advances every time search is explicitly invoked. See
445    /// [`InputBaseState::search_activation_revision`].
446    pub(super) search_activation_revision: u64,
447    pub(super) searchable: bool,
448    pub(super) replaceable: bool,
449    pub(super) soft_wrap: bool,
450    pub(super) wrapping_indent: WrappingIndent,
451    pub(super) scroll_beyond_last_line: Option<usize>,
452    pub(super) cursor_surrounding_lines: Option<usize>,
453    pub(super) blink_cursor: Entity<BlinkCursor>,
454    pub(super) loading: bool,
455    /// The cursors and selections.
456    ///
457    /// Always contains at least one selection where index 0 is the active cursor.
458    pub(super) selections: Selections,
459    /// Range for save the selected word, use to keep word range when drag move.
460    pub(super) selected_word_range: Option<CursorSelection>,
461    /// The marked range is the temporary insert text on IME typing.
462    pub(super) ime_marked_range: Option<CursorSelection>,
463    pub(super) last_layout: Option<LastLayout>,
464    /// Fresh caret geometry stashed during prepaint for caret-anchored popups.
465    ///
466    /// Popups are positioned in their deferred prepaint, which runs after the
467    /// input's prepaint but before its paint, so they read this instead of
468    /// the previous frame's `last_layout`.
469    pub(crate) prepaint_caret_geometry: Option<PrepaintCaretGeometry>,
470    pub(super) last_cursor: Option<usize>,
471    /// The input container bounds
472    pub(super) input_bounds: Bounds<Pixels>,
473    /// The text bounds
474    pub(super) last_bounds: Option<Bounds<Pixels>>,
475    /// The fully visible part of the window this input last asked its scroll
476    /// containers to reveal it in, while focused. `None` while unfocused.
477    pub(super) revealed_viewport: Option<Bounds<Pixels>>,
478    pub(super) last_selected_range: Option<CursorSelection>,
479    pub(super) selecting: bool,
480    /// Anchor point of an in-progress columnar (block) selection.
481    pub(super) column_select_start: Option<ColumnarPoint>,
482    /// The selection a long press made, with its handles and edit menu.
483    pub(super) touch_selection: super::touch::TouchSelection,
484    pub(crate) disabled: bool,
485    pub(crate) readonly: bool,
486    pub(crate) text_align: TextAlign,
487    pub(super) masked: bool,
488    pub(super) clean_on_escape: bool,
489    pub(super) submit_on_enter: bool,
490    /// Overrides for [`Self::text_input_configuration`].
491    pub(super) input_action: Option<TextInputAction>,
492    pub(super) autocorrect: Option<bool>,
493    pub(super) autocapitalize: Option<Autocapitalize>,
494    pub(super) show_whitespaces: bool,
495    /// This flag tells the renderer to prefer the end of the current visual line.
496    pub(crate) cursor_line_end_affinity: bool,
497    pub(super) pattern: Option<regex::Regex>,
498    pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
499    /// The step strategy for [`NumberInput`](crate::NumberInput) to increment/decrement.
500    /// See [`Self::step`] and [`Self::step_by`].
501    pub(crate) number_step: Option<NumberStep>,
502    /// The minimum value for [`NumberInput`](crate::NumberInput). See [`Self::min`].
503    pub(crate) number_min: Option<f64>,
504    /// The maximum value for [`NumberInput`](crate::NumberInput). See [`Self::max`].
505    pub(crate) number_max: Option<f64>,
506    pub(crate) scroll_handle: ScrollHandle,
507    /// Whether the text stretches past its ends, see [`Self::scroll_bounce`].
508    scroll_bounce: bool,
509    /// The text's stretch past an end, while it lasts.
510    pub(super) overscroll: Overscroll,
511    /// The deferred scroll offset to apply on next layout.
512    pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
513    /// The size of the scrollable content.
514    pub(crate) scroll_size: wgpui::Size<Pixels>,
515    pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
516    /// The widest measured unwrapped line width and what it was measured for.
517    pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
518    pub(super) editor_paddings: Edges<Pixels>,
519    /// The style this state paints with: what was projected onto it, with
520    /// every colour left unset resolved from the palette that is current. It
521    /// is rebuilt at the top of every render, which is what keeps it current
522    /// when the palette changes after the state was built.
523    pub(super) editor_style: InputEditorStyle,
524    /// What a consumer projected, kept verbatim so that resolution never
525    /// consumes its own output: resolving in place would fill the unset
526    /// colours once and then never see them as unset again, which is the same
527    /// freeze in a different place.
528    projected_editor_style: InputEditorStyle,
529    accessibility: Option<InputAccessibility>,
530    /// What paints in place of Base's editor scrollbar, when a consumer
531    /// supplies its own.
532    pub(super) scrollbar_renderer: Option<crate::input::EditorScrollbarRenderer>,
533
534    /// The mask pattern for formatting the input text
535    pub(crate) mask_pattern: MaskPattern,
536    /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`]
537    /// or [`Self::set_mask_pattern`]), to let [`NumberInput`](crate::NumberInput) only apply
538    /// its default mask when the user has not made an explicit choice.
539    pub(super) mask_pattern_set: bool,
540    pub(super) placeholder: SharedString,
541
542    /// Diagnostic currently requested by pointer hover; applications render it.
543    pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
544
545    context_menu_handler: Option<
546        Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
547    >,
548    pending_context_menu: Option<(Point<Pixels>, usize)>,
549
550    /// Whether the context menu that shows on right-click is enabled.
551    ///
552    pub(super) enable_context_menu: bool,
553
554    /// A flag to indicate if we are currently inserting a completion item.
555    pub(super) completion_inserting: bool,
556    pub(super) overlay_action_handler: Option<
557        Rc<
558            dyn Fn(
559                super::InputOverlayKind,
560                Box<dyn Action>,
561                &mut Window,
562                &mut Context<InputBaseState<M>>,
563            ) -> bool,
564        >,
565    >,
566
567    /// A flag to indicate if we have a pending update to the text.
568    ///
569    /// If true, will call some update (for example LSP, Syntax Highlight) before render.
570    _pending_update: bool,
571    /// A flag to indicate if we should ignore the next completion event.
572    pub(super) silent_replace_text: bool,
573    /// A flag to indicate if we should emit InputEvents.
574    pub(super) emit_events: bool,
575
576    _subscriptions: Vec<Subscription>,
577
578    pub(super) auto_scroll: AutoScroll,
579}
580
581/// Accessibility presentation for the editor's existing keyboard-focus boundary.
582///
583/// Frames and their addon controls keep their own identities. This projection
584/// does not create a focus handle or register another text Tab stop. The engine
585/// supplies the live value and guards accessibility actions against its current
586/// disabled, read-only and masked state.
587#[derive(Clone, Debug)]
588pub struct InputAccessibility {
589    role: Option<wgpui::Role>,
590    label: Option<SharedString>,
591    placeholder: Option<SharedString>,
592    accessibility_id: Option<SharedString>,
593    value_exposed: bool,
594}
595
596impl InputAccessibility {
597    pub fn new(role: Option<wgpui::Role>) -> Self {
598        Self {
599            role,
600            label: None,
601            placeholder: None,
602            accessibility_id: None,
603            value_exposed: true,
604        }
605    }
606
607    pub fn with_label(mut self, label: Option<SharedString>) -> Self {
608        self.label = label;
609        self
610    }
611
612    pub fn with_placeholder(mut self, placeholder: Option<SharedString>) -> Self {
613        self.placeholder = placeholder;
614        self
615    }
616
617    pub fn with_accessibility_id(mut self, id: Option<SharedString>) -> Self {
618        self.accessibility_id = id;
619        self
620    }
621
622    /// Suppress values for secret content even when the mask is revealed.
623    pub fn with_value_exposed(mut self, exposed: bool) -> Self {
624        self.value_exposed = exposed;
625        self
626    }
627
628    pub fn role(&self) -> Option<wgpui::Role> {
629        self.role
630    }
631
632    pub fn label(&self) -> Option<&SharedString> {
633        self.label.as_ref()
634    }
635
636    pub fn placeholder(&self) -> Option<&SharedString> {
637        self.placeholder.as_ref()
638    }
639
640    pub fn accessibility_id(&self) -> Option<&SharedString> {
641        self.accessibility_id.as_ref()
642    }
643
644    pub fn value_exposed(&self) -> bool {
645        self.value_exposed
646    }
647}
648
649/// Read-only styling data exposed to presentation facades.
650///
651/// The fields are private and read through the methods below, so that a new
652/// one can be added without breaking the facades.
653#[derive(Clone)]
654pub struct InputPresentation {
655    focus_handle: FocusHandle,
656    disabled: bool,
657    readonly: bool,
658    loading: bool,
659    masked: bool,
660    multi_line: bool,
661    code_editor: bool,
662    text_align: TextAlign,
663    placeholder: SharedString,
664    mask_placeholder: Option<String>,
665}
666
667impl InputPresentation {
668    pub fn focus_handle(&self) -> &FocusHandle {
669        &self.focus_handle
670    }
671
672    pub fn is_disabled(&self) -> bool {
673        self.disabled
674    }
675
676    pub fn is_readonly(&self) -> bool {
677        self.readonly
678    }
679
680    /// Returns true if the user is allowed to change the text.
681    ///
682    /// See also: [`InputBaseState::is_editable`].
683    pub fn is_editable(&self) -> bool {
684        !self.disabled && !self.readonly
685    }
686
687    pub fn is_loading(&self) -> bool {
688        self.loading
689    }
690
691    pub fn is_masked(&self) -> bool {
692        self.masked
693    }
694
695    pub fn is_multi_line(&self) -> bool {
696        self.multi_line
697    }
698
699    pub fn is_code_editor(&self) -> bool {
700        self.code_editor
701    }
702
703    pub fn text_align(&self) -> TextAlign {
704        self.text_align
705    }
706
707    pub fn placeholder(&self) -> &SharedString {
708        &self.placeholder
709    }
710
711    /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
712    pub fn mask_placeholder(&self) -> Option<&str> {
713        self.mask_placeholder.as_deref()
714    }
715}
716
717impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
718
719impl<M: InputModeKind> InputBaseState<M> {
720    #[doc(hidden)]
721    pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
722        let layout = self.last_layout.as_ref()?;
723        Some((layout.cursor_bounds?, layout.line_height))
724    }
725
726    /// Caret geometry from the latest prepaint, for caret-anchored popups.
727    ///
728    /// Popups positioned in their deferred prepaint read this to anchor to
729    /// the current frame's caret instead of the previous frame's paint.
730    #[doc(hidden)]
731    pub fn prepaint_caret_geometry(&self) -> Option<PrepaintCaretGeometry> {
732        self.prepaint_caret_geometry
733    }
734
735    pub fn input_bounds(&self) -> Bounds<Pixels> {
736        self.input_bounds
737    }
738
739    pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
740        self.last_bounds
741    }
742
743    /// The cached display map for querying wrapped rows and display positions.
744    ///
745    /// Reading this does not prepare text or force layout. Before the first
746    /// layout, [`DisplayMap::wrap_row_count`] can be zero; prepared empty text
747    /// has one row. The count describes content, independent of minimum rows,
748    /// auto-grow limits and viewport height.
749    ///
750    /// Text edits use the cached wrapping parameters. Layout refreshes the
751    /// cache after width or font changes; consume that count on a subsequent
752    /// render, or use [`Self::prewrap`] to prepare it before the first layout.
753    pub fn display_map(&self) -> &DisplayMap {
754        &self.display_map
755    }
756
757    /// Wrap the text for `font`, `font_size` and `width` before the first
758    /// layout, so that [`DisplayMap::wrap_row_count`] is known on the first frame.
759    ///
760    /// Call it after setting the value and the wrapping indent. `width` is the
761    /// width of the input's text area: its width less its padding, and less
762    /// the line-number gutter for an editor with line numbers. It wraps as
763    /// layout does, a little short of that width and with the state's wrapping
764    /// indent. Once the input has been laid out this does nothing, and layout
765    /// keeps the wrap up to date. The font and font size must match the input's
766    /// actual text style.
767    pub fn prewrap(
768        &mut self,
769        font: wgpui::Font,
770        font_size: Pixels,
771        width: Pixels,
772        cx: &mut Context<Self>,
773    ) {
774        if self.last_layout.is_some() {
775            return;
776        }
777        let wrap_width = (width - RIGHT_MARGIN).max(px(1.));
778        self.display_map.set_font(font, font_size, cx);
779        self.display_map
780            .set_tab_size(self.mode.tab_size().tab_size, cx);
781        self.display_map
782            .on_layout_changed(self.soft_wrap.then_some(wrap_width), cx);
783        self.display_map
784            .set_wrapping_indent(self.wrapping_indent, cx);
785        self.display_map.ensure_text_prepared(&self.text, cx);
786    }
787
788    pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
789        self.diagnostic_popover.clone()
790    }
791
792    pub fn presentation(&self) -> InputPresentation {
793        InputPresentation {
794            focus_handle: self.focus_handle.clone(),
795            disabled: self.disabled,
796            readonly: self.readonly,
797            loading: self.loading,
798            masked: self.masked,
799            multi_line: self.is_multi_line(),
800            code_editor: self.is_code_editor(),
801            text_align: self.text_align,
802            placeholder: self.placeholder.clone(),
803            mask_placeholder: self.mask_pattern.placeholder(),
804        }
805    }
806
807    /// Whether this input spans more than one line.
808    ///
809    /// Answered by the mode marker, which is fixed when the state is built.
810    /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
811    #[inline]
812    /// Whether this input paints scrollbars.
813    ///
814    /// Only a multi-line input can scroll: a single-line input keeps its
815    /// caret in view by moving its own offset, and never has a viewport a
816    /// user could drag. Adding the editor scrollbar to every input put a
817    /// thumb inside every text field, which is a control the field does not
818    /// have.
819    pub(crate) fn shows_scrollbar(&self) -> bool {
820        self.is_multi_line()
821    }
822
823    pub fn is_multi_line(&self) -> bool {
824        M::MULTI_LINE
825    }
826
827    /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
828    #[inline]
829    pub fn is_single_line(&self) -> bool {
830        !M::MULTI_LINE
831    }
832
833    /// Whether this input is a source-code editor.
834    #[inline]
835    pub fn is_code_editor(&self) -> bool {
836        M::CODE_EDITOR
837    }
838
839    /// Whether the user is allowed to copy the selection out.
840    ///
841    /// A masked input keeps its value out of the clipboard.
842    pub fn is_copyable(&self) -> bool {
843        self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
844    }
845
846    pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
847        let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
848        InputContextMenuCapabilities::new()
849            .disabled(self.disabled)
850            .readonly(self.readonly)
851            .code_editor(self.is_code_editor())
852            .selection(!self.active_selection().is_empty())
853            .masked(self.masked)
854            .go_to_definition(go_to_definition)
855            .code_actions(code_actions)
856    }
857
858    pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
859        if !self.is_single_line() || self.text_align == text_align {
860            return;
861        }
862
863        self.text_align = text_align;
864        cx.notify();
865    }
866
867    /// Flip the password mask.
868    ///
869    /// Setting the mask is a single-line method, but flipping it stays here:
870    /// the reveal button is rendered from the generic path, and it can only be
871    /// switched on through [`crate::input::InputState`] anyway.
872    pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
873        self.masked = !self.masked;
874        cx.notify();
875    }
876
877    pub fn on_context_menu(
878        &mut self,
879        handler: Rc<
880            dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
881        >,
882    ) {
883        self.context_menu_handler = Some(handler);
884    }
885
886    /// Keeps the selection highlighted while this popup or one of its children has focus.
887    ///
888    /// This does not transfer keyboard focus or keep the caret visible. The
889    /// association holds only a weak focus handle. Pass `None` to clear it.
890    pub fn set_selection_focus(&mut self, focus: Option<FocusHandle>, cx: &mut Context<Self>) {
891        self.selection_focus = focus.as_ref().map(FocusHandle::downgrade);
892        cx.notify();
893    }
894
895    /// Whether the input or its associated selection popup has focus.
896    pub fn has_selection_focus(&self, window: &Window, cx: &App) -> bool {
897        self.focus_handle.is_focused(window)
898            || self
899                .selection_focus
900                .as_ref()
901                .and_then(WeakFocusHandle::upgrade)
902                .is_some_and(|focus| focus.is_focused(window) || focus.contains_focused(window, cx))
903    }
904
905    /// Build the engine. Each mode's own `new` sets its layout on top of this.
906    fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
907        let focus_handle = cx.focus_handle().tab_stop(true);
908        let blink_cursor = cx.new(|_| BlinkCursor::new());
909        let undo_manager = UndoManager::new();
910
911        let _subscriptions = vec![
912            // Key bindings can consume events before on_key_down. Observe input
913            // before action dispatch so every keystroke resets the blink delay.
914            cx.intercept_keystrokes({
915                let focus_handle = focus_handle.clone();
916                let blink_cursor = blink_cursor.downgrade();
917                move |_, window, cx| {
918                    if focus_handle.is_focused(window) {
919                        _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
920                    }
921                }
922            }),
923            // Observe the blink cursor to repaint the view when it changes.
924            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
925            // Blink the cursor when the window is active, pause when it's not.
926            cx.observe_window_activation(window, |input, window, cx| {
927                if window.is_window_active() {
928                    let focus_handle = input.focus_handle.clone();
929                    if focus_handle.is_focused(window) {
930                        input.blink_cursor.update(cx, |blink_cursor, cx| {
931                            blink_cursor.start(cx);
932                        });
933                    }
934                }
935            }),
936            cx.on_focus(&focus_handle, window, Self::on_focus),
937            cx.on_blur(&focus_handle, window, Self::on_blur),
938        ];
939
940        let text_style = window.text_style();
941
942        Self {
943            extras: M::Extras::default(),
944            focus_handle: focus_handle.clone(),
945            selection_focus: None,
946            text: "".into(),
947            display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
948            search_session: super::SearchSession::default(),
949            search_activation_revision: 0,
950            searchable: false,
951            replaceable: true,
952            soft_wrap: true,
953            wrapping_indent: WrappingIndent::default(),
954            scroll_beyond_last_line: None,
955            cursor_surrounding_lines: None,
956            blink_cursor,
957            undo_manager,
958            inline_tokens: None,
959            pending_token: None,
960            replaying_history: false,
961            validated_token_edit: false,
962            document_revision: 0,
963            token_presentation: Default::default(),
964            token_bounds: Default::default(),
965            hovered_token: None,
966            pending_token_hover_exits: Vec::new(),
967            token_layout_cache: None,
968            pressed_token: None,
969            selections: Selections::default(),
970            selected_word_range: None,
971            ime_marked_range: None,
972            input_bounds: Bounds::default(),
973            selecting: false,
974            touch_selection: Default::default(),
975            disabled: false,
976            readonly: false,
977            text_align: TextAlign::Left,
978            masked: false,
979            clean_on_escape: false,
980            submit_on_enter: false,
981            input_action: None,
982            autocorrect: None,
983            autocapitalize: None,
984            show_whitespaces: false,
985            loading: false,
986            pattern: None,
987            validate: None,
988            number_step: Some(NumberStep::Fixed(1.)),
989            number_min: None,
990            number_max: None,
991            mode: LayoutMode::default(),
992            last_layout: None,
993            prepaint_caret_geometry: None,
994            last_bounds: None,
995            revealed_viewport: None,
996            last_selected_range: None,
997            column_select_start: None,
998            last_cursor: None,
999            scroll_handle: ScrollHandle::new(),
1000            scroll_bounce: crate::ScrollBounce::enabled_by_default(),
1001            overscroll: Overscroll::default(),
1002            scroll_size: wgpui::size(px(0.), px(0.)),
1003            editor_scrollbar_snapshot: Cell::new(None),
1004            longest_line_width: Cell::new(None),
1005            editor_paddings: Edges::default(),
1006            deferred_scroll_offset: None,
1007            placeholder: SharedString::default(),
1008            mask_pattern: MaskPattern::default(),
1009            mask_pattern_set: false,
1010            editor_style: InputEditorStyle::default(),
1011            projected_editor_style: InputEditorStyle::default(),
1012            accessibility: None,
1013            scrollbar_renderer: None,
1014            diagnostic_popover: None,
1015            context_menu_handler: None,
1016            pending_context_menu: None,
1017            enable_context_menu: true,
1018            completion_inserting: false,
1019            overlay_action_handler: None,
1020            silent_replace_text: false,
1021            emit_events: true,
1022            _subscriptions,
1023            _pending_update: false,
1024            cursor_line_end_affinity: false,
1025            auto_scroll: AutoScroll::default(),
1026        }
1027    }
1028
1029    /// Sets whether the context menu that shows on right-click is enabled.
1030    ///
1031    /// The context menu is enabled by default. Disabling it turns off the
1032    /// right-click menu entirely, including a custom menu set on the element.
1033    /// A custom menu already replaces the built-in one, so keep this enabled
1034    /// to show only your own items.
1035    pub fn context_menu(mut self, enable: bool) -> Self {
1036        self.enable_context_menu = enable;
1037        self
1038    }
1039
1040    pub fn set_context_menu_enabled(&mut self, enabled: bool) {
1041        self.enable_context_menu = enabled;
1042    }
1043
1044    /// Set whether search UI allows replacement, default is true.
1045    #[doc(hidden)]
1046    pub fn replaceable(mut self, allow: bool) -> Self {
1047        self.replaceable = allow;
1048        self
1049    }
1050
1051    /// Set placeholder
1052    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1053        self.placeholder = placeholder.into();
1054        self
1055    }
1056
1057    /// Set the highlighter language for code editor mode.
1058    pub fn set_highlighter(
1059        &mut self,
1060        new_language: impl Into<SharedString>,
1061        cx: &mut Context<Self>,
1062    ) {
1063        match &mut self.mode {
1064            LayoutMode::CodeEditor {
1065                language,
1066                highlighter,
1067                ..
1068            } => {
1069                language.set_name(new_language.into());
1070                *highlighter.borrow_mut() = None;
1071            }
1072            _ => {}
1073        }
1074        self.refresh(cx);
1075    }
1076
1077    fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
1078        match &mut self.mode {
1079            LayoutMode::CodeEditor { highlighter, .. } => {
1080                *highlighter.borrow_mut() = None;
1081            }
1082            _ => {}
1083        }
1084        cx.notify();
1085    }
1086
1087    /// Install the parser/highlighter adapter used by code-editor mode.
1088    pub fn set_highlighter_factory(
1089        &mut self,
1090        factory: InputHighlighterFactory,
1091        cx: &mut Context<Self>,
1092    ) {
1093        self.mode.set_highlighter_factory(factory);
1094        self._pending_update = true;
1095        self.token_layout_cache = None;
1096        cx.notify();
1097    }
1098
1099    /// Install a default adapter without replacing an application-provided one.
1100    pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
1101        self.mode.ensure_highlighter_factory(factory);
1102    }
1103
1104    pub fn set_editor_style(&mut self, style: InputEditorStyle) {
1105        self.editor_style = style.clone();
1106        self.projected_editor_style = style;
1107    }
1108
1109    /// Project semantics onto the editor, never onto a second focus owner.
1110    pub fn set_accessibility(&mut self, accessibility: InputAccessibility) {
1111        self.accessibility = Some(accessibility);
1112    }
1113
1114    fn handle_accessibility_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1115        if !self.disabled {
1116            self.focus(window, cx);
1117        }
1118    }
1119
1120    fn handle_accessibility_set_value(
1121        &mut self,
1122        data: Option<&wgpui::accesskit::ActionData>,
1123        window: &mut Window,
1124        cx: &mut Context<Self>,
1125    ) {
1126        let Some(wgpui::accesskit::ActionData::Value(value)) = data else {
1127            return;
1128        };
1129        // The action may have been queued before editability changed.
1130        if self.is_editable() {
1131            self.replace_all(value.to_string(), window, cx);
1132        }
1133    }
1134
1135    /// Set presentation padding for multi-line text and its scrollbar layout.
1136    #[doc(hidden)]
1137    pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
1138        self.editor_paddings = paddings;
1139    }
1140
1141    /// Supply the element painted in place of the editor's scrollbar, or
1142    /// `None` to keep Base's. The renderer is called where the editor paints
1143    /// its scrollbar, with that frame's [`EditorScrollbarContext`]. Like
1144    /// [`Self::set_editor_style`], this does not notify, so it can be called
1145    /// while rendering.
1146    ///
1147    /// [`EditorScrollbarContext`]: crate::input::EditorScrollbarContext
1148    pub fn set_scrollbar_renderer(
1149        &mut self,
1150        renderer: Option<crate::input::EditorScrollbarRenderer>,
1151    ) {
1152        self.scrollbar_renderer = renderer;
1153    }
1154
1155    pub fn apply_highlighter_fold_candidates(
1156        &mut self,
1157        candidates: Vec<crate::input::FoldRange>,
1158        cx: &mut Context<Self>,
1159    ) {
1160        if self.mode.is_folding() {
1161            self.display_map.set_fold_candidates(candidates);
1162        }
1163        cx.notify();
1164    }
1165
1166    #[inline]
1167    pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
1168        self.mode.diagnostics()
1169    }
1170
1171    #[inline]
1172    pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
1173        self.mode.diagnostics_mut()
1174    }
1175
1176    /// Set placeholder
1177    pub fn set_placeholder(
1178        &mut self,
1179        placeholder: impl Into<SharedString>,
1180        _: &mut Window,
1181        cx: &mut Context<Self>,
1182    ) {
1183        self.placeholder = placeholder.into();
1184        cx.notify();
1185    }
1186
1187    /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
1188    ///
1189    /// Returns:
1190    ///
1191    /// - The index of the line (zero-based) containing the offset.
1192    /// - The index of the sub-line (zero-based) within the line containing the offset.
1193    /// - The position of the offset.
1194    pub(super) fn line_and_position_for_offset(
1195        &self,
1196        offset: usize,
1197    ) -> (usize, usize, Option<Point<Pixels>>) {
1198        let Some(last_layout) = &self.last_layout else {
1199            return (0, 0, None);
1200        };
1201        let line_height = last_layout.line_height;
1202
1203        let mut y_offset = last_layout.visible_top;
1204        for (vi, line) in last_layout.lines.iter().enumerate() {
1205            let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
1206            let local_offset = offset.saturating_sub(prev_lines_offset);
1207            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
1208                let sub_line_index = (pos.y / line_height) as usize;
1209                let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
1210                return (vi, sub_line_index, Some(adjusted_pos));
1211            }
1212
1213            y_offset += line.size(line_height).height;
1214        }
1215        (0, 0, None)
1216    }
1217
1218    /// Set the value of the input field: plain text, or [`InputContent`](crate::input::InputContent) to
1219    /// restore text together with its inline tokens. Editing history is
1220    /// cleared and no [`InputEvent::Change`] is emitted.
1221    ///
1222    /// For single-line inputs the caret is placed at the end of the text while
1223    /// the view is scrolled back to the start, so a long value shows its
1224    /// beginning instead of its tail (matching HTML `<input>`). Multi-line
1225    /// inputs reset the selection to `0..0`.
1226    pub fn set_value(
1227        &mut self,
1228        value: impl Into<super::InputContent>,
1229        window: &mut Window,
1230        cx: &mut Context<Self>,
1231    ) {
1232        let content = value.into();
1233        self.inline_tokens = None;
1234        self.undo_manager.set_ignoring(true);
1235        self.emit_events = false;
1236        self.replace_text(content.text().clone(), window, cx);
1237        self.install_tokens(content);
1238        self.undo_manager.set_ignoring(false);
1239        self.emit_events = true;
1240
1241        self.reset_selection();
1242        self.reset_lsp_state();
1243        self.reset_scroll_to_start();
1244
1245        self.undo_manager.clear();
1246        cx.notify();
1247    }
1248
1249    /// Replace the entire text content while preserving undo history.
1250    ///
1251    /// Unlike [`set_value`](Self::set_value), this method records the
1252    /// replacement in the undo stack, allowing the user to undo/redo
1253    /// the change. The selection is placed at the end of the new text
1254    /// for single-line inputs, or cleared (0..0) for multi-line inputs.
1255    ///
1256    /// Use this when programmatically replacing the full text but the
1257    /// user should still be able to undo the operation — e.g. formatting.
1258    pub fn replace_all(
1259        &mut self,
1260        text: impl Into<SharedString>,
1261        window: &mut Window,
1262        cx: &mut Context<Self>,
1263    ) {
1264        self.replace_text(text, window, cx);
1265        self.reset_selection();
1266        self.reset_lsp_state();
1267        self.reset_scroll_to_start();
1268
1269        cx.notify();
1270    }
1271
1272    /// Perform `f` with the user-facing edit restrictions lifted.
1273    ///
1274    /// The `disabled` and `readonly` modes only reject the changes made by the
1275    /// user, the programmatic APIs must always be able to update the text.
1276    pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1277        let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1278        (self.disabled, self.readonly) = (false, false);
1279        f(self);
1280        (self.disabled, self.readonly) = (was_disabled, was_readonly);
1281    }
1282
1283    /// Insert text at the current cursor position.
1284    ///
1285    /// And the cursor will be moved to the end of inserted text.
1286    pub fn insert(
1287        &mut self,
1288        text: impl Into<SharedString>,
1289        window: &mut Window,
1290        cx: &mut Context<Self>,
1291    ) {
1292        let text: SharedString = text.into();
1293        self.with_edits_allowed(|this| {
1294            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1295            let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1296            this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1297            let end = this.active_selection().end;
1298            this.set_cursor_to(end);
1299        });
1300    }
1301
1302    /// Replace text at the current cursor position.
1303    ///
1304    /// And the cursor will be moved to the end of replaced text.
1305    pub fn replace(
1306        &mut self,
1307        text: impl Into<SharedString>,
1308        window: &mut Window,
1309        cx: &mut Context<Self>,
1310    ) {
1311        let text: SharedString = text.into();
1312        self.with_edits_allowed(|this| {
1313            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1314            this.replace_text_in_range_silent(None, &text, window, cx);
1315            let end = this.active_selection().end;
1316            this.set_cursor_to(end);
1317        });
1318    }
1319
1320    fn replace_text(
1321        &mut self,
1322        text: impl Into<SharedString>,
1323        window: &mut Window,
1324        cx: &mut Context<Self>,
1325    ) {
1326        let text: SharedString = text.into();
1327        self.with_edits_allowed(|this| {
1328            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1329            let range = 0..this.text.chars().map(|c| c.len_utf16()).sum();
1330            this.replace_text_in_range_silent(Some(range), &text, window, cx);
1331            this.reset_highlighter(cx);
1332        });
1333    }
1334
1335    fn reset_selection(&mut self) {
1336        self.selections.remove_all_but_active();
1337
1338        // For single-line inputs the caret is placed at the end of the text
1339        // (matching HTML `<input>`); multi-line inputs reset the selection to
1340        // `0..0`.
1341        if self.is_single_line() {
1342            let end = self.text.len_bytes();
1343            self.set_cursor_to(end);
1344        } else {
1345            self.active_selection_mut().clear();
1346        }
1347    }
1348
1349    fn reset_lsp_state(&mut self) {
1350        if self.is_code_editor() {
1351            self._pending_update = true;
1352            M::reset_language_features(self);
1353        }
1354    }
1355
1356    fn reset_scroll_to_start(&mut self) {
1357        // Move scroll to the start. For single-line the caret is at the end, so
1358        // override the cursor-follow scroll for the next painted frame to keep
1359        // the start visible; the deferred offset is consumed during that paint.
1360        self.scroll_handle.set_offset(point(px(0.), px(0.)));
1361        if self.is_single_line() {
1362            self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1363        }
1364    }
1365
1366    /// Set with disabled mode.
1367    ///
1368    /// See also: [`Self::set_disabled`].
1369    #[allow(unused)]
1370    pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1371        self.disabled = disabled;
1372        self
1373    }
1374
1375    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1376        if self.disabled == disabled {
1377            return;
1378        }
1379
1380        self.disabled = disabled;
1381        if disabled {
1382            M::hide_context_menu(self, cx);
1383            M::clear_inline_completion(self, cx);
1384        }
1385        cx.notify();
1386    }
1387
1388    /// Set with read-only mode.
1389    ///
1390    /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1391    /// focus, cursor, selection and copy behavior, it only rejects any change
1392    /// of the text made by the user.
1393    ///
1394    /// See also: [`Self::set_readonly`].
1395    #[allow(unused)]
1396    pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1397        self.readonly = readonly;
1398        self
1399    }
1400
1401    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1402        if self.readonly == readonly {
1403            return;
1404        }
1405
1406        self.readonly = readonly;
1407        if readonly {
1408            M::hide_context_menu(self, cx);
1409            M::clear_inline_completion(self, cx);
1410            self.search_session.replace_mode = false;
1411        }
1412        cx.notify();
1413    }
1414
1415    /// Returns true if the user is allowed to change the text.
1416    ///
1417    /// This is false when the input is `disabled` or `readonly`, the programmatic
1418    /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1419    pub fn is_editable(&self) -> bool {
1420        !self.disabled && !self.readonly
1421    }
1422
1423    /// Set true to clear the input by pressing Escape key.
1424    ///
1425    /// Not on Android, where Escape is also the back button.
1426    pub fn clean_on_escape(mut self) -> Self {
1427        self.clean_on_escape = true;
1428        self
1429    }
1430
1431    pub fn set_clean_on_escape(&mut self, clean: bool) {
1432        self.clean_on_escape = clean;
1433    }
1434
1435    /// Set true to treat `Enter` as a submit action in multi-line mode,
1436    /// while `Shift+Enter` inserts a newline.
1437    ///
1438    /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1439    #[doc(hidden)]
1440    pub fn submit_on_enter(mut self, submit: bool) -> Self {
1441        self.submit_on_enter = submit;
1442        self
1443    }
1444
1445    pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1446        self.submit_on_enter = submit;
1447        cx.notify();
1448    }
1449
1450    /// Set the action a software keyboard shows on its enter key, like Search
1451    /// or Send. Pressing it still emits [`InputEvent::PressEnter`].
1452    ///
1453    /// Default is [`TextInputAction::Done`] for a single-line input (and a
1454    /// multi-line one that submits on enter), and [`TextInputAction::Enter`]
1455    /// (a line break) for a multi-line input.
1456    pub fn input_action(mut self, action: TextInputAction) -> Self {
1457        self.input_action = Some(action);
1458        self
1459    }
1460
1461    /// Set whether the platform may autocorrect the text and offer word
1462    /// suggestions.
1463    ///
1464    /// Default is `false`. Enable this explicitly for fields that accept prose;
1465    /// masking or revealing text does not change the setting.
1466    pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1467        self.autocorrect = Some(autocorrect);
1468        self
1469    }
1470
1471    /// Set how a software keyboard capitalizes the text.
1472    ///
1473    /// Default is [`Autocapitalize::None`]. Enable capitalization explicitly for
1474    /// fields where it is appropriate, independently of autocorrection.
1475    pub fn autocapitalize(mut self, autocapitalize: Autocapitalize) -> Self {
1476        self.autocapitalize = Some(autocapitalize);
1477        self
1478    }
1479
1480    /// The text assistance a platform IME (a software keyboard) should give
1481    /// this input, from [`Self::input_action`], [`Self::autocorrect`] and
1482    /// [`Self::autocapitalize`] or the defaults they describe.
1483    pub fn text_input_configuration(&self) -> TextInputConfiguration {
1484        // Masking is a presentation choice, not a reliable content type: a
1485        // revealed password must not acquire text assistance. Keep assistance
1486        // opt-in for structured fields such as passwords, email and URLs.
1487        let autocorrect = self.autocorrect.unwrap_or(false);
1488        let input_action =
1489            self.input_action
1490                .unwrap_or(if self.is_multi_line() && !self.submit_on_enter {
1491                    TextInputAction::Enter
1492                } else {
1493                    TextInputAction::Done
1494                });
1495        TextInputConfiguration {
1496            autocorrect,
1497            autocapitalize: self.autocapitalize.unwrap_or(Autocapitalize::None),
1498            suggestions: autocorrect,
1499            input_action,
1500        }
1501    }
1502
1503    /// Set whether to show whitespace characters.
1504    #[doc(hidden)]
1505    pub fn show_whitespaces(mut self, show: bool) -> Self {
1506        self.show_whitespaces = show;
1507        self
1508    }
1509
1510    /// Update whether to show whitespace characters.
1511    pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1512        self.show_whitespaces = show;
1513        cx.notify();
1514    }
1515
1516    /// Empty rows reserved below the last line of content ("scroll
1517    /// beyond last line"), code-editor mode only. Mirrors VSCode's
1518    /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1519    ///
1520    /// - `None` (default): half the viewport, floored at
1521    ///   three line-heights.
1522    /// - `Some(0)`: no trailing space; the cursor sits flush with the
1523    ///   last row at scroll-max.
1524    /// - `Some(n)`: exactly `n` rows.
1525    pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1526        self.scroll_beyond_last_line = rows;
1527        self
1528    }
1529
1530    /// Update [`Self::scroll_beyond_last_line`] after construction.
1531    pub fn set_scroll_beyond_last_line(
1532        &mut self,
1533        rows: Option<usize>,
1534        _: &mut Window,
1535        cx: &mut Context<Self>,
1536    ) {
1537        if self.scroll_beyond_last_line == rows {
1538            return;
1539        }
1540        self.scroll_beyond_last_line = rows;
1541        cx.notify();
1542    }
1543
1544    /// Minimum number of lines the cursor is kept clear of the viewport's
1545    /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1546    /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1547    /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1548    /// empty region; this controls the cursor's resting distance from the
1549    /// edge.
1550    ///
1551    /// - `None` (default): three lines, falling back to
1552    ///   one line on small viewports.
1553    /// - `Some(n)`: requests `n` lines, clamped to half the viewport.
1554    ///
1555    /// In a constrained viewport, edge clearance yields to the cursor's
1556    /// complete visual row so surrounding space cannot clip the text being edited.
1557    pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1558        self.cursor_surrounding_lines = lines;
1559        self
1560    }
1561
1562    /// Update [`Self::cursor_surrounding_lines`] after construction.
1563    pub fn set_cursor_surrounding_lines(
1564        &mut self,
1565        lines: Option<usize>,
1566        _: &mut Window,
1567        cx: &mut Context<Self>,
1568    ) {
1569        if self.cursor_surrounding_lines == lines {
1570            return;
1571        }
1572        self.cursor_surrounding_lines = lines;
1573        cx.notify();
1574    }
1575
1576    /// Set the default value of the input field.
1577    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1578        let text: SharedString = value.into();
1579        self.text = Rope::from(self.normalize_input(&text).as_ref());
1580        if let Some(diagnostics) = self.mode.diagnostics_mut() {
1581            diagnostics.reset(&self.text)
1582        }
1583        // Note: We can't call display_map.set_text here because it needs cx.
1584        // The text will be set during prepare_if_need in element.rs
1585        self._pending_update = true;
1586        self
1587    }
1588
1589    /// Return the value of the input field as an owned string.
1590    ///
1591    /// The string is materialized on each call. See [`Self::text`] for the
1592    /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1593    pub fn value(&self) -> SharedString {
1594        SharedString::new(self.text.to_string())
1595    }
1596
1597    /// Return the portion of the value within the input field that
1598    /// is selected by the user, as an owned string.
1599    ///
1600    /// The string is materialized on each call. See [`Self::selected_text`]
1601    /// for the same selection borrowed out of the [`Rope`] the state owns.
1602    pub fn selected_value(&self) -> SharedString {
1603        SharedString::new(self.selected_text().to_string())
1604    }
1605
1606    /// Return the value without mask.
1607    pub fn unmask_value(&self) -> SharedString {
1608        self.mask_pattern.unmask(&self.text.to_string()).into()
1609    }
1610
1611    /// Kept so existing render paths keep compiling.
1612    ///
1613    /// Configuration used to be collected by a facade and applied here; the
1614    /// state now configures itself, so this does nothing and can be deleted at
1615    /// the call site.
1616    #[doc(hidden)]
1617    pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1618
1619    /// Return the text [`Rope`] of the input field.
1620    ///
1621    /// Borrowed from the state, so reading even a large document copies
1622    /// nothing. See [`Self::value`] when an owned string is wanted.
1623    pub fn text(&self) -> &Rope {
1624        &self.text
1625    }
1626
1627    /// Return the (0-based) [`Position`] of the cursor.
1628    pub fn cursor_position(&self) -> Position {
1629        let offset = self.cursor();
1630        self.text.offset_to_position(offset)
1631    }
1632
1633    /// Set (0-based) [`Position`] of the cursor.
1634    ///
1635    /// This will move the cursor to the specified line and column, and update the selection range.
1636    pub fn set_cursor_position(
1637        &mut self,
1638        position: impl Into<Position>,
1639        window: &mut Window,
1640        cx: &mut Context<Self>,
1641    ) {
1642        let position: Position = position.into();
1643        let offset = self.text.position_to_offset(&position);
1644
1645        self.move_to(offset, None, cx);
1646        self.update_preferred_column();
1647        self.focus(window, cx);
1648    }
1649
1650    /// Focus the input field.
1651    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1652        self.focus_handle.focus(window, cx);
1653        self.blink_cursor.update(cx, |cursor, cx| {
1654            cursor.start(cx);
1655        });
1656    }
1657
1658    /// Refresh the input, so the next render re-runs syntax highlighting and
1659    /// the LSP providers, not just a redraw.
1660    ///
1661    /// Assigning the `lsp` providers (or other render-affecting state) at
1662    /// runtime does not take effect until the text next changes. Call this
1663    /// afterwards to force the refresh on the next render.
1664    ///
1665    /// ```ignore
1666    /// input.update(cx, |state, cx| {
1667    ///     state.extras.lsp.hover_provider = Some(provider);
1668    ///     state.refresh(cx);
1669    /// });
1670    /// ```
1671    pub fn refresh(&mut self, cx: &mut Context<Self>) {
1672        self._pending_update = true;
1673        cx.notify();
1674    }
1675
1676    pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1677        self.undo_manager.break_transaction_coalescing();
1678        self.select_all_cursors_to(|s, sel| s.previous_boundary(sel.cursor_offset()), cx);
1679    }
1680
1681    pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1682        self.select_all_cursors_to(|s, sel| s.next_boundary(sel.cursor_offset()), cx);
1683    }
1684
1685    pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1686        if self.is_single_line() {
1687            return;
1688        }
1689        self.select_all_cursors_to_with_affinity(
1690            |s, sel| {
1691                s.vertical_selection_target(
1692                    sel.cursor_offset(),
1693                    sel.column_anchor,
1694                    s.line_end_affinity_for(sel),
1695                    -1,
1696                )
1697            },
1698            true,
1699            cx,
1700        );
1701    }
1702
1703    pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1704        if self.is_single_line() {
1705            return;
1706        }
1707        self.select_all_cursors_to_with_affinity(
1708            |s, sel| {
1709                s.vertical_selection_target(
1710                    sel.cursor_offset(),
1711                    sel.column_anchor,
1712                    s.line_end_affinity_for(sel),
1713                    1,
1714                )
1715            },
1716            true,
1717            cx,
1718        );
1719    }
1720
1721    pub(super) fn on_action_select_all(
1722        &mut self,
1723        _: &SelectAll,
1724        window: &mut Window,
1725        cx: &mut Context<Self>,
1726    ) {
1727        self.select_all(window, cx);
1728    }
1729
1730    pub(super) fn select_to_start(
1731        &mut self,
1732        _: &SelectToStart,
1733        _: &mut Window,
1734        cx: &mut Context<Self>,
1735    ) {
1736        self.undo_manager.break_transaction_coalescing();
1737        self.select_all_cursors_to(|_, _| 0, cx);
1738    }
1739
1740    pub(super) fn select_to_end(
1741        &mut self,
1742        _: &SelectToEnd,
1743        _: &mut Window,
1744        cx: &mut Context<Self>,
1745    ) {
1746        self.undo_manager.break_transaction_coalescing();
1747        let end = self.text.len_bytes();
1748        self.select_all_cursors_to(move |_, _| end, cx);
1749    }
1750
1751    pub(super) fn select_to_start_of_line(
1752        &mut self,
1753        _: &SelectToStartOfLine,
1754        _: &mut Window,
1755        cx: &mut Context<Self>,
1756    ) {
1757        self.undo_manager.break_transaction_coalescing();
1758        self.select_all_cursors_to(
1759            |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1760            cx,
1761        );
1762    }
1763
1764    pub(super) fn select_to_end_of_line(
1765        &mut self,
1766        _: &SelectToEndOfLine,
1767        _: &mut Window,
1768        cx: &mut Context<Self>,
1769    ) {
1770        self.undo_manager.break_transaction_coalescing();
1771        self.select_all_cursors_to_with_affinity(
1772            |s, sel| {
1773                (
1774                    s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1775                    true,
1776                )
1777            },
1778            false,
1779            cx,
1780        );
1781    }
1782
1783    pub(super) fn select_to_previous_word(
1784        &mut self,
1785        _: &SelectToPreviousWordStart,
1786        _: &mut Window,
1787        cx: &mut Context<Self>,
1788    ) {
1789        self.undo_manager.break_transaction_coalescing();
1790        self.select_all_cursors_to(
1791            |s, sel| s.previous_start_of_word_at(sel.cursor_offset()),
1792            cx,
1793        );
1794    }
1795
1796    pub(super) fn select_to_next_word(
1797        &mut self,
1798        _: &SelectToNextWordEnd,
1799        _: &mut Window,
1800        cx: &mut Context<Self>,
1801    ) {
1802        self.undo_manager.break_transaction_coalescing();
1803        self.select_all_cursors_to(|s, sel| s.next_end_of_word_at(sel.cursor_offset()), cx);
1804    }
1805
1806    /// Return the start offset of the previous word.
1807    /// Return the previous start offset of the word before `offset`.
1808    pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1809        if self.masked {
1810            // The mask replaces every character, so the displayed text has no
1811            // word boundaries to move or delete by. Collapse the word to the
1812            // whole text.
1813            return 0;
1814        }
1815
1816        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1817        // FIXME: Avoid to_string
1818        let left_part = self.text.byte_slice(0..offset).to_string();
1819
1820        let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1821            .rfind(|(_, s)| !s.trim_start().is_empty())
1822            .map(|(i, _)| i)
1823            .unwrap_or(0);
1824        self.token_boundary(target, Bias::Left)
1825    }
1826
1827    /// Return the next end offset of the word after `offset`.
1828    pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1829        if self.masked {
1830            // See `previous_start_of_word_at`.
1831            return self.text.len_bytes();
1832        }
1833
1834        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1835        let right_part = self
1836            .text
1837            .byte_slice(offset..self.text.len_bytes())
1838            .to_string();
1839
1840        let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1841            .find(|(_, s)| !s.trim_start().is_empty())
1842            .map(|(i, s)| offset + i + s.len())
1843            .unwrap_or(self.text.len_bytes());
1844        self.token_boundary(target, Bias::Right)
1845    }
1846
1847    /// Get start of line byte offset for the given `offset`.
1848    ///
1849    /// When soft wrap is active, first press goes to visual line start,
1850    /// second press (already at visual start) goes to logical line start.
1851    pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1852        if self.is_single_line() {
1853            return 0;
1854        }
1855
1856        let row = self.text.offset_to_point(offset).row;
1857        let logical_start = self.text.line_start_offset(row);
1858
1859        if self.soft_wrap && self.is_code_editor() {
1860            let wrap_point = self
1861                .display_map
1862                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1863            if let Some(line) = self.display_map.line(row)
1864                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1865            {
1866                let visual_start = logical_start + range.start;
1867                if offset != visual_start {
1868                    return visual_start;
1869                }
1870            }
1871        }
1872
1873        logical_start
1874    }
1875
1876    /// Get end of line byte offset for the given `offset`.
1877    ///
1878    /// When soft wrap is active, first press goes to visual line end,
1879    /// second press (already at visual end) goes to logical line end.
1880    pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1881        if self.is_single_line() {
1882            return self.text.len_bytes();
1883        }
1884
1885        let row = self.text.offset_to_point(offset).row;
1886        let logical_start = self.text.line_start_offset(row);
1887        let logical_end = self.text.line_end_offset(row);
1888
1889        if self.soft_wrap && self.is_code_editor() {
1890            // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
1891            // the next row, and a second End press would keep walking down instead of falling
1892            // through to the logical line end.
1893            let wrap_point = self
1894                .display_map
1895                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1896            if let Some(line) = self.display_map.line(row)
1897                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1898            {
1899                let visual_end = logical_start + range.end;
1900                if offset != visual_end {
1901                    return visual_end;
1902                }
1903            }
1904        }
1905
1906        logical_end
1907    }
1908
1909    /// Get indent string of next line.
1910    ///
1911    /// To get current and next line indent, to return more depth one.
1912    pub(super) fn indent_of_next_line(&mut self) -> String {
1913        self.indent_of_next_line_at(self.cursor())
1914    }
1915
1916    /// Get indent string of the next line, relative to the given `offset`.
1917    pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
1918        if self.is_single_line() {
1919            return "".into();
1920        }
1921
1922        let mut current_indent = String::new();
1923        let mut next_indent = String::new();
1924        let line_end_affinity = self.line_end_affinity_at(offset);
1925        let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
1926        let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
1927        for c in self.text.byte_slice(current_line_start_pos..).chars() {
1928            if !c.is_whitespace() {
1929                break;
1930            }
1931            if c == '\n' || c == '\r' {
1932                break;
1933            }
1934            current_indent.push(c);
1935        }
1936
1937        for c in self.text.byte_slice(next_line_start_pos..).chars() {
1938            if !c.is_whitespace() {
1939                break;
1940            }
1941            if c == '\n' || c == '\r' {
1942                break;
1943            }
1944            next_indent.push(c);
1945        }
1946
1947        if next_indent.len() > current_indent.len() {
1948            return next_indent;
1949        }
1950
1951        // Smart indent: one extra level after lines ending with a trigger.
1952        // Skipped inside strings and comments: the trigger is literal text.
1953        if let Some(rules) = self.mode.language_config() {
1954            if self.mode.is_smart_indent()
1955                && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
1956            {
1957                let line_before: String = self
1958                    .text
1959                    .byte_slice(current_line_start_pos..offset)
1960                    .chars()
1961                    .collect();
1962                if rules.opens_indent(line_before.trim_end()) {
1963                    let tab = self.mode.tab_size();
1964                    if tab.hard_tabs {
1965                        current_indent.push('\t');
1966                    } else {
1967                        for _ in 0..tab.tab_size {
1968                            current_indent.push(' ');
1969                        }
1970                    }
1971                } else {
1972                    let line_after = self
1973                        .text
1974                        .byte_slice(offset..next_line_start_pos)
1975                        .to_string();
1976                    if rules.closes_indent(&line_after) {
1977                        let tab = self.mode.tab_size();
1978                        if current_indent.ends_with('\t') {
1979                            current_indent.pop();
1980                        } else {
1981                            for _ in 0..tab.tab_size {
1982                                if !current_indent.ends_with(' ') {
1983                                    break;
1984                                }
1985                                current_indent.pop();
1986                            }
1987                        }
1988                    }
1989                }
1990            }
1991        }
1992
1993        current_indent
1994    }
1995
1996    /// Delete every selection as one batch. Collapsed cursors are first
1997    /// expanded to a deletion range by `collapsed_target` and non-empty
1998    /// selections delete their own range.
1999    ///
2000    /// `collapsed_intent` is the intent to record when every cursor is
2001    /// collapsed, which is what makes a run of single-character deletes undo
2002    /// as one gesture. Deleting a real selection is always atomic.
2003    fn delete_selections(
2004        &mut self,
2005        silent: bool,
2006        collapsed_intent: EditIntent,
2007        mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
2008        window: &mut Window,
2009        cx: &mut Context<Self>,
2010    ) {
2011        if !self.is_editable() {
2012            return;
2013        }
2014        let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
2015        let intent = if cursors.iter().all(|sel| sel.is_empty()) {
2016            collapsed_intent
2017        } else {
2018            EditIntent::Atomic
2019        };
2020        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
2021        for sel in &cursors {
2022            let range = if sel.is_empty() {
2023                collapsed_target(self, sel.cursor_offset())
2024            } else {
2025                sel.start..sel.end
2026            };
2027            let (start, end) = (range.start.min(range.end), range.start.max(range.end));
2028            let mut selection = *sel;
2029            selection.start = start;
2030            selection.end = end;
2031            new_selections.push(selection);
2032        }
2033        // Capture the user's selections before expanding or merging deletion
2034        // ranges. The edit ranges cannot reconstruct their original carets.
2035        self.undo_manager.begin_transaction_with(intent);
2036        self.undo_manager
2037            .record_selections(cursors.clone(), cursors.clone());
2038        self.selections.replace_all(new_selections);
2039        self.undo_manager.set_pending_intent(intent);
2040
2041        let was_silent = self.silent_replace_text;
2042        self.silent_replace_text = silent;
2043        self.replace_text_in_range(None, "", window, cx);
2044        self.silent_replace_text = was_silent;
2045        self.undo_manager
2046            .record_selections(cursors, self.selections.iter().copied().collect());
2047        self.undo_manager.commit_transaction();
2048        self.pause_blink_cursor(cx);
2049    }
2050
2051    /// Decide pairing against the pre-edit text, before an opening quote can
2052    /// change its own syntax context. Ordinary characters never query syntax.
2053    fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
2054        if self.silent_replace_text
2055            || self.ime_marked_range.is_some()
2056            || !self.selections.is_single()
2057            || !self.active_selection().is_empty()
2058            || !range.is_empty()
2059            || range.start != self.cursor()
2060            || text.chars().count() != 1
2061            || !self.mode.is_auto_close()
2062        {
2063            return None;
2064        }
2065        let rules = self.mode.language_config()?;
2066        if self
2067            .text
2068            .chars_at(self.text.byte_to_char(range.start))
2069            .next()
2070            .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
2071        {
2072            return None;
2073        }
2074        for (open, close, not_in) in rules.closing_pairs() {
2075            let Some(prefix) = open.strip_suffix(text) else {
2076                continue;
2077            };
2078            if !self.text_before_matches(range.start, prefix) {
2079                continue;
2080            }
2081            let start = range.start - prefix.len();
2082            if open == close
2083                && (self.is_escaped_at(start)
2084                    || self
2085                        .text
2086                        .chars_at(self.text.byte_to_char(start))
2087                        .reversed()
2088                        .next()
2089                        .is_some_and(|c| c.is_alphanumeric() || c == '_'))
2090            {
2091                continue;
2092            }
2093            if not_in.contains(&M::editing_syntax_context(self, start)) {
2094                continue;
2095            }
2096            return Some((open.len(), close.to_owned().into()));
2097        }
2098        None
2099    }
2100
2101    fn text_before_matches(&self, offset: usize, text: &str) -> bool {
2102        offset >= text.len()
2103            && self.text.is_char_boundary(offset - text.len())
2104            && self.text.byte_slice(offset - text.len()..offset) == text
2105    }
2106
2107    fn text_after_matches(&self, offset: usize, text: &str) -> bool {
2108        offset + text.len() <= self.text.len_bytes()
2109            && self.text.is_char_boundary(offset + text.len())
2110            && self.text.byte_slice(offset..offset + text.len()) == text
2111    }
2112
2113    fn is_escaped_at(&self, offset: usize) -> bool {
2114        self.text
2115            .chars_at(self.text.byte_to_char(offset))
2116            .reversed()
2117            .take_while(|c| *c == '\\')
2118            .count()
2119            % 2
2120            == 1
2121    }
2122
2123    /// Cursor target when a typed closer should skip over an existing one.
2124    ///
2125    /// Returns `Some(offset)` when `new_text` is a single closer from the
2126    /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
2127    /// not escaped. The caller then moves the cursor without editing text or
2128    /// history. `None` means insert normally.
2129    fn skip_over_target(&self, new_text: &str) -> Option<usize> {
2130        if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
2131            return None;
2132        }
2133        let rules = self.mode.language_config()?;
2134        let cursor = self.cursor();
2135        for (open, close, not_in) in rules.closing_pairs() {
2136            for (index, _) in close.char_indices() {
2137                if !close[index..].starts_with(new_text)
2138                    || !self.text_before_matches(cursor, &close[..index])
2139                    || !self.text_after_matches(cursor, &close[index..])
2140                {
2141                    continue;
2142                }
2143                let context = M::editing_syntax_context(self, cursor);
2144                let generated =
2145                    self.mode
2146                        .auto_closed_pairs()
2147                        .contains_closer(cursor, index, close.len());
2148                if !generated
2149                    && not_in.contains(&context)
2150                    && !(context == crate::input::SyntaxContext::String && open == close)
2151                {
2152                    continue;
2153                }
2154                if self.is_escaped_at(cursor - index) {
2155                    continue;
2156                }
2157                return Some(cursor + new_text.len());
2158            }
2159        }
2160        None
2161    }
2162
2163    pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
2164        // Nothing to delete at the start of the text. Propagate so an ancestor
2165        // (e.g. a command palette navigating back a level) can act on it.
2166        // This is harmless when nothing upstream is bound to backspace. With multiple
2167        // cursors the others can still delete, so only the lone-cursor case
2168        // propagates.
2169        if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
2170            cx.propagate();
2171            return;
2172        }
2173
2174        // Pair deletion follows automatic closing rules, independently of
2175        // structural brackets used by Enter.
2176        if self.mode.is_auto_close()
2177            && self.selections.is_single()
2178            && self.active_selection().is_empty()
2179        {
2180            let off = self.cursor();
2181            let deletion = self.mode.language_config().and_then(|rules| {
2182                rules.closing_pairs().find_map(|(open, close, not_in)| {
2183                    if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
2184                    {
2185                        return None;
2186                    }
2187                    let start = off - open.len();
2188                    let generated = self
2189                        .mode
2190                        .auto_closed_pairs()
2191                        .contains(start..off, off..off + close.len());
2192                    if self.is_escaped_at(start)
2193                        || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
2194                    {
2195                        return None;
2196                    }
2197                    Some(start..off + close.len())
2198                })
2199            });
2200            if let Some(range) = deletion {
2201                let utf16 = self.range_to_utf16(&range);
2202                self.replace_text_in_range_silent(Some(utf16), "", window, cx);
2203                return;
2204            }
2205        }
2206
2207        self.delete_selections(
2208            false,
2209            EditIntent::Backspace,
2210            |s, offset| s.previous_boundary(offset)..offset,
2211            window,
2212            cx,
2213        );
2214    }
2215
2216    pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2217        self.delete_selections(
2218            false,
2219            EditIntent::DeleteForward,
2220            |s, offset| offset..s.next_boundary(offset),
2221            window,
2222            cx,
2223        );
2224    }
2225
2226    pub(super) fn delete_to_beginning_of_line(
2227        &mut self,
2228        _: &DeleteToBeginningOfLine,
2229        window: &mut Window,
2230        cx: &mut Context<Self>,
2231    ) {
2232        self.delete_selections(
2233            true,
2234            EditIntent::Atomic,
2235            |s, offset| {
2236                let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
2237                if start == offset {
2238                    start = start.saturating_sub(1);
2239                }
2240                start..offset
2241            },
2242            window,
2243            cx,
2244        );
2245    }
2246
2247    pub(super) fn delete_to_end_of_line(
2248        &mut self,
2249        _: &DeleteToEndOfLine,
2250        window: &mut Window,
2251        cx: &mut Context<Self>,
2252    ) {
2253        self.delete_selections(
2254            true,
2255            EditIntent::Atomic,
2256            |s, offset| {
2257                let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
2258                if end == offset {
2259                    end = (end + 1).clamp(0, s.text.len_bytes());
2260                }
2261                offset..end
2262            },
2263            window,
2264            cx,
2265        );
2266    }
2267
2268    pub(super) fn delete_previous_word(
2269        &mut self,
2270        _: &DeleteToPreviousWordStart,
2271        window: &mut Window,
2272        cx: &mut Context<Self>,
2273    ) {
2274        self.delete_selections(
2275            true,
2276            EditIntent::Atomic,
2277            |s, offset| s.previous_start_of_word_at(offset)..offset,
2278            window,
2279            cx,
2280        );
2281    }
2282
2283    pub(super) fn delete_next_word(
2284        &mut self,
2285        _: &DeleteToNextWordEnd,
2286        window: &mut Window,
2287        cx: &mut Context<Self>,
2288    ) {
2289        self.delete_selections(
2290            true,
2291            EditIntent::Atomic,
2292            |s, offset| offset..s.next_end_of_word_at(offset),
2293            window,
2294            cx,
2295        );
2296    }
2297
2298    pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
2299        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2300            return;
2301        }
2302
2303        // Clear inline completion on enter (user chose not to accept it)
2304        if M::has_inline_completion(self) {
2305            M::clear_inline_completion(self, cx);
2306        }
2307
2308        // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
2309        // (without Shift) is treated as submit: propagate the action and emit
2310        // PressEnter without inserting a newline. `Shift+Enter` still inserts
2311        // a newline.
2312        let insert_newline = self.is_multi_line() && (!self.submit_on_enter || action.shift);
2313
2314        if insert_newline {
2315            if !self.selections.is_single() {
2316                // Insert a newline (with per-line indent) at every cursor.
2317                self.selections.merge_overlapping();
2318                let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2319                let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
2320                for sel in &selections {
2321                    let indent = if self.is_code_editor() {
2322                        self.indent_of_next_line_at(sel.cursor_offset())
2323                    } else {
2324                        String::new()
2325                    };
2326                    edits.push((sel.start..sel.end, format!("\n{}", indent)));
2327                }
2328                edits.sort_by_key(|(range, _)| range.start);
2329                self.replace_text_in_ranges(&edits, window, cx);
2330                self.pause_blink_cursor(cx);
2331            } else {
2332                // Bracket split: Enter between `{|}` produces `{\n  \n}`
2333                // with the cursor on the middle line. Controlled by smart_indent,
2334                // independently of automatic closing.
2335                // Skipped inside strings and comments: splitting there would
2336                // restructure literal text.
2337                let mut split = false;
2338                if self.is_code_editor() && self.active_selection().is_empty() {
2339                    if let Some(rules) = self.mode.language_config() {
2340                        if self.mode.is_smart_indent()
2341                            && M::editing_syntax_context(self, self.cursor())
2342                                == crate::input::SyntaxContext::Code
2343                        {
2344                            let off = self.cursor();
2345                            let is_pair = rules.brackets.iter().any(|p| {
2346                                !p.open.is_empty()
2347                                    && !p.close.is_empty()
2348                                    && p.open != p.close
2349                                    && self.text_before_matches(off, p.open.as_ref())
2350                                    && self.text_after_matches(off, p.close.as_ref())
2351                            });
2352                            if is_pair {
2353                                // Base indent: leading whitespace only.
2354                                let line_end_affinity = self.line_end_affinity_at(off);
2355                                let line_start = self.start_of_line_at(off, line_end_affinity);
2356                                let mut indent = String::new();
2357                                for c in self.text.byte_slice(line_start..).chars() {
2358                                    if !c.is_whitespace() || c == '\n' || c == '\r' {
2359                                        break;
2360                                    }
2361                                    indent.push(c);
2362                                }
2363                                // Extra level only with smart indent enabled.
2364                                let mut inner = indent.clone();
2365                                if self.mode.is_smart_indent() {
2366                                    let tab = self.mode.tab_size();
2367                                    if tab.hard_tabs {
2368                                        inner.push('\t');
2369                                    } else {
2370                                        for _ in 0..tab.tab_size {
2371                                            inner.push(' ');
2372                                        }
2373                                    }
2374                                }
2375                                let new_line_text = format!("\n{inner}\n{indent}");
2376                                self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2377                                self.set_cursor_to(off + 1 + inner.len());
2378                                self.update_preferred_column();
2379                                let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2380                                self.undo_manager
2381                                    .record_selections(cursors.clone(), cursors);
2382                                self.pause_blink_cursor(cx);
2383                                split = true;
2384                            }
2385                        }
2386                    }
2387                }
2388                if !split {
2389                    // Get current line indent
2390                    let indent = if self.is_code_editor() {
2391                        self.indent_of_next_line()
2392                    } else {
2393                        "".to_string()
2394                    };
2395
2396                    // Add newline and indent
2397                    let new_line_text = format!("\n{}", indent);
2398                    self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2399                    self.pause_blink_cursor(cx);
2400                }
2401            }
2402        } else {
2403            // Single line input or submit-on-enter: just emit the event
2404            // (e.g.: in a dialog to confirm, or a chat textarea to send).
2405            self.undo_manager.break_transaction_coalescing();
2406            cx.propagate();
2407        }
2408
2409        cx.emit(InputEvent::PressEnter {
2410            secondary: action.secondary,
2411            shift: action.shift,
2412        });
2413    }
2414
2415    pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2416        self.replace_text("", window, cx);
2417        self.set_selection(0, 0);
2418        self.scroll_to(0, None, cx);
2419    }
2420
2421    pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2422        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2423            return;
2424        }
2425
2426        // Escape also dismisses a request whose popup has not arrived yet.
2427        M::hide_context_menu(self, cx);
2428
2429        // Collapse extra cursors back to the active one first.
2430        if !self.selections.is_single() {
2431            self.undo_manager.break_transaction_coalescing();
2432            self.selections.remove_all_but_active();
2433            cx.notify();
2434            return;
2435        }
2436
2437        // Clear inline completion on escape
2438        if M::has_inline_completion(self) {
2439            M::clear_inline_completion(self, cx);
2440            return; // Consume the escape, don't propagate
2441        }
2442        M::clear_inline_completion(self, cx);
2443
2444        // The handles and the edit menu are the topmost surface to dismiss.
2445        if self.touch_selection().is_some() {
2446            self.dismiss_touch_selection(cx);
2447            return;
2448        }
2449
2450        if self.ime_marked_range.is_some() {
2451            self.unmark_text(window, cx);
2452        }
2453
2454        // Android delivers its back button as escape, and back leaves a field's
2455        // text alone: it closes what is open or navigates.
2456        if self.clean_on_escape && !cfg!(target_os = "android") {
2457            return self.clean(window, cx);
2458        }
2459
2460        cx.propagate();
2461    }
2462
2463    /// Show the right-click context menu as a native OS menu.
2464    pub(crate) fn handle_right_click_menu(
2465        &mut self,
2466        position: Point<Pixels>,
2467        offset: usize,
2468        window: &mut Window,
2469        cx: &mut Context<Self>,
2470    ) {
2471        if self.disabled {
2472            return;
2473        }
2474        if crate::GlobalState::is_in_deferred_context(cx) {
2475            return;
2476        }
2477
2478        if !self.active_selection().contains(offset) {
2479            self.move_to(offset, None, cx);
2480        }
2481
2482        if self.is_code_editor() {
2483            M::on_hover_definition(self, offset, window, cx);
2484        }
2485
2486        if let Some(handler) = self.context_menu_handler.clone() {
2487            let capabilities = self.context_menu_capabilities();
2488            let input = cx.weak_entity();
2489            // The handler runs with the input released, so a custom builder can
2490            // read it (cursor, selection, text) to build its items.
2491            window.defer(cx, move |window, cx| {
2492                if input.upgrade().is_none() {
2493                    return;
2494                }
2495                let previous_focus = window.focused(cx);
2496                handler(NativeMenu::new(), capabilities, position, window, cx);
2497                // A drawn menu takes focus synchronously; native menus leave it
2498                // on the input. Capture it here rather than in the handler.
2499                input
2500                    .update(cx, |this, cx| {
2501                        if window.focused(cx) == previous_focus
2502                            && !this.focus_handle.is_focused(window)
2503                            && this.has_selection_focus(window, cx)
2504                        {
2505                            // A custom handler can reuse an already-focused popup.
2506                            return;
2507                        }
2508                        let menu_focus = window.focused(cx).filter(|focus| {
2509                            Some(focus) != previous_focus.as_ref() && *focus != this.focus_handle
2510                        });
2511                        this.set_selection_focus(menu_focus, cx);
2512                    })
2513                    .ok();
2514            });
2515        }
2516    }
2517
2518    pub(super) fn add_cursor_above(
2519        &mut self,
2520        _: &AddCursorAbove,
2521        _: &mut Window,
2522        cx: &mut Context<Self>,
2523    ) {
2524        self.add_cursor_vertical(-1, cx);
2525    }
2526
2527    pub(super) fn add_cursor_below(
2528        &mut self,
2529        _: &AddCursorBelow,
2530        _: &mut Window,
2531        cx: &mut Context<Self>,
2532    ) {
2533        self.add_cursor_vertical(1, cx);
2534    }
2535
2536    /// Add a new cursor one display line above (`move_lines < 0`) or below each
2537    /// existing cursor, preserving the column. Cursors that would not move (at
2538    /// the first/last display row) or that would duplicate an existing cursor
2539    /// are skipped.
2540    fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2541        if !self.is_multi_line() {
2542            return;
2543        }
2544
2545        self.pause_blink_cursor(cx);
2546        // Changing the cursor set ends the editing gesture that came before it.
2547        self.undo_manager.break_transaction_coalescing();
2548
2549        let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2550            .selections
2551            .iter()
2552            .map(|sel| {
2553                (
2554                    sel.cursor_offset(),
2555                    sel.column_anchor,
2556                    self.line_end_affinity_for(sel),
2557                )
2558            })
2559            .collect();
2560        let mut offsets: std::collections::HashSet<usize> =
2561            sources.iter().map(|(offset, _, _)| *offset).collect();
2562
2563        let mut newest: Option<usize> = None;
2564        for (offset, anchor, line_end_affinity) in sources {
2565            let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2566            let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2567            if target == offset || offsets.contains(&target) {
2568                continue;
2569            }
2570            offsets.insert(target);
2571            let id = self.selections.generate_id();
2572            let mut cursor = CursorSelection::new(id, target, target);
2573            cursor.column_anchor = anchor;
2574            self.selections.add(cursor);
2575            newest = Some(target);
2576        }
2577
2578        if let Some(newest) = newest {
2579            self.scroll_to(newest, None, cx);
2580        }
2581        cx.notify();
2582    }
2583
2584    /// Add an additional collapsed cursor at `offset`.
2585    ///
2586    /// Rejected when `offset` lands inside an existing selection or exactly on
2587    /// an existing cursor.
2588    pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2589        if !self.is_multi_line() {
2590            return;
2591        }
2592
2593        for sel in self.selections.iter() {
2594            if sel.contains(offset) {
2595                return;
2596            }
2597            if sel.is_collapsed() && sel.cursor_offset() == offset {
2598                return;
2599            }
2600        }
2601
2602        self.undo_manager.break_transaction_coalescing();
2603        let id = self.selections.generate_id();
2604        let mut selection = CursorSelection::new(id, offset, offset);
2605        selection.column_anchor = self.preferred_column_for(offset);
2606        self.selections.add(selection);
2607        cx.notify();
2608    }
2609
2610    /// Build a columnar (block) selection spanning the rows between the two
2611    /// points, one selection per display row at the same column span.
2612    ///
2613    /// The span keeps the columns the pointer sat past the end of a short row, so a row
2614    /// that runs out of text does not narrow the block for the rows that do reach that
2615    /// far. Each row is then clipped to its own end, selecting as much of the span as it
2616    /// actually has.
2617    pub(super) fn build_columnar_selection(
2618        &mut self,
2619        start: ColumnarPoint,
2620        end: ColumnarPoint,
2621        cx: &mut Context<Self>,
2622    ) {
2623        if !self.is_multi_line() {
2624            return;
2625        }
2626
2627        self.undo_manager.break_transaction_coalescing();
2628
2629        let (start_row, start_col) = self.columnar_row_column(start);
2630        let (end_row, end_col) = self.columnar_row_column(end);
2631        let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2632        let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2633
2634        let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2635        for row in start_row..=end_row {
2636            let sel_start = self
2637                .display_map
2638                .display_row_column_to_offset(row, start_col);
2639            let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2640            let id = self.selections.generate_id();
2641            let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2642            let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2643            new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2644        }
2645
2646        self.selections.replace_all(new_selections);
2647        cx.notify();
2648    }
2649
2650    /// Resolve a columnar point to the display row it is on and the column it reaches,
2651    /// counting the columns beyond the row's end so a short row keeps the full span.
2652    fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2653        let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2654        let row = self
2655            .display_map
2656            .wrap_row_to_display_row(display_point.row)
2657            .unwrap_or_else(|| {
2658                self.display_map
2659                    .nearest_visible_display_row(display_point.row)
2660            });
2661
2662        (row, display_point.column + point.columns_past_line_end)
2663    }
2664
2665    pub(super) fn on_mouse_down(
2666        &mut self,
2667        event: &MouseDownEvent,
2668        window: &mut Window,
2669        cx: &mut Context<Self>,
2670    ) {
2671        // A token that consumed the press (a double click selecting it) must
2672        // not also place the caret.
2673        if window.default_prevented() {
2674            return;
2675        }
2676        // A tap asks for the virtual keyboard. Focus alone does not when it
2677        // moves from another input, or stays here, after the user hid it.
2678        if event.button == MouseButton::Left
2679            && crate::GlobalState::is_touch_press(cx)
2680            && !self.disabled
2681            && !self.readonly
2682        {
2683            window.request_virtual_keyboard();
2684        }
2685        self.undo_manager.break_transaction_coalescing();
2686        // Treat every press like a cursor move: take focus now rather than
2687        // after GPUI's focus observer runs, show the caret at once and restart
2688        // the idle delay, whatever phase the blink was in.
2689        if !self.disabled {
2690            self.focus(window, cx);
2691            self.pause_blink_cursor(cx);
2692        }
2693        // Input has its own text selection; suppress the window-level text
2694        // selection (Root) so it does not start a drag from here.
2695        crate::global_state::GlobalState::suppress_text_selection(cx);
2696
2697        // Clear inline completion on any mouse interaction
2698        M::clear_inline_completion(self, cx);
2699        // A tap on the touch selection asks for its menu back. Any other press
2700        // places the caret or starts a new drag, and the handles and the menu
2701        // no longer belong to what is selected.
2702        if event.button == MouseButton::Left
2703            && event.click_count == 1
2704            && self.reopen_edit_menu_at(event.position, cx)
2705        {
2706            return;
2707        }
2708        self.dismiss_touch_selection(cx);
2709
2710        // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2711        // Clear the marked range.
2712        if let Some(ime_marked_range) = &self.ime_marked_range {
2713            if ime_marked_range.len() == 0 {
2714                self.ime_marked_range = None;
2715            }
2716        }
2717
2718        self.selecting = true;
2719        let (offset, line_end_affinity, columns_past_line_end) =
2720            self.resolve_mouse_position(event.position);
2721
2722        if M::on_click(self, event, offset, window, cx) {
2723            return;
2724        }
2725
2726        // Triple click to select line
2727        if event.button == MouseButton::Left && event.click_count >= 3 {
2728            self.select_line(offset, window, cx);
2729            return;
2730        }
2731
2732        // Double click to select word
2733        if event.button == MouseButton::Left && event.click_count == 2 {
2734            self.select_word(offset, window, cx);
2735            // A double tap is touch's other way to select a word, and it
2736            // gets the handles and the menu like a long press does.
2737            if crate::GlobalState::is_touch_press(cx) {
2738                self.keep_touch_selection(cx);
2739            }
2740            return;
2741        }
2742
2743        // Show Mouse context menu
2744        if event.button == MouseButton::Right {
2745            if self.enable_context_menu {
2746                if !self.active_selection().contains(offset) {
2747                    self.move_to(offset, None, cx);
2748                }
2749                self.pending_context_menu = Some((event.position, offset));
2750            }
2751            return;
2752        }
2753
2754        // Multi-cursor placement, multi-line only.
2755        if self.is_multi_line() && event.button == MouseButton::Left {
2756            if event.modifiers.alt
2757                && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2758            {
2759                // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2760                // Mark selecting so the drag handler extends the block.
2761                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2762                self.selecting = true;
2763                self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2764                return;
2765            } else if event.modifiers.alt {
2766                self.add_cursor_at(offset, cx);
2767                // Keep click-to-add behavior, but use this press as the block
2768                // anchor if the user continues dragging with the left button.
2769                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2770                return;
2771            }
2772        }
2773
2774        if event.modifiers.shift {
2775            self.select_to_with_affinity(offset, line_end_affinity, cx);
2776        } else {
2777            self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2778        }
2779    }
2780
2781    pub(super) fn on_mouse_up(
2782        &mut self,
2783        event: &MouseUpEvent,
2784        window: &mut Window,
2785        cx: &mut Context<Self>,
2786    ) {
2787        if event.button == MouseButton::Right {
2788            if let Some((position, offset)) = self.pending_context_menu.take() {
2789                self.handle_right_click_menu(position, offset, window, cx);
2790            }
2791        }
2792        if self.active_selection().is_empty() {
2793            self.active_selection_mut().reversed = false;
2794        }
2795        self.selecting = false;
2796        self.selected_word_range = None;
2797        self.column_select_start = None;
2798        self.auto_scroll.stop();
2799    }
2800
2801    pub(super) fn on_mouse_move(
2802        &mut self,
2803        event: &MouseMoveEvent,
2804        window: &mut Window,
2805        cx: &mut Context<Self>,
2806    ) {
2807        // Check if mouse is within bounds
2808        let within_bounds = self
2809            .last_bounds
2810            .as_ref()
2811            .map(|bounds| bounds.contains(&event.position))
2812            .unwrap_or(false);
2813
2814        if !within_bounds {
2815            // Clear hover when mouse leaves the input
2816            M::clear_hover_state(self, cx);
2817            return;
2818        }
2819
2820        // Show diagnostic popover on mouse move
2821        let (offset, _) = self.index_for_mouse_position(event.position);
2822        M::on_mouse_move(self, offset, event, window, cx);
2823
2824        if self.is_code_editor() {
2825            // Keep the current popover while the pointer stays on the same
2826            // diagnostic, so moving over a squiggle neither repaints nor
2827            // rebuilds the popover.
2828            match self
2829                .mode
2830                .diagnostics()
2831                .and_then(|set| set.for_offset(offset))
2832            {
2833                Some(diagnostic) => {
2834                    if self.diagnostic_popover.as_deref() != Some(diagnostic) {
2835                        self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
2836                        cx.notify();
2837                    }
2838                }
2839                None => {
2840                    if self.diagnostic_popover.take().is_some() {
2841                        cx.notify();
2842                    }
2843                }
2844            }
2845        }
2846    }
2847
2848    pub(super) fn on_scroll_wheel(
2849        &mut self,
2850        event: &ScrollEvent,
2851        window: &mut Window,
2852        cx: &mut Context<Self>,
2853    ) {
2854        let line_height = self
2855            .last_layout
2856            .as_ref()
2857            .map(|layout| layout.line_height)
2858            .unwrap_or(window.line_height());
2859        let delta = event.delta.pixel_delta(line_height);
2860
2861        let old_offset = self.scroll_handle.offset();
2862        let precise = matches!(event.delta, wgpui::ScrollDelta::Pixels(_));
2863        if !precise || !self.scroll_bounce || cx.reduce_motion() || !self.overflows_vertically() {
2864            let displaced = self.overscroll.offset() != 0.;
2865            self.overscroll.reset();
2866            if displaced {
2867                cx.notify();
2868            }
2869        }
2870        let bounces = self.scroll_bounce
2871            && precise
2872            && !cx.reduce_motion()
2873            && delta.y.abs() >= delta.x.abs()
2874            && self.overflows_vertically();
2875        if bounces {
2876            let mut overscroll = std::mem::take(&mut self.overscroll);
2877            let stretched = overscroll.packet(
2878                delta.y.as_f32(),
2879                event.touch_phase,
2880                self.input_bounds.size.height.as_f32(),
2881                cx.background_executor().now(),
2882                |dy| {
2883                    let before = self.scroll_handle.offset();
2884                    self.update_scroll_offset(
2885                        Some(point(before.x + delta.x, before.y + px(dy))),
2886                        cx,
2887                    );
2888                    (self.scroll_handle.offset().y - before.y).as_f32()
2889                },
2890            );
2891            self.overscroll = overscroll;
2892            if stretched {
2893                cx.notify();
2894            }
2895        } else {
2896            // Axis drift must not drop the end of a vertical drag.
2897            if matches!(
2898                event.touch_phase,
2899                wgpui::TouchPhase::Ended | wgpui::TouchPhase::Cancelled
2900            ) && self.overscroll.offset() != 0.
2901            {
2902                self.overscroll.packet(
2903                    0.,
2904                    event.touch_phase,
2905                    self.input_bounds.size.height.as_f32(),
2906                    cx.background_executor().now(),
2907                    |_| 0.,
2908                );
2909                cx.notify();
2910            }
2911            self.update_scroll_offset(Some(old_offset + delta), cx);
2912        }
2913
2914        // Text that has room to scroll keeps a scroll over it even where the
2915        // text ends, so reaching the end does not scroll the region around the
2916        // input; text that fits leaves the scroll to that region.
2917        if self.scroll_handle.offset() != old_offset || self.overflows_along(delta) {
2918            cx.stop_propagation();
2919        }
2920
2921        if self.diagnostic_popover.take().is_some() {
2922            cx.notify();
2923        }
2924        // The handles follow the text; the menu would sit over whatever
2925        // scrolls underneath it, so it steps aside until the finger lifts.
2926        self.edit_menu_on_scroll(event.touch_phase, cx);
2927    }
2928
2929    /// Whether the text takes a wheel event moving by `delta` from the
2930    /// scroll areas around it: it has room to scroll along the axis the
2931    /// event mostly moves on. Unlike [`Self::overflows_along`], an event that
2932    /// moves on neither axis, such as a gesture's start or end, goes to text
2933    /// that can scroll vertically.
2934    pub(super) fn takes_scroll(&self, delta: Point<Pixels>) -> bool {
2935        if delta.y.abs() >= delta.x.abs() {
2936            self.overflows_vertically()
2937        } else {
2938            self.scroll_size.width > self.input_bounds.size.width
2939        }
2940    }
2941
2942    /// Whether the text has room to scroll along the axis `delta` mostly
2943    /// moves on. A trackpad swipe drifts a little off its axis, so the drift
2944    /// alone does not claim the scroll.
2945    fn overflows_along(&self, delta: Point<Pixels>) -> bool {
2946        if delta.y.abs() >= delta.x.abs() {
2947            delta.y != px(0.) && self.overflows_vertically()
2948        } else {
2949            self.scroll_size.width > self.input_bounds.size.width
2950        }
2951    }
2952
2953    /// Whether multi-line text is taller than the input.
2954    fn overflows_vertically(&self) -> bool {
2955        self.is_multi_line() && self.scroll_size.height > self.input_bounds.size.height
2956    }
2957
2958    pub(super) fn update_scroll_offset(
2959        &mut self,
2960        offset: Option<Point<Pixels>>,
2961        cx: &mut Context<Self>,
2962    ) {
2963        let mut offset = offset.unwrap_or(self.scroll_handle.offset());
2964        let safe_y_range =
2965            (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.);
2966
2967        offset.y = if self.is_single_line() {
2968            px(0.)
2969        } else {
2970            offset.y.clamp(safe_y_range.start, safe_y_range.end)
2971        };
2972        offset.x = clamp_horizontal_scroll_offset(
2973            offset.x,
2974            self.scroll_size.width,
2975            self.input_bounds.size.width,
2976            self.text_align,
2977        );
2978        if self.scroll_handle.offset() != offset {
2979            self.scroll_handle.set_offset(offset);
2980            cx.notify();
2981        }
2982    }
2983
2984    /// Scroll to make the given offset visible.
2985    ///
2986    /// If `direction` is Some, will keep edges at the same side.
2987    pub(crate) fn scroll_to(
2988        &mut self,
2989        offset: usize,
2990        direction: Option<MoveDirection>,
2991        cx: &mut Context<Self>,
2992    ) {
2993        let padding = if direction.is_some() {
2994            ScrollPadding::SurroundingLines
2995        } else {
2996            ScrollPadding::Minimal
2997        };
2998        self.scroll_to_with_padding(offset, direction, padding, cx);
2999    }
3000
3001    /// Reveal an offset with independently chosen direction restriction and padding.
3002    /// Search uses surrounding lines without restricting movement to match order.
3003    pub(crate) fn scroll_to_with_padding(
3004        &mut self,
3005        offset: usize,
3006        direction: Option<MoveDirection>,
3007        padding: ScrollPadding,
3008        cx: &mut Context<Self>,
3009    ) {
3010        let Some(last_layout) = self.last_layout.as_ref() else {
3011            return;
3012        };
3013        let Some(bounds) = self.last_bounds.as_ref() else {
3014            return;
3015        };
3016
3017        let mut scroll_offset = self.scroll_handle.offset();
3018        let was_offset = scroll_offset;
3019        let line_height = last_layout.line_height;
3020
3021        let point = self.text.offset_to_point(offset);
3022
3023        let row = point.row;
3024
3025        // Resolve the wrapped row even when the target is outside the last layout.
3026        let display_row = self
3027            .display_map
3028            .offset_to_display_row(offset, self.line_end_affinity_at(offset));
3029        let row_offset_y = line_height * display_row;
3030
3031        // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
3032        // in layout_cursors, so shifting the text here would cause a first-click visual jump.
3033        let safety_margin = match last_layout.text_align {
3034            TextAlign::Left => RIGHT_MARGIN,
3035            TextAlign::Right => px(0.),
3036            TextAlign::Center => CURSOR_WIDTH,
3037        };
3038        if let Some(vi) = last_layout
3039            .visible_buffer_lines
3040            .iter()
3041            .position(|&line| line == row)
3042        {
3043            let line = &last_layout.lines[vi];
3044            let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
3045            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
3046                let bounds_width = bounds.size.width - last_layout.line_number_width;
3047                let col_offset_x = pos.x;
3048                if col_offset_x - safety_margin < -scroll_offset.x {
3049                    // If the position is out of the visible area, scroll to make it visible
3050                    scroll_offset.x = -col_offset_x + safety_margin;
3051                } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
3052                    scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
3053                }
3054            }
3055        }
3056
3057        // Scroll the row into view. Use the same edge clearance helper as
3058        // `TextElement::layout_cursors` so both scroll-into-view paths agree
3059        // (a mismatch flickered on `Down` at end-of-buffer with a small
3060        // `cursor_surrounding_lines` override).
3061        let edge_height =
3062            if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
3063                super::element::cursor_surrounding_padding(
3064                    self.mode.is_auto_grow(),
3065                    self.cursor_surrounding_lines,
3066                    super::element::viewport_visible_lines(bounds.size.height, line_height),
3067                    line_height,
3068                )
3069            } else {
3070                px(0.)
3071            };
3072        scroll_offset.y = super::element::reveal_row(
3073            scroll_offset.y,
3074            row_offset_y,
3075            line_height,
3076            bounds.size.height,
3077            edge_height,
3078        );
3079
3080        // Avoid necessary scroll, when it was already in the correct position.
3081        if direction == Some(MoveDirection::Up) {
3082            scroll_offset.y = scroll_offset.y.max(was_offset.y);
3083        } else if direction == Some(MoveDirection::Down) {
3084            scroll_offset.y = scroll_offset.y.min(was_offset.y);
3085        }
3086
3087        // Clamp the deferred target into the same safe range that
3088        // `update_scroll_offset` enforces on persist, so paint never shows an
3089        // over-scrolled frame before the post-paint clamp pulls it back.
3090        let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.));
3091        scroll_offset.x = scroll_offset.x.min(px(0.));
3092        scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.));
3093        self.deferred_scroll_offset = Some(scroll_offset);
3094        cx.notify();
3095    }
3096
3097    pub(super) fn show_character_palette(
3098        &mut self,
3099        _: &ShowCharacterPalette,
3100        window: &mut Window,
3101        _: &mut Context<Self>,
3102    ) {
3103        window.show_character_palette();
3104    }
3105
3106    /// The text of every non-empty selection, in document order.
3107    fn selected_texts(&self) -> Vec<String> {
3108        let mut selections: Vec<CursorSelection> = self
3109            .selections
3110            .iter()
3111            .copied()
3112            .filter(|sel| !sel.is_empty())
3113            .collect();
3114        selections.sort_by_key(|sel| sel.start);
3115        selections
3116            .iter()
3117            .map(|sel| self.text.byte_slice(*sel).to_string())
3118            .collect()
3119    }
3120
3121    pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
3122        if !self.is_copyable() {
3123            return;
3124        }
3125
3126        let texts = self.selected_texts();
3127
3128        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3129    }
3130
3131    pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
3132        if !self.is_copyable() {
3133            return;
3134        }
3135
3136        let texts = self.selected_texts();
3137
3138        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3139
3140        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3141        self.replace_text_in_range_silent(None, "", window, cx);
3142    }
3143
3144    pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
3145        if !self.is_editable() {
3146            return;
3147        }
3148        if let Some(clipboard) = cx.read_from_clipboard() {
3149            self.insert_clipboard(clipboard, window, cx);
3150            return;
3151        }
3152        // The synchronous read is empty on platforms whose clipboard is
3153        // asynchronous and permission-gated (the web), so fall back to the
3154        // real read. It has to start here, still inside the user activation
3155        // that dispatched `Paste`, or the browser refuses the read.
3156        let read = cx.read_from_clipboard_async();
3157        let target = self.paste_target();
3158        cx.spawn_in(window, async move |this, cx| match read.await {
3159            Ok(Some(clipboard)) => {
3160                this.update_in(cx, |this, window, cx| {
3161                    // The read can sit behind a permission prompt for as
3162                    // long as the user likes. If they edited, moved the
3163                    // caret or left the input meanwhile, the paste would
3164                    // land where they no longer mean it to; drop it, as the
3165                    // browser's own paste event only reaches the focused
3166                    // input too.
3167                    if this.is_editable()
3168                        && this.focus_handle.is_focused(window)
3169                        && this.paste_target() == target
3170                    {
3171                        this.insert_clipboard(clipboard, window, cx);
3172                    }
3173                })
3174                .ok();
3175            }
3176            Ok(None) => {}
3177            Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
3178        })
3179        .detach();
3180    }
3181
3182    /// Where a paste would go right now: the document as edited so far and
3183    /// the selections it would replace. Two equal targets mean an edit made
3184    /// for one still applies to the other.
3185    fn paste_target(&self) -> PasteTarget {
3186        PasteTarget {
3187            document_revision: self.document_revision,
3188            selections: self.selections.iter().copied().collect(),
3189        }
3190    }
3191
3192    /// Inserts the clipboard text the way `Paste` does: one atomic edit,
3193    /// newlines dropped on a single-line input, one line per selection when
3194    /// the counts match on a multi-line one. A clipboard without text (an
3195    /// image, say) is left alone rather than replacing the selection with
3196    /// nothing.
3197    fn insert_clipboard(
3198        &mut self,
3199        clipboard: ClipboardItem,
3200        window: &mut Window,
3201        cx: &mut Context<Self>,
3202    ) {
3203        let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
3204            return;
3205        };
3206        // A paste is one atomic edit, never part of a typing run.
3207        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3208
3209        if !self.is_multi_line() {
3210            new_text = new_text.replace('\n', "");
3211            self.replace_text_in_range_silent(None, &new_text, window, cx);
3212            self.scroll_to(self.cursor(), None, cx);
3213            return;
3214        }
3215
3216        // Distribute one clipboard line per selection when the counts match.
3217        // Otherwise insert the whole clipboard text at each cursor.
3218        if !self.selections.is_single() {
3219            self.selections.merge_overlapping();
3220        }
3221        let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
3222        let count = self.selections.len();
3223        if count > 1 && lines.len() == count {
3224            let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3225            selections.sort_by_key(|sel| sel.start);
3226            let edits: Vec<(Range<usize>, String)> = selections
3227                .iter()
3228                .zip(lines)
3229                .map(|(sel, line)| (sel.start..sel.end, line))
3230                .collect();
3231            self.replace_text_in_ranges(&edits, window, cx);
3232        } else {
3233            self.replace_text_in_range_silent(None, &new_text, window, cx);
3234        }
3235        self.scroll_to(self.cursor(), None, cx);
3236    }
3237
3238    /// The intent of a batch the caller did not label: inserting text at
3239    /// collapsed cursors is typing, anything else stands on its own.
3240    fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
3241        if !new_text.is_empty()
3242            && !new_text.contains(['\n', '\r'])
3243            && edits.iter().all(|(range, _)| range.is_empty())
3244        {
3245            EditIntent::Typing
3246        } else {
3247            EditIntent::Atomic
3248        }
3249    }
3250
3251    /// Where a cursor stood before an edit made with this intent.
3252    ///
3253    /// Backspace and forward delete expand a collapsed cursor over the text
3254    /// they are about to remove, so the recorded cursor has to collapse back to
3255    /// the side it came from for undo to restore it where the user left it.
3256    fn collapse_for_intent(
3257        intent: EditIntent,
3258        mut selection: CursorSelection,
3259        range: &Range<usize>,
3260    ) -> CursorSelection {
3261        match intent {
3262            EditIntent::Backspace => selection.place_at(range.end, None),
3263            EditIntent::DeleteForward => selection.place_at(range.start, None),
3264            EditIntent::Typing | EditIntent::Atomic => {}
3265        }
3266        selection
3267    }
3268
3269    /// Whether an edit rewrites the character before a collapsed cursor, as the
3270    /// macOS Korean IME does on each keystroke instead of marking text.
3271    fn rewrites_typed_char(
3272        &self,
3273        selection: CursorSelection,
3274        range: &Range<usize>,
3275        old_text: &str,
3276        new_text: &str,
3277    ) -> bool {
3278        !self.silent_replace_text
3279            && selection.is_collapsed()
3280            && selection.cursor_offset() == range.end
3281            && old_text.chars().count() == 1
3282            && !old_text.contains(['\n', '\r'])
3283            && !new_text.contains(['\n', '\r'])
3284    }
3285
3286    fn push_history(
3287        &mut self,
3288        text: &Rope,
3289        range: &Range<usize>,
3290        new_text: &str,
3291        requested_intent: Option<EditIntent>,
3292        selection_before: CursorSelection,
3293        selection_after: Option<CursorSelection>,
3294    ) -> bool {
3295        self.document_revision = self.document_revision.wrapping_add(1);
3296        let token_delta = self.edit_tokens(range, new_text.len());
3297        if self.undo_manager.is_ignoring() {
3298            return false;
3299        }
3300
3301        let range =
3302            text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
3303        let old_text = text.byte_slice(range.clone()).to_string();
3304        let new_range = range.start..range.start + new_text.len();
3305
3306        let intent = requested_intent.unwrap_or_else(|| {
3307            if range.is_empty()
3308                && old_text.is_empty()
3309                && !new_text.is_empty()
3310                && !new_text.contains(['\n', '\r'])
3311                || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
3312            {
3313                EditIntent::Typing
3314            } else {
3315                EditIntent::Atomic
3316            }
3317        });
3318
3319        let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
3320        let selection_after =
3321            selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
3322
3323        let open_transaction = self.undo_manager.has_open_transaction();
3324        let mut change = Change::new(range, &old_text, new_range, new_text);
3325        change.token_delta = token_delta;
3326        let recorded = self.undo_manager.record_transaction(change, intent);
3327        // A batch records its own cursor sets. This covers a change that is a
3328        // transaction on its own.
3329        if recorded && !open_transaction {
3330            self.undo_manager
3331                .record_selections(vec![selection_before], vec![selection_after]);
3332        }
3333        recorded
3334    }
3335
3336    pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
3337        self.replay_history(true, window, cx);
3338    }
3339
3340    pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
3341        self.replay_history(false, window, cx);
3342    }
3343
3344    fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
3345        if !self.is_editable() {
3346            return;
3347        }
3348        let replay = if undo {
3349            self.undo_manager.undo()
3350        } else {
3351            self.undo_manager.redo()
3352        };
3353        let Some(replay) = replay else {
3354            return;
3355        };
3356        let token_aware = self.inline_tokens.is_some()
3357            || replay
3358                .changes
3359                .iter()
3360                .any(|change| change.token_delta.is_some());
3361        let emit_events = self.emit_events;
3362        if token_aware {
3363            self.emit_events = false;
3364        }
3365        self.replaying_history = token_aware;
3366        self.undo_manager.set_ignoring(true);
3367        for change in &replay.changes {
3368            let (range, text) = if undo {
3369                (change.new_range.into(), &change.old_text)
3370            } else {
3371                (change.old_range.into(), &change.new_text)
3372            };
3373            let range_utf16 = self.range_to_utf16(&range);
3374            self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
3375            self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
3376        }
3377        self.restore_selections(replay.selections);
3378        self.mode
3379            .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
3380        if token_aware {
3381            // Token replay bypasses IME normalization; a stale marked range
3382            // would otherwise describe text that no longer exists.
3383            self.ime_marked_range = None;
3384        }
3385        self.undo_manager.set_ignoring(false);
3386        self.replaying_history = false;
3387        self.emit_events = emit_events;
3388        if token_aware && emit_events {
3389            cx.emit(InputEvent::Change);
3390        }
3391        cx.notify();
3392    }
3393
3394    /// Restore a set of selections captured in a transaction, clamping offsets
3395    /// to the current text length. `None` leaves the current selections as the
3396    /// replay left them.
3397    fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
3398        let Some(selections) = selections else {
3399            return;
3400        };
3401
3402        let len = self.text.len_bytes();
3403        let restored: Vec<CursorSelection> = selections
3404            .into_iter()
3405            .map(|mut sel| {
3406                sel.start = sel.start.min(len);
3407                sel.end = sel.end.min(len);
3408                sel
3409            })
3410            .collect();
3411        self.selections.replace_all(restored);
3412        self.selections.merge_overlapping();
3413    }
3414
3415    /// Get byte offset of the cursor.
3416    ///
3417    /// The offset is the UTF-8 offset.
3418    pub fn cursor(&self) -> usize {
3419        if let Some(ime_marked_range) = &self.ime_marked_range {
3420            return ime_marked_range.end;
3421        }
3422
3423        self.selections.active().cursor_offset()
3424    }
3425
3426    /// Returns the active selection.
3427    pub(super) fn active_selection(&self) -> &CursorSelection {
3428        self.selections.active()
3429    }
3430
3431    /// Returns a mutable reference to the active selection.
3432    pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
3433        self.selections.active_mut()
3434    }
3435
3436    /// Sets the active selection to the given range, keeping its `reversed`
3437    /// and `column_anchor` state untouched.
3438    pub(super) fn set_selection(&mut self, start: usize, end: usize) {
3439        let range = self.normalize_token_range(start..end);
3440        let (start, end) = (range.start, range.end);
3441        let active = self.active_selection_mut();
3442        active.start = start;
3443        active.end = end;
3444    }
3445
3446    /// Collapses the active selection to a cursor at the given offset,
3447    /// clearing `reversed`.
3448    pub(super) fn set_cursor_to(&mut self, offset: usize) {
3449        let offset = self.token_boundary(offset, Bias::Right);
3450        let active = self.active_selection_mut();
3451        active.start = offset;
3452        active.end = offset;
3453        active.reversed = false;
3454    }
3455
3456    /// Visible row range in the last laid-out viewport, `None` before first layout.
3457    pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3458        self.last_layout.as_ref().map(|l| l.visible_range.clone())
3459    }
3460
3461    /// Current scroll offset of the editor viewport.
3462    pub fn scroll_offset(&self) -> wgpui::Point<wgpui::Pixels> {
3463        self.scroll_handle.offset()
3464    }
3465
3466    /// Set scroll offset of the editor viewport.
3467    ///
3468    /// The offset will be clamped to the valid range, and applied after the next layout.
3469    pub fn set_scroll_offset(
3470        &mut self,
3471        offset: wgpui::Point<wgpui::Pixels>,
3472        cx: &mut Context<Self>,
3473    ) {
3474        self.deferred_scroll_offset = Some(offset);
3475        cx.notify();
3476    }
3477
3478    /// Laid-out line height; `None` before first layout.
3479    pub fn line_height(&self) -> Option<wgpui::Pixels> {
3480        self.last_layout.as_ref().map(|l| l.line_height)
3481    }
3482
3483    /// Returns the active selection as a byte range into the text.
3484    ///
3485    /// With multiple cursors, this reads only the active selection.
3486    ///
3487    /// The range is empty (`start == end`) when no text is selected; in
3488    /// that case the offset equals `cursor()`. Byte offsets are measured
3489    /// in the underlying rope's byte units.
3490    pub fn selected_range(&self) -> std::ops::Range<usize> {
3491        (*self.selections.active()).into()
3492    }
3493
3494    pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3495        self.undo_manager.break_transaction_coalescing();
3496        self.selections.remove_all_but_active();
3497        self.set_selection(0, self.text.len_bytes());
3498        cx.notify();
3499    }
3500
3501    /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
3502    ///
3503    /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
3504    /// clipped to the preceding character boundary.
3505    pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3506        let range = self.normalize_token_range(range);
3507        let end_bias = if range.start == range.end {
3508            Bias::Left
3509        } else {
3510            Bias::Right
3511        };
3512        let start = self.text.clip_offset(range.start, Bias::Left);
3513        let end = self.text.clip_offset(range.end, end_bias);
3514
3515        self.move_to(start, None, cx);
3516        self.active_selection_mut().reversed = false;
3517        self.selected_word_range = None;
3518        self.select_to(end, cx);
3519    }
3520
3521    /// Add `range` as an additional selection, keeping the existing ones —
3522    /// the programmatic equivalent of Alt-clicking another cursor into the
3523    /// text.
3524    ///
3525    /// The range is clipped to the text and expanded to character
3526    /// boundaries, like [`Self::set_selected_range`]. A range already
3527    /// covered by a selection adds nothing. Overlapping selections are merged.
3528    /// On a single-line input there is no second cursor to add, so the call
3529    /// replaces the selection instead.
3530    /// The view scrolls to the new selection.
3531    pub fn add_selection(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3532        if !self.is_multi_line() {
3533            self.set_selected_range(range, cx);
3534            return;
3535        }
3536
3537        let range = self.normalize_token_range(range);
3538        let end_bias = if range.start == range.end {
3539            Bias::Left
3540        } else {
3541            Bias::Right
3542        };
3543        let start = self.cursor_boundary(range.start, Bias::Left);
3544        // Match set_selected_range: expand UTF-8 boundaries first, then place
3545        // the selection endpoint without splitting a CRLF newline.
3546        let end = self.cursor_boundary(self.text.clip_offset(range.end, end_bias), Bias::Left);
3547
3548        for sel in self.selections.iter() {
3549            if sel.start <= start && end <= sel.end {
3550                return;
3551            }
3552        }
3553
3554        self.undo_manager.break_transaction_coalescing();
3555        self.selected_word_range = None;
3556        self.pause_blink_cursor(cx);
3557        M::hide_context_menu(self, cx);
3558        M::clear_inline_completion(self, cx);
3559        let id = self.selections.generate_id();
3560        let mut selection = CursorSelection::new(id, start, end);
3561        selection.column_anchor = self.preferred_column_for(end);
3562        self.selections.add(selection);
3563        self.selections.merge_overlapping();
3564        self.scroll_to(end, None, cx);
3565        cx.notify();
3566    }
3567
3568    /// Resolve a mouse position to a byte offset in the text.
3569    ///
3570    /// Also reports the caret's line-end affinity for that offset: `true` when the position
3571    /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
3572    /// end of that row rather than at the start of the next one. Callers that place or extend a
3573    /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
3574    /// caret one row below the pointer.
3575    pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3576        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3577        (offset, line_end_affinity)
3578    }
3579
3580    /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
3581    /// how many columns the pointer sits past the end of that row.
3582    ///
3583    /// Only a columnar selection needs the third value; everywhere else a position past
3584    /// the end of a row means the end of that row, and
3585    /// [`Self::index_for_mouse_position`] is the call to make.
3586    pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3587        // If the text is empty, always return 0
3588        if self.text.len_bytes() == 0 {
3589            return (0, false, 0);
3590        }
3591
3592        let (Some(bounds), Some(last_layout)) =
3593            (self.last_bounds.as_ref(), self.last_layout.as_ref())
3594        else {
3595            return (0, false, 0);
3596        };
3597
3598        let line_height = last_layout.line_height;
3599        let line_number_width = last_layout.line_number_width;
3600
3601        // TIP: About the IBeam cursor
3602        //
3603        // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3604
3605        // The position is relative to the bounds of the text input
3606        //
3607        // bounds.origin:
3608        //
3609        // - included the input padding.
3610        // - included the scroll offset.
3611        let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3612
3613        let mut y_offset = last_layout.visible_top;
3614        // Position relative to the last line walked, kept for a pointer that ends up
3615        // below every line.
3616        let mut last_line_pos = None;
3617
3618        // Traverse visible buffer lines (compact, no hidden entries)
3619        for (vi, (line_layout, _buffer_line)) in last_layout
3620            .lines
3621            .iter()
3622            .zip(last_layout.visible_buffer_lines.iter())
3623            .enumerate()
3624        {
3625            let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3626
3627            // Calculate line origin for this display row
3628            let line_origin = point(px(0.), y_offset);
3629            let pos = inner_position - line_origin;
3630
3631            // Return offset by use closest_index_for_x if is single line mode.
3632            if self.is_single_line() {
3633                let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3634                // A single line never wraps, so there is no boundary to disambiguate.
3635                return (
3636                    self.resolve_index(line_start_offset + local_index),
3637                    false,
3638                    0,
3639                );
3640            }
3641
3642            // Check if mouse is in this line's bounds
3643            if let Some((local_index, line_end_affinity)) =
3644                line_layout.closest_index_for_position(pos, last_layout)
3645            {
3646                return (
3647                    self.resolve_index(line_start_offset + local_index),
3648                    line_end_affinity,
3649                    line_layout.columns_past_line_end(pos, last_layout),
3650                );
3651            } else if pos.y < px(0.) {
3652                // Mouse is above this line, return start of this line
3653                return (self.resolve_index(line_start_offset), false, 0);
3654            }
3655
3656            y_offset += line_layout.size(line_height).height;
3657            last_line_pos = Some(pos);
3658        }
3659
3660        // Clamp to the last laid-out row. Returning the end of the whole document
3661        // would select unseen text before drag autoscroll has reached it.
3662        let last_position = last_layout
3663            .lines
3664            .last()
3665            .zip(last_line_pos)
3666            .zip(last_layout.visible_line_byte_offsets.last())
3667            .map(|((line_layout, pos), line_start)| {
3668                let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3669                let pos = point(pos.x, last_row_top);
3670                (
3671                    self.resolve_index(line_start + line_layout.len()),
3672                    false,
3673                    line_layout.columns_past_line_end(pos, last_layout),
3674                )
3675            });
3676
3677        last_position.unwrap_or((self.text.len_bytes(), false, 0))
3678    }
3679
3680    /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3681    /// is masked.
3682    fn resolve_index(&self, index: usize) -> usize {
3683        if self.masked {
3684            self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3685        } else {
3686            index.min(self.text.len_bytes())
3687        }
3688    }
3689
3690    /// Returns a y offsetted point for the line origin.
3691    /// Select the text from the current cursor position to the given offset.
3692    ///
3693    /// The offset is the UTF-8 offset.
3694    ///
3695    /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
3696    /// Extend a single selection so its moving end lands at `offset`, flipping
3697    /// `reversed` when the ends cross. When a sticky `word_range` is given the
3698    /// selection is kept covering it.
3699    fn extend_selection(
3700        sel: &mut CursorSelection,
3701        offset: usize,
3702        word_range: Option<CursorSelection>,
3703    ) {
3704        if sel.reversed {
3705            sel.start = offset;
3706        } else {
3707            sel.end = offset;
3708        }
3709
3710        if sel.end < sel.start {
3711            sel.reversed = !sel.reversed;
3712            std::mem::swap(&mut sel.start, &mut sel.end);
3713        }
3714
3715        if let Some(word_range) = word_range {
3716            if sel.start > word_range.start {
3717                sel.start = word_range.start;
3718            }
3719            if sel.end < word_range.end {
3720                sel.end = word_range.end;
3721            }
3722        }
3723    }
3724
3725    /// Extend only the active selection to `offset`. Used by mouse drag.
3726    pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
3727        self.select_to_with_affinity(offset, false, cx);
3728    }
3729
3730    /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
3731    ///
3732    /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
3733    /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
3734    /// the text rather than from a visual position, so the caret has no reason to keep sticking
3735    /// to the end of a wrapped row.
3736    pub(crate) fn select_to_with_affinity(
3737        &mut self,
3738        offset: usize,
3739        line_end_affinity: bool,
3740        cx: &mut Context<Self>,
3741    ) {
3742        M::clear_inline_completion(self, cx);
3743
3744        self.cursor_line_end_affinity = line_end_affinity;
3745        let offset = self.cursor_boundary(offset, Bias::Left);
3746        let word_range = self.selected_word_range;
3747        Self::extend_selection(self.active_selection_mut(), offset, word_range);
3748        let range = self.normalize_token_range(self.selected_range());
3749        self.set_selection(range.start, range.end);
3750
3751        if self.active_selection().is_empty() {
3752            self.update_preferred_column();
3753        }
3754        cx.notify()
3755    }
3756
3757    /// Extend every selection to the offset produced by `f`, then merge any
3758    /// selections that now overlap. Used by keyboard selection commands.
3759    fn select_all_cursors_to(
3760        &mut self,
3761        f: impl Fn(&Self, &CursorSelection) -> usize,
3762        cx: &mut Context<Self>,
3763    ) {
3764        self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
3765    }
3766
3767    /// Extend selections with caret affinity, preserving their column anchors even
3768    /// when vertical movement collapses a selection to a cursor.
3769    fn select_all_cursors_to_with_affinity(
3770        &mut self,
3771        f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
3772        preserve_column: bool,
3773        cx: &mut Context<Self>,
3774    ) {
3775        self.pause_blink_cursor(cx);
3776        self.undo_manager.break_transaction_coalescing();
3777        M::clear_inline_completion(self, cx);
3778
3779        let mut active_affinity = false;
3780        let new_selections: Vec<CursorSelection> = self
3781            .selections
3782            .iter()
3783            .map(|sel| {
3784                let (offset, affinity) = f(self, sel);
3785                if sel.id == self.active_selection().id {
3786                    active_affinity = affinity;
3787                }
3788                let offset = self.cursor_boundary(offset, Bias::Left);
3789                let mut new_sel = *sel;
3790                Self::extend_selection(&mut new_sel, offset, None);
3791                let range = self.normalize_token_range(new_sel.start..new_sel.end);
3792                new_sel.start = range.start;
3793                new_sel.end = range.end;
3794                if !preserve_column {
3795                    new_sel.column_anchor =
3796                        self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
3797                } else if new_sel.column_anchor.is_none() {
3798                    new_sel.column_anchor = self.preferred_column_for_with_affinity(
3799                        sel.cursor_offset(),
3800                        self.line_end_affinity_for(sel),
3801                    );
3802                }
3803                new_sel
3804            })
3805            .collect();
3806        self.cursor_line_end_affinity = active_affinity;
3807        self.selections.replace_all(new_selections);
3808        self.selections.merge_overlapping();
3809
3810        self.scroll_to(self.cursor(), None, cx);
3811        cx.notify()
3812    }
3813
3814    /// Unselects the currently selected text.
3815    pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3816        self.undo_manager.break_transaction_coalescing();
3817        let offset = self.cursor();
3818        self.set_cursor_to(offset);
3819        cx.notify()
3820    }
3821
3822    #[inline]
3823    pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
3824        self.text.offset_utf16_to_offset(offset)
3825    }
3826
3827    #[inline]
3828    pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
3829        self.text.offset_to_offset_utf16(offset)
3830    }
3831
3832    #[inline]
3833    pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
3834        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
3835    }
3836
3837    #[inline]
3838    pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
3839        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
3840    }
3841
3842    /// If offset falls on a hidden (folded) line, clamp backward to the end of
3843    /// the fold header line (last visible position before the fold).
3844    fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
3845        let line = self.text.offset_to_point(offset).row;
3846        if self.display_map.is_buffer_line_hidden(line) {
3847            for fold in self.display_map.folded_ranges() {
3848                if line > fold.start_line && line <= fold.end_line {
3849                    return self.text.line_end_offset(fold.start_line);
3850                }
3851            }
3852        }
3853        offset
3854    }
3855
3856    /// If offset falls on a hidden (folded) line, clamp forward to the start of
3857    /// the fold end line (first visible position after the fold).
3858    fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
3859        let line = self.text.offset_to_point(offset).row;
3860        if self.display_map.is_buffer_line_hidden(line) {
3861            for fold in self.display_map.folded_ranges() {
3862                if line > fold.start_line && line <= fold.end_line {
3863                    return self.text.line_start_offset(fold.end_line);
3864                }
3865            }
3866        }
3867        offset
3868    }
3869
3870    /// Clip a cursor/selection offset without splitting a CRLF newline. This does
3871    /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
3872    pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
3873        let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
3874        if offset > 0
3875            && self.text.char_at(offset - 1) == Some('\r')
3876            && self.text.char_at(offset) == Some('\n')
3877        {
3878            if bias == Bias::Left {
3879                offset - 1
3880            } else {
3881                offset + 1
3882            }
3883        } else {
3884            offset
3885        }
3886    }
3887
3888    pub(super) fn previous_boundary(&self, offset: usize) -> usize {
3889        let offset = self.cursor_boundary(offset.saturating_sub(1), Bias::Left);
3890        self.clamp_offset_to_visible_backward(offset)
3891    }
3892
3893    pub(super) fn next_boundary(&self, offset: usize) -> usize {
3894        let offset = self.cursor_boundary(offset.saturating_add(1), Bias::Right);
3895        self.clamp_offset_to_visible_forward(offset)
3896    }
3897
3898    /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
3899    pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
3900        (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
3901            && !self.disabled
3902            && self.blink_cursor.read(cx).visible()
3903            && window.is_window_active()
3904    }
3905
3906    fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3907        self.blink_cursor.update(cx, |cursor, cx| {
3908            cursor.start(cx);
3909        });
3910        cx.emit(InputEvent::Focus);
3911    }
3912
3913    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3914        self.revealed_viewport = None;
3915        if M::is_context_menu_open(self, cx) {
3916            return;
3917        }
3918
3919        M::hide_context_menu(self, cx);
3920        self.undo_manager.break_transaction_coalescing();
3921
3922        // NOTE: Do not cancel select, when blur.
3923        // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
3924
3925        M::clear_hover_state(self, cx);
3926        self.diagnostic_popover = None;
3927        M::clear_inline_completion(self, cx);
3928        self.dismiss_touch_selection(cx);
3929        self.blink_cursor.update(cx, |cursor, cx| {
3930            cursor.stop(cx);
3931        });
3932        self.clamp_number_value(window, cx);
3933        cx.emit(InputEvent::Blur);
3934        cx.notify();
3935    }
3936
3937    /// Clamp the number value to the `min`/`max` range, used on blur.
3938    ///
3939    /// Out-of-range values are allowed while typing (e.g. `1` is an
3940    /// intermediate state of `15` when min is 10), and clamped on blur.
3941    fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3942        if !self.is_single_line() {
3943            return;
3944        }
3945        if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
3946            return;
3947        }
3948        if self.number_min.is_none() && self.number_max.is_none() {
3949            return;
3950        }
3951
3952        let Ok(value) = self.unmask_value().parse::<f64>() else {
3953            return;
3954        };
3955
3956        let clamped = match (self.number_min, self.number_max) {
3957            (Some(min), _) if value < min => min,
3958            (_, Some(max)) if value > max => max,
3959            _ => return,
3960        };
3961
3962        // The clamped value must pass the `pattern`/`validate` check,
3963        // otherwise keep the value as is.
3964        let new_text = clamped.to_string();
3965        if !self.is_valid_input(&new_text, cx) {
3966            return;
3967        }
3968
3969        let range = self.range_to_utf16(&(0..self.text.len_bytes()));
3970        self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
3971    }
3972
3973    pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
3974        self.blink_cursor.update(cx, |cursor, cx| {
3975            cursor.pause(cx);
3976        });
3977    }
3978
3979    pub(super) fn on_drag_move(
3980        &mut self,
3981        event: &MouseMoveEvent,
3982        window: &mut Window,
3983        cx: &mut Context<Self>,
3984    ) {
3985        if self.text.len_bytes() == 0 {
3986            return;
3987        }
3988
3989        if self.last_layout.is_none() {
3990            return;
3991        }
3992
3993        if !self.focus_handle.is_focused(window) {
3994            return;
3995        }
3996
3997        if !self.selecting {
3998            return;
3999        }
4000
4001        self.auto_scroll.last_drag_position = Some(event.position);
4002        let (offset, line_end_affinity, columns_past_line_end) =
4003            self.resolve_mouse_position(event.position);
4004        if let Some(start) = self.column_select_start {
4005            let end = ColumnarPoint::new(offset, columns_past_line_end);
4006            self.build_columnar_selection(start, end, cx);
4007        } else {
4008            self.select_to_with_affinity(offset, line_end_affinity, cx);
4009        }
4010
4011        if !self.is_single_line() {
4012            let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
4013            // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
4014            let scroll_delta = delta.map(|d| -d);
4015            self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
4016                let current = state.scroll_handle.offset();
4017                state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
4018                if let Some(pos) = state.auto_scroll.last_drag_position {
4019                    let (offset, line_end_affinity, columns_past_line_end) =
4020                        state.resolve_mouse_position(pos);
4021                    if let Some(start) = state.column_select_start {
4022                        let end = ColumnarPoint::new(offset, columns_past_line_end);
4023                        state.build_columnar_selection(start, end, cx);
4024                    } else {
4025                        state.select_to_with_affinity(offset, line_end_affinity, cx);
4026                    }
4027                }
4028            });
4029        }
4030    }
4031
4032    /// Normalize the inserted text before applying it to the input.
4033    ///
4034    /// For number inputs (with [`MaskPattern::Number`]), this converts
4035    /// full-width number characters into their ASCII equivalents,
4036    /// e.g. `12。5` -> `12.5`.
4037    pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
4038        let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4039            normalize_number_input(new_text)
4040        } else {
4041            Cow::Borrowed(new_text)
4042        };
4043
4044        if self.is_single_line() && normalized.contains(['\n', '\r']) {
4045            Cow::Owned(normalized.replace(['\n', '\r'], ""))
4046        } else {
4047            normalized
4048        }
4049    }
4050
4051    pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
4052        if new_text.is_empty() {
4053            return true;
4054        }
4055
4056        if let Some(validate) = &self.validate {
4057            if !validate(new_text, cx) {
4058                return false;
4059            }
4060        }
4061
4062        if !self.mask_pattern.is_valid(new_text) {
4063            return false;
4064        }
4065
4066        let Some(pattern) = &self.pattern else {
4067            return true;
4068        };
4069
4070        pattern.is_match(new_text)
4071    }
4072
4073    /// Set the mask pattern for formatting the input text.
4074    ///
4075    /// The pattern can contain:
4076    /// - 9: Any digit or dot
4077    /// - A: Any letter
4078    /// - *: Any character
4079    /// - Other characters will be treated as literal mask characters
4080    ///
4081    /// Example: "(999)999-999" for phone numbers
4082    pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
4083        self.mask_pattern = pattern.into();
4084        self.mask_pattern_set = true;
4085        if let Some(placeholder) = self.mask_pattern.placeholder() {
4086            self.placeholder = placeholder.into();
4087        }
4088        self
4089    }
4090
4091    pub fn set_mask_pattern(
4092        &mut self,
4093        pattern: impl Into<MaskPattern>,
4094        _: &mut Window,
4095        cx: &mut Context<Self>,
4096    ) {
4097        self.mask_pattern = pattern.into();
4098        self.mask_pattern_set = true;
4099        if let Some(placeholder) = self.mask_pattern.placeholder() {
4100            self.placeholder = placeholder.into();
4101        }
4102        cx.notify();
4103    }
4104
4105    /// Apply the default numeric mask unless the caller explicitly selected a mask.
4106    pub fn ensure_number_mask(&mut self) {
4107        if self.mask_pattern_set {
4108            return;
4109        }
4110        self.mask_pattern = MaskPattern::Number {
4111            separator: None,
4112            fraction: None,
4113        };
4114    }
4115
4116    pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
4117        let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
4118        self.input_bounds = new_bounds;
4119
4120        // Update display_map wrap_width if changed.
4121        if let Some(last_layout) = self.last_layout.as_ref() {
4122            if wrap_width_changed {
4123                let wrap_width = if !self.soft_wrap {
4124                    // None to disable wrapping (will use Pixels::MAX)
4125                    None
4126                } else {
4127                    last_layout.wrap_width
4128                };
4129
4130                self.display_map.on_layout_changed(wrap_width, cx);
4131                if self.is_multi_line() {
4132                    self.mode.update_auto_grow(&self.display_map);
4133                }
4134                cx.notify();
4135            }
4136        }
4137    }
4138
4139    /// Return the active selection's text, borrowed out of the [`Rope`]
4140    /// the state owns.
4141    ///
4142    /// See [`Self::selected_value`] when an owned string is wanted.
4143    pub fn selected_text(&self) -> RopeSlice<'_> {
4144        let range_utf16 = self.range_to_utf16(&self.selected_range());
4145        let range = self.range_from_utf16(&range_utf16);
4146        self.text.byte_slice(range)
4147    }
4148
4149    /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
4150    ///
4151    /// Returns `None` when the requested range is not currently laid out or visible.
4152    pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
4153        let Some(last_layout) = self.last_layout.as_ref() else {
4154            return None;
4155        };
4156
4157        let Some(last_bounds) = self.last_bounds else {
4158            return None;
4159        };
4160
4161        let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
4162        let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
4163
4164        let Some(start_pos) = start_pos else {
4165            return None;
4166        };
4167        let Some(end_pos) = end_pos else {
4168            return None;
4169        };
4170
4171        Some(Bounds::from_corners(
4172            last_bounds.origin + start_pos,
4173            last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
4174        ))
4175    }
4176
4177    /// Replace text in range in silent.
4178    ///
4179    /// This will not trigger any UI interaction, such as auto-completion.
4180    pub(crate) fn replace_text_in_range_silent(
4181        &mut self,
4182        range_utf16: Option<Range<usize>>,
4183        new_text: &str,
4184        window: &mut Window,
4185        cx: &mut Context<Self>,
4186    ) {
4187        self.silent_replace_text = true;
4188        self.replace_text_in_range(range_utf16, new_text, window, cx);
4189        self.silent_replace_text = false;
4190    }
4191
4192    /// Apply a batch of edits as one atomic history transaction.
4193    ///
4194    /// `edits` are `(byte range in the current pre-edit document, replacement)`
4195    /// pairs.
4196    pub(crate) fn replace_text_in_ranges(
4197        &mut self,
4198        edits: &[(Range<usize>, String)],
4199        window: &mut Window,
4200        cx: &mut Context<Self>,
4201    ) {
4202        if !self.is_editable() || edits.is_empty() {
4203            return;
4204        }
4205
4206        // Every edit invalidates provider responses for the previous document,
4207        // including deletion and indentation which do not trigger completion.
4208        M::hide_context_menu(self, cx);
4209        M::clear_inline_completion(self, cx);
4210
4211        // Sort descending by start so applying front-of-vec first edits the
4212        // highest offsets first, leaving lower offsets unchanged.
4213        let mut sorted: Vec<(Range<usize>, &str)> = edits
4214            .iter()
4215            .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
4216            .collect();
4217        sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
4218        if !self.token_spans().is_empty() {
4219            let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
4220            for (range, text) in sorted {
4221                if let Some(last) = merged
4222                    .last_mut()
4223                    .filter(|last| range.end > last.0.start || range == last.0)
4224                {
4225                    last.0.start = range.start.min(last.0.start);
4226                    last.0.end = range.end.max(last.0.end);
4227                } else {
4228                    merged.push((range, text));
4229                }
4230            }
4231            sorted = merged;
4232        }
4233
4234        #[cfg(debug_assertions)]
4235        for pair in sorted.windows(2) {
4236            debug_assert!(
4237                pair[1].0.end <= pair[0].0.start,
4238                "replace_text_in_ranges requires disjoint ranges"
4239            );
4240        }
4241
4242        // Wrap multiple edits in one explicit transaction so they undo as a
4243        // unit. A single edit records directly, which keeps it eligible for
4244        // the undo manager's typing coalescing.
4245        let requested_intent = self.undo_manager.take_pending_intent();
4246        let selection_before = *self.active_selection();
4247        let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
4248        // Snapshot the cursors before applying, so undo can restore them. A
4249        // delete has already expanded them over the text it removes, so they
4250        // collapse back to where the user left them.
4251        let selections_before: Vec<CursorSelection> = self
4252            .selections
4253            .iter()
4254            .map(|selection| {
4255                Self::collapse_for_intent(
4256                    requested_intent.unwrap_or(EditIntent::Atomic),
4257                    *selection,
4258                    &(selection.start..selection.end),
4259                )
4260            })
4261            .collect();
4262        let group = sorted.len() > 1;
4263        if group {
4264            self.undo_manager.begin_transaction();
4265        }
4266
4267        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4268        let mut recorded = false;
4269        // Several edits reach the highlighter as one batch, so it reparses
4270        // once for the change instead of once per edit.
4271        let mut highlighter_edits = Vec::new();
4272        for (range, new_text) in &sorted {
4273            let old_text = self.text.clone();
4274            self.mode.adjust_auto_closed_pair(range, new_text.len());
4275            self.text.replace(range.clone(), new_text);
4276
4277            M::adjust_annotations(self, range, new_text.len());
4278            recorded |= self.push_history(
4279                &old_text,
4280                range,
4281                new_text,
4282                requested_intent,
4283                selection_before,
4284                None,
4285            );
4286
4287            // Incremental, single-range updates must run per edit.
4288            self.display_map
4289                .adjust_folds_for_edit(&old_text, range, new_text);
4290            self.display_map
4291                .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
4292
4293            if group {
4294                if self.is_code_editor() {
4295                    let edit =
4296                        super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
4297                    highlighter_edits.push((edit, self.text.clone()));
4298                }
4299            } else {
4300                self.mode.update_highlighter(
4301                    super::mode::HighlighterUpdate {
4302                        selected_range: range,
4303                        old_text: &old_text,
4304                        new_text: &self.text,
4305                        change_text: new_text,
4306                        force: true,
4307                    },
4308                    window,
4309                    cx,
4310                );
4311
4312                self.update_fold_candidates_incremental(range, new_text);
4313            }
4314        }
4315
4316        if group {
4317            self.mode
4318                .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
4319
4320            // Fold candidates are read from the reparsed document, so each
4321            // edit is located where it ended up once every edit was applied.
4322            // `sorted` runs from the highest offset down.
4323            let mut shift = 0isize;
4324            for (range, new_text) in sorted.iter().rev() {
4325                let start = (range.start as isize + shift) as usize;
4326                self.update_fold_candidates_incremental(&(start..start), new_text);
4327                shift += new_text.len() as isize - range.len() as isize;
4328            }
4329
4330            self.undo_manager.commit_transaction();
4331        }
4332
4333        // One observable update per batch instead of one per edit.
4334        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4335            diagnostics.reset(&self.text)
4336        }
4337        M::refresh_language_features(self, window, cx);
4338        self.update_search(cx);
4339
4340        // Compute the resulting cursors.
4341        // One collapsed cursor per edit, at the end of its inserted text.
4342        let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
4343        ascending.sort_by_key(|edit| edit.0.start);
4344        let text_len = self.text.len_bytes();
4345        let mut delta: isize = 0;
4346        let mut edit_results = Vec::with_capacity(ascending.len());
4347        for (range, new_text) in &ascending {
4348            let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
4349            edit_results.push((range.clone(), offset));
4350            delta += new_text.len() as isize - (range.end as isize - range.start as isize);
4351        }
4352
4353        let mut used = vec![false; edit_results.len()];
4354        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
4355        for selection in original_selections {
4356            if let Ok(index) = edit_results
4357                .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
4358                    (range.start, range.end)
4359                })
4360                && !used[index]
4361            {
4362                let offset = edit_results[index].1;
4363                used[index] = true;
4364                let mut selection = selection;
4365                selection.place_at(offset, None);
4366                new_selections.push(selection);
4367            }
4368        }
4369        for (index, (_, offset)) in edit_results.into_iter().enumerate() {
4370            if !used[index] {
4371                new_selections.push(CursorSelection::new(
4372                    self.selections.generate_id(),
4373                    offset,
4374                    offset,
4375                ));
4376            }
4377        }
4378        self.selections.replace_all(new_selections);
4379        self.selections.merge_overlapping();
4380
4381        // Record the cursor snapshots for undo/redo restore.
4382        let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
4383        if recorded {
4384            self.undo_manager.record_auto_closed_pairs(
4385                auto_closed_pairs_before,
4386                self.mode.auto_closed_pairs().clone(),
4387            );
4388            self.undo_manager
4389                .record_selections(selections_before, selections_after);
4390        }
4391
4392        self.ime_marked_range.take();
4393        self.update_preferred_column();
4394        self.dismiss_touch_selection(cx);
4395        if self.is_multi_line() {
4396            self.mode.update_auto_grow(&self.display_map);
4397        }
4398        if self.emit_events {
4399            cx.emit(InputEvent::Change);
4400        }
4401        cx.notify();
4402    }
4403
4404    /// Update fold candidates from tree-sitter syntax tree (full extraction).
4405    /// Used only on initial load or language changes.
4406    fn update_fold_candidates(&mut self) {
4407        if !self.mode.is_folding() {
4408            return;
4409        }
4410
4411        let Some(highlighter_rc) = self.mode.highlighter() else {
4412            return;
4413        };
4414
4415        let highlighter = highlighter_rc.borrow();
4416        let Some(highlighter) = highlighter.as_ref() else {
4417            return;
4418        };
4419
4420        let fold_ranges = highlighter.fold_ranges(&self.text);
4421        self.display_map.set_fold_candidates(fold_ranges);
4422    }
4423
4424    /// Incrementally update fold candidates after a text edit.
4425    /// Only traverses the edited region of the syntax tree instead of the full tree.
4426    fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
4427        if !self.mode.is_folding() {
4428            return;
4429        }
4430
4431        let Some(highlighter_rc) = self.mode.highlighter() else {
4432            return;
4433        };
4434
4435        let highlighter = highlighter_rc.borrow();
4436        let Some(highlighter) = highlighter.as_ref() else {
4437            return;
4438        };
4439
4440        // The new byte range in the updated text after the edit
4441        let new_end = edit_range.start + new_text.len();
4442        self.display_map.update_fold_candidates_for_edit(
4443            |range, text| highlighter.fold_ranges_for_edit(range, text),
4444            edit_range.start..new_end,
4445            &self.text,
4446        );
4447    }
4448}
4449
4450impl<M: InputModeKind> InputBaseState<M> {
4451    fn replace_and_mark_text(
4452        &mut self,
4453        range_utf16: Option<Range<usize>>,
4454        new_text: &str,
4455        new_selected_range_utf16: Option<Range<usize>>,
4456        preserve_empty_composition: bool,
4457        window: &mut Window,
4458        cx: &mut Context<Self>,
4459    ) {
4460        let requested_intent = self.undo_manager.take_pending_intent();
4461        if !self.is_editable() {
4462            return;
4463        }
4464        let selection_before = *self.active_selection();
4465
4466        let starts_composition = self.ime_marked_range.is_none();
4467        if starts_composition {
4468            // Even a canceled preedit separates the typing gestures on either
4469            // side; its no-op transaction must not reconnect those gestures.
4470            self.undo_manager.break_transaction_coalescing();
4471            self.undo_manager.begin_transaction();
4472        }
4473
4474        // Collapse any extra cursors so we never leave stale secondary cursors behind.
4475        self.selections.remove_all_but_active();
4476
4477        M::reset_language_features(self);
4478
4479        // See the same NOTE in `replace_text_in_range`.
4480        let new_text = if self.replaying_history {
4481            Cow::Borrowed(new_text)
4482        } else {
4483            self.normalize_input(new_text)
4484        };
4485        let new_text: &str = &new_text;
4486
4487        let range = range_utf16
4488            .as_ref()
4489            .map(|range_utf16| self.range_from_utf16(range_utf16))
4490            .or(self.ime_marked_range.map(|range| {
4491                let range = self.range_to_utf16(&(range.start..range.end));
4492                self.range_from_utf16(&range)
4493            }))
4494            .unwrap_or(self.selected_range());
4495        let range = self.normalize_token_range(range);
4496
4497        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4498        let old_text = self.text.clone();
4499        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4500        self.text.replace(range.clone(), new_text);
4501
4502        if self.is_single_line() {
4503            let pending_text = self.text.to_string();
4504            // See the same NOTE in `replace_text_in_range`.
4505            if !self.replaying_history
4506                && !self.validated_token_edit
4507                && !self.is_valid_input(&pending_text, cx)
4508                && self.is_valid_input(&old_text.to_string(), cx)
4509            {
4510                self.text = old_text;
4511                if starts_composition {
4512                    self.undo_manager.commit_transaction();
4513                }
4514                return;
4515            }
4516        }
4517
4518        M::adjust_annotations(self, &range, new_text.len());
4519        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4520            diagnostics.reset(&self.text)
4521        }
4522        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4523        self.display_map
4524            .adjust_folds_for_edit(&old_text, &range, new_text);
4525        self.display_map
4526            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4527
4528        self.mode.update_highlighter::<M>(
4529            super::mode::HighlighterUpdate {
4530                selected_range: &range,
4531                old_text: &old_text,
4532                new_text: &self.text,
4533                change_text: &new_text,
4534                force: true,
4535            },
4536            window,
4537            cx,
4538        );
4539
4540        self.update_fold_candidates_incremental(&range, new_text);
4541        M::refresh_language_features(self, window, cx);
4542        if new_text.is_empty() {
4543            self.set_cursor_to(range.start);
4544            // A native empty preedit can precede a commit, so its insertion
4545            // anchor and original undo selection must survive until it ends.
4546            self.ime_marked_range =
4547                preserve_empty_composition.then_some((range.start..range.start).into());
4548        } else {
4549            self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
4550            let new_range = new_selected_range_utf16
4551                .as_ref()
4552                .map(|range_utf16| {
4553                    let new_text = Rope::from(new_text);
4554                    range.start + new_text.offset_utf16_to_offset(range_utf16.start)
4555                        ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
4556                })
4557                .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
4558            self.set_selection(new_range.start, new_range.end);
4559        }
4560        if self.is_multi_line() {
4561            self.mode.update_auto_grow(&self.display_map);
4562        }
4563        if self.push_history(
4564            &old_text,
4565            &range,
4566            new_text,
4567            requested_intent,
4568            selection_before,
4569            Some(*self.active_selection()),
4570        ) {
4571            self.undo_manager
4572                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4573            self.undo_manager.record_auto_closed_pairs(
4574                auto_closed_pairs_before,
4575                self.mode.auto_closed_pairs().clone(),
4576            );
4577        }
4578        if new_text.is_empty() && !preserve_empty_composition {
4579            self.undo_manager.commit_transaction();
4580        }
4581        cx.notify();
4582    }
4583}
4584
4585impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4586    fn text_for_range(
4587        &mut self,
4588        range_utf16: Range<usize>,
4589        adjusted_range: &mut Option<Range<usize>>,
4590        _window: &mut Window,
4591        _cx: &mut Context<Self>,
4592    ) -> Option<String> {
4593        let range = self.range_from_utf16(&range_utf16);
4594        adjusted_range.replace(self.range_to_utf16(&range));
4595        Some(self.text.byte_slice(range).to_string())
4596    }
4597
4598    fn selected_text_range(
4599        &mut self,
4600        _ignore_disabled_input: bool,
4601        _window: &mut Window,
4602        _cx: &mut Context<Self>,
4603    ) -> Option<UTF16Selection> {
4604        Some(UTF16Selection {
4605            range: self.range_to_utf16(&self.selected_range()),
4606            reversed: self.active_selection().reversed,
4607        })
4608    }
4609
4610    fn marked_text_range(
4611        &self,
4612        _window: &mut Window,
4613        _cx: &mut Context<Self>,
4614    ) -> Option<Range<usize>> {
4615        self.ime_marked_range
4616            .map(|range| self.range_to_utf16(&range.into()))
4617    }
4618
4619    fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
4620        self.ime_marked_range = None;
4621        self.undo_manager.commit_transaction();
4622    }
4623
4624    /// Replace text in range.
4625    ///
4626    /// - If the new text is invalid, it will not be replaced.
4627    /// - If `range_utf16` is not provided, the current selected range will be used.
4628    fn replace_text_in_range(
4629        &mut self,
4630        range_utf16: Option<Range<usize>>,
4631        new_text: &str,
4632        window: &mut Window,
4633        cx: &mut Context<Self>,
4634    ) {
4635        let requested_intent = self.undo_manager.take_pending_intent();
4636        if !self.is_editable() {
4637            return;
4638        }
4639        let selection_before = *self.active_selection();
4640        // Committing a composition ends the transaction it opened, whether or
4641        // not the platform follows up with `unmark_text`.
4642        let ends_composition = self.ime_marked_range.is_some();
4643
4644        self.pause_blink_cursor(cx);
4645
4646        // NOTE: The normalization keeps the UTF-16 length, but may change the
4647        // UTF-8 byte length, so all the byte-offset calculations below must
4648        // use the normalized text.
4649        let new_text = if self.replaying_history {
4650            Cow::Borrowed(new_text)
4651        } else {
4652            self.normalize_input(new_text)
4653        };
4654        let new_text: &str = &new_text;
4655
4656        let range = range_utf16
4657            .as_ref()
4658            .map(|range_utf16| self.range_from_utf16(range_utf16))
4659            .or(self.ime_marked_range.map(|range| {
4660                let range = self.range_to_utf16(&(range.start..range.end));
4661                self.range_from_utf16(&range)
4662            }))
4663            .unwrap_or(self.selected_range());
4664        let range = self.normalize_token_range(range);
4665
4666        // Skip-over as a pure cursor move: a typed closer that already follows
4667        // the cursor moves past it without touching text or history, so Undo
4668        // never exposes a transient duplicate. Only for interactive single
4669        // keystrokes (current selection, no IME mark, not silent replays).
4670        // `take_pending_intent` above already consumed any request.
4671        if range.is_empty()
4672            && range.start == self.cursor()
4673            && self.ime_marked_range.is_none()
4674            && !self.silent_replace_text
4675            && self.is_code_editor()
4676            && self.selections.is_single()
4677            && self.active_selection().is_empty()
4678        {
4679            if let Some(target) = self.skip_over_target(new_text) {
4680                self.set_cursor_to(target);
4681                self.update_preferred_column();
4682                cx.notify();
4683                return;
4684            }
4685        }
4686
4687        if self.is_multi_line() {
4688            let multi_cursor = range_utf16.is_none()
4689                && self.ime_marked_range.is_none()
4690                && !self.selections.is_single();
4691            if multi_cursor {
4692                self.selections.merge_overlapping();
4693                let mut edits: Vec<(Range<usize>, String)> = self
4694                    .selections
4695                    .iter()
4696                    .map(|sel| (sel.start..sel.end, new_text.to_string()))
4697                    .collect();
4698                edits.sort_by_key(|(range, _)| range.start);
4699                // One keystroke across several cursors is one batch, committed
4700                // with the intent of the keystroke so a run of them coalesces
4701                // into one undo just like single-cursor typing.
4702                let intent =
4703                    requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
4704                self.undo_manager.begin_transaction_with(intent);
4705                self.undo_manager.set_pending_intent(intent);
4706                self.replace_text_in_ranges(&edits, window, cx);
4707                self.undo_manager.commit_transaction();
4708            } else {
4709                if range_utf16.is_some() {
4710                    self.selections.remove_all_but_active();
4711                }
4712                if let Some(intent) = requested_intent {
4713                    self.undo_manager.set_pending_intent(intent);
4714                }
4715                if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
4716                    // One edit keeps the pair atomic even at undo coalescing limits.
4717                    let replacement = format!("{new_text}{closer}");
4718                    self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
4719                    let cursor = range.start + new_text.len();
4720                    self.mode.track_auto_closed_pair(
4721                        cursor - open_len..cursor,
4722                        cursor..cursor + closer.len(),
4723                    );
4724                    self.undo_manager
4725                        .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
4726                    self.set_cursor_to(cursor);
4727                    self.update_preferred_column();
4728                    self.undo_manager.record_selections(
4729                        vec![selection_before],
4730                        self.selections.iter().copied().collect(),
4731                    );
4732                } else {
4733                    self.replace_text_in_ranges(
4734                        &[(range.clone(), new_text.to_string())],
4735                        window,
4736                        cx,
4737                    );
4738                }
4739            }
4740            if ends_composition {
4741                self.undo_manager.commit_transaction();
4742            }
4743
4744            if !self.silent_replace_text {
4745                M::on_text_typed(self, &range, new_text, window, cx);
4746            }
4747            return;
4748        }
4749
4750        // Single-line path
4751        let old_text = self.text.clone();
4752        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4753        self.text.replace(range.clone(), new_text);
4754
4755        let mut new_offset = (range.start + new_text.len()).min(self.text.len_bytes());
4756
4757        // True if the mask has changed the text, e.g. regrouping the
4758        // separators or completing a leading dot.
4759        let mut mask_changed = false;
4760
4761        if self.is_single_line() {
4762            let pending_text = self.text.to_string();
4763            // Check if the new text is valid.
4764            //
4765            // Only reject the edit if the old text was valid, to avoid
4766            // trapping a pre-existing invalid text (e.g. a `default_value`
4767            // that does not conform), the user can still edit to fix it.
4768            if !self.replaying_history
4769                && !self.validated_token_edit
4770                && !self.is_valid_input(&pending_text, cx)
4771                && self.is_valid_input(&old_text.to_string(), cx)
4772            {
4773                self.text = old_text;
4774                return;
4775            }
4776
4777            if !self.replaying_history && !self.mask_pattern.is_none() {
4778                let mask_text = self.mask_pattern.mask(&pending_text);
4779                mask_changed = mask_text.as_str() != pending_text;
4780                self.text = Rope::from(mask_text.as_str());
4781                let new_text_len =
4782                    (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
4783                new_offset = (range.start + new_text_len).min(mask_text.len());
4784            }
4785        }
4786
4787        if mask_changed {
4788            // Masking rewrites the whole document, so ranges recorded against
4789            // the old text no longer point at anything.
4790            M::reset_annotations(self);
4791        } else {
4792            M::adjust_annotations(self, &range, new_text.len());
4793        }
4794        if mask_changed {
4795            // A segment-based history entry no longer matches the masked
4796            // document, record a whole-document change instead, so that
4797            // undo/redo can restore the text exactly.
4798            self.push_history(
4799                &old_text,
4800                &(0..old_text.len_bytes()),
4801                &self.text.to_string(),
4802                Some(EditIntent::Atomic),
4803                selection_before,
4804                Some((new_offset..new_offset).into()),
4805            );
4806        } else {
4807            self.push_history(
4808                &old_text,
4809                &range,
4810                &new_text,
4811                requested_intent,
4812                selection_before,
4813                None,
4814            );
4815        }
4816        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4817            diagnostics.reset(&self.text)
4818        }
4819        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4820        self.display_map
4821            .adjust_folds_for_edit(&old_text, &range, new_text);
4822        self.display_map
4823            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4824
4825        self.mode.update_highlighter::<M>(
4826            super::mode::HighlighterUpdate {
4827                selected_range: &range,
4828                old_text: &old_text,
4829                new_text: &self.text,
4830                change_text: &new_text,
4831                force: true,
4832            },
4833            window,
4834            cx,
4835        );
4836
4837        self.update_fold_candidates_incremental(&range, new_text);
4838        M::refresh_language_features(self, window, cx);
4839        self.set_cursor_to(new_offset);
4840        self.ime_marked_range.take();
4841        // A commit ends the IME composition: macOS delivers `insertText:` for
4842        // the confirmed candidate without a following `unmarkText`, so close
4843        // the transaction here. Leaving it open would keep merging every later
4844        // edit into the same change, which then carries the text and selection
4845        // of the first composition.
4846        if ends_composition {
4847            self.undo_manager
4848                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4849            self.undo_manager.commit_transaction();
4850        }
4851        self.update_preferred_column();
4852        self.update_search(cx);
4853        self.dismiss_touch_selection(cx);
4854        if self.is_multi_line() {
4855            self.mode.update_auto_grow(&self.display_map);
4856        }
4857        if !self.silent_replace_text {
4858            M::on_text_typed(self, &range, &new_text, window, cx);
4859        }
4860        if self.emit_events {
4861            cx.emit(InputEvent::Change);
4862        }
4863        cx.notify();
4864    }
4865
4866    fn clear_marked_text(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4867        if self.ime_marked_range.is_some() {
4868            self.replace_and_mark_text(None, "", Some(0..0), true, window, cx);
4869        }
4870    }
4871
4872    /// Mark text is the IME temporary insert on typing.
4873    fn replace_and_mark_text_in_range(
4874        &mut self,
4875        range_utf16: Option<Range<usize>>,
4876        new_text: &str,
4877        new_selected_range_utf16: Option<Range<usize>>,
4878        window: &mut Window,
4879        cx: &mut Context<Self>,
4880    ) {
4881        self.replace_and_mark_text(
4882            range_utf16,
4883            new_text,
4884            new_selected_range_utf16,
4885            false,
4886            window,
4887            cx,
4888        );
4889    }
4890
4891    /// Used to position IME candidates.
4892    fn bounds_for_range(
4893        &mut self,
4894        range_utf16: Range<usize>,
4895        bounds: Bounds<Pixels>,
4896        _window: &mut Window,
4897        _cx: &mut Context<Self>,
4898    ) -> Option<Bounds<Pixels>> {
4899        let last_layout = self.last_layout.as_ref()?;
4900        let line_height = last_layout.line_height;
4901        let line_number_width = last_layout.line_number_width;
4902        let range = self.range_from_utf16(&range_utf16);
4903
4904        let mut start_origin = None;
4905        let mut end_origin = None;
4906        let line_number_origin = point(line_number_width, px(0.));
4907        let mut y_offset = last_layout.visible_top;
4908
4909        for (vi, line) in last_layout.lines.iter().enumerate() {
4910            if start_origin.is_some() && end_origin.is_some() {
4911                break;
4912            }
4913
4914            let index_offset = last_layout.visible_line_byte_offsets[vi];
4915
4916            if start_origin.is_none() {
4917                if let Some(p) = line.position_for_index(
4918                    range.start.saturating_sub(index_offset),
4919                    last_layout,
4920                    false,
4921                ) {
4922                    start_origin = Some(p + point(px(0.), y_offset));
4923                }
4924            }
4925
4926            if end_origin.is_none() {
4927                if let Some(p) = line.position_for_index(
4928                    range.end.saturating_sub(index_offset),
4929                    last_layout,
4930                    false,
4931                ) {
4932                    end_origin = Some(p + point(px(0.), y_offset));
4933                }
4934            }
4935
4936            y_offset += line.size(line_height).height;
4937        }
4938
4939        let start_origin = start_origin.or_else(|| {
4940            let offset = self.last_cursor.or(Some(self.cursor()))?;
4941            let (_, _, origin) = self.line_and_position_for_offset(offset);
4942            origin.map(|origin| origin - line_number_origin)
4943        })?;
4944        let mut end_origin = end_origin.unwrap_or(start_origin);
4945        // Ensure at same line.
4946        end_origin.y = start_origin.y;
4947
4948        Some(Bounds::from_corners(
4949            bounds.origin + line_number_origin + start_origin,
4950            // + line_height for show IME panel under the cursor line.
4951            bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
4952        ))
4953    }
4954
4955    fn character_index_for_point(
4956        &mut self,
4957        point: wgpui::Point<Pixels>,
4958        _window: &mut Window,
4959        _cx: &mut Context<Self>,
4960    ) -> Option<usize> {
4961        let last_layout = self.last_layout.as_ref()?;
4962        let line_point = self.last_bounds?.localize(&point)?;
4963
4964        for (vi, line) in last_layout.lines.iter().enumerate() {
4965            let offset = last_layout.visible_line_byte_offsets[vi];
4966            if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
4967                return Some(self.offset_to_utf16(offset + utf8_index));
4968            }
4969        }
4970
4971        None
4972    }
4973
4974    fn text_input_configuration(
4975        &mut self,
4976        _window: &mut Window,
4977        _cx: &mut Context<Self>,
4978    ) -> TextInputConfiguration {
4979        InputBaseState::text_input_configuration(self)
4980    }
4981}
4982
4983impl<M: InputModeKind> Focusable for InputBaseState<M> {
4984    fn focus_handle(&self, _cx: &App) -> FocusHandle {
4985        self.focus_handle.clone()
4986    }
4987}
4988
4989impl<M: InputModeKind> Render for InputBaseState<M> {
4990    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4991        // Before anything reads it: the element resolves this style during
4992        // layout and paint, and both happen after this call in the same frame.
4993        self.editor_style = self
4994            .projected_editor_style
4995            .resolved(&crate::Theme::global(cx).tokens);
4996        let entity = cx.entity();
4997        if self._pending_update {
4998            self.mode.update_highlighter::<M>(
4999                super::mode::HighlighterUpdate {
5000                    selected_range: &(0..0),
5001                    old_text: &self.text,
5002                    new_text: &self.text,
5003                    change_text: "",
5004                    force: false,
5005                },
5006                window,
5007                cx,
5008            );
5009
5010            self.update_fold_candidates();
5011            M::refresh_language_features(self, window, cx);
5012            self._pending_update = false;
5013        }
5014
5015        let element = div()
5016            .id(EDITOR_ELEMENT_ID)
5017            .key_context(CONTEXT)
5018            .when_some(self.accessibility.as_ref(), |this, accessibility| {
5019                this.when_some(accessibility.role, |this, role| this.role(role))
5020                    .when_some(accessibility.label.clone(), |this, label| {
5021                        this.aria_label(label)
5022                    })
5023                    .when_some(accessibility.placeholder.clone(), |this, placeholder| {
5024                        this.aria_placeholder(placeholder)
5025                    })
5026                    .when_some(accessibility.accessibility_id.clone(), |this, id| {
5027                        this.accessibility_id(id)
5028                    })
5029                    .when(
5030                        accessibility.value_exposed
5031                            && !self.masked
5032                            && (window.is_a11y_active() || cfg!(feature = "test-support")),
5033                        |this| this.aria_value(self.text.to_string()),
5034                    )
5035                    .on_a11y_action(wgpui::AccessibleAction::Focus, {
5036                        let entity = entity.clone();
5037                        move |_, window, cx| {
5038                            entity.update(cx, |state, cx| {
5039                                state.handle_accessibility_focus(window, cx)
5040                            });
5041                        }
5042                    })
5043                    .when(self.is_editable(), |this| {
5044                        this.on_a11y_action(wgpui::AccessibleAction::SetValue, {
5045                            let entity = entity.clone();
5046                            move |data, window, cx| {
5047                                entity.update(cx, |state, cx| {
5048                                    state.handle_accessibility_set_value(data, window, cx)
5049                                });
5050                            }
5051                        })
5052                    })
5053            })
5054            .when(self.is_editable(), |this| {
5055                this.on_action(window.listener_for(&entity, InputBaseState::backspace))
5056                    .on_action(window.listener_for(&entity, InputBaseState::delete))
5057                    .on_action(
5058                        window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
5059                    )
5060                    .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
5061                    .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
5062                    .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
5063                    .on_action(window.listener_for(&entity, InputBaseState::enter))
5064                    .on_action(window.listener_for(&entity, InputBaseState::escape))
5065                    .on_action(window.listener_for(&entity, InputBaseState::paste))
5066                    .on_action(window.listener_for(&entity, InputBaseState::cut))
5067                    .on_action(window.listener_for(&entity, InputBaseState::undo))
5068                    .on_action(window.listener_for(&entity, InputBaseState::redo))
5069                    .when(self.is_multi_line(), |this| {
5070                        this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
5071                            .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
5072                            .on_action(window.listener_for(&entity, InputBaseState::indent_block))
5073                            .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
5074                    })
5075            })
5076            .on_action(window.listener_for(&entity, InputBaseState::left))
5077            .on_action(window.listener_for(&entity, InputBaseState::right))
5078            .on_action(window.listener_for(&entity, InputBaseState::select_left))
5079            .on_action(window.listener_for(&entity, InputBaseState::select_right))
5080            .when(self.is_multi_line(), |this| {
5081                this.on_action(window.listener_for(&entity, InputBaseState::up))
5082                    .on_action(window.listener_for(&entity, InputBaseState::down))
5083                    .on_action(window.listener_for(&entity, InputBaseState::select_up))
5084                    .on_action(window.listener_for(&entity, InputBaseState::select_down))
5085                    .on_action(window.listener_for(&entity, InputBaseState::page_up))
5086                    .on_action(window.listener_for(&entity, InputBaseState::page_down))
5087                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
5088                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
5089            })
5090            .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
5091            .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
5092            .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
5093            .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
5094            .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
5095            .on_action(window.listener_for(&entity, InputBaseState::home))
5096            .on_action(window.listener_for(&entity, InputBaseState::end))
5097            .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
5098            .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
5099            .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
5100            .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
5101            .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
5102            .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
5103            .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
5104            .on_action({
5105                let entity = entity.clone();
5106                move |_: &ActivateToken, window, cx| {
5107                    let state = entity.read(cx);
5108                    let activation = state
5109                        .token_spans()
5110                        .iter()
5111                        .find(|span| span.range() == state.selected_range())
5112                        .and_then(|span| {
5113                            state.range_to_bounds(&span.range()).and_then(|bounds| {
5114                                state.token_activation(
5115                                    span.range().start,
5116                                    bounds,
5117                                    wgpui::ClickEvent::Keyboard(wgpui::KeyboardClickEvent {
5118                                        bounds,
5119                                        ..Default::default()
5120                                    }),
5121                                )
5122                            })
5123                        });
5124                    if let Some((listener, event)) = activation {
5125                        listener(&event, window, cx);
5126                    }
5127                }
5128            })
5129            .on_action(window.listener_for(&entity, InputBaseState::copy))
5130            .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
5131            .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
5132            .on_mouse_down(
5133                MouseButton::Left,
5134                window.listener_for(&entity, InputBaseState::on_mouse_down),
5135            )
5136            .on_mouse_down(
5137                MouseButton::Right,
5138                window.listener_for(&entity, InputBaseState::on_mouse_down),
5139            )
5140            .on_mouse_up(
5141                MouseButton::Left,
5142                window.listener_for(&entity, InputBaseState::on_mouse_up),
5143            )
5144            .on_mouse_up(
5145                MouseButton::Right,
5146                window.listener_for(&entity, InputBaseState::on_mouse_up),
5147            )
5148            .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
5149            .on_scroll(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
5150            .when(self.is_multi_line() && !self.disabled, |this| {
5151                this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
5152            })
5153            .when(!self.disabled, |this| {
5154                if self.is_multi_line() && window.modifiers().alt {
5155                    this.cursor_crosshair()
5156                } else {
5157                    this.cursor_text()
5158                }
5159            })
5160            .flex_1()
5161            // A single line fills the frame and sits at its vertical center,
5162            // so the frame needs no layout of its own to hold it. It is never
5163            // shorter than its line, though: this root clips (overflow-x
5164            // hidden clips both axes), and a frame whose padding leaves less
5165            // than a line, like Component's Input, would cut off descenders.
5166            .map(|this| {
5167                if self.is_multi_line() {
5168                    this.h_full()
5169                } else {
5170                    this.min_h_full().flex().items_center()
5171                }
5172            })
5173            .flex_grow_1()
5174            .overflow_x_hidden()
5175            .when(self.is_multi_line(), |this| {
5176                this.pt(self.editor_paddings.top)
5177                    .pr(self.editor_paddings.right)
5178                    .pb(self.editor_paddings.bottom)
5179                    .pl(self.editor_paddings.left)
5180            })
5181            .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
5182            .when(self.shows_scrollbar(), |this| {
5183                this.child(EditorScrollbar::new(entity.clone()))
5184            });
5185
5186        // Actions only one mode handles are registered by that mode, where
5187        // `Self` is concrete enough to name its own entity type.
5188        M::register_actions(element, &entity, window)
5189            .test_support()
5190            .track_focus(&self.focus_handle)
5191    }
5192}
5193
5194#[cfg(test)]
5195mod tests {
5196    use super::*;
5197
5198    #[wgpui::test]
5199    fn accessibility_actions_recheck_live_editability(cx: &mut TestAppContext) {
5200        cx.update(crate::init);
5201        let (state, cx) = cx.add_window_view(|window, cx| {
5202            crate::input::InputState::new(window, cx).default_value("initial")
5203        });
5204        let changes = Rc::new(Cell::new(0));
5205        let observed = changes.clone();
5206        let _subscription = cx.update(|_, cx| {
5207            cx.subscribe(&state, move |_, event: &InputEvent, _| {
5208                if matches!(event, InputEvent::Change) {
5209                    observed.set(observed.get() + 1);
5210                }
5211            })
5212        });
5213        cx.update(|window, cx| {
5214            state.update(cx, |state, cx| {
5215                state.handle_accessibility_set_value(None, window, cx);
5216                state.handle_accessibility_focus(window, cx);
5217                assert!(state.focus_handle.is_focused(window));
5218            });
5219            window.draw(cx).clear();
5220        });
5221        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5222        assert_eq!(changes.get(), 0);
5223
5224        let action = wgpui::accesskit::ActionData::Value("updated🦀".into());
5225        cx.update(|window, cx| {
5226            state.update(cx, |state, cx| {
5227                state.handle_accessibility_set_value(Some(&action), window, cx)
5228            });
5229        });
5230        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5231        assert_eq!(changes.get(), 1);
5232        for disabled in [false, true] {
5233            cx.update(|window, cx| {
5234                window.blur();
5235                state.update(cx, |state, cx| {
5236                    state.set_disabled(disabled, cx);
5237                    state.set_readonly(!disabled, cx);
5238                    state.handle_accessibility_focus(window, cx);
5239                    assert_eq!(state.focus_handle.is_focused(window), !disabled);
5240                    let rejected = wgpui::accesskit::ActionData::Value("rejected".into());
5241                    state.handle_accessibility_set_value(Some(&rejected), window, cx);
5242                });
5243            });
5244            assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5245            assert_eq!(changes.get(), 1);
5246        }
5247        cx.update(|window, cx| {
5248            state.update(cx, |state, cx| {
5249                state.set_disabled(false, cx);
5250                state.set_readonly(false, cx);
5251                state.handle_accessibility_focus(window, cx);
5252            });
5253            window.draw(cx).clear();
5254            window.dispatch_action(Box::new(Undo), cx);
5255        });
5256        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5257        cx.update(|window, cx| {
5258            state.update(cx, |state, cx| {
5259                state.set_masked(true, window, cx);
5260                state.handle_accessibility_set_value(Some(&action), window, cx);
5261            });
5262        });
5263        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5264    }
5265
5266    #[wgpui::test]
5267    fn accessibility_set_value_preserves_exact_editor_text(cx: &mut TestAppContext) {
5268        cx.update(crate::init);
5269        let (editor, cx) = cx.add_window_view(|window, cx| {
5270            crate::input::EditorState::new(window, cx).language("rust")
5271        });
5272        let action = wgpui::accesskit::ActionData::Value("(".into());
5273        cx.update(|window, cx| {
5274            editor.update(cx, |editor, cx| {
5275                editor.handle_accessibility_set_value(Some(&action), window, cx)
5276            });
5277        });
5278        assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "(");
5279    }
5280
5281    #[wgpui::test]
5282    fn revealing_a_password_keeps_text_assistance_disabled(cx: &mut TestAppContext) {
5283        cx.update(crate::init);
5284        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5285            let state = cx.new(|cx| crate::input::InputState::new(window, cx).masked(true));
5286            let hidden = state.read(cx).text_input_configuration();
5287            assert!(!hidden.autocorrect && !hidden.suggestions);
5288            assert_eq!(hidden.autocapitalize, Autocapitalize::None);
5289
5290            // The component's reveal button uses this same state transition.
5291            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5292            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5293            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5294            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5295            wgpui::EmptyView
5296        });
5297    }
5298
5299    #[wgpui::test]
5300    fn text_input_configuration_follows_the_input(cx: &mut TestAppContext) {
5301        use crate::input::{InputState, TextareaState};
5302
5303        cx.update(crate::init);
5304        let mut states = None;
5305        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5306            states = Some((
5307                cx.new(|cx| InputState::new(window, cx)),
5308                cx.new(|cx| InputState::new(window, cx).masked(true)),
5309                cx.new(|cx| TextareaState::new(window, cx)),
5310                cx.new(|cx| {
5311                    InputState::new(window, cx)
5312                        .input_action(TextInputAction::Search)
5313                        .autocorrect(true)
5314                        .autocapitalize(Autocapitalize::Words)
5315                }),
5316            ));
5317            wgpui::EmptyView
5318        });
5319        let (plain, masked, textarea, search) = states.unwrap();
5320
5321        cx.read(|cx| {
5322            assert_eq!(
5323                plain.read(cx).text_input_configuration(),
5324                TextInputConfiguration {
5325                    input_action: TextInputAction::Done,
5326                    ..Default::default()
5327                }
5328            );
5329            assert_eq!(
5330                masked.read(cx).text_input_configuration(),
5331                TextInputConfiguration {
5332                    input_action: TextInputAction::Done,
5333                    ..Default::default()
5334                }
5335            );
5336            assert_eq!(
5337                textarea.read(cx).text_input_configuration(),
5338                TextInputConfiguration {
5339                    input_action: TextInputAction::Enter,
5340                    ..Default::default()
5341                }
5342            );
5343            let search = search.read(cx).text_input_configuration();
5344            assert_eq!(search.input_action, TextInputAction::Search);
5345            assert_eq!(search.autocapitalize, Autocapitalize::Words);
5346            assert!(search.autocorrect);
5347            assert!(search.suggestions);
5348        });
5349    }
5350
5351    #[wgpui::test]
5352    fn test_unicode_completions_use_byte_coordinates_after_edits_and_invocation(
5353        cx: &mut TestAppContext,
5354    ) {
5355        use crate::input::{CompletionProvider, EditorState};
5356        use lsp_types::{CompletionContext, CompletionResponse};
5357        use std::cell::RefCell;
5358        use wgpui::Task;
5359
5360        #[derive(Default)]
5361        struct Provider {
5362            starts: RefCell<Vec<usize>>,
5363            queries: RefCell<Vec<(usize, String)>>,
5364        }
5365
5366        impl CompletionProvider for Provider {
5367            fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
5368                self.starts.borrow_mut().push(offset);
5369                true
5370            }
5371
5372            fn completions(
5373                &self,
5374                _: &Rope,
5375                offset: usize,
5376                trigger: CompletionContext,
5377                _: &mut Window,
5378                _: &mut App,
5379            ) -> Task<anyhow::Result<CompletionResponse>> {
5380                self.queries
5381                    .borrow_mut()
5382                    .push((offset, trigger.trigger_character.unwrap_or_default()));
5383                Task::ready(Ok(CompletionResponse::Array(vec![])))
5384            }
5385        }
5386
5387        cx.update(crate::init);
5388        let mut editor = None;
5389        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5390            editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
5391            wgpui::EmptyView
5392        });
5393        let editor = editor.unwrap();
5394        let provider = Rc::new(Provider::default());
5395        window
5396            .update(cx, |_, window, cx| {
5397                editor.update(cx, |state, cx| {
5398                    state.extras.lsp.completion_provider = Some(provider.clone());
5399                    state
5400                        .extras
5401                        .context_menu_content
5402                        .completion
5403                        .trigger_start_offset = Some(0);
5404                    state.extras.context_menu_content.completion.query = "aa".into();
5405                    state.set_cursor_to(1);
5406                    state.add_cursor_at(0, cx);
5407
5408                    state.replace_text_in_range(None, "中", window, cx);
5409
5410                    assert_eq!(state.value(), "中a中a");
5411                    assert_eq!(provider.starts.borrow().as_slice(), &[4]);
5412                    assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
5413
5414                    let source = "😀.prefix_你好";
5415                    state.set_value(source, window, cx);
5416                    state.set_cursor_to(source.len());
5417                    state.show_completions(window, cx);
5418
5419                    let completion = &state.extras.context_menu_content.completion;
5420                    assert_eq!(completion.query, "prefix_你好");
5421                    assert_eq!(completion.trigger_start_offset, Some("😀.".len()));
5422                    assert_eq!(
5423                        provider.queries.borrow().last(),
5424                        Some(&(source.len(), String::new()))
5425                    );
5426                });
5427            })
5428            .unwrap();
5429    }
5430
5431    #[wgpui::test]
5432    fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
5433        use crate::input::{InlineToken, InlineTokenPresentation};
5434        let width = Rc::new(Cell::new(4000.));
5435        let render_width = width.clone();
5436        let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
5437        view.window_handle
5438            .update(cx, |_, window, cx| {
5439                view.input.update(cx, |state, cx| {
5440                    state
5441                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
5442                        .unwrap();
5443                    state
5444                        .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
5445                        .unwrap();
5446                    state.set_token_presentation(
5447                        InlineTokenPresentation::default()
5448                            .token(move |_, _, _| div().w(px(render_width.get()))),
5449                    );
5450                });
5451            })
5452            .unwrap();
5453        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5454        visual.update(|window, cx| window.draw(cx).clear());
5455        view.input.read_with(&visual, |state, _| {
5456            assert_eq!(state.display_map.wrap_row_count(), 2);
5457            let first = state.range_to_bounds(&(0..2)).unwrap();
5458            let second = state.range_to_bounds(&(2..4)).unwrap();
5459            assert!(second.origin.y > first.origin.y);
5460            assert_eq!(
5461                state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
5462                2
5463            );
5464        });
5465        width.set(100.);
5466        view.input.update(&mut visual, |_, cx| cx.notify());
5467        visual.update(|window, cx| window.draw(cx).clear());
5468        view.input.read_with(&visual, |state, _| {
5469            assert_eq!(state.display_map.wrap_row_count(), 1)
5470        });
5471    }
5472
5473    #[wgpui::test]
5474    fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
5475        use crate::input::{InlineToken, InlineTokenPresentation};
5476        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5477        let target = view.input.clone();
5478        view.window_handle
5479            .update(cx, |_, window, cx| {
5480                view.input.update(cx, |state, cx| {
5481                    state
5482                        .replace_range_with_token(
5483                            7..13,
5484                            InlineToken::new("a", "@alice"),
5485                            window,
5486                            cx,
5487                        )
5488                        .unwrap();
5489                    state.set_token_presentation(
5490                        InlineTokenPresentation::default()
5491                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5492                            .on_token_click(move |_, window, cx| {
5493                                target.update(cx, |state, cx| {
5494                                    state.set_value("activated", window, cx)
5495                                })
5496                            }),
5497                    );
5498                    state.focus(window, cx);
5499                    state.set_selected_range(7..13, cx);
5500                });
5501            })
5502            .unwrap();
5503        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5504        visual.update(|window, cx| window.draw(cx).clear());
5505        visual.update(|window, cx| {
5506            let state = view.input.read(cx);
5507            let bounds = state.range_to_bounds(&(7..13)).unwrap();
5508            assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
5509            let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
5510            let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
5511            assert_eq!((left, right), (7, 13));
5512            window.dispatch_action(Box::new(ActivateToken), cx);
5513        });
5514        visual.run_until_parked();
5515        view.input.read_with(&visual, |state, _| {
5516            assert_eq!(state.value().as_ref(), "activated")
5517        });
5518    }
5519
5520    #[wgpui::test]
5521    fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
5522        use crate::input::InlineToken;
5523        cx.update(crate::init);
5524        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5525        view.window_handle
5526            .update(cx, |_, window, cx| {
5527                view.input.update(cx, |state, cx| {
5528                    state
5529                        .replace_range_with_token(
5530                            7..13,
5531                            InlineToken::new("a", "@alice"),
5532                            window,
5533                            cx,
5534                        )
5535                        .unwrap();
5536                    state.set_selected_range(0..0, cx);
5537                });
5538            })
5539            .unwrap();
5540        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5541        visual.update(|window, cx| window.draw(cx).clear());
5542        let bounds = view
5543            .input
5544            .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
5545        visual.simulate_click(bounds.center(), wgpui::Modifiers::default());
5546        visual.run_until_parked();
5547        view.input.read_with(&visual, |state, _| {
5548            assert_eq!(state.selected_range(), 7..13, "a click selects the token");
5549        });
5550    }
5551
5552    #[wgpui::test]
5553    fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) {
5554        use crate::input::{InlineToken, InlineTokenPresentation};
5555        use wgpui::{Bounds, point, px, size};
5556        cx.update(crate::init);
5557        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5558        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
5559        view.window_handle
5560            .update(cx, |_, window, cx| {
5561                view.input.update(cx, |state, cx| {
5562                    state
5563                        .replace_range_with_token(
5564                            7..13,
5565                            InlineToken::new("a", "@alice"),
5566                            window,
5567                            cx,
5568                        )
5569                        .unwrap();
5570                    state.set_token_presentation(
5571                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5572                    );
5573                    state.set_selected_range(0..0, cx);
5574                });
5575            })
5576            .unwrap();
5577        view.window_handle
5578            .update(cx, |_, _, cx| {
5579                view.input.update(cx, |state, _| {
5580                    let (_, entered) = state
5581                        .token_hover(7, bounds, true, None)
5582                        .expect("hover enters an enabled token");
5583                    assert!(entered.is_hovered());
5584                    assert_eq!(entered.token().id().as_ref(), "a");
5585                    assert_eq!(entered.range(), 7..13);
5586                    assert_eq!(entered.bounds(), bounds);
5587                    let (_, left) = state
5588                        .token_hover(7, bounds, false, None)
5589                        .expect("hover leaves the same token");
5590                    assert!(!left.is_hovered());
5591                    assert_eq!(state.selected_range(), 0..0, "hover never selects");
5592                    assert!(state.token_hover(99, bounds, true, None).is_none());
5593                });
5594            })
5595            .unwrap();
5596
5597        // Disabled tokens suppress hover, matching click; readonly allows it.
5598        view.window_handle
5599            .update(cx, |_, _, cx| {
5600                view.input.update(cx, |state, cx| {
5601                    state.set_disabled(true, cx);
5602                });
5603            })
5604            .unwrap();
5605        view.window_handle
5606            .update(cx, |_, _, cx| {
5607                view.input.update(cx, |state, _| {
5608                    assert!(state.token_hover(7, bounds, true, None).is_none())
5609                })
5610            })
5611            .unwrap();
5612        view.window_handle
5613            .update(cx, |_, _, cx| {
5614                view.input.update(cx, |state, cx| {
5615                    state.set_disabled(false, cx);
5616                    state.set_readonly(true, cx);
5617                });
5618            })
5619            .unwrap();
5620        view.window_handle
5621            .update(cx, |_, _, cx| {
5622                view.input.update(cx, |state, _| {
5623                    assert!(state.token_hover(7, bounds, true, None).is_some())
5624                })
5625            })
5626            .unwrap();
5627
5628        // Without a hover listener there is no hover activation.
5629        view.window_handle
5630            .update(cx, |_, _, cx| {
5631                view.input.update(cx, |state, _| {
5632                    state.set_token_presentation(InlineTokenPresentation::default());
5633                });
5634            })
5635            .unwrap();
5636        view.window_handle
5637            .update(cx, |_, _, cx| {
5638                view.input.update(cx, |state, _| {
5639                    assert!(state.token_hover(7, bounds, true, None).is_none())
5640                })
5641            })
5642            .unwrap();
5643    }
5644
5645    #[wgpui::test]
5646    fn test_inline_token_hover_exit_delivered_when_token_removed(cx: &mut TestAppContext) {
5647        use crate::input::{InlineToken, InlineTokenPresentation};
5648        use std::cell::RefCell;
5649        use std::rc::Rc;
5650        cx.update(crate::init);
5651        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5652        let events: Rc<RefCell<Vec<(SharedString, bool)>>> = Rc::new(RefCell::new(Vec::new()));
5653        let sink = events.clone();
5654        view.window_handle
5655            .update(cx, |_, window, cx| {
5656                view.input.update(cx, |state, cx| {
5657                    state
5658                        .replace_range_with_token(
5659                            7..13,
5660                            InlineToken::new("a", "@alice"),
5661                            window,
5662                            cx,
5663                        )
5664                        .unwrap();
5665                    state.set_token_presentation(
5666                        InlineTokenPresentation::default()
5667                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5668                            .on_token_hover(move |event, _, _| {
5669                                sink.borrow_mut()
5670                                    .push((event.token().id().clone(), event.is_hovered()));
5671                            }),
5672                    );
5673                });
5674            })
5675            .unwrap();
5676        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5677        visual.update(|window, cx| window.draw(cx).clear());
5678        let known_bounds = view.input.read_with(&visual, |state, _| {
5679            state
5680                .token_bounds
5681                .get(&7)
5682                .copied()
5683                .expect("placed token bounds")
5684        });
5685        visual.simulate_mouse_move(known_bounds.center(), None, wgpui::Modifiers::default());
5686        visual.run_until_parked();
5687        visual.update(|window, cx| window.draw(cx).clear());
5688        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
5689
5690        // Remove the token while the pointer is still over its stale row: the
5691        // exit must fire even though the token element that owns the hover
5692        // mask is gone.
5693        view.window_handle
5694            .update(cx, |_, window, cx| {
5695                view.input
5696                    .update(cx, |state, cx| state.set_value("no tokens", window, cx));
5697            })
5698            .unwrap();
5699        visual.run_until_parked();
5700        visual.update(|window, cx| window.draw(cx).clear());
5701        assert_eq!(
5702            events.borrow().as_slice(),
5703            &[("a".into(), true), ("a".into(), false)]
5704        );
5705    }
5706
5707    #[wgpui::test]
5708    fn test_inline_token_hover_bounds_stay_single_row_at_wrap_boundary(cx: &mut TestAppContext) {
5709        use crate::input::{InlineToken, InlineTokenPresentation};
5710        cx.update(crate::init);
5711        let view = InputView::build_textarea(cx, |state| {
5712            state
5713                .rows(4)
5714                .default_value("aaaa bbbb cccc dddd @alice eeee ffff")
5715        });
5716        view.window_handle
5717            .update(cx, |_, window, cx| {
5718                view.input.update(cx, |state, cx| {
5719                    state
5720                        .replace_range_with_token(
5721                            20..26,
5722                            InlineToken::new("a", "@alice"),
5723                            window,
5724                            cx,
5725                        )
5726                        .unwrap();
5727                    state.set_token_presentation(
5728                        InlineTokenPresentation::default()
5729                            .token(|_, _, _| div().w(px(60.)).h(px(20.))),
5730                    );
5731                });
5732            })
5733            .unwrap();
5734        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5735        visual.update(|window, cx| window.draw(cx).clear());
5736        let (placed, ranged, line_height) = view.input.read_with(&visual, |state, _| {
5737            (
5738                state
5739                    .token_bounds
5740                    .get(&20)
5741                    .copied()
5742                    .expect("placed token bounds"),
5743                state.range_to_bounds(&(20..26)),
5744                state.last_layout.as_ref().unwrap().line_height,
5745            )
5746        });
5747        // The laid-out element always occupies exactly one row of height, even
5748        // when the range-extent path resolves the same end boundary onto the
5749        // next visual row at a soft-wrap edge.
5750        assert!(placed.size.height <= line_height + px(1.), "{placed:?}");
5751        assert!(
5752            placed.size.width <= px(61.) && placed.size.width > px(0.),
5753            "{placed:?}"
5754        );
5755        if let Some(ranged) = ranged {
5756            assert!(
5757                ranged.size.height >= placed.size.height - px(1.),
5758                "{ranged:?} vs {placed:?}"
5759            );
5760        }
5761    }
5762
5763    #[wgpui::test]
5764    fn test_inline_token_hover_same_offset_replacement_exits_predecessor(cx: &mut TestAppContext) {
5765        use crate::input::{InlineToken, InlineTokenPresentation};
5766        use std::{cell::RefCell, rc::Rc};
5767        cx.update(crate::init);
5768        let view = InputView::build(cx, |state| state.default_value("@alice!"));
5769        let events = Rc::new(RefCell::new(Vec::new()));
5770        let sink = events.clone();
5771        view.window_handle
5772            .update(cx, |_, window, cx| {
5773                view.input.update(cx, |state, cx| {
5774                    state
5775                        .replace_range_with_token(0..6, InlineToken::new("a", "@alice"), window, cx)
5776                        .unwrap();
5777                    state.set_token_presentation(
5778                        InlineTokenPresentation::default()
5779                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5780                            .on_token_hover(move |event, _, _| {
5781                                sink.borrow_mut()
5782                                    .push((event.token().id().clone(), event.is_hovered()));
5783                            }),
5784                    );
5785                });
5786            })
5787            .unwrap();
5788        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5789        visual.update(|window, cx| window.draw(cx).clear());
5790        let bounds = view
5791            .input
5792            .read_with(&visual, |state, _| state.token_bounds[&0]);
5793        visual.simulate_mouse_move(bounds.center(), None, wgpui::Modifiers::default());
5794        visual.run_until_parked();
5795        visual.update(|window, cx| window.draw(cx).clear());
5796        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
5797
5798        view.window_handle
5799            .update(cx, |_, window, cx| {
5800                view.input.update(cx, |state, cx| {
5801                    state
5802                        .replace_range_with_token(0..6, InlineToken::new("b", "@alice"), window, cx)
5803                        .unwrap();
5804                });
5805            })
5806            .unwrap();
5807        visual.run_until_parked();
5808        visual.update(|window, cx| window.draw(cx).clear());
5809        visual.simulate_mouse_move(
5810            bounds.center() + wgpui::point(px(1.), px(0.)),
5811            None,
5812            wgpui::Modifiers::default(),
5813        );
5814        visual.run_until_parked();
5815        visual.update(|window, cx| window.draw(cx).clear());
5816        assert_eq!(
5817            events.borrow().as_slice(),
5818            &[("a".into(), true), ("a".into(), false), ("b".into(), true)]
5819        );
5820        // Disabling keeps the token mounted; re-enabling must reset GPUI's
5821        // retained hover state even with a stationary pointer.
5822        view.input
5823            .update(&mut visual, |state, cx| state.set_disabled(true, cx));
5824        visual.update(|window, cx| window.draw(cx).clear());
5825        visual.run_until_parked();
5826        assert_eq!(events.borrow().last(), Some(&("b".into(), false)));
5827        view.input
5828            .update(&mut visual, |state, cx| state.set_disabled(false, cx));
5829        visual.update(|window, cx| window.draw(cx).clear());
5830        visual.run_until_parked();
5831        visual.simulate_mouse_move(bounds.center(), None, wgpui::Modifiers::default());
5832        visual.run_until_parked();
5833        assert_eq!(
5834            events.borrow().as_slice(),
5835            &[
5836                ("a".into(), true),
5837                ("a".into(), false),
5838                ("b".into(), true),
5839                ("b".into(), false),
5840                ("b".into(), true)
5841            ]
5842        );
5843        visual.simulate_mouse_move(
5844            bounds.bottom_right() + wgpui::point(px(10.), px(10.)),
5845            None,
5846            wgpui::Modifiers::default(),
5847        );
5848        visual.run_until_parked();
5849        assert_eq!(
5850            events.borrow().as_slice(),
5851            &[
5852                ("a".into(), true),
5853                ("a".into(), false),
5854                ("b".into(), true),
5855                ("b".into(), false),
5856                ("b".into(), true),
5857                ("b".into(), false)
5858            ]
5859        );
5860    }
5861
5862    #[wgpui::test]
5863    fn test_inline_token_hover_older_exit_keeps_newer_snapshot(cx: &mut TestAppContext) {
5864        use crate::input::{InlineToken, InlineTokenPresentation};
5865        use wgpui::{Bounds, point, px, size};
5866        cx.update(crate::init);
5867        let view = InputView::build(cx, |state| state.default_value("@a @b"));
5868        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
5869        view.window_handle
5870            .update(cx, |_, window, cx| {
5871                view.input.update(cx, |state, cx| {
5872                    state
5873                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
5874                        .unwrap();
5875                    state
5876                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
5877                        .unwrap();
5878                    state.set_token_presentation(
5879                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5880                    );
5881                    // The pointer moves A -> B; GPUI dispatches B's enter
5882                    // before A's exit.
5883                    state
5884                        .token_hover(0, bounds, true, None)
5885                        .expect("hover enters A");
5886                    state
5887                        .token_hover(3, bounds, true, None)
5888                        .expect("hover enters B");
5889                    let (_, exit_a) = state.token_hover(0, bounds, false, None).expect("A exits");
5890                    assert!(!exit_a.is_hovered());
5891                    // B's snapshot must survive A's late exit.
5892                    assert_eq!(
5893                        state
5894                            .hovered_token
5895                            .as_ref()
5896                            .expect("B still hovered")
5897                            .span
5898                            .token()
5899                            .id()
5900                            .as_ref(),
5901                        "b"
5902                    );
5903                    // Removing B afterwards still produces B's reconciled exit.
5904                    state.set_value("no tokens", window, cx);
5905                    state.token_bounds.clear();
5906                    let (listener, exit_b) = state.reconcile_token_hover().expect("B must exit");
5907                    assert!(!exit_b.is_hovered());
5908                    assert_eq!(exit_b.token().id().as_ref(), "b");
5909                    drop(listener);
5910                });
5911            })
5912            .unwrap();
5913    }
5914
5915    #[wgpui::test]
5916    fn test_inline_token_hover_late_exit_matches_replaced_token(cx: &mut TestAppContext) {
5917        use crate::input::{InlineToken, InlineTokenPresentation};
5918        cx.update(crate::init);
5919        let view = InputView::build(cx, |state| state.default_value("@a"));
5920        view.window_handle
5921            .update(cx, |_, window, cx| {
5922                view.input.update(cx, |state, cx| {
5923                    let a = InlineToken::new("a", "@a");
5924                    let b = InlineToken::new("b", "@a");
5925                    state
5926                        .replace_range_with_token(0..2, a.clone(), window, cx)
5927                        .unwrap();
5928                    state.set_token_presentation(
5929                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5930                    );
5931                    let bounds = wgpui::Bounds::default();
5932                    state.token_hover(0, bounds, true, Some(&a)).unwrap();
5933                    state
5934                        .replace_range_with_token(0..2, b.clone(), window, cx)
5935                        .unwrap();
5936                    state.token_hover(0, bounds, true, Some(&b)).unwrap();
5937                    let (_, exit_a) = state.token_hover(0, bounds, false, Some(&a)).unwrap();
5938                    assert_eq!(exit_a.token().id().as_ref(), "a");
5939                    assert_eq!(state.hovered_token.as_ref().unwrap().span.token(), &b);
5940                    let (_, exit_b) = state.token_hover(0, bounds, false, Some(&b)).unwrap();
5941                    assert_eq!(exit_b.token().id().as_ref(), "b");
5942                    assert!(state.pending_token_hover_exits.is_empty());
5943                });
5944            })
5945            .unwrap();
5946    }
5947
5948    #[wgpui::test]
5949    fn test_inline_token_hover_exit_keeps_entry_utf16_after_edit(cx: &mut TestAppContext) {
5950        use crate::input::{InlineToken, InlineTokenPresentation};
5951        use wgpui::EntityInputHandler as _;
5952        cx.update(crate::init);
5953        let view = InputView::build(cx, |state| state.default_value("🙂 @a"));
5954        view.window_handle
5955            .update(cx, |_, window, cx| {
5956                view.input.update(cx, |state, cx| {
5957                    state
5958                        .replace_range_with_token(5..7, InlineToken::new("a", "@a"), window, cx)
5959                        .unwrap();
5960                    state.set_token_presentation(
5961                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5962                    );
5963                    let bounds = wgpui::Bounds::default();
5964                    let (_, enter) = state.token_hover(5, bounds, true, None).unwrap();
5965                    assert_eq!(enter.range_utf16(), (3, 5));
5966                    state.replace_text_in_range(Some(0..2), "abcd", window, cx);
5967                    assert_eq!(state.token_spans()[0].range(), 5..7);
5968                    let (_, exit) = state.token_hover(5, bounds, false, None).unwrap();
5969                    assert_eq!(exit.range_utf16(), (3, 5));
5970                });
5971            })
5972            .unwrap();
5973    }
5974
5975    #[wgpui::test]
5976    fn test_inline_token_hover_callback_edit_preserves_both_exits(cx: &mut TestAppContext) {
5977        use crate::input::{InlineToken, InlineTokenPresentation};
5978        cx.update(crate::init);
5979        let view = InputView::build(cx, |state| state.default_value("@a @b"));
5980        view.window_handle
5981            .update(cx, |_, window, cx| {
5982                view.input.update(cx, |state, cx| {
5983                    state
5984                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
5985                        .unwrap();
5986                    state
5987                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
5988                        .unwrap();
5989                    state.set_token_presentation(
5990                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5991                    );
5992                    let bounds = wgpui::Bounds::default();
5993                    state.token_hover(0, bounds, true, None).unwrap();
5994                    state.token_hover(3, bounds, true, None).unwrap();
5995                    // Model an edit in B's enter callback before A's queued exit.
5996                    state.set_value("gone", window, cx);
5997                    let (_, exit_a) = state.token_hover(0, bounds, false, None).unwrap();
5998                    assert_eq!(exit_a.token().id().as_ref(), "a");
5999                    let (_, exit_b) = state.reconcile_token_hover().unwrap();
6000                    assert_eq!(exit_b.token().id().as_ref(), "b");
6001                    assert!(state.token_hover(0, bounds, false, None).is_none());
6002                    assert!(state.reconcile_token_hover().is_none());
6003                });
6004            })
6005            .unwrap();
6006    }
6007
6008    #[wgpui::test]
6009    fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
6010        let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
6011        view.window_handle
6012            .update(cx, |_, window, cx| {
6013                view.input.update(cx, |state, cx| {
6014                    let token =
6015                        crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
6016                    state
6017                        .replace_range_with_token(4..10, token.clone(), window, cx)
6018                        .unwrap();
6019                    assert_eq!(state.value().as_ref(), "问 @alice!");
6020                    assert_eq!(state.tokens()[0].range(), 4..10);
6021                    assert_eq!(state.next_end_of_word_at(4), 10);
6022                    assert_eq!(state.previous_start_of_word_at(10), 4);
6023                    state.undo(&Undo, window, cx);
6024                    assert!(
6025                        state.tokens().is_empty(),
6026                        "identity-only association is undoable"
6027                    );
6028                    assert_eq!(state.value().as_ref(), "问 @alice!");
6029                    state.redo(&Redo, window, cx);
6030                    assert_eq!(state.tokens()[0].token(), &token);
6031                    state.set_selected_range(6..7, cx);
6032                    assert_eq!(state.selected_range(), 4..10);
6033                    state.replace("", window, cx);
6034                    assert_eq!(state.value().as_ref(), "问 !");
6035                    assert!(state.tokens().is_empty());
6036                    state.undo(&Undo, window, cx);
6037                    assert_eq!(state.tokens()[0].token(), &token);
6038                    state.set_selected_range(0..0, cx);
6039                    state.replace("🙂", window, cx);
6040                    assert_eq!(state.tokens()[0].range(), 8..14);
6041                    state.undo(&Undo, window, cx);
6042                    assert_eq!(state.tokens()[0].range(), 4..10);
6043                    let before = state.content();
6044                    state
6045                        .replace_range_with_token(0..0, token.clone(), window, cx)
6046                        .expect("the same reference may occur twice");
6047                    assert_eq!(state.value().as_ref(), "@alice问 @alice!");
6048                    assert_eq!(state.tokens().len(), 2);
6049                    assert_eq!(state.tokens()[1].token(), &token);
6050                    state.undo(&Undo, window, cx);
6051                    assert_eq!(state.content(), before);
6052                    state.set_value(before.text().clone(), window, cx);
6053                    assert!(state.tokens().is_empty());
6054                    assert!(!state.undo_manager.has_undos());
6055                });
6056            })
6057            .unwrap();
6058    }
6059
6060    #[wgpui::test]
6061    fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
6062        use crate::input::{InlineToken, InlineTokenError, InputContent};
6063        let view = InputView::build_textarea(cx, |state| state);
6064        view.window_handle
6065            .update(cx, |_, window, cx| {
6066                view.input.update(cx, |state, cx| {
6067                    let content = InputContent::new("@a@b\n后面")
6068                        .with_token(0..2, InlineToken::new("a", "@a"))
6069                        .unwrap()
6070                        .with_token(2..4, InlineToken::new("b", "@b"))
6071                        .unwrap();
6072                    state.set_value(content.clone(), window, cx);
6073                    state.set_selected_range(2..2, cx);
6074                    assert_eq!(state.previous_boundary(2), 0);
6075                    assert_eq!(state.next_boundary(2), 4);
6076                    state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
6077                    assert_eq!(state.value().as_ref(), "中@b\n后面");
6078                    assert_eq!(state.tokens().len(), 1);
6079                    assert_eq!(
6080                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6081                        Err(InlineTokenError::CompositionActive)
6082                    );
6083                    state.clear_marked_text(window, cx);
6084                    assert_eq!(state.value().as_ref(), "@b\n后面");
6085                    assert_eq!(state.tokens().len(), 1);
6086                    assert_eq!(state.ime_marked_range, Some((0..0).into()));
6087                    assert_eq!(
6088                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6089                        Err(InlineTokenError::CompositionActive)
6090                    );
6091                    state.replace_text_in_range(None, "中文", window, cx);
6092                    state.undo(&Undo, window, cx);
6093                    assert_eq!(state.content(), content);
6094                    state.redo(&Redo, window, cx);
6095                    assert_eq!(state.value().as_ref(), "中文@b\n后面");
6096                    state.undo(&Undo, window, cx);
6097                    state.replace_all("plain", window, cx);
6098                    assert!(state.tokens().is_empty());
6099                    state.undo(&Undo, window, cx);
6100                    assert_eq!(state.content(), content);
6101                });
6102            })
6103            .unwrap();
6104        let view = InputView::build(cx, |state| state);
6105        view.window_handle
6106            .update(cx, |_, window, cx| {
6107                view.input.update(cx, |state, cx| {
6108                    assert_eq!(
6109                        InputContent::new("a\u{301}")
6110                            .with_token(0..1, InlineToken::new("bad", "a"))
6111                            .err(),
6112                        Some(InlineTokenError::InvalidBoundary)
6113                    );
6114                    assert_eq!(
6115                        InputContent::new("@a@a")
6116                            .with_token(0..2, InlineToken::new("a", "@a"))
6117                            .unwrap()
6118                            .with_token(1..3, InlineToken::new("x", "a@"))
6119                            .err(),
6120                        Some(InlineTokenError::OverlappingTokens)
6121                    );
6122                    state
6123                        .replace_with_token(InlineToken::new("a", "@a"), window, cx)
6124                        .unwrap();
6125                    let before = state.content();
6126                    state.set_masked(true, window, cx);
6127                    assert!(!state.tokens_visible());
6128                    assert_eq!(
6129                        state.replace_with_token(InlineToken::new("b", "b"), window, cx),
6130                        Err(InlineTokenError::UnsupportedMode)
6131                    );
6132                    assert_eq!(state.content(), before);
6133                    state.undo(&Undo, window, cx);
6134                    assert!(state.tokens().is_empty());
6135                    state.redo(&Redo, window, cx);
6136                    assert_eq!(state.content(), before);
6137                    assert!(!state.tokens_visible());
6138                });
6139            })
6140            .unwrap();
6141    }
6142
6143    use crate::theme::Theme;
6144    use wgpui::{TestAppContext, VisualTestContext, size};
6145
6146    use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TabSize, TextareaMode};
6147
6148    fn set_test_syntax_provider(
6149        provider: Rc<dyn crate::input::SyntaxContextProvider>,
6150        cx: &mut App,
6151    ) {
6152        struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
6153        impl crate::input::LanguageProvider for TestLanguages {
6154            fn syntax_context_provider(
6155                &self,
6156                _: &str,
6157            ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
6158                Some(self.0.clone())
6159            }
6160        }
6161        crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
6162    }
6163
6164    struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
6165
6166    impl<M: InputModeKind> Render for TestRoot<M> {
6167        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6168            div().size_full().child(self.0.clone())
6169        }
6170    }
6171
6172    struct InputView<M: InputModeKind> {
6173        input: Entity<InputBaseState<M>>,
6174        window_handle: wgpui::WindowHandle<TestRoot<M>>,
6175    }
6176
6177    /// Helper to open a state of one mode in a window for testing.
6178    impl<M: InputModeKind> InputView<M> {
6179        fn build_with(
6180            cx: &mut TestAppContext,
6181            make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
6182            + 'static,
6183        ) -> Self {
6184            let mut input: Option<Entity<InputBaseState<M>>> = None;
6185
6186            let window = cx.update(|cx| {
6187                cx.open_window(Default::default(), |window, cx| {
6188                    // Set up the theme first
6189                    cx.set_global(Theme::default());
6190                    // Initialize input keybindings
6191                    super::super::init(cx);
6192
6193                    input = Some(cx.new(|cx| make(window, cx)));
6194
6195                    cx.new(|_| TestRoot(input.clone().unwrap()))
6196                })
6197                .unwrap()
6198            });
6199
6200            Self {
6201                input: input.clone().unwrap(),
6202                window_handle: window,
6203            }
6204        }
6205    }
6206
6207    impl InputView<EditorMode> {
6208        /// An editor state, for the tests that exercise code-editor behavior.
6209        fn new(cx: &mut TestAppContext) -> Self {
6210            Self::build_editor(cx, |state| state)
6211        }
6212
6213        fn build_editor(
6214            cx: &mut TestAppContext,
6215            f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
6216        ) -> Self {
6217            Self::build_with(cx, move |window, cx| {
6218                f(crate::input::EditorState::new(window, cx).language("sql"))
6219            })
6220        }
6221    }
6222
6223    impl InputView<TextareaMode> {
6224        fn build_textarea(
6225            cx: &mut TestAppContext,
6226            f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
6227        ) -> Self {
6228            Self::build_with(cx, move |window, cx| {
6229                f(crate::input::TextareaState::new(window, cx))
6230            })
6231        }
6232    }
6233
6234    impl InputView<InputMode> {
6235        /// A single-line state, the default these tests were written against.
6236        fn build(
6237            cx: &mut TestAppContext,
6238            f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
6239        ) -> Self {
6240            Self::build_with(cx, move |window, cx| {
6241                f(crate::input::InputState::new(window, cx))
6242            })
6243        }
6244    }
6245
6246    /// Sends one trackpad packet straight to the input.
6247    fn swipe<M: InputModeKind>(
6248        view: &InputView<M>,
6249        cx: &mut VisualTestContext,
6250        dy: f32,
6251        phase: wgpui::TouchPhase,
6252    ) {
6253        cx.update(|window, cx| {
6254            view.input.update(cx, |state, cx| {
6255                state.on_scroll_wheel(
6256                    &ScrollEvent {
6257                        delta: wgpui::ScrollDelta::Pixels(point(px(0.), px(dy))),
6258                        touch_phase: phase,
6259                        ..Default::default()
6260                    },
6261                    window,
6262                    cx,
6263                )
6264            })
6265        });
6266    }
6267
6268    fn long_text() -> String {
6269        (0..60)
6270            .map(|n| format!("line {n}"))
6271            .collect::<Vec<_>>()
6272            .join("\n")
6273    }
6274
6275    #[wgpui::test]
6276    fn test_scroll_bounce_stretches_past_the_end_and_springs_back(cx: &mut TestAppContext) {
6277        use wgpui::TouchPhase::{Ended, Moved, Started};
6278
6279        let view = InputView::build_textarea(cx, |state| {
6280            state.scroll_bounce(true).default_value(long_text())
6281        });
6282        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6283        cx.update(|window, cx| window.draw(cx).clear());
6284        let drawn_at = |cx: &mut VisualTestContext| {
6285            view.input
6286                .read_with(cx, |state, _| state.last_bounds.unwrap().origin.y)
6287        };
6288
6289        swipe(&view, &mut cx, -20., Started);
6290        swipe(&view, &mut cx, -100_000., Moved);
6291        let (end, stretch) = view.input.read_with(&cx, |state, _| {
6292            (state.scroll_handle.offset().y, state.overscroll.offset())
6293        });
6294        assert!(end < px(0.), "the text scrolled to its end");
6295        assert!(stretch < 0., "the rest stretched the edge: {stretch}");
6296        cx.update(|window, cx| window.draw(cx).clear());
6297        let stretched_at = drawn_at(&mut cx);
6298
6299        swipe(&view, &mut cx, 0., Ended);
6300        for _ in 0..120 {
6301            cx.executor()
6302                .advance_clock(std::time::Duration::from_millis(16));
6303            cx.update(|window, cx| window.draw(cx).clear());
6304        }
6305        view.input.read_with(&cx, |state, _| {
6306            assert_eq!(state.overscroll.offset(), 0., "the edge sprang back");
6307            assert_eq!(
6308                state.scroll_handle.offset().y,
6309                end,
6310                "scrolling stayed exact"
6311            );
6312        });
6313        let moved = (stretched_at - drawn_at(&mut cx)).as_f32();
6314        assert!(
6315            (moved - stretch).abs() < 0.001,
6316            "the stretch only moved where the text was drawn: {moved} vs {stretch}"
6317        );
6318    }
6319
6320    /// Swipes far past the end of the text and returns where the text
6321    /// scrolled to and how far its edge stretched.
6322    fn swipe_past_the_end(
6323        view: &InputView<TextareaMode>,
6324        cx: &mut VisualTestContext,
6325    ) -> (Pixels, f32) {
6326        use wgpui::TouchPhase::{Moved, Started};
6327
6328        cx.update(|window, cx| window.draw(cx).clear());
6329        swipe(view, cx, -20., Started);
6330        swipe(view, cx, -100_000., Moved);
6331        view.input.read_with(cx, |state, _| {
6332            (state.scroll_handle.offset().y, state.overscroll.offset())
6333        })
6334    }
6335
6336    #[wgpui::test]
6337    fn test_scroll_bounce_stays_put_under_reduced_motion(cx: &mut TestAppContext) {
6338        cx.update(|cx| cx.set_reduce_motion(true));
6339        let view = InputView::build_textarea(cx, |state| {
6340            state.scroll_bounce(true).default_value(long_text())
6341        });
6342        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6343        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6344        assert!(end < px(0.), "the text still scrolls");
6345        assert_eq!(stretch, 0., "the edge does not stretch");
6346    }
6347
6348    #[wgpui::test]
6349    fn test_scroll_bounce_follows_the_platform_by_default(cx: &mut TestAppContext) {
6350        let view = InputView::build_textarea(cx, |state| state.default_value(long_text()));
6351        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6352        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6353        assert!(end < px(0.), "the text scrolls");
6354        assert_eq!(
6355            stretch != 0.,
6356            crate::ScrollBounce::enabled_by_default(),
6357            "the edge stretches where the platform's scroll views do"
6358        );
6359    }
6360
6361    #[wgpui::test]
6362    fn test_scroll_bounce_leaves_text_that_fits(cx: &mut TestAppContext) {
6363        let view = InputView::build_textarea(cx, |state| {
6364            state.scroll_bounce(true).default_value("one line")
6365        });
6366        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6367        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6368        assert_eq!((end, stretch), (px(0.), 0.));
6369    }
6370
6371    #[wgpui::test]
6372    fn test_scroll_bounce_resets_when_replacement_text_fits(cx: &mut TestAppContext) {
6373        let view = InputView::build_textarea(cx, |state| {
6374            state.scroll_bounce(true).default_value(long_text())
6375        });
6376        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6377        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6378        assert!(stretch < 0.);
6379        cx.update(|window, cx| {
6380            view.input
6381                .update(cx, |state, cx| state.set_value("short", window, cx));
6382            window.draw(cx).clear();
6383        });
6384        swipe(&view, &mut cx, 0., wgpui::TouchPhase::Ended);
6385        view.input.read_with(&cx, |state, _| {
6386            assert_eq!(state.overscroll.offset(), 0.);
6387            assert_eq!(state.scroll_handle.offset().y, px(0.));
6388        });
6389    }
6390
6391    #[wgpui::test]
6392    fn test_scroll_bounce_releases_when_the_end_packet_is_horizontal(cx: &mut TestAppContext) {
6393        let view = InputView::build_textarea(cx, |state| {
6394            state.scroll_bounce(true).default_value(long_text())
6395        });
6396        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6397        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6398        assert!(stretch < 0.);
6399        cx.update(|window, cx| {
6400            view.input.update(cx, |state, cx| {
6401                state.on_scroll_wheel(
6402                    &ScrollEvent {
6403                        delta: wgpui::ScrollDelta::Pixels(point(px(1.), px(0.))),
6404                        touch_phase: wgpui::TouchPhase::Ended,
6405                        ..Default::default()
6406                    },
6407                    window,
6408                    cx,
6409                );
6410            });
6411        });
6412        for _ in 0..120 {
6413            cx.executor()
6414                .advance_clock(std::time::Duration::from_millis(16));
6415            cx.update(|window, cx| window.draw(cx).clear());
6416        }
6417        assert_eq!(
6418            view.input
6419                .read_with(&cx, |state, _| state.overscroll.offset()),
6420            0.
6421        );
6422    }
6423
6424    #[wgpui::test]
6425    fn test_scroll_bounce_ordinary_mouse_wheel_does_not_stretch(cx: &mut TestAppContext) {
6426        let view = InputView::build_textarea(cx, |state| {
6427            state.scroll_bounce(true).default_value(long_text())
6428        });
6429        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6430        cx.update(|window, cx| {
6431            window.draw(cx).clear();
6432            view.input.update(cx, |state, cx| {
6433                state.on_scroll_wheel(
6434                    &ScrollEvent {
6435                        delta: wgpui::ScrollDelta::Lines(point(0., -100_000.)),
6436                        touch_phase: wgpui::TouchPhase::Moved,
6437                        ..Default::default()
6438                    },
6439                    window,
6440                    cx,
6441                );
6442                assert!(state.scroll_handle.offset().y < px(0.));
6443                assert_eq!(state.overscroll.offset(), 0.);
6444            });
6445        });
6446    }
6447
6448    #[wgpui::test]
6449    fn test_scroll_bounce_new_wheel_input_interrupts_the_return(cx: &mut TestAppContext) {
6450        let view = InputView::build_textarea(cx, |state| {
6451            state.scroll_bounce(true).default_value(long_text())
6452        });
6453        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6454        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6455        assert!(stretch < 0.);
6456        swipe(&view, &mut cx, 0., wgpui::TouchPhase::Ended);
6457        cx.executor()
6458            .advance_clock(std::time::Duration::from_millis(16));
6459        cx.update(|window, cx| {
6460            window.draw(cx).clear();
6461            view.input.update(cx, |state, cx| {
6462                state.on_scroll_wheel(
6463                    &ScrollEvent {
6464                        delta: wgpui::ScrollDelta::Lines(point(0., 2.)),
6465                        touch_phase: wgpui::TouchPhase::Moved,
6466                        ..Default::default()
6467                    },
6468                    window,
6469                    cx,
6470                );
6471                assert!(state.scroll_handle.offset().y > end);
6472                assert_eq!(state.overscroll.offset(), 0.);
6473            });
6474        });
6475    }
6476
6477    #[wgpui::test]
6478    fn test_turning_scroll_bounce_off_drops_the_stretch(cx: &mut TestAppContext) {
6479        let view = InputView::build_textarea(cx, |state| {
6480            state.scroll_bounce(true).default_value(long_text())
6481        });
6482        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6483        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6484        assert!(stretch < 0., "the edge stretched: {stretch}");
6485        view.input
6486            .update(&mut cx, |state, cx| state.set_scroll_bounce(false, cx));
6487        assert_eq!(
6488            view.input
6489                .read_with(&cx, |state, _| state.overscroll.offset()),
6490            0.
6491        );
6492    }
6493
6494    /// The frame is laid out by the application, which should not have to
6495    /// center a single line inside it.
6496    #[wgpui::test]
6497    fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
6498        struct Frame(Entity<InputBaseState<InputMode>>);
6499        impl Render for Frame {
6500            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6501                crate::input::InputBase::new("frame")
6502                    .h(px(60.))
6503                    .child(crate::input::Input::new(&self.0))
6504            }
6505        }
6506
6507        cx.update(crate::init);
6508        let mut input = None;
6509        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6510            let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
6511            input = Some(state.clone());
6512            Frame(state)
6513        });
6514        let input = input.unwrap();
6515        let mut cx = VisualTestContext::from_window(window.into(), cx);
6516        cx.update(|window, cx| window.draw(cx).clear());
6517
6518        input.read_with(&cx, |state, _| {
6519            let line = state.input_bounds;
6520            assert_eq!(line.center().y, px(30.), "line {line:?}");
6521        });
6522    }
6523
6524    #[wgpui::test]
6525    fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
6526        use std::{cell::Cell, rc::Rc};
6527
6528        cx.update(crate::init);
6529        let mut input = None;
6530        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6531            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
6532            wgpui::EmptyView
6533        });
6534        let input = input.unwrap();
6535        input.update(cx, |state, cx| {
6536            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
6537            state.scroll_size = size(px(100.), px(20.));
6538            state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
6539        });
6540        let notifications = Rc::new(Cell::new(0));
6541        let count = notifications.clone();
6542        let _subscription =
6543            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
6544
6545        window
6546            .update(cx, |_, window, cx| {
6547                input.update(cx, |state, cx| {
6548                    state.on_scroll_wheel(
6549                        &ScrollEvent {
6550                            delta: wgpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
6551                            ..Default::default()
6552                        },
6553                        window,
6554                        cx,
6555                    );
6556                    assert_eq!(state.scroll_handle.offset(), Point::default());
6557                    assert!(state.diagnostic_popover().is_none());
6558                });
6559            })
6560            .unwrap();
6561        assert_eq!(
6562            notifications.get(),
6563            1,
6564            "clearing a diagnostic must notify even when scrolling is clamped"
6565        );
6566        window
6567            .update(cx, |_, window, cx| {
6568                input.update(cx, |state, cx| {
6569                    state.on_scroll_wheel(
6570                        &ScrollEvent {
6571                            delta: wgpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
6572                            ..Default::default()
6573                        },
6574                        window,
6575                        cx,
6576                    );
6577                });
6578            })
6579            .unwrap();
6580        assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
6581    }
6582
6583    #[wgpui::test]
6584    fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
6585        use std::{cell::Cell, rc::Rc};
6586        struct Panel {
6587            input: Entity<crate::input::EditorState>,
6588            observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
6589        }
6590        impl Render for Panel {
6591            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
6592                self.observed.set(self.input.read(cx).cursor_layout());
6593                div().size_full().child(self.input.clone())
6594            }
6595        }
6596        struct Root(Entity<Panel>);
6597        impl Render for Root {
6598            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6599                div().size_full().child(
6600                    self.0
6601                        .clone()
6602                        .cached(wgpui::StyleRefinement::default().size_full()),
6603                )
6604            }
6605        }
6606        cx.update(crate::init);
6607        let observed = Rc::new(Cell::new(None));
6608        let mut input = None;
6609        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6610            let state = cx.new(|cx| {
6611                let mut state = crate::input::EditorState::new(window, cx);
6612                state.set_value("abcdefgh", window, cx);
6613                state
6614            });
6615            input = Some(state.clone());
6616            Root(cx.new(|_| Panel {
6617                input: state,
6618                observed: observed.clone(),
6619            }))
6620        });
6621        cx.run_until_parked();
6622        let input = input.unwrap();
6623        let before = input.read_with(cx, |state, _| state.cursor_layout());
6624        // The caret geometry only exists once the input has painted, and a
6625        // notify sent from inside a draw marks the view dirty without asking
6626        // for another frame, so the consumer reads the geometry on the next
6627        // invalidation rather than during the paint that produced it.
6628        input.update(cx, |_, cx| cx.notify());
6629        cx.run_until_parked();
6630        assert_eq!(observed.get(), before);
6631        window
6632            .update(cx, |_, _, cx| {
6633                input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
6634            })
6635            .unwrap();
6636        cx.run_until_parked();
6637        window.update(cx, |_, _, cx| cx.notify()).unwrap();
6638        let after = input.read_with(cx, |state, _| state.cursor_layout());
6639        assert_ne!(after, before, "the caret must actually move");
6640        assert_eq!(
6641            observed.get(),
6642            after,
6643            "render consumers must receive the newly painted caret geometry"
6644        );
6645    }
6646
6647    #[wgpui::test]
6648    fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
6649        use std::{cell::Cell, rc::Rc};
6650
6651        cx.update(crate::init);
6652        let mut input = None;
6653        let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6654            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
6655            wgpui::EmptyView
6656        });
6657        let input = input.unwrap();
6658        let notifications = Rc::new(Cell::new(0));
6659        let count = notifications.clone();
6660        let _subscription =
6661            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
6662
6663        input.update(cx, |state, _| {
6664            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
6665            state.scroll_size = size(px(300.), px(20.));
6666        });
6667        for target in [
6668            None,
6669            Some(point(px(0.), px(0.))),
6670            Some(point(px(20.), px(50.))),
6671        ] {
6672            input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
6673            assert_eq!(
6674                notifications.get(),
6675                0,
6676                "an unchanged clamped offset must stay quiet"
6677            );
6678        }
6679        input.update(cx, |state, cx| {
6680            state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
6681            assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
6682        });
6683        assert_eq!(notifications.get(), 1, "a scroll must notify");
6684        input.update(cx, |state, cx| {
6685            state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
6686            assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
6687        });
6688        assert_eq!(notifications.get(), 2);
6689        input.update(cx, |state, cx| {
6690            state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
6691        });
6692        assert_eq!(
6693            notifications.get(),
6694            2,
6695            "clamping to the current offset must stay quiet"
6696        );
6697        input.update(cx, |state, cx| {
6698            state.scroll_size.width = px(110.);
6699            state.update_scroll_offset(None, cx);
6700            assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
6701        });
6702        assert_eq!(
6703            notifications.get(),
6704            3,
6705            "a smaller scroll range must clamp and notify"
6706        );
6707    }
6708
6709    #[wgpui::test]
6710    fn test_set_line_number_notifies_only_on_change(cx: &mut TestAppContext) {
6711        use std::{cell::Cell, rc::Rc};
6712
6713        cx.update(crate::init);
6714        let mut input = None;
6715        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6716            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
6717            wgpui::EmptyView
6718        });
6719        let input = input.unwrap();
6720        let shown = input.read_with(cx, |state, _| state.mode.line_number());
6721        let notifications = Rc::new(Cell::new(0));
6722        let count = notifications.clone();
6723        let _subscription =
6724            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
6725
6726        window
6727            .update(cx, |_, window, cx| {
6728                input.update(cx, |state, cx| state.set_line_number(shown, window, cx))
6729            })
6730            .unwrap();
6731        assert_eq!(notifications.get(), 0);
6732
6733        window
6734            .update(cx, |_, window, cx| {
6735                input.update(cx, |state, cx| state.set_line_number(!shown, window, cx))
6736            })
6737            .unwrap();
6738        assert_eq!(notifications.get(), 1);
6739        assert_eq!(
6740            input.read_with(cx, |state, _| state.mode.line_number()),
6741            !shown
6742        );
6743    }
6744
6745    #[wgpui::test]
6746    fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
6747        use std::{cell::Cell, rc::Rc};
6748
6749        cx.update(crate::init);
6750        let mut input = None;
6751        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6752            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
6753            wgpui::EmptyView
6754        });
6755        let input = input.unwrap();
6756        cx.run_until_parked();
6757
6758        let notifications = Rc::new(Cell::new(0));
6759        let count = notifications.clone();
6760        let _subscription =
6761            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
6762        cx.run_until_parked();
6763
6764        // Seeding a form is a write, so it notifies once. The input is not
6765        // focused and draws no caret, so nothing may notify after that.
6766        window
6767            .update(cx, |_, window, cx| {
6768                input.update(cx, |state, cx| state.set_value("seeded", window, cx));
6769            })
6770            .unwrap();
6771        cx.run_until_parked();
6772        let settled = notifications.get();
6773
6774        cx.executor()
6775            .advance_clock(std::time::Duration::from_secs(3));
6776        cx.run_until_parked();
6777
6778        assert_eq!(
6779            notifications.get(),
6780            settled,
6781            "an unfocused input is blinking, and every blink repaints the view it is in"
6782        );
6783    }
6784
6785    #[wgpui::test]
6786    fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
6787        use std::{cell::Cell, rc::Rc};
6788
6789        struct Panel {
6790            input: Entity<crate::input::InputState>,
6791            renders: Rc<Cell<usize>>,
6792        }
6793        impl Render for Panel {
6794            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6795                self.renders.set(self.renders.get() + 1);
6796                div().size_full().child(self.input.clone())
6797            }
6798        }
6799        struct Root(Entity<Panel>);
6800        impl Render for Root {
6801            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6802                div().size_full().child(
6803                    self.0
6804                        .clone()
6805                        .cached(wgpui::StyleRefinement::default().size_full()),
6806                )
6807            }
6808        }
6809
6810        cx.update(crate::init);
6811        let renders = Rc::new(Cell::new(0));
6812        let mut input = None;
6813        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6814            let state = cx.new(|cx| crate::input::InputState::new(window, cx));
6815            input = Some(state.clone());
6816            Root(cx.new(|_| Panel {
6817                input: state,
6818                renders: renders.clone(),
6819            }))
6820        });
6821        cx.run_until_parked();
6822        let before = renders.get();
6823        assert!(before > 0);
6824        for _ in 0..60 {
6825            window.update(cx, |_, _, cx| cx.notify()).unwrap();
6826        }
6827        assert_eq!(
6828            renders.get(),
6829            before,
6830            "an idle input must not invalidate its cached parent"
6831        );
6832
6833        let input = input.unwrap();
6834        window
6835            .update(cx, |_, window, cx| {
6836                input.update(cx, |state, cx| state.set_value("changed", window, cx));
6837            })
6838            .unwrap();
6839        assert!(
6840            renders.get() > before,
6841            "text changes must invalidate the parent"
6842        );
6843        // The first paint reports the changed text extent to layout consumers.
6844        window.update(cx, |_, _, cx| cx.notify()).unwrap();
6845        let before = renders.get();
6846        for _ in 0..60 {
6847            window.update(cx, |_, _, cx| cx.notify()).unwrap();
6848        }
6849        assert_eq!(renders.get(), before, "the edited input must settle again");
6850
6851        cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
6852        cx.run_until_parked();
6853        assert!(renders.get() > before, "resizing must invalidate layout");
6854    }
6855
6856    #[wgpui::test]
6857    fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
6858        cx.update(crate::init);
6859        let view = InputView::build_textarea(cx, |state| state);
6860        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6861        cx.update(|window, cx| {
6862            view.input.update(cx, |state, cx| {
6863                for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
6864                    state.set_value(original, window, cx);
6865                    let newline = original.find('\n').unwrap();
6866                    let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
6867                        newline - 1
6868                    } else {
6869                        newline
6870                    };
6871                    state.end(&MoveEnd, window, cx);
6872                    assert_eq!(state.cursor(), end);
6873                    state.right(&MoveRight, window, cx);
6874                    assert_eq!(state.cursor(), newline + 1);
6875                    state.left(&MoveLeft, window, cx);
6876                    assert_eq!(state.cursor(), end);
6877                    state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
6878                    assert_eq!(state.selected_range(), end..end);
6879                    state.move_to_end(&MoveToEnd, window, cx);
6880                    assert_eq!(state.cursor(), original.len());
6881                    state.move_to_start(&MoveToStart, window, cx);
6882                    assert_eq!(state.cursor(), 0);
6883                    assert_eq!(state.value().as_bytes(), original.as_bytes());
6884                }
6885                // A lone CR is an ordinary character; it must not skip its neighbour.
6886                state.set_value("a\rb", window, cx);
6887                state.right(&MoveRight, window, cx);
6888                assert_eq!(state.cursor(), 1);
6889                state.right(&MoveRight, window, cx);
6890                assert_eq!(state.cursor(), 2);
6891            })
6892        });
6893    }
6894
6895    #[wgpui::test]
6896    fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
6897        cx.update(crate::init);
6898
6899        // A single-line input keeps its caret in view by moving its own offset;
6900        // it has no viewport to drag, so a scrollbar in a text field is a
6901        // control that does not exist.
6902        let single = InputView::build(cx, |state| state);
6903        single
6904            .input
6905            .update(cx, |state, _| assert!(!state.shows_scrollbar()));
6906
6907        let multi = InputView::build_textarea(cx, |state| state);
6908        multi
6909            .input
6910            .update(cx, |state, _| assert!(state.shows_scrollbar()));
6911    }
6912
6913    #[wgpui::test]
6914    fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
6915        use std::{cell::Cell, rc::Rc};
6916        cx.update(crate::init);
6917        let input_view = InputView::new(cx);
6918        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6919        let input = input_view.input;
6920        let calls = Rc::new(Cell::new(0usize));
6921        let items = Rc::new(Cell::new(0usize));
6922        let menu_focus = cx.update(|_, cx| cx.focus_handle());
6923
6924        cx.update(|window, cx| {
6925            input.update(cx, |state, cx| {
6926                let calls2 = calls.clone();
6927                let items2 = items.clone();
6928                let menu_focus = menu_focus.clone();
6929                state.on_context_menu(Rc::new(move |menu, _, _, window, cx| {
6930                    calls2.set(calls2.get() + 1);
6931                    items2.set(menu.items.len());
6932                    menu_focus.focus(window, cx);
6933                }));
6934                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
6935            })
6936        });
6937        assert_eq!(calls.get(), 1);
6938        assert_eq!(items.get(), 0);
6939        input.read_with(&cx, |state, _| {
6940            assert_eq!(
6941                state
6942                    .selection_focus
6943                    .as_ref()
6944                    .and_then(WeakFocusHandle::upgrade)
6945                    .as_ref(),
6946                Some(&menu_focus),
6947                "the menu callback must retain selection without reborrowing its input"
6948            );
6949        });
6950
6951        // A custom handler may keep using the same, already-focused menu.
6952        cx.update(|window, cx| {
6953            input.update(cx, |state, cx| {
6954                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
6955            });
6956        });
6957        assert_eq!(calls.get(), 2);
6958        cx.update(|window, cx| {
6959            assert!(input.read(cx).has_selection_focus(window, cx));
6960        });
6961
6962        cx.update(|window, cx| {
6963            input.update(cx, |state, cx| {
6964                state.disabled = true;
6965                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
6966            })
6967        });
6968        assert_eq!(calls.get(), 2);
6969    }
6970
6971    #[wgpui::test]
6972    fn context_menu_handler_can_read_its_input(cx: &mut TestAppContext) {
6973        use std::{cell::Cell, rc::Rc};
6974        cx.update(crate::init);
6975        let input_view = InputView::new(cx);
6976        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6977        let input = input_view.input;
6978        let cursor = Rc::new(Cell::new(None));
6979
6980        cx.update(|window, cx| {
6981            input.update(cx, |state, cx| {
6982                state.set_value("hello", window, cx);
6983                let weak = cx.weak_entity();
6984                let cursor = cursor.clone();
6985                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
6986                    cursor.set(weak.upgrade().map(|input| input.read(cx).cursor()));
6987                }));
6988                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
6989            })
6990        });
6991        assert_eq!(cursor.get(), Some(2));
6992    }
6993
6994    #[wgpui::test]
6995    fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
6996        let input_view = InputView::new(cx);
6997        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6998        let input = input_view.input;
6999
7000        cx.update(|window, cx| {
7001            input.update(cx, |state, cx| {
7002                state.set_value("hello", window, cx);
7003                state.set_readonly(true, cx);
7004            });
7005        });
7006
7007        cx.update(|_, cx| {
7008            input.read_with(cx, |state, _| {
7009                assert!(!state.is_editable());
7010                assert!(!state.is_replaceable());
7011            });
7012        });
7013
7014        // Typing (and IME) goes through the input handler, it must be rejected.
7015        cx.update(|window, cx| {
7016            input.update(cx, |state, cx| {
7017                state.replace_text_in_range(None, " world", window, cx);
7018                state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
7019            });
7020        });
7021        cx.update(|_, cx| {
7022            input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
7023        });
7024
7025        // The programmatic APIs are not limited by the readonly mode.
7026        cx.update(|window, cx| {
7027            input.update(cx, |state, cx| {
7028                state.insert(" world", window, cx);
7029                state.set_value("changed", window, cx);
7030            });
7031        });
7032        cx.update(|_, cx| {
7033            input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
7034        });
7035
7036        // And the user can edit again after leaving the readonly mode.
7037        // The caret is at the start, because `set_value` has reset the selection.
7038        cx.update(|window, cx| {
7039            input.update(cx, |state, cx| {
7040                state.set_readonly(false, cx);
7041                state.replace_text_in_range(None, "!", window, cx);
7042            });
7043        });
7044        cx.update(|_, cx| {
7045            input.read_with(cx, |state, _| {
7046                assert!(state.is_editable());
7047                assert_eq!(state.value(), "!changed");
7048            });
7049        });
7050    }
7051
7052    /// Regression test: editing at a caret that sits far outside the viewport
7053    /// must reveal it in one frame. The cursor-follow in `layout_cursors` runs
7054    /// only on the frame the selection changes, so its old one-line step left
7055    /// the caret offscreen after typing at the end of a long paste.
7056    #[wgpui::test]
7057    fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
7058        let mut input = None;
7059        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7060            cx.set_global(Theme::default());
7061            super::super::init(cx);
7062            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
7063            input = Some(state.clone());
7064            TestRoot(state)
7065        });
7066        let mut cx = VisualTestContext::from_window(window.into(), cx);
7067        let input = input.unwrap();
7068
7069        let text: String = (1..=100)
7070            .map(|i| format!("line {i}"))
7071            .collect::<Vec<_>>()
7072            .join("\n");
7073        cx.update(|window, cx| {
7074            input.update(cx, |state, cx| {
7075                state.set_value(text, window, cx);
7076                let end = state.text.len_bytes();
7077                state.set_selection(end, end);
7078            });
7079        });
7080        cx.run_until_parked();
7081
7082        // The user scrolled back to the top to read the pasted text.
7083        cx.update(|_, cx| {
7084            input.update(cx, |state, cx| {
7085                state.scroll_handle.set_offset(point(px(0.), px(0.)));
7086                cx.notify();
7087            });
7088        });
7089        cx.run_until_parked();
7090
7091        cx.update(|window, cx| {
7092            input.update(cx, |state, cx| {
7093                state.replace_text_in_range(None, "X", window, cx);
7094            });
7095        });
7096        cx.run_until_parked();
7097
7098        cx.update(|_, cx| {
7099            input.read_with(cx, |state, _| {
7100                assert!(state.value().ends_with("line 100X"));
7101                let (caret, _) = state.cursor_layout().expect("caret painted");
7102                let viewport = state.input_bounds();
7103                let scroll_y = state.scroll_handle.offset().y;
7104                let top = caret.origin.y - viewport.origin.y + scroll_y;
7105                assert!(
7106                    top >= px(0.) && top + caret.size.height <= viewport.size.height,
7107                    "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
7108                    viewport.size.height,
7109                );
7110            });
7111        });
7112    }
7113
7114    /// Regression test: changing the auto-grow limits keeps the rows fitted to
7115    /// the text. `set_auto_grow` used to start over at `min_rows`, and the rows
7116    /// were counted again only on the next edit or wrap width change.
7117    #[wgpui::test]
7118    fn test_set_auto_grow_keeps_rows_fitted(cx: &mut TestAppContext) {
7119        let mut input = None;
7120        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7121            cx.set_global(Theme::default());
7122            super::super::init(cx);
7123            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 10));
7124            input = Some(state.clone());
7125            TestRoot(state)
7126        });
7127        let mut cx = VisualTestContext::from_window(window.into(), cx);
7128        let input = input.unwrap();
7129
7130        let text: String = (1..=8)
7131            .map(|i| format!("line {i}"))
7132            .collect::<Vec<_>>()
7133            .join("\n");
7134        cx.update(|window, cx| {
7135            input.update(cx, |state, cx| state.set_value(text, window, cx));
7136        });
7137        cx.run_until_parked();
7138        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7139
7140        // A larger maximum keeps all eight rows.
7141        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 12, cx)));
7142        cx.run_until_parked();
7143        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7144
7145        // A smaller maximum caps them.
7146        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 4, cx)));
7147        cx.run_until_parked();
7148        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 4)));
7149    }
7150
7151    /// Regression test: `scroll_to` at end-of-buffer must produce a deferred
7152    /// scroll target within the safe scroll range, so the painted frame
7153    /// matches what `update_scroll_offset` persists (no jitter). A small
7154    /// `cursor_surrounding_lines` override used to mismatch the hardcoded
7155    /// 3-line edge clearance in `scroll_to`, overshooting `safe_y_min`.
7156    #[wgpui::test]
7157    fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
7158        let input_view = InputView::new(cx);
7159        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7160        let input = input_view.input;
7161
7162        // JetBrains-style: 1 trailing empty row + 1-line cursor surrounding.
7163        cx.update(|window, cx| {
7164            input.update(cx, |state, cx| {
7165                state.set_scroll_beyond_last_line(Some(1), window, cx);
7166                state.set_cursor_surrounding_lines(Some(1), window, cx);
7167                let text: String = (1..=50)
7168                    .map(|i| format!("line {i}"))
7169                    .collect::<Vec<_>>()
7170                    .join("\n");
7171                state.set_value(text, window, cx);
7172            });
7173        });
7174        cx.run_until_parked();
7175
7176        // Sanity: paint populated `scroll_size` and `input_bounds` — without
7177        // these, `safe_y_min` below collapses to 0 and the assertion is vacuous.
7178        cx.update(|_, cx| {
7179            input.read_with(cx, |state, _| {
7180                assert!(
7181                    state.scroll_size.height > px(0.),
7182                    "scroll_size not populated by initial paint"
7183                );
7184                assert!(
7185                    state.input_bounds.size.height > px(0.),
7186                    "input_bounds not populated by initial paint"
7187                );
7188            });
7189        });
7190
7191        // Move cursor to end with downward direction — same code path as a
7192        // `Down` keystroke at EOB. `scroll_to` runs synchronously inside
7193        // `move_to`; inspect `deferred_scroll_offset` in the same closure
7194        // before the next paint consumes and clears it.
7195        cx.update(|_, cx| {
7196            input.update(cx, |state, cx| {
7197                let end = state.text.len_bytes();
7198                state.move_to(end, Some(MoveDirection::Down), cx);
7199
7200                let deferred = state
7201                    .deferred_scroll_offset
7202                    .expect("scroll_to should populate deferred_scroll_offset");
7203                let safe_y_min =
7204                    (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
7205
7206                assert!(
7207                    deferred.y >= safe_y_min,
7208                    "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
7209                     — paint would jitter (Bug C regression)",
7210                    deferred.y,
7211                    safe_y_min,
7212                );
7213            });
7214        });
7215    }
7216
7217    #[wgpui::test]
7218    fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
7219        assert_search_reveals_with_padding_after_manual_scroll(false, cx);
7220    }
7221
7222    #[wgpui::test]
7223    fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
7224        cx: &mut TestAppContext,
7225    ) {
7226        assert_search_reveals_with_padding_after_manual_scroll(true, cx);
7227    }
7228
7229    fn assert_search_reveals_with_padding_after_manual_scroll(
7230        previous: bool,
7231        cx: &mut TestAppContext,
7232    ) {
7233        let input_view = InputView::new(cx);
7234        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7235        let input = input_view.input;
7236        let text = (0..160)
7237            .map(|row| {
7238                if matches!(row, 20 | 60 | 100) {
7239                    format!("match on row {row}")
7240                } else {
7241                    format!("line {row}")
7242                }
7243            })
7244            .collect::<Vec<_>>()
7245            .join("\n");
7246        let start = text.match_indices("match").nth(1).unwrap().0;
7247        let expected_match = start..start + "match".len();
7248        cx.update(|window, cx| {
7249            input.update(cx, |state, cx| {
7250                state.set_cursor_surrounding_lines(Some(3), window, cx);
7251                state.set_value(text, window, cx);
7252                state.set_search_query("match", true, cx);
7253                if previous {
7254                    state.search_session.matcher.next();
7255                    state.search_session.matcher.next();
7256                }
7257            });
7258        });
7259        cx.run_until_parked();
7260        cx.update(|_, cx| {
7261            input.update(cx, |state, cx| {
7262                let line_height = state.last_layout.as_ref().unwrap().line_height;
7263                let y = if previous { px(0.) } else { -line_height * 80. };
7264                state.set_scroll_offset(point(px(0.), y), cx);
7265            });
7266        });
7267        cx.run_until_parked();
7268        input.read_with(&cx, |state, _| {
7269            let visible = state.visible_row_range().unwrap();
7270            if previous {
7271                assert!(visible.end <= 60, "target must be below the viewport");
7272            } else {
7273                assert!(visible.start > 60, "target must be above the viewport");
7274            }
7275        });
7276        cx.update(|_, cx| {
7277            input.update(cx, |state, cx| {
7278                let range = if previous {
7279                    state.previous_search_match(cx)
7280                } else {
7281                    state.next_search_match(cx)
7282                };
7283                assert_eq!(range, Some(expected_match));
7284                assert_eq!(state.search_session.matcher.label(), "2/3");
7285            });
7286        });
7287        cx.run_until_parked();
7288        input.read_with(&cx, |state, _| {
7289            assert!(state.visible_row_range().unwrap().contains(&60));
7290            let line_height = state.last_layout.as_ref().unwrap().line_height;
7291            let target_y = line_height * 60. + state.scroll_handle.offset().y;
7292            // Three lines of edge clearance include the matched line itself.
7293            assert!(target_y >= line_height * 2. - px(0.1));
7294            assert!(
7295                target_y + line_height * 3.
7296                    <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
7297                "search must preserve the configured surrounding-line padding"
7298            );
7299        });
7300    }
7301
7302    /// A host that wants the search shortcut for its own search UI.
7303    struct SearchHost {
7304        editor: Entity<InputBaseState<EditorMode>>,
7305        search_requests: Rc<Cell<usize>>,
7306    }
7307
7308    impl Render for SearchHost {
7309        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7310            let search_requests = self.search_requests.clone();
7311            div()
7312                .size_full()
7313                .on_action(cx.listener(move |_, _: &Search, _, _| {
7314                    search_requests.set(search_requests.get() + 1);
7315                }))
7316                .child(self.editor.clone())
7317        }
7318    }
7319
7320    /// Opens an editor inside [`SearchHost`], focused, and presses the search
7321    /// shortcut once. Returns the editor and the host's request count.
7322    fn press_search_shortcut(
7323        cx: &mut TestAppContext,
7324        searchable: bool,
7325    ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
7326        let search_requests = Rc::new(Cell::new(0));
7327        let mut editor = None;
7328        let window = cx.update(|cx| {
7329            cx.open_window(Default::default(), |window, cx| {
7330                cx.set_global(Theme::default());
7331                super::super::init(cx);
7332                let state =
7333                    cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
7334                editor = Some(state.clone());
7335                cx.new(|_| SearchHost {
7336                    editor: state,
7337                    search_requests: search_requests.clone(),
7338                })
7339            })
7340            .unwrap()
7341        });
7342        let editor = editor.unwrap();
7343        let mut cx = VisualTestContext::from_window(window.into(), cx);
7344        cx.update(|window, cx| {
7345            editor.update(cx, |state, cx| state.focus(window, cx));
7346        });
7347        cx.run_until_parked();
7348        #[cfg(target_os = "macos")]
7349        cx.simulate_keystrokes("cmd-f");
7350        #[cfg(not(target_os = "macos"))]
7351        cx.simulate_keystrokes("ctrl-f");
7352        cx.run_until_parked();
7353        (editor, search_requests)
7354    }
7355
7356    #[wgpui::test]
7357    fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
7358        let (editor, search_requests) = press_search_shortcut(cx, false);
7359        assert_eq!(search_requests.get(), 1);
7360        editor.read_with(cx, |state, _| {
7361            assert!(!state.search_session().open);
7362            assert!(!state.search_session().is_active());
7363        });
7364    }
7365
7366    #[wgpui::test]
7367    fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
7368        let (editor, search_requests) = press_search_shortcut(cx, true);
7369        assert_eq!(search_requests.get(), 0);
7370        editor.read_with(cx, |state, _| {
7371            assert!(state.search_session().open);
7372            assert!(state.search_session().is_active());
7373        });
7374    }
7375
7376    #[wgpui::test]
7377    fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
7378        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7379        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7380        let input = input_view.input;
7381        cx.update(|window, cx| {
7382            input.update(cx, |state, cx| {
7383                state.set_value("foo bar foo", window, cx);
7384                state.set_search_query("foo", true, cx);
7385            });
7386        });
7387        cx.run_until_parked();
7388        input.read_with(&cx, |state, _| {
7389            let session = state.search_session();
7390            assert!(session.is_active());
7391            assert!(!session.open);
7392            assert_eq!(session.matcher.len(), 2);
7393        });
7394        cx.update(|_, cx| {
7395            input.update(cx, |state, cx| state.close_search(cx));
7396        });
7397        input.read_with(&cx, |state, _| {
7398            assert!(!state.search_session().is_active());
7399        });
7400    }
7401
7402    /// A closed search skips rescanning on edits, so every path that reads
7403    /// the matches again must see the edited text, not the text at close.
7404    #[wgpui::test]
7405    fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
7406        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7407        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7408        let input = input_view.input;
7409        cx.update(|window, cx| {
7410            input.update(cx, |state, cx| {
7411                state.set_value("foo bar foo", window, cx);
7412                state.set_search_query("foo", true, cx);
7413                state.close_search(cx);
7414
7415                state.set_value("bar foo", window, cx);
7416                assert_eq!(state.next_search_match(cx), Some(4..7));
7417
7418                state.set_value("foo foo foo", window, cx);
7419                state.set_search_query("foo", true, cx);
7420                assert_eq!(state.search_session().matcher.len(), 3);
7421            });
7422        });
7423    }
7424
7425    #[wgpui::test]
7426    fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
7427        let input_view = InputView::new(cx);
7428        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7429        let input = input_view.input;
7430        let text = format!(
7431            "match\n{}\n{}match\n{}",
7432            "line\n".repeat(80),
7433            "wrapped text ".repeat(500),
7434            "line\n".repeat(80)
7435        );
7436        cx.update(|window, cx| {
7437            input.update(cx, |state, cx| {
7438                state.set_cursor_surrounding_lines(Some(3), window, cx);
7439                state.set_value(text, window, cx);
7440                state.set_search_query("match", true, cx);
7441            });
7442        });
7443        cx.run_until_parked();
7444        cx.update(|_, cx| {
7445            input.update(cx, |state, cx| {
7446                state.next_search_match(cx).unwrap();
7447            });
7448        });
7449        cx.run_until_parked();
7450        input.read_with(&cx, |state, _| {
7451            let range = state.search_session.matcher.matched_ranges()[1].clone();
7452            let layout = state.last_layout.as_ref().unwrap();
7453            let (_, _, position) = state.line_and_position_for_offset(range.end);
7454            let y = position.expect("wrapped match must be laid out").y
7455                + state.scroll_handle.offset().y;
7456            assert!(y >= layout.line_height * 2. - px(0.1));
7457            assert!(
7458                y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
7459                "wrapped match must retain surrounding display rows"
7460            );
7461        });
7462    }
7463
7464    #[wgpui::test]
7465    fn test_number_step(cx: &mut TestAppContext) {
7466        let input = InputView::build(cx, |state| state).input;
7467
7468        cx.update(|cx| {
7469            input.update(cx, |_state, cx| {
7470                assert_eq!(
7471                    NumberStep::from(5.).value(123., StepAction::Increment, cx),
7472                    5.
7473                );
7474
7475                // The step can differ by direction at a boundary: at 1.0 it
7476                // is 0.1 going down and 0.5 going up.
7477                let step = NumberStep::by_value(|value, action, _cx| {
7478                    let below = match action {
7479                        StepAction::Increment => value < 1.0,
7480                        StepAction::Decrement => value <= 1.0,
7481                    };
7482                    if below { 0.1 } else { 0.5 }
7483                });
7484                assert_eq!(step.value(0.5, StepAction::Increment, cx), 0.1);
7485                assert_eq!(step.value(1.0, StepAction::Increment, cx), 0.5);
7486                assert_eq!(step.value(1.0, StepAction::Decrement, cx), 0.1);
7487                assert_eq!(step.value(2.0, StepAction::Decrement, cx), 0.5);
7488            });
7489        });
7490    }
7491
7492    #[wgpui::test]
7493    fn test_number_input_normalization(cx: &mut TestAppContext) {
7494        let input_view = InputView::build(cx, |state| {
7495            state.mask_pattern(MaskPattern::Number {
7496                separator: None,
7497                fraction: None,
7498            })
7499        });
7500        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7501        let input = input_view.input;
7502
7503        // Full-width digits and the ideographic full stop are normalized,
7504        // and the cursor is at the end (in normalized bytes, not the
7505        // original 12 bytes).
7506        cx.update(|window, cx| {
7507            input.update(cx, |state, cx| {
7508                state.replace_text_in_range(None, "12。5", window, cx);
7509            });
7510        });
7511        cx.run_until_parked();
7512        cx.update(|_, cx| {
7513            input.read_with(cx, |state, _| {
7514                assert_eq!(state.value(), "12.5");
7515                let cursor: Range<usize> = state.selected_range();
7516                assert_eq!(cursor, 4..4);
7517            });
7518        });
7519
7520        // Non-numeric input is rejected.
7521        cx.update(|window, cx| {
7522            input.update(cx, |state, cx| {
7523                state.replace_text_in_range(None, "abc", window, cx);
7524            });
7525        });
7526        cx.run_until_parked();
7527        cx.update(|_, cx| {
7528            input.read_with(cx, |state, _| {
7529                assert_eq!(state.value(), "12.5");
7530            });
7531        });
7532
7533        // A bare leading dot is kept as-is (normalized from the ideographic
7534        // full stop), not completed to "0.", so it stays editable.
7535        cx.update(|window, cx| {
7536            input.update(cx, |state, cx| {
7537                let range = state.range_to_utf16(&(0..state.text.len_bytes()));
7538                state.replace_text_in_range(Some(range), "。", window, cx);
7539            });
7540        });
7541        cx.run_until_parked();
7542        cx.update(|_, cx| {
7543            input.read_with(cx, |state, _| {
7544                assert_eq!(state.value(), ".");
7545                let cursor: Range<usize> = state.selected_range();
7546                assert_eq!(cursor, 1..1);
7547            });
7548        });
7549    }
7550
7551    #[wgpui::test]
7552    fn test_mask_pattern_accepts_non_ascii_text(cx: &mut TestAppContext) {
7553        let input_view = InputView::build(cx, |state| state.mask_pattern("9999年99月"));
7554        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7555        let input = input_view.input;
7556
7557        cx.update(|window, cx| {
7558            input.update(cx, |state, cx| {
7559                state.replace_text_in_range(None, "2024年12月", window, cx);
7560            });
7561        });
7562        cx.run_until_parked();
7563        cx.update(|_, cx| {
7564            input.read_with(cx, |state, _| {
7565                assert_eq!(state.value(), "2024年12月");
7566            });
7567        });
7568    }
7569
7570    #[wgpui::test]
7571    fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
7572        let input_view = InputView::build(cx, |state| {
7573            state.mask_pattern(MaskPattern::Number {
7574                separator: Some(','),
7575                fraction: Some(2),
7576            })
7577        });
7578        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7579        let input = input_view.input;
7580
7581        cx.update(|window, cx| {
7582            input.update(cx, |state, cx| {
7583                state.replace_text_in_range(None, "1234", window, cx);
7584            });
7585        });
7586        cx.run_until_parked();
7587        cx.update(|_, cx| {
7588            input.read_with(cx, |state, _| {
7589                assert_eq!(state.value(), "1,234");
7590                assert_eq!(state.unmask_value(), "1234");
7591            });
7592        });
7593    }
7594
7595    #[wgpui::test]
7596    fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
7597        let input_view = InputView::build(cx, |state| {
7598            state
7599                .mask_pattern(MaskPattern::Number {
7600                    separator: None,
7601                    fraction: None,
7602                })
7603                .min(10.)
7604                .max(100.)
7605        });
7606        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7607        let input = input_view.input;
7608
7609        // Out-of-range values are allowed while typing, and clamped on blur.
7610        cx.update(|window, cx| {
7611            input.update(cx, |state, cx| {
7612                state.replace_text_in_range(None, "1000", window, cx);
7613                assert_eq!(state.value(), "1000");
7614                state.clamp_number_value(window, cx);
7615                assert_eq!(state.value(), "100");
7616
7617                let range = state.range_to_utf16(&(0..state.text.len_bytes()));
7618                state.replace_text_in_range(Some(range), "1", window, cx);
7619                assert_eq!(state.value(), "1");
7620                state.clamp_number_value(window, cx);
7621                assert_eq!(state.value(), "10");
7622            });
7623        });
7624    }
7625
7626    #[wgpui::test]
7627    fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
7628        let input_view = InputView::build(cx, |state| {
7629            state.mask_pattern(MaskPattern::Number {
7630                separator: Some(','),
7631                fraction: None,
7632            })
7633        });
7634        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7635        let input = input_view.input;
7636
7637        // When the mask changes the text (regrouping separators), a
7638        // whole-document change is recorded, so undo/redo can restore it.
7639        cx.update(|window, cx| {
7640            input.update(cx, |state, cx| {
7641                state.replace_text_in_range(None, "1234", window, cx);
7642                assert_eq!(state.value(), "1,234");
7643                state.replace_text_in_range(None, "5", window, cx);
7644                assert_eq!(state.value(), "12,345");
7645
7646                // Each whole-document mask rewrite is an atomic undo step.
7647                // Before the whole-document history fix, undo produced a
7648                // corrupted value like "1,2344".
7649                state.undo(&Undo, window, cx);
7650                assert_eq!(state.value(), "1,234");
7651                state.undo(&Undo, window, cx);
7652                assert_eq!(state.value(), "");
7653                state.redo(&Redo, window, cx);
7654                assert_eq!(state.value(), "1,234");
7655                state.redo(&Redo, window, cx);
7656                assert_eq!(state.value(), "12,345");
7657            });
7658        });
7659    }
7660
7661    #[wgpui::test]
7662    fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
7663        let input_view = InputView::build(cx, |state| state);
7664        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7665        let input = input_view.input;
7666
7667        cx.update(|window, cx| {
7668            input.update(cx, |state, cx| {
7669                state.replace_text_in_range(None, "a", window, cx);
7670                state.replace_text_in_range(None, "b", window, cx);
7671                assert_eq!(state.value(), "ab");
7672
7673                state.undo(&Undo, window, cx);
7674                assert_eq!(state.value(), "");
7675            });
7676        });
7677    }
7678
7679    #[wgpui::test]
7680    fn test_undo_manager_cursor_movement_splits_typing(cx: &mut TestAppContext) {
7681        let input_view = InputView::build(cx, |state| state);
7682        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7683        let input = input_view.input;
7684
7685        cx.update(|window, cx| {
7686            input.update(cx, |state, cx| {
7687                state.replace_text_in_range(None, "a", window, cx);
7688                state.replace_text_in_range(None, "b", window, cx);
7689                state.left(&MoveLeft, window, cx);
7690                state.replace_text_in_range(None, "x", window, cx);
7691                assert_eq!(state.value(), "axb");
7692
7693                state.undo(&Undo, window, cx);
7694                assert_eq!(state.value(), "ab");
7695                state.undo(&Undo, window, cx);
7696                assert_eq!(state.value(), "");
7697            });
7698        });
7699    }
7700
7701    #[wgpui::test]
7702    fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
7703        let input_view = InputView::build(cx, |state| state);
7704        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7705        let input = input_view.input;
7706
7707        cx.update(|window, cx| {
7708            input.update(cx, |state, cx| {
7709                state.set_value("abcd", window, cx);
7710                state.set_selected_range(2..2, cx);
7711                state.backspace(&Backspace, window, cx);
7712                state.delete(&Delete, window, cx);
7713                assert_eq!(state.value(), "ad");
7714
7715                state.undo(&Undo, window, cx);
7716                assert_eq!(state.value(), "acd");
7717                state.undo(&Undo, window, cx);
7718                assert_eq!(state.value(), "abcd");
7719            });
7720        });
7721    }
7722
7723    #[wgpui::test]
7724    fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
7725        let input_view = InputView::build(cx, |state| state);
7726        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7727        let input = input_view.input;
7728
7729        cx.update(|window, cx| {
7730            input.update(cx, |state, cx| {
7731                state.set_value("abcd", window, cx);
7732                state.backspace(&Backspace, window, cx);
7733                state.backspace(&Backspace, window, cx);
7734                assert_eq!(state.value(), "ab");
7735                state.undo(&Undo, window, cx);
7736                assert_eq!(state.value(), "abcd");
7737                assert_eq!(state.selected_range(), 4..4);
7738
7739                state.set_value("abcd", window, cx);
7740                state.set_selected_range(1..1, cx);
7741                state.delete(&Delete, window, cx);
7742                state.delete(&Delete, window, cx);
7743                assert_eq!(state.value(), "ad");
7744                state.undo(&Undo, window, cx);
7745                assert_eq!(state.value(), "abcd");
7746                assert_eq!(state.selected_range(), 1..1);
7747            });
7748        });
7749    }
7750
7751    #[wgpui::test]
7752    fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
7753        let input_view = InputView::build(cx, |state| state);
7754        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7755        let input = input_view.input;
7756
7757        cx.update(|window, cx| {
7758            cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
7759            input.update(cx, |state, cx| {
7760                state.replace_text_in_range(None, "a", window, cx);
7761                state.paste(&Paste, window, cx);
7762                state.replace_text_in_range(None, "b", window, cx);
7763                assert_eq!(state.value(), "aPb");
7764
7765                state.undo(&Undo, window, cx);
7766                assert_eq!(state.value(), "aP");
7767                state.undo(&Undo, window, cx);
7768                assert_eq!(state.value(), "a");
7769                state.undo(&Undo, window, cx);
7770                assert_eq!(state.value(), "");
7771            });
7772        });
7773    }
7774
7775    #[wgpui::test]
7776    fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
7777        let input_view = InputView::build(cx, |state| state);
7778        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7779        let input = input_view.input;
7780
7781        cx.update(|window, cx| {
7782            input.update(cx, |state, cx| {
7783                state.replace_text_in_range(None, "a", window, cx);
7784                state.insert("P", window, cx);
7785                state.replace_text_in_range(None, "b", window, cx);
7786                assert_eq!(state.value(), "aPb");
7787
7788                state.undo(&Undo, window, cx);
7789                assert_eq!(state.value(), "aP");
7790                state.undo(&Undo, window, cx);
7791                assert_eq!(state.value(), "a");
7792            });
7793        });
7794    }
7795
7796    #[wgpui::test]
7797    fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
7798        let input_view = InputView::build(cx, |state| state);
7799        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7800        let input = input_view.input;
7801
7802        cx.update(|window, cx| {
7803            input.update(cx, |state, cx| {
7804                state.replace_text_in_range(None, "a", window, cx);
7805                state.replace_text_in_range(None, "b", window, cx);
7806                state.select_all(window, cx);
7807                state.unselect(window, cx);
7808                state.replace_text_in_range(None, "c", window, cx);
7809
7810                state.undo(&Undo, window, cx);
7811                assert_eq!(state.value(), "ab");
7812                state.undo(&Undo, window, cx);
7813                assert_eq!(state.value(), "");
7814            });
7815        });
7816    }
7817
7818    #[wgpui::test]
7819    fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
7820        let input_view = InputView::build_textarea(cx, |state| state);
7821        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7822        let input = input_view.input;
7823
7824        cx.update(|window, cx| {
7825            input.update(cx, |state, cx| {
7826                state.replace_text_in_range(None, "a", window, cx);
7827                state.enter(
7828                    &Enter {
7829                        secondary: false,
7830                        shift: false,
7831                    },
7832                    window,
7833                    cx,
7834                );
7835                state.replace_text_in_range(None, "b", window, cx);
7836
7837                state.undo(&Undo, window, cx);
7838                assert_eq!(state.value(), "a\n");
7839                state.undo(&Undo, window, cx);
7840                assert_eq!(state.value(), "a");
7841                state.undo(&Undo, window, cx);
7842                assert_eq!(state.value(), "");
7843            });
7844        });
7845    }
7846
7847    #[wgpui::test]
7848    fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
7849        let input_view = InputView::build(cx, |state| state);
7850        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7851        let input = input_view.input;
7852
7853        cx.update(|window, cx| {
7854            input.update(cx, |state, cx| {
7855                for part in ["a", "b", "c"] {
7856                    state.replace_text_in_range(None, part, window, cx);
7857                }
7858                state.enter(
7859                    &Enter {
7860                        secondary: false,
7861                        shift: false,
7862                    },
7863                    window,
7864                    cx,
7865                );
7866                for part in ["d", "e", "f"] {
7867                    state.replace_text_in_range(None, part, window, cx);
7868                }
7869                assert_eq!(state.value(), "abcdef");
7870
7871                state.undo(&Undo, window, cx);
7872                assert_eq!(state.value(), "abc");
7873                state.undo(&Undo, window, cx);
7874                assert_eq!(state.value(), "");
7875            });
7876        });
7877    }
7878
7879    #[wgpui::test]
7880    fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
7881        let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
7882        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7883        let input = input_view.input;
7884
7885        cx.update(|window, cx| {
7886            input.update(cx, |state, cx| {
7887                state.replace_text_in_range(None, "before submit", window, cx);
7888                state.enter(
7889                    &Enter {
7890                        secondary: false,
7891                        shift: false,
7892                    },
7893                    window,
7894                    cx,
7895                );
7896                state.replace_text_in_range(None, " after submit", window, cx);
7897                assert_eq!(state.value(), "before submit after submit");
7898
7899                state.undo(&Undo, window, cx);
7900                assert_eq!(state.value(), "before submit");
7901                state.undo(&Undo, window, cx);
7902                assert_eq!(state.value(), "");
7903            });
7904        });
7905    }
7906
7907    #[wgpui::test]
7908    fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
7909        let input_view = InputView::build(cx, |state| state);
7910        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7911        let input = input_view.input;
7912
7913        cx.update(|window, cx| {
7914            input.update(cx, |state, cx| {
7915                state.replace_text_in_range(None, "before blur", window, cx);
7916                state.on_blur(window, cx);
7917                state.on_focus(window, cx);
7918                state.replace_text_in_range(None, " after focus", window, cx);
7919                assert_eq!(state.value(), "before blur after focus");
7920
7921                state.undo(&Undo, window, cx);
7922                assert_eq!(state.value(), "before blur");
7923                state.undo(&Undo, window, cx);
7924                assert_eq!(state.value(), "");
7925            });
7926        });
7927    }
7928
7929    #[wgpui::test]
7930    fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
7931        let input_view = InputView::build_textarea(cx, |state| state);
7932        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7933        let input = input_view.input;
7934
7935        cx.update(|window, cx| {
7936            input.update(cx, |state, cx| {
7937                let enter = Enter {
7938                    secondary: false,
7939                    shift: false,
7940                };
7941                state.replace_text_in_range(None, "a", window, cx);
7942                state.enter(&enter, window, cx);
7943                state.replace_text_in_range(None, "b", window, cx);
7944                state.enter(&enter, window, cx);
7945                state.replace_text_in_range(None, "c", window, cx);
7946                assert_eq!(state.value(), "a\nb\nc");
7947
7948                for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
7949                    state.undo(&Undo, window, cx);
7950                    assert_eq!(state.value(), expected);
7951                }
7952            });
7953        });
7954    }
7955
7956    #[wgpui::test]
7957    fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
7958        let input_view = InputView::build_textarea(cx, |state| state);
7959        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7960        let input = input_view.input;
7961        let parts = [
7962            "The ",
7963            "quick ",
7964            "brown fox, ",
7965            "你好,世界 ",
7966            "🦀 jumps over 13 lazy dogs.",
7967        ];
7968        let expected = parts.concat();
7969
7970        cx.update(|window, cx| {
7971            input.update(cx, |state, cx| {
7972                for part in parts {
7973                    state.replace_text_in_range(None, part, window, cx);
7974                }
7975                assert_eq!(state.value(), expected);
7976
7977                state.undo(&Undo, window, cx);
7978                assert_eq!(state.value(), "");
7979                state.redo(&Redo, window, cx);
7980                assert_eq!(state.value(), expected);
7981            });
7982        });
7983    }
7984
7985    #[wgpui::test]
7986    fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
7987        cx: &mut TestAppContext,
7988    ) {
7989        let input_view = InputView::build_textarea(cx, |state| state);
7990        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7991        let input = input_view.input;
7992        let enter = Enter {
7993            secondary: false,
7994            shift: false,
7995        };
7996
7997        cx.update(|window, cx| {
7998            input.update(cx, |state, cx| {
7999                for (index, line) in [
8000                    "first line with punctuation!",
8001                    "第二行包含 Unicode 🦀",
8002                    "third line has several words",
8003                ]
8004                .into_iter()
8005                .enumerate()
8006                {
8007                    for chunk in line.split_inclusive(' ') {
8008                        state.replace_text_in_range(None, chunk, window, cx);
8009                    }
8010                    if index < 2 {
8011                        state.enter(&enter, window, cx);
8012                    }
8013                }
8014
8015                assert_eq!(
8016                    state.value(),
8017                    "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
8018                );
8019                state.undo(&Undo, window, cx);
8020                assert_eq!(
8021                    state.value(),
8022                    "first line with punctuation!\n第二行包含 Unicode 🦀\n"
8023                );
8024                state.undo(&Undo, window, cx);
8025                assert_eq!(
8026                    state.value(),
8027                    "first line with punctuation!\n第二行包含 Unicode 🦀"
8028                );
8029                state.undo(&Undo, window, cx);
8030                assert_eq!(state.value(), "first line with punctuation!\n");
8031            });
8032        });
8033    }
8034
8035    #[wgpui::test]
8036    fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
8037        let input_view = InputView::build(cx, |state| state);
8038        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8039        let input = input_view.input;
8040
8041        cx.update(|window, cx| {
8042            input.update(cx, |state, cx| {
8043                state.set_value("hunter2", window, cx);
8044                state.set_masked(true, window, cx);
8045                state.select_all(window, cx);
8046                cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
8047
8048                state.copy(&Copy, window, cx);
8049                assert_eq!(
8050                    cx.read_from_clipboard().and_then(|item| item.text()),
8051                    Some("sentinel".to_string())
8052                );
8053
8054                // Cut neither copies nor deletes.
8055                state.cut(&Cut, window, cx);
8056                assert_eq!(state.value(), "hunter2");
8057                assert_eq!(
8058                    cx.read_from_clipboard().and_then(|item| item.text()),
8059                    Some("sentinel".to_string())
8060                );
8061
8062                // Revealing the value restores both.
8063                state.set_masked(false, window, cx);
8064                state.copy(&Copy, window, cx);
8065                assert_eq!(
8066                    cx.read_from_clipboard().and_then(|item| item.text()),
8067                    Some("hunter2".to_string())
8068                );
8069            });
8070        });
8071    }
8072
8073    #[wgpui::test]
8074    fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
8075        let input_view = InputView::build(cx, |state| state);
8076        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8077        let input = input_view.input;
8078
8079        cx.update(|window, cx| {
8080            input.update(cx, |state, cx| {
8081                state.set_value("aaa bbb ccc", window, cx);
8082                state.set_masked(true, window, cx);
8083                state.set_selected_range(7..7, cx);
8084
8085                // The mask hides word boundaries, so a word delete takes
8086                // everything before the caret and leaves the rest.
8087                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8088                assert_eq!(state.value(), " ccc");
8089                assert_eq!(state.selected_range(), 0..0);
8090
8091                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
8092                assert_eq!(state.value(), "");
8093
8094                // A double click takes the whole value, not one word.
8095                state.set_value("aaa bbb ccc", window, cx);
8096                state.select_word(9, window, cx);
8097                assert_eq!(state.selected_range(), 0..11);
8098
8099                // Unmasked, the same delete only takes one word.
8100                state.set_masked(false, window, cx);
8101                state.set_value("aaa bbb ccc", window, cx);
8102                state.set_selected_range(11..11, cx);
8103                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8104                assert_eq!(state.value(), "aaa bbb ");
8105
8106                state.set_value("aaa bbb ccc", window, cx);
8107                state.select_word(9, window, cx);
8108                assert_eq!(state.selected_range(), 8..11);
8109            });
8110        });
8111    }
8112
8113    #[wgpui::test]
8114    fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
8115        let input_view = InputView::build(cx, |state| state);
8116        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8117        let input = input_view.input;
8118
8119        cx.update(|window, cx| {
8120            input.update(cx, |state, cx| {
8121                state.set_value("hunter2", window, cx);
8122                state.select_all(window, cx);
8123                assert!(state.context_menu_capabilities().is_copyable());
8124
8125                state.set_masked(true, window, cx);
8126                let capabilities = state.context_menu_capabilities();
8127                assert!(capabilities.is_masked());
8128                assert!(capabilities.has_selection());
8129                assert!(!capabilities.is_copyable());
8130            });
8131        });
8132    }
8133
8134    #[wgpui::test]
8135    fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
8136        cx: &mut TestAppContext,
8137    ) {
8138        let input_view = InputView::build(cx, |state| state);
8139        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8140        let input = input_view.input;
8141
8142        cx.update(|window, cx| {
8143            input.update(cx, |state, cx| {
8144                state.replace_text_in_range(None, "alpha beta gamma", window, cx);
8145                state.set_selected_range(6..10, cx);
8146                state.cut(&Cut, window, cx);
8147                assert_eq!(state.value(), "alpha  gamma");
8148
8149                state.paste(&Paste, window, cx);
8150                state.paste(&Paste, window, cx);
8151                assert_eq!(state.value(), "alpha betabeta gamma");
8152
8153                state.undo(&Undo, window, cx);
8154                assert_eq!(state.value(), "alpha beta gamma");
8155                state.undo(&Undo, window, cx);
8156                assert_eq!(state.value(), "alpha  gamma");
8157                state.undo(&Undo, window, cx);
8158                assert_eq!(state.value(), "alpha beta gamma");
8159            });
8160        });
8161    }
8162
8163    #[wgpui::test]
8164    fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
8165        let input_view = InputView::build_textarea(cx, |state| state);
8166        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8167        let input = input_view.input;
8168
8169        cx.update(|window, cx| {
8170            input.update(cx, |state, cx| {
8171                state.set_value("one two three\nfour five", window, cx);
8172                state.set_selected_range(13..13, cx);
8173                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8174                assert_eq!(state.value(), "one two \nfour five");
8175                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
8176                assert_eq!(state.value(), "one two four five");
8177
8178                state.undo(&Undo, window, cx);
8179                assert_eq!(state.value(), "one two \nfour five");
8180                state.undo(&Undo, window, cx);
8181                assert_eq!(state.value(), "one two three\nfour five");
8182            });
8183        });
8184    }
8185
8186    #[wgpui::test]
8187    fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
8188        let input_view = InputView::build_textarea(cx, |state| state);
8189        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8190        let input = input_view.input;
8191
8192        cx.update(|window, cx| {
8193            input.update(cx, |state, cx| {
8194                state.replace_text_in_range(None, "before", window, cx);
8195                state.set_selected_range(0..6, cx);
8196                state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
8197                assert_eq!(state.value(), "line one\nline two\n第三行");
8198
8199                state.undo(&Undo, window, cx);
8200                assert_eq!(state.value(), "before");
8201                assert_eq!(state.selected_range(), 0..6);
8202                state.redo(&Redo, window, cx);
8203                assert_eq!(state.value(), "line one\nline two\n第三行");
8204            });
8205        });
8206    }
8207
8208    #[wgpui::test]
8209    fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
8210        let input_view = InputView::build(cx, |state| state);
8211        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8212        let input = input_view.input;
8213
8214        cx.update(|window, cx| {
8215            input.update(cx, |state, cx| {
8216                state.replace_text_in_range(None, "prefix ", window, cx);
8217                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
8218                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
8219                state.replace_and_mark_text_in_range(None, "你", None, window, cx);
8220                state.unmark_text(window, cx);
8221                state.replace_text_in_range(None, " suffix", window, cx);
8222                assert_eq!(state.value(), "prefix 你 suffix");
8223
8224                state.undo(&Undo, window, cx);
8225                assert_eq!(state.value(), "prefix 你");
8226                state.undo(&Undo, window, cx);
8227                assert_eq!(state.value(), "prefix ");
8228                state.undo(&Undo, window, cx);
8229                assert_eq!(state.value(), "");
8230            });
8231        });
8232    }
8233
8234    #[wgpui::test]
8235    fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
8236        let input_view = InputView::build(cx, |state| state);
8237        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8238        let input = input_view.input;
8239
8240        cx.update(|window, cx| {
8241            input.update(cx, |state, cx| {
8242                state.replace_text_in_range(None, "abc", window, cx);
8243                state.set_selected_range(1..2, cx);
8244                state.replace_text_in_range(None, "X", window, cx);
8245                state.replace_text_in_range(None, "z", window, cx);
8246                assert_eq!(state.value(), "aXzc");
8247
8248                state.undo(&Undo, window, cx);
8249                assert_eq!(state.value(), "aXc");
8250                state.undo(&Undo, window, cx);
8251                assert_eq!(state.value(), "abc");
8252                state.undo(&Undo, window, cx);
8253                assert_eq!(state.value(), "");
8254            });
8255        });
8256    }
8257
8258    #[wgpui::test]
8259    fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
8260        let input_view = InputView::build(cx, |state| {
8261            state.mask_pattern(MaskPattern::Number {
8262                separator: None,
8263                fraction: None,
8264            })
8265        });
8266        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8267        let input = input_view.input;
8268
8269        cx.update(|window, cx| {
8270            input.update(cx, |state, cx| {
8271                state.replace_text_in_range(None, "1.2", window, cx);
8272
8273                // Delete the integer part "1": the value keeps the leading dot
8274                // (".2"), not completed to "0.2", so the digits before the dot
8275                // stay editable.
8276                let range = state.range_to_utf16(&(0..1));
8277                state.replace_text_in_range(Some(range), "", window, cx);
8278                assert_eq!(state.value(), ".2");
8279                let cursor: Range<usize> = state.selected_range();
8280                assert_eq!(cursor, 0..0);
8281
8282                // The user can type a new integer part.
8283                state.replace_text_in_range(Some(0..0), "3", window, cx);
8284                assert_eq!(state.value(), "3.2");
8285            });
8286        });
8287    }
8288
8289    #[wgpui::test]
8290    fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
8291        // A pre-existing invalid text (e.g. a `default_value` that does not
8292        // conform) must not trap the user, the edit is allowed to fix it.
8293        let input_view = InputView::build(cx, |state| {
8294            state
8295                .mask_pattern(MaskPattern::Number {
8296                    separator: None,
8297                    fraction: None,
8298                })
8299                .default_value("1,234")
8300        });
8301        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8302        let input = input_view.input;
8303
8304        cx.update(|window, cx| {
8305            input.update(cx, |state, cx| {
8306                // Delete the last char, the pending text "1,23" is still
8307                // invalid, but the edit is allowed since the old text was
8308                // already invalid.
8309                let range = state.range_to_utf16(&(4..5));
8310                state.replace_text_in_range(Some(range), "", window, cx);
8311                assert_eq!(state.value(), "1,23");
8312
8313                // Once the text becomes valid, the validation works as usual.
8314                let range = state.range_to_utf16(&(1..2));
8315                state.replace_text_in_range(Some(range), "", window, cx);
8316                assert_eq!(state.value(), "123");
8317                state.replace_text_in_range(None, "a", window, cx);
8318                assert_eq!(state.value(), "123");
8319            });
8320        });
8321    }
8322
8323    /// After `set_value` on a single-line input the caret sits at the end (like
8324    /// HTML `<input>`), yet the view is scrolled back to the start so a long
8325    /// value shows its beginning instead of its tail.
8326    #[wgpui::test]
8327    fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
8328        let input_view = InputView::build(cx, |state| state);
8329        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8330        let input = input_view.input;
8331
8332        // Long enough to overflow any reasonable single-line input width.
8333        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8334        let len = value.len();
8335
8336        // Right after `set_value`, before the next paint consumes the deferred
8337        // offset: caret is at the end, and the view is forced back to the start.
8338        cx.update(|window, cx| {
8339            input.update(cx, |state, cx| {
8340                state.set_value(value.clone(), window, cx);
8341
8342                assert_eq!(
8343                    state.selected_range(),
8344                    len..len,
8345                    "single-line caret should be at the end after set_value"
8346                );
8347                assert_eq!(
8348                    state.deferred_scroll_offset,
8349                    Some(point(px(0.), px(0.))),
8350                    "the view should be forced back to the start"
8351                );
8352            });
8353        });
8354
8355        // After a paint, the steady-state view stays at the start (x == 0) even
8356        // though the caret is at the far end.
8357        cx.run_until_parked();
8358        cx.update(|_, cx| {
8359            input.read_with(cx, |state, _| {
8360                assert!(
8361                    state.scroll_size.width > state.input_bounds.size.width,
8362                    "value must overflow the input width or this test is vacuous"
8363                );
8364                assert_eq!(
8365                    state.scroll_handle.offset().x,
8366                    px(0.),
8367                    "long value should display from its start, not its tail"
8368                );
8369            });
8370        });
8371    }
8372
8373    /// `replace_all` on a single-line input replaces the text, puts the
8374    /// caret at the end, and — like `set_value` — snaps the view back to the
8375    /// start so a long value shows its beginning instead of its tail.
8376    #[wgpui::test]
8377    fn test_replace_all_single_line(cx: &mut TestAppContext) {
8378        let input_view = InputView::build(cx, |state| state);
8379        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8380        let input = input_view.input;
8381
8382        // Long enough to overflow any reasonable single-line input width.
8383        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8384        let len = value.len();
8385
8386        // Right after `replace_all`, before the next paint consumes the
8387        // deferred offset: caret is at the end, and the view is forced back
8388        // to the start.
8389        cx.update(|window, cx| {
8390            input.update(cx, |state, cx| {
8391                state.set_value("hello", window, cx);
8392                state.replace_all(value.clone(), window, cx);
8393                assert_eq!(state.value(), value);
8394                assert_eq!(
8395                    state.selected_range(),
8396                    len..len,
8397                    "single-line caret should be at the end after replace_all"
8398                );
8399                assert_eq!(
8400                    state.scroll_handle.offset(),
8401                    point(px(0.), px(0.)),
8402                    "the scroll offset should be reset to the start"
8403                );
8404                assert_eq!(
8405                    state.deferred_scroll_offset,
8406                    Some(point(px(0.), px(0.))),
8407                    "single-line should set a deferred scroll offset to keep the start visible"
8408                );
8409            });
8410        });
8411
8412        // After a paint, the steady-state view stays at the start (x == 0)
8413        // even though the caret is at the far end.
8414        cx.run_until_parked();
8415        cx.update(|_, cx| {
8416            input.read_with(cx, |state, _| {
8417                assert!(
8418                    state.scroll_size.width > state.input_bounds.size.width,
8419                    "value must overflow the input width or this test is vacuous"
8420                );
8421                assert_eq!(
8422                    state.scroll_handle.offset().x,
8423                    px(0.),
8424                    "long value should display from its start, not its tail"
8425                );
8426            });
8427        });
8428    }
8429
8430    #[wgpui::test]
8431    fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
8432        let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
8433        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8434        let input = input_view.input;
8435
8436        cx.update(|window, cx| {
8437            input.update(cx, |state, cx| {
8438                assert_eq!(state.value(), "defaultvalue");
8439
8440                state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
8441                assert_eq!(state.value(), "firstsecondthirdfourth");
8442
8443                state.set_value("", window, cx);
8444                state.insert("a\nb", window, cx);
8445                assert_eq!(state.value(), "ab");
8446            });
8447
8448            cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
8449            input.update(cx, |state, cx| {
8450                state.set_value("", window, cx);
8451                state.paste(&Paste, window, cx);
8452                assert_eq!(state.value(), "abcd");
8453            });
8454        });
8455
8456        cx.run_until_parked();
8457    }
8458
8459    /// `replace_all` on a multi-line (non-code-editor) input clears the
8460    /// selection to `0..0` and resets the scroll offset, but does not set a
8461    /// deferred scroll offset (single-line only).
8462    #[wgpui::test]
8463    fn test_replace_all_multi_line(cx: &mut TestAppContext) {
8464        let input_view = InputView::build_textarea(cx, |state| state);
8465        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8466        let input = input_view.input;
8467
8468        cx.update(|window, cx| {
8469            input.update(cx, |state, cx| {
8470                state.set_value("foo\nbar", window, cx);
8471                state.replace_all("baz\nqux", window, cx);
8472                assert_eq!(state.value(), "baz\nqux");
8473                assert_eq!(
8474                    state.selected_range(),
8475                    0..0,
8476                    "multi-line selection should be cleared after replace_all"
8477                );
8478                assert_eq!(
8479                    state.scroll_handle.offset(),
8480                    point(px(0.), px(0.)),
8481                    "the scroll offset should be reset to the start"
8482                );
8483                assert!(
8484                    state.deferred_scroll_offset.is_none(),
8485                    "multi-line should not set a deferred scroll offset"
8486                );
8487            });
8488        });
8489    }
8490
8491    /// Unlike `set_value`, `replace_all` records the change so the user can
8492    /// undo it back to the previous text and redo to the new text.
8493    #[wgpui::test]
8494    fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
8495        let input_view = InputView::build(cx, |state| state);
8496        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8497        let input = input_view.input;
8498
8499        cx.update(|window, cx| {
8500            input.update(cx, |state, cx| {
8501                // Seed with a value and clear history so the baseline is clean.
8502                state.set_value("first", window, cx);
8503                assert!(
8504                    !state.undo_manager.has_undos(),
8505                    "history should be empty after set_value"
8506                );
8507
8508                // replace_all records a single undoable change.
8509                state.replace_all("second", window, cx);
8510                assert_eq!(state.value(), "second");
8511                assert!(
8512                    state.undo_manager.has_undos(),
8513                    "replace_all should record an undo step"
8514                );
8515
8516                // Undo restores the previous text.
8517                state.undo(&Undo, window, cx);
8518                assert_eq!(state.value(), "first");
8519
8520                // Redo reapplies the replacement.
8521                state.redo(&Redo, window, cx);
8522                assert_eq!(state.value(), "second");
8523            });
8524        });
8525    }
8526
8527    /// `replace_all` on a code editor marks a pending update and resets LSP
8528    /// state, so diagnostics/completions refresh against the new text.
8529    #[wgpui::test]
8530    fn test_replace_all_code_editor(cx: &mut TestAppContext) {
8531        let input_view = InputView::new(cx);
8532        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8533        let input = input_view.input;
8534
8535        cx.update(|window, cx| {
8536            input.update(cx, |state, cx| {
8537                // Plant a pending-update flag and some LSP state to verify reset.
8538                state.set_value("select 1", window, cx);
8539                state._pending_update = false;
8540
8541                state.replace_all("select 2", window, cx);
8542                assert_eq!(state.value(), "select 2");
8543                assert!(
8544                    state._pending_update,
8545                    "replace_all on a code editor should request a pending update"
8546                );
8547            });
8548        });
8549    }
8550
8551    #[wgpui::test]
8552    fn test_set_selected_range(cx: &mut TestAppContext) {
8553        let input_view = InputView::build(cx, |state| state.default_value("hello world"));
8554        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8555        let input = input_view.input;
8556
8557        cx.update(|_, cx| {
8558            input.update(cx, |s, cx| {
8559                s.set_selected_range(0..5, cx);
8560                assert_eq!(s.selected_range(), 0..5);
8561                assert_eq!(s.selected_text().to_string(), "hello");
8562
8563                s.set_selected_range(6..11, cx);
8564                assert_eq!(s.selected_text().to_string(), "world");
8565
8566                // clamped + collapsed
8567                s.set_selected_range(100..100, cx);
8568                assert_eq!(s.selected_range(), 11..11);
8569            });
8570        });
8571    }
8572
8573    /// A single-edit batch round-trips through undo/redo.
8574    #[wgpui::test]
8575    fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
8576        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
8577        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8578        let input = input_view.input;
8579
8580        cx.update(|window, cx| {
8581            input.update(cx, |s, cx| {
8582                s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
8583                assert_eq!(s.value(), "HELLO world");
8584
8585                s.undo(&Undo, window, cx);
8586                assert_eq!(s.value(), "hello world");
8587
8588                s.redo(&Redo, window, cx);
8589                assert_eq!(s.value(), "HELLO world");
8590            });
8591        });
8592    }
8593
8594    /// A single undo restores the exact original text and a single redo
8595    /// re-applies all edits, verifying the back-to-front application ordering.
8596    #[wgpui::test]
8597    fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
8598        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
8599        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8600        let input = input_view.input;
8601
8602        cx.update(|window, cx| {
8603            input.update(cx, |s, cx| {
8604                // Two edits at different positions, given in pre-edit
8605                // coordinates and in arbitrary (non-sorted) order.
8606                s.replace_text_in_ranges(
8607                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
8608                    window,
8609                    cx,
8610                );
8611                assert_eq!(s.value(), "X bbb Y");
8612
8613                // One collapsed cursor per edit, at the end of each inserted text.
8614                let cursors: Vec<usize> =
8615                    s.selections.iter().map(|sel| sel.cursor_offset()).collect();
8616                assert_eq!(cursors, vec![1, 7]);
8617
8618                // The whole batch is a single undo transaction.
8619                assert_eq!(s.undo_manager.undo_count(), 1);
8620
8621                // One undo restores the exact original text.
8622                s.undo(&Undo, window, cx);
8623                assert_eq!(s.value(), "aaa bbb ccc");
8624
8625                // One redo re-applies all edits.
8626                s.redo(&Redo, window, cx);
8627                assert_eq!(s.value(), "X bbb Y");
8628            });
8629        });
8630    }
8631
8632    /// A multi-edit change reaches the highlighter once, with every edit in
8633    /// application order and the text right after each, which is what the
8634    /// default `update_batch` replays through `update` one edit at a time.
8635    #[wgpui::test]
8636    fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
8637        use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
8638        use std::cell::RefCell;
8639        use wgpui::HighlightStyle;
8640
8641        struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
8642
8643        impl InputHighlighter for RecordingHighlighter {
8644            fn language(&self) -> SharedString {
8645                "recording".into()
8646            }
8647
8648            fn update(
8649                &mut self,
8650                _: Option<InputEdit>,
8651                text: &Rope,
8652                _: bool,
8653                _: &mut Window,
8654                _: &mut Context<EditorState>,
8655            ) {
8656                self.0.borrow_mut().push(vec![text.to_string()]);
8657            }
8658
8659            fn update_batch(
8660                &mut self,
8661                edits: &[(InputEdit, Rope)],
8662                _: bool,
8663                _: &mut Window,
8664                _: &mut Context<EditorState>,
8665            ) {
8666                let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
8667                self.0.borrow_mut().push(texts);
8668            }
8669
8670            fn styles(
8671                &self,
8672                range: &Range<usize>,
8673                _: &dyn HighlightStyleResolver,
8674            ) -> Vec<(Range<usize>, HighlightStyle)> {
8675                vec![(range.clone(), HighlightStyle::default())]
8676            }
8677
8678            fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
8679                Vec::new()
8680            }
8681        }
8682
8683        let updates = Rc::new(RefCell::new(Vec::new()));
8684        let input_view = InputView::new(cx);
8685        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8686        let input = input_view.input;
8687
8688        cx.update(|window, cx| {
8689            input.update(cx, |s, cx| {
8690                s.set_value("aaa bbb ccc", window, cx);
8691                let recorded = updates.clone();
8692                s.set_highlighter_factory(
8693                    Rc::new(move |_: &str| {
8694                        let highlighter: Box<dyn InputHighlighter> =
8695                            Box::new(RecordingHighlighter(recorded.clone()));
8696                        Some(highlighter)
8697                    }),
8698                    cx,
8699                );
8700                s.replace_text_in_ranges(
8701                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
8702                    window,
8703                    cx,
8704                );
8705            });
8706        });
8707
8708        assert_eq!(
8709            *updates.borrow(),
8710            vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
8711        );
8712    }
8713
8714    /// An IME composition (marking then commit) undoes as a single unit.
8715    #[wgpui::test]
8716    fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
8717        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
8718        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8719        let input = input_view.input;
8720
8721        cx.update(|window, cx| {
8722            input.update(cx, |s, cx| {
8723                // Simulate an IME composition: mark, refine, then commit.
8724                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
8725                s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
8726                s.replace_text_in_range(None, "你", window, cx);
8727                assert_eq!(s.value(), "你");
8728
8729                // The entire composition is one undo transaction.
8730                assert_eq!(s.undo_manager.undo_count(), 1);
8731
8732                s.undo(&Undo, window, cx);
8733                assert_eq!(s.value(), "");
8734
8735                s.redo(&Redo, window, cx);
8736                assert_eq!(s.value(), "你");
8737            });
8738        });
8739    }
8740
8741    /// A keystroke right after a committed composition must be its own undo
8742    /// entry, not merged into the (finalized) composition transaction.
8743    #[wgpui::test]
8744    fn test_edit_after_composition_is_separate_undo(cx: &mut TestAppContext) {
8745        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
8746        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8747        let input = input_view.input;
8748
8749        cx.update(|window, cx| {
8750            input.update(cx, |s, cx| {
8751                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
8752                s.replace_text_in_range(None, "你", window, cx);
8753                assert_eq!(s.value(), "你");
8754                assert_eq!(s.undo_manager.undo_count(), 1);
8755
8756                // Typing after the commit is a distinct transaction.
8757                s.replace_text_in_range(None, "x", window, cx);
8758                assert_eq!(s.value(), "你x");
8759                assert_eq!(s.undo_manager.undo_count(), 2);
8760
8761                s.undo(&Undo, window, cx);
8762                assert_eq!(s.value(), "你");
8763                s.undo(&Undo, window, cx);
8764                assert_eq!(s.value(), "");
8765            });
8766        });
8767    }
8768
8769    /// Canceling a composition via `unmark_text` closes its transaction so it
8770    /// does not leak and swallow a later edit.
8771    #[wgpui::test]
8772    fn test_composition_cancel_via_unmark_does_not_leak(cx: &mut TestAppContext) {
8773        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
8774        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8775        let input = input_view.input;
8776
8777        cx.update(|window, cx| {
8778            input.update(cx, |s, cx| {
8779                // Start a composition, then cancel it via unmark.
8780                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
8781                s.unmark_text(window, cx);
8782                let after_cancel = s.undo_manager.undo_count();
8783
8784                // A later edit is recorded independently.
8785                s.replace_text_in_range(None, "x", window, cx);
8786                assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
8787            });
8788        });
8789    }
8790
8791    #[wgpui::test]
8792    fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
8793        let input_view = InputView::build(cx, |state| state.default_value("éx"));
8794        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8795        let input = input_view.input;
8796
8797        cx.update(|window, cx| {
8798            input.update(cx, |state, cx| {
8799                state.set_selected_range(0..1, cx);
8800                assert_eq!(state.selected_range(), 0..2);
8801                state.copy(&Copy, window, cx);
8802
8803                state.set_selected_range(1..1, cx);
8804                assert_eq!(state.selected_range(), 0..0);
8805            });
8806        });
8807    }
8808
8809    #[wgpui::test]
8810    fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
8811        let input_view = InputView::build(cx, |state| state.default_value("你好 "));
8812        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8813        let input = input_view.input;
8814
8815        cx.update(|window, cx| {
8816            input.update(cx, |state, cx| {
8817                state.set_selected_range(7..7, cx);
8818                state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
8819                state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
8820
8821                assert_eq!(state.value(), "你好 sh");
8822                assert_eq!(state.selected_range(), 9..9);
8823                assert_eq!(state.ime_marked_range, Some((7..9).into()));
8824            });
8825        });
8826    }
8827
8828    #[wgpui::test]
8829    fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
8830        let input_view = InputView::build(cx, |state| state);
8831        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8832        let input = input_view.input;
8833
8834        cx.update(|window, cx| {
8835            input.update(cx, |state, cx| {
8836                state.set_value("a", window, cx);
8837                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
8838                state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
8839                state.replace_text_in_range(None, "是", window, cx);
8840                assert_eq!(state.value(), "a是");
8841
8842                state.undo(&Undo, window, cx);
8843                assert_eq!(state.value(), "a");
8844                state.redo(&Redo, window, cx);
8845                assert_eq!(state.value(), "a是");
8846            });
8847        });
8848    }
8849
8850    #[wgpui::test]
8851    fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
8852        let input_view = InputView::build(cx, |state| state);
8853        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8854        let input = input_view.input;
8855
8856        cx.update(|window, cx| {
8857            input.update(cx, |state, cx| {
8858                // First composition: "jin" -> "今天"
8859                state.replace_and_mark_text_in_range(None, "j", None, window, cx);
8860                state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
8861                state.replace_text_in_range(None, "今天", window, cx);
8862                // Second composition: "wo" -> "我们"
8863                state.replace_and_mark_text_in_range(None, "w", None, window, cx);
8864                state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
8865                state.replace_text_in_range(None, "我们", window, cx);
8866                assert_eq!(state.value(), "今天我们");
8867                assert_eq!(state.selected_range(), 12..12);
8868
8869                state.undo(&Undo, window, cx);
8870                assert_eq!(state.value(), "今天");
8871                assert_eq!(state.selected_range(), 6..6);
8872
8873                state.undo(&Undo, window, cx);
8874                assert_eq!(state.value(), "");
8875                assert_eq!(state.selected_range(), 0..0);
8876
8877                state.redo(&Redo, window, cx);
8878                assert_eq!(state.value(), "今天");
8879                assert_eq!(state.selected_range(), 6..6);
8880
8881                state.redo(&Redo, window, cx);
8882                assert_eq!(state.value(), "今天我们");
8883                assert_eq!(state.selected_range(), 12..12);
8884            });
8885        });
8886    }
8887
8888    #[wgpui::test]
8889    fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
8890        let input_view = InputView::build(cx, |state| state);
8891        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8892        let input = input_view.input;
8893
8894        cx.update(|window, cx| {
8895            input.update(cx, |state, cx| {
8896                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
8897                state.replace_text_in_range(None, "你", window, cx);
8898                state.undo_manager.set_pending_intent(EditIntent::Typing);
8899                state.replace_text_in_range(None, "a", window, cx);
8900                state.undo_manager.set_pending_intent(EditIntent::Typing);
8901                state.replace_text_in_range(None, "b", window, cx);
8902                assert_eq!(state.value(), "你ab");
8903
8904                state.undo(&Undo, window, cx);
8905                assert_eq!(state.value(), "你");
8906
8907                state.undo(&Undo, window, cx);
8908                assert_eq!(state.value(), "");
8909            });
8910        });
8911    }
8912
8913    #[wgpui::test]
8914    fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
8915        let input_view = InputView::build(cx, |state| state);
8916        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8917        let input = input_view.input;
8918
8919        cx.update(|window, cx| {
8920            input.update(cx, |state, cx| {
8921                state.set_value("a", window, cx);
8922                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
8923                state.replace_and_mark_text_in_range(None, "", None, window, cx);
8924
8925                assert_eq!(state.value(), "a");
8926                assert!(!state.undo_manager.has_undos());
8927            });
8928        });
8929    }
8930
8931    /// The macOS Korean IME rewrites the character it just inserted.
8932    #[wgpui::test]
8933    fn test_undo_manager_ime_rewrites_of_typed_char_are_one_group(cx: &mut TestAppContext) {
8934        let input_view = InputView::build(cx, |state| state);
8935        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8936        let input = input_view.input;
8937
8938        cx.update(|window, cx| {
8939            input.update(cx, |state, cx| {
8940                state.set_value("é ", window, cx);
8941                state.set_selected_range(3..3, cx);
8942                // g k s r m f: "ㅎ" -> "하" -> "한", then "ㄱ" -> "그" -> "글"
8943                state.replace_text_in_range(None, "ㅎ", window, cx);
8944                state.replace_text_in_range(Some(2..3), "하", window, cx);
8945                state.replace_text_in_range(Some(2..3), "한", window, cx);
8946                state.replace_text_in_range(None, "ㄱ", window, cx);
8947                state.replace_text_in_range(Some(3..4), "그", window, cx);
8948                state.replace_text_in_range(Some(3..4), "글", window, cx);
8949                assert_eq!(state.value(), "é 한글");
8950                assert_eq!(state.undo_manager.undo_count(), 1);
8951
8952                state.undo(&Undo, window, cx);
8953                assert_eq!(state.value(), "é ");
8954                assert_eq!(state.selected_range(), 3..3);
8955
8956                state.redo(&Redo, window, cx);
8957                assert_eq!(state.value(), "é 한글");
8958                assert_eq!(state.selected_range(), 9..9);
8959            });
8960        });
8961    }
8962
8963    #[wgpui::test]
8964    fn test_undo_manager_rewrite_after_cursor_movement_is_separate(cx: &mut TestAppContext) {
8965        let input_view = InputView::build(cx, |state| state);
8966        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8967        let input = input_view.input;
8968
8969        cx.update(|window, cx| {
8970            input.update(cx, |state, cx| {
8971                state.replace_text_in_range(None, "c", window, cx);
8972                state.replace_text_in_range(None, "e", window, cx);
8973                state.left(&MoveLeft, window, cx);
8974                state.right(&MoveRight, window, cx);
8975                state.replace_text_in_range(Some(1..2), "é", window, cx);
8976                assert_eq!(state.value(), "cé");
8977
8978                state.undo(&Undo, window, cx);
8979                assert_eq!(state.value(), "ce");
8980                state.undo(&Undo, window, cx);
8981                assert_eq!(state.value(), "");
8982            });
8983        });
8984    }
8985
8986    #[wgpui::test]
8987    fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
8988        let input_view = InputView::build(cx, |state| state);
8989        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8990        let input = input_view.input;
8991
8992        cx.update(|window, cx| {
8993            input.update(cx, |state, cx| {
8994                state.set_value("abc", window, cx);
8995                state.set_selected_range(1..2, cx);
8996                state.replace_text_in_range(None, "X", window, cx);
8997
8998                state.undo(&Undo, window, cx);
8999                assert_eq!(state.value(), "abc");
9000                assert_eq!(state.selected_range(), 1..2);
9001
9002                state.redo(&Redo, window, cx);
9003                assert_eq!(state.value(), "aXc");
9004                assert_eq!(state.selected_range(), 2..2);
9005            });
9006        });
9007    }
9008
9009    #[wgpui::test]
9010    fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
9011        let input_view = InputView::build(cx, |state| state);
9012        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9013        let input = input_view.input;
9014
9015        cx.update(|window, cx| {
9016            input.update(cx, |state, cx| {
9017                state.set_value("abc", window, cx);
9018                state.set_selected_range(1..1, cx);
9019                state.delete(&Delete, window, cx);
9020
9021                state.undo(&Undo, window, cx);
9022                assert_eq!(state.value(), "abc");
9023                assert_eq!(state.selected_range(), 1..1);
9024            });
9025        });
9026    }
9027
9028    #[wgpui::test]
9029    fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
9030        let input_view = InputView::build(cx, |state| state);
9031        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9032        let input = input_view.input;
9033
9034        cx.update(|window, cx| {
9035            input.update(cx, |state, cx| {
9036                state.replace_text_in_range(None, "ab", window, cx);
9037                state.undo(&Undo, window, cx);
9038                state.set_selected_range(0..0, cx);
9039                state.redo(&Redo, window, cx);
9040                assert_eq!(state.value(), "ab");
9041
9042                state.undo(&Undo, window, cx);
9043                state.replace_text_in_range(None, "x", window, cx);
9044                state.redo(&Redo, window, cx);
9045                assert_eq!(state.value(), "x");
9046            });
9047        });
9048    }
9049
9050    #[wgpui::test]
9051    fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
9052        let input_view = InputView::build(cx, |state| state);
9053        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9054        let input = input_view.input;
9055
9056        cx.update(|window, cx| {
9057            input.update(cx, |state, cx| {
9058                state.replace_text_in_range(None, "a", window, cx);
9059                state.move_to(0, None, cx);
9060                state.replace_text_in_range(None, "", window, cx);
9061                state.undo(&Undo, window, cx);
9062                assert_eq!(state.value(), "");
9063                state.redo(&Redo, window, cx);
9064                assert_eq!(state.value(), "a");
9065                assert_eq!(state.cursor(), 1);
9066            });
9067        });
9068    }
9069
9070    #[wgpui::test]
9071    fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
9072        let input_view = InputView::build(cx, |state| state);
9073        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9074        let input = input_view.input;
9075
9076        cx.update(|window, cx| {
9077            input.update(cx, |state, cx| {
9078                state.replace_text_in_range(None, "a", window, cx);
9079                state.left(&MoveLeft, window, cx);
9080                state.right(&MoveRight, window, cx);
9081                state.replace_text_in_range(None, "b", window, cx);
9082
9083                state.undo(&Undo, window, cx);
9084                assert_eq!(state.value(), "a");
9085                state.undo(&Undo, window, cx);
9086                assert_eq!(state.value(), "");
9087            });
9088        });
9089    }
9090
9091    #[wgpui::test]
9092    fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
9093        cx: &mut TestAppContext,
9094    ) {
9095        let input_view = InputView::build(cx, |state| state);
9096        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9097        let input = input_view.input;
9098
9099        cx.update(|window, cx| {
9100            input.update(cx, |state, cx| {
9101                state.replace_text_in_range(None, "alpha", window, cx);
9102                state.replace_text_in_range(None, "", window, cx);
9103                state.replace_text_in_range(None, "beta", window, cx);
9104                assert_eq!(state.value(), "alphabeta");
9105
9106                state.undo(&Undo, window, cx);
9107                assert_eq!(state.value(), "alpha");
9108                state.undo(&Undo, window, cx);
9109                assert_eq!(state.value(), "");
9110            });
9111        });
9112    }
9113
9114    #[wgpui::test]
9115    fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
9116        let input_view = InputView::build(cx, |state| {
9117            state.mask_pattern(MaskPattern::Number {
9118                separator: Some(','),
9119                fraction: None,
9120            })
9121        });
9122        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9123        let input = input_view.input;
9124
9125        cx.update(|window, cx| {
9126            input.update(cx, |state, cx| {
9127                state.set_value("12345", window, cx);
9128                state.set_selected_range(2..2, cx);
9129                state.replace_text_in_range(None, "9", window, cx);
9130                let selection_after_edit = state.selected_range();
9131                assert_ne!(selection_after_edit.end, state.value().len());
9132
9133                state.undo(&Undo, window, cx);
9134                state.redo(&Redo, window, cx);
9135                assert_eq!(state.selected_range(), selection_after_edit);
9136            });
9137        });
9138    }
9139
9140    /// Unfolding at a position opens exactly the folds hiding it.
9141    ///
9142    /// A fold keeps its own first and last line visible, so a position on
9143    /// either of them opens nothing. Nested folds all open at once, sibling
9144    /// folds stay closed, and the opened ranges stay fold candidates.
9145    #[wgpui::test]
9146    fn test_unfold_at(cx: &mut TestAppContext) {
9147        use crate::input::{FoldRange, Position};
9148
9149        let view = InputView::<EditorMode>::new(cx);
9150        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9151        let input = view.input;
9152
9153        // An outer fold over lines 0..=5, a fold nested inside it, and a
9154        // sibling fold that must never be touched.
9155        cx.update(|window, cx| {
9156            input.update(cx, |state, cx| {
9157                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
9158                state.apply_highlighter_fold_candidates(
9159                    vec![
9160                        FoldRange::new(0, 5),
9161                        FoldRange::new(2, 4),
9162                        FoldRange::new(7, 10),
9163                    ],
9164                    cx,
9165                );
9166                state.display_map.set_folded(0, true);
9167                state.display_map.set_folded(2, true);
9168                state.display_map.set_folded(7, true);
9169            });
9170        });
9171
9172        // The outer fold's own first and last line stay visible, so neither
9173        // position opens anything.
9174        for line in [0, 5] {
9175            cx.update(|_, cx| {
9176                input.update(cx, |state, cx| {
9177                    assert!(!state.display_map.is_buffer_line_hidden(line));
9178                    assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
9179                });
9180                input.read_with(cx, |state, _| {
9181                    assert!(state.display_map.is_folded_at(0));
9182                    assert!(state.display_map.is_folded_at(2));
9183                    assert!(state.display_map.is_folded_at(7));
9184                });
9185            });
9186        }
9187
9188        // Line 3 is hidden by both the outer and the nested fold, so both
9189        // open; the sibling fold does not.
9190        cx.update(|_, cx| {
9191            input.update(cx, |state, cx| {
9192                assert!(state.unfold_at(Position::new(3, 0), cx));
9193            });
9194            input.read_with(cx, |state, _| {
9195                assert!(!state.display_map.is_buffer_line_hidden(3));
9196                assert!(!state.display_map.is_folded_at(0));
9197                assert!(!state.display_map.is_folded_at(2));
9198                assert!(state.display_map.is_folded_at(7));
9199                // The opened ranges are still candidates for refolding.
9200                assert!(state.display_map.is_fold_candidate(0));
9201                assert!(state.display_map.is_fold_candidate(2));
9202            });
9203        });
9204
9205        // Nothing is hidden there any more, so a second call is a no-op.
9206        cx.update(|_, cx| {
9207            input.update(cx, |state, cx| {
9208                assert!(!state.unfold_at(Position::new(3, 0), cx));
9209            });
9210        });
9211    }
9212
9213    /// Losing focus hides the hover popover but keeps the decorations.
9214    ///
9215    /// Both used to be dropped by one call, so clicking away threw away
9216    /// decorations the application had installed and never asked to remove.
9217    #[wgpui::test]
9218    fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
9219        let view = InputView::<EditorMode>::new(cx);
9220        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9221        let input = view.input;
9222
9223        cx.update(|window, cx| {
9224            input.update(cx, |state, cx| {
9225                state.set_value("select 1", window, cx);
9226                let _collection = state.create_decorations_collection(
9227                    vec![crate::input::TextDecoration::new(
9228                        0..6,
9229                        wgpui::HighlightStyle {
9230                            font_weight: Some(wgpui::FontWeight::BOLD),
9231                            ..Default::default()
9232                        },
9233                    )],
9234                    cx,
9235                );
9236                state.present_hover(
9237                    0..6,
9238                    lsp_types::Hover {
9239                        contents: lsp_types::HoverContents::Scalar(
9240                            lsp_types::MarkedString::String("docs".into()),
9241                        ),
9242                        range: None,
9243                    },
9244                    cx,
9245                );
9246                assert!(state.hover_popover().is_some());
9247
9248                state.on_blur(window, cx);
9249
9250                assert!(
9251                    state.hover_popover().is_none(),
9252                    "blur should hide the hover popover"
9253                );
9254                let decorations = state.extras.decoration_layers();
9255                assert!(
9256                    decorations.iter().any(|layer| !layer.is_empty()),
9257                    "blur must not discard decorations"
9258                );
9259            });
9260        });
9261    }
9262
9263    /// The mode marker is the only source of truth for the kind of input.
9264    ///
9265    /// An auto-growing textarea capped at one row used to report itself as
9266    /// single-line, because the answer was derived from the row counts.
9267    #[wgpui::test]
9268    fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
9269        let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
9270        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9271        view.input.read_with(&mut cx, |state, _| {
9272            assert!(state.is_multi_line());
9273            assert!(!state.is_single_line());
9274            assert!(!state.is_code_editor());
9275        });
9276    }
9277
9278    #[wgpui::test]
9279    fn test_textarea_prewrap_prepares_content_rows_before_layout(cx: &mut TestAppContext) {
9280        cx.update(crate::init);
9281        for (value, expected_rows) in [("", 1), ("one\ntwo", 2)] {
9282            cx.open_window(size(px(400.), px(100.)), |window, cx| {
9283                let font = window.text_style().font();
9284                cx.new(|cx| {
9285                    let mut state = crate::input::TextareaState::new(window, cx)
9286                        .rows(12)
9287                        .default_value(value);
9288                    assert_eq!(state.display_map().wrap_row_count(), 0);
9289                    state.prewrap(font, px(14.), px(120.), cx);
9290                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
9291                    assert_eq!(state.value(), value);
9292                    state
9293                });
9294                wgpui::EmptyView
9295            });
9296        }
9297    }
9298
9299    #[wgpui::test]
9300    fn test_textarea_prewrap_respects_soft_wrap_before_layout(cx: &mut TestAppContext) {
9301        cx.update(crate::init);
9302        let value = "select id, name, email, phone from users where active\nlimit 10";
9303        for soft_wrap in [true, false] {
9304            cx.open_window(size(px(400.), px(100.)), |window, cx| {
9305                let font = window.text_style().font();
9306                cx.new(|cx| {
9307                    let mut state = crate::input::TextareaState::new(window, cx)
9308                        .rows(1)
9309                        .soft_wrap(soft_wrap)
9310                        .default_value(value);
9311                    state.prewrap(font, px(14.), px(120.), cx);
9312                    let rows = state.display_map().wrap_row_count();
9313                    if soft_wrap {
9314                        assert!(rows > 2, "the first logical line must wrap");
9315                    } else {
9316                        assert_eq!(rows, 2);
9317                    }
9318                    assert_eq!(state.value(), value);
9319                    state
9320                });
9321                wgpui::EmptyView
9322            });
9323        }
9324    }
9325
9326    #[wgpui::test]
9327    fn test_prewrap_counts_wrapped_rows_before_the_first_paint(cx: &mut TestAppContext) {
9328        cx.update(crate::init);
9329        let text = "select id, name, email, phone from users where active\nlimit 10";
9330        for (soft_wrap, wraps) in [(true, true), (false, false)] {
9331            let mut input = None;
9332            cx.open_window(size(px(400.), px(100.)), |window, cx| {
9333                let font = window.text_style().font();
9334                let editor = cx.new(|cx| {
9335                    let mut state = crate::input::EditorState::new(window, cx)
9336                        .soft_wrap(soft_wrap)
9337                        .default_value(text);
9338                    state.prewrap(font, px(14.), px(120.), cx);
9339                    state
9340                });
9341                input = Some(editor);
9342                wgpui::EmptyView
9343            });
9344            let rows = input
9345                .unwrap()
9346                .read_with(cx, |state, _| state.display_map().wrap_row_count());
9347            // Two lines; at 120px the first wraps unless soft wrap is off.
9348            assert_eq!(rows > 2, wraps, "soft_wrap({soft_wrap}): {rows} rows");
9349            if !wraps {
9350                assert_eq!(rows, 2);
9351            }
9352        }
9353    }
9354
9355    #[wgpui::test]
9356    fn test_prewrap_uses_the_configured_tab_stops(cx: &mut TestAppContext) {
9357        cx.update(crate::init);
9358        cx.open_window(size(px(400.), px(100.)), |window, cx| {
9359            let font = window.text_style().font();
9360            let font_size = px(14.);
9361            let font_id = window.text_system().resolve_font(&font);
9362            let space_width = window.text_system().layout_width(font_id, font_size, ' ');
9363            cx.new(|cx| {
9364                let mut state = crate::input::EditorState::new(window, cx)
9365                    .tab_size(TabSize {
9366                        tab_size: 4,
9367                        hard_tabs: true,
9368                    })
9369                    .default_value("\t\t");
9370                for (tab_size, expected_rows) in [(4, 2), (2, 1), (8, 2)] {
9371                    state.set_tab_size(
9372                        TabSize {
9373                            tab_size,
9374                            hard_tabs: true,
9375                        },
9376                        cx,
9377                    );
9378                    state.prewrap(font.clone(), font_size, space_width * 5. + RIGHT_MARGIN, cx);
9379                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
9380                }
9381                state
9382            });
9383            wgpui::EmptyView
9384        });
9385    }
9386
9387    /// Prewrap counts with the state's wrapping indent, as the first layout
9388    /// does: continuation rows indented as deep as their line take more rows.
9389    #[wgpui::test]
9390    fn test_prewrap_wraps_with_the_wrapping_indent(cx: &mut TestAppContext) {
9391        cx.update(crate::init);
9392        let text = "            select id, name, email, phone from users where active";
9393        let mut rows = Vec::new();
9394        for indent in [WrappingIndent::Same, WrappingIndent::None] {
9395            let mut input = None;
9396            cx.open_window(size(px(400.), px(100.)), |window, cx| {
9397                let font = window.text_style().font();
9398                input = Some(cx.new(|cx| {
9399                    let mut state = crate::input::EditorState::new(window, cx)
9400                        .wrapping_indent(indent)
9401                        .default_value(text);
9402                    state.prewrap(font, px(14.), px(200.), cx);
9403                    state
9404                }));
9405                wgpui::EmptyView
9406            });
9407            rows.push(
9408                input
9409                    .unwrap()
9410                    .read_with(cx, |state, _| state.display_map().wrap_row_count()),
9411            );
9412        }
9413        assert!(rows[0] > rows[1], "rows with Same, None: {rows:?}");
9414    }
9415
9416    /// Once the editor is laid out, layout owns the wrap and prewrap leaves it.
9417    #[wgpui::test]
9418    fn test_prewrap_does_nothing_once_laid_out(cx: &mut TestAppContext) {
9419        struct Frame(Entity<crate::input::EditorState>);
9420        impl Render for Frame {
9421            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9422                crate::input::InputBase::new("frame")
9423                    .h(px(100.))
9424                    .child(crate::input::Editor::new(&self.0))
9425            }
9426        }
9427
9428        cx.update(crate::init);
9429        let text = "select id, name, email, phone from users where active\nlimit 10";
9430        let mut input = None;
9431        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
9432            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
9433            input = Some(state.clone());
9434            Frame(state)
9435        });
9436        let input = input.unwrap();
9437        let mut cx = VisualTestContext::from_window(window.into(), cx);
9438        cx.update(|window, cx| window.draw(cx).clear());
9439
9440        let laid_out = input.read_with(&cx, |state, _| state.display_map().wrap_row_count());
9441        assert!(laid_out >= 2, "laid out to {laid_out} rows");
9442        let font = cx.update(|window, _| window.text_style().font());
9443        input.update(&mut cx, |state, cx| {
9444            state.prewrap(font, px(14.), px(60.), cx)
9445        });
9446        assert_eq!(
9447            input.read_with(&cx, |state, _| state.display_map().wrap_row_count()),
9448            laid_out
9449        );
9450    }
9451
9452    /// Soft wrap is on by default, for every mode that can wrap.
9453    ///
9454    /// The default lives in the shared constructor, where a mode-specific
9455    /// `new` can silently fail to restore it; this pins it down.
9456    #[wgpui::test]
9457    fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
9458        let textarea = InputView::build_textarea(cx, |state| state);
9459        let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
9460        textarea
9461            .input
9462            .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
9463
9464        let editor = InputView::<EditorMode>::new(cx);
9465        let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
9466        editor
9467            .input
9468            .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
9469    }
9470
9471    /// Parse a cursor spec into `(text, cursor_offsets)`. Non-empty lines are
9472    /// joined with `\n` plus a trailing `\n`. `|` marks a cursor. Leading
9473    /// whitespace is kept, so a spec can express indentation.
9474    fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
9475        let mut full_text = String::new();
9476        let mut cursor_offsets = Vec::new();
9477        let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
9478
9479        for (line_idx, line) in non_empty_lines.iter().enumerate() {
9480            let mut positions = Vec::new();
9481            let mut text = String::new();
9482            for ch in line.chars() {
9483                if ch == '|' {
9484                    positions.push(text.len());
9485                } else {
9486                    text.push(ch);
9487                }
9488            }
9489
9490            if line_idx > 0 {
9491                full_text.push('\n');
9492            }
9493            let line_start = full_text.len();
9494            for pos in positions {
9495                cursor_offsets.push(line_start + pos);
9496            }
9497            full_text.push_str(&text);
9498        }
9499        full_text.push('\n');
9500
9501        (full_text, cursor_offsets)
9502    }
9503
9504    /// Build a multi-line input for multi-cursor tests.
9505    fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
9506        InputView::build_textarea(cx, |state| state)
9507    }
9508
9509    /// Set the text and cursor positions from a spec (see [`parse_cursor_spec`]).
9510    fn setup_cursors<M: InputModeKind>(
9511        cx: &mut VisualTestContext,
9512        input: &Entity<InputBaseState<M>>,
9513        spec: &str,
9514    ) {
9515        let (full_text, offsets) = parse_cursor_spec(spec);
9516        cx.update(|window, cx| {
9517            input.update(cx, |state, cx| {
9518                state.set_value(&full_text, window, cx);
9519                let selections = offsets
9520                    .into_iter()
9521                    .map(|offset| {
9522                        CursorSelection::new(state.selections.generate_id(), offset, offset)
9523                    })
9524                    .collect();
9525                state.selections.replace_all(selections);
9526                cx.notify();
9527            });
9528        });
9529    }
9530
9531    /// Assert the text and cursor positions match a spec.
9532    #[track_caller]
9533    fn assert_cursors<M: InputModeKind>(
9534        cx: &mut VisualTestContext,
9535        input: &Entity<InputBaseState<M>>,
9536        spec: &str,
9537    ) {
9538        let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
9539        expected_cursors.sort();
9540
9541        let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
9542            (
9543                state.text.to_string(),
9544                state
9545                    .selections
9546                    .iter()
9547                    .map(|s| s.cursor_offset())
9548                    .collect::<Vec<_>>(),
9549            )
9550        });
9551        actual_cursors.sort();
9552
9553        assert_eq!(
9554            actual_text, expected_text,
9555            "Text mismatch:\nExpected: {expected_text:?}\nActual:   {actual_text:?}"
9556        );
9557        assert_eq!(
9558            actual_cursors, expected_cursors,
9559            "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual:   {actual_cursors:?}"
9560        );
9561    }
9562
9563    #[wgpui::test]
9564    fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
9565        cx.update(crate::init);
9566        let view = InputView::<EditorMode>::new(cx);
9567        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9568        for modifiers in [
9569            wgpui::Modifiers {
9570                alt: true,
9571                ..Default::default()
9572            },
9573            wgpui::Modifiers {
9574                alt: true,
9575                shift: true,
9576                ..Default::default()
9577            },
9578            #[cfg(target_os = "linux")]
9579            wgpui::Modifiers {
9580                alt: true,
9581                control: true,
9582                ..Default::default()
9583            },
9584        ] {
9585            setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
9586            cx.update(|window, cx| {
9587                view.input.update(cx, |state, cx| state.focus(window, cx));
9588            });
9589            let (start, end) = view.input.read_with(&cx, |state, _| {
9590                let layout = state.last_layout.as_ref().unwrap();
9591                let origin = state.last_bounds.unwrap().origin;
9592                let position = |row: usize, col| {
9593                    let local = layout.lines[row]
9594                        .position_for_index(col, layout, false)
9595                        .unwrap();
9596                    origin
9597                        + point(
9598                            layout.line_number_width + local.x,
9599                            layout.line_height * (row as f32 + 0.5),
9600                        )
9601                };
9602                (position(0, 1), position(2, 3))
9603            });
9604            // Land inside the third column instead of exactly on its trailing
9605            // glyph boundary, where pixel rounding can select the next column.
9606            let end = point(end.x - px(0.5), end.y);
9607            // A cached Ctrl-hover definition must not steal a column gesture.
9608            cx.update(|_, cx| {
9609                view.input.update(cx, |state, _| {
9610                    state.extras.hover_definition.update(
9611                        0..4,
9612                        vec![lsp_types::LocationLink {
9613                            origin_selection_range: None,
9614                            target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
9615                            target_range: Default::default(),
9616                            target_selection_range: Default::default(),
9617                        }],
9618                    );
9619                });
9620            });
9621            cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
9622            cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
9623            cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
9624            view.input.read_with(&cx, |state, _| {
9625                let ranges: Vec<_> = state
9626                    .selections
9627                    .iter()
9628                    .map(|sel| sel.start..sel.end)
9629                    .collect();
9630                assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
9631            });
9632            // Moving after release must leave the block intact.
9633            cx.simulate_mouse_move(start, None, modifiers);
9634            cx.simulate_keystrokes("x");
9635            assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
9636        }
9637    }
9638
9639    #[wgpui::test]
9640    fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
9641        cx.update(crate::init);
9642        let view = InputView::<EditorMode>::new(cx);
9643        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9644        setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
9645        cx.update(|window, cx| {
9646            view.input.update(cx, |state, cx| state.focus(window, cx));
9647        });
9648        let (start, end) = view.input.read_with(&cx, |state, _| {
9649            let layout = state.last_layout.as_ref().unwrap();
9650            let origin = state.last_bounds.unwrap().origin;
9651            let local = layout.lines[0]
9652                .position_for_index(1, layout, false)
9653                .unwrap();
9654            let x = layout.line_number_width + local.x;
9655            (
9656                origin + point(x, layout.line_height * 2.5),
9657                origin + point(x, layout.line_height * 0.5),
9658            )
9659        });
9660        let modifiers = wgpui::Modifiers {
9661            alt: true,
9662            ..Default::default()
9663        };
9664        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
9665        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
9666        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
9667        assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
9668    }
9669
9670    #[wgpui::test]
9671    fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
9672        cx.update(crate::init);
9673        let view = InputView::<EditorMode>::new(cx);
9674        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9675        setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
9676        cx.update(|window, cx| {
9677            view.input.update(cx, |state, cx| state.focus(window, cx));
9678        });
9679        // Drag from row 0 column 1 down to row 1, at the x of row 0's column 5. Row 1
9680        // only has two characters, so the pointer ends past its end.
9681        let (start, end) = view.input.read_with(&cx, |state, _| {
9682            let layout = state.last_layout.as_ref().unwrap();
9683            let origin = state.last_bounds.unwrap().origin;
9684            let x_of = |index| {
9685                layout.line_number_width
9686                    + layout.lines[0]
9687                        .position_for_index(index, layout, false)
9688                        .unwrap()
9689                        .x
9690            };
9691            (
9692                origin + point(x_of(1), layout.line_height * 0.5),
9693                origin + point(x_of(5), layout.line_height * 1.5),
9694            )
9695        });
9696        let modifiers = wgpui::Modifiers {
9697            alt: true,
9698            shift: true,
9699            ..Default::default()
9700        };
9701        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
9702        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
9703        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
9704
9705        // The short row is clipped to its own end; the long row keeps the full span.
9706        view.input.read_with(&cx, |state, _| {
9707            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
9708            assert_eq!(ranges, vec![(1, 5), (8, 9)]);
9709        });
9710    }
9711
9712    #[wgpui::test]
9713    fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
9714        cx.update(crate::init);
9715        let view = InputView::<EditorMode>::new(cx);
9716        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9717        setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
9718        let position = view.input.read_with(&cx, |state, _| {
9719            let layout = state.last_layout.as_ref().unwrap();
9720            state.last_bounds.unwrap().origin
9721                + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
9722        });
9723        let modifiers = wgpui::Modifiers {
9724            alt: true,
9725            ..Default::default()
9726        };
9727        cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
9728        cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
9729        view.input.read_with(&cx, |state, _| {
9730            assert!(!state.selecting);
9731            assert!(state.column_select_start.is_none());
9732        });
9733    }
9734
9735    #[wgpui::test]
9736    fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
9737        let view = InputView::<EditorMode>::new(cx);
9738        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9739        setup_cursors(&mut cx, &view.input, "a|b");
9740        cx.update(|window, cx| {
9741            view.input.update(cx, |state, cx| {
9742                state.focus(window, cx);
9743                state.pause_blink_cursor(cx);
9744            });
9745        });
9746        cx.run_until_parked();
9747        cx.executor()
9748            .advance_clock(std::time::Duration::from_millis(300));
9749        cx.run_until_parked();
9750        view.input.read_with(&cx, |state, cx| {
9751            assert!(!state.blink_cursor.read(cx).visible());
9752        });
9753        // Copy consumes its shortcut without editing text or moving selections.
9754        for _ in 0..5 {
9755            #[cfg(target_os = "macos")]
9756            cx.simulate_keystrokes("cmd-c");
9757            #[cfg(not(target_os = "macos"))]
9758            cx.simulate_keystrokes("ctrl-c");
9759            cx.run_until_parked();
9760            cx.executor()
9761                .advance_clock(std::time::Duration::from_millis(200));
9762            cx.run_until_parked();
9763            view.input.read_with(&cx, |state, cx| {
9764                assert!(state.blink_cursor.read(cx).visible());
9765            });
9766        }
9767    }
9768
9769    #[wgpui::test]
9770    fn test_mouse_down_shows_cursor_like_a_cursor_move(cx: &mut TestAppContext) {
9771        cx.update(crate::init);
9772        let view = InputView::<EditorMode>::new(cx);
9773        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9774        setup_cursors(&mut cx, &view.input, "abcd|efgh");
9775        let position = |offset: Pixels, cx: &mut VisualTestContext| {
9776            view.input.read_with(cx, |state, _| {
9777                let layout = state.last_layout.as_ref().unwrap();
9778                state.last_bounds.unwrap().origin
9779                    + point(layout.line_number_width + offset, layout.line_height * 0.5)
9780            })
9781        };
9782        let visible = |cx: &mut VisualTestContext| {
9783            view.input
9784                .read_with(cx, |state, cx| state.blink_cursor.read(cx).visible())
9785        };
9786
9787        // The press itself shows the caret, without waiting for the focus
9788        // observer, and the idle delay holds it there like a cursor move.
9789        let first = position(px(2.), &mut cx);
9790        cx.simulate_mouse_down(first, MouseButton::Left, Default::default());
9791        assert!(visible(&mut cx));
9792        cx.simulate_mouse_up(first, MouseButton::Left, Default::default());
9793        cx.run_until_parked();
9794
9795        // Pressing elsewhere in the focused input, in the hidden phase of the
9796        // blink, shows the caret again at the press.
9797        cx.executor()
9798            .advance_clock(std::time::Duration::from_millis(400));
9799        cx.run_until_parked();
9800        assert!(!visible(&mut cx));
9801        let second = position(px(30.), &mut cx);
9802        cx.simulate_mouse_down(second, MouseButton::Left, Default::default());
9803        assert!(visible(&mut cx));
9804        cx.executor()
9805            .advance_clock(std::time::Duration::from_millis(250));
9806        cx.run_until_parked();
9807        assert!(visible(&mut cx));
9808        cx.simulate_mouse_up(second, MouseButton::Left, Default::default());
9809    }
9810
9811    #[wgpui::test]
9812    fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
9813        let view = InputView::<EditorMode>::new(cx);
9814        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9815        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
9816        // Start each action in the hidden phase without depending on a
9817        // key-down listener: actions and text input also arrive directly.
9818        for action in 0..6 {
9819            cx.update(|_, cx| {
9820                view.input.update(cx, |state, cx| {
9821                    state.blink_cursor = cx.new(|_| BlinkCursor::new());
9822                    state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
9823                });
9824            });
9825            cx.run_until_parked();
9826            cx.executor()
9827                .advance_clock(std::time::Duration::from_millis(500));
9828            cx.run_until_parked();
9829            view.input.read_with(&cx, |state, cx| {
9830                assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
9831            });
9832
9833            cx.update(|window, cx| {
9834                view.input.update(cx, |state, cx| {
9835                    match action {
9836                        0 => state.add_cursor_above(&AddCursorAbove, window, cx),
9837                        1 => state.add_cursor_below(&AddCursorBelow, window, cx),
9838                        2 => state.select_up(&SelectUp, window, cx),
9839                        3 => state.select_down(&SelectDown, window, cx),
9840                        4 => state.replace_text_in_range(None, "x", window, cx),
9841                        _ => state.backspace(&Backspace, window, cx),
9842                    }
9843                    assert!(state.blink_cursor.read(cx).visible(), "action {action}");
9844                });
9845            });
9846        }
9847    }
9848
9849    #[wgpui::test]
9850    fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
9851        let view = InputView::<EditorMode>::new(cx);
9852        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9853        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
9854        cx.update(|window, cx| {
9855            view.input.update(cx, |state, cx| state.focus(window, cx));
9856        });
9857        #[cfg(target_os = "macos")]
9858        cx.simulate_keystrokes("cmd-alt-up");
9859        #[cfg(target_os = "windows")]
9860        cx.simulate_keystrokes("ctrl-alt-up");
9861        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
9862        cx.simulate_keystrokes("alt-shift-up");
9863        view.input
9864            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
9865        #[cfg(target_os = "macos")]
9866        cx.simulate_keystrokes("cmd-alt-down");
9867        #[cfg(target_os = "windows")]
9868        cx.simulate_keystrokes("ctrl-alt-down");
9869        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
9870        cx.simulate_keystrokes("alt-shift-down");
9871        view.input
9872            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
9873        cx.simulate_keystrokes("x");
9874        assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
9875    }
9876
9877    #[wgpui::test]
9878    fn test_multi_cursor_platform_word_selection_dispatch(cx: &mut TestAppContext) {
9879        let view = InputView::<EditorMode>::new(cx);
9880        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9881        setup_cursors(&mut cx, &view.input, "one |two\none |two");
9882        cx.update(|window, cx| {
9883            view.input.update(cx, |state, cx| state.focus(window, cx));
9884        });
9885        #[cfg(any(target_os = "macos", target_os = "linux"))]
9886        cx.simulate_keystrokes("alt-shift-right");
9887        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
9888        cx.simulate_keystrokes("ctrl-shift-right");
9889        cx.simulate_keystrokes("x");
9890        assert_cursors(&mut cx, &view.input, "one x|\none x|");
9891        setup_cursors(&mut cx, &view.input, "one two|\none two|");
9892        #[cfg(any(target_os = "macos", target_os = "linux"))]
9893        cx.simulate_keystrokes("alt-shift-left");
9894        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
9895        cx.simulate_keystrokes("ctrl-shift-left");
9896        cx.simulate_keystrokes("x");
9897        assert_cursors(&mut cx, &view.input, "one x|\none x|");
9898    }
9899
9900    #[cfg(not(target_os = "macos"))]
9901    #[wgpui::test]
9902    fn test_multi_cursor_horizontal_selection_dispatch(cx: &mut TestAppContext) {
9903        let view = InputView::<EditorMode>::new(cx);
9904        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9905        setup_cursors(&mut cx, &view.input, "ab\na|b");
9906        cx.update(|window, cx| {
9907            view.input.update(cx, |state, cx| state.focus(window, cx));
9908        });
9909        #[cfg(target_os = "windows")]
9910        cx.simulate_keystrokes("ctrl-alt-up");
9911        #[cfg(not(target_os = "windows"))]
9912        cx.simulate_keystrokes("alt-shift-up");
9913        #[cfg(target_os = "linux")]
9914        cx.simulate_keystrokes("shift-right");
9915        #[cfg(not(target_os = "linux"))]
9916        cx.simulate_keystrokes("alt-shift-right");
9917        view.input.read_with(&cx, |state, _| {
9918            assert_eq!(
9919                state
9920                    .selections
9921                    .iter()
9922                    .map(|s| s.start..s.end)
9923                    .collect::<Vec<_>>(),
9924                vec![4..5, 1..2]
9925            );
9926        });
9927        #[cfg(target_os = "linux")]
9928        cx.simulate_keystrokes("shift-left shift-left");
9929        #[cfg(not(target_os = "linux"))]
9930        cx.simulate_keystrokes("alt-shift-left alt-shift-left");
9931        view.input.read_with(&cx, |state, _| {
9932            assert_eq!(
9933                state
9934                    .selections
9935                    .iter()
9936                    .map(|s| s.start..s.end)
9937                    .collect::<Vec<_>>(),
9938                vec![3..4, 0..1]
9939            );
9940        });
9941        cx.simulate_keystrokes("x");
9942        assert_cursors(&mut cx, &view.input, "x|b\nx|b");
9943    }
9944
9945    #[wgpui::test]
9946    fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
9947        cx.update(crate::init);
9948        let view = InputView::<EditorMode>::new(cx);
9949        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9950        setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
9951        cx.update(|window, cx| {
9952            view.input.update(cx, |state, cx| state.focus(window, cx));
9953        });
9954        let position = view.input.read_with(&cx, |state, _| {
9955            let bounds = state.last_bounds.unwrap();
9956            let layout = state.last_layout.as_ref().unwrap();
9957            bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
9958        });
9959        cx.simulate_click(
9960            position,
9961            wgpui::Modifiers {
9962                alt: true,
9963                ..Default::default()
9964            },
9965        );
9966        view.input
9967            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
9968    }
9969
9970    #[wgpui::test]
9971    fn test_add_selection(cx: &mut TestAppContext) {
9972        let view = InputView::<EditorMode>::new(cx);
9973        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9974        cx.update(|window, cx| {
9975            view.input.update(cx, |state, cx| {
9976                state.focus(window, cx);
9977                state.set_value("foo bar foo", window, cx);
9978                state.set_selected_range(0..3, cx);
9979                // The programmatic second cursor: the next occurrence.
9980                state.add_selection(8..11, cx);
9981                // Adding a range that is already selected changes nothing.
9982                state.add_selection(0..3, cx);
9983            });
9984        });
9985        view.input.read_with(&cx, |state, _| {
9986            let mut ranges: Vec<Range<usize>> =
9987                state.selections.iter().map(|s| s.start..s.end).collect();
9988            ranges.sort_by_key(|r| r.start);
9989            assert_eq!(ranges, vec![0..3, 8..11]);
9990        });
9991        // Typing replaces every selection at once.
9992        cx.simulate_keystrokes("x");
9993        view.input.read_with(&cx, |state, _| {
9994            assert_eq!(state.text.to_string(), "x bar x")
9995        });
9996    }
9997
9998    #[wgpui::test]
9999    fn test_add_selection_preserves_crlf_boundaries(cx: &mut TestAppContext) {
10000        let view = InputView::build_textarea(cx, |state| state.default_value("a\r\nb"));
10001        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10002        cx.update(|window, cx| {
10003            view.input.update(cx, |state, cx| {
10004                state.focus(window, cx);
10005                state.set_selected_range(4..4, cx);
10006                state.add_selection(2..2, cx);
10007                let ranges: Vec<_> = state.selections.iter().map(|s| s.start..s.end).collect();
10008                assert_eq!(ranges, vec![4..4, 1..1]);
10009            });
10010        });
10011        cx.simulate_keystrokes("x");
10012        view.input.read_with(&cx, |state, _| {
10013            assert_eq!(state.value(), "ax\r\nbx");
10014        });
10015        cx.update(|window, cx| {
10016            view.input.update(cx, |state, cx| {
10017                state.set_value("a\r\nb", window, cx);
10018                state.set_selected_range(4..4, cx);
10019                state.add_selection(2..3, cx);
10020                state.cut(&Cut, window, cx);
10021                assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "\r\n");
10022                assert_eq!(state.value(), "ab");
10023            });
10024        });
10025    }
10026
10027    #[wgpui::test]
10028    fn test_add_selection_merges_overlaps_before_copy_and_cut(cx: &mut TestAppContext) {
10029        let view = InputView::<EditorMode>::new(cx);
10030        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10031        cx.update(|window, cx| {
10032            view.input.update(cx, |state, cx| {
10033                // Cover partial overlaps, a containing range, and a bridge
10034                // between two previously disjoint selections.
10035                for additions in [vec![2..5], vec![0..5], vec![4..5, 2..4]] {
10036                    state.set_value("abcdef", window, cx);
10037                    state.set_selected_range(0..3, cx);
10038                    let active_id = state.active_selection().id;
10039                    for range in additions {
10040                        state.add_selection(range, cx);
10041                    }
10042                    assert_eq!(state.active_selection().id, active_id);
10043                    assert_eq!(state.selected_range(), 0..5);
10044                    assert_eq!(state.selections.len(), 1);
10045                    state.copy(&Copy, window, cx);
10046                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
10047                    state.cut(&Cut, window, cx);
10048                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
10049                    assert_eq!(state.value(), "f");
10050                    state.undo(&Undo, window, cx);
10051                    assert_eq!(state.value(), "abcdef");
10052                    assert_eq!(state.selected_range(), 0..5);
10053                }
10054            });
10055        });
10056    }
10057
10058    #[wgpui::test]
10059    fn test_add_selection_clears_inline_completion(cx: &mut TestAppContext) {
10060        use crate::input::CompletionProvider;
10061        use lsp_types::{
10062            CompletionContext, CompletionResponse, InlineCompletionContext, InlineCompletionItem,
10063            InlineCompletionResponse,
10064        };
10065        use std::time::Duration;
10066        use wgpui::Task;
10067
10068        struct Provider(Rc<Cell<usize>>);
10069
10070        impl CompletionProvider for Provider {
10071            fn is_completion_trigger(&self, _: usize, _: &str, _: &mut App) -> bool {
10072                false
10073            }
10074
10075            fn completions(
10076                &self,
10077                _: &Rope,
10078                _: usize,
10079                _: CompletionContext,
10080                _: &mut Window,
10081                _: &mut App,
10082            ) -> Task<anyhow::Result<CompletionResponse>> {
10083                Task::ready(Ok(CompletionResponse::Array(vec![])))
10084            }
10085
10086            fn inline_completion(
10087                &self,
10088                _: &Rope,
10089                _: usize,
10090                _: InlineCompletionContext,
10091                _: &mut Window,
10092                _: &mut App,
10093            ) -> Task<anyhow::Result<InlineCompletionResponse>> {
10094                self.0.set(self.0.get() + 1);
10095                Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
10096            }
10097        }
10098
10099        let view = InputView::<EditorMode>::new(cx);
10100        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10101        let calls = Rc::new(Cell::new(0));
10102        cx.update(|window, cx| {
10103            view.input.update(cx, |state, cx| {
10104                state.focus(window, cx);
10105                state.set_value("aa\naa", window, cx);
10106                state.set_selected_range(2..2, cx);
10107                state.extras.inline_completion.item = Some(InlineCompletionItem {
10108                    insert_text: "suggestion".into(),
10109                    filter_text: None,
10110                    range: None,
10111                    command: None,
10112                    insert_text_format: None,
10113                });
10114                state.add_selection(5..5, cx);
10115                assert!(!state.has_inline_completion());
10116                state.indent_inline(&IndentInline, window, cx);
10117                assert_eq!(state.value(), "aa  \naa  ");
10118                assert_eq!(state.selections.len(), 2);
10119
10120                // The active cursor stays put, so only canceling the task
10121                // prevents this pending request from fetching a suggestion.
10122                state.set_value("aa\naa", window, cx);
10123                state.set_selected_range(2..2, cx);
10124                state.extras.lsp.completion_provider = Some(Rc::new(Provider(calls.clone())));
10125                state.schedule_inline_completion(window, cx);
10126            });
10127        });
10128        cx.run_until_parked();
10129        cx.update(|_, cx| {
10130            view.input
10131                .update(cx, |state, cx| state.add_selection(5..5, cx));
10132        });
10133        cx.executor().advance_clock(Duration::from_secs(1));
10134        cx.run_until_parked();
10135        assert_eq!(calls.get(), 0);
10136        view.input.read_with(&cx, |state, _| {
10137            assert!(!state.has_inline_completion());
10138            assert_eq!(state.selections.len(), 2);
10139            assert_eq!(state.value(), "aa\naa");
10140        });
10141    }
10142
10143    #[wgpui::test]
10144    fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
10145        let view = multi_line(cx);
10146        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10147        setup_cursors(&mut cx, &view.input, "hello|");
10148        cx.update(|window, cx| {
10149            view.input.update(cx, |state, cx| {
10150                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
10151                state.undo(&Undo, window, cx);
10152                assert_eq!(state.selected_range(), 5..5);
10153            });
10154        });
10155    }
10156
10157    #[wgpui::test]
10158    fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
10159        let view = multi_line(cx);
10160        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10161        setup_cursors(&mut cx, &view.input, "a|b|c");
10162        cx.update(|window, cx| {
10163            view.input.update(cx, |state, cx| {
10164                state.backspace(&Backspace, window, cx);
10165                state.undo(&Undo, window, cx);
10166            });
10167        });
10168        assert_cursors(&mut cx, &view.input, "a|b|c");
10169    }
10170
10171    #[wgpui::test]
10172    fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
10173        let view = InputView::<EditorMode>::new(cx);
10174        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10175        cx.update(|window, cx| {
10176            view.input.update(cx, |state, cx| {
10177                state.set_value("abcdef ".repeat(30), window, cx);
10178                state.display_map.on_layout_changed(Some(px(60.)), cx);
10179                let line = state.display_map.line(0).unwrap();
10180                assert!(line.wrapped_lines.len() > 1);
10181                let boundary = line.wrapped_lines[0].end;
10182                state.move_to_with_affinity(boundary, None, true, cx);
10183                state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
10184                assert_eq!(state.selected_range(), boundary..state.text.len_bytes());
10185            });
10186        });
10187    }
10188
10189    #[wgpui::test]
10190    fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
10191        let view = multi_line(cx);
10192        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10193        setup_cursors(&mut cx, &view.input, "|你好\n|世界");
10194        cx.update(|window, cx| {
10195            view.input.update(cx, |state, cx| {
10196                state.outdent(false, window, cx);
10197                state.outdent(true, window, cx);
10198            });
10199        });
10200        assert_cursors(&mut cx, &view.input, "|你好\n|世界");
10201    }
10202
10203    #[wgpui::test]
10204    fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
10205        let view = multi_line(cx);
10206        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10207        setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
10208        cx.update(|window, cx| {
10209            view.input.update(cx, |state, cx| {
10210                state.build_columnar_selection(
10211                    ColumnarPoint::new(1, 0),
10212                    ColumnarPoint::new(11, 0),
10213                    cx,
10214                );
10215                let text = state.value();
10216                for sel in state.selections.iter() {
10217                    assert!(text.is_char_boundary(sel.start));
10218                    assert!(text.is_char_boundary(sel.end));
10219                }
10220                state.replace_text_in_range(None, "X", window, cx);
10221            });
10222        });
10223    }
10224
10225    #[wgpui::test]
10226    fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
10227        let view = InputView::<EditorMode>::new(cx);
10228        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10229        cx.update(|window, cx| {
10230            view.input.update(cx, |state, cx| {
10231                state.set_value("abc def", window, cx);
10232                state.create_decorations_collection(
10233                    vec![crate::input::TextDecoration::new(
10234                        4..7,
10235                        wgpui::HighlightStyle::default(),
10236                    )],
10237                    cx,
10238                );
10239                state.set_selected_range(0..0, cx);
10240                state.replace_text_in_range(None, "X", window, cx);
10241                let layers = state.extras.decoration_layers();
10242                assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
10243            });
10244        });
10245    }
10246
10247    #[wgpui::test]
10248    fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
10249        let view = InputView::<EditorMode>::new(cx);
10250        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10251        setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
10252        cx.update(|window, cx| {
10253            view.input.update(cx, |state, cx| {
10254                set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
10255                state.backspace(&Backspace, window, cx);
10256            });
10257        });
10258        assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
10259    }
10260
10261    #[wgpui::test]
10262    fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
10263        struct UnexpectedQuery;
10264        impl crate::input::SyntaxContextProvider for UnexpectedQuery {
10265            fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
10266                panic!("ordinary typing must not query syntax");
10267            }
10268        }
10269        let view = InputView::<EditorMode>::new(cx);
10270        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10271        setup_cursors(&mut cx, &view.input, "|");
10272        cx.update(|window, cx| {
10273            view.input.update(cx, |state, cx| {
10274                set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
10275                for c in ["a", "b", "c"] {
10276                    state.replace_text_in_range(None, c, window, cx);
10277                }
10278            });
10279        });
10280        assert_cursors(&mut cx, &view.input, "abc|");
10281    }
10282
10283    #[wgpui::test]
10284    fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
10285        let view = InputView::<EditorMode>::new(cx);
10286        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10287        setup_cursors(&mut cx, &view.input, "|");
10288        cx.update(|window, cx| {
10289            view.input.update(cx, |state, cx| {
10290                for _ in 0..999 {
10291                    state.replace_text_in_range(None, "a", window, cx);
10292                }
10293                state.replace_text_in_range(None, "(", window, cx);
10294                state.undo(&Undo, window, cx);
10295                assert!(!state.text.to_string().contains('('));
10296                assert!(!state.text.to_string().contains(')'));
10297                state.redo(&Redo, window, cx);
10298            });
10299        });
10300        assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
10301    }
10302
10303    #[wgpui::test]
10304    fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
10305        let view = InputView::<EditorMode>::new(cx);
10306        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10307        setup_cursors(&mut cx, &view.input, "// (|)");
10308        cx.update(|window, cx| {
10309            view.input.update(cx, |state, cx| {
10310                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
10311                state.replace_text_in_range(None, ")", window, cx);
10312            });
10313        });
10314        assert_cursors(&mut cx, &view.input, "// ()|)");
10315    }
10316
10317    #[wgpui::test]
10318    fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
10319        let view = InputView::<EditorMode>::new(cx);
10320        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10321        setup_cursors(&mut cx, &view.input, "(a|)");
10322        let before = view.input.read_with(&cx, |state, _| state.text.to_string());
10323        cx.update(|window, cx| {
10324            view.input.update(cx, |state, cx| {
10325                state.replace_text_in_range(Some(2..2), ")", window, cx);
10326            });
10327        });
10328        assert_cursors(&mut cx, &view.input, "(a)|");
10329        cx.update(|window, cx| {
10330            view.input
10331                .update(cx, |state, cx| state.undo(&Undo, window, cx));
10332        });
10333        view.input.read_with(&cx, |state, _| {
10334            assert_eq!(
10335                state.text.to_string(),
10336                before,
10337                "skip must not remove an existing closer on undo"
10338            );
10339        });
10340    }
10341
10342    #[wgpui::test]
10343    fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
10344        let view = InputView::<EditorMode>::new(cx);
10345        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10346        setup_cursors(&mut cx, &view.input, "|");
10347        cx.update(|window, cx| {
10348            view.input.update(cx, |state, cx| {
10349                state.replace_text_in_range(None, "(", window, cx);
10350            });
10351        });
10352        assert_cursors(&mut cx, &view.input, "(|)");
10353        cx.update(|window, cx| {
10354            view.input.update(cx, |state, cx| {
10355                state.undo(&Undo, window, cx);
10356                state.redo(&Redo, window, cx);
10357            });
10358        });
10359        assert_cursors(&mut cx, &view.input, "(|)");
10360    }
10361
10362    #[wgpui::test]
10363    fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
10364        let view = InputView::<EditorMode>::new(cx);
10365        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10366        setup_cursors(&mut cx, &view.input, "{|}");
10367        cx.update(|window, cx| {
10368            view.input.update(cx, |state, cx| {
10369                state.enter(
10370                    &Enter {
10371                        secondary: false,
10372                        shift: false,
10373                    },
10374                    window,
10375                    cx,
10376                );
10377            });
10378        });
10379        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
10380        cx.update(|window, cx| {
10381            view.input.update(cx, |state, cx| {
10382                state.undo(&Undo, window, cx);
10383            });
10384        });
10385        assert_cursors(&mut cx, &view.input, "{|}");
10386        cx.update(|window, cx| {
10387            view.input
10388                .update(cx, |state, cx| state.redo(&Redo, window, cx));
10389        });
10390        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
10391    }
10392
10393    #[wgpui::test]
10394    fn test_auto_close_parens(cx: &mut TestAppContext) {
10395        let view = InputView::<EditorMode>::new(cx);
10396        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10397        setup_cursors(&mut cx, &view.input, "|");
10398        cx.update(|window, cx| {
10399            view.input.update(cx, |state, cx| {
10400                state.replace_text_in_range(None, "(", window, cx);
10401            });
10402        });
10403        assert_cursors(&mut cx, &view.input, "(|)");
10404        // Selection must be collapsed: typing next must insert, not replace.
10405        cx.update(|window, cx| {
10406            view.input.update(cx, |state, cx| {
10407                state.replace_text_in_range(None, "x", window, cx);
10408            });
10409        });
10410        assert_cursors(&mut cx, &view.input, "(x|)");
10411    }
10412
10413    #[wgpui::test]
10414    fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
10415        let view = InputView::<EditorMode>::new(cx);
10416        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10417        setup_cursors(&mut cx, &view.input, "(|)");
10418        cx.update(|window, cx| {
10419            view.input.update(cx, |state, cx| {
10420                state.replace_text_in_range(None, ")", window, cx);
10421            });
10422        });
10423        // No duplicate closer, cursor moves past the existing one.
10424        assert_cursors(&mut cx, &view.input, "()|");
10425        // Selection must be collapsed, not covering blank space.
10426        view.input.read_with(&cx, |state, _| {
10427            assert!(state.active_selection().is_empty());
10428        });
10429    }
10430
10431    #[wgpui::test]
10432    fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
10433        let view = InputView::<EditorMode>::new(cx);
10434        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10435        setup_cursors(&mut cx, &view.input, "don|");
10436        cx.update(|window, cx| {
10437            view.input.update(cx, |state, cx| {
10438                state.replace_text_in_range(None, "'", window, cx);
10439            });
10440        });
10441        // Contraction: no auto-close.
10442        assert_cursors(&mut cx, &view.input, "don'|");
10443    }
10444
10445    #[wgpui::test]
10446    fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
10447        let view = InputView::<EditorMode>::new(cx);
10448        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10449        // Unicode-safe previous-char lookup: must not panic on multi-byte prefix.
10450        // CJK counts as word-like, so no pairing — single quote inserted.
10451        setup_cursors(&mut cx, &view.input, "中|");
10452        cx.update(|window, cx| {
10453            view.input.update(cx, |state, cx| {
10454                state.replace_text_in_range(None, "'", window, cx);
10455            });
10456        });
10457        assert_cursors(&mut cx, &view.input, "中'|");
10458    }
10459
10460    #[wgpui::test]
10461    fn test_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
10462        let view = InputView::<EditorMode>::new(cx);
10463        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10464        // Cursor before existing closing quote: typing `"` skips past it.
10465        setup_cursors(&mut cx, &view.input, "\"hello|\"");
10466        cx.update(|window, cx| {
10467            view.input.update(cx, |state, cx| {
10468                state.replace_text_in_range(None, "\"", window, cx);
10469            });
10470        });
10471        assert_cursors(&mut cx, &view.input, "\"hello\"|");
10472        view.input.read_with(&cx, |state, _| {
10473            assert!(state.active_selection().is_empty());
10474        });
10475    }
10476
10477    #[wgpui::test]
10478    fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
10479        let view = InputView::<EditorMode>::new(cx);
10480        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10481        // UTF-16 conversion: deleting `()` after CJK must not touch neighbors.
10482        setup_cursors(&mut cx, &view.input, "中(|)abc");
10483        cx.update(|window, cx| {
10484            view.input
10485                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
10486        });
10487        assert_cursors(&mut cx, &view.input, "中|abc");
10488    }
10489
10490    #[wgpui::test]
10491    fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
10492        let view = InputView::<EditorMode>::new(cx);
10493        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10494        setup_cursors(&mut cx, &view.input, "{|}");
10495        cx.update(|window, cx| {
10496            view.input.update(cx, |state, cx| {
10497                state.set_smart_indent(false, window, cx);
10498                state.enter(
10499                    &Enter {
10500                        secondary: false,
10501                        shift: false,
10502                    },
10503                    window,
10504                    cx,
10505                );
10506            });
10507        });
10508        // Smart indent controls both structural splitting and extra indentation.
10509        assert_cursors(&mut cx, &view.input, "{\n|}");
10510    }
10511
10512    #[wgpui::test]
10513    fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
10514        let view = InputView::<EditorMode>::new(cx);
10515        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10516        setup_cursors(&mut cx, &view.input, "{|}");
10517        cx.update(|window, cx| {
10518            view.input.update(cx, |state, cx| {
10519                state.set_auto_close(false, window, cx);
10520                state.enter(
10521                    &Enter {
10522                        secondary: false,
10523                        shift: false,
10524                    },
10525                    window,
10526                    cx,
10527                );
10528            });
10529        });
10530        // Disabling automatic insertion does not disable structural indentation.
10531        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
10532    }
10533
10534    #[wgpui::test]
10535    fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
10536        use crate::input::{AutoClosingPair, set_language_config};
10537        let view = InputView::<EditorMode>::new(cx);
10538        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10539        cx.update(|window, cx| {
10540            set_language_config(
10541                "alpha",
10542                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
10543                cx,
10544            );
10545            set_language_config(
10546                "beta",
10547                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
10548                cx,
10549            );
10550            let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
10551            let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
10552            first.update(cx, |state, cx| {
10553                state.replace_text_in_range(None, "«", window, cx);
10554                assert_eq!(state.text().to_string(), "«»");
10555                state.set_value("", window, cx);
10556                state.set_smart_indent(false, window, cx);
10557                state.set_highlighter("beta", cx);
10558                assert!(!state.mode.is_smart_indent());
10559                state.replace_text_in_range(None, "‹", window, cx);
10560                assert_eq!(state.text().to_string(), "‹›");
10561                state.set_value("", window, cx);
10562                state.set_highlighter("unknown", cx);
10563                state.replace_text_in_range(None, "(", window, cx);
10564                assert_eq!(state.text().to_string(), "()");
10565            });
10566            second.update(cx, |state, cx| {
10567                state.replace_text_in_range(None, "‹", window, cx);
10568                assert_eq!(state.text().to_string(), "‹›");
10569            });
10570        });
10571    }
10572
10573    #[wgpui::test]
10574    fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
10575        use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
10576        struct StringLanguages(Rc<Cell<usize>>);
10577        impl LanguageProvider for StringLanguages {
10578            fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
10579                self.0.set(self.0.get() + 1);
10580                Some(Rc::new(StringAllProvider))
10581            }
10582        }
10583        struct CodeLanguages;
10584        impl LanguageProvider for CodeLanguages {}
10585        let view = InputView::<EditorMode>::new(cx);
10586        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10587        cx.update(|window, cx| {
10588            let creations = Rc::new(Cell::new(0));
10589            set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
10590            view.input.update(cx, |state, cx| {
10591                state.replace_text_in_range(None, "(", window, cx);
10592                state.replace_text_in_range(None, "[", window, cx);
10593                assert_eq!(state.text().to_string(), "([");
10594                assert_eq!(
10595                    creations.get(),
10596                    1,
10597                    "retain the document provider between edits"
10598                );
10599            });
10600            set_language_provider(Rc::new(CodeLanguages), cx);
10601            view.input.update(cx, |state, cx| {
10602                state.replace_text_in_range(None, "{", window, cx);
10603                assert_eq!(state.text().to_string(), "([{}");
10604            });
10605        });
10606    }
10607
10608    #[wgpui::test]
10609    fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
10610        use crate::input::{AutoClosingPair, set_language_config};
10611        let view = InputView::<EditorMode>::new(cx);
10612        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10613        setup_cursors(&mut cx, &view.input, "|");
10614        cx.update(|window, cx| {
10615            view.input.update(cx, |state, cx| {
10616                state.set_highlighter("CUSTOM", cx);
10617                state.set_auto_close(false, window, cx);
10618                state.set_smart_indent(false, window, cx);
10619            });
10620            set_language_config(
10621                "custom",
10622                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
10623                cx,
10624            );
10625            // Batched registrations must update every affected language.
10626            set_language_config("other", LanguageConfig::default(), cx);
10627            view.input.update(cx, |state, cx| {
10628                assert!(!state.mode.is_auto_close());
10629                assert!(!state.mode.is_smart_indent());
10630                state.set_auto_close(true, window, cx);
10631                state.replace_text_in_range(None, "«", window, cx);
10632            });
10633        });
10634        assert_cursors(&mut cx, &view.input, "«|»");
10635    }
10636
10637    #[wgpui::test]
10638    fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
10639        let view = InputView::<EditorMode>::new(cx);
10640        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10641        setup_cursors(&mut cx, &view.input, "|word");
10642        cx.update(|window, cx| {
10643            view.input.update(cx, |state, cx| {
10644                state.replace_text_in_range(None, "(", window, cx)
10645            });
10646        });
10647        assert_cursors(&mut cx, &view.input, "(|word");
10648        setup_cursors(&mut cx, &view.input, "|word");
10649        cx.update(|window, cx| {
10650            view.input.update(cx, |state, cx| {
10651                crate::input::set_language_config(
10652                    state.language_name(),
10653                    LanguageConfig::default().auto_close_before("w"),
10654                    cx,
10655                );
10656                state.replace_text_in_range(None, "(", window, cx);
10657            });
10658        });
10659        assert_cursors(&mut cx, &view.input, "(|)word");
10660    }
10661
10662    #[wgpui::test]
10663    fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
10664        use crate::input::{AutoClosingPair, SyntaxContext};
10665        let view = InputView::<EditorMode>::new(cx);
10666        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10667        setup_cursors(&mut cx, &view.input, "|");
10668        cx.update(|window, cx| {
10669            view.input.update(cx, |state, cx| {
10670                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
10671                crate::input::set_language_config(
10672                    state.language_name(),
10673                    LanguageConfig::default().auto_closing_pairs([
10674                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
10675                        AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
10676                    ]),
10677                    cx,
10678                );
10679                state.replace_text_in_range(None, "(", window, cx);
10680                state.replace_text_in_range(None, "[", window, cx);
10681            });
10682        });
10683        assert_cursors(&mut cx, &view.input, "([|)");
10684    }
10685
10686    #[wgpui::test]
10687    fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
10688        use crate::input::{AutoClosingPair, SyntaxContext};
10689        struct BlockComment;
10690        impl crate::input::SyntaxContextProvider for BlockComment {
10691            fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
10692                if text.to_string().contains("/*") {
10693                    SyntaxContext::Comment
10694                } else {
10695                    SyntaxContext::Code
10696                }
10697            }
10698        }
10699        let view = InputView::<EditorMode>::new(cx);
10700        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10701        setup_cursors(&mut cx, &view.input, "|");
10702        cx.update(|window, cx| {
10703            view.input.update(cx, |state, cx| {
10704                set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
10705                crate::input::set_language_config(
10706                    state.language_name(),
10707                    LanguageConfig::default()
10708                        .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
10709                            .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
10710                    cx,
10711                );
10712                state.replace_text_in_range(None, "/", window, cx);
10713                state.replace_text_in_range(None, "*", window, cx);
10714            });
10715        });
10716        assert_cursors(&mut cx, &view.input, "/*|*/");
10717        cx.update(|window, cx| {
10718            view.input
10719                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
10720        });
10721        assert_cursors(&mut cx, &view.input, "|");
10722        cx.update(|window, cx| {
10723            view.input.update(cx, |state, cx| {
10724                state.undo(&Undo, window, cx);
10725                state.replace_text_in_range(None, "*", window, cx);
10726                state.replace_text_in_range(None, "/", window, cx);
10727            });
10728        });
10729        assert_cursors(&mut cx, &view.input, "/**/|");
10730    }
10731
10732    #[wgpui::test]
10733    fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
10734        use crate::input::BracketPair;
10735        let view = InputView::<EditorMode>::new(cx);
10736        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10737        setup_cursors(&mut cx, &view.input, "|");
10738        cx.update(|window, cx| {
10739            view.input.update(cx, |state, cx| {
10740                let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
10741                rules.auto_closing_pairs = None;
10742                crate::input::set_language_config(state.language_name(), rules.clone(), cx);
10743                state.replace_text_in_range(None, "«", window, cx);
10744                crate::input::set_language_config(
10745                    state.language_name(),
10746                    rules.auto_closing_pairs([]),
10747                    cx,
10748                );
10749                state.replace_text_in_range(None, "«", window, cx);
10750            });
10751        });
10752        assert_cursors(&mut cx, &view.input, "««|»");
10753    }
10754
10755    #[wgpui::test]
10756    fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
10757        use crate::input::{AutoClosingPair, SyntaxContext};
10758        let view = InputView::<EditorMode>::new(cx);
10759        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10760        setup_cursors(&mut cx, &view.input, "|");
10761        cx.update(|window, cx| {
10762            view.input.update(cx, |state, cx| {
10763                crate::input::set_language_config(
10764                    state.language_name(),
10765                    LanguageConfig::default()
10766                        .auto_closing_pairs([
10767                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
10768                        ]),
10769                    cx,
10770                );
10771                state.replace_text_in_range(None, "/", window, cx);
10772                state.replace_text_in_range(None, "*", window, cx);
10773                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
10774                state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
10775                state.undo(&Undo, window, cx);
10776                state.replace_text_in_range(None, "*", window, cx);
10777                state.replace_text_in_range(None, "/", window, cx);
10778            });
10779        });
10780        assert_cursors(&mut cx, &view.input, "/**/|");
10781    }
10782
10783    #[wgpui::test]
10784    fn test_undo_does_not_promote_literal_comment_delimiters(cx: &mut TestAppContext) {
10785        use crate::input::{AutoClosingPair, SyntaxContext};
10786        let view = InputView::<EditorMode>::new(cx);
10787        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10788        setup_cursors(&mut cx, &view.input, "/*|*/");
10789        cx.update(|window, cx| {
10790            view.input.update(cx, |state, cx| {
10791                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
10792                crate::input::set_language_config(
10793                    state.language_name(),
10794                    LanguageConfig::default()
10795                        .auto_closing_pairs([
10796                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
10797                        ]),
10798                    cx,
10799                );
10800                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
10801                state.undo(&Undo, window, cx);
10802                state.backspace(&Backspace, window, cx);
10803            });
10804        });
10805        assert_cursors(&mut cx, &view.input, "/|*/");
10806    }
10807
10808    #[wgpui::test]
10809    fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
10810        use crate::input::{AutoClosingPair, SyntaxContext};
10811        struct CommentScope;
10812        impl crate::input::SyntaxContextProvider for CommentScope {
10813            fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
10814                if text
10815                    .to_string()
10816                    .find("*/")
10817                    .is_some_and(|end| offset < end + 2)
10818                {
10819                    SyntaxContext::Comment
10820                } else {
10821                    SyntaxContext::Code
10822                }
10823            }
10824        }
10825        let view = InputView::<EditorMode>::new(cx);
10826        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10827        setup_cursors(&mut cx, &view.input, "|");
10828        cx.update(|window, cx| {
10829            view.input.update(cx, |state, cx| {
10830                set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
10831                crate::input::set_language_config(
10832                    state.language_name(),
10833                    LanguageConfig::default().auto_closing_pairs([
10834                        AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
10835                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
10836                    ]),
10837                    cx,
10838                );
10839                state.replace_text_in_range(None, "/", window, cx);
10840                state.replace_text_in_range(None, "*", window, cx);
10841                state.set_selected_range(4..4, cx);
10842                state.replace_text_in_range(None, "(", window, cx);
10843                state.set_selected_range(2..2, cx);
10844                state.replace_text_in_range(None, "*", window, cx);
10845                state.replace_text_in_range(None, "/", window, cx);
10846            });
10847        });
10848        assert_cursors(&mut cx, &view.input, "/**/|()");
10849        cx.update(|window, cx| {
10850            view.input.update(cx, |state, cx| {
10851                state.set_selected_range(2..2, cx);
10852                state.backspace(&Backspace, window, cx);
10853                state.undo(&Undo, window, cx);
10854                state.redo(&Redo, window, cx);
10855            });
10856        });
10857        assert_cursors(&mut cx, &view.input, "|()");
10858    }
10859
10860    #[wgpui::test]
10861    fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
10862        use crate::input::{AutoClosingPair, SyntaxContext};
10863        let view = InputView::<EditorMode>::new(cx);
10864        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10865        setup_cursors(&mut cx, &view.input, "|");
10866        cx.update(|window, cx| {
10867            view.input.update(cx, |state, cx| {
10868                crate::input::set_language_config(
10869                    state.language_name(),
10870                    LanguageConfig::default()
10871                        .auto_closing_pairs([
10872                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
10873                        ]),
10874                    cx,
10875                );
10876                state.replace_text_in_range(None, "/", window, cx);
10877                state.replace_text_in_range(None, "*", window, cx);
10878                state.replace_text_in_range(Some(0..2), "//", window, cx);
10879                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
10880                state.replace_text_in_range(None, "*", window, cx);
10881            });
10882        });
10883        assert_cursors(&mut cx, &view.input, "//*|*/");
10884    }
10885
10886    #[wgpui::test]
10887    fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
10888        use crate::input::IndentationRules;
10889        let view = InputView::<EditorMode>::new(cx);
10890        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10891        setup_cursors(&mut cx, &view.input, "BEGIN|");
10892        cx.update(|window, cx| {
10893            view.input.update(cx, |state, cx| {
10894                let rules = |insensitive| {
10895                    LanguageConfig::default().indentation_rules(IndentationRules::new(
10896                        regex::RegexBuilder::new("begin$")
10897                            .case_insensitive(insensitive)
10898                            .build()
10899                            .unwrap(),
10900                        regex::Regex::new("^end").unwrap(),
10901                    ))
10902                };
10903                crate::input::set_language_config(state.language_name(), rules(false), cx);
10904                crate::input::set_language_config(state.language_name(), rules(true), cx);
10905                state.enter(
10906                    &Enter {
10907                        secondary: false,
10908                        shift: false,
10909                    },
10910                    window,
10911                    cx,
10912                );
10913            });
10914        });
10915        assert_cursors(&mut cx, &view.input, "BEGIN\n  |");
10916    }
10917
10918    #[wgpui::test]
10919    fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
10920        use crate::input::IndentationRules;
10921        let view = InputView::<EditorMode>::new(cx);
10922        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10923        let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
10924            regex::Regex::new(r"\bbegin\s*$").unwrap(),
10925            regex::Regex::new(r"^\s*end\b").unwrap(),
10926        ));
10927        for (before, expected) in [("begin|", "begin\n  |"), ("  |end", "  \n|end")] {
10928            setup_cursors(&mut cx, &view.input, before);
10929            cx.update(|window, cx| {
10930                view.input.update(cx, |state, cx| {
10931                    crate::input::set_language_config(state.language_name(), rules.clone(), cx);
10932                    state.enter(
10933                        &Enter {
10934                            secondary: false,
10935                            shift: false,
10936                        },
10937                        window,
10938                        cx,
10939                    );
10940                });
10941            });
10942            assert_cursors(&mut cx, &view.input, expected);
10943        }
10944    }
10945
10946    #[wgpui::test]
10947    fn test_custom_language_config(cx: &mut TestAppContext) {
10948        let view = InputView::<EditorMode>::new(cx);
10949        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10950        cx.update(|_window, cx| {
10951            view.input.update(cx, |state, cx| {
10952                crate::input::set_language_config(
10953                    state.language_name(),
10954                    crate::input::language_config::LanguageConfig::default()
10955                        .brackets([crate::input::BracketPair::new("«", "»")])
10956                        .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
10957                    cx,
10958                );
10959            });
10960        });
10961        // Custom pair closes.
10962        setup_cursors(&mut cx, &view.input, "|");
10963        cx.update(|window, cx| {
10964            view.input.update(cx, |state, cx| {
10965                state.replace_text_in_range(None, "«", window, cx);
10966            });
10967        });
10968        assert_cursors(&mut cx, &view.input, "«|»");
10969        // Default `(` no longer pairs under custom rules.
10970        cx.update(|window, cx| {
10971            view.input.update(cx, |state, cx| {
10972                state.set_value("\n", window, cx);
10973                state.set_selected_range(0..0, cx);
10974                state.replace_text_in_range(None, "(", window, cx);
10975            });
10976        });
10977        assert_cursors(&mut cx, &view.input, "(|");
10978    }
10979
10980    #[wgpui::test]
10981    fn test_skip_records_no_history(cx: &mut TestAppContext) {
10982        let view = InputView::<EditorMode>::new(cx);
10983        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10984        setup_cursors(&mut cx, &view.input, "(a|)");
10985        cx.update(|window, cx| {
10986            view.input.update(cx, |state, cx| {
10987                // Type a normal char (recorded), then skip over `)`.
10988                state.replace_text_in_range(None, "b", window, cx);
10989            });
10990        });
10991        assert_cursors(&mut cx, &view.input, "(ab|)");
10992        cx.update(|window, cx| {
10993            view.input.update(cx, |state, cx| {
10994                state.replace_text_in_range(None, ")", window, cx);
10995            });
10996        });
10997        // Skip is a pure cursor move: no history entry of its own.
10998        assert_cursors(&mut cx, &view.input, "(ab)|");
10999        // Undo removes `b`, never exposing a transient `())`.
11000        cx.update(|window, cx| {
11001            view.input
11002                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11003        });
11004        assert_cursors(&mut cx, &view.input, "(a|)");
11005    }
11006
11007    #[wgpui::test]
11008    fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
11009        let view = InputView::<EditorMode>::new(cx);
11010        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11011        setup_cursors(&mut cx, &view.input, "|");
11012        cx.update(|window, cx| {
11013            view.input.update(cx, |state, cx| {
11014                state.replace_text_in_range(None, "(", window, cx);
11015            });
11016        });
11017        assert_cursors(&mut cx, &view.input, "(|)");
11018        // One undo removes the whole pair (typing coalescing).
11019        cx.update(|window, cx| {
11020            view.input
11021                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11022        });
11023        assert_cursors(&mut cx, &view.input, "|");
11024    }
11025
11026    #[wgpui::test]
11027    fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
11028        let view = InputView::<EditorMode>::new(cx);
11029        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11030        // Odd backslashes: the typed quote is escaped, insert literally.
11031        setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
11032        cx.update(|window, cx| {
11033            view.input.update(cx, |state, cx| {
11034                state.replace_text_in_range(None, "\"", window, cx);
11035            });
11036        });
11037        assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
11038    }
11039
11040    #[wgpui::test]
11041    fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
11042        let view = InputView::<EditorMode>::new(cx);
11043        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11044        // Even backslashes: quote is not escaped, skip over the terminator.
11045        setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
11046        cx.update(|window, cx| {
11047            view.input.update(cx, |state, cx| {
11048                state.replace_text_in_range(None, "\"", window, cx);
11049            });
11050        });
11051        assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
11052    }
11053
11054    #[wgpui::test]
11055    fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
11056        use crate::input::{BracketPair, LanguageConfig};
11057
11058        let view = InputView::<EditorMode>::new(cx);
11059        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11060        cx.update(|window, cx| {
11061            view.input.update(cx, |state, cx| {
11062                // Language changes update rules without changing editor preferences.
11063                state.set_smart_indent(false, window, cx);
11064                crate::input::set_language_config(
11065                    state.language_name(),
11066                    LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
11067                    cx,
11068                );
11069            });
11070        });
11071        view.input.read_with(&cx, |state, _| {
11072            assert!(!state.mode.is_smart_indent(), "editor option preserved");
11073            assert!(state.mode.is_auto_close());
11074            let pairs = &state.mode.language_config().unwrap().brackets;
11075            assert_eq!(pairs.len(), 1, "pairs follow configuration");
11076            assert_eq!(pairs[0].open.as_ref(), "«");
11077        });
11078    }
11079
11080    struct CommentAllProvider;
11081    impl crate::input::SyntaxContextProvider for CommentAllProvider {
11082        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
11083            crate::input::SyntaxContext::Comment
11084        }
11085    }
11086
11087    struct StringAllProvider;
11088    impl crate::input::SyntaxContextProvider for StringAllProvider {
11089        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
11090            crate::input::SyntaxContext::String
11091        }
11092    }
11093
11094    #[wgpui::test]
11095    fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
11096        use std::rc::Rc;
11097
11098        let view = InputView::<EditorMode>::new(cx);
11099        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11100        cx.update(|_window, cx| {
11101            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
11102        });
11103        // Trigger `{` inside a string: no extra level, base indent only.
11104        setup_cursors(&mut cx, &view.input, "  x = {|");
11105        cx.update(|window, cx| {
11106            view.input.update(cx, |state, cx| {
11107                state.enter(
11108                    &Enter {
11109                        secondary: false,
11110                        shift: false,
11111                    },
11112                    window,
11113                    cx,
11114                );
11115            });
11116        });
11117        assert_cursors(&mut cx, &view.input, "  x = {\n  |");
11118    }
11119
11120    #[wgpui::test]
11121    fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
11122        use std::rc::Rc;
11123
11124        let view = InputView::<EditorMode>::new(cx);
11125        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11126        cx.update(|_window, cx| {
11127            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
11128        });
11129        // No three-way split inside strings: plain newline instead.
11130        setup_cursors(&mut cx, &view.input, "{|}");
11131        cx.update(|window, cx| {
11132            view.input.update(cx, |state, cx| {
11133                state.enter(
11134                    &Enter {
11135                        secondary: false,
11136                        shift: false,
11137                    },
11138                    window,
11139                    cx,
11140                );
11141            });
11142        });
11143        assert_cursors(&mut cx, &view.input, "{\n|}");
11144    }
11145
11146    #[wgpui::test]
11147    fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
11148        use std::rc::Rc;
11149
11150        let view = InputView::<EditorMode>::new(cx);
11151        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11152        cx.update(|_window, cx| {
11153            set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
11154        });
11155        setup_cursors(&mut cx, &view.input, "|");
11156        cx.update(|window, cx| {
11157            view.input.update(cx, |state, cx| {
11158                state.replace_text_in_range(None, "(", window, cx);
11159            });
11160        });
11161        // In comments every character is literal.
11162        assert_cursors(&mut cx, &view.input, "(|");
11163    }
11164
11165    #[wgpui::test]
11166    fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
11167        let view = InputView::<EditorMode>::new(cx);
11168        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11169        setup_cursors(&mut cx, &view.input, "{|}");
11170        cx.update(|window, cx| {
11171            view.input
11172                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11173        });
11174        assert_cursors(&mut cx, &view.input, "|");
11175    }
11176
11177    #[wgpui::test]
11178    fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
11179        let view = InputView::<EditorMode>::new(cx);
11180        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11181        setup_cursors(&mut cx, &view.input, "{d|}");
11182        cx.update(|window, cx| {
11183            view.input
11184                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11185        });
11186        // Only `d` is deleted, the closing brace stays.
11187        assert_cursors(&mut cx, &view.input, "{|}");
11188    }
11189
11190    #[wgpui::test]
11191    fn test_enter_splits_brackets(cx: &mut TestAppContext) {
11192        let view = InputView::<EditorMode>::new(cx);
11193        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11194        setup_cursors(&mut cx, &view.input, "{|}");
11195        cx.update(|window, cx| {
11196            view.input.update(cx, |state, cx| {
11197                state.enter(
11198                    &Enter {
11199                        secondary: false,
11200                        shift: false,
11201                    },
11202                    window,
11203                    cx,
11204                );
11205            });
11206        });
11207        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11208        // Selection must be collapsed: typing next must insert, not replace.
11209        view.input.read_with(&cx, |state, _| {
11210            assert!(state.active_selection().is_empty());
11211        });
11212        cx.update(|window, cx| {
11213            view.input.update(cx, |state, cx| {
11214                state.replace_text_in_range(None, "x", window, cx);
11215            });
11216        });
11217        assert_cursors(&mut cx, &view.input, "{\n  x|\n}");
11218    }
11219
11220    #[wgpui::test]
11221    fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
11222        let view = InputView::<EditorMode>::new(cx);
11223        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11224        setup_cursors(&mut cx, &view.input, "fn main() {|");
11225        cx.update(|window, cx| {
11226            view.input.update(cx, |state, cx| {
11227                state.enter(
11228                    &Enter {
11229                        secondary: false,
11230                        shift: false,
11231                    },
11232                    window,
11233                    cx,
11234                );
11235            });
11236        });
11237        assert_cursors(&mut cx, &view.input, "fn main() {\n  |");
11238    }
11239
11240    #[wgpui::test]
11241    fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
11242        let view = multi_line(cx);
11243        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11244        setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
11245        cx.update(|window, cx| {
11246            view.input
11247                .update(cx, |state, cx| state.indent(true, window, cx));
11248        });
11249        assert_cursors(&mut cx, &view.input, "  |ab\n  |cd\n  |ef");
11250        cx.update(|window, cx| {
11251            view.input
11252                .update(cx, |state, cx| state.outdent(true, window, cx));
11253        });
11254        assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
11255    }
11256
11257    #[wgpui::test]
11258    fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
11259        let view = multi_line(cx);
11260        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11261        setup_cursors(&mut cx, &view.input, "ab\n | cd");
11262        cx.update(|window, cx| {
11263            view.input
11264                .update(cx, |state, cx| state.outdent(true, window, cx));
11265        });
11266        assert_cursors(&mut cx, &view.input, "ab\n|cd");
11267    }
11268
11269    #[wgpui::test]
11270    fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
11271        let view = InputView::build(cx, |state| state);
11272        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11273        cx.update(|window, cx| {
11274            view.input.update(cx, |state, cx| {
11275                state.set_value("abc", window, cx);
11276                state.set_selected_range(1..2, cx);
11277                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
11278                state.replace_text_in_range(None, "你", window, cx);
11279                state.undo(&Undo, window, cx);
11280                assert_eq!(state.value(), "abc");
11281                assert_eq!(state.selected_range(), 1..2);
11282                state.redo(&Redo, window, cx);
11283                assert_eq!(state.selected_range(), 4..4);
11284            });
11285        });
11286    }
11287
11288    fn assert_cleared_preedit_preserves_composition<M: InputModeKind>(
11289        view: InputView<M>,
11290        cx: &mut TestAppContext,
11291    ) {
11292        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11293        for reversed in [false, true] {
11294            let original_selection = cx.update(|window, cx| {
11295                let selection = view.input.update(cx, |state, cx| {
11296                    state.set_value("😀界終", window, cx);
11297                    state.set_selection(4, 7);
11298                    state.active_selection_mut().reversed = reversed;
11299                    state.focus(window, cx);
11300                    *state.active_selection()
11301                });
11302                window.draw(cx).clear();
11303                selection
11304            });
11305
11306            cx.simulate_ime_event(wgpui::ImeEvent::Enabled)
11307                .expect("focused input accepts native IME events");
11308            cx.simulate_ime_event(wgpui::ImeEvent::Preedit(String::new(), None))
11309                .expect("empty native preedit without a composition");
11310            view.input.read_with(&cx, |state, _| {
11311                assert_eq!(state.value(), "😀界終");
11312                assert_eq!(*state.active_selection(), original_selection);
11313                assert!(!state.undo_manager.has_undos());
11314            });
11315
11316            cx.simulate_ime_event(wgpui::ImeEvent::Preedit("ni🦀".into(), Some((6, 6))))
11317                .expect("native preedit cursor uses UTF-8 byte offsets");
11318            view.input.read_with(&cx, |state, _| {
11319                assert_eq!(state.value(), "😀ni🦀終");
11320                assert_eq!(state.selected_range(), 10..10);
11321                assert_eq!(state.ime_marked_range, Some((4..10).into()));
11322            });
11323            cx.simulate_ime_event(wgpui::ImeEvent::Preedit(String::new(), None))
11324                .expect("native empty preedit clears the previous candidate");
11325            cx.update(|window, cx| {
11326                view.input.update(cx, |state, cx| {
11327                    assert_eq!(state.value(), "😀終");
11328                    assert_eq!(state.selected_range(), 4..4);
11329                    assert_eq!(state.marked_text_range(window, cx), Some(2..2));
11330                    assert!(state.undo_manager.has_open_transaction());
11331                });
11332            });
11333
11334            cx.simulate_ime_event(wgpui::ImeEvent::Preedit(String::new(), None))
11335                .expect("repeated native empty preedit");
11336            view.input.read_with(&cx, |state, _| {
11337                assert_eq!(state.value(), "😀終");
11338                assert!(state.undo_manager.has_open_transaction());
11339            });
11340            cx.simulate_ime_event(wgpui::ImeEvent::Commit("你".into()))
11341                .expect("native candidate commit");
11342            cx.update(|window, cx| {
11343                view.input.update(cx, |state, cx| {
11344                    assert_eq!(state.value(), "😀你終");
11345                    assert_eq!(state.selected_range(), 7..7);
11346                    assert!(state.ime_marked_range.is_none());
11347                    assert!(!state.undo_manager.has_open_transaction());
11348                    assert_eq!(state.undo_manager.undo_count(), 1);
11349
11350                    state.undo(&Undo, window, cx);
11351                    assert_eq!(state.value(), "😀界終");
11352                    assert_eq!(*state.active_selection(), original_selection);
11353                    state.redo(&Redo, window, cx);
11354                    assert_eq!(state.value(), "😀你終");
11355                    assert_eq!(state.selected_range(), 7..7);
11356
11357                    state.replace_text_in_range(None, "!", window, cx);
11358                    state.undo(&Undo, window, cx);
11359                    assert_eq!(state.value(), "😀你終");
11360                    state.undo(&Undo, window, cx);
11361                    assert_eq!(state.value(), "😀界終");
11362                    assert_eq!(*state.active_selection(), original_selection);
11363                });
11364            });
11365        }
11366    }
11367
11368    #[wgpui::test]
11369    fn test_cleared_preedit_commit_restores_unicode_selection_as_one_undo(cx: &mut TestAppContext) {
11370        let input = InputView::build(cx, |state| state);
11371        assert_cleared_preedit_preserves_composition(input, cx);
11372        let textarea = InputView::build_textarea(cx, |state| state);
11373        assert_cleared_preedit_preserves_composition(textarea, cx);
11374        let editor = InputView::build_editor(cx, |state| state);
11375        assert_cleared_preedit_preserves_composition(editor, cx);
11376    }
11377
11378    #[wgpui::test]
11379    fn test_native_ime_disabled_clears_preedit_and_closes_undo_transaction(
11380        cx: &mut TestAppContext,
11381    ) {
11382        let view = InputView::build(cx, |state| state);
11383        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11384        for (original, selection) in [("😀終", 4..4), ("😀界終", 4..7)] {
11385            for clear_first in [false, true] {
11386                cx.update(|window, cx| {
11387                    view.input.update(cx, |state, cx| {
11388                        state.set_value(original, window, cx);
11389                        state.set_selected_range(selection.clone(), cx);
11390                        state.focus(window, cx);
11391                    });
11392                    window.draw(cx).clear();
11393                });
11394                cx.simulate_ime_event(wgpui::ImeEvent::Preedit("ni".into(), Some((2, 2))))
11395                    .expect("native composition starts");
11396                if clear_first {
11397                    cx.simulate_ime_event(wgpui::ImeEvent::Preedit(String::new(), None))
11398                        .expect("native preedit clears before cancellation");
11399                }
11400                cx.simulate_ime_event(wgpui::ImeEvent::Disabled)
11401                    .expect("native IME cancellation");
11402                cx.update(|window, cx| {
11403                    view.input.update(cx, |state, cx| {
11404                        assert_eq!(state.value(), "😀終");
11405                        assert_eq!(state.selected_range(), 4..4);
11406                        assert!(state.ime_marked_range.is_none());
11407                        assert!(!state.undo_manager.has_open_transaction());
11408                        assert_eq!(
11409                            state.undo_manager.undo_count(),
11410                            usize::from(!selection.is_empty())
11411                        );
11412                        if !selection.is_empty() {
11413                            state.undo(&Undo, window, cx);
11414                            assert_eq!(state.value(), original);
11415                            assert_eq!(state.selected_range(), selection);
11416                            state.redo(&Redo, window, cx);
11417                            assert_eq!(state.value(), "😀終");
11418                        }
11419
11420                        state.replace_text_in_range(None, "!", window, cx);
11421                        state.undo(&Undo, window, cx);
11422                        assert_eq!(state.value(), "😀終");
11423                        assert_eq!(state.selected_range(), 4..4);
11424                        if !selection.is_empty() {
11425                            state.undo(&Undo, window, cx);
11426                            assert_eq!(state.value(), original);
11427                            assert_eq!(state.selected_range(), selection);
11428                        }
11429                    });
11430                });
11431            }
11432        }
11433    }
11434
11435    #[wgpui::test]
11436    fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
11437        let view = multi_line(cx);
11438        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11439        cx.update(|window, cx| {
11440            view.input.update(cx, |state, cx| {
11441                state.set_value("abc", window, cx);
11442                state.set_selected_range(1..1, cx);
11443                state.replace_text_in_range(None, "X", window, cx);
11444                state.set_selected_range(0..0, cx);
11445                state.replace_text_in_range(None, "", window, cx);
11446                state.undo(&Undo, window, cx);
11447                state.redo(&Redo, window, cx);
11448                assert_eq!(state.value(), "aXbc");
11449                assert_eq!(state.selected_range(), 2..2);
11450            });
11451        });
11452    }
11453
11454    #[wgpui::test]
11455    fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
11456        let view = multi_line(cx);
11457        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11458        let input = view.input;
11459
11460        setup_cursors(&mut cx, &input, "|hello |world|");
11461        cx.update(|window, cx| {
11462            input.update(cx, |state, cx| {
11463                state.replace_text_in_range(None, ">>>", window, cx);
11464            });
11465        });
11466        assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
11467    }
11468
11469    #[wgpui::test]
11470    fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
11471        let view = multi_line(cx);
11472        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11473        let input = view.input;
11474
11475        setup_cursors(&mut cx, &input, "|islands| cars|");
11476        cx.update(|window, cx| {
11477            input.update(cx, |state, cx| {
11478                state.backspace(&Backspace, window, cx);
11479            });
11480        });
11481        // The first cursor has nothing to delete. The others delete an `s`.
11482        assert_cursors(&mut cx, &input, "|island| car|");
11483    }
11484
11485    #[wgpui::test]
11486    fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
11487        let view = multi_line(cx);
11488        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11489        let input = view.input;
11490
11491        setup_cursors(&mut cx, &input, "hello| |world");
11492        cx.update(|window, cx| {
11493            input.update(cx, |state, cx| {
11494                state.delete(&Delete, window, cx);
11495            });
11496        });
11497        // Adjacent deletions merge into a single cursor.
11498        assert_cursors(&mut cx, &input, "hello|orld");
11499    }
11500
11501    #[wgpui::test]
11502    fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
11503        let view = multi_line(cx);
11504        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11505        let input = view.input;
11506
11507        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
11508        cx.update(|window, cx| {
11509            input.update(cx, |state, cx| {
11510                state.replace_text_in_range(None, "a", window, cx);
11511            });
11512        });
11513        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
11514
11515        // The whole multi-edit insert is a single undo transaction.
11516        input.read_with(&cx, |state, _| {
11517            assert_eq!(state.undo_manager.undo_count(), 1);
11518        });
11519
11520        cx.update(|window, cx| {
11521            input.update(cx, |state, cx| {
11522                state.backspace(&Backspace, window, cx);
11523            });
11524        });
11525        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11526    }
11527
11528    #[wgpui::test]
11529    fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
11530        let view = multi_line(cx);
11531        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11532        let input = view.input;
11533
11534        setup_cursors(&mut cx, &input, "ab|cd\nabcd");
11535        cx.update(|window, cx| {
11536            input.update(cx, |state, cx| {
11537                state.add_cursor_below(&AddCursorBelow, window, cx);
11538            });
11539        });
11540        assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
11541    }
11542
11543    #[wgpui::test]
11544    fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
11545        let view = multi_line(cx);
11546        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11547        let input = view.input;
11548
11549        setup_cursors(&mut cx, &input, "he|llo");
11550        cx.update(|_, cx| {
11551            input.update(cx, |state, cx| {
11552                // Duplicate of the existing cursor is rejected.
11553                state.add_cursor_at(2, cx);
11554                assert_eq!(state.selections.len(), 1);
11555                // A distinct offset adds a cursor.
11556                state.add_cursor_at(4, cx);
11557                assert_eq!(state.selections.len(), 2);
11558            });
11559        });
11560    }
11561
11562    #[wgpui::test]
11563    fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
11564        let view = multi_line(cx);
11565        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11566        let input = view.input;
11567
11568        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
11569        cx.update(|window, cx| {
11570            input.update(cx, |state, cx| {
11571                state.replace_text_in_range(None, "a", window, cx);
11572            });
11573        });
11574        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
11575
11576        cx.update(|window, cx| {
11577            input.update(cx, |state, cx| {
11578                state.undo(&Undo, window, cx);
11579            });
11580        });
11581        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11582
11583        cx.update(|window, cx| {
11584            input.update(cx, |state, cx| {
11585                state.redo(&Redo, window, cx);
11586            });
11587        });
11588        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
11589    }
11590
11591    #[wgpui::test]
11592    fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
11593        let view = multi_line(cx);
11594        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11595        let input = view.input;
11596
11597        setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
11598        cx.update(|window, cx| {
11599            input.update(cx, |state, cx| {
11600                state.replace_text_in_range(None, "a", window, cx);
11601            });
11602        });
11603        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
11604
11605        cx.update(|window, cx| {
11606            input.update(cx, |state, cx| {
11607                state.undo(&Undo, window, cx);
11608            });
11609        });
11610        assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
11611
11612        cx.update(|window, cx| {
11613            input.update(cx, |state, cx| {
11614                state.redo(&Redo, window, cx);
11615            });
11616        });
11617        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
11618    }
11619
11620    #[wgpui::test]
11621    fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
11622        let view = multi_line(cx);
11623        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11624        let input = view.input;
11625
11626        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
11627        for ch in ['a', 'b', 'c'] {
11628            cx.update(|window, cx| {
11629                input.update(cx, |state, cx| {
11630                    state.replace_text_in_range(None, &ch.to_string(), window, cx);
11631                });
11632            });
11633        }
11634        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
11635
11636        // The repeated keystrokes form one typing gesture.
11637        cx.update(|window, cx| {
11638            input.update(cx, |state, cx| {
11639                assert_eq!(state.undo_manager.undo_count(), 1);
11640                state.undo(&Undo, window, cx);
11641            });
11642        });
11643        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11644
11645        cx.update(|window, cx| {
11646            input.update(cx, |state, cx| {
11647                state.redo(&Redo, window, cx);
11648            });
11649        });
11650        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
11651    }
11652
11653    #[wgpui::test]
11654    fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
11655        let view = multi_line(cx);
11656        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11657        let input = view.input;
11658
11659        setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
11660        for _ in 0..3 {
11661            cx.update(|window, cx| {
11662                input.update(cx, |state, cx| {
11663                    state.backspace(&Backspace, window, cx);
11664                });
11665            });
11666        }
11667        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11668
11669        cx.update(|window, cx| {
11670            input.update(cx, |state, cx| {
11671                assert_eq!(state.undo_manager.undo_count(), 1);
11672                state.undo(&Undo, window, cx);
11673            });
11674        });
11675        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
11676    }
11677
11678    #[wgpui::test]
11679    fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
11680        let view = multi_line(cx);
11681        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11682        let input = view.input;
11683
11684        setup_cursors(&mut cx, &input, "|1\n2\n3");
11685        cx.update(|window, cx| {
11686            input.update(cx, |state, cx| {
11687                state.replace_text_in_range(None, "a", window, cx);
11688                state.add_cursor_below(&AddCursorBelow, window, cx);
11689                state.replace_text_in_range(None, "b", window, cx);
11690            });
11691        });
11692        assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
11693
11694        // The keystroke after the cursor was added is its own undo entry.
11695        cx.update(|window, cx| {
11696            input.update(cx, |state, cx| {
11697                state.undo(&Undo, window, cx);
11698            });
11699        });
11700        assert_cursors(&mut cx, &input, "a|1\n2|\n3");
11701    }
11702
11703    #[wgpui::test]
11704    fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
11705        let view = multi_line(cx);
11706        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11707        let input = view.input;
11708
11709        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
11710        cx.update(|window, cx| {
11711            input.update(cx, |state, cx| {
11712                state.indent_inline(&IndentInline, window, cx);
11713                assert_eq!(state.undo_manager.undo_count(), 1);
11714                state.undo(&Undo, window, cx);
11715            });
11716        });
11717        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11718    }
11719
11720    #[wgpui::test]
11721    fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
11722        let view = multi_line(cx);
11723        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11724        let input = view.input;
11725
11726        // Cursors at line starts.
11727        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
11728        cx.update(|window, cx| {
11729            input.update(cx, |state, cx| {
11730                state.indent(false, window, cx);
11731            });
11732        });
11733        assert_cursors(&mut cx, &input, "  |1\n  |2\n  |3");
11734
11735        cx.update(|window, cx| {
11736            input.update(cx, |state, cx| {
11737                state.outdent(false, window, cx);
11738            });
11739        });
11740        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
11741    }
11742
11743    #[wgpui::test]
11744    fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
11745        let view = multi_line(cx);
11746        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11747        let input = view.input;
11748
11749        // A mid-line indent lands at the cursor, and the outdent does not
11750        // take it back: it only ever removes leading line indentation.
11751        setup_cursors(&mut cx, &input, "1|2\n1|2");
11752        cx.update(|window, cx| {
11753            input.update(cx, |state, cx| {
11754                state.indent(false, window, cx);
11755            });
11756        });
11757        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
11758
11759        cx.update(|window, cx| {
11760            input.update(cx, |state, cx| {
11761                state.outdent(false, window, cx);
11762            });
11763        });
11764        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
11765
11766        // A line with leading indentation loses that, wherever the cursor is.
11767        setup_cursors(&mut cx, &input, "  1|2\n  1|2");
11768        cx.update(|window, cx| {
11769            input.update(cx, |state, cx| {
11770                state.outdent(false, window, cx);
11771            });
11772        });
11773        assert_cursors(&mut cx, &input, "1|2\n1|2");
11774    }
11775
11776    #[wgpui::test]
11777    fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
11778        let view = multi_line(cx);
11779        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11780        let input = view.input;
11781
11782        setup_cursors(&mut cx, &input, "a|b\nc|d");
11783        cx.update(|window, cx| {
11784            input.update(cx, |state, cx| {
11785                let before: Vec<_> = state.selections.iter().copied().collect();
11786                state.set_readonly(true, cx);
11787                state.backspace(&Backspace, window, cx);
11788                state.indent_inline(&IndentInline, window, cx);
11789
11790                assert_eq!(state.value(), "ab\ncd\n");
11791                assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
11792            });
11793        });
11794    }
11795
11796    #[wgpui::test]
11797    fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
11798        let view = multi_line(cx);
11799        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11800        let input = view.input;
11801
11802        setup_cursors(&mut cx, &input, "x|\n|y");
11803        cx.update(|window, cx| {
11804            input.update(cx, |state, cx| {
11805                let mut selections: Vec<_> = state.selections.iter().copied().collect();
11806                selections.swap(0, 1);
11807                state.selections.replace_all(selections);
11808                let active_id = state.active_selection().id;
11809                state.replace_text_in_range(None, "!", window, cx);
11810                assert_eq!(state.active_selection().id, active_id);
11811            });
11812        });
11813    }
11814
11815    #[wgpui::test]
11816    fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
11817        let view = multi_line(cx);
11818        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11819        let input = view.input;
11820
11821        cx.update(|window, cx| {
11822            input.update(cx, |state, cx| {
11823                state.set_value("line1\nline2\nline3", window, cx);
11824                let id = state.selections.generate_id();
11825                state
11826                    .selections
11827                    .replace_all(vec![CursorSelection::new(id, 0, 17)]);
11828                cx.notify();
11829            });
11830        });
11831
11832        cx.update(|window, cx| {
11833            input.update(cx, |state, cx| {
11834                state.indent(true, window, cx);
11835            });
11836        });
11837        input.read_with(&cx, |state, _| {
11838            assert_eq!(state.text.to_string(), "  line1\n  line2\n  line3");
11839        });
11840
11841        cx.update(|window, cx| {
11842            input.update(cx, |state, cx| {
11843                state.outdent(true, window, cx);
11844            });
11845        });
11846        input.read_with(&cx, |state, _| {
11847            assert_eq!(state.text.to_string(), "line1\nline2\nline3");
11848        });
11849    }
11850
11851    #[wgpui::test]
11852    fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
11853        let view = multi_line(cx);
11854        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11855        let input = view.input;
11856
11857        setup_cursors(
11858            &mut cx,
11859            &input,
11860            "on|e two three\none t|wo three\non|e two three",
11861        );
11862
11863        cx.update(|window, cx| {
11864            input.update(cx, |state, cx| {
11865                state.move_to_next_word(&MoveToNextWord, window, cx);
11866            });
11867        });
11868        assert_cursors(
11869            &mut cx,
11870            &input,
11871            "one| two three\none two| three\none| two three",
11872        );
11873
11874        cx.update(|window, cx| {
11875            input.update(cx, |state, cx| {
11876                state.move_to_previous_word(&MoveToPreviousWord, window, cx);
11877            });
11878        });
11879        assert_cursors(
11880            &mut cx,
11881            &input,
11882            "|one two three\none |two three\n|one two three",
11883        );
11884
11885        // Move to end/start of document collapses to a single cursor.
11886        cx.update(|window, cx| {
11887            input.update(cx, |state, cx| {
11888                state.move_to_end(&MoveToEnd, window, cx);
11889            });
11890        });
11891        input.read_with(&cx, |state, _| {
11892            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
11893            assert_eq!(cursors, vec![state.text.len_bytes()]);
11894        });
11895
11896        cx.update(|window, cx| {
11897            input.update(cx, |state, cx| {
11898                state.move_to_start(&MoveToStart, window, cx);
11899            });
11900        });
11901        input.read_with(&cx, |state, _| {
11902            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
11903            assert_eq!(cursors, vec![0]);
11904        });
11905    }
11906
11907    #[wgpui::test]
11908    fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
11909        let view = multi_line(cx);
11910        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11911        let input = view.input;
11912
11913        setup_cursors(
11914            &mut cx,
11915            &input,
11916            "on|e two three\none t|wo three\non|e two three",
11917        );
11918        cx.update(|window, cx| {
11919            input.update(cx, |state, cx| {
11920                state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
11921            });
11922        });
11923        assert_cursors(
11924            &mut cx,
11925            &input,
11926            "|one two three\n|one two three\n|one two three",
11927        );
11928
11929        // Select to document start collapses to the active cursor only.
11930        setup_cursors(
11931            &mut cx,
11932            &input,
11933            "on|e two three\none t|wo three\non|e two three",
11934        );
11935        cx.update(|window, cx| {
11936            input.update(cx, |state, cx| {
11937                state.select_to_start(&SelectToStart, window, cx);
11938            });
11939        });
11940        input.read_with(&cx, |state, _| {
11941            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
11942            assert_eq!(cursors, vec![0]);
11943        });
11944    }
11945
11946    #[wgpui::test]
11947    fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
11948        let view = multi_line(cx);
11949        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11950        let input = view.input;
11951
11952        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
11953        cx.update(|window, cx| {
11954            input.update(cx, |state, cx| {
11955                state.select_right(&SelectRight, window, cx);
11956            });
11957        });
11958        input.read_with(&cx, |state, _| {
11959            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
11960            assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
11961        });
11962
11963        cx.update(|window, cx| {
11964            input.update(cx, |state, cx| {
11965                state.replace_text_in_range(None, "x", window, cx);
11966            });
11967        });
11968        assert_cursors(&mut cx, &input, "x|\nx|\nx|");
11969    }
11970
11971    #[wgpui::test]
11972    fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
11973        let view = multi_line(cx);
11974        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11975        let input = view.input;
11976
11977        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
11978        cx.update(|window, cx| {
11979            input.update(cx, |state, cx| {
11980                state.escape(&Escape, window, cx);
11981            });
11982        });
11983        input.read_with(&cx, |state, _| {
11984            assert_eq!(state.selections.len(), 1);
11985        });
11986    }
11987
11988    #[wgpui::test]
11989    fn test_build_columnar_selection(cx: &mut TestAppContext) {
11990        let view = multi_line(cx);
11991        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11992        let input = view.input;
11993
11994        setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
11995        cx.update(|_, cx| {
11996            input.update(cx, |state, cx| {
11997                // From row 0 col 1 to row 2 col 3.
11998                state.build_columnar_selection(
11999                    ColumnarPoint::new(1, 0),
12000                    ColumnarPoint::new(13, 0),
12001                    cx,
12002                );
12003                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12004                assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
12005            });
12006        });
12007    }
12008
12009    #[wgpui::test]
12010    fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
12011        let view = multi_line(cx);
12012        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12013        let input = view.input;
12014
12015        setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
12016        cx.update(|_, cx| {
12017            input.update(cx, |state, cx| {
12018                // Ends on the short row, 3 columns past its end: the block still spans
12019                // columns 1..5, and only that row is clipped to what it has.
12020                state.build_columnar_selection(
12021                    ColumnarPoint::new(1, 0),
12022                    ColumnarPoint::new(9, 3),
12023                    cx,
12024                );
12025                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12026                assert_eq!(ranges, vec![(1, 5), (8, 9)]);
12027            });
12028        });
12029    }
12030
12031    #[wgpui::test]
12032    fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
12033        let view = multi_line(cx);
12034        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12035        let input = view.input;
12036
12037        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12038        cx.update(|_, cx| {
12039            cx.write_to_clipboard(ClipboardItem::new_string("x\ny\nz".to_string()));
12040        });
12041        cx.update(|window, cx| {
12042            input.update(cx, |state, cx| {
12043                state.paste(&Paste, window, cx);
12044            });
12045        });
12046        // One clipboard line per cursor.
12047        assert_cursors(&mut cx, &input, "x|1\ny|2\nz|3");
12048    }
12049
12050    #[wgpui::test]
12051    fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
12052        use wgpui::{Image, ImageFormat};
12053
12054        let input_view = InputView::build(cx, |state| state);
12055        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
12056        let input = input_view.input;
12057
12058        cx.update(|window, cx| {
12059            input.update(cx, |state, cx| {
12060                state.set_value("hello world", window, cx);
12061                state.select_all(window, cx);
12062                cx.write_to_clipboard(ClipboardItem::new_image(&Image::from_bytes(
12063                    ImageFormat::Png,
12064                    vec![0x89, b'P', b'N', b'G'],
12065                )));
12066
12067                // An image-only clipboard must not replace the selection
12068                // with nothing.
12069                state.paste(&Paste, window, cx);
12070                assert_eq!(state.value(), "hello world");
12071                assert_eq!(state.selected_range(), 0..11);
12072            });
12073        });
12074    }
12075
12076    #[wgpui::test]
12077    fn test_paste_target_tracks_edits_and_selections(cx: &mut TestAppContext) {
12078        let view = multi_line(cx);
12079        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12080        let input = view.input;
12081
12082        setup_cursors(&mut cx, &input, "ab|c");
12083        let target = input.read_with(&cx, |state, _| state.paste_target());
12084        // Nothing happened: a paste asked for then still applies.
12085        assert_eq!(
12086            input.read_with(&cx, |state, _| state.paste_target()),
12087            target
12088        );
12089
12090        // Moving the caret changes where the paste would go.
12091        cx.update(|_, cx| {
12092            input.update(cx, |state, cx| {
12093                let id = state.selections.generate_id();
12094                state
12095                    .selections
12096                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
12097                cx.notify();
12098            });
12099        });
12100        let moved = input.read_with(&cx, |state, _| state.paste_target());
12101        assert_ne!(moved, target);
12102
12103        // Editing the text changes it too, even with the caret put back.
12104        cx.update(|window, cx| {
12105            input.update(cx, |state, cx| {
12106                state.replace_text_in_range_silent(None, "x", window, cx);
12107                let id = state.selections.generate_id();
12108                state
12109                    .selections
12110                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
12111            });
12112        });
12113        assert_ne!(input.read_with(&cx, |state, _| state.paste_target()), moved);
12114    }
12115
12116    #[wgpui::test]
12117    fn test_ime_candidate_bounds_fallback_before_repaint(cx: &mut TestAppContext) {
12118        let input_view = InputView::build_textarea(cx, |state| {
12119            state.default_value("这是一段已经输入的中文文字")
12120        });
12121        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
12122        visual.update(|window, cx| window.draw(cx).clear());
12123
12124        visual.update(|window, cx| {
12125            input_view.input.update(cx, |state, cx| {
12126                state.focus(window, cx);
12127                let len = state.text.len_bytes();
12128                state.set_cursor_to(len);
12129            });
12130        });
12131        visual.update(|window, cx| window.draw(cx).clear());
12132
12133        visual.update(|window, cx| {
12134            input_view.input.update(cx, |state, cx| {
12135                let bounds = state.text_bounds().unwrap_or_default();
12136                let before = state.selected_text_range(false, window, cx).unwrap().range;
12137                let previous = state
12138                    .bounds_for_range(before.end..before.end, bounds, window, cx)
12139                    .unwrap();
12140
12141                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
12142
12143                let after = state.selected_text_range(false, window, cx).unwrap().range;
12144                let pending = state
12145                    .bounds_for_range(after.end..after.end, bounds, window, cx)
12146                    .unwrap();
12147
12148                assert!(
12149                    (pending.origin.x - previous.origin.x).abs() < px(40.0),
12150                    "pending origin.x {:?} must remain close to previous origin.x {:?}",
12151                    pending.origin.x,
12152                    previous.origin.x
12153                );
12154
12155                let range_bounds = state
12156                    .bounds_for_range(before.end..after.end, bounds, window, cx)
12157                    .unwrap();
12158                assert!(
12159                    (range_bounds.origin.x - previous.origin.x).abs() < px(40.0),
12160                    "range_bounds origin.x {:?} must remain close to previous origin.x {:?}",
12161                    range_bounds.origin.x,
12162                    previous.origin.x
12163                );
12164                assert!(range_bounds.size.width >= px(0.0));
12165            });
12166        });
12167    }
12168}
12169
12170/// Methods that only a single-line input offers.
12171impl InputBaseState<crate::input::InputMode> {
12172    /// Create a single-line text input state.
12173    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
12174        Self::new_in_mode(window, cx)
12175    }
12176
12177    /// Set a custom step function of the [`NumberInput`](crate::NumberInput).
12178    ///
12179    /// The `f` receives the current value and the [`StepAction`], and returns
12180    /// the step to apply, so the step can vary with the value.
12181    ///
12182    /// # Example
12183    ///
12184    /// ```ignore
12185    /// // At the boundary 1.0 the step is 0.1 going down and 0.5 going up.
12186    /// InputState::new(window, cx).step_by(|value, action, _cx| match action {
12187    ///     StepAction::Increment => if value < 1.0 { 0.1 } else { 0.5 },
12188    ///     StepAction::Decrement => if value <= 1.0 { 0.1 } else { 0.5 },
12189    /// })
12190    /// ```
12191    pub fn step_by(mut self, f: impl Fn(f64, StepAction, &mut App) -> f64 + 'static) -> Self {
12192        self.number_step = Some(NumberStep::by_value(f));
12193        self
12194    }
12195
12196    /// Set with password masked state.
12197    pub fn masked(mut self, masked: bool) -> Self {
12198        self.masked = masked;
12199        self
12200    }
12201
12202    /// Set the password masked state of the input field.
12203    pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
12204        self.masked = masked;
12205        cx.notify();
12206    }
12207
12208    /// Set the regular expression pattern of the input field.
12209    pub fn pattern(mut self, pattern: regex::Regex) -> Self {
12210        self.pattern = Some(pattern);
12211        self
12212    }
12213
12214    /// Set the regular expression pattern of the input field with reference.
12215    pub fn set_pattern(
12216        &mut self,
12217        pattern: regex::Regex,
12218        _window: &mut Window,
12219        _cx: &mut Context<Self>,
12220    ) {
12221        self.pattern = Some(pattern);
12222    }
12223
12224    /// Set the validation function of the input field.
12225    pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
12226        self.validate = Some(Box::new(f));
12227        self
12228    }
12229
12230    pub fn set_validator(
12231        &mut self,
12232        validate: impl Fn(&str, &mut App) -> bool + 'static,
12233        _cx: &mut Context<Self>,
12234    ) {
12235        self.validate = Some(Box::new(validate));
12236    }
12237
12238    /// Set the step value of the [`NumberInput`](crate::NumberInput) for increment/decrement.
12239    ///
12240    /// If any of `step`, `min`, `max` is set, the [`NumberInput`](crate::NumberInput) will
12241    /// update the value internally (step by `step`, default 1, clamp to the
12242    /// `min`/`max` range and emit [`InputEvent::Change`]) instead of emitting
12243    /// [`super::NumberInputEvent::Step`].
12244    ///
12245    /// See also [`Self::step_by`] to calculate the step value
12246    /// based on the current value.
12247    pub fn step(mut self, step: impl Into<NumberStep>) -> Self {
12248        self.number_step = Some(step.into());
12249        self
12250    }
12251
12252    /// Set the minimum value of the [`NumberInput`](crate::NumberInput).
12253    ///
12254    /// The value will be clamped to the minimum value on stepping and on
12255    /// blur (only if the clamped value passes the `pattern`/`validate` check).
12256    /// See also [`Self::step`].
12257    pub fn min(mut self, min: f64) -> Self {
12258        self.number_min = Some(min);
12259        self
12260    }
12261
12262    /// Set the maximum value of the [`NumberInput`](crate::NumberInput).
12263    ///
12264    /// The value will be clamped to the maximum value on stepping and on
12265    /// blur (only if the clamped value passes the `pattern`/`validate` check).
12266    /// See also [`Self::step`].
12267    pub fn max(mut self, max: f64) -> Self {
12268        self.number_max = Some(max);
12269        self
12270    }
12271
12272    /// Update the step value after construction, `None` to fall back to
12273    /// emitting [`super::NumberInputEvent::Step`] (if `min`, `max` are unset).
12274    ///
12275    /// See [`Self::step`] and [`Self::step_by`].
12276    pub fn set_step(
12277        &mut self,
12278        step: impl Into<Option<NumberStep>>,
12279        _: &mut Window,
12280        _: &mut Context<Self>,
12281    ) {
12282        self.number_step = step.into();
12283    }
12284
12285    /// Update the minimum value after construction. See [`Self::min`].
12286    pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
12287        self.number_min = min;
12288    }
12289
12290    /// Update the maximum value after construction. See [`Self::max`].
12291    pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
12292        self.number_max = max;
12293    }
12294
12295    /// Set true to show spinner at the input right.
12296    pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
12297        self.loading = loading;
12298        cx.notify();
12299    }
12300}
12301
12302/// Methods shared by the two multi-line modes, and reachable on neither a
12303/// single-line input nor anything else.
12304impl<M: crate::input::MultiLineMode> InputBaseState<M> {
12305    /// Set whether text taller than the input stretches past its top and
12306    /// bottom and springs back when precise trackpad or Magic Mouse scrolling
12307    /// or its momentum runs into an end. Ordinary line-wheel scrolling does
12308    /// not bounce. The default follows
12309    /// [`crate::ScrollBounce::enabled_by_default`]: on on iOS, Android and
12310    /// macOS, off elsewhere. Under reduced motion the text stops at its ends
12311    /// without stretching.
12312    pub fn scroll_bounce(mut self, scroll_bounce: bool) -> Self {
12313        self.scroll_bounce = scroll_bounce;
12314        self
12315    }
12316
12317    /// Update whether the text stretches past its ends, see
12318    /// [`InputBaseState::scroll_bounce`]. Turning it off drops a stretch in
12319    /// progress.
12320    pub fn set_scroll_bounce(&mut self, scroll_bounce: bool, cx: &mut Context<Self>) {
12321        if self.scroll_bounce != scroll_bounce {
12322            self.scroll_bounce = scroll_bounce;
12323            self.overscroll.reset();
12324            cx.notify();
12325        }
12326    }
12327
12328    /// Whether the built-in search panel and its shortcut are enabled. Off by
12329    /// default, on for the code editor.
12330    ///
12331    /// This only concerns the panel. An input that is not searchable still
12332    /// answers [`InputBaseState::set_search_query`] and the other search
12333    /// methods, and lets `Ctrl-F` / `Cmd-F` bubble up to its ancestors, so an
12334    /// application can put its own search UI on top of the same engine.
12335    pub fn searchable(mut self, searchable: bool) -> Self {
12336        self.searchable = searchable;
12337        self
12338    }
12339
12340    /// See [`InputBaseState::searchable`].
12341    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
12342        self.searchable = searchable;
12343        cx.notify();
12344    }
12345
12346    /// Set the soft wrap mode, default is true.
12347    #[doc(hidden)]
12348    pub fn soft_wrap(mut self, wrap: bool) -> Self {
12349        self.soft_wrap = wrap;
12350        self
12351    }
12352
12353    /// Update the soft wrap mode, default is true.
12354    pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
12355        self.soft_wrap = wrap;
12356        if wrap {
12357            let wrap_width = self
12358                .last_layout
12359                .as_ref()
12360                .and_then(|b| b.wrap_width)
12361                .unwrap_or(self.input_bounds.size.width);
12362
12363            self.display_map.on_layout_changed(Some(wrap_width), cx);
12364
12365            // Reset scroll to left 0
12366            let mut offset = self.scroll_handle.offset();
12367            offset.x = px(0.);
12368            self.scroll_handle.set_offset(offset);
12369        } else {
12370            self.display_map.on_layout_changed(None, cx);
12371        }
12372        cx.notify();
12373    }
12374
12375    /// Set how soft-wrapped continuation lines are indented, default is [`WrappingIndent::Same`]
12376    #[doc(hidden)]
12377    pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
12378        self.wrapping_indent = wrapping_indent;
12379        self
12380    }
12381
12382    /// Update how soft-wrapped continuation lines are indented.
12383    pub fn set_wrapping_indent(
12384        &mut self,
12385        wrapping_indent: WrappingIndent,
12386        _: &mut Window,
12387        cx: &mut Context<Self>,
12388    ) {
12389        self.wrapping_indent = wrapping_indent;
12390        self.display_map.set_wrapping_indent(wrapping_indent, cx);
12391        cx.notify();
12392    }
12393}
12394
12395/// Methods that only ordinary multi-line text offers.
12396impl InputBaseState<crate::input::TextareaMode> {
12397    /// Create a multi-line text state.
12398    ///
12399    /// Being multi-line is carried by the mode, not by the layout, so the
12400    /// default plain-text layout needs no adjustment here.
12401    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
12402        Self::new_in_mode(window, cx)
12403    }
12404
12405    pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
12406        self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
12407        self.mode.update_auto_grow(&self.display_map);
12408        cx.notify();
12409    }
12410
12411    /// Set the number of rows for the multi-line Textarea.
12412    ///
12413    /// This is only used when `multi_line` is set to true. The input is at least
12414    /// this many lines tall.
12415    ///
12416    /// default: 1
12417    #[doc(hidden)]
12418    pub fn rows(mut self, rows: usize) -> Self {
12419        match &mut self.mode {
12420            LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
12421                *r = rows
12422            }
12423            LayoutMode::AutoGrow {
12424                max_rows: max_r,
12425                rows: r,
12426                ..
12427            } => {
12428                *r = rows;
12429                *max_r = rows;
12430            }
12431        }
12432        self
12433    }
12434
12435    pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
12436        match &mut self.mode {
12437            LayoutMode::PlainText { rows: value, .. }
12438            | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
12439            LayoutMode::AutoGrow {
12440                rows: value,
12441                max_rows,
12442                ..
12443            } => {
12444                *value = rows;
12445                *max_rows = rows;
12446            }
12447        }
12448        cx.notify();
12449    }
12450
12451    /// Grow with the content from `min_rows` through `max_rows`.
12452    pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
12453        self.mode = LayoutMode::auto_grow(min_rows, max_rows);
12454        self
12455    }
12456}
12457
12458/// Methods that only a source-code editor offers.
12459impl InputBaseState<crate::input::EditorMode> {
12460    /// Create a source-code editor state.
12461    ///
12462    /// Default options: line numbers on, tab size 2 with soft tabs, indent
12463    /// guides on, multi-line, and search enabled. Set the language for syntax
12464    /// highlighting with [`Self::language`]; without one the text is shown
12465    /// unhighlighted.
12466    ///
12467    /// The editor aims at simple code editing or display, not at being a
12468    /// full-featured code editor. It offers syntax highlighting, auto indent,
12469    /// line numbers, and handles large text up to about 50K lines.
12470    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
12471        let mut state = Self::new_in_mode(window, cx);
12472        state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
12473        state.searchable = true;
12474        state
12475    }
12476
12477    /// Set the language to highlight, e.g. `"rust"`.
12478    ///
12479    /// See [`Self::set_highlighter`] to change it after construction.
12480    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
12481        if let LayoutMode::CodeEditor {
12482            language: l,
12483            highlighter,
12484            ..
12485        } = &mut self.mode
12486        {
12487            l.set_name(language.into());
12488            *highlighter.borrow_mut() = None;
12489        }
12490        self
12491    }
12492
12493    /// The current language name, e.g. `"rust"`.
12494    pub fn language_name(&self) -> SharedString {
12495        match &self.mode {
12496            LayoutMode::CodeEditor { language, .. } => language.name(),
12497            _ => SharedString::default(),
12498        }
12499    }
12500
12501    /// Set enable/disable code folding.
12502    ///
12503    /// Default: true
12504    #[doc(hidden)]
12505    pub fn folding(mut self, folding: bool) -> Self {
12506        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
12507            *f = folding;
12508        }
12509        self
12510    }
12511
12512    /// Set code folding at runtime.
12513    ///
12514    /// When disabling, all existing folds are cleared.
12515    pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
12516        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
12517            *f = folding;
12518        }
12519        if !folding {
12520            self.display_map.clear_folds();
12521        }
12522        cx.notify();
12523    }
12524
12525    /// Unfold any folded ranges that hide the given position.
12526    ///
12527    /// Use this to reveal a position before acting on it (e.g. before
12528    /// [`Self::set_cursor_position`], which stops at a fold boundary),
12529    /// without touching folds elsewhere in the buffer. Fold candidates are
12530    /// kept, so the opened ranges can be folded again from the gutter.
12531    ///
12532    /// A fold keeps its own first and last line visible, so a position on
12533    /// either of them opens nothing. Nested folds all open, since opening
12534    /// only the outermost would leave the position hidden.
12535    ///
12536    /// Returns whether any fold was opened.
12537    pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
12538        let offset = self.text.position_to_offset(&position.into());
12539        let line = self.text.offset_to_point(offset).row;
12540        // A fold hides start_line + 1 ..= end_line - 1, so a line is hidden
12541        // exactly when some folded range strictly contains it.
12542        let covering: Vec<usize> = self
12543            .display_map
12544            .folded_ranges()
12545            .iter()
12546            .filter(|fold| line > fold.start_line && line < fold.end_line)
12547            .map(|fold| fold.start_line)
12548            .collect();
12549        if covering.is_empty() {
12550            return false;
12551        }
12552
12553        for start_line in covering {
12554            self.display_map.set_folded(start_line, false);
12555        }
12556        cx.notify();
12557        true
12558    }
12559
12560    /// Set enable/disable line number.
12561    #[doc(hidden)]
12562    pub fn line_number(mut self, line_number: bool) -> Self {
12563        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
12564            *l = line_number;
12565        }
12566        self
12567    }
12568
12569    /// Set line number.
12570    pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
12571        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
12572            if *l == line_number {
12573                return;
12574            }
12575            *l = line_number;
12576        }
12577        cx.notify();
12578    }
12579
12580    /// Set enable/disable automatic closing brackets and quotes.
12581    ///
12582    /// When enabled, typing an opener from [`LanguageConfig::auto_closing_pairs`](crate::input::language_config::LanguageConfig::auto_closing_pairs) inserts the
12583    /// matching closer and places the cursor inside. Typing a closer that is
12584    /// already present just moves past it. Default: true
12585    #[doc(hidden)]
12586    pub fn auto_close(mut self, auto_close: bool) -> Self {
12587        self.mode.set_auto_close(auto_close);
12588        self
12589    }
12590
12591    /// Set automatic closing brackets and quotes at runtime.
12592    pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
12593        self.mode.set_auto_close(auto_close);
12594        cx.notify();
12595    }
12596
12597    /// Set enable/disable smart indent on Enter.
12598    ///
12599    /// When enabled, Enter uses structural brackets and
12600    /// [`LanguageConfig::indentation_rules`](crate::input::language_config::LanguageConfig::indentation_rules) to choose indentation.
12601    /// Default: true
12602    #[doc(hidden)]
12603    pub fn smart_indent(mut self, smart_indent: bool) -> Self {
12604        self.mode.set_smart_indent(smart_indent);
12605        self
12606    }
12607
12608    /// Set smart indent on Enter at runtime.
12609    pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
12610        self.mode.set_smart_indent(smart_indent);
12611        cx.notify();
12612    }
12613}