From b3ef977127a5f7be46931c303402991806d1f269 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 06:27:20 +0000 Subject: [PATCH 1/2] epaint, egui: move the cursor on screen in bidi text, with affinity Left and Right move the cursor one grapheme cluster on screen, as in Chromium, Safari, Firefox, GTK and Cocoa; Ctrl/Alt+Left/Right move one word on screen. Past the end of a row the cursor goes on in the reading order of its paragraph. Shift+arrows still select a logical range. Where the direction changes, `CCursor::prefer_next_row` now also picks which run's edge the cursor is drawn at: a click sticks the cursor to the char that was clicked, a move to the char it moved past, and typing to the inserted text. Home and End go to the start and end of the row in reading order, so to the right and left ends in a right-to-left paragraph; Cmd+Left/Right go to the left and right ends. The cursor on an empty right-to-left row is on the right, and a selected newline is drawn at the end of its row in reading order. Password fields mask each grapheme cluster with one bullet, padded with combining grapheme joiners, so the cursor never lands inside a cluster of the real text. --- .../egui/src/text_selection/cursor_range.rs | 124 ++- crates/egui/src/text_selection/visuals.rs | 72 +- crates/egui/src/widgets/text_edit/builder.rs | 50 +- crates/epaint/src/text/caret.rs | 816 ++++++++++++++++++ crates/epaint/src/text/cursor.rs | 13 +- crates/epaint/src/text/mod.rs | 1 + crates/epaint/src/text/text_layout_types.rs | 79 +- 7 files changed, 1088 insertions(+), 67 deletions(-) create mode 100644 crates/epaint/src/text/caret.rs diff --git a/crates/egui/src/text_selection/cursor_range.rs b/crates/egui/src/text_selection/cursor_range.rs index 4d76207e..cd23e185 100644 --- a/crates/egui/src/text_selection/cursor_range.rs +++ b/crates/egui/src/text_selection/cursor_range.rs @@ -2,7 +2,7 @@ use epaint::{Galley, text::CharIndex, text::cursor::CCursor}; use crate::{Event, Id, Key, Modifiers, os::OperatingSystem}; -use super::text_cursor_state::{ccursor_next_word, ccursor_previous_word, slice_char_range}; +use super::text_cursor_state::slice_char_range; /// A selected text range (could be a range of length zero). /// @@ -103,6 +103,25 @@ impl CCursorRange { } } + /// The two ends, the one on the left on screen first. + /// + /// On one row that is the one further left; across rows, the one that comes first + /// in a left-to-right paragraph and last in a right-to-left one. + fn sorted_on_screen(&self, galley: &Galley) -> [CCursor; 2] { + let [min, max] = self.sorted_cursors(); + let min_row = galley.layout_from_cursor(min).row; + let max_row = galley.layout_from_cursor(max).row; + let swap = if min_row == max_row { + galley.pos_from_cursor(max).min.x < galley.pos_from_cursor(min).min.x + } else { + galley + .rows + .get(galley.layout_from_cursor(self.primary).row) + .is_some_and(|row| row.rtl_paragraph) + }; + if swap { [max, min] } else { [min, max] } + } + pub fn slice_str<'s>(&self, text: &'s str) -> &'s str { let [min, max] = self.sorted_cursors(); slice_char_range(text, min.index..max.index) @@ -125,11 +144,8 @@ impl CCursorRange { } Key::ArrowLeft | Key::ArrowRight if modifiers.is_none() && !self.is_empty() => { - if key == Key::ArrowLeft { - *self = Self::one(self.sorted_cursors()[0]); - } else { - *self = Self::one(self.sorted_cursors()[1]); - } + let [left, right] = self.sorted_on_screen(galley); + *self = Self::one(if key == Key::ArrowLeft { left } else { right }); true } @@ -274,30 +290,32 @@ fn move_single_cursor( Key::E => (galley.cursor_end_of_row(cursor), None), Key::P => galley.cursor_up_one_row(cursor, *h_pos), Key::N => galley.cursor_down_one_row(cursor, *h_pos), + // Backward and forward in logical order, as in Cocoa's `moveBackward:` and `moveForward:`: Key::B => (galley.cursor_left_one_character(cursor), None), Key::F => (galley.cursor_right_one_character(cursor), None), _ => return, } } else { match key { + // Left and right move on screen, also in right-to-left text: Key::ArrowLeft => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows - (ccursor_previous_word(galley, *cursor), None) + (galley.cursor_word_left_visually(cursor), None) } else if modifiers.mac_cmd { - (galley.cursor_begin_of_row(cursor), None) + (galley.cursor_left_end_of_row(cursor), None) } else { - (galley.cursor_left_one_character(cursor), None) + (galley.cursor_left_visually(cursor), None) } } Key::ArrowRight => { if modifiers.alt || modifiers.ctrl { // alt on mac, ctrl on windows - (ccursor_next_word(galley, *cursor), None) + (galley.cursor_word_right_visually(cursor), None) } else if modifiers.mac_cmd { - (galley.cursor_end_of_row(cursor), None) + (galley.cursor_right_end_of_row(cursor), None) } else { - (galley.cursor_right_one_character(cursor), None) + (galley.cursor_right_visually(cursor), None) } } Key::ArrowUp => { @@ -341,3 +359,85 @@ fn move_single_cursor( *cursor = new_cursor; *h_pos = new_h_pos; } + +#[cfg(test)] +mod tests { + use alloc::sync::Arc; + + use epaint::{ + Color32, FontId, + text::{FontDefinitions, Fonts, TextOptions}, + }; + + use super::*; + + fn galley(text: &str) -> Arc { + let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); + fonts.with_pixels_per_point(1.0).layout_no_wrap( + text.to_owned(), + FontId::proportional(14.0), + Color32::WHITE, + ) + } + + fn press(range: &mut CCursorRange, galley: &Galley, modifiers: Modifiers, key: Key) { + assert!(range.on_key_press(OperatingSystem::Windows, galley, &modifiers, key)); + } + + /// Shift+arrows move the cursor on screen, but select a logical range. + #[test] + fn shift_arrows_select_a_logical_range() { + let galley = galley("abc אבג def"); + let mut range = CCursorRange::one(galley.begin()); + for _ in 0..5 { + press(&mut range, &galley, Modifiers::SHIFT, Key::ArrowRight); + } + // Past "abc " and the left end of the Hebrew word, "ג": + assert_eq!(range.as_sorted_char_range(), CharIndex(0)..CharIndex(6)); + press(&mut range, &galley, Modifiers::SHIFT, Key::ArrowRight); + assert_eq!(range.as_sorted_char_range(), CharIndex(0)..CharIndex(5)); + + press(&mut range, &galley, Modifiers::CTRL, Key::ArrowRight); + assert_eq!(range.single().map(|c| c.index), Some(CharIndex(4))); + } + + /// Left and Right put the cursor at the end of the selection on that side of the screen. + #[test] + fn arrows_collapse_a_selection_to_its_end_on_screen() { + let galley = galley("abc אבג def"); + // The Hebrew word, from the right of "א" to the left of "ג": + let before_alef = CCursor { + prefer_next_row: true, + ..CCursor::new(4) + }; + let after_gimel = CCursor::new(7); + let hebrew = CCursorRange::two(before_alef, after_gimel); + assert_eq!(hebrew.as_sorted_char_range(), CharIndex(4)..CharIndex(7)); + + let mut range = hebrew; + press(&mut range, &galley, Modifiers::NONE, Key::ArrowLeft); + assert_eq!(range.single().map(|c| c.index), Some(CharIndex(7))); + let mut range = hebrew; + press(&mut range, &galley, Modifiers::NONE, Key::ArrowRight); + assert_eq!(range.single().map(|c| c.index), Some(CharIndex(4))); + } + + #[test] + fn home_and_end_in_a_rtl_paragraph() { + // On screen: "abc גבא", which starts on the right. + let galley = galley("אבג abc"); + let mut range = CCursorRange::one(CCursor::new(5)); + press(&mut range, &galley, Modifiers::NONE, Key::Home); + assert_eq!(range.primary.index, CharIndex(0)); + press(&mut range, &galley, Modifiers::NONE, Key::End); + assert_eq!(range.primary.index, CharIndex(4)); + press(&mut range, &galley, Modifiers::NONE, Key::ArrowRight); + assert_eq!(range.primary.index, CharIndex(5)); + + // Ctrl+F on a Mac moves forward in logical order: + let mut range = CCursorRange::one(CCursor::new(2)); + let modifiers = Modifiers::CTRL; + assert!(range.on_key_press(OperatingSystem::Mac, &galley, &modifiers, Key::F)); + assert_eq!(range.primary.index, CharIndex(3)); + } +} diff --git a/crates/egui/src/text_selection/visuals.rs b/crates/egui/src/text_selection/visuals.rs index 6b3886d3..ccf29201 100644 --- a/crates/egui/src/text_selection/visuals.rs +++ b/crates/egui/src/text_selection/visuals.rs @@ -45,6 +45,15 @@ pub fn paint_text_selection( let max = galley.layout_from_cursor(max); for ri in min.row..=max.row { + // Where the cursor goes on this row if it is empty, row-relative: + let empty_row_x = galley + .pos_from_layout_cursor(&LayoutCursor { + row: ri, + column: CharIndex::ZERO, + }) + .min + .x + - galley.rows[ri].pos.x; let placed_row = &mut galley.rows[ri]; let row = Arc::make_mut(&mut placed_row.row); @@ -62,12 +71,27 @@ pub fn paint_text_selection( } else { 0.0 }; - if row.glyphs.iter().any(|glyph| glyph.is_rtl()) { - if 0.0 < newline_size { - ranges.push(Rangef::new(row.size.x, row.size.x + newline_size)); + // The newline is at the end of the row in reading order: + if row.rtl_paragraph { + let left = row + .glyphs + .iter() + .map(|g| g.pos.x) + .reduce(f32::min) + .unwrap_or(empty_row_x); + match ranges.first_mut() { + Some(range) if range.min <= left => range.min = left - newline_size, + _ if 0.0 < newline_size => { + ranges.insert(0, Rangef::new(left - newline_size, left)); + } + _ => {} } - } else if let Some(range) = ranges.last_mut() { - range.max = row.size.x + newline_size; + } else if !row.glyphs.iter().any(|glyph| glyph.is_rtl()) { + if let Some(range) = ranges.last_mut() { + range.max = row.size.x + newline_size; + } + } else if 0.0 < newline_size { + ranges.push(Rangef::new(row.size.x, row.size.x + newline_size)); } ranges }; @@ -373,4 +397,42 @@ mod tests { 1 ); } + + /// A selected newline is drawn at the end of its row in reading order. + #[test] + fn selected_newline_follows_the_paragraph_direction() { + let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); + for (text, rtl) in [("אבג\nדהו", true), ("abc אבג\ndef", false)] { + let mut galley = fonts.with_pixels_per_point(1.0).layout_no_wrap( + text.to_owned(), + FontId::proportional(14.0), + Color32::WHITE, + ); + let end = galley.end(); + let mut rects = vec![]; + let range = CCursorRange::two(CCursor::new(0), end); + paint_text_selection(&mut galley, &Visuals::dark(), &range, Some(&mut rects)); + + let row = &galley.rows[0]; + let selected_x = rects + .iter() + .filter(|rect| rect.row == 0) + .flat_map(|rect| rect.vertex_indices) + .map(|i| row.visuals.mesh.vertices[i as usize].pos.x); + let (min, max) = selected_x.fold((f32::INFINITY, f32::NEG_INFINITY), |(a, b), x| { + (a.min(x), b.max(x)) + }); + let glyphs_min = row + .glyphs + .iter() + .map(|g| g.pos.x) + .fold(f32::INFINITY, f32::min); + let glyphs_max = row.glyphs.iter().map(|g| g.max_x()).fold(0.0, f32::max); + if rtl { + assert!(min < glyphs_min && max <= glyphs_max, "{text:?}"); + } else { + assert!(glyphs_min <= min && glyphs_max < max, "{text:?}"); + } + } + } } diff --git a/crates/egui/src/widgets/text_edit/builder.rs b/crates/egui/src/widgets/text_edit/builder.rs index 44236a69..66fd7ca3 100644 --- a/crates/egui/src/widgets/text_edit/builder.rs +++ b/crates/egui/src/widgets/text_edit/builder.rs @@ -1154,12 +1154,18 @@ impl<'t> TextEdit<'t> { } fn mask_if_password(is_password: bool, text: &str) -> String { + /// One bullet per grapheme cluster, so the cursor moves over the masked text + /// as over the real text. The rest of each cluster is invisible combining grapheme joiners, + /// which keeps every char index the same as in the real text. fn mask_password(text: &str) -> String { - core::iter::repeat_n( - epaint::text::PASSWORD_REPLACEMENT_CHAR, - text.chars().count(), - ) - .collect::() + use unicode_segmentation::UnicodeSegmentation as _; + const JOINER: char = '\u{34F}'; + let mut masked = String::with_capacity(text.len()); + for cluster in text.graphemes(true) { + masked.push(epaint::text::PASSWORD_REPLACEMENT_CHAR); + masked.extend(cluster.chars().skip(1).map(|_| JOINER)); + } + masked } if is_password { @@ -1540,7 +1546,12 @@ fn insert_replacing_selection( let single_line = text_to_insert.replace(['\r', '\n'], " "); text.insert_text_at(&mut ccursor, &single_line, char_limit); } - ccursor + // Stick to the inserted text, so that where the direction changes the cursor stays + // where the next char typed in that direction goes. + CCursor { + prefer_next_row: false, + ..ccursor + } } /// The text of the last [`accesskit::Action::SetValue`] request for this widget, if any. @@ -1632,3 +1643,30 @@ fn check_for_mutating_key_press( _ => None, } } + +#[cfg(test)] +mod tests { + use epaint::text::{CharIndex, grapheme}; + + use super::mask_if_password; + + /// The masked text must have the same chars and grapheme clusters as the real one, + /// or the cursor ends up inside a cluster of the buffer. + #[test] + fn password_mask_keeps_char_indices_and_clusters() { + for text in ["e\u{301}a", "ن\u{64E}ص", "👩\u{200D}🚀x", "abc", ""] { + let masked = mask_if_password(true, text); + let count = text.chars().count(); + assert_eq!(masked.chars().count(), count, "{text:?}"); + for i in 0..=count { + let i = CharIndex(i); + assert_eq!( + grapheme::next_boundary(&masked, i), + grapheme::next_boundary(text, i), + "{text:?} at {i:?}" + ); + } + } + assert_eq!(mask_if_password(true, "e\u{301}a").matches('•').count(), 2); + } +} diff --git a/crates/epaint/src/text/caret.rs b/crates/epaint/src/text/caret.rs new file mode 100644 index 00000000..2bfc540d --- /dev/null +++ b/crates/epaint/src/text/caret.rs @@ -0,0 +1,816 @@ +//! Placing and moving the text cursor on screen, in text of mixed direction. +//! +//! Left and Right move the cursor on screen, one grapheme cluster or one word at a time, +//! as in Chromium, Safari, Firefox, GTK and the Cocoa text system (Qt alone moves in logical +//! order by default). A selection stays a logical range of chars, and may be drawn in pieces. +//! +//! Where the bidi level changes, one char offset has two places on screen: the edge of the +//! run before it and the edge of the run after it. [`CCursor::prefer_next_row`] picks one, +//! the same way it picks the end of a row or the start of the next one at a row wrap: +//! `true` (downstream) means the char after the cursor, `false` (upstream) the char before it. +//! +//! On a row, the cursor stops once at each boundary between two clusters on screen, +//! and at both ends of the row. A cursor that moves past a cluster sticks to it, +//! so moving back returns it to the same place. + +use unicode_segmentation::UnicodeSegmentation as _; + +use emath::Align; + +use super::{CharIndex, Galley, Row, cursor::CCursor, grapheme}; + +/// A grapheme cluster of a [`Row`], with its row-relative char range. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Cluster { + start: usize, + end: usize, + rtl: bool, +} + +/// A cursor in a row: a row-relative column, and whether it sticks to the cluster +/// after it (downstream) or before it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct RowCaret { + column: usize, + downstream: bool, +} + +impl Cluster { + /// The cursor on the left edge of this cluster, sticking to it. + fn left_caret(self) -> RowCaret { + if self.rtl { + RowCaret { + column: self.end, + downstream: false, + } + } else { + RowCaret { + column: self.start, + downstream: true, + } + } + } + + /// The cursor on the right edge of this cluster, sticking to it. + fn right_caret(self) -> RowCaret { + if self.rtl { + RowCaret { + column: self.start, + downstream: true, + } + } else { + RowCaret { + column: self.end, + downstream: false, + } + } + } +} + +/// The cursor stop that `caret` is at, in `clusters` (from left to right): +/// stop `k` is left of cluster `k`, and stop `clusters.len()` is the right end of the row. +fn stop_of(clusters: &[Cluster], caret: RowCaret) -> usize { + let column = caret.column; + let after = clusters + .iter() + .position(|c| c.start == column) + .map(|i| (i, true)); + let before = clusters + .iter() + .position(|c| c.end == column) + .map(|i| (i, false)); + let inside = || { + clusters + .iter() + .position(|c| c.start < column && column < c.end) + .map(|i| (i, true)) + }; + let attached = if caret.downstream { + after.or(before) + } else { + before.or(after) + }; + let Some((i, at_start)) = attached.or_else(inside) else { + return 0; + }; + // The logical start of a right-to-left cluster is its right edge. + i + usize::from(at_start == clusters[i].rtl) +} + +/// The cursor at stop `stop`, sticking to the cluster on its left if `stick_left` and there is one, +/// otherwise to the one on its right. +fn caret_at_stop(clusters: &[Cluster], stop: usize, stick_left: bool) -> RowCaret { + let from_left = stop + .checked_sub(1) + .and_then(|i| clusters.get(i)) + .map(|c| c.right_caret()); + let from_right = clusters.get(stop).map(|c| c.left_caret()); + let caret = if stick_left { + from_left.or(from_right) + } else { + from_right.or(from_left) + }; + caret.unwrap_or(RowCaret { + column: 0, + downstream: true, + }) +} + +impl Row { + /// The grapheme clusters of this row, from left to right. + fn visual_clusters(&self) -> Vec { + let text = self.text(); + let mut cluster_of = vec![0; self.glyphs.len()]; + let mut ranges = Vec::new(); + let mut start = 0; + for cluster in text.graphemes(true) { + let end = start + cluster.chars().count(); + cluster_of[start..end].fill(ranges.len()); + ranges.push(start..end); + start = end; + } + + let mut seen = vec![false; ranges.len()]; + let mut clusters = Vec::with_capacity(ranges.len()); + for glyph in self.visual_order() { + let i = cluster_of[glyph]; + if !seen[i] { + seen[i] = true; + let range = &ranges[i]; + clusters.push(Cluster { + start: range.start, + end: range.end, + rtl: self.glyphs[range.start].is_rtl(), + }); + } + } + clusters + } + + /// Like [`Self::x_offset`], for a cursor that sticks to the char after it (`downstream`) + /// or the char before it. + /// + /// Where the bidi level changes at `column`, those two chars can be apart on screen, + /// and the cursor goes on the edge of the one it sticks to. + pub fn x_offset_with_affinity(&self, column: CharIndex, downstream: bool) -> f32 { + let c = column.0; + if !downstream + && 0 < c + && c < self.glyphs.len() + && self.glyphs[c - 1].bidi_level != self.glyphs[c].bidi_level + { + let before = &self.glyphs[grapheme::previous_boundary(&self.text(), column).0]; + return if before.is_rtl() { + before.pos.x + } else { + before.max_x() + }; + } + self.x_offset(column) + } + + /// The column at `desired_x` (row-relative), as [`Self::char_at`], + /// and whether the cursor sticks to the char after it: the cluster that was hit. + pub(crate) fn caret_at(&self, desired_x: f32) -> (CharIndex, bool) { + let column = self.char_at(desired_x); + let c = column.0; + if c == 0 || self.glyphs.len() <= c { + return (column, c == 0); + } + if self.glyphs[c - 1].bidi_level == self.glyphs[c].bidi_level { + return (column, true); + } + // Stick to whichever neighbor of `column` is nearer to `desired_x`. + let distance = |glyph: &super::Glyph| { + (glyph.pos.x - desired_x) + .max(desired_x - glyph.max_x()) + .max(0.0) + }; + let before = &self.glyphs[grapheme::previous_boundary(&self.text(), column).0]; + (column, distance(&self.glyphs[c]) <= distance(before)) + } +} + +/// Word segments (UAX #29) of the text of a galley, for word motion. +struct Words { + chars: Vec, + + /// For each char: the index of its segment. + segment: Vec, + + /// For each segment: is it all word chars (letters, digits, `_`)? + is_word: Vec, +} + +impl Words { + fn new(galley: &Galley) -> Self { + let mut text = String::new(); + for row in &galley.rows { + text.extend(row.glyphs.iter().map(|g| g.chr)); + if row.ends_with_newline { + text.push('\n'); + } + } + let mut segment = Vec::with_capacity(text.len()); + let mut is_word = Vec::new(); + for word in text.split_word_bounds() { + let id = is_word.len() as u32; + segment.extend(word.chars().map(|_| id)); + is_word.push(word.chars().all(|c| c.is_alphanumeric() || c == '_')); + } + Self { + chars: text.chars().collect(), + segment, + is_word, + } + } + + /// Does word motion stop before the char at `inside`, coming from `across` + /// (`None`: from a paragraph break)? + /// + /// It stops before each segment that is not a word, so it skips spaces and then a word, + /// and before each `.`, as on macOS for `www.example.com`. + fn stops_before(&self, inside: usize, across: Option) -> bool { + let Some(&segment) = self.segment.get(inside) else { + return true; + }; + !self.is_word[segment as usize] + && (self.chars[inside] == '.' + || across.is_none_or(|across| self.segment.get(across) != Some(&segment))) + } +} + +/// ## Cursor movement on screen +impl Galley { + fn row_start(&self, row: usize) -> usize { + self.rows[..row] + .iter() + .map(|row| row.char_count_including_newline().0) + .sum() + } + + fn row_caret(&self, cursor: &CCursor) -> (usize, RowCaret) { + let layout = self.layout_from_cursor(*cursor); + let row = layout.row.min(self.rows.len() - 1); + let caret = RowCaret { + column: layout.column.0.min(self.rows[row].glyphs.len()), + downstream: cursor.prefer_next_row, + }; + (row, caret) + } + + fn cursor_from_row_caret(&self, row: usize, caret: RowCaret) -> CCursor { + CCursor { + index: CharIndex(self.row_start(row) + caret.column), + prefer_next_row: caret.downstream, + } + } + + /// Does `row` wrap onto the next row, rather than end its paragraph? + fn wraps(&self, row: usize) -> bool { + !self.rows[row].ends_with_newline && row + 1 < self.rows.len() + } + + /// The cursor at the start (in reading order) of `row`, or at its end. + fn row_edge(&self, row: usize, start: bool) -> RowCaret { + let clusters = self.rows[row].visual_clusters(); + let at_left = start != self.rows[row].rtl_paragraph; + let stop = if at_left { 0 } else { clusters.len() }; + caret_at_stop(&clusters, stop, !at_left) + } + + /// The x coordinate, in galley coordinates, of a cursor at `column` of `row`. + pub(crate) fn caret_x(&self, row: usize, column: CharIndex, downstream: bool) -> f32 { + let placed_row = &self.rows[row]; + if placed_row.glyphs.is_empty() + && placed_row.rtl_paragraph + && self.job.halign == Align::Min + && self.job.halign_min_is_start + { + // An empty right-to-left row starts where the other right-to-left rows do: + return self + .rows + .iter() + .map(|row| row.pos.x + row.size.x) + .fold(0.0, f32::max); + } + placed_row.pos.x + placed_row.x_offset_with_affinity(column, downstream) + } + + /// The cursor one grapheme cluster to the left on screen. + /// + /// Past the left end of a row it goes on to the previous row in a left-to-right paragraph, + /// and to the next one in a right-to-left paragraph. + pub fn cursor_left_visually(&self, cursor: &CCursor) -> CCursor { + self.cursor_one_cluster(cursor, false) + } + + /// The cursor one grapheme cluster to the right on screen. + /// + /// Past the right end of a row it goes on to the next row in a left-to-right paragraph, + /// and to the previous one in a right-to-left paragraph. + pub fn cursor_right_visually(&self, cursor: &CCursor) -> CCursor { + self.cursor_one_cluster(cursor, true) + } + + fn cursor_one_cluster(&self, cursor: &CCursor, rightward: bool) -> CCursor { + if self.rows.is_empty() { + return *cursor; + } + let (row, caret) = self.row_caret(cursor); + let clusters = self.rows[row].visual_clusters(); + let stop = stop_of(&clusters, caret); + let forward = rightward != self.rows[row].rtl_paragraph; + + let target = if rightward { + (stop < clusters.len()).then_some(stop + 1) + } else { + stop.checked_sub(1) + }; + if let Some(target) = target { + let caret = caret_at_stop(&clusters, target, rightward); + let end_of_row = if self.rows[row].rtl_paragraph { + 0 + } else { + clusters.len() + }; + if target == end_of_row + && caret.column == self.rows[row].glyphs.len() + && self.wraps(row) + { + // The end of a wrapped row is the start of the next row; show it there. + return CCursor { + index: CharIndex(self.row_start(row) + caret.column), + prefer_next_row: true, + }; + } + return self.cursor_from_row_caret(row, caret); + } + + let next_row = if forward { + Some(row + 1).filter(|&r| r < self.rows.len()) + } else { + row.checked_sub(1) + }; + let Some(next_row) = next_row else { + return *cursor; + }; + let entry = self.cursor_from_row_caret(next_row, self.row_edge(next_row, forward)); + if entry.index == cursor.index { + // Across a row wrap the end of one row is the start of the next; don't stop twice. + self.cursor_one_cluster(&entry, rightward) + } else { + entry + } + } + + /// The cursor one word to the left on screen: to the start of the word + /// on its left, in reading order of that word. + /// + /// It snaps to grapheme clusters and goes on to other rows like [`Self::cursor_left_visually`]. + pub fn cursor_word_left_visually(&self, cursor: &CCursor) -> CCursor { + self.cursor_one_word(cursor, false) + } + + /// The cursor one word to the right on screen. See [`Self::cursor_word_left_visually`]. + pub fn cursor_word_right_visually(&self, cursor: &CCursor) -> CCursor { + self.cursor_one_word(cursor, true) + } + + fn cursor_one_word(&self, cursor: &CCursor, rightward: bool) -> CCursor { + if self.rows.is_empty() { + return *cursor; + } + let words = Words::new(self); + let (mut row, caret) = self.row_caret(cursor); + let mut clusters = self.rows[row].visual_clusters(); + let mut stop = stop_of(&clusters, caret); + + // Each pass moves on to another row in one direction, or returns. + for _ in 0..=self.rows.len() { + let row_start = self.row_start(row); + let placed_row = &self.rows[row]; + let forward = rightward != placed_row.rtl_paragraph; + let edge = if rightward { clusters.len() } else { 0 }; + let at = |stop: usize| { + self.cursor_from_row_caret(row, caret_at_stop(&clusters, stop, rightward)) + }; + + let mut k = stop; + while k != edge { + k = if rightward { k + 1 } else { k - 1 }; + if k == edge { + break; + } + let (inside, across) = if rightward { + (clusters[k], clusters[k - 1]) + } else { + (clusters[k - 1], clusters[k]) + }; + if words.stops_before(row_start + inside.start, Some(row_start + across.start)) { + return at(k); + } + } + + // The edge of the row: a paragraph break, the end of the text, or a row wrap. + let soft = if forward { + self.wraps(row) + } else { + row > 0 && self.wraps(row - 1) + }; + if stop != edge { + if !soft { + return at(edge); + } + let boundary = if forward { + row_start + placed_row.char_count_including_newline().0 + } else { + row_start + }; + let edge_cluster = if rightward { + clusters.last() + } else { + clusters.first() + }; + let (inside, across) = if forward { + (boundary, edge_cluster.map(|c| row_start + c.start)) + } else { + (boundary - 1, edge_cluster.map(|c| row_start + c.start)) + }; + if words.stops_before(inside, across) { + let cursor = at(edge); + // The end of a wrapped row is the start of the next row; show it there. + let prefer_next_row = + cursor.prefer_next_row || (forward && cursor.index.0 == boundary); + return CCursor { + prefer_next_row, + ..cursor + }; + } + } + + let next_row = if forward { + Some(row + 1).filter(|&r| r < self.rows.len()) + } else { + row.checked_sub(1) + }; + let Some(next_row) = next_row else { + return at(edge); + }; + row = next_row; + clusters = self.rows[row].visual_clusters(); + let at_left = forward != self.rows[row].rtl_paragraph; + stop = if at_left { 0 } else { clusters.len() }; + if soft { + continue; + } + + // Past a paragraph break: + let entry = self.cursor_from_row_caret(row, self.row_edge(row, forward)); + if at_left != rightward { + // A paragraph of the other direction, entered at the far side. + return entry; + } + let inside = if rightward { + clusters.first() + } else { + clusters.last() + }; + match inside { + Some(inside) if !words.stops_before(self.row_start(row) + inside.start, None) => {} + _ => return entry, + } + } + *cursor + } + + /// The cursor at the left end of its row on screen. + pub fn cursor_left_end_of_row(&self, cursor: &CCursor) -> CCursor { + self.cursor_row_end_on_screen(cursor, false) + } + + /// The cursor at the right end of its row on screen. + pub fn cursor_right_end_of_row(&self, cursor: &CCursor) -> CCursor { + self.cursor_row_end_on_screen(cursor, true) + } + + fn cursor_row_end_on_screen(&self, cursor: &CCursor, right: bool) -> CCursor { + if self.rows.is_empty() { + return *cursor; + } + let (row, _) = self.row_caret(cursor); + let start = right == self.rows[row].rtl_paragraph; + self.cursor_from_row_caret(row, self.row_edge(row, start)) + } + + /// The cursor at the start of its row in reading order: the left end in a + /// left-to-right paragraph, the right end in a right-to-left one. + pub fn cursor_begin_of_row(&self, cursor: &CCursor) -> CCursor { + if self.rows.is_empty() { + return *cursor; + } + let (row, _) = self.row_caret(cursor); + self.cursor_from_row_caret(row, self.row_edge(row, true)) + } + + /// The cursor at the end of its row in reading order: the right end in a + /// left-to-right paragraph, the left end in a right-to-left one. + pub fn cursor_end_of_row(&self, cursor: &CCursor) -> CCursor { + if self.rows.is_empty() { + return *cursor; + } + let (row, _) = self.row_caret(cursor); + self.cursor_from_row_caret(row, self.row_edge(row, false)) + } +} + +#[cfg(test)] +mod tests { + use alloc::sync::Arc; + + use emath::vec2; + + use super::*; + use crate::{ + Color32, FontId, + text::{FontDefinitions, Fonts, LayoutJob, TextDirection, TextOptions}, + }; + + fn layout(text: &str, direction: TextDirection, wrap_width: f32) -> Arc { + let mut fonts = Fonts::new(TextOptions::default(), FontDefinitions::default()); + let mut job = LayoutJob::simple( + text.to_owned(), + FontId::proportional(14.0), + Color32::WHITE, + wrap_width, + ); + job.direction = direction; + fonts.with_pixels_per_point(1.0).layout_job(job) + } + + fn auto(text: &str) -> Arc { + layout(text, TextDirection::Auto, f32::INFINITY) + } + + fn x(galley: &Galley, cursor: CCursor) -> f32 { + galley.pos_from_cursor(cursor).min.x + } + + /// The cursors from pressing a key until the cursor stops moving. + fn presses(galley: &Galley, from: CCursor, step: impl Fn(&CCursor) -> CCursor) -> Vec { + let mut cursors = vec![from]; + loop { + let next = step(cursors.last().unwrap()); + let last = cursors.last().unwrap(); + if next.index == last.index && x(galley, next) == x(galley, *last) { + return cursors; + } + assert!(cursors.len() < 100, "no end in sight: {cursors:?}"); + cursors.push(next); + } + } + + fn indices(cursors: &[CCursor]) -> Vec { + cursors.iter().map(|c| c.index.0).collect() + } + + /// Each press moves the cursor further in the same direction on screen. + fn assert_moves_on_screen(galley: &Galley, cursors: &[CCursor], rightward: bool) { + for pair in cursors.windows(2) { + let (a, b) = (x(galley, pair[0]), x(galley, pair[1])); + assert!( + if rightward { a < b } else { b < a }, + "{:?}: {:?} at {a} to {:?} at {b}", + galley.text(), + pair[0], + pair[1] + ); + } + } + + /// Visits every place on the row once, from one end to the other, both ways. + fn assert_arrow_sequences(galley: &Galley, rightward: &[usize], leftward: &[usize]) { + let row = &galley.rows[0]; + let left_end = galley.cursor_left_end_of_row(&galley.begin()); + let right_end = galley.cursor_right_end_of_row(&galley.begin()); + let left = row + .glyphs + .iter() + .map(|g| g.pos.x) + .fold(f32::INFINITY, f32::min); + assert_eq!(x(galley, left_end), row.pos.x + left); + + let cursors = presses(galley, left_end, |c| galley.cursor_right_visually(c)); + assert_eq!(indices(&cursors), rightward, "{:?}", galley.text()); + assert_moves_on_screen(galley, &cursors, true); + assert_eq!(x(galley, *cursors.last().unwrap()), x(galley, right_end)); + + let cursors = presses(galley, right_end, |c| galley.cursor_left_visually(c)); + assert_eq!(indices(&cursors), leftward, "{:?}", galley.text()); + assert_moves_on_screen(galley, &cursors, false); + assert_eq!(x(galley, *cursors.last().unwrap()), x(galley, left_end)); + } + + #[test] + fn arrows_move_on_screen_in_mixed_text() { + // On screen: "abc גבא def" + assert_arrow_sequences( + &auto("abc אבג def"), + &[0, 1, 2, 3, 4, 6, 5, 4, 8, 9, 10, 11], + &[11, 10, 9, 8, 7, 5, 6, 7, 3, 2, 1, 0], + ); + // A right-to-left paragraph, on screen: "abc גבא" + assert_arrow_sequences( + &auto("אבג abc"), + &[4, 5, 6, 7, 3, 2, 1, 0], + &[0, 1, 2, 3, 4, 6, 5, 4], + ); + // Digits are left-to-right within Arabic, on screen: "رانيد 123 نمث" + assert_arrow_sequences( + &auto("ثمن 123 دينار"), + &[13, 12, 11, 10, 9, 8, 7, 5, 6, 7, 3, 2, 1, 0], + &[0, 1, 2, 3, 4, 6, 5, 4, 8, 9, 10, 11, 12, 13], + ); + // Three levels: digits (2) in Hebrew (1) in English (0), on screen: "abc והד 123 גבא def" + assert_arrow_sequences( + &auto("abc אבג 123 דהו def"), + &[ + 0, 1, 2, 3, 4, 14, 13, 12, 11, 9, 10, 11, 7, 6, 5, 4, 16, 17, 18, 19, + ], + &[ + 19, 18, 17, 16, 15, 5, 6, 7, 8, 10, 9, 8, 12, 13, 14, 15, 3, 2, 1, 0, + ], + ); + } + + /// One char offset, two places: the cursor sticks to the run it moved past. + #[test] + fn affinity_picks_the_run() { + let galley = auto("abc אבג def"); + let row = &galley.rows[0]; + let [space, alef, gimel, space2] = [3, 4, 6, 7].map(|i| row.glyphs[i]); + + let upstream = |i| CCursor::new(i); + let downstream = |i| CCursor { + prefer_next_row: true, + ..CCursor::new(i) + }; + // After "abc ", or before the alef at the right end of the Hebrew word: + assert_eq!(x(&galley, upstream(4)), space.max_x()); + assert_eq!(x(&galley, downstream(4)), alef.max_x()); + // After the gimel at its left end, or before the second space: + assert_eq!(x(&galley, upstream(7)), gimel.pos.x); + assert_eq!(x(&galley, downstream(7)), space2.pos.x); + } + + /// A click sticks the cursor to the char that was clicked. + #[test] + fn clicks_pick_the_affinity() { + let galley = auto("abc אבג def"); + let row = &galley.rows[0]; + let y = row.size.y / 2.0; + let click = |i: usize, fraction: f32| { + let rect = row.glyphs[i].logical_rect(); + galley.cursor_from_pos(vec2(rect.lerp_inside([fraction, 0.5]).x, y)) + }; + let near = |cursor: CCursor, edge: f32| (x(&galley, cursor) - edge).abs() < 0.01; + + let alef = row.glyphs[4]; + let cursor = click(4, 0.75); + assert_eq!((cursor.index.0, cursor.prefer_next_row), (4, true)); + assert!(near(cursor, alef.max_x())); + + let space = row.glyphs[3]; + let cursor = click(3, 0.75); + assert_eq!((cursor.index.0, cursor.prefer_next_row), (4, false)); + assert!(near(cursor, space.max_x())); + + let gimel = row.glyphs[6]; + let cursor = click(6, 0.25); + assert_eq!((cursor.index.0, cursor.prefer_next_row), (7, false)); + assert!(near(cursor, gimel.pos.x)); + + let space2 = row.glyphs[7]; + let cursor = click(7, 0.25); + assert_eq!((cursor.index.0, cursor.prefer_next_row), (7, true)); + assert!(near(cursor, space2.pos.x)); + } + + /// Wrapped left-to-right text: the end of a row and the start of the next are one stop. + #[test] + fn arrows_cross_a_row_wrap_once() { + let unwrapped = auto("abc def"); + let width = unwrapped.rows[0].glyphs[4].pos.x + 1.0; + let galley = layout("abc def", TextDirection::Auto, width); + assert_eq!(galley.rows.len(), 2); + + let rightward = presses(&galley, galley.begin(), |c| galley.cursor_right_visually(c)); + assert_eq!(indices(&rightward), [0, 1, 2, 3, 4, 5, 6, 7]); + assert_eq!(galley.layout_from_cursor(rightward[4]).row, 1); + + let leftward = presses(&galley, galley.end(), |c| galley.cursor_left_visually(c)); + assert_eq!(indices(&leftward), [7, 6, 5, 4, 3, 2, 1, 0]); + assert_eq!(galley.layout_from_cursor(leftward[3]).row, 1); + } + + /// Past the end of a row, the cursor goes on in the reading order of the paragraph. + #[test] + fn arrows_cross_rows_in_reading_order() { + let galley = layout("אב\nגד", TextDirection::RightToLeft, f32::INFINITY); + let leftward = presses(&galley, galley.begin(), |c| galley.cursor_left_visually(c)); + assert_eq!(indices(&leftward), [0, 1, 2, 3, 4, 5]); + let rightward = presses(&galley, galley.end(), |c| galley.cursor_right_visually(c)); + assert_eq!(indices(&rightward), [5, 4, 3, 2, 1, 0]); + } + + #[test] + fn home_and_end_go_to_the_start_and_end_in_reading_order() { + let ends = |galley: &Galley, from: usize| { + let from = CCursor::new(from); + let home = galley.cursor_begin_of_row(&from); + let end = galley.cursor_end_of_row(&from); + let row = &galley.rows[0]; + // Which end of the row on screen, to the nearest point: + let side = |cursor| ((x(galley, cursor) - row.pos.x) / row.size.x).round(); + ((home.index.0, side(home)), (end.index.0, side(end))) + }; + + let (left, right) = (0.0, 1.0); + let galley = auto("abc אבג def"); + assert_eq!(ends(&galley, 5), ((0, left), (11, right))); + + // The ends of the row on screen, not in logical order: + let galley = auto("אבג abc"); + assert_eq!(ends(&galley, 5), ((0, right), (4, left))); + let left_end = galley.cursor_left_end_of_row(&CCursor::new(1)); + let right_end = galley.cursor_right_end_of_row(&CCursor::new(5)); + assert_eq!((left_end.index.0, right_end.index.0), (4, 0)); + + let galley = auto("abc אבג"); + assert_eq!(ends(&galley, 1), ((0, left), (4, right))); + } + + /// An empty row of a right-to-left paragraph starts on the right, like the others. + #[test] + fn cursor_on_an_empty_rtl_row_is_on_the_right() { + let galley = layout("אבג\n", TextDirection::RightToLeft, f32::INFINITY); + let right = galley.rows[0].pos.x + galley.rows[0].size.x; + assert_eq!(x(&galley, galley.end()), right); + assert_eq!(x(&galley, CCursor::new(4)), right); + + let galley = layout("abc\n", TextDirection::LeftToRight, f32::INFINITY); + assert_eq!(x(&galley, galley.end()), 0.0); + } + + #[test] + fn word_motion_moves_on_screen() { + let words = |galley: &Galley, from: CCursor, rightward: bool| { + let step = |c: &CCursor| { + if rightward { + galley.cursor_word_right_visually(c) + } else { + galley.cursor_word_left_visually(c) + } + }; + let cursors = presses(galley, from, step); + assert_moves_on_screen(galley, &cursors, rightward); + indices(&cursors) + }; + + // On screen: "abc גבא def". Rightward to the right end of each word, leftward to the left end: + let galley = auto("abc אבג def"); + assert_eq!(words(&galley, galley.begin(), true), [0, 3, 4, 11]); + assert_eq!(words(&galley, galley.end(), false), [11, 8, 7, 0]); + + // A right-to-left paragraph, on screen: "והד גבא" + let galley = auto("אבג דהו"); + assert_eq!(words(&galley, galley.begin(), false), [0, 3, 7]); + assert_eq!(words(&galley, galley.end(), true), [7, 4, 0]); + + // Across paragraphs, as in logical order: + let galley = auto("abc def\nghi"); + let rightward = presses(&galley, galley.begin(), |c| { + galley.cursor_word_right_visually(c) + }); + assert_eq!(indices(&rightward), [0, 3, 7, 11]); + let leftward = presses(&galley, galley.end(), |c| { + galley.cursor_word_left_visually(c) + }); + assert_eq!(indices(&leftward), [11, 8, 4, 0]); + + // A dot is a stop: + let galley = auto("www.example.com"); + assert_eq!(words(&galley, galley.begin(), true), [0, 3, 11, 15]); + } + + /// A combining mark moves with its base. + #[test] + fn arrows_skip_whole_clusters() { + let galley = auto("אָב"); + let cursors = presses(&galley, galley.begin(), |c| galley.cursor_left_visually(c)); + assert_eq!(indices(&cursors), [0, 2, 3]); + let galley = auto("a\u{301}b"); + let cursors = presses(&galley, galley.begin(), |c| galley.cursor_right_visually(c)); + assert_eq!(indices(&cursors), [0, 2, 3]); + } +} diff --git a/crates/epaint/src/text/cursor.rs b/crates/epaint/src/text/cursor.rs index d54bf1d4..deeffd18 100644 --- a/crates/epaint/src/text/cursor.rs +++ b/crates/epaint/src/text/cursor.rs @@ -11,10 +11,15 @@ pub struct CCursor { /// Character offset (NOT byte offset!). pub index: CharIndex, - /// If this cursors sits right at the border of a wrapped row break (NOT paragraph break) - /// do we prefer the next row? - /// This is *almost* always what you want, *except* for when - /// explicitly clicking the end of a row or pressing the end key. + /// Does the cursor stick to the char after it (downstream), rather than the one before it? + /// + /// This decides where a cursor is drawn when those two chars are apart on screen: + /// * At a wrapped row break (NOT paragraph break): the start of the next row, + /// or the end of this one. The next row is *almost* always what you want, *except* + /// for when explicitly clicking the end of a row or pressing the end key. + /// * Where the text direction changes: the edge of the run after the cursor, + /// or of the run before it. A click sticks the cursor to the char that was clicked, + /// and moving the cursor sticks it to the char it moved past. pub prefer_next_row: bool, } diff --git a/crates/epaint/src/text/mod.rs b/crates/epaint/src/text/mod.rs index 9bfa3872..ae802931 100644 --- a/crates/epaint/src/text/mod.rs +++ b/crates/epaint/src/text/mod.rs @@ -1,5 +1,6 @@ //! Everything related to text, fonts, text layout, cursors etc. +mod caret; pub mod cursor; mod face_store; mod family; diff --git a/crates/epaint/src/text/text_layout_types.rs b/crates/epaint/src/text/text_layout_types.rs index 9cb0eb38..2a907429 100644 --- a/crates/epaint/src/text/text_layout_types.rs +++ b/crates/epaint/src/text/text_layout_types.rs @@ -1372,13 +1372,25 @@ impl Galley { return self.end_pos(); }; - let x = row.x_offset(layout_cursor.column) + row.pos.x; + let x = self.caret_x(layout_cursor.row, layout_cursor.column, true); Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y())) } /// Returns a 0-width Rect. + /// + /// Where the text direction changes, the cursor is drawn at the edge of the char it sticks to, + /// see [`CCursor::prefer_next_row`]. pub fn pos_from_cursor(&self, cursor: CCursor) -> Rect { - self.pos_from_layout_cursor(&self.layout_from_cursor(cursor)) + let layout_cursor = self.layout_from_cursor(cursor); + let Some(row) = self.rows.get(layout_cursor.row) else { + return self.end_pos(); + }; + let x = self.caret_x( + layout_cursor.row, + layout_cursor.column, + cursor.prefer_next_row, + ); + Rect::from_min_max(pos2(x, row.min_y()), pos2(x, row.max_y())) } /// Cursor at the given position within the galley. @@ -1417,8 +1429,7 @@ impl Galley { if is_pos_within_row || y_dist < best_y_dist { best_y_dist = y_dist; // char_at is `Row` not `PlacedRow` relative which means we have to subtract the pos. - let column = row.char_at(pos.x - row.pos.x); - let prefer_next_row = column < row.char_count_excluding_newline(); + let (column, prefer_next_row) = row.caret_at(pos.x - row.pos.x); cursor = CCursor { index: ccursor_index + column, prefer_next_row, @@ -1560,22 +1571,24 @@ impl Galley { h_pos: Option, ) -> (CCursor, Option) { let layout_cursor = self.layout_from_cursor(*cursor); - let h_pos = h_pos.unwrap_or_else(|| self.pos_from_layout_cursor(&layout_cursor).center().x); + let h_pos = h_pos.unwrap_or_else(|| self.pos_from_cursor(*cursor).center().x); if layout_cursor.row == 0 { (CCursor::default(), None) } else { let new_row = layout_cursor.row - 1; - let new_layout_cursor = { - // keep same X coord - // char_at is Row-relative, so subtract the row's position - let column = self.rows[new_row].char_at(h_pos - self.rows[new_row].pos.x); - LayoutCursor { - row: new_row, - column, - } + // Keep the same x coordinate. `caret_at` is row-relative. + let (column, downstream) = + self.rows[new_row].caret_at(h_pos - self.rows[new_row].pos.x); + let new_cursor = self.cursor_from_layout(LayoutCursor { + row: new_row, + column, + }); + let new_cursor = CCursor { + prefer_next_row: downstream, + ..new_cursor }; - (self.cursor_from_layout(new_layout_cursor), Some(h_pos)) + (new_cursor, Some(h_pos)) } } @@ -1585,42 +1598,28 @@ impl Galley { h_pos: Option, ) -> (CCursor, Option) { let layout_cursor = self.layout_from_cursor(*cursor); - let h_pos = h_pos.unwrap_or_else(|| self.pos_from_layout_cursor(&layout_cursor).center().x); + let h_pos = h_pos.unwrap_or_else(|| self.pos_from_cursor(*cursor).center().x); if layout_cursor.row + 1 < self.rows.len() { let new_row = layout_cursor.row + 1; - let new_layout_cursor = { - // keep same X coord - // char_at is Row-relative, so subtract the row's position - let column = self.rows[new_row].char_at(h_pos - self.rows[new_row].pos.x); - LayoutCursor { - row: new_row, - column, - } + // Keep the same x coordinate. `caret_at` is row-relative. + let (column, downstream) = + self.rows[new_row].caret_at(h_pos - self.rows[new_row].pos.x); + let new_cursor = self.cursor_from_layout(LayoutCursor { + row: new_row, + column, + }); + let new_cursor = CCursor { + prefer_next_row: downstream, + ..new_cursor }; - (self.cursor_from_layout(new_layout_cursor), Some(h_pos)) + (new_cursor, Some(h_pos)) } else { (self.end(), None) } } - pub fn cursor_begin_of_row(&self, cursor: &CCursor) -> CCursor { - let layout_cursor = self.layout_from_cursor(*cursor); - self.cursor_from_layout(LayoutCursor { - row: layout_cursor.row, - column: CharIndex::ZERO, - }) - } - - pub fn cursor_end_of_row(&self, cursor: &CCursor) -> CCursor { - let layout_cursor = self.layout_from_cursor(*cursor); - self.cursor_from_layout(LayoutCursor { - row: layout_cursor.row, - column: self.rows[layout_cursor.row].char_count_excluding_newline(), - }) - } - pub fn cursor_begin_of_paragraph(&self, cursor: &CCursor) -> CCursor { let mut layout_cursor = self.layout_from_cursor(*cursor); layout_cursor.column = CharIndex::ZERO; From bed6dfe3f3e5df576a64e9ed1c6c08ac34d5e4c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 21 Oct 2026 06:36:48 +0000 Subject: [PATCH 2/2] epaint: a paragraph without a strong character takes the direction before it With `TextDirection::Auto`, an empty line or a line of digits takes the direction of the paragraph before it, as in most editors, so a new line in right-to-left text starts on the right. The first paragraph of the text falls back to left-to-right. The paragraph cache passes that direction to the job of each such paragraph. --- crates/epaint/src/text/galley_cache.rs | 25 +++++- crates/epaint/src/text/text_layout.rs | 92 ++++++++++++++++++--- crates/epaint/src/text/text_layout_types.rs | 4 +- 3 files changed, 108 insertions(+), 13 deletions(-) diff --git a/crates/epaint/src/text/galley_cache.rs b/crates/epaint/src/text/galley_cache.rs index 8742b5b3..acbc8569 100644 --- a/crates/epaint/src/text/galley_cache.rs +++ b/crates/epaint/src/text/galley_cache.rs @@ -4,7 +4,9 @@ use emath::OrderedFloat; use nohash_hasher::IntMap; use crate::text::{ - ByteIndex, Galley, LayoutJob, LayoutSection, fonts::FontsImpl, text_layout::layout, + ByteIndex, Galley, LayoutJob, LayoutSection, TextDirection, + fonts::FontsImpl, + text_layout::{is_neutral, layout}, }; /// A laid-out [`Galley`], and what we need to know to evict it. @@ -149,6 +151,8 @@ impl GalleyCache { let mut max_rows_remaining = job.wrap.max_rows; let mut child_galleys = Vec::new(); let mut child_hashes = Vec::new(); + // Is the last paragraph with a strong character right-to-left? + let mut previous_rtl = job.direction == TextDirection::RightToLeft; while start < job.text.len() { let is_first_paragraph = start == 0; @@ -161,6 +165,23 @@ impl GalleyCache { end += 1; // If the text ends with a newline, we include it in the last paragraph. } + // With `Auto`, a paragraph without a strong character takes the direction of the + // one before it, which its own job can't see: + let mut direction = job.direction; + if direction == TextDirection::Auto { + let paragraph = &job.text[start..end]; + if paragraph.is_ascii() && !previous_rtl { + // Left-to-right either way. + } else if is_neutral(paragraph) { + if previous_rtl { + direction = TextDirection::RightToLeft; + } + } else { + previous_rtl = + unicode_bidi::get_base_direction(paragraph) == unicode_bidi::Direction::Rtl; + } + } + let mut paragraph_job = LayoutJob { text: job.text[start..end].to_owned(), wrap: crate::text::TextWrapping { @@ -169,7 +190,7 @@ impl GalleyCache { }, sections: Vec::new(), break_on_newline: job.break_on_newline, - direction: job.direction, + direction, halign: job.halign, halign_min_is_start: job.halign_min_is_start, justify: job.justify, diff --git a/crates/epaint/src/text/text_layout.rs b/crates/epaint/src/text/text_layout.rs index e94c1e26..7bae63f6 100644 --- a/crates/epaint/src/text/text_layout.rs +++ b/crates/epaint/src/text/text_layout.rs @@ -1856,6 +1856,11 @@ struct BidiLevels { /// The byte ranges of the right-to-left paragraphs, in order. rtl_paragraphs: Vec>, + /// Is the last paragraph right-to-left? The empty paragraph after a final `\n` follows it. + last_rtl: bool, + + text_len: usize, + direction: TextDirection, } @@ -1864,6 +1869,8 @@ impl BidiLevels { let mut bidi = Self { levels: None, rtl_paragraphs: Vec::new(), + last_rtl: direction == TextDirection::RightToLeft, + text_len: text.len(), direction, }; let paragraph_level = match direction { @@ -1873,27 +1880,47 @@ impl BidiLevels { TextDirection::RightToLeft => Some(unicode_bidi::Level::rtl()), }; let info = unicode_bidi::BidiInfo::new(text, paragraph_level); - bidi.rtl_paragraphs = info - .paragraphs - .iter() - .filter(|paragraph| paragraph.level.is_rtl()) - .map(|paragraph| paragraph.range.clone()) - .collect(); + let mut levels: Vec = info.levels.iter().map(|level| level.number()).collect(); + for paragraph in &info.paragraphs { + let range = paragraph.range.clone(); + let mut rtl = paragraph.level.is_rtl(); + if direction == TextDirection::Auto && is_neutral(&text[range.clone()]) { + // No strong character: take the direction of the paragraph before, + // so that a new line in right-to-left text starts on the right. + rtl = bidi.last_rtl; + if rtl { + let paragraph_info = unicode_bidi::BidiInfo::new( + &text[range.clone()], + Some(unicode_bidi::Level::rtl()), + ); + for (level, resolved) in + levels[range.clone()].iter_mut().zip(¶graph_info.levels) + { + *level = resolved.number(); + } + } + } + if rtl { + bidi.rtl_paragraphs.push(range); + } + bidi.last_rtl = rtl; + } // A right-to-left paragraph needs its levels even when they are all even, // e.g. for trailing whitespace (rule L1). if info.has_rtl() || !bidi.rtl_paragraphs.is_empty() { - bidi.levels = Some(info.levels.iter().map(|level| level.number()).collect()); + bidi.levels = Some(levels); } bidi } /// Is the paragraph that contains the byte at `byte_offset` right-to-left? /// - /// With [`TextDirection::Auto`], the empty paragraph after a final `\n` is left-to-right. + /// The empty paragraph after a final `\n` has the direction of the one before it. fn is_rtl_paragraph(&self, byte_offset: usize) -> bool { match self.direction { TextDirection::LeftToRight => false, TextDirection::RightToLeft => true, + TextDirection::Auto if self.text_len <= byte_offset => self.last_rtl, TextDirection::Auto => { let i = self .rtl_paragraphs @@ -1906,6 +1933,11 @@ impl BidiLevels { } } +/// Does `paragraph` lack a strong character (UAX #9 rule P2), e.g. an empty line or only digits? +pub(crate) fn is_neutral(paragraph: &str) -> bool { + unicode_bidi::get_base_direction(paragraph) == unicode_bidi::Direction::Mixed +} + /// UAX #9 rule L1: segment separators (tab), paragraph separators, and any sequence /// of whitespace before one of them or at the end of the row take the paragraph level. /// @@ -3464,11 +3496,12 @@ mod tests { fn paragraph_direction_is_auto_or_forced() { let mut fonts = test_fonts(); - // Each paragraph takes the direction of its first strong character: + // Each paragraph takes the direction of its first strong character, + // or of the paragraph before it if it has none: let galley = layout_with_direction(&mut fonts, "abc אבג\nאבג abc\n123", TextDirection::Auto); let rtl: Vec = galley.rows.iter().map(|row| row.rtl_paragraph).collect(); - assert_eq!(rtl, [false, true, false]); + assert_eq!(rtl, [false, true, true]); assert_visual_order(&galley.rows[0].row, &[0, 1, 2, 6, 5, 4]); assert_visual_order(&galley.rows[1].row, &[4, 5, 6, 2, 1, 0]); @@ -3493,6 +3526,45 @@ mod tests { assert_visual_order(&galley.rows[0].row, &[0, 1, 2]); } + /// With `Auto`, a paragraph without a strong character takes the direction of the one before, + /// both when the job is laid out whole and when `Fonts` lays out each paragraph on its own. + #[test] + fn neutral_paragraphs_take_the_direction_before_them() { + let cases: [(&str, &[bool]); 5] = [ + // An empty line after Hebrew, and the empty line after a final newline: + ("אבג\n\nabc\n\n", &[true, true, false, false, false]), + ("אבג\n", &[true, true]), + // Digits after Arabic, and after English: + ("ثمن\n123 456\nabc\n123", &[true, true, false, false]), + // The first paragraph has nothing before it: + ("123\nאבג\n", &[false, true, true]), + ("\n\nאבג", &[false, false, true]), + ]; + let mut fonts = test_fonts(); + let mut cached = Fonts::new(TextOptions::default(), FontDefinitions::default()); + for (text, expected) in cases { + let whole = layout_with_direction(&mut fonts, text, TextDirection::Auto); + let job = LayoutJob::simple( + text.to_owned(), + FontId::proportional(14.0), + Color32::WHITE, + f32::INFINITY, + ); + let split = cached.with_pixels_per_point(1.0).layout_job(job); + for galley in [&whole, &*split] { + let rtl: Vec = galley.rows.iter().map(|row| row.rtl_paragraph).collect(); + assert_eq!(rtl, expected, "{text:?}"); + } + } + + // Digits in a right-to-left paragraph get the levels of one: + let galley = layout_with_direction(&mut fonts, "ثمن\n12 34", TextDirection::Auto); + let row = &galley.rows[1].row; + let levels: Vec = row.glyphs.iter().map(|g| g.bidi_level).collect(); + assert_eq!(levels, [2, 2, 1, 2, 2]); + assert_visual_order(row, &[3, 4, 2, 0, 1]); + } + /// `Fonts` lays out each paragraph of a multi-paragraph job on its own; /// every one of them must keep the job's direction. #[test] diff --git a/crates/epaint/src/text/text_layout_types.rs b/crates/epaint/src/text/text_layout_types.rs index 2a907429..4c5ae77d 100644 --- a/crates/epaint/src/text/text_layout_types.rs +++ b/crates/epaint/src/text/text_layout_types.rs @@ -372,7 +372,9 @@ impl core::hash::Hash for LayoutJob { #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))] pub enum TextDirection { /// Each paragraph takes the direction of its first strong character (UAX #9 rules P2 and P3), - /// the same as `dir="auto"` in HTML. A paragraph without one is left-to-right. + /// the same as `dir="auto"` in HTML. A paragraph without one, such as an empty line + /// or a line of digits, takes the direction of the paragraph before it, as in most editors; + /// the first paragraph of the text is then left-to-right. #[default] Auto,