Skip to main content

sui_widgets/
text_surface.rs

1use std::ops::Range;
2
3use sui_core::{
4    Color, EditableTextSemantics, Event, ImeEvent, InvalidationKind, InvalidationRequest,
5    InvalidationTarget, KeyState, KeyboardEvent, Path, Point, PointerButton, PointerEventKind,
6    Rect, ScrollDelta, SemanticsAction, SemanticsNode, SemanticsRole, SemanticsTextRange,
7    SemanticsValue, Size, Vector, WakeEvent, WidgetId, WindowEvent,
8};
9use sui_layout::{Constraints, Padding as Insets};
10use sui_runtime::{
11    Command, EventCtx, EventPhase, LayerOptions, MeasureCtx, PaintBoundaryMode, PaintCtx,
12    SemanticsCtx, Widget,
13};
14use sui_scene::{LayerCompositionMode, StrokeStyle};
15use sui_text::{
16    PersistentTextLayout, TextCursor, TextDirection, TextDocument, TextLayoutRequest,
17    TextParagraph, TextSelection, TextSpan, TextStyle, TextWrap,
18};
19
20use crate::{
21    DefaultTheme, MotionScalar, ThemeColorScheme,
22    editor::{
23        EditorCommand, EditorCommandResult, EditorDocument, EditorState, EditorTextEdit,
24        clamp_to_grapheme_boundary, selection_range,
25    },
26    selection::{SelectionChange, SelectionOwnerId, SelectionScope},
27    text_align::paint_aligned_text,
28    text_command::TextCommand,
29};
30
31#[derive(Debug, Clone, PartialEq)]
32pub struct TextSurfaceStyleSpan {
33    pub range: Range<usize>,
34    pub style: TextStyle,
35}
36
37impl TextSurfaceStyleSpan {
38    pub fn new(range: Range<usize>, style: TextStyle) -> Self {
39        Self { range, style }
40    }
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub enum TextSurfaceOverlayKind {
45    Syntax,
46    Diagnostic,
47    SearchMatch,
48    CurrentLine,
49    RichTextPreview,
50    Custom(String),
51}
52
53#[derive(Debug, Clone, PartialEq)]
54pub struct TextSurfaceStyleOverlay {
55    pub range: Range<usize>,
56    pub style: TextStyle,
57    pub kind: TextSurfaceOverlayKind,
58}
59
60impl TextSurfaceStyleOverlay {
61    pub fn new(range: Range<usize>, style: TextStyle, kind: TextSurfaceOverlayKind) -> Self {
62        Self { range, style, kind }
63    }
64}
65
66#[derive(Debug, Clone, Copy)]
67struct IndexedTextRange {
68    source_index: usize,
69    start: usize,
70    end: usize,
71}
72
73#[derive(Debug, Clone, Default)]
74struct TextSurfaceRangeIndex {
75    by_start: Vec<IndexedTextRange>,
76    prefix_max_end: Vec<usize>,
77}
78
79impl TextSurfaceRangeIndex {
80    fn rebuild(&mut self, ranges: impl IntoIterator<Item = (usize, usize)>) {
81        self.by_start = ranges
82            .into_iter()
83            .enumerate()
84            .map(|(source_index, (start, end))| IndexedTextRange {
85                source_index,
86                start,
87                end,
88            })
89            .collect();
90        self.by_start
91            .sort_unstable_by_key(|range| (range.start, range.end, range.source_index));
92
93        self.prefix_max_end.clear();
94        self.prefix_max_end.reserve(self.by_start.len());
95        let mut max_end = 0;
96        for range in &self.by_start {
97            max_end = max_end.max(range.end);
98            self.prefix_max_end.push(max_end);
99        }
100    }
101
102    fn overlapping_indices(&self, query: &Range<usize>) -> Vec<usize> {
103        if query.is_empty() {
104            return Vec::new();
105        }
106
107        let upper = self
108            .by_start
109            .partition_point(|range| range.start < query.end);
110        let lower = self.prefix_max_end[..upper].partition_point(|max_end| *max_end <= query.start);
111        let mut indices = self.by_start[lower..upper]
112            .iter()
113            .filter(|range| query.start < range.end)
114            .map(|range| range.source_index)
115            .collect::<Vec<_>>();
116        // Source order defines precedence: later spans override earlier spans,
117        // and overlays are applied after ordinary spans.
118        indices.sort_unstable();
119        indices
120    }
121}
122
123pub struct TextSurface {
124    theme: Box<DefaultTheme>,
125    theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
126    name: String,
127    placeholder: String,
128    read_only: bool,
129    editor: EditorState,
130    text_style: Option<TextStyle>,
131    text_style_reader: Option<Box<dyn Fn(DefaultTheme) -> TextStyle>>,
132    padding: Option<Insets>,
133    min_width: Option<f32>,
134    min_height: Option<f32>,
135    wrap: TextWrap,
136    direction: TextDirection,
137    style_spans: Vec<TextSurfaceStyleSpan>,
138    style_span_index: TextSurfaceRangeIndex,
139    style_span_max_line_height: f32,
140    style_overlays: Vec<TextSurfaceStyleOverlay>,
141    style_overlay_index: TextSurfaceRangeIndex,
142    style_overlay_max_line_height: f32,
143    style_revision: u64,
144    hovered: bool,
145    hover_animation: AnimatedScalar,
146    focus_animation: AnimatedScalar,
147    dragging_selection: bool,
148    layout: Option<PersistentTextLayout>,
149    line_layouts: Vec<Option<PersistentTextLayout>>,
150    line_offsets: Vec<usize>,
151    line_lengths: Vec<usize>,
152    line_layout_box_size: Option<Size>,
153    line_layout_style: Option<TextStyle>,
154    line_layout_revision: u64,
155    line_layout_style_revision: u64,
156    selection_scope: Option<SelectionScope>,
157    on_change: Option<Box<dyn FnMut(String)>>,
158}
159
160impl TextSurface {
161    pub fn new(name: impl Into<String>) -> Self {
162        Self {
163            theme: Box::new(DefaultTheme::default()),
164            theme_reader: None,
165            name: name.into(),
166            placeholder: String::new(),
167            read_only: false,
168            editor: EditorState::new(),
169            text_style: None,
170            text_style_reader: None,
171            padding: None,
172            min_width: None,
173            min_height: None,
174            wrap: TextWrap::NoWrap,
175            direction: TextDirection::Auto,
176            style_spans: Vec::new(),
177            style_span_index: TextSurfaceRangeIndex::default(),
178            style_span_max_line_height: 0.0,
179            style_overlays: Vec::new(),
180            style_overlay_index: TextSurfaceRangeIndex::default(),
181            style_overlay_max_line_height: 0.0,
182            style_revision: 0,
183            hovered: false,
184            hover_animation: AnimatedScalar::new(0.0),
185            focus_animation: AnimatedScalar::new(0.0),
186            dragging_selection: false,
187            layout: None,
188            line_layouts: Vec::new(),
189            line_offsets: Vec::new(),
190            line_lengths: Vec::new(),
191            line_layout_box_size: None,
192            line_layout_style: None,
193            line_layout_revision: u64::MAX,
194            line_layout_style_revision: u64::MAX,
195            selection_scope: None,
196            on_change: None,
197        }
198    }
199
200    pub fn theme(mut self, theme: DefaultTheme) -> Self {
201        self.theme = Box::new(theme);
202        self.theme_reader = None;
203        self
204    }
205
206    pub fn theme_when<F>(mut self, theme: F) -> Self
207    where
208        F: Fn() -> DefaultTheme + 'static,
209    {
210        self.theme_reader = Some(Box::new(theme));
211        self
212    }
213
214    pub fn text_style(mut self, text_style: TextStyle) -> Self {
215        self.text_style = Some(text_style);
216        self.text_style_reader = None;
217        self
218    }
219
220    pub fn text_style_when<F>(mut self, text_style: F) -> Self
221    where
222        F: Fn(DefaultTheme) -> TextStyle + 'static,
223    {
224        self.text_style_reader = Some(Box::new(text_style));
225        self.text_style = None;
226        self
227    }
228
229    pub fn padding(mut self, padding: Insets) -> Self {
230        self.padding = Some(padding);
231        self
232    }
233
234    pub fn min_width(mut self, width: f32) -> Self {
235        self.min_width = Some(width.max(0.0));
236        self
237    }
238
239    pub fn min_height(mut self, height: f32) -> Self {
240        self.min_height = Some(height.max(0.0));
241        self
242    }
243
244    pub fn wrap(mut self, wrap: TextWrap) -> Self {
245        self.wrap = wrap;
246        if self.wrap != TextWrap::NoWrap {
247            self.editor.set_scroll(0.0, self.editor.scroll_y());
248        }
249        self.invalidate_line_layouts();
250        self
251    }
252
253    pub fn direction(mut self, direction: TextDirection) -> Self {
254        self.direction = direction;
255        self.invalidate_line_layouts();
256        self
257    }
258
259    pub fn style_spans(mut self, spans: Vec<TextSurfaceStyleSpan>) -> Self {
260        self.set_style_spans(spans);
261        self
262    }
263
264    pub fn set_style_spans(&mut self, spans: Vec<TextSurfaceStyleSpan>) {
265        self.style_spans = spans;
266        self.style_span_index.rebuild(
267            self.style_spans
268                .iter()
269                .map(|span| (span.range.start, span.range.end)),
270        );
271        self.style_span_max_line_height = self
272            .style_spans
273            .iter()
274            .map(|span| span.style.line_height.max(span.style.font_size))
275            .fold(0.0, f32::max);
276        self.bump_style_revision();
277    }
278
279    pub fn current_style_spans(&self) -> &[TextSurfaceStyleSpan] {
280        &self.style_spans
281    }
282
283    pub fn style_overlays(mut self, overlays: Vec<TextSurfaceStyleOverlay>) -> Self {
284        self.set_style_overlays(overlays);
285        self
286    }
287
288    pub fn set_style_overlays(&mut self, overlays: Vec<TextSurfaceStyleOverlay>) {
289        self.style_overlays = overlays;
290        self.style_overlay_index.rebuild(
291            self.style_overlays
292                .iter()
293                .map(|overlay| (overlay.range.start, overlay.range.end)),
294        );
295        self.style_overlay_max_line_height = self
296            .style_overlays
297            .iter()
298            .map(|overlay| overlay.style.line_height.max(overlay.style.font_size))
299            .fold(0.0, f32::max);
300        self.bump_style_revision();
301    }
302
303    pub fn current_style_overlays(&self) -> &[TextSurfaceStyleOverlay] {
304        &self.style_overlays
305    }
306
307    pub fn value(mut self, value: impl Into<String>) -> Self {
308        self.set_value(value);
309        self
310    }
311
312    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
313        self.placeholder = placeholder.into();
314        self
315    }
316
317    pub fn read_only(mut self) -> Self {
318        self.read_only = true;
319        self
320    }
321
322    pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
323        self.selection_scope = Some(selection_scope);
324        self
325    }
326
327    pub fn selection_scope(mut self, selection_scope: SelectionScope) -> Self {
328        self.selection_scope = Some(selection_scope);
329        self
330    }
331
332    pub fn current_value(&self) -> &str {
333        self.editor.document().text()
334    }
335
336    pub fn set_value(&mut self, value: impl Into<String>) {
337        self.editor.set_text(value);
338        self.invalidate_line_layouts();
339    }
340
341    pub fn on_change<F>(mut self, on_change: F) -> Self
342    where
343        F: FnMut(String) + 'static,
344    {
345        self.on_change = Some(Box::new(on_change));
346        self
347    }
348
349    fn resolved_theme(&self) -> DefaultTheme {
350        self.theme_reader
351            .as_ref()
352            .map(|theme| theme())
353            .unwrap_or(*self.theme)
354    }
355
356    fn resolved_text_style(&self) -> TextStyle {
357        let theme = self.resolved_theme();
358        if let Some(text_style) = &self.text_style_reader {
359            return text_style(theme);
360        }
361        self.text_style
362            .clone()
363            .unwrap_or_else(|| theme.body_text_style())
364    }
365
366    fn display_text_style(&self) -> TextStyle {
367        let theme = self.resolved_theme();
368        let mut style = self.resolved_text_style();
369        if self.read_only {
370            style.color = theme.palette.text_muted;
371        }
372        style
373    }
374
375    fn placeholder_text_style(&self) -> TextStyle {
376        let theme = self.resolved_theme();
377        let mut style = self.resolved_text_style();
378        style.color = theme.palette.placeholder;
379        style
380    }
381
382    fn should_show_placeholder(&self) -> bool {
383        self.display_text_len() == 0 && !self.placeholder.is_empty()
384    }
385
386    fn resolved_padding(&self) -> Insets {
387        let theme = self.resolved_theme();
388        self.padding.unwrap_or(theme.metrics.text_input_padding)
389    }
390
391    fn resolved_min_size(&self) -> Size {
392        let theme = self.resolved_theme();
393        Size::new(
394            self.min_width.unwrap_or(theme.metrics.text_input_min_width),
395            self.min_height
396                .unwrap_or(theme.metrics.text_area_min_height),
397        )
398    }
399
400    fn bump_style_revision(&mut self) {
401        self.style_revision = self.style_revision.saturating_add(1);
402        self.invalidate_line_layouts();
403    }
404
405    fn rebase_style_ranges_after_edit(&mut self, edit: &EditorTextEdit) {
406        self.style_spans.retain_mut(|span| {
407            let Some(range) = rebased_text_range(&span.range, edit) else {
408                return false;
409            };
410            span.range = range;
411            true
412        });
413        self.style_overlays.retain_mut(|overlay| {
414            let Some(range) = rebased_text_range(&overlay.range, edit) else {
415                return false;
416            };
417            overlay.range = range;
418            true
419        });
420        self.style_span_index.rebuild(
421            self.style_spans
422                .iter()
423                .map(|span| (span.range.start, span.range.end)),
424        );
425        self.style_overlay_index.rebuild(
426            self.style_overlays
427                .iter()
428                .map(|overlay| (overlay.range.start, overlay.range.end)),
429        );
430    }
431
432    fn invalidate_line_layouts(&mut self) {
433        self.layout = None;
434        self.line_layouts.clear();
435        self.line_offsets.clear();
436        self.line_lengths.clear();
437        self.line_layout_box_size = None;
438        self.line_layout_style = None;
439        self.line_layout_revision = u64::MAX;
440        self.line_layout_style_revision = u64::MAX;
441    }
442
443    fn reconcile_composition_line_layouts(
444        &mut self,
445        line_texts: &[String],
446        line_offsets: Vec<usize>,
447        line_lengths: Vec<usize>,
448        line_box_size: Size,
449        line_style: &TextStyle,
450    ) {
451        let metadata_matches = self.line_layout_box_size == Some(line_box_size)
452            && self.line_layout_style.as_ref() == Some(line_style)
453            && self.line_layout_style_revision == self.style_revision;
454        let previous_offsets = std::mem::replace(&mut self.line_offsets, line_offsets);
455        let previous_lengths = std::mem::replace(&mut self.line_lengths, line_lengths);
456        let mut previous_layouts = std::mem::take(&mut self.line_layouts);
457        let mut next_layouts = Vec::with_capacity(line_texts.len());
458
459        for (index, line_text) in line_texts.iter().enumerate() {
460            let can_reuse = metadata_matches
461                && previous_offsets.get(index) == self.line_offsets.get(index)
462                && previous_lengths.get(index) == self.line_lengths.get(index);
463            let layout = can_reuse
464                .then(|| previous_layouts.get_mut(index).and_then(Option::take))
465                .flatten()
466                .filter(|layout| layout.text() == line_text);
467            next_layouts.push(layout);
468        }
469
470        self.line_layouts = next_layouts;
471    }
472
473    fn single_line_composition_display_line(&self) -> Option<(usize, String)> {
474        let composition = self.editor.composition()?;
475        if composition.text.contains('\n') {
476            return None;
477        }
478
479        let document = self.editor.document();
480        let line_index = document.line_index_for_offset(composition.replacement_range.start);
481        let line_range = document.line_range(line_index);
482        if composition.replacement_range.end > line_range.end {
483            return None;
484        }
485
486        let mut line_text = document.line_text(line_index).to_string();
487        let local_range = composition
488            .replacement_range
489            .start
490            .saturating_sub(line_range.start)
491            ..composition
492                .replacement_range
493                .end
494                .saturating_sub(line_range.start);
495        line_text.replace_range(local_range, &composition.text);
496        Some((line_index, line_text))
497    }
498
499    fn reconcile_single_line_composition_layouts(
500        &mut self,
501        composition_line: usize,
502        composition_line_len: usize,
503        line_box_size: Size,
504        line_style: &TextStyle,
505    ) {
506        let line_count = self.editor.document().line_count();
507        let can_reuse = self.line_layout_box_size == Some(line_box_size)
508            && self.line_layout_style.as_ref() == Some(line_style)
509            && self.line_layout_style_revision == self.style_revision
510            && self.line_layouts.len() == line_count
511            && self.line_offsets.len() == line_count
512            && self.line_lengths.len() == line_count;
513        if !can_reuse {
514            self.line_layouts = vec![None; line_count];
515            self.line_offsets.resize(line_count, 0);
516            self.line_lengths.resize(line_count, 0);
517        }
518
519        let document_line_len = self.editor.document().line_range(composition_line).len();
520        let inserted_delta = composition_line_len.saturating_sub(document_line_len);
521        let removed_delta = document_line_len.saturating_sub(composition_line_len);
522
523        for index in 0..line_count {
524            let document_range = self.editor.document().line_range(index);
525            let display_start = if index <= composition_line {
526                document_range.start
527            } else if inserted_delta > 0 {
528                document_range.start + inserted_delta
529            } else {
530                document_range.start - removed_delta
531            };
532            let display_len = if index == composition_line {
533                composition_line_len
534            } else {
535                document_range.len()
536            };
537            self.line_offsets[index] = display_start;
538            self.line_lengths[index] = display_len;
539            if !can_reuse || index == composition_line {
540                self.line_layouts[index] = None;
541            }
542        }
543    }
544
545    fn refresh_reusable_document_line_metadata(
546        document: &EditorDocument,
547        line_layouts: &mut [Option<PersistentTextLayout>],
548        line_offsets: &mut [usize],
549        line_lengths: &mut [usize],
550    ) {
551        if let Some(start) = document.line_offsets_dirty_from() {
552            for index in start.min(document.line_count())..document.line_count() {
553                let line_range = document.line_range(index);
554                line_offsets[index] = line_range.start;
555                line_lengths[index] = line_range.len();
556            }
557        }
558
559        for index in document.dirty_line_range() {
560            if index < line_layouts.len() {
561                let line_range = document.line_range(index);
562                line_offsets[index] = line_range.start;
563                line_lengths[index] = line_range.len();
564                line_layouts[index] = None;
565            }
566        }
567    }
568
569    fn selection_range(&self) -> Range<usize> {
570        self.editor.selection_range()
571    }
572
573    fn display_text(&self) -> String {
574        self.editor.display_text()
575    }
576
577    fn display_text_len(&self) -> usize {
578        if let Some(composition) = self.editor.composition() {
579            self.editor
580                .document()
581                .len()
582                .saturating_sub(composition.replacement_range.len())
583                .saturating_add(composition.text.len())
584        } else {
585            self.editor.document().len()
586        }
587    }
588
589    fn display_selection(&self) -> TextSelection {
590        self.editor.display_selection()
591    }
592
593    fn layout_box_width(&self, available_width: f32) -> f32 {
594        if self.wrap == TextWrap::NoWrap {
595            1_000_000.0
596        } else {
597            available_width.max(1.0)
598        }
599    }
600
601    fn layout_box_size(&self, available_width: f32) -> Size {
602        let style = self.resolved_text_style();
603        let estimated_lines = if self.editor.composition().is_some() {
604            self.display_text().lines().count().max(1)
605        } else {
606            self.editor.document().line_count().max(1)
607        } as f32;
608        Size::new(
609            self.layout_box_width(available_width),
610            (estimated_lines * style.line_height).max(style.line_height),
611        )
612    }
613
614    fn content_rect(&self, bounds: Rect) -> Rect {
615        inset_rect(bounds, self.resolved_padding())
616    }
617
618    fn content_viewport_size(&self, bounds: Rect) -> Size {
619        self.content_rect(bounds).size
620    }
621
622    fn commit_text_change(&mut self) {
623        let value = self.current_value().to_string();
624        if let Some(on_change) = &mut self.on_change {
625            on_change(value);
626        }
627    }
628
629    fn apply_editor_result(&mut self, ctx: &mut EventCtx, mut result: EditorCommandResult) {
630        let copied_to_clipboard = result.clipboard_text.is_some();
631        if let Some(text) = result.clipboard_text.take() {
632            ctx.set_clipboard_text(text);
633        }
634        if result.text_changed {
635            if let Some(edit) = self.editor.take_text_edit() {
636                self.rebase_style_ranges_after_edit(&edit);
637            }
638            self.commit_text_change();
639        }
640        if result.layout_changed() {
641            ctx.request_text();
642        } else if result.overlay_changed() {
643            self.request_after_overlay_change(ctx);
644        }
645        if result.text_changed || result.selection_changed || result.composition_changed {
646            sync_editor_selection_scope(ctx, self.selection_scope.as_ref(), &self.editor);
647            if !result.layout_changed() {
648                ctx.request_semantics();
649            }
650        }
651        if result.handled && !(copied_to_clipboard && self.selection_scope.is_some()) {
652            ctx.set_handled();
653        }
654    }
655
656    fn execute_editor_command(
657        &mut self,
658        ctx: &mut EventCtx,
659        command: EditorCommand,
660    ) -> EditorCommandResult {
661        let result = self.editor.execute(command);
662        self.apply_editor_result(ctx, result.clone());
663        result
664    }
665
666    /// Select the entire document.
667    pub fn select_all(&mut self, ctx: &mut EventCtx) {
668        self.execute_editor_command(ctx, EditorCommand::SelectAll);
669    }
670
671    /// Copy the current selection to the clipboard. No-op when the selection
672    /// is collapsed.
673    pub fn copy(&mut self, ctx: &mut EventCtx) {
674        self.execute_editor_command(ctx, EditorCommand::Copy);
675    }
676
677    /// Copy the current selection to the clipboard and delete it. No-op when
678    /// read-only or the selection is collapsed.
679    pub fn cut(&mut self, ctx: &mut EventCtx) {
680        if self.read_only {
681            return;
682        }
683        self.execute_editor_command(ctx, EditorCommand::Cut);
684    }
685
686    /// Replace the current selection with the clipboard text. No-op when
687    /// read-only or the clipboard has no text.
688    pub fn paste(&mut self, ctx: &mut EventCtx) {
689        if self.read_only {
690            return;
691        }
692        let command = paste_command(ctx);
693        self.execute_editor_command(ctx, command);
694    }
695
696    /// Currently selected document text (empty when the selection is
697    /// collapsed).
698    pub fn selected_text(&self) -> &str {
699        self.editor.selected_text()
700    }
701
702    fn apply_text_command(&mut self, ctx: &mut EventCtx, command: TextCommand) {
703        match command {
704            TextCommand::SelectAll => self.select_all(ctx),
705            TextCommand::Copy => self.copy(ctx),
706            TextCommand::Cut => self.cut(ctx),
707            TextCommand::Paste => self.paste(ctx),
708        }
709    }
710
711    fn move_line_boundary(&mut self, to_start: bool, extend: bool) -> EditorCommandResult {
712        let focus = if extend {
713            self.editor.selection().focus.utf8_offset
714        } else {
715            self.selection_range().end
716        };
717
718        let target = if self.has_line_layout_cache() {
719            let line_index = self.line_index_for_offset(focus);
720            if to_start {
721                self.line_offsets[line_index]
722            } else {
723                self.line_offsets[line_index] + self.line_lengths[line_index]
724            }
725        } else if let Some(layout) = self.layout.as_ref() {
726            let caret = layout.caret(TextCursor::new(focus));
727            let line = &layout.lines()[caret.line_index];
728            if to_start {
729                line.byte_range.start
730            } else {
731                line.byte_range.end
732            }
733        } else {
734            return self.editor.execute(if to_start {
735                EditorCommand::MoveLineStart { extend }
736            } else {
737                EditorCommand::MoveLineEnd { extend }
738            });
739        };
740
741        self.editor.execute(EditorCommand::MoveTo {
742            offset: target,
743            extend,
744        })
745    }
746
747    fn move_vertical(
748        &mut self,
749        delta_lines: isize,
750        extend: bool,
751        _viewport_height: f32,
752    ) -> EditorCommandResult {
753        let focus = if extend {
754            self.editor.selection().focus.utf8_offset
755        } else {
756            self.selection_range().end
757        };
758
759        if self.has_line_layout_cache() {
760            let Some(caret) = self.caret_rect_for_cursor(TextCursor::new(focus)) else {
761                return EditorCommandResult::default();
762            };
763            let preferred_x = self.editor.preferred_x().unwrap_or(caret.x());
764            let line_index = self.line_index_for_offset(focus) as isize + delta_lines;
765            let target_line =
766                line_index.clamp(0, self.line_count().saturating_sub(1) as isize) as usize;
767            let local_offset = if let Some(Some(layout)) = self.line_layouts.get(target_line) {
768                let Some(line) = layout.lines().first() else {
769                    return EditorCommandResult::default();
770                };
771                let local = layout.hit_test_point(Point::new(
772                    preferred_x,
773                    line.rect.y() + (line.rect.height() * 0.5),
774                ));
775                local.utf8_offset.min(self.line_lengths[target_line])
776            } else {
777                self.estimate_inline_offset_for_x(target_line, preferred_x)
778            };
779            let target = self.line_offsets[target_line] + local_offset;
780            let result = self.editor.execute(EditorCommand::MoveTo {
781                offset: target,
782                extend,
783            });
784            self.editor.set_preferred_x(Some(preferred_x));
785            return result;
786        }
787
788        let Some(layout) = self.layout.as_ref() else {
789            let lines = delta_lines.unsigned_abs().max(1);
790            return self.editor.execute(if delta_lines < 0 {
791                if lines == 1 {
792                    EditorCommand::MoveUp { extend }
793                } else {
794                    EditorCommand::PageUp { extend, lines }
795                }
796            } else if lines == 1 {
797                EditorCommand::MoveDown { extend }
798            } else {
799                EditorCommand::PageDown { extend, lines }
800            });
801        };
802        if layout.lines().is_empty() {
803            return EditorCommandResult::default();
804        }
805        let caret = layout.caret(TextCursor::new(focus));
806        let preferred_x = self.editor.preferred_x().unwrap_or(caret.rect.x());
807        let line_index = caret.line_index as isize + delta_lines;
808        let target_line =
809            line_index.clamp(0, layout.lines().len().saturating_sub(1) as isize) as usize;
810        let line = &layout.lines()[target_line];
811        let target = layout.hit_test_point(Point::new(
812            preferred_x,
813            line.rect.y() + (line.rect.height() * 0.5),
814        ));
815        let result = self.editor.execute(EditorCommand::MoveTo {
816            offset: target.utf8_offset,
817            extend,
818        });
819        self.editor.set_preferred_x(Some(preferred_x));
820        result
821    }
822
823    fn shape_line_layout(
824        &self,
825        ctx: &mut MeasureCtx,
826        handle: Option<sui_text::TextLayoutHandle>,
827        line_text: &str,
828        line_range: Range<usize>,
829        line_box_size: Size,
830        base_style: TextStyle,
831    ) -> sui_core::Result<PersistentTextLayout> {
832        if self.style_spans.is_empty() && self.style_overlays.is_empty() {
833            return ctx.layout().shape_text_persistent(
834                handle,
835                line_text.to_string(),
836                line_box_size,
837                base_style,
838            );
839        }
840
841        let spans = self.line_text_spans(line_text, line_range, base_style);
842        let mut paragraph = TextParagraph::from_spans(spans);
843        paragraph.style.direction = self.direction;
844        paragraph.style.wrap = self.wrap;
845        ctx.layout().layout_document_persistent(
846            handle,
847            TextLayoutRequest::new(TextDocument {
848                paragraphs: vec![paragraph],
849            })
850            .with_box_size(line_box_size),
851        )
852    }
853
854    fn line_text_spans(
855        &self,
856        line_text: &str,
857        line_range: Range<usize>,
858        base_style: TextStyle,
859    ) -> Vec<TextSpan> {
860        let style_indices = self.style_span_index.overlapping_indices(&line_range);
861        let overlay_indices = self.style_overlay_index.overlapping_indices(&line_range);
862        let mut breaks =
863            Vec::with_capacity(2 + (style_indices.len() + overlay_indices.len()).saturating_mul(2));
864        breaks.extend([0, line_text.len()]);
865        for index in &style_indices {
866            Self::collect_style_breaks(
867                &self.style_spans[*index].range,
868                &line_range,
869                line_text,
870                &mut breaks,
871            );
872        }
873        for index in &overlay_indices {
874            Self::collect_style_breaks(
875                &self.style_overlays[*index].range,
876                &line_range,
877                line_text,
878                &mut breaks,
879            );
880        }
881
882        breaks.sort_unstable();
883        breaks.dedup();
884
885        let mut spans = Vec::new();
886        for pair in breaks.windows(2) {
887            let start = pair[0];
888            let end = pair[1];
889            if start >= end {
890                continue;
891            }
892            let global_range = line_range.start + start..line_range.start + end;
893            let mut style = base_style.clone();
894            for index in &style_indices {
895                let span = &self.style_spans[*index];
896                if ranges_intersect(&global_range, &span.range) {
897                    style = span.style.clone();
898                }
899            }
900            for index in &overlay_indices {
901                let overlay = &self.style_overlays[*index];
902                if ranges_intersect(&global_range, &overlay.range) {
903                    style = overlay.style.clone();
904                }
905            }
906            spans.push(TextSpan::new(line_text[start..end].to_string(), style));
907        }
908
909        if spans.is_empty() {
910            spans.push(TextSpan::new(String::new(), base_style));
911        }
912        spans
913    }
914
915    fn collect_style_breaks(
916        span_range: &Range<usize>,
917        line_range: &Range<usize>,
918        line_text: &str,
919        breaks: &mut Vec<usize>,
920    ) {
921        if !ranges_intersect(line_range, span_range) {
922            return;
923        }
924        let local_start = span_range.start.saturating_sub(line_range.start);
925        let local_end = span_range
926            .end
927            .min(line_range.end)
928            .saturating_sub(line_range.start);
929        breaks.push(clamp_to_grapheme_boundary(line_text, local_start));
930        breaks.push(clamp_to_grapheme_boundary(line_text, local_end));
931    }
932
933    fn update_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
934        if self.hovered != hovered {
935            let theme = self.resolved_theme();
936            self.hovered = hovered;
937            set_hover_animation_target(
938                &mut self.hover_animation,
939                hovered as u8 as f32,
940                &theme,
941                ctx,
942            );
943            ctx.request_paint();
944            ctx.request_semantics();
945        }
946    }
947
948    fn advance_animations(&mut self, time: f64, ctx: &mut EventCtx) {
949        let previous_hover = self.hover_animation.value;
950        let previous_focus = self.focus_animation.value;
951        let animating = self.hover_animation.advance(time) | self.focus_animation.advance(time);
952        let changed = self.hover_animation.changed_since(previous_hover)
953            || self.focus_animation.changed_since(previous_focus);
954
955        if changed {
956            ctx.request_paint();
957        }
958        if animating {
959            ctx.request_animation_frame();
960        }
961    }
962
963    fn point_to_cursor(&self, bounds: Rect, position: Point) -> Option<TextCursor> {
964        let content = self.content_rect(bounds);
965        if !content.contains(position) {
966            return None;
967        }
968
969        if self.has_line_layout_cache() {
970            let local_x = position.x - content.x() + self.editor.scroll_x();
971            let local_y = position.y - content.y() + self.editor.scroll_y();
972            let line_index = self.line_index_for_y(local_y);
973            let local_offset = if let Some(Some(layout)) = self.line_layouts.get(line_index) {
974                let line = layout.lines().first()?;
975                let local = layout.hit_test_point(Point::new(
976                    local_x,
977                    line.rect.y() + (line.rect.height() * 0.5),
978                ));
979                local.utf8_offset.min(self.line_lengths[line_index])
980            } else {
981                self.estimate_inline_offset_for_x(line_index, local_x)
982            };
983            return Some(TextCursor::new(
984                self.line_offsets[line_index] + local_offset,
985            ));
986        }
987
988        let layout = self.layout.as_ref()?;
989
990        let local = Point::new(
991            position.x - content.x() + self.editor.scroll_x(),
992            position.y - content.y() + self.editor.scroll_y(),
993        );
994        Some(layout.hit_test_point(local))
995    }
996
997    fn line_range_with_overdraw(&self, viewport_height: f32, overdraw: f32) -> Range<usize> {
998        if self.has_line_layout_cache() {
999            if viewport_height <= 0.0 {
1000                return 0..0;
1001            }
1002
1003            let line_height = self.line_height().max(1.0);
1004            let visible_top = (self.editor.scroll_y() - overdraw).max(0.0);
1005            let visible_bottom = self.editor.scroll_y() + viewport_height + overdraw;
1006            let start = (visible_top / line_height).floor() as usize;
1007            let end = ((visible_bottom / line_height).ceil() as usize + 1)
1008                .min(self.line_count())
1009                .max(start + usize::from(start < self.line_count()));
1010            return start.min(self.line_count())..end;
1011        }
1012
1013        let Some(layout) = self.layout.as_ref() else {
1014            return 0..0;
1015        };
1016        if layout.lines().is_empty() || viewport_height <= 0.0 {
1017            return 0..0;
1018        }
1019
1020        let visible_top = (self.editor.scroll_y() - overdraw).max(0.0);
1021        let visible_bottom = self.editor.scroll_y() + viewport_height + overdraw;
1022        let mut start = 0usize;
1023        while start < layout.lines().len() {
1024            if layout.lines()[start].rect.max_y() >= visible_top {
1025                break;
1026            }
1027            start += 1;
1028        }
1029
1030        let mut end = start;
1031        while end < layout.lines().len() {
1032            if layout.lines()[end].rect.y() > visible_bottom {
1033                break;
1034            }
1035            end += 1;
1036        }
1037
1038        start..end.max(start + usize::from(start < layout.lines().len()))
1039    }
1040
1041    fn visible_line_range(&self, viewport_height: f32) -> Range<usize> {
1042        self.line_range_with_overdraw(viewport_height, 0.0)
1043    }
1044
1045    fn prefetched_line_range(&self, viewport_height: f32) -> Range<usize> {
1046        let overdraw = self.line_height().max(1.0) * 6.0;
1047        self.line_range_with_overdraw(viewport_height, overdraw)
1048    }
1049
1050    fn visible_line_layouts_are_ready(&self, viewport_height: f32) -> bool {
1051        if !self.has_line_layout_cache() {
1052            return self.layout.is_some();
1053        }
1054
1055        self.visible_line_range(viewport_height)
1056            .all(|index| self.line_layouts.get(index).is_some_and(Option::is_some))
1057    }
1058
1059    fn request_view_refresh(&self, ctx: &mut EventCtx) {
1060        let viewport_height = self.content_viewport_size(ctx.bounds()).height;
1061        if self.visible_line_layouts_are_ready(viewport_height) {
1062            ctx.request_paint();
1063        } else {
1064            ctx.request_measure();
1065        }
1066    }
1067
1068    fn clamp_scroll_to_bounds(&mut self, viewport_size: Size) -> bool {
1069        let previous = (self.editor.scroll_x(), self.editor.scroll_y());
1070        let content_size = if self.has_line_layout_cache() {
1071            self.multi_line_content_size()
1072        } else if let Some(layout) = self.layout.as_ref() {
1073            layout_content_size(layout)
1074        } else {
1075            self.editor.set_scroll(0.0, 0.0);
1076            return previous != (0.0, 0.0);
1077        };
1078
1079        let max_x = if self.wrap == TextWrap::NoWrap {
1080            (content_size.width - viewport_size.width).max(0.0)
1081        } else {
1082            0.0
1083        };
1084        let max_y = (content_size.height - viewport_size.height).max(0.0);
1085        self.editor.set_scroll(
1086            self.editor.scroll_x().clamp(0.0, max_x),
1087            self.editor.scroll_y().clamp(0.0, max_y),
1088        );
1089        previous != (self.editor.scroll_x(), self.editor.scroll_y())
1090    }
1091
1092    fn ensure_caret_visible(&mut self, bounds: Rect) -> bool {
1093        let viewport = self.content_viewport_size(bounds);
1094        if viewport.width <= 0.0 || viewport.height <= 0.0 {
1095            return false;
1096        }
1097
1098        let previous = (self.editor.scroll_x(), self.editor.scroll_y());
1099        let Some(caret) = self.caret_rect_for_cursor(self.display_selection().focus) else {
1100            return false;
1101        };
1102        let mut scroll_x = self.editor.scroll_x();
1103        let mut scroll_y = self.editor.scroll_y();
1104        if self.wrap == TextWrap::NoWrap {
1105            if caret.x() < scroll_x {
1106                scroll_x = caret.x().max(0.0);
1107            } else if caret.max_x() > scroll_x + viewport.width {
1108                scroll_x = (caret.max_x() - viewport.width).max(0.0);
1109            }
1110        } else {
1111            scroll_x = 0.0;
1112        }
1113        if caret.y() < scroll_y {
1114            scroll_y = caret.y().max(0.0);
1115        } else if caret.max_y() > scroll_y + viewport.height {
1116            scroll_y = (caret.max_y() - viewport.height).max(0.0);
1117        }
1118        self.editor.set_scroll(scroll_x, scroll_y);
1119        let _ = self.clamp_scroll_to_bounds(viewport);
1120        previous != (self.editor.scroll_x(), self.editor.scroll_y())
1121    }
1122
1123    fn scroll_by(&mut self, bounds: Rect, delta: Vector) -> bool {
1124        let previous = (self.editor.scroll_x(), self.editor.scroll_y());
1125        let mut scroll_x = self.editor.scroll_x();
1126        let mut scroll_y = self.editor.scroll_y();
1127        if self.wrap == TextWrap::NoWrap {
1128            scroll_x += delta.x;
1129        }
1130        scroll_y += delta.y;
1131        self.editor.set_scroll(scroll_x, scroll_y);
1132        let _ = self.clamp_scroll_to_bounds(self.content_viewport_size(bounds));
1133        previous != (self.editor.scroll_x(), self.editor.scroll_y())
1134    }
1135
1136    fn request_after_overlay_change(&mut self, ctx: &mut EventCtx) {
1137        if self.ensure_caret_visible(ctx.bounds()) {
1138            self.request_view_refresh(ctx);
1139        } else {
1140            ctx.request_paint();
1141        }
1142    }
1143
1144    fn line_count(&self) -> usize {
1145        self.line_offsets.len()
1146    }
1147
1148    fn has_line_layout_cache(&self) -> bool {
1149        !self.line_offsets.is_empty()
1150    }
1151
1152    fn line_slot_height_for_style(&self, base_style: &TextStyle) -> f32 {
1153        let base = base_style.line_height.max(base_style.font_size).max(1.0);
1154        base.max(self.style_span_max_line_height)
1155            .max(self.style_overlay_max_line_height)
1156    }
1157
1158    fn line_height(&self) -> f32 {
1159        self.line_slot_height_for_style(&self.resolved_text_style())
1160    }
1161
1162    fn line_layout_height(&self, layout: &PersistentTextLayout, base_line_height: f32) -> f32 {
1163        layout.measurement().height.max(base_line_height)
1164    }
1165
1166    fn line_layout_y_offset(
1167        &self,
1168        layout: &PersistentTextLayout,
1169        base_line_height: f32,
1170        slot_height: f32,
1171    ) -> f32 {
1172        ((slot_height - self.line_layout_height(layout, base_line_height)).max(0.0)) * 0.5
1173    }
1174
1175    fn line_origin_y(
1176        &self,
1177        line_index: usize,
1178        layout: &PersistentTextLayout,
1179        base_line_height: f32,
1180        slot_height: f32,
1181    ) -> f32 {
1182        line_index as f32 * slot_height
1183            + self.line_layout_y_offset(layout, base_line_height, slot_height)
1184    }
1185
1186    fn line_index_for_offset(&self, offset: usize) -> usize {
1187        let offset = offset.min(self.display_text_len());
1188        if self.editor.composition().is_none() && self.has_line_layout_cache() {
1189            return self
1190                .editor
1191                .document()
1192                .line_index_for_offset(offset)
1193                .min(self.line_count().saturating_sub(1));
1194        }
1195        self.line_offsets
1196            .iter()
1197            .enumerate()
1198            .rev()
1199            .find(|(_, start)| **start <= offset)
1200            .map(|(index, _)| index)
1201            .unwrap_or(0)
1202    }
1203
1204    fn line_index_for_y(&self, y: f32) -> usize {
1205        let line_height = self.line_height().max(1.0);
1206        ((y / line_height).floor() as usize).min(self.line_count().saturating_sub(1))
1207    }
1208
1209    fn estimate_inline_offset_for_x(&self, line_index: usize, x: f32) -> usize {
1210        let length = self.line_lengths.get(line_index).copied().unwrap_or(0);
1211        if length == 0 {
1212            return 0;
1213        }
1214
1215        let average_advance = (self.resolved_text_style().font_size * 0.55).max(1.0);
1216        ((x.max(0.0) / average_advance).round() as usize).min(length)
1217    }
1218
1219    fn estimated_caret_rect_for_line(&self, line_index: usize, local_offset: usize) -> Rect {
1220        let style = self.resolved_text_style();
1221        let average_advance = (style.font_size * 0.55).max(1.0);
1222        Rect::new(
1223            average_advance * local_offset as f32,
1224            line_index as f32 * self.line_height(),
1225            1.0,
1226            style.line_height.max(1.0),
1227        )
1228    }
1229
1230    fn caret_rect_for_cursor(&self, cursor: TextCursor) -> Option<Rect> {
1231        if self.has_line_layout_cache() {
1232            let line_index = self.line_index_for_offset(cursor.utf8_offset);
1233            let local_offset = cursor
1234                .utf8_offset
1235                .saturating_sub(self.line_offsets[line_index])
1236                .min(self.line_lengths[line_index]);
1237            let Some(Some(layout)) = self.line_layouts.get(line_index) else {
1238                return Some(self.estimated_caret_rect_for_line(line_index, local_offset));
1239            };
1240            let base_line_height = self.resolved_text_style().line_height;
1241            let slot_height = self.line_height();
1242            return Some(layout.caret_rect(local_offset).translate(Vector::new(
1243                0.0,
1244                self.line_origin_y(line_index, layout, base_line_height, slot_height),
1245            )));
1246        }
1247
1248        self.layout.as_ref().map(|layout| layout.caret(cursor).rect)
1249    }
1250
1251    fn selection_rects_for_display(&self, selection: &TextSelection) -> Vec<Rect> {
1252        if self.has_line_layout_cache() {
1253            let mut rects = Vec::new();
1254            let range = selection_range(selection, self.display_text_len());
1255            if range.is_empty() || self.line_count() == 0 {
1256                return rects;
1257            }
1258
1259            let start_line = self.line_index_for_offset(range.start);
1260            let end_line = self
1261                .line_index_for_offset(range.end)
1262                .min(self.line_count().saturating_sub(1));
1263            let base_line_height = self.resolved_text_style().line_height;
1264            let slot_height = self.line_height();
1265            for line_index in start_line..=end_line {
1266                let line_start = self.line_offsets[line_index];
1267                let line_end = line_start + self.line_lengths[line_index];
1268                let selection_start = range.start.max(line_start);
1269                let selection_end = range.end.min(line_end);
1270                if selection_start >= selection_end {
1271                    continue;
1272                }
1273
1274                let local_range = selection_start.saturating_sub(line_start)
1275                    ..selection_end.saturating_sub(line_start);
1276                let Some(Some(layout)) = self.line_layouts.get(line_index) else {
1277                    let start = self.estimated_caret_rect_for_line(line_index, local_range.start);
1278                    let end = self.estimated_caret_rect_for_line(line_index, local_range.end);
1279                    rects.push(Rect::new(
1280                        start.x(),
1281                        start.y(),
1282                        (end.x() - start.x()).max(1.0),
1283                        start.height(),
1284                    ));
1285                    continue;
1286                };
1287                let local_rects = layout.selection_rects(local_range);
1288                rects.extend(local_rects.into_iter().map(|rect| {
1289                    rect.translate(Vector::new(
1290                        0.0,
1291                        self.line_origin_y(line_index, layout, base_line_height, slot_height),
1292                    ))
1293                }));
1294            }
1295            return rects;
1296        }
1297
1298        self.layout
1299            .as_ref()
1300            .map(|layout| layout.selection_geometry(selection).rects)
1301            .unwrap_or_default()
1302    }
1303
1304    fn multi_line_content_size(&self) -> Size {
1305        let estimated_advance = self.resolved_text_style().font_size * 0.55;
1306        let estimated_width = self
1307            .line_lengths
1308            .iter()
1309            .map(|length| *length as f32 * estimated_advance)
1310            .fold(0.0_f32, f32::max);
1311        let measured_width = self
1312            .line_layouts
1313            .iter()
1314            .filter_map(|layout| layout.as_ref())
1315            .map(|layout| layout.measurement().width)
1316            .fold(0.0_f32, f32::max);
1317        Size::new(
1318            estimated_width.max(measured_width),
1319            self.line_count() as f32 * self.line_height(),
1320        )
1321    }
1322}
1323
1324impl Widget for TextSurface {
1325    fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
1326        match event {
1327            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
1328                let hovered = ctx.bounds().contains(pointer.position);
1329                self.update_hovered(hovered, ctx);
1330                if self.dragging_selection
1331                    && ctx.phase() != EventPhase::Capture
1332                    && pointer.buttons.contains(PointerButton::Primary)
1333                    && let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position)
1334                {
1335                    let anchor = self.editor.selection().anchor.utf8_offset;
1336                    let result = self.editor.execute(EditorCommand::SetSelection {
1337                        anchor,
1338                        focus: cursor.utf8_offset,
1339                    });
1340                    self.apply_editor_result(ctx, result);
1341                }
1342            }
1343            Event::Pointer(pointer)
1344                if pointer.kind == PointerEventKind::Down
1345                    && pointer.button == Some(PointerButton::Primary)
1346                    && ctx.phase() != EventPhase::Capture
1347                    && ctx.bounds().contains(pointer.position) =>
1348            {
1349                self.update_hovered(true, ctx);
1350                let clear_result = self.editor.execute(EditorCommand::ClearComposition);
1351                self.apply_editor_result(ctx, clear_result);
1352                if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
1353                    let command = if pointer.modifiers.shift {
1354                        EditorCommand::SetSelection {
1355                            anchor: self.editor.selection().anchor.utf8_offset,
1356                            focus: cursor.utf8_offset,
1357                        }
1358                    } else {
1359                        EditorCommand::MoveTo {
1360                            offset: cursor.utf8_offset,
1361                            extend: false,
1362                        }
1363                    };
1364                    let result = self.editor.execute(command);
1365                    self.apply_editor_result(ctx, result);
1366                }
1367                self.dragging_selection = true;
1368                ctx.request_focus();
1369                ctx.request_pointer_capture(pointer.pointer_id);
1370                self.request_after_overlay_change(ctx);
1371                ctx.request_semantics();
1372                ctx.set_handled();
1373            }
1374            Event::Pointer(pointer)
1375                if pointer.kind == PointerEventKind::Up
1376                    && pointer.button == Some(PointerButton::Primary)
1377                    && self.dragging_selection =>
1378            {
1379                self.dragging_selection = false;
1380                ctx.release_pointer_capture(pointer.pointer_id);
1381                ctx.request_paint();
1382                ctx.set_handled();
1383            }
1384            Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
1385                if self.dragging_selection {
1386                    self.dragging_selection = false;
1387                    ctx.release_pointer_capture(pointer.pointer_id);
1388                    ctx.request_paint();
1389                    ctx.set_handled();
1390                }
1391            }
1392            Event::Pointer(pointer)
1393                if pointer.kind == PointerEventKind::Down
1394                    && pointer.button == Some(PointerButton::Secondary)
1395                    && ctx.phase() != EventPhase::Capture
1396                    && ctx.bounds().contains(pointer.position) =>
1397            {
1398                // Focus on right-click (keeping the selection intact) so
1399                // follow-up clipboard commands land here. Deliberately not
1400                // handled: wrapping context menus react to the same press.
1401                self.update_hovered(true, ctx);
1402                if !ctx.is_focused() {
1403                    ctx.request_focus();
1404                    self.request_after_overlay_change(ctx);
1405                    ctx.request_semantics();
1406                }
1407            }
1408            Event::Pointer(pointer)
1409                if pointer.kind == PointerEventKind::Scroll
1410                    && ctx.phase() != EventPhase::Capture
1411                    && ctx.bounds().contains(pointer.position) =>
1412            {
1413                let delta = pointer
1414                    .scroll_delta
1415                    .map(scroll_delta_to_offset)
1416                    .unwrap_or(pointer.delta);
1417                if self.scroll_by(ctx.bounds(), Vector::new(-delta.x, -delta.y)) {
1418                    self.request_view_refresh(ctx);
1419                    ctx.request_semantics();
1420                    ctx.set_handled();
1421                }
1422            }
1423            Event::Ime(ImeEvent::CompositionStart) if ctx.is_focused() && !self.read_only => {
1424                self.execute_editor_command(ctx, EditorCommand::StartComposition);
1425            }
1426            Event::Ime(ImeEvent::CompositionUpdate { text, cursor_range })
1427                if ctx.is_focused() && !self.read_only =>
1428            {
1429                self.execute_editor_command(
1430                    ctx,
1431                    EditorCommand::UpdateComposition {
1432                        text: text.clone(),
1433                        cursor_range: cursor_range.clone(),
1434                    },
1435                );
1436            }
1437            Event::Ime(ImeEvent::CompositionCommit { text })
1438                if ctx.is_focused() && !self.read_only =>
1439            {
1440                self.execute_editor_command(ctx, EditorCommand::CommitComposition(text.clone()));
1441            }
1442            Event::Ime(ImeEvent::CompositionEnd) if ctx.is_focused() && !self.read_only => {
1443                self.execute_editor_command(ctx, EditorCommand::EndComposition);
1444            }
1445            Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
1446                let command_modifier = key.modifiers.control || key.modifiers.meta;
1447                let result = match key.key.as_str() {
1448                    "a" | "A" if command_modifier => self.editor.execute(EditorCommand::SelectAll),
1449                    "c" | "C" if command_modifier => self.editor.execute(EditorCommand::Copy),
1450                    "x" | "X" if command_modifier && !self.read_only => {
1451                        self.editor.execute(EditorCommand::Cut)
1452                    }
1453                    "v" | "V" if command_modifier && !self.read_only => {
1454                        let command = paste_command(ctx);
1455                        self.editor.execute(command)
1456                    }
1457                    "z" | "Z" if command_modifier && key.modifiers.shift && !self.read_only => {
1458                        self.editor.execute(EditorCommand::Redo)
1459                    }
1460                    "z" | "Z" if command_modifier && !self.read_only => {
1461                        self.editor.execute(EditorCommand::Undo)
1462                    }
1463                    "y" | "Y" if command_modifier && !self.read_only => {
1464                        self.editor.execute(EditorCommand::Redo)
1465                    }
1466                    "ArrowLeft" if command_modifier => {
1467                        self.editor.execute(EditorCommand::MoveWordLeft {
1468                            extend: key.modifiers.shift,
1469                        })
1470                    }
1471                    "ArrowRight" if command_modifier => {
1472                        self.editor.execute(EditorCommand::MoveWordRight {
1473                            extend: key.modifiers.shift,
1474                        })
1475                    }
1476                    "ArrowLeft" => self.editor.execute(EditorCommand::MoveLeft {
1477                        extend: key.modifiers.shift,
1478                    }),
1479                    "ArrowRight" => self.editor.execute(EditorCommand::MoveRight {
1480                        extend: key.modifiers.shift,
1481                    }),
1482                    "ArrowUp" => self.move_vertical(
1483                        -1,
1484                        key.modifiers.shift,
1485                        self.content_viewport_size(ctx.bounds()).height,
1486                    ),
1487                    "ArrowDown" => self.move_vertical(
1488                        1,
1489                        key.modifiers.shift,
1490                        self.content_viewport_size(ctx.bounds()).height,
1491                    ),
1492                    "Home" => self.move_line_boundary(true, key.modifiers.shift),
1493                    "End" => self.move_line_boundary(false, key.modifiers.shift),
1494                    "PageUp" => {
1495                        let line_height = self.line_height().max(1.0);
1496                        let delta = (self.content_viewport_size(ctx.bounds()).height / line_height)
1497                            .floor()
1498                            .max(1.0) as isize;
1499                        self.move_vertical(
1500                            -delta,
1501                            key.modifiers.shift,
1502                            self.content_viewport_size(ctx.bounds()).height,
1503                        )
1504                    }
1505                    "PageDown" => {
1506                        let line_height = self.line_height().max(1.0);
1507                        let delta = (self.content_viewport_size(ctx.bounds()).height / line_height)
1508                            .floor()
1509                            .max(1.0) as isize;
1510                        self.move_vertical(
1511                            delta,
1512                            key.modifiers.shift,
1513                            self.content_viewport_size(ctx.bounds()).height,
1514                        )
1515                    }
1516                    "Backspace" if !self.read_only => {
1517                        self.editor.execute(EditorCommand::DeleteBackward)
1518                    }
1519                    "Delete" if !self.read_only => {
1520                        self.editor.execute(EditorCommand::DeleteForward)
1521                    }
1522                    "Enter" if !self.read_only => self
1523                        .editor
1524                        .execute(EditorCommand::InsertText("\n".to_string())),
1525                    _ if !self.read_only && self.editor.composition().is_none() => {
1526                        if let Some(text) = keyboard_text(key) {
1527                            self.editor
1528                                .execute(EditorCommand::InsertText(text.to_string()))
1529                        } else {
1530                            self.editor.execute(EditorCommand::Noop)
1531                        }
1532                    }
1533                    _ => self.editor.execute(EditorCommand::Noop),
1534                };
1535                self.apply_editor_result(ctx, result);
1536            }
1537            Event::Window(WindowEvent::Focused(false)) => {
1538                let result = self.editor.execute(EditorCommand::ClearComposition);
1539                self.apply_editor_result(ctx, result);
1540            }
1541            Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
1542                self.advance_animations(*time, ctx);
1543            }
1544            _ => {}
1545        }
1546    }
1547
1548    fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
1549        let Some(command) = TextCommand::from_command(command) else {
1550            return;
1551        };
1552        if !ctx.is_focused() {
1553            ctx.request_focus();
1554        }
1555        self.apply_text_command(ctx, command);
1556    }
1557
1558    fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
1559        let padding = self.resolved_padding();
1560        let min_size = self.resolved_min_size();
1561        let available_width = if constraints.max.width.is_finite() {
1562            (constraints.max.width - padding.left - padding.right).max(0.0)
1563        } else {
1564            (min_size.width - padding.left - padding.right).max(0.0)
1565        };
1566
1567        let composition_active = self.editor.composition().is_some();
1568        let line_style = self.display_text_style();
1569        let line_box_size = Size::new(
1570            self.layout_box_width(available_width),
1571            line_style.line_height.max(1.0),
1572        );
1573        let viewport_height = if constraints.max.height.is_finite() {
1574            (constraints.max.height - padding.top - padding.bottom).max(0.0)
1575        } else {
1576            (min_size.height - padding.top - padding.bottom).max(line_style.line_height)
1577        };
1578        let cache_lines_individually = self.wrap == TextWrap::NoWrap;
1579        let mut line_layout_failed = false;
1580
1581        if !composition_active {
1582            let document = self.editor.document();
1583            let line_count = document.line_count();
1584            if cache_lines_individually && line_count > 1 {
1585                let can_reuse_lines = self.line_layout_revision != u64::MAX
1586                    && self.line_layout_box_size == Some(line_box_size)
1587                    && self.line_layout_style.as_ref() == Some(&line_style)
1588                    && self.line_layout_style_revision == self.style_revision
1589                    && self.line_layouts.len() == line_count
1590                    && self.line_offsets.len() == line_count
1591                    && self.line_lengths.len() == line_count;
1592
1593                if !can_reuse_lines {
1594                    self.line_layouts = vec![None; line_count];
1595                    self.line_offsets.clear();
1596                    self.line_lengths.clear();
1597                    self.line_offsets.reserve(line_count);
1598                    self.line_lengths.reserve(line_count);
1599                    for index in 0..line_count {
1600                        let line_range = document.line_range(index);
1601                        self.line_offsets.push(line_range.start);
1602                        self.line_lengths.push(line_range.len());
1603                    }
1604                } else {
1605                    Self::refresh_reusable_document_line_metadata(
1606                        document,
1607                        &mut self.line_layouts,
1608                        &mut self.line_offsets,
1609                        &mut self.line_lengths,
1610                    );
1611                }
1612
1613                let visible_lines = self.prefetched_line_range(viewport_height);
1614                let caret_line =
1615                    self.line_index_for_offset(self.display_selection().focus.utf8_offset);
1616                let mut lines_to_shape = Vec::with_capacity(visible_lines.len().saturating_add(1));
1617                lines_to_shape.extend(visible_lines);
1618                if caret_line < line_count && !lines_to_shape.contains(&caret_line) {
1619                    lines_to_shape.push(caret_line);
1620                }
1621
1622                for index in lines_to_shape {
1623                    if self.line_layouts[index].is_some() {
1624                        continue;
1625                    }
1626                    let line_range = document.line_range(index);
1627                    match self.shape_line_layout(
1628                        ctx,
1629                        None,
1630                        document.line_text(index),
1631                        line_range,
1632                        line_box_size,
1633                        line_style.clone(),
1634                    ) {
1635                        Ok(layout) => self.line_layouts[index] = Some(layout),
1636                        Err(_) => {
1637                            line_layout_failed = true;
1638                            break;
1639                        }
1640                    }
1641                }
1642
1643                if !line_layout_failed {
1644                    self.line_layout_box_size = Some(line_box_size);
1645                    self.line_layout_style = Some(line_style.clone());
1646                    self.line_layout_revision = document.revision();
1647                    self.line_layout_style_revision = self.style_revision;
1648                    self.layout = None;
1649                    self.editor.clear_document_dirty();
1650                }
1651            } else {
1652                self.line_layouts.clear();
1653                self.line_offsets.clear();
1654                self.line_lengths.clear();
1655                self.line_layout_box_size = None;
1656                self.line_layout_style = None;
1657                self.line_layout_revision = u64::MAX;
1658                self.line_layout_style_revision = u64::MAX;
1659            }
1660        } else {
1661            let single_line_composition = self.single_line_composition_display_line();
1662            if cache_lines_individually
1663                && self.editor.document().line_count() > 1
1664                && let Some((composition_line, composition_line_text)) = single_line_composition
1665            {
1666                self.reconcile_single_line_composition_layouts(
1667                    composition_line,
1668                    composition_line_text.len(),
1669                    line_box_size,
1670                    &line_style,
1671                );
1672
1673                let visible_lines = self.prefetched_line_range(viewport_height);
1674                let caret_line =
1675                    self.line_index_for_offset(self.display_selection().focus.utf8_offset);
1676                let line_count = self.editor.document().line_count();
1677                let mut lines_to_shape = Vec::with_capacity(visible_lines.len().saturating_add(1));
1678                lines_to_shape.extend(visible_lines);
1679                if caret_line < line_count && !lines_to_shape.contains(&caret_line) {
1680                    lines_to_shape.push(caret_line);
1681                }
1682
1683                for index in lines_to_shape {
1684                    if self.line_layouts[index].is_some() {
1685                        continue;
1686                    }
1687                    let line_range = if index == composition_line {
1688                        self.line_offsets[index]
1689                            ..self.line_offsets[index] + self.line_lengths[index]
1690                    } else {
1691                        self.editor.document().line_range(index)
1692                    };
1693                    let line_text = if index == composition_line {
1694                        composition_line_text.as_str()
1695                    } else {
1696                        self.editor.document().line_text(index)
1697                    };
1698                    match self.shape_line_layout(
1699                        ctx,
1700                        None,
1701                        line_text,
1702                        line_range,
1703                        line_box_size,
1704                        line_style.clone(),
1705                    ) {
1706                        Ok(layout) => self.line_layouts[index] = Some(layout),
1707                        Err(_) => {
1708                            line_layout_failed = true;
1709                            break;
1710                        }
1711                    }
1712                }
1713
1714                if !line_layout_failed {
1715                    self.line_layout_box_size = Some(line_box_size);
1716                    self.line_layout_style = Some(line_style.clone());
1717                    self.line_layout_revision = u64::MAX;
1718                    self.line_layout_style_revision = self.style_revision;
1719                    self.layout = None;
1720                }
1721            } else {
1722                let display_text = self.display_text();
1723                let (line_texts, line_offsets, line_lengths) =
1724                    split_lines_with_offsets(&display_text);
1725                if cache_lines_individually && line_texts.len() > 1 {
1726                    self.reconcile_composition_line_layouts(
1727                        &line_texts,
1728                        line_offsets,
1729                        line_lengths,
1730                        line_box_size,
1731                        &line_style,
1732                    );
1733
1734                    let visible_lines = self.prefetched_line_range(viewport_height);
1735                    let caret_line =
1736                        self.line_index_for_offset(self.display_selection().focus.utf8_offset);
1737                    let mut lines_to_shape =
1738                        Vec::with_capacity(visible_lines.len().saturating_add(1));
1739                    lines_to_shape.extend(visible_lines);
1740                    if caret_line < line_texts.len() && !lines_to_shape.contains(&caret_line) {
1741                        lines_to_shape.push(caret_line);
1742                    }
1743
1744                    for index in lines_to_shape {
1745                        if self.line_layouts[index].is_some() {
1746                            continue;
1747                        }
1748                        let line_range = self.line_offsets[index]
1749                            ..self.line_offsets[index] + self.line_lengths[index];
1750                        match self.shape_line_layout(
1751                            ctx,
1752                            None,
1753                            &line_texts[index],
1754                            line_range,
1755                            line_box_size,
1756                            line_style.clone(),
1757                        ) {
1758                            Ok(layout) => self.line_layouts[index] = Some(layout),
1759                            Err(_) => {
1760                                line_layout_failed = true;
1761                                break;
1762                            }
1763                        }
1764                    }
1765
1766                    if !line_layout_failed {
1767                        self.line_layout_box_size = Some(line_box_size);
1768                        self.line_layout_style = Some(line_style.clone());
1769                        self.line_layout_revision = u64::MAX;
1770                        self.line_layout_style_revision = self.style_revision;
1771                        self.layout = None;
1772                    }
1773                } else {
1774                    self.line_layouts.clear();
1775                    self.line_offsets.clear();
1776                    self.line_lengths.clear();
1777                    self.line_layout_box_size = None;
1778                    self.line_layout_style = None;
1779                    self.line_layout_revision = u64::MAX;
1780                    self.line_layout_style_revision = u64::MAX;
1781                }
1782            }
1783        }
1784
1785        if line_layout_failed {
1786            self.line_layouts.clear();
1787            self.line_offsets.clear();
1788            self.line_lengths.clear();
1789            self.line_layout_box_size = None;
1790            self.line_layout_style = None;
1791            self.line_layout_revision = u64::MAX;
1792            self.line_layout_style_revision = u64::MAX;
1793        }
1794
1795        self.layout = if !self.has_line_layout_cache() {
1796            let display_text = self.display_text();
1797            let handle = self.layout.as_ref().map(|layout| layout.handle());
1798            let box_size = self.layout_box_size(available_width);
1799            if self.style_spans.is_empty() && self.style_overlays.is_empty() {
1800                ctx.layout()
1801                    .shape_text_persistent(handle, display_text, box_size, line_style)
1802                    .ok()
1803            } else {
1804                self.shape_line_layout(
1805                    ctx,
1806                    handle,
1807                    &display_text,
1808                    0..display_text.len(),
1809                    box_size,
1810                    line_style,
1811                )
1812                .ok()
1813            }
1814        } else {
1815            None
1816        };
1817
1818        let mut natural_content_size = if self.has_line_layout_cache() {
1819            self.multi_line_content_size()
1820        } else {
1821            self.layout
1822                .as_ref()
1823                .map(layout_content_size)
1824                .unwrap_or(Size::new(min_size.width, min_size.height))
1825        };
1826        if self.should_show_placeholder() {
1827            let placeholder_style = self.placeholder_text_style();
1828            if let Ok(measurement) = ctx
1829                .layout()
1830                .measure_text(self.placeholder.clone(), placeholder_style.clone())
1831            {
1832                natural_content_size.width = natural_content_size.width.max(measurement.width);
1833                natural_content_size.height = natural_content_size
1834                    .height
1835                    .max(measurement.height.max(placeholder_style.line_height));
1836            }
1837        }
1838        let natural = Size::new(
1839            natural_content_size.width + padding.left + padding.right,
1840            natural_content_size.height + padding.top + padding.bottom,
1841        );
1842
1843        let desired = Size::new(
1844            if constraints.max.width.is_finite() {
1845                constraints.max.width
1846            } else {
1847                natural.width.max(min_size.width)
1848            },
1849            if constraints.max.height.is_finite() {
1850                constraints.max.height
1851            } else {
1852                natural.height.max(min_size.height)
1853            },
1854        );
1855        let size = constraints.clamp(Size::new(
1856            desired.width.max(min_size.width),
1857            desired.height.max(min_size.height),
1858        ));
1859
1860        let _ = self.clamp_scroll_to_bounds(
1861            self.content_viewport_size(Rect::from_origin_size(Point::ZERO, size)),
1862        );
1863        size
1864    }
1865
1866    fn paint(&self, ctx: &mut PaintCtx) {
1867        let theme = self.resolved_theme();
1868        let palette = theme.palette;
1869        let metrics = theme.metrics;
1870        let content = self.content_rect(ctx.bounds());
1871        let hover_progress = self.hover_animation.value;
1872        let focus_progress = self.focus_animation.value;
1873        let base_background = if self.read_only {
1874            palette.surface
1875        } else {
1876            mix_color(palette.control, palette.control_hover, hover_progress)
1877        };
1878        let background = mix_color(base_background, palette.surface_focus, focus_progress);
1879        let border = mix_color(
1880            mix_color(palette.border, palette.border_hover, hover_progress),
1881            palette.border_focus,
1882            focus_progress,
1883        );
1884
1885        draw_surface_frame(
1886            ctx,
1887            ctx.bounds(),
1888            metrics.corner_radius,
1889            metrics.border_width,
1890            background,
1891            border,
1892            (focus_progress > AnimatedScalar::EPSILON).then_some(
1893                palette
1894                    .focus_ring
1895                    .with_alpha(palette.focus_ring.alpha * focus_progress),
1896            ),
1897            metrics.focus_ring_width,
1898            metrics.focus_ring_outset,
1899        );
1900
1901        if !self.has_line_layout_cache() && self.layout.is_none() {
1902            return;
1903        }
1904
1905        let display_selection = self.display_selection();
1906        let origin = Point::new(
1907            content.x() - self.editor.scroll_x(),
1908            content.y() - self.editor.scroll_y(),
1909        );
1910        let line_range = self.visible_line_range(content.height());
1911        let selection_rects = self.selection_rects_for_display(&display_selection);
1912        let current_caret = self.caret_rect_for_cursor(display_selection.focus);
1913        let current_line_index = self.line_index_for_offset(display_selection.focus.utf8_offset);
1914        let base_line_height = self.resolved_text_style().line_height;
1915        let slot_height = self.line_height();
1916
1917        ctx.push_clip_rect(content);
1918
1919        if selection_rects.is_empty() {
1920            let line_rect = Rect::new(
1921                content.x(),
1922                origin.y + current_line_index as f32 * slot_height,
1923                content.width(),
1924                slot_height,
1925            );
1926            ctx.fill(
1927                Path::rounded_rect(line_rect, 0.0),
1928                palette.accent.with_alpha(match theme.colors.scheme {
1929                    ThemeColorScheme::Light => 0.05,
1930                    ThemeColorScheme::Dark => 0.12,
1931                    ThemeColorScheme::HighContrast => 0.18,
1932                }),
1933            );
1934        } else {
1935            for rect in selection_rects {
1936                ctx.fill(
1937                    Path::rounded_rect(rect.translate(origin.to_vector()), 3.0),
1938                    palette.selection,
1939                );
1940            }
1941        }
1942
1943        if self.should_show_placeholder() {
1944            let placeholder_style = self.placeholder_text_style();
1945            let placeholder_slot = Rect::new(
1946                origin.x,
1947                origin.y,
1948                content.width(),
1949                slot_height.max(placeholder_style.line_height),
1950            );
1951            paint_aligned_text(
1952                ctx,
1953                placeholder_slot,
1954                &self.placeholder,
1955                &placeholder_style,
1956                placeholder_style.line_height,
1957                0.0,
1958            );
1959        }
1960
1961        if self.has_line_layout_cache() {
1962            for line_index in line_range {
1963                if let Some(Some(layout)) = self.line_layouts.get(line_index) {
1964                    let line_y =
1965                        self.line_origin_y(line_index, layout, base_line_height, slot_height);
1966                    ctx.draw_persistent_text_layout(
1967                        Point::new(origin.x, origin.y + line_y),
1968                        layout,
1969                    );
1970                }
1971            }
1972        } else if let Some(layout) = &self.layout {
1973            ctx.draw_persistent_text_layout_window(origin, layout, line_range);
1974        }
1975
1976        if ctx.is_focused() && !self.read_only {
1977            let Some(current_caret) = current_caret else {
1978                ctx.pop_clip();
1979                return;
1980            };
1981            let caret_width = physical_pixels(ctx, metrics.caret_width);
1982            let caret = Rect::new(
1983                origin.x + current_caret.x(),
1984                origin.y + current_caret.y(),
1985                caret_width,
1986                current_caret.height().max(1.0),
1987            );
1988            ctx.set_ime_composition_rect(caret);
1989            ctx.fill(Path::rounded_rect(caret, caret_width * 0.5), palette.caret);
1990        }
1991
1992        ctx.pop_clip();
1993    }
1994
1995    fn layer_options(&self) -> LayerOptions {
1996        LayerOptions {
1997            paint_boundary: PaintBoundaryMode::Explicit,
1998            composition_mode: LayerCompositionMode::Scroll,
1999        }
2000    }
2001
2002    fn semantics(&self, ctx: &mut SemanticsCtx) {
2003        let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
2004        let display_text = self.display_text();
2005        let display_selection = self.display_selection();
2006        let selection = selection_range(&display_selection, display_text.len());
2007        node.name = Some(self.name.clone());
2008        node.value = Some(SemanticsValue::Text(display_text));
2009        node.state.focused = ctx.is_focused();
2010        node.state.hovered = self.hovered;
2011        node.editable_text = Some(EditableTextSemantics {
2012            caret_offset: display_selection.focus.utf8_offset,
2013            selection: SemanticsTextRange::new(selection.start, selection.end),
2014            multiline: true,
2015            password: false,
2016            readonly: self.read_only,
2017            scroll_x: self.editor.scroll_x(),
2018            scroll_y: self.editor.scroll_y(),
2019        });
2020        node.actions = if self.read_only {
2021            vec![
2022                SemanticsAction::Focus,
2023                SemanticsAction::SetSelection,
2024                SemanticsAction::Copy,
2025            ]
2026        } else {
2027            vec![
2028                SemanticsAction::Focus,
2029                SemanticsAction::SetValue,
2030                SemanticsAction::SetSelection,
2031                SemanticsAction::InsertText,
2032                SemanticsAction::DeleteBackward,
2033                SemanticsAction::DeleteForward,
2034                SemanticsAction::Copy,
2035                SemanticsAction::Cut,
2036                SemanticsAction::Paste,
2037                SemanticsAction::Undo,
2038                SemanticsAction::Redo,
2039            ]
2040        };
2041        ctx.push(node);
2042    }
2043
2044    fn accepts_focus(&self) -> bool {
2045        true
2046    }
2047
2048    fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
2049        if !focused {
2050            let result = self.editor.execute(EditorCommand::ClearComposition);
2051            if result.layout_changed() {
2052                ctx.request_text();
2053            }
2054        }
2055        let theme = self.resolved_theme();
2056        set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
2057        ctx.request_paint();
2058        ctx.request_semantics();
2059    }
2060}
2061
2062type AnimatedScalar = MotionScalar;
2063
2064fn set_animation_target(
2065    animation: &mut AnimatedScalar,
2066    target: f32,
2067    duration: f64,
2068    easing: crate::Easing,
2069    ctx: &mut EventCtx,
2070) -> bool {
2071    animation.set_target_event(target, duration, easing, ctx)
2072}
2073
2074fn set_hover_animation_target(
2075    animation: &mut AnimatedScalar,
2076    target: f32,
2077    theme: &DefaultTheme,
2078    ctx: &mut EventCtx,
2079) -> bool {
2080    set_animation_target(
2081        animation,
2082        target,
2083        theme.motion.hover_duration(),
2084        theme.motion.hover_easing(),
2085        ctx,
2086    )
2087}
2088
2089fn set_focus_animation_target(
2090    animation: &mut AnimatedScalar,
2091    target: f32,
2092    theme: &DefaultTheme,
2093    ctx: &mut EventCtx,
2094) -> bool {
2095    set_animation_target(
2096        animation,
2097        target,
2098        theme.motion.focus_duration(),
2099        theme.motion.focus_easing(),
2100        ctx,
2101    )
2102}
2103
2104fn mix_color(from: Color, to: Color, amount: f32) -> Color {
2105    crate::animation::Interpolate::interpolate(from, to, amount).clamped()
2106}
2107
2108fn inset_rect(rect: Rect, padding: Insets) -> Rect {
2109    Rect::new(
2110        rect.x() + padding.left,
2111        rect.y() + padding.top,
2112        (rect.width() - padding.left - padding.right).max(0.0),
2113        (rect.height() - padding.top - padding.bottom).max(0.0),
2114    )
2115}
2116
2117fn draw_surface_frame(
2118    ctx: &mut PaintCtx,
2119    bounds: Rect,
2120    radius: f32,
2121    border_width: f32,
2122    background: Color,
2123    border: Color,
2124    focus_ring: Option<Color>,
2125    focus_ring_width: f32,
2126    focus_ring_outset: f32,
2127) {
2128    let fill = Path::rounded_rect(bounds, radius);
2129    ctx.fill(fill, background);
2130
2131    if border_width > 0.0 {
2132        let width = physical_pixels(ctx, border_width);
2133        let inset = width * 0.5;
2134        ctx.stroke(
2135            Path::rounded_rect(bounds.inflate(-inset, -inset), (radius - inset).max(0.0)),
2136            border,
2137            StrokeStyle::new(width),
2138        );
2139    }
2140
2141    if let Some(focus_ring) = focus_ring {
2142        let outset = physical_pixels(ctx, focus_ring_outset);
2143        ctx.stroke(
2144            Path::rounded_rect(bounds.inflate(outset, outset), radius + outset),
2145            focus_ring,
2146            StrokeStyle::new(physical_pixels(ctx, focus_ring_width)),
2147        );
2148    }
2149}
2150
2151fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
2152    if value <= 0.0 {
2153        return 0.0;
2154    }
2155
2156    ctx.dpi().physical_pixels_to_logical(value)
2157}
2158
2159fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
2160    match delta {
2161        ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
2162        ScrollDelta::Pixels(delta) => delta,
2163    }
2164}
2165
2166fn keyboard_text(event: &KeyboardEvent) -> Option<&str> {
2167    if event.state != KeyState::Pressed
2168        || event.is_composing
2169        || event.modifiers.control
2170        || event.modifiers.alt
2171        || event.modifiers.meta
2172    {
2173        return None;
2174    }
2175
2176    if let Some(text) = event
2177        .text
2178        .as_deref()
2179        .filter(|text| !text.is_empty() && !text.chars().any(char::is_control))
2180    {
2181        return Some(text);
2182    }
2183
2184    let key = event.key.as_str();
2185    (key.chars().count() == 1 && !key.chars().any(char::is_control)).then_some(key)
2186}
2187
2188fn layout_content_size(layout: &PersistentTextLayout) -> Size {
2189    let line_height = layout
2190        .lines()
2191        .iter()
2192        .map(|line| line.rect.max_y())
2193        .fold(0.0_f32, f32::max)
2194        .max(layout.measurement().height);
2195    Size::new(layout.measurement().width, line_height)
2196}
2197
2198fn ranges_intersect(left: &Range<usize>, right: &Range<usize>) -> bool {
2199    left.start < right.end && right.start < left.end
2200}
2201
2202fn rebased_text_range(range: &Range<usize>, edit: &EditorTextEdit) -> Option<Range<usize>> {
2203    let replacement_end = edit.range.start.saturating_add(edit.replacement_len);
2204    let start = if range.start < edit.range.start {
2205        range.start
2206    } else if range.start >= edit.range.end {
2207        replacement_end.saturating_add(range.start.saturating_sub(edit.range.end))
2208    } else {
2209        edit.range.start
2210    };
2211    let end = if range.end <= edit.range.start {
2212        range.end
2213    } else if range.end >= edit.range.end {
2214        replacement_end.saturating_add(range.end.saturating_sub(edit.range.end))
2215    } else {
2216        replacement_end
2217    };
2218    (start < end).then_some(start..end)
2219}
2220
2221fn request_selection_change(ctx: &mut EventCtx, change: SelectionChange) {
2222    for owner in change.affected_owners() {
2223        let widget_id = WidgetId::new(owner.get());
2224        ctx.request(InvalidationRequest::new(
2225            InvalidationTarget::Widget(widget_id),
2226            InvalidationKind::Paint,
2227        ));
2228        ctx.request(InvalidationRequest::new(
2229            InvalidationTarget::Widget(widget_id),
2230            InvalidationKind::Semantics,
2231        ));
2232    }
2233}
2234
2235/// Paste command carrying the clipboard text, or `Noop` when the clipboard is
2236/// empty so an empty paste cannot delete the current selection.
2237pub(crate) fn paste_command(ctx: &EventCtx) -> EditorCommand {
2238    ctx.clipboard_text()
2239        .filter(|text| !text.is_empty())
2240        .map(EditorCommand::Paste)
2241        .unwrap_or(EditorCommand::Noop)
2242}
2243
2244fn sync_editor_selection_scope(
2245    ctx: &mut EventCtx,
2246    selection_scope: Option<&SelectionScope>,
2247    editor: &EditorState,
2248) {
2249    let Some(scope) = selection_scope else {
2250        return;
2251    };
2252    let owner = SelectionOwnerId::from(ctx.widget_id());
2253    let range = editor.selection_range();
2254    let selected = editor.selected_text().to_string();
2255    let change = scope.replace_text(owner, owner, range, editor.document().len(), selected);
2256    request_selection_change(ctx, change);
2257}
2258
2259#[cfg(test)]
2260#[allow(clippy::items_after_test_module)]
2261mod tests {
2262    use super::*;
2263    use std::{cell::RefCell, rc::Rc};
2264
2265    use sui_core::{
2266        Event, Modifiers, PointerButtons, PointerEvent, PointerKind, SemanticsValue, WindowId,
2267    };
2268    use sui_runtime::{
2269        Application, RenderOutput, Runtime, SceneStatisticsDetailMode, WindowBuilder,
2270        set_window_scene_statistics_detail_mode,
2271    };
2272    use sui_scene::{Brush, SceneCommand};
2273
2274    fn build_runtime<W>(root: W) -> (Runtime, WindowId)
2275    where
2276        W: Widget + 'static,
2277    {
2278        let runtime = Application::new()
2279            .window(WindowBuilder::new().title("Editor").root(root))
2280            .build()
2281            .expect("runtime should build");
2282        let window_id = runtime.window_ids()[0];
2283        (runtime, window_id)
2284    }
2285
2286    fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
2287        let mut buttons = PointerButtons::NONE;
2288        if pressed {
2289            buttons.insert(PointerButton::Primary);
2290        }
2291
2292        Event::Pointer(PointerEvent {
2293            pointer_id: 1,
2294            kind,
2295            position,
2296            delta: Vector::ZERO,
2297            scroll_delta: None,
2298            button: Some(PointerButton::Primary),
2299            buttons,
2300            modifiers: Modifiers::NONE,
2301            pointer_kind: PointerKind::Mouse,
2302            is_primary: true,
2303        })
2304    }
2305
2306    fn key_event(key: &str) -> Event {
2307        Event::Keyboard(KeyboardEvent::new(key, KeyState::Pressed))
2308    }
2309
2310    fn command_key_event(key: &str) -> Event {
2311        let mut event = KeyboardEvent::new(key, KeyState::Pressed);
2312        event.modifiers.control = true;
2313        Event::Keyboard(event)
2314    }
2315
2316    #[test]
2317    fn keyboard_text_falls_back_to_printable_key_when_text_payload_is_missing() {
2318        let mut event = KeyboardEvent::new("h", KeyState::Pressed);
2319        event.text = None;
2320        assert_eq!(keyboard_text(&event), Some("h"));
2321
2322        event.modifiers.control = true;
2323        assert_eq!(keyboard_text(&event), None);
2324    }
2325
2326    fn text_input_node(output: &RenderOutput) -> &SemanticsNode {
2327        output
2328            .semantics
2329            .iter()
2330            .find(|node| node.role == SemanticsRole::TextInput)
2331            .expect("text input semantics node should exist")
2332    }
2333
2334    fn shaped_text_commands(output: &RenderOutput) -> Vec<sui_text::ShapedText> {
2335        let mut found = Vec::new();
2336        output
2337            .frame
2338            .scene
2339            .visit_commands(&mut |command| match command {
2340                SceneCommand::DrawShapedText(text) => found.push(text.clone()),
2341                SceneCommand::DrawShapedTextWindow(text) => found.push(sui_text::ShapedText {
2342                    origin: text.origin,
2343                    layout_handle: text.layout_handle,
2344                    layout_version: text.layout_version,
2345                    bounds: text.bounds,
2346                    color_override: text.color_override,
2347                }),
2348                _ => {}
2349            });
2350        found
2351    }
2352
2353    fn solid_fill_colors(output: &RenderOutput) -> Vec<Color> {
2354        let mut colors = Vec::new();
2355        output
2356            .frame
2357            .scene
2358            .visit_commands(&mut |command| match command {
2359                SceneCommand::FillRect {
2360                    brush: Brush::Solid(color),
2361                    ..
2362                }
2363                | SceneCommand::FillPath {
2364                    brush: Brush::Solid(color),
2365                    ..
2366                } => colors.push(*color),
2367                _ => {}
2368            });
2369        colors
2370    }
2371
2372    fn solid_stroke_colors(output: &RenderOutput) -> Vec<Color> {
2373        let mut colors = Vec::new();
2374        output
2375            .frame
2376            .scene
2377            .visit_commands(&mut |command| match command {
2378                SceneCommand::StrokeRect {
2379                    brush: Brush::Solid(color),
2380                    ..
2381                }
2382                | SceneCommand::StrokePath {
2383                    brush: Brush::Solid(color),
2384                    ..
2385                } => colors.push(*color),
2386                _ => {}
2387            });
2388        colors
2389    }
2390
2391    fn handle_ready_events(runtime: &mut Runtime) -> usize {
2392        let ready = runtime.drain_ready_events();
2393        let count = ready.len();
2394        for (ready_window, event) in ready {
2395            runtime
2396                .handle_event(ready_window, event)
2397                .expect("ready event should be handled");
2398        }
2399        count
2400    }
2401
2402    fn assert_approx_eq(actual: f32, expected: f32) {
2403        assert!(
2404            (actual - expected).abs() <= 0.01,
2405            "expected {actual} to be within 0.01 of {expected}"
2406        );
2407    }
2408
2409    #[test]
2410    fn text_surface_hover_and_focus_use_theme_motion() {
2411        let theme = DefaultTheme::default();
2412        let hover_duration = theme.motion.hover_duration();
2413        let focus_duration = theme.motion.focus_duration();
2414        let expected_hover =
2415            super::mix_color(theme.palette.control, theme.palette.control_hover, 1.0);
2416        let (mut runtime, window_id) = build_runtime(
2417            crate::SizedBox::new()
2418                .size(Size::new(220.0, 96.0))
2419                .with_child(
2420                    TextSurface::new("Editor")
2421                        .theme(theme)
2422                        .placeholder("Write notes"),
2423                ),
2424        );
2425
2426        let _ = runtime.render(window_id).expect("render should succeed");
2427        runtime
2428            .handle_event(
2429                window_id,
2430                primary_pointer(PointerEventKind::Move, Point::new(16.0, 16.0), false),
2431            )
2432            .expect("hover event should be handled");
2433
2434        runtime.tick(hover_duration * 0.5);
2435        assert_eq!(handle_ready_events(&mut runtime), 1);
2436        let mid_hover = runtime.render(window_id).expect("render should succeed");
2437        let mid_hover_background = solid_fill_colors(&mid_hover)[0];
2438        assert_ne!(mid_hover_background, theme.palette.control);
2439        assert_ne!(mid_hover_background, expected_hover);
2440
2441        runtime.tick(hover_duration);
2442        assert_eq!(handle_ready_events(&mut runtime), 1);
2443        let settled_hover = runtime.render(window_id).expect("render should succeed");
2444        assert_eq!(solid_fill_colors(&settled_hover)[0], expected_hover);
2445
2446        runtime
2447            .handle_event(
2448                window_id,
2449                primary_pointer(PointerEventKind::Down, Point::new(16.0, 16.0), true),
2450            )
2451            .expect("focus event should be handled");
2452
2453        runtime.tick(hover_duration + focus_duration * 0.5);
2454        assert_eq!(handle_ready_events(&mut runtime), 1);
2455        let mid_focus = runtime.render(window_id).expect("render should succeed");
2456        assert!(!solid_stroke_colors(&mid_focus).contains(&theme.palette.focus_ring));
2457
2458        runtime.tick(hover_duration + focus_duration);
2459        assert_eq!(handle_ready_events(&mut runtime), 1);
2460        let settled_focus = runtime.render(window_id).expect("render should succeed");
2461        assert_eq!(
2462            solid_fill_colors(&settled_focus)[0],
2463            theme.palette.surface_focus
2464        );
2465        assert!(solid_stroke_colors(&settled_focus).contains(&theme.palette.focus_ring));
2466    }
2467
2468    #[test]
2469    fn text_surface_theme_when_and_text_style_when_read_current_theme() {
2470        let theme = Rc::new(RefCell::new(DefaultTheme::default()));
2471        let theme_reader = Rc::clone(&theme);
2472        let style_reader = Rc::clone(&theme);
2473        let (mut runtime, window_id) = build_runtime(
2474            crate::SizedBox::new()
2475                .size(Size::new(180.0, 72.0))
2476                .with_child(
2477                    TextSurface::new("Editor")
2478                        .value("themed text")
2479                        .theme_when(move || *theme_reader.borrow())
2480                        .text_style_when(move |_| {
2481                            let theme = *style_reader.borrow();
2482                            theme.text_style(theme.palette.text)
2483                        }),
2484                ),
2485        );
2486
2487        let light = runtime.render(window_id).expect("render should succeed");
2488        assert_eq!(
2489            solid_fill_colors(&light)[0],
2490            DefaultTheme::default().palette.control
2491        );
2492
2493        *theme.borrow_mut() = DefaultTheme::dark();
2494        runtime
2495            .handle_event(
2496                window_id,
2497                Event::Window(WindowEvent::Resized(Size::new(180.0, 72.0))),
2498            )
2499            .expect("resize should invalidate themed text surface");
2500        let dark = runtime.render(window_id).expect("render should succeed");
2501
2502        assert_eq!(
2503            solid_fill_colors(&dark)[0],
2504            DefaultTheme::dark().palette.control
2505        );
2506        assert_ne!(light.frame.scene, dark.frame.scene);
2507    }
2508
2509    #[test]
2510    fn text_surface_submits_only_visible_line_windows() {
2511        let long_text = (0..240)
2512            .map(|index| format!("line {index:02}"))
2513            .collect::<Vec<_>>()
2514            .join("\n");
2515        let (mut runtime, window_id) = build_runtime(
2516            crate::SizedBox::new()
2517                .size(Size::new(180.0, 96.0))
2518                .with_child(TextSurface::new("Editor").value(long_text)),
2519        );
2520        set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
2521
2522        let output = runtime.render(window_id).expect("render should succeed");
2523        let shaped = shaped_text_commands(&output);
2524        let layout_misses = output.diagnostics.text_caches.runtime_layout.misses;
2525
2526        assert!(
2527            shaped.len() < 24,
2528            "expected visible-line submission only, emitted {} shaped lines",
2529            shaped.len(),
2530        );
2531        assert!(
2532            layout_misses < 80,
2533            "expected viewport-aware measure, recorded {layout_misses} layout misses"
2534        );
2535        assert!(
2536            shaped
2537                .first()
2538                .and_then(|text| text.resolve(output.frame.text_layout_registry.as_ref()))
2539                .is_some_and(|layout| layout.text() == "line 00")
2540        );
2541    }
2542
2543    #[test]
2544    fn text_surface_word_wrap_shapes_full_document_layout() {
2545        let value = "alpha beta gamma delta epsilon zeta eta theta iota\nsecond wrapped line";
2546        let (mut runtime, window_id) = build_runtime(
2547            crate::SizedBox::new()
2548                .size(Size::new(120.0, 120.0))
2549                .with_child(TextSurface::new("Editor").wrap(TextWrap::Word).value(value)),
2550        );
2551
2552        let output = runtime.render(window_id).expect("render should succeed");
2553        let shaped = shaped_text_commands(&output);
2554
2555        assert_eq!(
2556            shaped.len(),
2557            1,
2558            "wrapped text should be submitted as a document layout, not cached logical lines"
2559        );
2560        let layout = shaped[0]
2561            .resolve(output.frame.text_layout_registry.as_ref())
2562            .expect("wrapped text layout should resolve");
2563        assert_eq!(layout.text(), value);
2564        assert!(
2565            layout.lines().len() > value.lines().count(),
2566            "word wrapping should produce more visual lines than logical document lines"
2567        );
2568    }
2569
2570    #[test]
2571    fn text_surface_scroll_updates_visible_window() {
2572        let long_text = (0..32)
2573            .map(|index| format!("line {index:02}"))
2574            .collect::<Vec<_>>()
2575            .join("\n");
2576        let mut surface = TextSurface::new("Editor").value(long_text);
2577        let bounds = Rect::new(0.0, 0.0, 180.0, 96.0);
2578        let content = surface.content_rect(bounds);
2579        let (line_texts, line_offsets, line_lengths) =
2580            split_lines_with_offsets(surface.current_value());
2581        let mut line_layouts = Vec::new();
2582        for line in &line_texts {
2583            line_layouts.push(
2584                sui_text::TextSystem::new()
2585                    .shape_text_persistent(
2586                        None,
2587                        line.clone(),
2588                        Size::new(
2589                            surface.layout_box_size(content.width()).width,
2590                            surface.resolved_text_style().line_height,
2591                        ),
2592                        surface.resolved_text_style(),
2593                        &sui_text::FontRegistry::new(),
2594                    )
2595                    .expect("text surface line layout should shape"),
2596            );
2597        }
2598        surface.line_layouts = line_layouts.into_iter().map(Some).collect();
2599        surface.line_offsets = line_offsets;
2600        surface.line_lengths = line_lengths;
2601
2602        let before_window = surface.visible_line_range(content.height());
2603        assert!(surface.scroll_by(bounds, Vector::new(0.0, 120.0)));
2604        let after_window = surface.visible_line_range(content.height());
2605
2606        assert!(after_window.start >= before_window.start);
2607        assert_ne!(after_window, before_window);
2608    }
2609
2610    #[test]
2611    fn text_surface_refreshes_shifted_offsets_without_discarding_plain_suffix_layouts() {
2612        let mut surface = TextSurface::new("Editor").value("a\nb\nc");
2613        let (line_texts, line_offsets, line_lengths) =
2614            split_lines_with_offsets(surface.current_value());
2615        let text_system = sui_text::TextSystem::new();
2616        let font_registry = sui_text::FontRegistry::new();
2617        let style = surface.resolved_text_style();
2618        let retained = text_system
2619            .shape_text_persistent(
2620                None,
2621                line_texts[1].clone(),
2622                Size::new(180.0, style.line_height),
2623                style,
2624                &font_registry,
2625            )
2626            .expect("suffix line should shape");
2627        let retained_handle = retained.handle();
2628        surface.line_layouts = vec![None, Some(retained), None];
2629        surface.line_offsets = line_offsets;
2630        surface.line_lengths = line_lengths;
2631        surface.editor.clear_document_dirty();
2632
2633        surface.editor.execute(EditorCommand::SetSelection {
2634            anchor: 1,
2635            focus: 1,
2636        });
2637        surface
2638            .editor
2639            .execute(EditorCommand::InsertText("XYZ".to_string()));
2640
2641        TextSurface::refresh_reusable_document_line_metadata(
2642            surface.editor.document(),
2643            &mut surface.line_layouts,
2644            &mut surface.line_offsets,
2645            &mut surface.line_lengths,
2646        );
2647
2648        assert_eq!(surface.line_offsets, vec![0, 5, 7]);
2649        assert_eq!(surface.line_lengths, vec![4, 1, 1]);
2650        assert_eq!(
2651            surface.line_layouts[1]
2652                .as_ref()
2653                .map(PersistentTextLayout::handle),
2654            Some(retained_handle)
2655        );
2656        assert!(surface.line_layouts[0].is_none());
2657    }
2658
2659    #[test]
2660    fn shifted_style_ranges_preserve_unchanged_suffix_layouts_after_edit() {
2661        let mut surface =
2662            TextSurface::new("Editor")
2663                .value("a\nb")
2664                .style_spans(vec![TextSurfaceStyleSpan::new(
2665                    2..3,
2666                    TextStyle::new(Color::rgba(1.0, 0.0, 0.0, 1.0)),
2667                )]);
2668        let (line_texts, line_offsets, line_lengths) =
2669            split_lines_with_offsets(surface.current_value());
2670        let style = surface.resolved_text_style();
2671        let retained = sui_text::TextSystem::new()
2672            .shape_text_persistent(
2673                None,
2674                line_texts[1].clone(),
2675                Size::new(180.0, style.line_height),
2676                style,
2677                &sui_text::FontRegistry::new(),
2678            )
2679            .expect("styled suffix line should shape");
2680        surface.line_layouts = vec![None, Some(retained)];
2681        surface.line_offsets = line_offsets;
2682        surface.line_lengths = line_lengths;
2683        surface.editor.clear_document_dirty();
2684        surface.editor.execute(EditorCommand::SetSelection {
2685            anchor: 1,
2686            focus: 1,
2687        });
2688        surface
2689            .editor
2690            .execute(EditorCommand::InsertText("XYZ".to_string()));
2691        let edit = surface
2692            .editor
2693            .take_text_edit()
2694            .expect("text insertion should report its edited range");
2695        surface.rebase_style_ranges_after_edit(&edit);
2696
2697        TextSurface::refresh_reusable_document_line_metadata(
2698            surface.editor.document(),
2699            &mut surface.line_layouts,
2700            &mut surface.line_offsets,
2701            &mut surface.line_lengths,
2702        );
2703
2704        assert!(surface.line_layouts[1].is_some());
2705        assert_eq!(surface.style_spans[0].range, 5..6);
2706    }
2707
2708    #[test]
2709    fn text_style_range_rebasing_respects_insertion_boundaries() {
2710        let insertion = EditorTextEdit {
2711            range: 3..3,
2712            replacement_len: 2,
2713        };
2714
2715        assert_eq!(rebased_text_range(&(1..3), &insertion), Some(1..3));
2716        assert_eq!(rebased_text_range(&(3..5), &insertion), Some(5..7));
2717        assert_eq!(rebased_text_range(&(2..5), &insertion), Some(2..7));
2718
2719        let deletion = EditorTextEdit {
2720            range: 2..5,
2721            replacement_len: 0,
2722        };
2723        assert_eq!(rebased_text_range(&(3..4), &deletion), None);
2724        assert_eq!(rebased_text_range(&(5..7), &deletion), Some(2..4));
2725    }
2726
2727    #[test]
2728    fn text_surface_centers_shorter_line_layouts_in_global_line_slots() {
2729        let mut base_style = TextStyle::new(Color::BLACK);
2730        base_style.font_size = 14.0;
2731        base_style.line_height = 18.0;
2732        let mut tall_style = TextStyle::new(Color::BLACK);
2733        tall_style.font_size = 28.0;
2734        tall_style.line_height = 36.0;
2735        let value = "tiny\nheader";
2736        let tall_range = "tiny\n".len()..value.len();
2737        let surface = TextSurface::new("Editor")
2738            .text_style(base_style.clone())
2739            .value(value)
2740            .style_overlays(vec![TextSurfaceStyleOverlay::new(
2741                tall_range.clone(),
2742                tall_style,
2743                TextSurfaceOverlayKind::Syntax,
2744            )]);
2745
2746        let (mut runtime, window_id) = build_runtime(
2747            crate::SizedBox::new()
2748                .size(Size::new(260.0, 96.0))
2749                .with_child(surface),
2750        );
2751        let output = runtime.render(window_id).expect("render should succeed");
2752        let shaped = shaped_text_commands(&output);
2753        let registry = output.frame.text_layout_registry.as_ref();
2754        let first = shaped
2755            .iter()
2756            .find(|text| {
2757                text.resolve(registry)
2758                    .is_some_and(|layout| layout.text() == "tiny")
2759            })
2760            .expect("first line should draw");
2761        let second = shaped
2762            .iter()
2763            .find(|text| {
2764                text.resolve(registry)
2765                    .is_some_and(|layout| layout.text() == "header")
2766            })
2767            .expect("second line should draw");
2768        let first_layout = first
2769            .resolve(registry)
2770            .expect("first layout should resolve");
2771        let second_layout = second
2772            .resolve(registry)
2773            .expect("second layout should resolve");
2774        let first_height = first_layout
2775            .measurement()
2776            .height
2777            .max(base_style.line_height);
2778        let second_height = second_layout
2779            .measurement()
2780            .height
2781            .max(base_style.line_height);
2782        // The authored overlay line-height owns the shared row slot even when
2783        // the resolved font's measured glyph box is shorter or taller. Arial
2784        // happened to match this slot; Segoe UI and Noto Sans need not.
2785        let slot_height = 36.0;
2786        assert!(
2787            first_height < slot_height,
2788            "fixture should produce a shorter first line"
2789        );
2790
2791        let first_offset = (slot_height - first_height).max(0.0) * 0.5;
2792        let second_offset = (slot_height - second_height).max(0.0) * 0.5;
2793        let first_row_top = second.origin.y - slot_height - second_offset;
2794        assert_approx_eq(first.origin.y, first_row_top + first_offset);
2795
2796        let text_system = sui_text::TextSystem::new();
2797        let mut geometry_surface = TextSurface::new("Editor")
2798            .text_style(base_style.clone())
2799            .value(value);
2800        geometry_surface.line_layouts = vec![
2801            Some(
2802                text_system
2803                    .shape_text_persistent(
2804                        None,
2805                        "tiny",
2806                        Size::new(240.0, base_style.line_height),
2807                        base_style.clone(),
2808                        &sui_text::FontRegistry::new(),
2809                    )
2810                    .expect("first line should shape"),
2811            ),
2812            Some(
2813                text_system
2814                    .shape_text_persistent(
2815                        None,
2816                        "header",
2817                        Size::new(240.0, base_style.line_height),
2818                        TextStyle {
2819                            font_size: 28.0,
2820                            line_height: 36.0,
2821                            ..base_style.clone()
2822                        },
2823                        &sui_text::FontRegistry::new(),
2824                    )
2825                    .expect("second line should shape"),
2826            ),
2827        ];
2828        geometry_surface.line_offsets = vec![0, "tiny\n".len()];
2829        geometry_surface.line_lengths = vec!["tiny".len(), "header".len()];
2830        let first_geometry_layout = geometry_surface.line_layouts[0]
2831            .as_ref()
2832            .expect("first line layout should exist");
2833        let local_caret = first_geometry_layout.caret_rect(0);
2834        let local_selection = first_geometry_layout.selection_rects(0.."tiny".len());
2835        let base_line_height = geometry_surface.resolved_text_style().line_height;
2836        let slot_height = geometry_surface.line_height();
2837        let first_origin_y =
2838            geometry_surface.line_origin_y(0, first_geometry_layout, base_line_height, slot_height);
2839        let caret = geometry_surface
2840            .caret_rect_for_cursor(TextCursor::new(0))
2841            .expect("caret should resolve");
2842        let selection = geometry_surface.selection_rects_for_display(&TextSelection::new(
2843            TextCursor::new(0),
2844            TextCursor::new("tiny".len()),
2845        ));
2846
2847        assert_approx_eq(caret.y(), first_origin_y + local_caret.y());
2848        assert_eq!(selection.len(), local_selection.len());
2849        assert_approx_eq(selection[0].y(), first_origin_y + local_selection[0].y());
2850    }
2851
2852    #[test]
2853    fn text_surface_supports_editing_and_keeps_layout_handle_on_cursor_moves() {
2854        let changes = Rc::new(RefCell::new(Vec::new()));
2855        let on_change = Rc::clone(&changes);
2856        let (mut runtime, window_id) = build_runtime(
2857            TextSurface::new("Editor").on_change(move |value| on_change.borrow_mut().push(value)),
2858        );
2859
2860        let _ = runtime
2861            .render(window_id)
2862            .expect("initial render should succeed");
2863        runtime
2864            .handle_event(
2865                window_id,
2866                primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
2867            )
2868            .expect("focus click should succeed");
2869        runtime
2870            .handle_event(
2871                window_id,
2872                Event::Ime(ImeEvent::CompositionCommit {
2873                    text: "hello".to_string(),
2874                }),
2875            )
2876            .expect("ime commit should succeed");
2877
2878        let after_insert = runtime
2879            .render(window_id)
2880            .expect("render after insert should succeed");
2881        let inserted_line = shaped_text_commands(&after_insert)
2882            .into_iter()
2883            .next()
2884            .expect("text surface should draw a shaped line after insert");
2885        let inserted_handle = inserted_line.layout_handle;
2886        let inserted_version = inserted_line.layout_version;
2887
2888        runtime
2889            .handle_event(
2890                window_id,
2891                Event::Keyboard(KeyboardEvent::new("ArrowLeft", KeyState::Pressed)),
2892            )
2893            .expect("arrow key should succeed");
2894
2895        let after_move = runtime
2896            .render(window_id)
2897            .expect("render after cursor move should succeed");
2898        let moved_line = shaped_text_commands(&after_move)
2899            .into_iter()
2900            .next()
2901            .expect("text surface should draw a shaped line after cursor move");
2902
2903        assert_eq!(changes.borrow().last().map(String::as_str), Some("hello"));
2904        assert_eq!(moved_line.layout_handle, inserted_handle);
2905        assert_eq!(moved_line.layout_version, inserted_version);
2906        assert!(after_move.ime_composition_rect.is_some());
2907        assert_eq!(
2908            after_move
2909                .semantics
2910                .iter()
2911                .find(|node| node.role == SemanticsRole::TextInput)
2912                .and_then(|node| node.value.clone()),
2913            Some(SemanticsValue::Text("hello".to_string()))
2914        );
2915    }
2916
2917    #[test]
2918    fn text_surface_selection_scope_tracks_keyboard_selection() {
2919        let selection = SelectionScope::new();
2920        let (mut runtime, window_id) = build_runtime(
2921            TextSurface::new("Editor")
2922                .value("alpha\nbeta")
2923                .selectable(selection.clone()),
2924        );
2925
2926        let _ = runtime
2927            .render(window_id)
2928            .expect("initial render should succeed");
2929        runtime
2930            .handle_event(
2931                window_id,
2932                primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
2933            )
2934            .expect("focus click should succeed");
2935        runtime
2936            .handle_event(window_id, command_key_event("a"))
2937            .expect("select all should succeed");
2938
2939        assert_eq!(selection.selected_text().as_deref(), Some("alpha\nbeta"));
2940    }
2941
2942    #[test]
2943    fn text_surface_caret_uses_theme_palette_color() {
2944        let mut theme = DefaultTheme::default();
2945        theme.palette.caret = Color::rgba(0.02, 0.18, 0.72, 1.0);
2946        let caret_color = theme.palette.caret;
2947        let accent_text = theme.palette.accent_text;
2948        let (mut runtime, window_id) = build_runtime(
2949            TextSurface::new("Editor")
2950                .theme(theme)
2951                .value("Visible caret on white"),
2952        );
2953
2954        runtime
2955            .render(window_id)
2956            .expect("initial render should succeed");
2957        runtime
2958            .handle_event(
2959                window_id,
2960                primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
2961            )
2962            .expect("focus click should succeed");
2963        let output = runtime
2964            .render(window_id)
2965            .expect("focused render should succeed");
2966        let fill_colors = solid_fill_colors(&output);
2967
2968        assert!(fill_colors.contains(&caret_color));
2969        assert!(!fill_colors.contains(&accent_text));
2970    }
2971
2972    #[test]
2973    fn text_surface_placeholder_uses_placeholder_style_without_editable_value() {
2974        let mut theme = DefaultTheme::default();
2975        theme.palette.placeholder = Color::rgba(0.42, 0.47, 0.55, 1.0);
2976        let placeholder_color = theme.palette.placeholder;
2977        let mut text_style = theme.body_text_style();
2978        text_style.font_size = 28.0;
2979        text_style.line_height = 12.0;
2980
2981        let (mut runtime, window_id) = build_runtime(
2982            crate::SizedBox::new()
2983                .size(Size::new(280.0, 96.0))
2984                .with_child(
2985                    TextSurface::new("Editor")
2986                        .theme(theme)
2987                        .text_style(text_style.clone())
2988                        .placeholder("Write notes"),
2989                ),
2990        );
2991        let output = runtime.render(window_id).expect("render should succeed");
2992        let registry = output.frame.text_layout_registry.as_ref();
2993        let (placeholder_command, placeholder) = shaped_text_commands(&output)
2994            .into_iter()
2995            .find_map(|text| {
2996                let layout = text.resolve(registry)?;
2997                (layout.text() == "Write notes").then(|| (text, layout.clone()))
2998            })
2999            .expect("placeholder text should draw");
3000        let node = text_input_node(&output);
3001
3002        assert_eq!(node.value, Some(SemanticsValue::Text(String::new())));
3003        assert_eq!(placeholder_command.color_override, Some(placeholder_color));
3004        assert_eq!(placeholder.style().font_size, text_style.font_size);
3005        assert_eq!(placeholder.style().line_height, text_style.line_height);
3006        assert!(placeholder.measurement().height > text_style.line_height);
3007    }
3008
3009    #[test]
3010    fn text_surface_read_only_uses_muted_text_and_blocks_mutation() {
3011        let mut theme = DefaultTheme::default();
3012        theme.palette.text_muted = Color::rgba(0.36, 0.40, 0.47, 1.0);
3013        let muted = theme.palette.text_muted;
3014        let caret = theme.palette.caret;
3015        let mut text_style = theme.body_text_style();
3016        text_style.font_size = 24.0;
3017        text_style.line_height = 13.0;
3018        let changes = Rc::new(RefCell::new(Vec::new()));
3019        let on_change = Rc::clone(&changes);
3020        let (mut runtime, window_id) = build_runtime(
3021            crate::SizedBox::new()
3022                .size(Size::new(280.0, 96.0))
3023                .with_child(
3024                    TextSurface::new("Editor")
3025                        .theme(theme)
3026                        .text_style(text_style.clone())
3027                        .value("Pinned")
3028                        .read_only()
3029                        .on_change(move |value| on_change.borrow_mut().push(value)),
3030                ),
3031        );
3032
3033        runtime
3034            .render(window_id)
3035            .expect("initial render should succeed");
3036        runtime
3037            .handle_event(
3038                window_id,
3039                primary_pointer(PointerEventKind::Down, Point::new(32.0, 24.0), true),
3040            )
3041            .expect("focus click should succeed");
3042        runtime
3043            .handle_event(
3044                window_id,
3045                Event::Ime(ImeEvent::CompositionCommit {
3046                    text: " edited".to_string(),
3047                }),
3048            )
3049            .expect("read-only ime commit should be ignored");
3050        runtime
3051            .handle_event(window_id, key_event("Backspace"))
3052            .expect("read-only backspace should be ignored");
3053        runtime
3054            .handle_event(window_id, command_key_event("x"))
3055            .expect("read-only cut should be ignored");
3056        let output = runtime.render(window_id).expect("render should succeed");
3057        let node = text_input_node(&output);
3058        let editable = node
3059            .editable_text
3060            .as_ref()
3061            .expect("editable text semantics should be present");
3062        let registry = output.frame.text_layout_registry.as_ref();
3063        let text = shaped_text_commands(&output)
3064            .into_iter()
3065            .find_map(|text| {
3066                text.resolve(registry)
3067                    .filter(|layout| layout.text() == "Pinned")
3068                    .cloned()
3069            })
3070            .expect("read-only value should draw");
3071        let fill_colors = solid_fill_colors(&output);
3072
3073        assert_eq!(node.value, Some(SemanticsValue::Text("Pinned".to_string())));
3074        assert!(editable.readonly);
3075        assert!(node.actions.contains(&SemanticsAction::Focus));
3076        assert!(node.actions.contains(&SemanticsAction::SetSelection));
3077        assert!(node.actions.contains(&SemanticsAction::Copy));
3078        for action in [
3079            SemanticsAction::SetValue,
3080            SemanticsAction::InsertText,
3081            SemanticsAction::DeleteBackward,
3082            SemanticsAction::DeleteForward,
3083            SemanticsAction::Cut,
3084            SemanticsAction::Paste,
3085            SemanticsAction::Undo,
3086            SemanticsAction::Redo,
3087        ] {
3088            assert!(
3089                !node.actions.contains(&action),
3090                "read-only surface should not expose {action:?}"
3091            );
3092        }
3093        assert_eq!(text.style().color, muted);
3094        assert_eq!(text.style().font_size, text_style.font_size);
3095        assert_eq!(text.style().line_height, text_style.line_height);
3096        assert!(changes.borrow().is_empty());
3097        assert!(!fill_colors.contains(&caret));
3098    }
3099
3100    #[test]
3101    fn text_surface_shortcuts_use_editor_command_layer() {
3102        let changes = Rc::new(RefCell::new(Vec::new()));
3103        let on_change = Rc::clone(&changes);
3104        let (mut runtime, window_id) = build_runtime(
3105            TextSurface::new("Editor").on_change(move |value| on_change.borrow_mut().push(value)),
3106        );
3107
3108        runtime
3109            .render(window_id)
3110            .expect("initial render should succeed");
3111        runtime
3112            .handle_event(
3113                window_id,
3114                primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
3115            )
3116            .expect("focus click should succeed");
3117        runtime
3118            .handle_event(
3119                window_id,
3120                Event::Ime(ImeEvent::CompositionCommit {
3121                    text: "hello world".to_string(),
3122                }),
3123            )
3124            .expect("initial edit should succeed");
3125        runtime
3126            .handle_event(window_id, command_key_event("a"))
3127            .expect("select all should succeed");
3128        runtime
3129            .handle_event(window_id, command_key_event("x"))
3130            .expect("cut should succeed");
3131        runtime
3132            .handle_event(window_id, command_key_event("v"))
3133            .expect("paste should succeed");
3134        runtime
3135            .handle_event(window_id, command_key_event("z"))
3136            .expect("undo should succeed");
3137        runtime
3138            .handle_event(window_id, command_key_event("y"))
3139            .expect("redo should succeed");
3140
3141        let output = runtime.render(window_id).expect("render should succeed");
3142        assert_eq!(
3143            text_input_node(&output).value,
3144            Some(SemanticsValue::Text("hello world".to_string()))
3145        );
3146        assert_eq!(
3147            changes.borrow().last().map(String::as_str),
3148            Some("hello world")
3149        );
3150    }
3151
3152    #[test]
3153    fn text_surface_deletes_grapheme_clusters() {
3154        let (mut runtime, window_id) = build_runtime(
3155            crate::SizedBox::new()
3156                .size(Size::new(320.0, 80.0))
3157                .with_child(TextSurface::new("Editor").value("a🇯🇵e\u{301}z")),
3158        );
3159
3160        runtime
3161            .render(window_id)
3162            .expect("initial render should succeed");
3163        runtime
3164            .handle_event(
3165                window_id,
3166                primary_pointer(PointerEventKind::Down, Point::new(300.0, 24.0), true),
3167            )
3168            .expect("end click should succeed");
3169        runtime
3170            .handle_event(window_id, key_event("Backspace"))
3171            .expect("delete z should succeed");
3172        runtime
3173            .handle_event(window_id, key_event("Backspace"))
3174            .expect("delete combining grapheme should succeed");
3175        runtime
3176            .handle_event(window_id, key_event("Backspace"))
3177            .expect("delete flag grapheme should succeed");
3178
3179        let output = runtime.render(window_id).expect("render should succeed");
3180        assert_eq!(
3181            text_input_node(&output).value,
3182            Some(SemanticsValue::Text("a".to_string()))
3183        );
3184    }
3185
3186    #[test]
3187    fn text_surface_ime_cursor_range_updates_editable_semantics() {
3188        let (mut runtime, window_id) = build_runtime(
3189            crate::SizedBox::new()
3190                .size(Size::new(320.0, 80.0))
3191                .with_child(TextSurface::new("Editor").value("hello ")),
3192        );
3193
3194        runtime
3195            .render(window_id)
3196            .expect("initial render should succeed");
3197        runtime
3198            .handle_event(
3199                window_id,
3200                primary_pointer(PointerEventKind::Down, Point::new(300.0, 24.0), true),
3201            )
3202            .expect("end click should succeed");
3203        runtime
3204            .handle_event(window_id, Event::Ime(ImeEvent::CompositionStart))
3205            .expect("composition start should succeed");
3206        runtime
3207            .handle_event(
3208                window_id,
3209                Event::Ime(ImeEvent::CompositionUpdate {
3210                    text: "世界".to_string(),
3211                    cursor_range: Some(0.."世".len()),
3212                }),
3213            )
3214            .expect("composition update should succeed");
3215
3216        let output = runtime.render(window_id).expect("render should succeed");
3217        let node = text_input_node(&output);
3218        assert_eq!(
3219            node.value,
3220            Some(SemanticsValue::Text("hello 世界".to_string()))
3221        );
3222        let editable = node
3223            .editable_text
3224            .as_ref()
3225            .expect("editable text semantics should be present");
3226        assert_eq!(editable.caret_offset, "hello 世".len());
3227        assert_eq!(
3228            editable.selection,
3229            SemanticsTextRange::new("hello 世".len(), "hello 世".len())
3230        );
3231    }
3232
3233    #[test]
3234    fn text_surface_semantics_expose_editable_text_actions() {
3235        let (mut runtime, window_id) = build_runtime(TextSurface::new("Editor").value("one\ntwo"));
3236        let output = runtime.render(window_id).expect("render should succeed");
3237        let node = text_input_node(&output);
3238        let editable = node
3239            .editable_text
3240            .as_ref()
3241            .expect("editable text semantics should be present");
3242
3243        assert!(editable.multiline);
3244        assert!(!editable.readonly);
3245        assert_eq!(editable.caret_offset, "one\ntwo".len());
3246        assert_eq!(
3247            editable.selection,
3248            SemanticsTextRange::new("one\ntwo".len(), "one\ntwo".len())
3249        );
3250        for action in [
3251            SemanticsAction::SetSelection,
3252            SemanticsAction::InsertText,
3253            SemanticsAction::DeleteBackward,
3254            SemanticsAction::DeleteForward,
3255            SemanticsAction::Copy,
3256            SemanticsAction::Cut,
3257            SemanticsAction::Paste,
3258            SemanticsAction::Undo,
3259            SemanticsAction::Redo,
3260        ] {
3261            assert!(
3262                node.actions.contains(&action),
3263                "missing editable text action {action:?}"
3264            );
3265        }
3266    }
3267
3268    #[test]
3269    fn text_surface_style_overlays_do_not_mutate_source_text() {
3270        let syntax_style = TextStyle::new(Color::BLACK);
3271        let (mut runtime, window_id) = build_runtime(
3272            TextSurface::new("Editor")
3273                .value("let value = 1")
3274                .style_overlays(vec![TextSurfaceStyleOverlay::new(
3275                    0..3,
3276                    syntax_style.clone(),
3277                    TextSurfaceOverlayKind::Syntax,
3278                )]),
3279        );
3280
3281        let output = runtime.render(window_id).expect("render should succeed");
3282        let node = text_input_node(&output);
3283        assert_eq!(
3284            node.value,
3285            Some(SemanticsValue::Text("let value = 1".to_string()))
3286        );
3287
3288        let shaped = shaped_text_commands(&output);
3289        let layout = shaped
3290            .first()
3291            .and_then(|text| text.resolve(output.frame.text_layout_registry.as_ref()))
3292            .expect("styled text layout should resolve");
3293        assert_eq!(layout.text(), "let value = 1");
3294        assert!(
3295            layout
3296                .run_views()
3297                .any(|run| run.style.color == syntax_style.color && run.run.byte_range == (0..3)),
3298            "syntax overlay should style the keyword without changing the source text"
3299        );
3300    }
3301}
3302
3303fn split_lines_with_offsets(text: &str) -> (Vec<String>, Vec<usize>, Vec<usize>) {
3304    let mut lines = Vec::new();
3305    let mut offsets = Vec::new();
3306    let mut lengths = Vec::new();
3307    let mut start = 0usize;
3308
3309    for segment in text.split('\n') {
3310        offsets.push(start);
3311        lengths.push(segment.len());
3312        lines.push(segment.to_string());
3313        start += segment.len() + 1;
3314    }
3315
3316    if lines.is_empty() {
3317        lines.push(String::new());
3318        offsets.push(0);
3319        lengths.push(0);
3320    }
3321
3322    (lines, offsets, lengths)
3323}