PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(type): use the correct line at soft-wrap caret boundaries (#3174)
Nigel Ihza Firdausy27856994641c
diff --git a/crates/engine/src/type_caret_cmds.rs b/crates/engine/src/type_caret_cmds.rsindex 83e6e0634..528472cc2 100644--- a/crates/engine/src/type_caret_cmds.rs+++ b/crates/engine/src/type_caret_cmds.rs@@ -266,7 +266,8 @@ mod tests {assert_eq!(u(&h, "index"), i as u64, "{text:?} index {i} at ({x}, {y}) -> {h}");assert_eq!(h["line"], c["line"], "{text:?} index {i}");assert_eq!(u(&h, "layer"), id);- let on_line = lines.iter().position(|ln| {+ // A shared soft-wrap boundary belongs to the following line, where the caret is drawn (#3068).+ let on_line = lines.iter().rposition(|ln| {let a = ln["start"].as_u64().unwrap();let b = ln["end"].as_u64().unwrap();(i as u64) >= a && (i as u64) <= b@@ -380,6 +381,25 @@ mod tests {assert_eq!(s.journal.len(), journal);}+ #[test]+ fn wrapped_caret_queries_use_the_line_that_contains_the_caret() {+ let mut s = session();+ let id = create(&mut s, json!({"text": "ab cd", "box": [20, 20, 20, 70], "size": 12, "font": "Inter"}));+ let info = s.execute("type.info", json!({"layer": id})).unwrap();+ let lines = info["lines"].as_array().unwrap();+ assert!(lines.len() >= 2, "{lines:?}");+ let index = lines[1]["start"].as_u64().unwrap() as usize;+ assert_eq!(index as u64, lines[0]["end"].as_u64().unwrap(), "shared wrap boundary");+ assert_eq!(s.execute("type.caret", json!({"layer": id, "index": index})).unwrap()["line"], 1);+ assert_eq!(go(&mut s, id, index, "lineStart", None), index as u64);+ assert_eq!(go(&mut s, id, index, "lineEnd", None), lines[1]["end"].as_u64().unwrap());++ let hard = create(&mut s, json!({"text": "ab\ncd", "x": 30, "y": 100, "size": 12, "font": "Inter"}));+ assert_eq!(s.execute("type.caret", json!({"layer": hard, "index": 3})).unwrap()["line"], 1);+ assert_eq!(go(&mut s, hard, 3, "lineStart", None), 3);+ assert_eq!(go(&mut s, hard, 3, "lineEnd", None), 5);+ }+#[test]fn hit_test_picks_the_topmost_visible_type_layer_and_empty_text_is_index_zero() {let mut s = session();diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rsindex 23d1af5f6..c95a5a064 100644--- a/crates/text/src/layout.rs+++ b/crates/text/src/layout.rs@@ -234,9 +234,10 @@ impl TextLayout {self.hit_test_line(x, y)}- /// Byte offset of the caret nearest to a line-space point.- pub fn hit_test_line(&self, x: f32, y: f32) -> usize {- let Some((li, line)) = self.lines.iter().enumerate().min_by(|a, b| {+ /// The visual line nearest to a line-space ordinate, including its ascent and descent.+ /// Pointer hit testing uses this even where adjacent lines share a caret byte offset.+ fn closest_line(&self, y: f32) -> Option<(usize, &LineInfo)> {+ self.lines.iter().enumerate().min_by(|a, b| {let d = |l: &LineInfo| {if y < l.baseline - l.ascent {l.baseline - l.ascent - y@@ -247,7 +248,12 @@ impl TextLayout {}};d(a.1).total_cmp(&d(b.1))- }) else {+ })+ }++ /// Byte offset of the caret nearest to a line-space point.+ pub fn hit_test_line(&self, x: f32, y: f32) -> usize {+ let Some((li, line)) = self.closest_line(y) else {return 0;};let mut best = (f32::MAX, line.range.end);@@ -311,15 +317,20 @@ pub fn char_index(text: &str, byte: usize) -> usize {text[..byte].chars().count()}-/// Line containing a byte offset (the last line when the offset sits past every line).+/// Line containing a byte offset. At a shared wrap boundary the caret belongs to+/// the following line, while an offset at the end of the text stays on the last.pub fn line_index(layout: &TextLayout, byte: usize) -> usize {- layout.lines.iter().position(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1))+ layout.lines.iter().rposition(|ln| byte >= ln.range.start && byte <= ln.range.end).unwrap_or_else(|| layout.lines.len().saturating_sub(1))}/// Nearest caret to a text-space point: character index and the line it sits on.pub fn hit_char(layout: &TextLayout, text: &str, x: f32, y: f32) -> (usize, usize) {let byte = layout.hit_test(x, y);- (char_index(text, byte), line_index(layout, byte))+ // At a soft-wrap boundary either visual line can share this byte offset. The+ // pointer's line, not the caret's preferred (following) line, is authoritative.+ let (_, line_y) = layout.to_line(x, y);+ let line = layout.closest_line(line_y).map_or_else(|| line_index(layout, byte), |(index, _)| index);+ (char_index(text, byte), line)}/// Text-space point inside the laid-out line boxes, expanded by `slop` px on every side.@@ -377,7 +388,7 @@ pub fn line_edge(layout: &TextLayout, text: &str, idx: usize, end: bool) -> usizlet n = text.chars().count();let idx = idx.min(n);let byte = byte_index(text, idx);- let line = layout.lines.iter().find(|ln| byte >= ln.range.start && byte <= ln.range.end).or(layout.lines.last());+ let line = layout.lines.get(line_index(layout, byte));line.map_or(idx, |ln| char_index(text, if end { ln.range.end } else { ln.range.start }))}diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rsindex 3f656c21a..e89d32ac3 100644--- a/crates/text/src/tests.rs+++ b/crates/text/src/tests.rs@@ -417,6 +417,44 @@ fn hit_test_and_caret() {assert_eq!(l.caret(3).0, l.lines[0].x1);}+#[test]+fn wrapped_and_forced_line_starts_use_the_following_line() {+ use crate::layout::{byte_index, line_edge, line_index};++ let mut engine = TextEngine::new();+ let mut wrapped = point("ab cd", 12.0);+ wrapped.shape = TextShape::Box { x: 0.0, y: 0.0, width: 20.0, height: 70.0 };+ let layout = engine.layout(&wrapped, 72.0);+ assert!(layout.lines.len() >= 2, "paragraph must wrap: {:?}", layout.lines);+ let boundary = layout.lines[1].range.start;+ assert_eq!(layout.lines[0].range.end, boundary);+ let index = wrapped.text[..boundary].chars().count();+ assert_eq!(line_index(&layout, byte_index(&wrapped.text, index)), 1);+ assert_eq!(line_edge(&layout, &wrapped.text, index, false), index);+ assert_eq!(line_edge(&layout, &wrapped.text, index, true), wrapped.text[..layout.lines[1].range.end].chars().count());+ // The previous line's right edge shares the caret index, but a click there+ // must still report the previous visual line.+ let first = &layout.lines[0];+ let (x, y) = layout.to_text(first.x1, first.baseline);+ assert_eq!(crate::layout::hit_char(&layout, &wrapped.text, x, y).1, 0);++ let text = "a\u{3}b";+ let forced = engine.layout(&point(text, 12.0), 72.0);+ assert_eq!(forced.lines.len(), 2);+ let start = forced.lines[1].range.start;+ let index = text[..start].chars().count();+ assert_eq!(line_index(&forced, start), 1);+ assert_eq!(line_edge(&forced, text, index, false), index);+ assert_eq!(line_edge(&forced, text, index, true), text.chars().count());++ // A normal paragraph break has distinct boundaries and retains its line.+ let text = "a\nb";+ let paragraph = engine.layout(&point(text, 12.0), 72.0);+ assert_eq!(line_index(¶graph, paragraph.lines[0].range.end), 0);+ assert_eq!(line_index(¶graph, paragraph.lines[1].range.start), 1);+ assert_eq!(line_index(¶graph, text.len()), 1);+}+#[test]fn empty_text_and_empty_lines() {let mut e = TextEngine::new();