Fix underflow in ccursor_previous_word for a cursor past the text

From emilk/egui#8698 (commit 27ded9ed3). A cursor can be stored past the end
of the text when a row has more glyphs than characters; Ctrl+ArrowLeft then
subtracted below zero. `ccursor_previous_word` clamps such a cursor.

The epaint half of #8698 (one glyph per character in a right-to-left run) is
covered by the bidi layout; its regression test is kept.

Co-authored-by: odessadraekavik <4887819+odessadraekavik@users.noreply.github.com>
This commit is contained in:
aionggandodessadraekavik committed 2026-10-21 05:16:13 +00:00
1 parent 0e27d87e33
commit 777977b7bd
2 files changed
+50 -1

No files matched your search

@@ -367,7 +367,9 @@ fn ccursor_next_line(text: &str, ccursor: CCursor) -> CCursor {
pub fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor {
let num_chars = CharIndex(text.chars().count());
let reversed: String = text.graphemes(true).rev().collect();
let boundary = next_word_boundary_char_index(&reversed, num_chars - ccursor.index);
// The cursor can be past the end of the text, e.g. when a row has more glyphs than characters.
let chars_after_cursor = num_chars - ccursor.index.min(num_chars);
let boundary = next_word_boundary_char_index(&reversed, chars_after_cursor);
CCursor {
index: num_chars - boundary.min(num_chars),
prefer_next_row: true,
@@ -552,6 +554,11 @@ mod test {
assert_eq!(ccursor_previous_word(text, CCursor::new(5)).index.0, 4);
assert_eq!(ccursor_previous_word(text, CCursor::new(4)).index.0, 0);
assert_eq!(ccursor_previous_word(text, CCursor::new(0)).index.0, 0);
// A cursor past the end of the text must not underflow:
assert_eq!(ccursor_previous_word(text, CCursor::new(12)).index.0, 8);
assert_eq!(ccursor_previous_word(text, CCursor::new(99)).index.0, 8);
assert_eq!(ccursor_previous_word("", CCursor::new(1)).index.0, 0);
}
#[test]
+42
View File
@@ -3144,6 +3144,48 @@ mod tests {
}
}
/// Regression test for <https://github.com/emilk/egui/issues/8576>.
///
/// The shaper returns a right-to-left run in visual order, with decreasing
/// cluster offsets. Such a run must still produce one glyph per character.
#[test]
fn test_right_to_left_run_glyph_count() {
let pixels_per_point = 1.0;
let mut fonts = test_fonts();
let font_id = FontId::default();
let cases = [
"ب",
"بب",
"ببب",
"אב",
"a אבג b",
"שלום 42 עולם",
// Base char + combining mark inside a right-to-left run
"ב\u{05BC}א",
];
for text in cases {
let job = LayoutJob::simple(
text.to_owned(),
font_id.clone(),
Color32::WHITE,
f32::INFINITY,
);
let galley = layout(&mut fonts, pixels_per_point, job.into());
let total_glyphs: usize = galley.rows.iter().map(|r| r.row.glyphs.len()).sum();
let num_chars = text.chars().count();
assert_eq!(total_glyphs, num_chars, "Glyph count mismatch for {text:?}");
assert_eq!(
galley.end().index.0,
num_chars,
"Galley::end().index mismatch for {text:?}",
);
}
}
#[cfg(feature = "default_fonts")]
fn measure_text(
fonts: &mut FontsImpl,