Skip to main content

sui_widgets/
text_surface.rs

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