use std::ops::Range;
use sui_core::{
Color, EditableTextSemantics, Event, ImeEvent, KeyState, Path, Point, PointerButton,
PointerEventKind, Rect, ScrollDelta, SemanticsNode, SemanticsRole, SemanticsTextRange,
SemanticsValue, Size, Vector, WakeEvent, WindowEvent,
};
use sui_layout::{Constraints, Padding as Insets};
use sui_runtime::{
Command, EventCtx, EventPhase, LayerOptions, MeasureCtx, PaintBoundaryMode, PaintCtx,
SemanticsCtx, Widget,
};
use sui_scene::{LayerCompositionMode, StrokeStyle};
use sui_text::{
PersistentTextLayout, TextCursor, TextDirection, TextDocument, TextLayoutRequest,
TextParagraph, TextSelection, TextSpan, TextStyle, TextWrap,
};
use crate::{
DefaultTheme, MotionScalar, ThemeColorScheme,
editable_text::{EditableTextController, EditableTextLineMode, paste_command},
editor::{
EditorCommand, EditorCommandResult, EditorDocument, EditorTextEdit,
clamp_to_grapheme_boundary, selection_range,
},
selection::{SelectionClipboardBehavior, SelectionScope},
text_align::paint_aligned_text,
text_command::TextCommand,
};
#[derive(Debug, Clone, PartialEq)]
pub struct TextSurfaceStyleSpan {
pub range: Range<usize>,
pub style: TextStyle,
}
impl TextSurfaceStyleSpan {
pub fn new(range: Range<usize>, style: TextStyle) -> Self {
Self { range, style }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextSurfaceOverlayKind {
Syntax,
Diagnostic,
SearchMatch,
CurrentLine,
RichTextPreview,
Custom(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct TextSurfaceStyleOverlay {
pub range: Range<usize>,
pub style: TextStyle,
pub kind: TextSurfaceOverlayKind,
}
impl TextSurfaceStyleOverlay {
pub fn new(range: Range<usize>, style: TextStyle, kind: TextSurfaceOverlayKind) -> Self {
Self { range, style, kind }
}
}
#[derive(Debug, Clone, Copy)]
struct IndexedTextRange {
source_index: usize,
start: usize,
end: usize,
}
#[derive(Debug, Clone, Default)]
struct TextSurfaceRangeIndex {
by_start: Vec<IndexedTextRange>,
prefix_max_end: Vec<usize>,
}
impl TextSurfaceRangeIndex {
fn rebuild(&mut self, ranges: impl IntoIterator<Item = (usize, usize)>) {
self.by_start = ranges
.into_iter()
.enumerate()
.map(|(source_index, (start, end))| IndexedTextRange {
source_index,
start,
end,
})
.collect();
self.by_start
.sort_unstable_by_key(|range| (range.start, range.end, range.source_index));
self.prefix_max_end.clear();
self.prefix_max_end.reserve(self.by_start.len());
let mut max_end = 0;
for range in &self.by_start {
max_end = max_end.max(range.end);
self.prefix_max_end.push(max_end);
}
}
fn overlapping_indices(&self, query: &Range<usize>) -> Vec<usize> {
if query.is_empty() {
return Vec::new();
}
let upper = self
.by_start
.partition_point(|range| range.start < query.end);
let lower = self.prefix_max_end[..upper].partition_point(|max_end| *max_end <= query.start);
let mut indices = self.by_start[lower..upper]
.iter()
.filter(|range| query.start < range.end)
.map(|range| range.source_index)
.collect::<Vec<_>>();
indices.sort_unstable();
indices
}
}
pub struct TextSurface {
theme: Box<DefaultTheme>,
theme_reader: Option<Box<dyn Fn() -> DefaultTheme>>,
name: String,
placeholder: String,
read_only: bool,
editor: EditableTextController,
text_style: Option<TextStyle>,
text_style_reader: Option<Box<dyn Fn(DefaultTheme) -> TextStyle>>,
padding: Option<Insets>,
min_width: Option<f32>,
min_height: Option<f32>,
wrap: TextWrap,
direction: TextDirection,
style_spans: Vec<TextSurfaceStyleSpan>,
style_span_index: TextSurfaceRangeIndex,
style_span_max_line_height: f32,
style_overlays: Vec<TextSurfaceStyleOverlay>,
style_overlay_index: TextSurfaceRangeIndex,
style_overlay_max_line_height: f32,
style_revision: u64,
hovered: bool,
hover_animation: AnimatedScalar,
focus_animation: AnimatedScalar,
dragging_selection: bool,
layout: Option<PersistentTextLayout>,
line_layouts: Vec<Option<PersistentTextLayout>>,
line_offsets: Vec<usize>,
line_lengths: Vec<usize>,
line_layout_box_size: Option<Size>,
line_layout_style: Option<TextStyle>,
line_layout_revision: u64,
line_layout_style_revision: u64,
on_change: Option<Box<dyn FnMut(String)>>,
}
impl TextSurface {
pub fn new(name: impl Into<String>) -> Self {
Self {
theme: Box::new(DefaultTheme::default()),
theme_reader: None,
name: name.into(),
placeholder: String::new(),
read_only: false,
editor: EditableTextController::new(),
text_style: None,
text_style_reader: None,
padding: None,
min_width: None,
min_height: None,
wrap: TextWrap::NoWrap,
direction: TextDirection::Auto,
style_spans: Vec::new(),
style_span_index: TextSurfaceRangeIndex::default(),
style_span_max_line_height: 0.0,
style_overlays: Vec::new(),
style_overlay_index: TextSurfaceRangeIndex::default(),
style_overlay_max_line_height: 0.0,
style_revision: 0,
hovered: false,
hover_animation: AnimatedScalar::new(0.0),
focus_animation: AnimatedScalar::new(0.0),
dragging_selection: false,
layout: None,
line_layouts: Vec::new(),
line_offsets: Vec::new(),
line_lengths: Vec::new(),
line_layout_box_size: None,
line_layout_style: None,
line_layout_revision: u64::MAX,
line_layout_style_revision: u64::MAX,
on_change: None,
}
}
pub fn theme(mut self, theme: DefaultTheme) -> Self {
self.theme = Box::new(theme);
self.theme_reader = None;
self
}
pub fn theme_when<F>(mut self, theme: F) -> Self
where
F: Fn() -> DefaultTheme + 'static,
{
self.theme_reader = Some(Box::new(theme));
self
}
pub fn text_style(mut self, text_style: TextStyle) -> Self {
self.text_style = Some(text_style);
self.text_style_reader = None;
self
}
pub fn text_style_when<F>(mut self, text_style: F) -> Self
where
F: Fn(DefaultTheme) -> TextStyle + 'static,
{
self.text_style_reader = Some(Box::new(text_style));
self.text_style = None;
self
}
pub fn padding(mut self, padding: Insets) -> Self {
self.padding = Some(padding);
self
}
pub fn min_width(mut self, width: f32) -> Self {
self.min_width = Some(width.max(0.0));
self
}
pub fn min_height(mut self, height: f32) -> Self {
self.min_height = Some(height.max(0.0));
self
}
pub fn wrap(mut self, wrap: TextWrap) -> Self {
self.wrap = wrap;
if self.wrap != TextWrap::NoWrap {
let scroll_y = self.editor.scroll_y();
self.editor.set_scroll(0.0, scroll_y);
}
self.invalidate_line_layouts();
self
}
pub fn direction(mut self, direction: TextDirection) -> Self {
self.direction = direction;
self.invalidate_line_layouts();
self
}
pub fn style_spans(mut self, spans: Vec<TextSurfaceStyleSpan>) -> Self {
self.set_style_spans(spans);
self
}
pub fn set_style_spans(&mut self, spans: Vec<TextSurfaceStyleSpan>) {
self.style_spans = spans;
self.style_span_index.rebuild(
self.style_spans
.iter()
.map(|span| (span.range.start, span.range.end)),
);
self.style_span_max_line_height = self
.style_spans
.iter()
.map(|span| span.style.line_height.max(span.style.font_size))
.fold(0.0, f32::max);
self.bump_style_revision();
}
pub fn current_style_spans(&self) -> &[TextSurfaceStyleSpan] {
&self.style_spans
}
pub fn style_overlays(mut self, overlays: Vec<TextSurfaceStyleOverlay>) -> Self {
self.set_style_overlays(overlays);
self
}
pub fn set_style_overlays(&mut self, overlays: Vec<TextSurfaceStyleOverlay>) {
self.style_overlays = overlays;
self.style_overlay_index.rebuild(
self.style_overlays
.iter()
.map(|overlay| (overlay.range.start, overlay.range.end)),
);
self.style_overlay_max_line_height = self
.style_overlays
.iter()
.map(|overlay| overlay.style.line_height.max(overlay.style.font_size))
.fold(0.0, f32::max);
self.bump_style_revision();
}
pub fn current_style_overlays(&self) -> &[TextSurfaceStyleOverlay] {
&self.style_overlays
}
pub fn value(mut self, value: impl Into<String>) -> Self {
self.set_value(value);
self
}
pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn read_only(mut self) -> Self {
self.read_only = true;
self
}
pub fn selectable(mut self, selection_scope: SelectionScope) -> Self {
self.editor.selectable(selection_scope);
self
}
pub fn selection_scope(mut self, selection_scope: SelectionScope) -> Self {
self.editor.selection_scope(selection_scope);
self
}
pub fn clipboard_behavior(mut self, behavior: SelectionClipboardBehavior) -> Self {
self.editor.clipboard_behavior(behavior);
self
}
pub fn copy_to_clipboard(self, enabled: bool) -> Self {
self.clipboard_behavior(if enabled {
SelectionClipboardBehavior::WidgetManaged
} else {
SelectionClipboardBehavior::AppManaged
})
}
pub fn current_value(&self) -> &str {
self.editor.document().text()
}
pub fn set_value(&mut self, value: impl Into<String>) {
self.editor.set_text(value);
self.invalidate_line_layouts();
}
pub fn on_change<F>(mut self, on_change: F) -> Self
where
F: FnMut(String) + 'static,
{
self.on_change = Some(Box::new(on_change));
self
}
fn resolved_theme(&self) -> DefaultTheme {
self.theme_reader
.as_ref()
.map(|theme| theme())
.unwrap_or(*self.theme)
}
fn resolved_text_style(&self) -> TextStyle {
let theme = self.resolved_theme();
if let Some(text_style) = &self.text_style_reader {
return text_style(theme);
}
self.text_style
.clone()
.unwrap_or_else(|| theme.body_text_style())
}
fn display_text_style(&self) -> TextStyle {
let theme = self.resolved_theme();
let mut style = self.resolved_text_style();
if self.read_only {
style.color = theme.palette.text_muted;
}
style
}
fn placeholder_text_style(&self) -> TextStyle {
let theme = self.resolved_theme();
let mut style = self.resolved_text_style();
style.color = theme.palette.placeholder;
style
}
fn should_show_placeholder(&self) -> bool {
self.display_text_len() == 0 && !self.placeholder.is_empty()
}
fn resolved_padding(&self) -> Insets {
let theme = self.resolved_theme();
self.padding.unwrap_or(theme.metrics.text_input_padding)
}
fn resolved_min_size(&self) -> Size {
let theme = self.resolved_theme();
Size::new(
self.min_width.unwrap_or(theme.metrics.text_input_min_width),
self.min_height
.unwrap_or(theme.metrics.text_area_min_height),
)
}
fn bump_style_revision(&mut self) {
self.style_revision = self.style_revision.saturating_add(1);
self.invalidate_line_layouts();
}
fn rebase_style_ranges_after_edit(&mut self, edit: &EditorTextEdit) {
self.style_spans.retain_mut(|span| {
let Some(range) = rebased_text_range(&span.range, edit) else {
return false;
};
span.range = range;
true
});
self.style_overlays.retain_mut(|overlay| {
let Some(range) = rebased_text_range(&overlay.range, edit) else {
return false;
};
overlay.range = range;
true
});
self.style_span_index.rebuild(
self.style_spans
.iter()
.map(|span| (span.range.start, span.range.end)),
);
self.style_overlay_index.rebuild(
self.style_overlays
.iter()
.map(|overlay| (overlay.range.start, overlay.range.end)),
);
}
fn invalidate_line_layouts(&mut self) {
self.layout = None;
self.line_layouts.clear();
self.line_offsets.clear();
self.line_lengths.clear();
self.line_layout_box_size = None;
self.line_layout_style = None;
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = u64::MAX;
}
fn reconcile_composition_line_layouts(
&mut self,
line_texts: &[String],
line_offsets: Vec<usize>,
line_lengths: Vec<usize>,
line_box_size: Size,
line_style: &TextStyle,
) {
let metadata_matches = self.line_layout_box_size == Some(line_box_size)
&& self.line_layout_style.as_ref() == Some(line_style)
&& self.line_layout_style_revision == self.style_revision;
let previous_offsets = std::mem::replace(&mut self.line_offsets, line_offsets);
let previous_lengths = std::mem::replace(&mut self.line_lengths, line_lengths);
let mut previous_layouts = std::mem::take(&mut self.line_layouts);
let mut next_layouts = Vec::with_capacity(line_texts.len());
for (index, line_text) in line_texts.iter().enumerate() {
let can_reuse = metadata_matches
&& previous_offsets.get(index) == self.line_offsets.get(index)
&& previous_lengths.get(index) == self.line_lengths.get(index);
let layout = can_reuse
.then(|| previous_layouts.get_mut(index).and_then(Option::take))
.flatten()
.filter(|layout| layout.text() == line_text);
next_layouts.push(layout);
}
self.line_layouts = next_layouts;
}
fn single_line_composition_display_line(&self) -> Option<(usize, String)> {
let composition = self.editor.composition()?;
if composition.text.contains('\n') {
return None;
}
let document = self.editor.document();
let line_index = document.line_index_for_offset(composition.replacement_range.start);
let line_range = document.line_range(line_index);
if composition.replacement_range.end > line_range.end {
return None;
}
let mut line_text = document.line_text(line_index).to_string();
let local_range = composition
.replacement_range
.start
.saturating_sub(line_range.start)
..composition
.replacement_range
.end
.saturating_sub(line_range.start);
line_text.replace_range(local_range, &composition.text);
Some((line_index, line_text))
}
fn reconcile_single_line_composition_layouts(
&mut self,
composition_line: usize,
composition_line_len: usize,
line_box_size: Size,
line_style: &TextStyle,
) {
let line_count = self.editor.document().line_count();
let can_reuse = self.line_layout_box_size == Some(line_box_size)
&& self.line_layout_style.as_ref() == Some(line_style)
&& self.line_layout_style_revision == self.style_revision
&& self.line_layouts.len() == line_count
&& self.line_offsets.len() == line_count
&& self.line_lengths.len() == line_count;
if !can_reuse {
self.line_layouts = vec![None; line_count];
self.line_offsets.resize(line_count, 0);
self.line_lengths.resize(line_count, 0);
}
let document_line_len = self.editor.document().line_range(composition_line).len();
let inserted_delta = composition_line_len.saturating_sub(document_line_len);
let removed_delta = document_line_len.saturating_sub(composition_line_len);
for index in 0..line_count {
let document_range = self.editor.document().line_range(index);
let display_start = if index <= composition_line {
document_range.start
} else if inserted_delta > 0 {
document_range.start + inserted_delta
} else {
document_range.start - removed_delta
};
let display_len = if index == composition_line {
composition_line_len
} else {
document_range.len()
};
self.line_offsets[index] = display_start;
self.line_lengths[index] = display_len;
if !can_reuse || index == composition_line {
self.line_layouts[index] = None;
}
}
}
fn refresh_reusable_document_line_metadata(
document: &EditorDocument,
line_layouts: &mut [Option<PersistentTextLayout>],
line_offsets: &mut [usize],
line_lengths: &mut [usize],
) {
if let Some(start) = document.line_offsets_dirty_from() {
for index in start.min(document.line_count())..document.line_count() {
let line_range = document.line_range(index);
line_offsets[index] = line_range.start;
line_lengths[index] = line_range.len();
}
}
for index in document.dirty_line_range() {
if index < line_layouts.len() {
let line_range = document.line_range(index);
line_offsets[index] = line_range.start;
line_lengths[index] = line_range.len();
line_layouts[index] = None;
}
}
}
fn selection_range(&self) -> Range<usize> {
self.editor.selection_range()
}
fn display_text(&self) -> String {
self.editor.display_text()
}
fn display_text_len(&self) -> usize {
if let Some(composition) = self.editor.composition() {
self.editor
.document()
.len()
.saturating_sub(composition.replacement_range.len())
.saturating_add(composition.text.len())
} else {
self.editor.document().len()
}
}
fn display_selection(&self) -> TextSelection {
self.editor.display_selection()
}
fn layout_box_width(&self, available_width: f32) -> f32 {
if self.wrap == TextWrap::NoWrap {
1_000_000.0
} else {
available_width.max(1.0)
}
}
fn layout_box_size(&self, available_width: f32) -> Size {
let style = self.resolved_text_style();
let estimated_lines = if self.editor.composition().is_some() {
self.display_text().lines().count().max(1)
} else {
self.editor.document().line_count().max(1)
} as f32;
Size::new(
self.layout_box_width(available_width),
(estimated_lines * style.line_height).max(style.line_height),
)
}
fn content_rect(&self, bounds: Rect) -> Rect {
inset_rect(bounds, self.resolved_padding())
}
fn content_viewport_size(&self, bounds: Rect) -> Size {
self.content_rect(bounds).size
}
fn commit_text_change(&mut self) {
let value = self.current_value().to_string();
if let Some(on_change) = &mut self.on_change {
on_change(value);
}
}
fn apply_editor_result(&mut self, ctx: &mut EventCtx, mut result: EditorCommandResult) {
self.editor.apply_result_common(ctx, &mut result);
if result.text_changed {
if let Some(edit) = self.editor.take_text_edit() {
self.rebase_style_ranges_after_edit(&edit);
}
self.commit_text_change();
}
if result.layout_changed() {
ctx.request_text();
} else if result.overlay_changed() {
self.request_after_overlay_change(ctx);
}
if result.text_changed || result.selection_changed || result.composition_changed {
if !result.layout_changed() {
ctx.request_semantics();
}
}
}
fn execute_editor_command(
&mut self,
ctx: &mut EventCtx,
command: EditorCommand,
) -> EditorCommandResult {
let result = self.editor.execute(command);
self.apply_editor_result(ctx, result.clone());
result
}
pub fn select_all(&mut self, ctx: &mut EventCtx) {
self.execute_editor_command(ctx, EditorCommand::SelectAll);
}
pub fn copy(&mut self, ctx: &mut EventCtx) {
self.execute_editor_command(ctx, EditorCommand::Copy);
}
pub fn cut(&mut self, ctx: &mut EventCtx) {
if self.read_only {
return;
}
self.execute_editor_command(ctx, EditorCommand::Cut);
}
pub fn paste(&mut self, ctx: &mut EventCtx) {
if self.read_only {
return;
}
let command = paste_command(ctx, EditableTextLineMode::MultiLine);
self.execute_editor_command(ctx, command);
}
pub fn selected_text(&self) -> &str {
self.editor.selected_text()
}
fn apply_text_command(&mut self, ctx: &mut EventCtx, command: TextCommand) {
if let Some(command) = self.editor.text_command(
ctx,
command,
self.read_only,
EditableTextLineMode::MultiLine,
) {
self.execute_editor_command(ctx, command);
}
}
fn move_line_boundary(&mut self, to_start: bool, extend: bool) -> EditorCommandResult {
let focus = if extend {
self.editor.selection().focus.utf8_offset
} else {
self.selection_range().end
};
let target = if self.has_line_layout_cache() {
let line_index = self.line_index_for_offset(focus);
if to_start {
self.line_offsets[line_index]
} else {
self.line_offsets[line_index] + self.line_lengths[line_index]
}
} else if let Some(layout) = self.layout.as_ref() {
let caret = layout.caret(TextCursor::new(focus));
let line = &layout.lines()[caret.line_index];
if to_start {
line.byte_range.start
} else {
line.byte_range.end
}
} else {
return self.editor.execute(if to_start {
EditorCommand::MoveLineStart { extend }
} else {
EditorCommand::MoveLineEnd { extend }
});
};
self.editor.execute(EditorCommand::MoveTo {
offset: target,
extend,
})
}
fn move_vertical(
&mut self,
delta_lines: isize,
extend: bool,
_viewport_height: f32,
) -> EditorCommandResult {
let focus = if extend {
self.editor.selection().focus.utf8_offset
} else {
self.selection_range().end
};
if self.has_line_layout_cache() {
let Some(caret) = self.caret_rect_for_cursor(TextCursor::new(focus)) else {
return EditorCommandResult::default();
};
let preferred_x = self.editor.preferred_x().unwrap_or(caret.x());
let line_index = self.line_index_for_offset(focus) as isize + delta_lines;
let target_line =
line_index.clamp(0, self.line_count().saturating_sub(1) as isize) as usize;
let local_offset = if let Some(Some(layout)) = self.line_layouts.get(target_line) {
let Some(line) = layout.lines().first() else {
return EditorCommandResult::default();
};
let local = layout.hit_test_point(Point::new(
preferred_x,
line.rect.y() + (line.rect.height() * 0.5),
));
local.utf8_offset.min(self.line_lengths[target_line])
} else {
self.estimate_inline_offset_for_x(target_line, preferred_x)
};
let target = self.line_offsets[target_line] + local_offset;
let result = self.editor.execute(EditorCommand::MoveTo {
offset: target,
extend,
});
self.editor.set_preferred_x(Some(preferred_x));
return result;
}
let Some(layout) = self.layout.as_ref() else {
let lines = delta_lines.unsigned_abs().max(1);
return self.editor.execute(if delta_lines < 0 {
if lines == 1 {
EditorCommand::MoveUp { extend }
} else {
EditorCommand::PageUp { extend, lines }
}
} else if lines == 1 {
EditorCommand::MoveDown { extend }
} else {
EditorCommand::PageDown { extend, lines }
});
};
if layout.lines().is_empty() {
return EditorCommandResult::default();
}
let caret = layout.caret(TextCursor::new(focus));
let preferred_x = self.editor.preferred_x().unwrap_or(caret.rect.x());
let line_index = caret.line_index as isize + delta_lines;
let target_line =
line_index.clamp(0, layout.lines().len().saturating_sub(1) as isize) as usize;
let line = &layout.lines()[target_line];
let target = layout.hit_test_point(Point::new(
preferred_x,
line.rect.y() + (line.rect.height() * 0.5),
));
let result = self.editor.execute(EditorCommand::MoveTo {
offset: target.utf8_offset,
extend,
});
self.editor.set_preferred_x(Some(preferred_x));
result
}
fn shape_line_layout(
&self,
ctx: &mut MeasureCtx,
handle: Option<sui_text::TextLayoutHandle>,
line_text: &str,
line_range: Range<usize>,
line_box_size: Size,
base_style: TextStyle,
) -> sui_core::Result<PersistentTextLayout> {
if self.style_spans.is_empty() && self.style_overlays.is_empty() {
return ctx.layout().shape_text_persistent(
handle,
line_text.to_string(),
line_box_size,
base_style,
);
}
let spans = self.line_text_spans(line_text, line_range, base_style);
let mut paragraph = TextParagraph::from_spans(spans);
paragraph.style.direction = self.direction;
paragraph.style.wrap = self.wrap;
ctx.layout().layout_document_persistent(
handle,
TextLayoutRequest::new(TextDocument {
paragraphs: vec![paragraph],
})
.with_box_size(line_box_size),
)
}
fn line_text_spans(
&self,
line_text: &str,
line_range: Range<usize>,
base_style: TextStyle,
) -> Vec<TextSpan> {
let style_indices = self.style_span_index.overlapping_indices(&line_range);
let overlay_indices = self.style_overlay_index.overlapping_indices(&line_range);
let mut breaks =
Vec::with_capacity(2 + (style_indices.len() + overlay_indices.len()).saturating_mul(2));
breaks.extend([0, line_text.len()]);
for index in &style_indices {
Self::collect_style_breaks(
&self.style_spans[*index].range,
&line_range,
line_text,
&mut breaks,
);
}
for index in &overlay_indices {
Self::collect_style_breaks(
&self.style_overlays[*index].range,
&line_range,
line_text,
&mut breaks,
);
}
breaks.sort_unstable();
breaks.dedup();
let mut spans = Vec::new();
for pair in breaks.windows(2) {
let start = pair[0];
let end = pair[1];
if start >= end {
continue;
}
let global_range = line_range.start + start..line_range.start + end;
let mut style = base_style.clone();
for index in &style_indices {
let span = &self.style_spans[*index];
if ranges_intersect(&global_range, &span.range) {
style = span.style.clone();
}
}
for index in &overlay_indices {
let overlay = &self.style_overlays[*index];
if ranges_intersect(&global_range, &overlay.range) {
style = overlay.style.clone();
}
}
spans.push(TextSpan::new(line_text[start..end].to_string(), style));
}
if spans.is_empty() {
spans.push(TextSpan::new(String::new(), base_style));
}
spans
}
fn collect_style_breaks(
span_range: &Range<usize>,
line_range: &Range<usize>,
line_text: &str,
breaks: &mut Vec<usize>,
) {
if !ranges_intersect(line_range, span_range) {
return;
}
let local_start = span_range.start.saturating_sub(line_range.start);
let local_end = span_range
.end
.min(line_range.end)
.saturating_sub(line_range.start);
breaks.push(clamp_to_grapheme_boundary(line_text, local_start));
breaks.push(clamp_to_grapheme_boundary(line_text, local_end));
}
fn update_hovered(&mut self, hovered: bool, ctx: &mut EventCtx) {
if self.hovered != hovered {
let theme = self.resolved_theme();
self.hovered = hovered;
set_hover_animation_target(
&mut self.hover_animation,
hovered as u8 as f32,
&theme,
ctx,
);
ctx.request_paint();
ctx.request_semantics();
}
}
fn advance_animations(&mut self, time: f64, ctx: &mut EventCtx) {
let previous_hover = self.hover_animation.value;
let previous_focus = self.focus_animation.value;
let animating = self.hover_animation.advance(time) | self.focus_animation.advance(time);
let changed = self.hover_animation.changed_since(previous_hover)
|| self.focus_animation.changed_since(previous_focus);
if changed {
ctx.request_paint();
}
if animating {
ctx.request_animation_frame();
}
}
fn point_to_cursor(&self, bounds: Rect, position: Point) -> Option<TextCursor> {
let content = self.content_rect(bounds);
if !content.contains(position) {
return None;
}
if self.has_line_layout_cache() {
let local_x = position.x - content.x() + self.editor.scroll_x();
let local_y = position.y - content.y() + self.editor.scroll_y();
let line_index = self.line_index_for_y(local_y);
let local_offset = if let Some(Some(layout)) = self.line_layouts.get(line_index) {
let line = layout.lines().first()?;
let local = layout.hit_test_point(Point::new(
local_x,
line.rect.y() + (line.rect.height() * 0.5),
));
local.utf8_offset.min(self.line_lengths[line_index])
} else {
self.estimate_inline_offset_for_x(line_index, local_x)
};
return Some(TextCursor::new(
self.line_offsets[line_index] + local_offset,
));
}
let layout = self.layout.as_ref()?;
let local = Point::new(
position.x - content.x() + self.editor.scroll_x(),
position.y - content.y() + self.editor.scroll_y(),
);
Some(layout.hit_test_point(local))
}
fn line_range_with_overdraw(&self, viewport_height: f32, overdraw: f32) -> Range<usize> {
if self.has_line_layout_cache() {
if viewport_height <= 0.0 {
return 0..0;
}
let line_height = self.line_height().max(1.0);
let visible_top = (self.editor.scroll_y() - overdraw).max(0.0);
let visible_bottom = self.editor.scroll_y() + viewport_height + overdraw;
let start = (visible_top / line_height).floor() as usize;
let end = ((visible_bottom / line_height).ceil() as usize + 1)
.min(self.line_count())
.max(start + usize::from(start < self.line_count()));
return start.min(self.line_count())..end;
}
let Some(layout) = self.layout.as_ref() else {
return 0..0;
};
if layout.lines().is_empty() || viewport_height <= 0.0 {
return 0..0;
}
let visible_top = (self.editor.scroll_y() - overdraw).max(0.0);
let visible_bottom = self.editor.scroll_y() + viewport_height + overdraw;
let mut start = 0usize;
while start < layout.lines().len() {
if layout.lines()[start].rect.max_y() >= visible_top {
break;
}
start += 1;
}
let mut end = start;
while end < layout.lines().len() {
if layout.lines()[end].rect.y() > visible_bottom {
break;
}
end += 1;
}
start..end.max(start + usize::from(start < layout.lines().len()))
}
fn visible_line_range(&self, viewport_height: f32) -> Range<usize> {
self.line_range_with_overdraw(viewport_height, 0.0)
}
fn prefetched_line_range(&self, viewport_height: f32) -> Range<usize> {
let overdraw = self.line_height().max(1.0) * 6.0;
self.line_range_with_overdraw(viewport_height, overdraw)
}
fn visible_line_layouts_are_ready(&self, viewport_height: f32) -> bool {
if !self.has_line_layout_cache() {
return self.layout.is_some();
}
self.visible_line_range(viewport_height)
.all(|index| self.line_layouts.get(index).is_some_and(Option::is_some))
}
fn request_view_refresh(&self, ctx: &mut EventCtx) {
let viewport_height = self.content_viewport_size(ctx.bounds()).height;
if self.visible_line_layouts_are_ready(viewport_height) {
ctx.request_paint();
} else {
ctx.request_measure();
}
}
fn clamp_scroll_to_bounds(&mut self, viewport_size: Size) -> bool {
let previous = (self.editor.scroll_x(), self.editor.scroll_y());
let content_size = if self.has_line_layout_cache() {
self.multi_line_content_size()
} else if let Some(layout) = self.layout.as_ref() {
layout_content_size(layout)
} else {
self.editor.set_scroll(0.0, 0.0);
return previous != (0.0, 0.0);
};
let max_x = if self.wrap == TextWrap::NoWrap {
(content_size.width - viewport_size.width).max(0.0)
} else {
0.0
};
let max_y = (content_size.height - viewport_size.height).max(0.0);
let scroll_x = self.editor.scroll_x().clamp(0.0, max_x);
let scroll_y = self.editor.scroll_y().clamp(0.0, max_y);
self.editor.set_scroll(scroll_x, scroll_y);
previous != (self.editor.scroll_x(), self.editor.scroll_y())
}
fn ensure_caret_visible(&mut self, bounds: Rect) -> bool {
let viewport = self.content_viewport_size(bounds);
if viewport.width <= 0.0 || viewport.height <= 0.0 {
return false;
}
let previous = (self.editor.scroll_x(), self.editor.scroll_y());
let Some(caret) = self.caret_rect_for_cursor(self.display_selection().focus) else {
return false;
};
let mut scroll_x = self.editor.scroll_x();
let mut scroll_y = self.editor.scroll_y();
if self.wrap == TextWrap::NoWrap {
if caret.x() < scroll_x {
scroll_x = caret.x().max(0.0);
} else if caret.max_x() > scroll_x + viewport.width {
scroll_x = (caret.max_x() - viewport.width).max(0.0);
}
} else {
scroll_x = 0.0;
}
if caret.y() < scroll_y {
scroll_y = caret.y().max(0.0);
} else if caret.max_y() > scroll_y + viewport.height {
scroll_y = (caret.max_y() - viewport.height).max(0.0);
}
self.editor.set_scroll(scroll_x, scroll_y);
let _ = self.clamp_scroll_to_bounds(viewport);
previous != (self.editor.scroll_x(), self.editor.scroll_y())
}
fn scroll_by(&mut self, bounds: Rect, delta: Vector) -> bool {
let previous = (self.editor.scroll_x(), self.editor.scroll_y());
let mut scroll_x = self.editor.scroll_x();
let mut scroll_y = self.editor.scroll_y();
if self.wrap == TextWrap::NoWrap {
scroll_x += delta.x;
}
scroll_y += delta.y;
self.editor.set_scroll(scroll_x, scroll_y);
let _ = self.clamp_scroll_to_bounds(self.content_viewport_size(bounds));
previous != (self.editor.scroll_x(), self.editor.scroll_y())
}
fn request_after_overlay_change(&mut self, ctx: &mut EventCtx) {
if self.ensure_caret_visible(ctx.bounds()) {
self.request_view_refresh(ctx);
} else {
ctx.request_paint();
}
}
fn line_count(&self) -> usize {
self.line_offsets.len()
}
fn has_line_layout_cache(&self) -> bool {
!self.line_offsets.is_empty()
}
fn line_slot_height_for_style(&self, base_style: &TextStyle) -> f32 {
let base = base_style.line_height.max(base_style.font_size).max(1.0);
base.max(self.style_span_max_line_height)
.max(self.style_overlay_max_line_height)
}
fn line_height(&self) -> f32 {
self.line_slot_height_for_style(&self.resolved_text_style())
}
fn line_layout_height(&self, layout: &PersistentTextLayout, base_line_height: f32) -> f32 {
layout.measurement().height.max(base_line_height)
}
fn line_layout_y_offset(
&self,
layout: &PersistentTextLayout,
base_line_height: f32,
slot_height: f32,
) -> f32 {
((slot_height - self.line_layout_height(layout, base_line_height)).max(0.0)) * 0.5
}
fn line_origin_y(
&self,
line_index: usize,
layout: &PersistentTextLayout,
base_line_height: f32,
slot_height: f32,
) -> f32 {
line_index as f32 * slot_height
+ self.line_layout_y_offset(layout, base_line_height, slot_height)
}
fn line_index_for_offset(&self, offset: usize) -> usize {
let offset = offset.min(self.display_text_len());
if self.editor.composition().is_none() && self.has_line_layout_cache() {
return self
.editor
.document()
.line_index_for_offset(offset)
.min(self.line_count().saturating_sub(1));
}
self.line_offsets
.iter()
.enumerate()
.rev()
.find(|(_, start)| **start <= offset)
.map(|(index, _)| index)
.unwrap_or(0)
}
fn line_index_for_y(&self, y: f32) -> usize {
let line_height = self.line_height().max(1.0);
((y / line_height).floor() as usize).min(self.line_count().saturating_sub(1))
}
fn estimate_inline_offset_for_x(&self, line_index: usize, x: f32) -> usize {
let length = self.line_lengths.get(line_index).copied().unwrap_or(0);
if length == 0 {
return 0;
}
let average_advance = (self.resolved_text_style().font_size * 0.55).max(1.0);
((x.max(0.0) / average_advance).round() as usize).min(length)
}
fn estimated_caret_rect_for_line(&self, line_index: usize, local_offset: usize) -> Rect {
let style = self.resolved_text_style();
let average_advance = (style.font_size * 0.55).max(1.0);
Rect::new(
average_advance * local_offset as f32,
line_index as f32 * self.line_height(),
1.0,
style.line_height.max(1.0),
)
}
fn caret_rect_for_cursor(&self, cursor: TextCursor) -> Option<Rect> {
if self.has_line_layout_cache() {
let line_index = self.line_index_for_offset(cursor.utf8_offset);
let local_offset = cursor
.utf8_offset
.saturating_sub(self.line_offsets[line_index])
.min(self.line_lengths[line_index]);
let Some(Some(layout)) = self.line_layouts.get(line_index) else {
return Some(self.estimated_caret_rect_for_line(line_index, local_offset));
};
let base_line_height = self.resolved_text_style().line_height;
let slot_height = self.line_height();
return Some(layout.caret_rect(local_offset).translate(Vector::new(
0.0,
self.line_origin_y(line_index, layout, base_line_height, slot_height),
)));
}
self.layout.as_ref().map(|layout| layout.caret(cursor).rect)
}
fn selection_rects_for_display(&self, selection: &TextSelection) -> Vec<Rect> {
if self.has_line_layout_cache() {
let mut rects = Vec::new();
let range = selection_range(selection, self.display_text_len());
if range.is_empty() || self.line_count() == 0 {
return rects;
}
let start_line = self.line_index_for_offset(range.start);
let end_line = self
.line_index_for_offset(range.end)
.min(self.line_count().saturating_sub(1));
let base_line_height = self.resolved_text_style().line_height;
let slot_height = self.line_height();
for line_index in start_line..=end_line {
let line_start = self.line_offsets[line_index];
let line_end = line_start + self.line_lengths[line_index];
let selection_start = range.start.max(line_start);
let selection_end = range.end.min(line_end);
if selection_start >= selection_end {
continue;
}
let local_range = selection_start.saturating_sub(line_start)
..selection_end.saturating_sub(line_start);
let Some(Some(layout)) = self.line_layouts.get(line_index) else {
let start = self.estimated_caret_rect_for_line(line_index, local_range.start);
let end = self.estimated_caret_rect_for_line(line_index, local_range.end);
rects.push(Rect::new(
start.x(),
start.y(),
(end.x() - start.x()).max(1.0),
start.height(),
));
continue;
};
let local_rects = layout.selection_rects(local_range);
rects.extend(local_rects.into_iter().map(|rect| {
rect.translate(Vector::new(
0.0,
self.line_origin_y(line_index, layout, base_line_height, slot_height),
))
}));
}
return rects;
}
self.layout
.as_ref()
.map(|layout| layout.selection_geometry(selection).rects)
.unwrap_or_default()
}
fn multi_line_content_size(&self) -> Size {
let estimated_advance = self.resolved_text_style().font_size * 0.55;
let estimated_width = self
.line_lengths
.iter()
.map(|length| *length as f32 * estimated_advance)
.fold(0.0_f32, f32::max);
let measured_width = self
.line_layouts
.iter()
.filter_map(|layout| layout.as_ref())
.map(|layout| layout.measurement().width)
.fold(0.0_f32, f32::max);
Size::new(
estimated_width.max(measured_width),
self.line_count() as f32 * self.line_height(),
)
}
}
impl Widget for TextSurface {
fn event(&mut self, ctx: &mut EventCtx, event: &Event) {
match event {
Event::Pointer(pointer) if pointer.kind == PointerEventKind::Move => {
let hovered = ctx.bounds().contains(pointer.position);
self.update_hovered(hovered, ctx);
if self.dragging_selection
&& ctx.phase() != EventPhase::Capture
&& pointer.buttons.contains(PointerButton::Primary)
&& let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position)
{
let anchor = self.editor.selection().anchor.utf8_offset;
let result = self.editor.execute(EditorCommand::SetSelection {
anchor,
focus: cursor.utf8_offset,
});
self.apply_editor_result(ctx, result);
}
}
Event::Pointer(pointer)
if pointer.kind == PointerEventKind::Down
&& pointer.button == Some(PointerButton::Primary)
&& ctx.phase() != EventPhase::Capture
&& ctx.bounds().contains(pointer.position) =>
{
self.update_hovered(true, ctx);
let clear_result = self.editor.execute(EditorCommand::ClearComposition);
self.apply_editor_result(ctx, clear_result);
if let Some(cursor) = self.point_to_cursor(ctx.bounds(), pointer.position) {
let command = if pointer.modifiers.shift {
EditorCommand::SetSelection {
anchor: self.editor.selection().anchor.utf8_offset,
focus: cursor.utf8_offset,
}
} else {
EditorCommand::MoveTo {
offset: cursor.utf8_offset,
extend: false,
}
};
let result = self.editor.execute(command);
self.apply_editor_result(ctx, result);
}
self.dragging_selection = true;
ctx.request_focus();
ctx.request_pointer_capture(pointer.pointer_id);
self.request_after_overlay_change(ctx);
ctx.request_semantics();
ctx.set_handled();
}
Event::Pointer(pointer)
if pointer.kind == PointerEventKind::Up
&& pointer.button == Some(PointerButton::Primary)
&& self.dragging_selection =>
{
self.dragging_selection = false;
ctx.release_pointer_capture(pointer.pointer_id);
ctx.request_paint();
ctx.set_handled();
}
Event::Pointer(pointer) if pointer.kind == PointerEventKind::Cancel => {
if self.dragging_selection {
self.dragging_selection = false;
ctx.release_pointer_capture(pointer.pointer_id);
ctx.request_paint();
ctx.set_handled();
}
}
Event::Pointer(pointer)
if pointer.kind == PointerEventKind::Down
&& pointer.button == Some(PointerButton::Secondary)
&& ctx.phase() != EventPhase::Capture
&& ctx.bounds().contains(pointer.position) =>
{
self.update_hovered(true, ctx);
if !ctx.is_focused() {
ctx.request_focus();
self.request_after_overlay_change(ctx);
ctx.request_semantics();
}
}
Event::Pointer(pointer)
if pointer.kind == PointerEventKind::Scroll
&& ctx.phase() != EventPhase::Capture
&& ctx.bounds().contains(pointer.position) =>
{
let delta = pointer
.scroll_delta
.map(scroll_delta_to_offset)
.unwrap_or(pointer.delta);
if self.scroll_by(ctx.bounds(), Vector::new(-delta.x, -delta.y)) {
self.request_view_refresh(ctx);
ctx.request_semantics();
ctx.set_handled();
}
}
Event::Semantics(semantics) if semantics.target == ctx.widget_id() => {
if let Some(commands) = self.editor.semantics_commands(
ctx,
&semantics.action,
self.read_only,
EditableTextLineMode::MultiLine,
) {
for command in commands {
self.execute_editor_command(ctx, command);
}
}
}
Event::Ime(ImeEvent::CompositionStart) if ctx.is_focused() && !self.read_only => {
self.execute_editor_command(ctx, EditorCommand::StartComposition);
}
Event::Ime(ImeEvent::CompositionUpdate { text, cursor_range })
if ctx.is_focused() && !self.read_only =>
{
self.execute_editor_command(
ctx,
EditorCommand::UpdateComposition {
text: text.clone(),
cursor_range: cursor_range.clone(),
},
);
}
Event::Ime(ImeEvent::CompositionCommit { text })
if ctx.is_focused() && !self.read_only =>
{
self.execute_editor_command(ctx, EditorCommand::CommitComposition(text.clone()));
}
Event::Ime(ImeEvent::CompositionEnd) if ctx.is_focused() && !self.read_only => {
self.execute_editor_command(ctx, EditorCommand::EndComposition);
}
Event::Keyboard(key) if ctx.is_focused() && key.state == KeyState::Pressed => {
let result = match key.key.as_str() {
"ArrowUp" => Some(self.move_vertical(
-1,
key.modifiers.shift,
self.content_viewport_size(ctx.bounds()).height,
)),
"ArrowDown" => Some(self.move_vertical(
1,
key.modifiers.shift,
self.content_viewport_size(ctx.bounds()).height,
)),
"Home" => Some(self.move_line_boundary(true, key.modifiers.shift)),
"End" => Some(self.move_line_boundary(false, key.modifiers.shift)),
"PageUp" => {
let line_height = self.line_height().max(1.0);
let delta = (self.content_viewport_size(ctx.bounds()).height / line_height)
.floor()
.max(1.0) as isize;
Some(self.move_vertical(
-delta,
key.modifiers.shift,
self.content_viewport_size(ctx.bounds()).height,
))
}
"PageDown" => {
let line_height = self.line_height().max(1.0);
let delta = (self.content_viewport_size(ctx.bounds()).height / line_height)
.floor()
.max(1.0) as isize;
Some(self.move_vertical(
delta,
key.modifiers.shift,
self.content_viewport_size(ctx.bounds()).height,
))
}
_ => self
.editor
.keyboard_command(ctx, key, self.read_only, EditableTextLineMode::MultiLine)
.map(|command| self.editor.execute(command)),
};
if let Some(result) = result {
self.apply_editor_result(ctx, result);
}
}
Event::Window(WindowEvent::Focused(false)) => {
let result = self.editor.execute(EditorCommand::ClearComposition);
self.apply_editor_result(ctx, result);
}
Event::Wake(WakeEvent::AnimationFrame { time, .. }) => {
self.advance_animations(*time, ctx);
}
_ => {}
}
}
fn command(&mut self, ctx: &mut EventCtx, command: &Command<'_>) {
let Some(command) = TextCommand::from_command(command) else {
return;
};
if !ctx.is_focused() {
ctx.request_focus();
}
self.apply_text_command(ctx, command);
}
fn measure(&mut self, ctx: &mut MeasureCtx, constraints: Constraints) -> Size {
let padding = self.resolved_padding();
let min_size = self.resolved_min_size();
let available_width = if constraints.max.width.is_finite() {
(constraints.max.width - padding.left - padding.right).max(0.0)
} else {
(min_size.width - padding.left - padding.right).max(0.0)
};
let composition_active = self.editor.composition().is_some();
let line_style = self.display_text_style();
let line_box_size = Size::new(
self.layout_box_width(available_width),
line_style.line_height.max(1.0),
);
let viewport_height = if constraints.max.height.is_finite() {
(constraints.max.height - padding.top - padding.bottom).max(0.0)
} else {
(min_size.height - padding.top - padding.bottom).max(line_style.line_height)
};
let cache_lines_individually = self.wrap == TextWrap::NoWrap;
let mut line_layout_failed = false;
if !composition_active {
let document = self.editor.document();
let line_count = document.line_count();
if cache_lines_individually && line_count > 1 {
let can_reuse_lines = self.line_layout_revision != u64::MAX
&& self.line_layout_box_size == Some(line_box_size)
&& self.line_layout_style.as_ref() == Some(&line_style)
&& self.line_layout_style_revision == self.style_revision
&& self.line_layouts.len() == line_count
&& self.line_offsets.len() == line_count
&& self.line_lengths.len() == line_count;
if !can_reuse_lines {
self.line_layouts = vec![None; line_count];
self.line_offsets.clear();
self.line_lengths.clear();
self.line_offsets.reserve(line_count);
self.line_lengths.reserve(line_count);
for index in 0..line_count {
let line_range = document.line_range(index);
self.line_offsets.push(line_range.start);
self.line_lengths.push(line_range.len());
}
} else {
Self::refresh_reusable_document_line_metadata(
document,
&mut self.line_layouts,
&mut self.line_offsets,
&mut self.line_lengths,
);
}
let visible_lines = self.prefetched_line_range(viewport_height);
let caret_line =
self.line_index_for_offset(self.display_selection().focus.utf8_offset);
let mut lines_to_shape = Vec::with_capacity(visible_lines.len().saturating_add(1));
lines_to_shape.extend(visible_lines);
if caret_line < line_count && !lines_to_shape.contains(&caret_line) {
lines_to_shape.push(caret_line);
}
for index in lines_to_shape {
if self.line_layouts[index].is_some() {
continue;
}
let line_range = document.line_range(index);
match self.shape_line_layout(
ctx,
None,
document.line_text(index),
line_range,
line_box_size,
line_style.clone(),
) {
Ok(layout) => self.line_layouts[index] = Some(layout),
Err(_) => {
line_layout_failed = true;
break;
}
}
}
if !line_layout_failed {
self.line_layout_box_size = Some(line_box_size);
self.line_layout_style = Some(line_style.clone());
self.line_layout_revision = document.revision();
self.line_layout_style_revision = self.style_revision;
self.layout = None;
self.editor.clear_document_dirty();
}
} else {
self.line_layouts.clear();
self.line_offsets.clear();
self.line_lengths.clear();
self.line_layout_box_size = None;
self.line_layout_style = None;
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = u64::MAX;
}
} else {
let single_line_composition = self.single_line_composition_display_line();
if cache_lines_individually
&& self.editor.document().line_count() > 1
&& let Some((composition_line, composition_line_text)) = single_line_composition
{
self.reconcile_single_line_composition_layouts(
composition_line,
composition_line_text.len(),
line_box_size,
&line_style,
);
let visible_lines = self.prefetched_line_range(viewport_height);
let caret_line =
self.line_index_for_offset(self.display_selection().focus.utf8_offset);
let line_count = self.editor.document().line_count();
let mut lines_to_shape = Vec::with_capacity(visible_lines.len().saturating_add(1));
lines_to_shape.extend(visible_lines);
if caret_line < line_count && !lines_to_shape.contains(&caret_line) {
lines_to_shape.push(caret_line);
}
for index in lines_to_shape {
if self.line_layouts[index].is_some() {
continue;
}
let line_range = if index == composition_line {
self.line_offsets[index]
..self.line_offsets[index] + self.line_lengths[index]
} else {
self.editor.document().line_range(index)
};
let line_text = if index == composition_line {
composition_line_text.as_str()
} else {
self.editor.document().line_text(index)
};
match self.shape_line_layout(
ctx,
None,
line_text,
line_range,
line_box_size,
line_style.clone(),
) {
Ok(layout) => self.line_layouts[index] = Some(layout),
Err(_) => {
line_layout_failed = true;
break;
}
}
}
if !line_layout_failed {
self.line_layout_box_size = Some(line_box_size);
self.line_layout_style = Some(line_style.clone());
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = self.style_revision;
self.layout = None;
}
} else {
let display_text = self.display_text();
let (line_texts, line_offsets, line_lengths) =
split_lines_with_offsets(&display_text);
if cache_lines_individually && line_texts.len() > 1 {
self.reconcile_composition_line_layouts(
&line_texts,
line_offsets,
line_lengths,
line_box_size,
&line_style,
);
let visible_lines = self.prefetched_line_range(viewport_height);
let caret_line =
self.line_index_for_offset(self.display_selection().focus.utf8_offset);
let mut lines_to_shape =
Vec::with_capacity(visible_lines.len().saturating_add(1));
lines_to_shape.extend(visible_lines);
if caret_line < line_texts.len() && !lines_to_shape.contains(&caret_line) {
lines_to_shape.push(caret_line);
}
for index in lines_to_shape {
if self.line_layouts[index].is_some() {
continue;
}
let line_range = self.line_offsets[index]
..self.line_offsets[index] + self.line_lengths[index];
match self.shape_line_layout(
ctx,
None,
&line_texts[index],
line_range,
line_box_size,
line_style.clone(),
) {
Ok(layout) => self.line_layouts[index] = Some(layout),
Err(_) => {
line_layout_failed = true;
break;
}
}
}
if !line_layout_failed {
self.line_layout_box_size = Some(line_box_size);
self.line_layout_style = Some(line_style.clone());
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = self.style_revision;
self.layout = None;
}
} else {
self.line_layouts.clear();
self.line_offsets.clear();
self.line_lengths.clear();
self.line_layout_box_size = None;
self.line_layout_style = None;
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = u64::MAX;
}
}
}
if line_layout_failed {
self.line_layouts.clear();
self.line_offsets.clear();
self.line_lengths.clear();
self.line_layout_box_size = None;
self.line_layout_style = None;
self.line_layout_revision = u64::MAX;
self.line_layout_style_revision = u64::MAX;
}
self.layout = if !self.has_line_layout_cache() {
let display_text = self.display_text();
let handle = self.layout.as_ref().map(|layout| layout.handle());
let box_size = self.layout_box_size(available_width);
if self.style_spans.is_empty() && self.style_overlays.is_empty() {
ctx.layout()
.shape_text_persistent(handle, display_text, box_size, line_style)
.ok()
} else {
self.shape_line_layout(
ctx,
handle,
&display_text,
0..display_text.len(),
box_size,
line_style,
)
.ok()
}
} else {
None
};
let mut natural_content_size = if self.has_line_layout_cache() {
self.multi_line_content_size()
} else {
self.layout
.as_ref()
.map(layout_content_size)
.unwrap_or(Size::new(min_size.width, min_size.height))
};
if self.should_show_placeholder() {
let placeholder_style = self.placeholder_text_style();
if let Ok(measurement) = ctx
.layout()
.measure_text(self.placeholder.clone(), placeholder_style.clone())
{
natural_content_size.width = natural_content_size.width.max(measurement.width);
natural_content_size.height = natural_content_size
.height
.max(measurement.height.max(placeholder_style.line_height));
}
}
let natural = Size::new(
natural_content_size.width + padding.left + padding.right,
natural_content_size.height + padding.top + padding.bottom,
);
let desired = Size::new(
if constraints.max.width.is_finite() {
constraints.max.width
} else {
natural.width.max(min_size.width)
},
if constraints.max.height.is_finite() {
constraints.max.height
} else {
natural.height.max(min_size.height)
},
);
let size = constraints.clamp(Size::new(
desired.width.max(min_size.width),
desired.height.max(min_size.height),
));
let _ = self.clamp_scroll_to_bounds(
self.content_viewport_size(Rect::from_origin_size(Point::ZERO, size)),
);
size
}
fn paint(&self, ctx: &mut PaintCtx) {
let theme = self.resolved_theme();
let palette = theme.palette;
let metrics = theme.metrics;
let content = self.content_rect(ctx.bounds());
let hover_progress = self.hover_animation.value;
let focus_progress = self.focus_animation.value;
let base_background = if self.read_only {
palette.surface
} else {
mix_color(palette.control, palette.control_hover, hover_progress)
};
let background = mix_color(base_background, palette.surface_focus, focus_progress);
let border = mix_color(
mix_color(palette.border, palette.border_hover, hover_progress),
palette.border_focus,
focus_progress,
);
draw_surface_frame(
ctx,
ctx.bounds(),
metrics.corner_radius,
metrics.border_width,
background,
border,
(focus_progress > AnimatedScalar::EPSILON).then_some(
palette
.focus_ring
.with_alpha(palette.focus_ring.alpha * focus_progress),
),
metrics.focus_ring_width,
metrics.focus_ring_outset,
);
if !self.has_line_layout_cache() && self.layout.is_none() {
return;
}
let display_selection = self.display_selection();
let origin = Point::new(
content.x() - self.editor.scroll_x(),
content.y() - self.editor.scroll_y(),
);
let line_range = self.visible_line_range(content.height());
let selection_rects = self.selection_rects_for_display(&display_selection);
let current_caret = self.caret_rect_for_cursor(display_selection.focus);
let current_line_index = self.line_index_for_offset(display_selection.focus.utf8_offset);
let base_line_height = self.resolved_text_style().line_height;
let slot_height = self.line_height();
ctx.push_clip_rect(content);
if selection_rects.is_empty() {
let line_rect = Rect::new(
content.x(),
origin.y + current_line_index as f32 * slot_height,
content.width(),
slot_height,
);
ctx.fill(
Path::rounded_rect(line_rect, 0.0),
palette.accent.with_alpha(match theme.colors.scheme {
ThemeColorScheme::Light => 0.05,
ThemeColorScheme::Dark => 0.12,
ThemeColorScheme::HighContrast => 0.18,
}),
);
} else {
for rect in selection_rects {
ctx.fill(
Path::rounded_rect(rect.translate(origin.to_vector()), 3.0),
palette.selection,
);
}
}
if self.should_show_placeholder() {
let placeholder_style = self.placeholder_text_style();
let placeholder_slot = Rect::new(
origin.x,
origin.y,
content.width(),
slot_height.max(placeholder_style.line_height),
);
paint_aligned_text(
ctx,
placeholder_slot,
&self.placeholder,
&placeholder_style,
placeholder_style.line_height,
0.0,
);
}
if self.has_line_layout_cache() {
for line_index in line_range {
if let Some(Some(layout)) = self.line_layouts.get(line_index) {
let line_y =
self.line_origin_y(line_index, layout, base_line_height, slot_height);
ctx.draw_persistent_text_layout(
Point::new(origin.x, origin.y + line_y),
layout,
);
}
}
} else if let Some(layout) = &self.layout {
ctx.draw_persistent_text_layout_window(origin, layout, line_range);
}
if ctx.is_focused() && !self.read_only {
let Some(current_caret) = current_caret else {
ctx.pop_clip();
return;
};
let caret_width = physical_pixels(ctx, metrics.caret_width);
let caret = Rect::new(
origin.x + current_caret.x(),
origin.y + current_caret.y(),
caret_width,
current_caret.height().max(1.0),
);
ctx.set_ime_composition_rect(caret);
ctx.fill(Path::rounded_rect(caret, caret_width * 0.5), palette.caret);
}
ctx.pop_clip();
}
fn layer_options(&self) -> LayerOptions {
LayerOptions {
paint_boundary: PaintBoundaryMode::Explicit,
composition_mode: LayerCompositionMode::Scroll,
}
}
fn semantics(&self, ctx: &mut SemanticsCtx) {
let mut node = SemanticsNode::new(ctx.widget_id(), SemanticsRole::TextInput, ctx.bounds());
let display_text = self.display_text();
let display_selection = self.display_selection();
let selection = selection_range(&display_selection, display_text.len());
node.name = Some(self.name.clone());
node.value = Some(SemanticsValue::Text(display_text));
node.state.focused = ctx.is_focused();
node.state.hovered = self.hovered;
node.editable_text = Some(EditableTextSemantics {
caret_offset: display_selection.focus.utf8_offset,
selection: SemanticsTextRange::new(selection.start, selection.end),
multiline: true,
password: false,
readonly: self.read_only,
scroll_x: self.editor.scroll_x(),
scroll_y: self.editor.scroll_y(),
});
node.actions = self.editor.semantic_actions(self.read_only);
ctx.push(node);
}
fn accepts_focus(&self) -> bool {
true
}
fn focus_changed(&mut self, ctx: &mut EventCtx, focused: bool) {
if !focused {
let result = self.editor.execute(EditorCommand::ClearComposition);
if result.layout_changed() {
ctx.request_text();
}
}
let theme = self.resolved_theme();
set_focus_animation_target(&mut self.focus_animation, focused as u8 as f32, &theme, ctx);
ctx.request_paint();
ctx.request_semantics();
}
}
type AnimatedScalar = MotionScalar;
fn set_animation_target(
animation: &mut AnimatedScalar,
target: f32,
duration: f64,
easing: crate::Easing,
ctx: &mut EventCtx,
) -> bool {
animation.set_target_event(target, duration, easing, ctx)
}
fn set_hover_animation_target(
animation: &mut AnimatedScalar,
target: f32,
theme: &DefaultTheme,
ctx: &mut EventCtx,
) -> bool {
set_animation_target(
animation,
target,
theme.motion.hover_duration(),
theme.motion.hover_easing(),
ctx,
)
}
fn set_focus_animation_target(
animation: &mut AnimatedScalar,
target: f32,
theme: &DefaultTheme,
ctx: &mut EventCtx,
) -> bool {
set_animation_target(
animation,
target,
theme.motion.focus_duration(),
theme.motion.focus_easing(),
ctx,
)
}
fn mix_color(from: Color, to: Color, amount: f32) -> Color {
crate::animation::Interpolate::interpolate(from, to, amount).clamped()
}
fn inset_rect(rect: Rect, padding: Insets) -> Rect {
Rect::new(
rect.x() + padding.left,
rect.y() + padding.top,
(rect.width() - padding.left - padding.right).max(0.0),
(rect.height() - padding.top - padding.bottom).max(0.0),
)
}
fn draw_surface_frame(
ctx: &mut PaintCtx,
bounds: Rect,
radius: f32,
border_width: f32,
background: Color,
border: Color,
focus_ring: Option<Color>,
focus_ring_width: f32,
focus_ring_outset: f32,
) {
let fill = Path::rounded_rect(bounds, radius);
ctx.fill(fill, background);
if border_width > 0.0 {
let width = physical_pixels(ctx, border_width);
let inset = width * 0.5;
ctx.stroke(
Path::rounded_rect(bounds.inflate(-inset, -inset), (radius - inset).max(0.0)),
border,
StrokeStyle::new(width),
);
}
if let Some(focus_ring) = focus_ring {
let outset = physical_pixels(ctx, focus_ring_outset);
ctx.stroke(
Path::rounded_rect(bounds.inflate(outset, outset), radius + outset),
focus_ring,
StrokeStyle::new(physical_pixels(ctx, focus_ring_width)),
);
}
}
fn physical_pixels(ctx: &PaintCtx, value: f32) -> f32 {
if value <= 0.0 {
return 0.0;
}
ctx.dpi().physical_pixels_to_logical(value)
}
fn scroll_delta_to_offset(delta: ScrollDelta) -> Vector {
match delta {
ScrollDelta::Lines(delta) => Vector::new(delta.x * 40.0, delta.y * 40.0),
ScrollDelta::Pixels(delta) => delta,
}
}
fn layout_content_size(layout: &PersistentTextLayout) -> Size {
let line_height = layout
.lines()
.iter()
.map(|line| line.rect.max_y())
.fold(0.0_f32, f32::max)
.max(layout.measurement().height);
Size::new(layout.measurement().width, line_height)
}
fn ranges_intersect(left: &Range<usize>, right: &Range<usize>) -> bool {
left.start < right.end && right.start < left.end
}
fn rebased_text_range(range: &Range<usize>, edit: &EditorTextEdit) -> Option<Range<usize>> {
let replacement_end = edit.range.start.saturating_add(edit.replacement_len);
let start = if range.start < edit.range.start {
range.start
} else if range.start >= edit.range.end {
replacement_end.saturating_add(range.start.saturating_sub(edit.range.end))
} else {
edit.range.start
};
let end = if range.end <= edit.range.start {
range.end
} else if range.end >= edit.range.end {
replacement_end.saturating_add(range.end.saturating_sub(edit.range.end))
} else {
replacement_end
};
(start < end).then_some(start..end)
}
#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
use super::*;
use crate::editable_text::keyboard_text;
use std::{cell::RefCell, rc::Rc};
use sui_core::{
Event, KeyboardEvent, Modifiers, PointerButtons, PointerEvent, PointerKind,
SemanticsAction, SemanticsValue, WindowId,
};
use sui_runtime::{
Application, RenderOutput, Runtime, SceneStatisticsDetailMode, WindowBuilder,
set_window_scene_statistics_detail_mode,
};
use sui_scene::{Brush, SceneCommand};
fn build_runtime<W>(root: W) -> (Runtime, WindowId)
where
W: Widget + 'static,
{
let runtime = Application::new()
.window(WindowBuilder::new().title("Editor").root(root))
.build()
.expect("runtime should build");
let window_id = runtime.window_ids()[0];
(runtime, window_id)
}
fn primary_pointer(kind: PointerEventKind, position: Point, pressed: bool) -> Event {
let mut buttons = PointerButtons::NONE;
if pressed {
buttons.insert(PointerButton::Primary);
}
Event::Pointer(PointerEvent {
pointer_id: 1,
kind,
position,
delta: Vector::ZERO,
scroll_delta: None,
button: Some(PointerButton::Primary),
buttons,
modifiers: Modifiers::NONE,
pointer_kind: PointerKind::Mouse,
is_primary: true,
})
}
fn key_event(key: &str) -> Event {
Event::Keyboard(KeyboardEvent::new(key, KeyState::Pressed))
}
fn command_key_event(key: &str) -> Event {
let mut event = KeyboardEvent::new(key, KeyState::Pressed);
event.modifiers.control = true;
Event::Keyboard(event)
}
#[test]
fn keyboard_text_falls_back_to_printable_key_when_text_payload_is_missing() {
let mut event = KeyboardEvent::new("h", KeyState::Pressed);
event.text = None;
assert_eq!(keyboard_text(&event), Some("h"));
event.modifiers.control = true;
assert_eq!(keyboard_text(&event), None);
}
fn text_input_node(output: &RenderOutput) -> &SemanticsNode {
output
.semantics
.iter()
.find(|node| node.role == SemanticsRole::TextInput)
.expect("text input semantics node should exist")
}
fn shaped_text_commands(output: &RenderOutput) -> Vec<sui_text::ShapedText> {
let mut found = Vec::new();
output
.frame
.scene
.visit_commands(&mut |command| match command {
SceneCommand::DrawShapedText(text) => found.push(text.clone()),
SceneCommand::DrawShapedTextWindow(text) => found.push(sui_text::ShapedText {
origin: text.origin,
layout_handle: text.layout_handle,
layout_version: text.layout_version,
bounds: text.bounds,
color_override: text.color_override,
}),
_ => {}
});
found
}
fn solid_fill_colors(output: &RenderOutput) -> Vec<Color> {
let mut colors = Vec::new();
output
.frame
.scene
.visit_commands(&mut |command| match command {
SceneCommand::FillRect {
brush: Brush::Solid(color),
..
}
| SceneCommand::FillPath {
brush: Brush::Solid(color),
..
} => colors.push(*color),
_ => {}
});
colors
}
fn solid_stroke_colors(output: &RenderOutput) -> Vec<Color> {
let mut colors = Vec::new();
output
.frame
.scene
.visit_commands(&mut |command| match command {
SceneCommand::StrokeRect {
brush: Brush::Solid(color),
..
}
| SceneCommand::StrokePath {
brush: Brush::Solid(color),
..
} => colors.push(*color),
_ => {}
});
colors
}
fn handle_ready_events(runtime: &mut Runtime) -> usize {
let ready = runtime.drain_ready_events();
let count = ready.len();
for (ready_window, event) in ready {
runtime
.handle_event(ready_window, event)
.expect("ready event should be handled");
}
count
}
fn assert_approx_eq(actual: f32, expected: f32) {
assert!(
(actual - expected).abs() <= 0.01,
"expected {actual} to be within 0.01 of {expected}"
);
}
#[test]
fn text_surface_hover_and_focus_use_theme_motion() {
let theme = DefaultTheme::default();
let hover_duration = theme.motion.hover_duration();
let focus_duration = theme.motion.focus_duration();
let expected_hover =
super::mix_color(theme.palette.control, theme.palette.control_hover, 1.0);
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(220.0, 96.0))
.with_child(
TextSurface::new("Editor")
.theme(theme)
.placeholder("Write notes"),
),
);
let _ = runtime.render(window_id).expect("render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Move, Point::new(16.0, 16.0), false),
)
.expect("hover event should be handled");
runtime.tick(hover_duration * 0.5);
assert_eq!(handle_ready_events(&mut runtime), 1);
let mid_hover = runtime.render(window_id).expect("render should succeed");
let mid_hover_background = solid_fill_colors(&mid_hover)[0];
assert_ne!(mid_hover_background, theme.palette.control);
assert_ne!(mid_hover_background, expected_hover);
runtime.tick(hover_duration);
assert_eq!(handle_ready_events(&mut runtime), 1);
let settled_hover = runtime.render(window_id).expect("render should succeed");
assert_eq!(solid_fill_colors(&settled_hover)[0], expected_hover);
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(16.0, 16.0), true),
)
.expect("focus event should be handled");
runtime.tick(hover_duration + focus_duration * 0.5);
assert_eq!(handle_ready_events(&mut runtime), 1);
let mid_focus = runtime.render(window_id).expect("render should succeed");
assert!(!solid_stroke_colors(&mid_focus).contains(&theme.palette.focus_ring));
runtime.tick(hover_duration + focus_duration);
assert_eq!(handle_ready_events(&mut runtime), 1);
let settled_focus = runtime.render(window_id).expect("render should succeed");
assert_eq!(
solid_fill_colors(&settled_focus)[0],
theme.palette.surface_focus
);
assert!(solid_stroke_colors(&settled_focus).contains(&theme.palette.focus_ring));
}
#[test]
fn text_surface_theme_when_and_text_style_when_read_current_theme() {
let theme = Rc::new(RefCell::new(DefaultTheme::default()));
let theme_reader = Rc::clone(&theme);
let style_reader = Rc::clone(&theme);
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(180.0, 72.0))
.with_child(
TextSurface::new("Editor")
.value("themed text")
.theme_when(move || *theme_reader.borrow())
.text_style_when(move |_| {
let theme = *style_reader.borrow();
theme.text_style(theme.palette.text)
}),
),
);
let light = runtime.render(window_id).expect("render should succeed");
assert_eq!(
solid_fill_colors(&light)[0],
DefaultTheme::default().palette.control
);
*theme.borrow_mut() = DefaultTheme::dark();
runtime
.handle_event(
window_id,
Event::Window(WindowEvent::Resized(Size::new(180.0, 72.0))),
)
.expect("resize should invalidate themed text surface");
let dark = runtime.render(window_id).expect("render should succeed");
assert_eq!(
solid_fill_colors(&dark)[0],
DefaultTheme::dark().palette.control
);
assert_ne!(light.frame.scene, dark.frame.scene);
}
#[test]
fn text_surface_submits_only_visible_line_windows() {
let long_text = (0..240)
.map(|index| format!("line {index:02}"))
.collect::<Vec<_>>()
.join("\n");
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(180.0, 96.0))
.with_child(TextSurface::new("Editor").value(long_text)),
);
set_window_scene_statistics_detail_mode(window_id, SceneStatisticsDetailMode::Detailed);
let output = runtime.render(window_id).expect("render should succeed");
let shaped = shaped_text_commands(&output);
let layout_misses = output.diagnostics.text_caches.runtime_layout.misses;
assert!(
shaped.len() < 24,
"expected visible-line submission only, emitted {} shaped lines",
shaped.len(),
);
assert!(
layout_misses < 80,
"expected viewport-aware measure, recorded {layout_misses} layout misses"
);
assert!(
shaped
.first()
.and_then(|text| text.resolve(output.frame.text_layout_registry.as_ref()))
.is_some_and(|layout| layout.text() == "line 00")
);
}
#[test]
fn text_surface_word_wrap_shapes_full_document_layout() {
let value = "alpha beta gamma delta epsilon zeta eta theta iota\nsecond wrapped line";
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(120.0, 120.0))
.with_child(TextSurface::new("Editor").wrap(TextWrap::Word).value(value)),
);
let output = runtime.render(window_id).expect("render should succeed");
let shaped = shaped_text_commands(&output);
assert_eq!(
shaped.len(),
1,
"wrapped text should be submitted as a document layout, not cached logical lines"
);
let layout = shaped[0]
.resolve(output.frame.text_layout_registry.as_ref())
.expect("wrapped text layout should resolve");
assert_eq!(layout.text(), value);
assert!(
layout.lines().len() > value.lines().count(),
"word wrapping should produce more visual lines than logical document lines"
);
}
#[test]
fn text_surface_scroll_updates_visible_window() {
let long_text = (0..32)
.map(|index| format!("line {index:02}"))
.collect::<Vec<_>>()
.join("\n");
let mut surface = TextSurface::new("Editor").value(long_text);
let bounds = Rect::new(0.0, 0.0, 180.0, 96.0);
let content = surface.content_rect(bounds);
let (line_texts, line_offsets, line_lengths) =
split_lines_with_offsets(surface.current_value());
let mut line_layouts = Vec::new();
for line in &line_texts {
line_layouts.push(
sui_text::TextSystem::new()
.shape_text_persistent(
None,
line.clone(),
Size::new(
surface.layout_box_size(content.width()).width,
surface.resolved_text_style().line_height,
),
surface.resolved_text_style(),
&sui_text::FontRegistry::new(),
)
.expect("text surface line layout should shape"),
);
}
surface.line_layouts = line_layouts.into_iter().map(Some).collect();
surface.line_offsets = line_offsets;
surface.line_lengths = line_lengths;
let before_window = surface.visible_line_range(content.height());
assert!(surface.scroll_by(bounds, Vector::new(0.0, 120.0)));
let after_window = surface.visible_line_range(content.height());
assert!(after_window.start >= before_window.start);
assert_ne!(after_window, before_window);
}
#[test]
fn text_surface_refreshes_shifted_offsets_without_discarding_plain_suffix_layouts() {
let mut surface = TextSurface::new("Editor").value("a\nb\nc");
let (line_texts, line_offsets, line_lengths) =
split_lines_with_offsets(surface.current_value());
let text_system = sui_text::TextSystem::new();
let font_registry = sui_text::FontRegistry::new();
let style = surface.resolved_text_style();
let retained = text_system
.shape_text_persistent(
None,
line_texts[1].clone(),
Size::new(180.0, style.line_height),
style,
&font_registry,
)
.expect("suffix line should shape");
let retained_handle = retained.handle();
surface.line_layouts = vec![None, Some(retained), None];
surface.line_offsets = line_offsets;
surface.line_lengths = line_lengths;
surface.editor.clear_document_dirty();
surface.editor.execute(EditorCommand::SetSelection {
anchor: 1,
focus: 1,
});
surface
.editor
.execute(EditorCommand::InsertText("XYZ".to_string()));
TextSurface::refresh_reusable_document_line_metadata(
surface.editor.document(),
&mut surface.line_layouts,
&mut surface.line_offsets,
&mut surface.line_lengths,
);
assert_eq!(surface.line_offsets, vec![0, 5, 7]);
assert_eq!(surface.line_lengths, vec![4, 1, 1]);
assert_eq!(
surface.line_layouts[1]
.as_ref()
.map(PersistentTextLayout::handle),
Some(retained_handle)
);
assert!(surface.line_layouts[0].is_none());
}
#[test]
fn shifted_style_ranges_preserve_unchanged_suffix_layouts_after_edit() {
let mut surface =
TextSurface::new("Editor")
.value("a\nb")
.style_spans(vec![TextSurfaceStyleSpan::new(
2..3,
TextStyle::new(Color::rgba(1.0, 0.0, 0.0, 1.0)),
)]);
let (line_texts, line_offsets, line_lengths) =
split_lines_with_offsets(surface.current_value());
let style = surface.resolved_text_style();
let retained = sui_text::TextSystem::new()
.shape_text_persistent(
None,
line_texts[1].clone(),
Size::new(180.0, style.line_height),
style,
&sui_text::FontRegistry::new(),
)
.expect("styled suffix line should shape");
surface.line_layouts = vec![None, Some(retained)];
surface.line_offsets = line_offsets;
surface.line_lengths = line_lengths;
surface.editor.clear_document_dirty();
surface.editor.execute(EditorCommand::SetSelection {
anchor: 1,
focus: 1,
});
surface
.editor
.execute(EditorCommand::InsertText("XYZ".to_string()));
let edit = surface
.editor
.take_text_edit()
.expect("text insertion should report its edited range");
surface.rebase_style_ranges_after_edit(&edit);
TextSurface::refresh_reusable_document_line_metadata(
surface.editor.document(),
&mut surface.line_layouts,
&mut surface.line_offsets,
&mut surface.line_lengths,
);
assert!(surface.line_layouts[1].is_some());
assert_eq!(surface.style_spans[0].range, 5..6);
}
#[test]
fn text_style_range_rebasing_respects_insertion_boundaries() {
let insertion = EditorTextEdit {
range: 3..3,
replacement_len: 2,
};
assert_eq!(rebased_text_range(&(1..3), &insertion), Some(1..3));
assert_eq!(rebased_text_range(&(3..5), &insertion), Some(5..7));
assert_eq!(rebased_text_range(&(2..5), &insertion), Some(2..7));
let deletion = EditorTextEdit {
range: 2..5,
replacement_len: 0,
};
assert_eq!(rebased_text_range(&(3..4), &deletion), None);
assert_eq!(rebased_text_range(&(5..7), &deletion), Some(2..4));
}
#[test]
fn text_surface_centers_shorter_line_layouts_in_global_line_slots() {
let mut base_style = TextStyle::new(Color::BLACK);
base_style.font_size = 14.0;
base_style.line_height = 18.0;
let mut tall_style = TextStyle::new(Color::BLACK);
tall_style.font_size = 28.0;
tall_style.line_height = 36.0;
let value = "tiny\nheader";
let tall_range = "tiny\n".len()..value.len();
let surface = TextSurface::new("Editor")
.text_style(base_style.clone())
.value(value)
.style_overlays(vec![TextSurfaceStyleOverlay::new(
tall_range.clone(),
tall_style,
TextSurfaceOverlayKind::Syntax,
)]);
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(260.0, 96.0))
.with_child(surface),
);
let output = runtime.render(window_id).expect("render should succeed");
let shaped = shaped_text_commands(&output);
let registry = output.frame.text_layout_registry.as_ref();
let first = shaped
.iter()
.find(|text| {
text.resolve(registry)
.is_some_and(|layout| layout.text() == "tiny")
})
.expect("first line should draw");
let second = shaped
.iter()
.find(|text| {
text.resolve(registry)
.is_some_and(|layout| layout.text() == "header")
})
.expect("second line should draw");
let first_layout = first
.resolve(registry)
.expect("first layout should resolve");
let second_layout = second
.resolve(registry)
.expect("second layout should resolve");
let first_height = first_layout
.measurement()
.height
.max(base_style.line_height);
let second_height = second_layout
.measurement()
.height
.max(base_style.line_height);
let slot_height = 36.0;
assert!(
first_height < slot_height,
"fixture should produce a shorter first line"
);
let first_offset = (slot_height - first_height).max(0.0) * 0.5;
let second_offset = (slot_height - second_height).max(0.0) * 0.5;
let first_row_top = second.origin.y - slot_height - second_offset;
assert_approx_eq(first.origin.y, first_row_top + first_offset);
let text_system = sui_text::TextSystem::new();
let mut geometry_surface = TextSurface::new("Editor")
.text_style(base_style.clone())
.value(value);
geometry_surface.line_layouts = vec![
Some(
text_system
.shape_text_persistent(
None,
"tiny",
Size::new(240.0, base_style.line_height),
base_style.clone(),
&sui_text::FontRegistry::new(),
)
.expect("first line should shape"),
),
Some(
text_system
.shape_text_persistent(
None,
"header",
Size::new(240.0, base_style.line_height),
TextStyle {
font_size: 28.0,
line_height: 36.0,
..base_style.clone()
},
&sui_text::FontRegistry::new(),
)
.expect("second line should shape"),
),
];
geometry_surface.line_offsets = vec![0, "tiny\n".len()];
geometry_surface.line_lengths = vec!["tiny".len(), "header".len()];
let first_geometry_layout = geometry_surface.line_layouts[0]
.as_ref()
.expect("first line layout should exist");
let local_caret = first_geometry_layout.caret_rect(0);
let local_selection = first_geometry_layout.selection_rects(0.."tiny".len());
let base_line_height = geometry_surface.resolved_text_style().line_height;
let slot_height = geometry_surface.line_height();
let first_origin_y =
geometry_surface.line_origin_y(0, first_geometry_layout, base_line_height, slot_height);
let caret = geometry_surface
.caret_rect_for_cursor(TextCursor::new(0))
.expect("caret should resolve");
let selection = geometry_surface.selection_rects_for_display(&TextSelection::new(
TextCursor::new(0),
TextCursor::new("tiny".len()),
));
assert_approx_eq(caret.y(), first_origin_y + local_caret.y());
assert_eq!(selection.len(), local_selection.len());
assert_approx_eq(selection[0].y(), first_origin_y + local_selection[0].y());
}
#[test]
fn text_surface_supports_editing_and_keeps_layout_handle_on_cursor_moves() {
let changes = Rc::new(RefCell::new(Vec::new()));
let on_change = Rc::clone(&changes);
let (mut runtime, window_id) = build_runtime(
TextSurface::new("Editor").on_change(move |value| on_change.borrow_mut().push(value)),
);
let _ = runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
)
.expect("focus click should succeed");
runtime
.handle_event(
window_id,
Event::Ime(ImeEvent::CompositionCommit {
text: "hello".to_string(),
}),
)
.expect("ime commit should succeed");
let after_insert = runtime
.render(window_id)
.expect("render after insert should succeed");
let inserted_line = shaped_text_commands(&after_insert)
.into_iter()
.next()
.expect("text surface should draw a shaped line after insert");
let inserted_handle = inserted_line.layout_handle;
let inserted_version = inserted_line.layout_version;
runtime
.handle_event(
window_id,
Event::Keyboard(KeyboardEvent::new("ArrowLeft", KeyState::Pressed)),
)
.expect("arrow key should succeed");
let after_move = runtime
.render(window_id)
.expect("render after cursor move should succeed");
let moved_line = shaped_text_commands(&after_move)
.into_iter()
.next()
.expect("text surface should draw a shaped line after cursor move");
assert_eq!(changes.borrow().last().map(String::as_str), Some("hello"));
assert_eq!(moved_line.layout_handle, inserted_handle);
assert_eq!(moved_line.layout_version, inserted_version);
assert!(after_move.ime_composition_rect.is_some());
assert_eq!(
after_move
.semantics
.iter()
.find(|node| node.role == SemanticsRole::TextInput)
.and_then(|node| node.value.clone()),
Some(SemanticsValue::Text("hello".to_string()))
);
}
#[test]
fn text_surface_selection_scope_tracks_keyboard_selection() {
let selection = SelectionScope::new();
let (mut runtime, window_id) = build_runtime(
TextSurface::new("Editor")
.value("alpha\nbeta")
.selectable(selection.clone()),
);
let _ = runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
)
.expect("focus click should succeed");
runtime
.handle_event(window_id, command_key_event("a"))
.expect("select all should succeed");
runtime.clipboard().set_text("app-owned");
runtime
.handle_event(window_id, command_key_event("c"))
.expect("copy shortcut should be routed to the app");
let output = runtime
.render(window_id)
.expect("render after selection should succeed");
let node = text_input_node(&output);
assert_eq!(selection.selected_text().as_deref(), Some("alpha\nbeta"));
assert_eq!(runtime.clipboard().text().as_deref(), Some("app-owned"));
assert!(!node.actions.contains(&SemanticsAction::Copy));
}
#[test]
fn text_surface_caret_uses_theme_palette_color() {
let mut theme = DefaultTheme::default();
theme.palette.caret = Color::rgba(0.02, 0.18, 0.72, 1.0);
let caret_color = theme.palette.caret;
let accent_text = theme.palette.accent_text;
let (mut runtime, window_id) = build_runtime(
TextSurface::new("Editor")
.theme(theme)
.value("Visible caret on white"),
);
runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
)
.expect("focus click should succeed");
let output = runtime
.render(window_id)
.expect("focused render should succeed");
let fill_colors = solid_fill_colors(&output);
assert!(fill_colors.contains(&caret_color));
assert!(!fill_colors.contains(&accent_text));
}
#[test]
fn text_surface_placeholder_uses_placeholder_style_without_editable_value() {
let mut theme = DefaultTheme::default();
theme.palette.placeholder = Color::rgba(0.42, 0.47, 0.55, 1.0);
let placeholder_color = theme.palette.placeholder;
let mut text_style = theme.body_text_style();
text_style.font_size = 28.0;
text_style.line_height = 12.0;
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(280.0, 96.0))
.with_child(
TextSurface::new("Editor")
.theme(theme)
.text_style(text_style.clone())
.placeholder("Write notes"),
),
);
let output = runtime.render(window_id).expect("render should succeed");
let registry = output.frame.text_layout_registry.as_ref();
let (placeholder_command, placeholder) = shaped_text_commands(&output)
.into_iter()
.find_map(|text| {
let layout = text.resolve(registry)?;
(layout.text() == "Write notes").then(|| (text, layout.clone()))
})
.expect("placeholder text should draw");
let node = text_input_node(&output);
assert_eq!(node.value, Some(SemanticsValue::Text(String::new())));
assert_eq!(placeholder_command.color_override, Some(placeholder_color));
assert_eq!(placeholder.style().font_size, text_style.font_size);
assert_eq!(placeholder.style().line_height, text_style.line_height);
assert!(placeholder.measurement().height > text_style.line_height);
}
#[test]
fn text_surface_read_only_uses_muted_text_and_blocks_mutation() {
let mut theme = DefaultTheme::default();
theme.palette.text_muted = Color::rgba(0.36, 0.40, 0.47, 1.0);
let muted = theme.palette.text_muted;
let caret = theme.palette.caret;
let mut text_style = theme.body_text_style();
text_style.font_size = 24.0;
text_style.line_height = 13.0;
let changes = Rc::new(RefCell::new(Vec::new()));
let on_change = Rc::clone(&changes);
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(280.0, 96.0))
.with_child(
TextSurface::new("Editor")
.theme(theme)
.text_style(text_style.clone())
.value("Pinned")
.read_only()
.on_change(move |value| on_change.borrow_mut().push(value)),
),
);
runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(32.0, 24.0), true),
)
.expect("focus click should succeed");
runtime
.handle_event(
window_id,
Event::Ime(ImeEvent::CompositionCommit {
text: " edited".to_string(),
}),
)
.expect("read-only ime commit should be ignored");
runtime
.handle_event(window_id, key_event("Backspace"))
.expect("read-only backspace should be ignored");
runtime
.handle_event(window_id, command_key_event("x"))
.expect("read-only cut should be ignored");
let output = runtime.render(window_id).expect("render should succeed");
let node = text_input_node(&output);
let editable = node
.editable_text
.as_ref()
.expect("editable text semantics should be present");
let registry = output.frame.text_layout_registry.as_ref();
let text = shaped_text_commands(&output)
.into_iter()
.find_map(|text| {
text.resolve(registry)
.filter(|layout| layout.text() == "Pinned")
.cloned()
})
.expect("read-only value should draw");
let fill_colors = solid_fill_colors(&output);
assert_eq!(node.value, Some(SemanticsValue::Text("Pinned".to_string())));
assert!(editable.readonly);
assert!(node.actions.contains(&SemanticsAction::Focus));
assert!(node.actions.contains(&SemanticsAction::SetSelection));
assert!(node.actions.contains(&SemanticsAction::Copy));
for action in [
SemanticsAction::SetValue,
SemanticsAction::InsertText,
SemanticsAction::DeleteBackward,
SemanticsAction::DeleteForward,
SemanticsAction::Cut,
SemanticsAction::Paste,
SemanticsAction::Undo,
SemanticsAction::Redo,
] {
assert!(
!node.actions.contains(&action),
"read-only surface should not expose {action:?}"
);
}
assert_eq!(text.style().color, muted);
assert_eq!(text.style().font_size, text_style.font_size);
assert_eq!(text.style().line_height, text_style.line_height);
assert!(changes.borrow().is_empty());
assert!(!fill_colors.contains(&caret));
}
#[test]
fn text_surface_shortcuts_use_editor_command_layer() {
let changes = Rc::new(RefCell::new(Vec::new()));
let on_change = Rc::clone(&changes);
let (mut runtime, window_id) = build_runtime(
TextSurface::new("Editor").on_change(move |value| on_change.borrow_mut().push(value)),
);
runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(24.0, 24.0), true),
)
.expect("focus click should succeed");
runtime
.handle_event(
window_id,
Event::Ime(ImeEvent::CompositionCommit {
text: "hello world".to_string(),
}),
)
.expect("initial edit should succeed");
runtime
.handle_event(window_id, command_key_event("a"))
.expect("select all should succeed");
runtime
.handle_event(window_id, command_key_event("x"))
.expect("cut should succeed");
runtime
.handle_event(window_id, command_key_event("v"))
.expect("paste should succeed");
runtime
.handle_event(window_id, command_key_event("z"))
.expect("undo should succeed");
runtime
.handle_event(window_id, command_key_event("y"))
.expect("redo should succeed");
let output = runtime.render(window_id).expect("render should succeed");
assert_eq!(
text_input_node(&output).value,
Some(SemanticsValue::Text("hello world".to_string()))
);
assert_eq!(
changes.borrow().last().map(String::as_str),
Some("hello world")
);
}
#[test]
fn text_surface_deletes_grapheme_clusters() {
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(320.0, 80.0))
.with_child(TextSurface::new("Editor").value("a🇯🇵e\u{301}z")),
);
runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(300.0, 24.0), true),
)
.expect("end click should succeed");
runtime
.handle_event(window_id, key_event("Backspace"))
.expect("delete z should succeed");
runtime
.handle_event(window_id, key_event("Backspace"))
.expect("delete combining grapheme should succeed");
runtime
.handle_event(window_id, key_event("Backspace"))
.expect("delete flag grapheme should succeed");
let output = runtime.render(window_id).expect("render should succeed");
assert_eq!(
text_input_node(&output).value,
Some(SemanticsValue::Text("a".to_string()))
);
}
#[test]
fn text_surface_ime_cursor_range_updates_editable_semantics() {
let (mut runtime, window_id) = build_runtime(
crate::SizedBox::new()
.size(Size::new(320.0, 80.0))
.with_child(TextSurface::new("Editor").value("hello ")),
);
runtime
.render(window_id)
.expect("initial render should succeed");
runtime
.handle_event(
window_id,
primary_pointer(PointerEventKind::Down, Point::new(300.0, 24.0), true),
)
.expect("end click should succeed");
runtime
.handle_event(window_id, Event::Ime(ImeEvent::CompositionStart))
.expect("composition start should succeed");
runtime
.handle_event(
window_id,
Event::Ime(ImeEvent::CompositionUpdate {
text: "世界".to_string(),
cursor_range: Some(0.."世".len()),
}),
)
.expect("composition update should succeed");
let output = runtime.render(window_id).expect("render should succeed");
let node = text_input_node(&output);
assert_eq!(
node.value,
Some(SemanticsValue::Text("hello 世界".to_string()))
);
let editable = node
.editable_text
.as_ref()
.expect("editable text semantics should be present");
assert_eq!(editable.caret_offset, "hello 世".len());
assert_eq!(
editable.selection,
SemanticsTextRange::new("hello 世".len(), "hello 世".len())
);
}
#[test]
fn text_surface_semantics_expose_editable_text_actions() {
let (mut runtime, window_id) = build_runtime(TextSurface::new("Editor").value("one\ntwo"));
let output = runtime.render(window_id).expect("render should succeed");
let node = text_input_node(&output);
let editable = node
.editable_text
.as_ref()
.expect("editable text semantics should be present");
assert!(editable.multiline);
assert!(!editable.readonly);
assert_eq!(editable.caret_offset, "one\ntwo".len());
assert_eq!(
editable.selection,
SemanticsTextRange::new("one\ntwo".len(), "one\ntwo".len())
);
for action in [
SemanticsAction::SetSelection,
SemanticsAction::InsertText,
SemanticsAction::DeleteBackward,
SemanticsAction::DeleteForward,
SemanticsAction::Copy,
SemanticsAction::Cut,
SemanticsAction::Paste,
SemanticsAction::Undo,
SemanticsAction::Redo,
] {
assert!(
node.actions.contains(&action),
"missing editable text action {action:?}"
);
}
}
#[test]
fn text_surface_style_overlays_do_not_mutate_source_text() {
let syntax_style = TextStyle::new(Color::BLACK);
let (mut runtime, window_id) = build_runtime(
TextSurface::new("Editor")
.value("let value = 1")
.style_overlays(vec![TextSurfaceStyleOverlay::new(
0..3,
syntax_style.clone(),
TextSurfaceOverlayKind::Syntax,
)]),
);
let output = runtime.render(window_id).expect("render should succeed");
let node = text_input_node(&output);
assert_eq!(
node.value,
Some(SemanticsValue::Text("let value = 1".to_string()))
);
let shaped = shaped_text_commands(&output);
let layout = shaped
.first()
.and_then(|text| text.resolve(output.frame.text_layout_registry.as_ref()))
.expect("styled text layout should resolve");
assert_eq!(layout.text(), "let value = 1");
assert!(
layout
.run_views()
.any(|run| run.style.color == syntax_style.color && run.run.byte_range == (0..3)),
"syntax overlay should style the keyword without changing the source text"
);
}
}
fn split_lines_with_offsets(text: &str) -> (Vec<String>, Vec<usize>, Vec<usize>) {
let mut lines = Vec::new();
let mut offsets = Vec::new();
let mut lengths = Vec::new();
let mut start = 0usize;
for segment in text.split('\n') {
offsets.push(start);
lengths.push(segment.len());
lines.push(segment.to_string());
start += segment.len() + 1;
}
if lines.is_empty() {
lines.push(String::new());
offsets.push(0);
lengths.push(0);
}
(lines, offsets, lengths)
}