Skip to main content

sui_widgets/
text_surface.rs

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