use crate::color::TextStyle;
use crate::widget::TextMetrics;
pub const MAX_TEXT_LEN: usize = 16 * 1024 * 1024;
#[derive(Clone, Debug, Default)]
pub struct TextBuffer {
text: String,
cursor: usize,
anchor: usize,
}
impl TextBuffer {
pub fn new() -> Self {
Self::default()
}
pub fn from_text(text: impl Into<String>) -> Self {
let text = text.into();
let end = text.len();
Self {
text,
cursor: end,
anchor: end,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn len_bytes(&self) -> usize {
self.text.len()
}
pub fn len_chars(&self) -> usize {
self.text.chars().count()
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn anchor(&self) -> usize {
self.anchor
}
pub fn selection(&self) -> Option<(usize, usize)> {
if self.anchor == self.cursor {
None
} else if self.anchor < self.cursor {
Some((self.anchor, self.cursor))
} else {
Some((self.cursor, self.anchor))
}
}
pub fn has_selection(&self) -> bool {
self.anchor != self.cursor
}
pub fn selected_text(&self) -> Option<&str> {
self.selection().map(|(a, b)| &self.text[a..b])
}
fn snap(&self, byte: usize) -> usize {
let mut pos = byte.min(self.text.len());
while pos > 0 && !self.text.is_char_boundary(pos) {
pos -= 1;
}
pos
}
pub fn set_cursor(&mut self, byte: usize) -> bool {
let pos = self.snap(byte);
let moved = pos != self.cursor;
self.cursor = pos;
self.anchor = pos;
moved
}
pub fn set_selection(&mut self, anchor: usize, cursor: usize) {
self.anchor = self.snap(anchor);
self.cursor = self.snap(cursor);
}
pub fn select_all(&mut self) {
self.anchor = 0;
self.cursor = self.text.len();
}
pub fn clear_selection(&mut self) {
self.anchor = self.cursor;
}
fn prev_boundary(&self, pos: usize) -> usize {
if pos == 0 {
return 0;
}
let mut p = pos.min(self.text.len());
while p > 0 && !self.text.is_char_boundary(p) {
p -= 1;
}
if p == 0 {
return 0;
}
match self.text[..p].chars().next_back() {
Some(ch) => p - ch.len_utf8(),
None => 0,
}
}
fn next_boundary(&self, pos: usize) -> usize {
let p = self.snap(pos);
match self.text[p..].chars().next() {
Some(ch) => p + ch.len_utf8(),
None => self.text.len(),
}
}
pub fn move_left(&mut self, extend: bool) -> bool {
let target = self.prev_boundary(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_right(&mut self, extend: bool) -> bool {
let target = self.next_boundary(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_line_start(&mut self, extend: bool) -> bool {
let target = self.line_start(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn move_line_end(&mut self, extend: bool) -> bool {
let target = self.line_end(self.cursor);
if target == self.cursor {
return false;
}
self.cursor = target;
if !extend {
self.anchor = target;
}
true
}
pub fn delete_selection(&mut self) -> bool {
let Some((start, end)) = self.selection() else {
return false;
};
self.text.replace_range(start..end, "");
self.cursor = start;
self.anchor = start;
true
}
pub fn insert_str(&mut self, s: &str) {
if s.is_empty() {
return;
}
self.delete_selection();
let room = MAX_TEXT_LEN.saturating_sub(self.text.len());
let mut take = s.len().min(room);
while take > 0 && !s.is_char_boundary(take) {
take -= 1;
}
if take == 0 {
return;
}
self.text.insert_str(self.cursor, &s[..take]);
self.cursor += take;
self.anchor = self.cursor;
}
pub fn insert_char(&mut self, ch: char) {
let mut buf = [0u8; 4];
self.insert_str(ch.encode_utf8(&mut buf));
}
pub fn backspace(&mut self) -> bool {
if self.has_selection() {
return self.delete_selection();
}
if self.cursor == 0 {
return false;
}
let start = self.prev_boundary(self.cursor);
self.text.replace_range(start..self.cursor, "");
self.cursor = start;
self.anchor = start;
true
}
pub fn delete_forward(&mut self) -> bool {
if self.has_selection() {
return self.delete_selection();
}
if self.cursor >= self.text.len() {
return false;
}
let end = self.next_boundary(self.cursor);
self.text.replace_range(self.cursor..end, "");
self.anchor = self.cursor;
true
}
pub fn line_start(&self, offset: usize) -> usize {
let offset = self.snap(offset);
match self.text[..offset].rfind('\n') {
Some(idx) => idx + 1,
None => 0,
}
}
pub fn line_end(&self, offset: usize) -> usize {
let offset = self.snap(offset);
match self.text[offset..].find('\n') {
Some(idx) => offset + idx,
None => self.text.len(),
}
}
pub fn current_line(&self) -> (usize, usize) {
(self.line_start(self.cursor), self.line_end(self.cursor))
}
pub fn current_line_text(&self) -> &str {
let (start, end) = self.current_line();
&self.text[start..end]
}
pub fn char_width(ch: char, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
let mut buf = [0u8; 4];
let s = ch.encode_utf8(&mut buf);
metrics.measure_text(s, style).w
}
pub fn x_for_offset(&self, offset: usize, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
let start = self.line_start(offset);
let end = self.line_end(offset);
let offset = self.snap(offset).clamp(start, end);
let mut x = 0.0;
for ch in self.text[start..offset].chars() {
x += Self::char_width(ch, metrics, style);
}
x
}
pub fn cursor_x(&self, metrics: &dyn TextMetrics, style: &TextStyle) -> f32 {
self.x_for_offset(self.cursor, metrics, style)
}
pub fn offset_for_x(&self, x: f32, metrics: &dyn TextMetrics, style: &TextStyle) -> usize {
let (start, end) = self.current_line();
let mut best = start;
let mut best_dist = (x - 0.0).abs();
let mut pen = 0.0f32;
for (idx, ch) in self.text[start..end].char_indices() {
pen += Self::char_width(ch, metrics, style);
let boundary = start + idx + ch.len_utf8();
let dist = (x - pen).abs();
if dist < best_dist {
best = boundary;
best_dist = dist;
}
}
best
}
pub fn place_cursor_at_x(
&mut self,
x: f32,
metrics: &dyn TextMetrics,
style: &TextStyle,
) -> usize {
let offset = self.offset_for_x(x, metrics, style);
self.set_cursor(offset);
offset
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometry::Size;
struct Mono;
impl TextMetrics for Mono {
fn measure_text(&self, text: &str, _style: &TextStyle) -> Size {
let mut w = 0.0;
for ch in text.chars() {
w += if (ch as u32) >= 0x2E80 { 16.0 } else { 8.0 };
}
Size::new(w, 16.0)
}
fn line_height(&self, _style: &TextStyle) -> f32 {
16.0
}
fn scale(&self) -> f32 {
1.0
}
}
fn style() -> TextStyle {
TextStyle::default()
}
#[test]
fn insert_mixed_cjk_and_ascii() {
let mut buf = TextBuffer::new();
buf.insert_str("Hello");
buf.insert_char('中');
buf.insert_str(" Y901");
assert_eq!(buf.text(), "Hello中 Y901");
assert_eq!(buf.len_bytes(), 13);
assert_eq!(buf.cursor(), 13);
assert_eq!(buf.len_chars(), 11);
}
#[test]
fn insert_replaces_selection() {
let mut buf = TextBuffer::from_text("abcdef");
buf.set_selection(1, 4); assert_eq!(buf.selected_text(), Some("bcd"));
buf.insert_str("X");
assert_eq!(buf.text(), "aXef");
assert_eq!(buf.cursor(), 2);
assert!(!buf.has_selection());
}
#[test]
fn backspace_across_cjk_never_splits_utf8() {
let mut buf = TextBuffer::from_text("a中b");
assert_eq!(buf.cursor(), 5);
assert!(buf.backspace()); assert_eq!(buf.text(), "a中");
assert_eq!(buf.cursor(), 4);
assert!(buf.backspace()); assert_eq!(buf.text(), "a");
assert_eq!(buf.cursor(), 1);
assert!(buf.backspace()); assert_eq!(buf.text(), "");
assert_eq!(buf.cursor(), 0);
assert!(!buf.backspace(), "空缓冲区退格应返回 false");
assert!(buf.text().is_char_boundary(0));
}
#[test]
fn backspace_with_selection_deletes_selection() {
let mut buf = TextBuffer::from_text("你好世界");
buf.set_selection(3, 9); assert!(buf.backspace());
assert_eq!(buf.text(), "你界");
assert_eq!(buf.cursor(), 3);
}
#[test]
fn backspace_on_emoji_removes_whole_codepoint() {
let mut buf = TextBuffer::from_text("a😀");
assert_eq!(buf.len_bytes(), 5); buf.backspace();
assert_eq!(buf.text(), "a");
}
#[test]
fn delete_forward_removes_next_char() {
let mut buf = TextBuffer::from_text("中a");
buf.set_cursor(0);
assert!(buf.delete_forward());
assert_eq!(buf.text(), "a");
assert_eq!(buf.cursor(), 0);
}
#[test]
fn cursor_snaps_to_char_boundary() {
let mut buf = TextBuffer::from_text("中");
buf.set_cursor(1);
assert_eq!(buf.cursor(), 0);
buf.set_cursor(2);
assert_eq!(buf.cursor(), 0);
buf.set_cursor(3);
assert_eq!(buf.cursor(), 3);
buf.set_cursor(999);
assert_eq!(buf.cursor(), 3);
}
#[test]
fn move_left_right_by_char() {
let mut buf = TextBuffer::from_text("a中b");
buf.set_cursor(0);
assert!(buf.move_right(false));
assert_eq!(buf.cursor(), 1); assert!(buf.move_right(false));
assert_eq!(buf.cursor(), 4); assert!(buf.move_left(false));
assert_eq!(buf.cursor(), 1); assert!(!buf.move_left(false) || buf.cursor() == 0);
}
#[test]
fn shift_move_extends_selection() {
let mut buf = TextBuffer::from_text("abc");
buf.set_cursor(0);
buf.move_right(true);
buf.move_right(true);
assert_eq!(buf.selection(), Some((0, 2)));
assert_eq!(buf.selected_text(), Some("ab"));
buf.move_left(true);
assert_eq!(buf.selection(), Some((0, 1)));
}
#[test]
fn x_for_offset_counts_cjk_as_two_cells() {
let buf = TextBuffer::from_text("a中b");
let s = style();
assert_eq!(buf.x_for_offset(0, &Mono, &s), 0.0);
assert_eq!(buf.x_for_offset(1, &Mono, &s), 8.0);
assert_eq!(buf.x_for_offset(4, &Mono, &s), 24.0);
assert_eq!(buf.x_for_offset(5, &Mono, &s), 32.0);
}
#[test]
fn offset_for_x_picks_nearest_boundary() {
let mut buf = TextBuffer::from_text("a中b");
buf.set_cursor(0);
let s = style();
assert_eq!(buf.offset_for_x(-5.0, &Mono, &s), 0);
assert_eq!(buf.offset_for_x(3.0, &Mono, &s), 0); assert_eq!(buf.offset_for_x(9.0, &Mono, &s), 1); assert_eq!(buf.offset_for_x(15.0, &Mono, &s), 1); assert_eq!(buf.offset_for_x(17.0, &Mono, &s), 4); assert_eq!(buf.offset_for_x(30.0, &Mono, &s), 5); assert_eq!(buf.offset_for_x(999.0, &Mono, &s), 5); }
#[test]
fn offset_roundtrip_through_x() {
let text = "Hello 你好 Y901";
let buf = TextBuffer::from_text(text);
let s = style();
for (byte, _ch) in text.char_indices() {
let x = buf.x_for_offset(byte, &Mono, &s);
let back = buf.offset_for_x(x, &Mono, &s);
assert_eq!(back, byte, "byte {byte} 经 X 往返后变成 {back}");
}
let end = text.len();
let x = buf.x_for_offset(end, &Mono, &s);
assert_eq!(buf.offset_for_x(x, &Mono, &s), end);
}
#[test]
fn click_places_cursor() {
let mut buf = TextBuffer::from_text("ab中");
buf.place_cursor_at_x(20.0, &Mono, &style());
assert_eq!(buf.cursor(), 2); assert!(!buf.has_selection());
}
#[test]
fn line_bounds_and_measure_are_per_line() {
let mut buf = TextBuffer::from_text("abc\ndefg");
assert_eq!(buf.line_start(0), 0);
assert_eq!(buf.line_end(0), 3);
buf.set_cursor(6); assert_eq!(buf.current_line(), (4, 8));
assert_eq!(buf.current_line_text(), "defg");
let s = style();
assert_eq!(buf.x_for_offset(4, &Mono, &s), 0.0);
assert_eq!(buf.x_for_offset(6, &Mono, &s), 16.0);
assert_eq!(buf.offset_for_x(17.0, &Mono, &s), 6);
}
#[test]
fn empty_buffer_measurements_are_zero() {
let buf = TextBuffer::new();
let s = style();
assert_eq!(buf.x_for_offset(0, &Mono, &s), 0.0);
assert_eq!(buf.offset_for_x(100.0, &Mono, &s), 0);
assert_eq!(buf.current_line(), (0, 0));
}
}