diff --git a/render-wasm/src/render/text_editor.rs b/render-wasm/src/render/text_editor.rs index 0c29a0fab1..6194ddbcf0 100644 --- a/render-wasm/src/render/text_editor.rs +++ b/render-wasm/src/render/text_editor.rs @@ -1,7 +1,7 @@ use crate::render::options::RenderOptions; use crate::shapes::text_paragraph::LayoutParagraph; use crate::shapes::text_vertical; -use crate::shapes::{vertical_align_offset, Shape, TextContent, Type}; +use crate::shapes::{vertical_align_offset, Shape, TextContent, TextPositionWithAffinity, Type}; use crate::state::{TextEditorState, TextSelection}; use crate::view::Viewbox; use skia_safe::textlayout::{RectHeightStyle, RectWidthStyle}; @@ -153,11 +153,15 @@ fn vertical_layout_for_shape( fn calculate_vertical_cursor_rect( text_content: &TextContent, shape: &Shape, - paragraph: usize, - offset: usize, + cursor: &TextPositionWithAffinity, ) -> Option { let (layout, origin_x) = vertical_layout_for_shape(text_content, shape); - let rect = text_vertical::caret_rect(&layout, paragraph, offset)?; + let rect = text_vertical::caret_rect_with_affinity( + &layout, + cursor.paragraph, + cursor.offset, + cursor.is_upstream(), + )?; Some(Rect::from_xywh( origin_x + rect.x(), rect.y(), @@ -226,12 +230,7 @@ pub(crate) fn cursor_rect( } if text_content.is_vertical() { - return calculate_vertical_cursor_rect( - text_content, - shape, - cursor.paragraph, - cursor.offset, - ); + return calculate_vertical_cursor_rect(text_content, shape, &cursor); } let layout_paragraphs: Vec<_> = text_content.layout.paragraphs.iter().flatten().collect(); @@ -244,11 +243,233 @@ pub(crate) fn cursor_rect( let plans = text_content.horizontal_plans(); let plan = plans.get(cursor.paragraph)?; let model = ¶graphs[cursor.paragraph]; - let rect = - horizontal_caret_rect_with_offsets(model, laid_out_para, cursor.offset, &plan.offsets); + let rect = horizontal_caret_rect_with_offsets( + model, + laid_out_para, + cursor.offset, + cursor.is_upstream(), + &plan.offsets, + ); Some(rect.with_offset((plan.x_offset(model, shape.selrect.width()), y_offset))) } +/// The start (`before`) or the end of the whole text. +fn text_edge(text_content: &TextContent, before: bool) -> TextPositionWithAffinity { + let paragraphs = text_content.paragraphs(); + if before || paragraphs.is_empty() { + return TextPositionWithAffinity::new_downstream_affinity(0, 0); + } + let last = paragraphs.len() - 1; + TextPositionWithAffinity::new_downstream_affinity(last, paragraph_chars(¶graphs[last])) +} + +fn paragraph_chars(paragraph: &crate::shapes::Paragraph) -> usize { + paragraph + .children() + .iter() + .map(|span| span.text.chars().count()) + .sum() +} + +/// Laid-out horizontal paragraphs with their models and plans, or None +/// when the text has no layout for every paragraph. +fn horizontal_parts( + text_content: &TextContent, +) -> Option<( + Vec<&LayoutParagraph>, + std::rc::Rc>, +)> { + let layout_paragraphs: Vec<&LayoutParagraph> = + text_content.layout.paragraphs.iter().flatten().collect(); + (layout_paragraphs.len() == text_content.paragraphs().len()) + .then(|| (layout_paragraphs, text_content.horizontal_plans())) +} + +/// Index of the line of `laid_out` at the paragraph-local `y`, or the +/// nearest one. +fn line_at(laid_out: &LayoutParagraph, y: f32) -> Option { + let lines = laid_out.get_line_metrics(); + let distance = |line: &skia_safe::textlayout::LineMetrics| { + let top = (line.baseline - line.ascent) as f32; + let bottom = (line.baseline + line.descent) as f32; + if y < top { + top - y + } else if y >= bottom { + y - bottom + } else { + 0.0 + } + }; + (0..lines.len()).min_by(|a, b| distance(&lines[*a]).total_cmp(&distance(&lines[*b]))) +} + +/// Caret moved one visual line from `focus`: a line of horizontal text, up +/// when `before`, or a column of vertical text, to the right when `before`. +/// `goal` is the position along the line kept from the move before, if any. +/// Returns the new caret and the goal to keep; a move past the first or +/// last line goes to the start or end of the text. None without a layout. +pub(crate) fn caret_line_step( + text_content: &TextContent, + shape: &Shape, + focus: &TextPositionWithAffinity, + before: bool, + goal: Option, +) -> Option<(TextPositionWithAffinity, f32)> { + if text_content.is_vertical() { + let (layout, _) = vertical_layout_for_shape(text_content, shape); + let rect = text_vertical::caret_rect_with_affinity( + &layout, + focus.paragraph, + focus.offset, + focus.is_upstream(), + )?; + let goal = goal.unwrap_or(rect.top()); + let cursor = text_vertical::caret_column_step( + &layout, + focus.paragraph, + focus.offset, + focus.is_upstream(), + before, + goal, + ) + .map_or_else( + || text_edge(text_content, before), + |(paragraph, offset)| { + TextPositionWithAffinity::new_downstream_affinity(paragraph, offset) + }, + ); + return Some((cursor, goal)); + } + + let (layout_paragraphs, plans) = horizontal_parts(text_content)?; + let model = text_content.paragraphs().get(focus.paragraph)?; + let laid_out = *layout_paragraphs.get(focus.paragraph)?; + let plan = plans.get(focus.paragraph)?; + let x_offset = plan.x_offset(model, shape.selrect.width()); + let rect = horizontal_caret_rect_with_offsets( + model, + laid_out, + focus.offset, + focus.is_upstream(), + &plan.offsets, + ); + let goal = goal.unwrap_or(rect.left() + x_offset); + + // Inside a warichu note, the other sub-line is one line away. + if let Some((offset, upstream)) = crate::shapes::horizontal_warichu_step( + model, + laid_out, + focus.offset, + focus.is_upstream(), + goal - x_offset, + !before, + ) { + let cursor = if upstream { + TextPositionWithAffinity::new_upstream_affinity(focus.paragraph, offset) + } else { + TextPositionWithAffinity::new_downstream_affinity(focus.paragraph, offset) + }; + return Some((cursor, goal)); + } + + // Every line as (top, bottom) in content coordinates. + let mut lines = Vec::new(); + let mut current = None; + let mut paragraph_top = 0.0; + for (index, paragraph) in layout_paragraphs.iter().enumerate() { + let caret_line = (index == focus.paragraph) + .then(|| line_at(paragraph, rect.center_y())) + .flatten(); + for (line_index, line) in paragraph.get_line_metrics().iter().enumerate() { + if caret_line == Some(line_index) { + current = Some(lines.len()); + } + lines.push(( + paragraph_top + (line.baseline - line.ascent) as f32, + paragraph_top + (line.baseline + line.descent) as f32, + )); + } + paragraph_top += paragraph.height(); + } + let current = current?; + let target = if before { + current.checked_sub(1) + } else { + Some(current + 1).filter(|index| *index < lines.len()) + }; + let Some(target) = target else { + return Some((text_edge(text_content, before), goal)); + }; + // Off-center, so a warichu note in that line takes the sub-line next + // to the caret: the first going down, the second going up. + let (top, bottom) = lines[target]; + let y = if before { + top + (bottom - top) * 0.75 + } else { + top + (bottom - top) * 0.25 + }; + let cursor = text_content.get_caret_position_from_shape_coords( + &Point::new(goal, y), + &shape.selrect, + shape.vertical_align(), + )?; + Some((cursor, goal)) +} + +/// Caret at the start of the visual line or column holding `focus`, or at +/// its end when `end`. The end of a wrapped line or column is upstream, so +/// the caret stays on it. +pub(crate) fn caret_line_edge( + text_content: &TextContent, + shape: &Shape, + focus: &TextPositionWithAffinity, + end: bool, +) -> Option { + let model = text_content.paragraphs().get(focus.paragraph)?; + let chars = paragraph_chars(model); + let at = |offset: usize| { + if end && offset < chars { + TextPositionWithAffinity::new_upstream_affinity(focus.paragraph, offset) + } else { + TextPositionWithAffinity::new_downstream_affinity(focus.paragraph, offset) + } + }; + if text_content.is_vertical() { + let (layout, _) = vertical_layout_for_shape(text_content, shape); + let (_, offset) = text_vertical::caret_column_edge( + &layout, + focus.paragraph, + focus.offset, + focus.is_upstream(), + end, + )?; + return Some(at(offset)); + } + + let (layout_paragraphs, plans) = horizontal_parts(text_content)?; + let laid_out = *layout_paragraphs.get(focus.paragraph)?; + let plan = plans.get(focus.paragraph)?; + let rect = horizontal_caret_rect_with_offsets( + model, + laid_out, + focus.offset, + focus.is_upstream(), + &plan.offsets, + ); + let lines = laid_out.get_line_metrics(); + let index = line_at(laid_out, rect.center_y())?; + let line = &lines[index]; + let offset = if !end { + plan.offsets.builder_to_source(line.start_index) + } else if index + 1 < lines.len() { + plan.offsets + .builder_to_source(line.end_excluding_whitespaces) + } else { + chars + }; + Some(at(offset)) +} + /// Caret rect at the source character offset `char_pos` of a laid-out /// horizontal paragraph, in the paragraph's coordinates. It covers the /// character at the offset (overtype carets use its width), or follows the @@ -263,17 +484,23 @@ fn horizontal_caret_rect( para, laid_out_para, char_pos, + false, &crate::shapes::HorizontalOffsets::new(para), ) } +/// Caret rect at `char_pos` (see `horizontal_caret_rect`). An `upstream` +/// offset at the start of a wrapped line is drawn at the end of the line +/// before it. fn horizontal_caret_rect_with_offsets( para: &crate::shapes::Paragraph, laid_out_para: &LayoutParagraph, char_pos: usize, + upstream: bool, offsets: &crate::shapes::HorizontalOffsets, ) -> Rect { - if let Some(rect) = crate::shapes::horizontal_warichu_caret_rect(para, laid_out_para, char_pos) + if let Some(rect) = + crate::shapes::horizontal_warichu_caret_rect(para, laid_out_para, char_pos, upstream) { return rect; } @@ -313,7 +540,21 @@ fn horizontal_caret_rect_with_offsets( } let start = offsets.source_to_builder(char_pos); let end = offsets.source_to_builder(para.next_grapheme_offset(char_pos)); - match first_rect(start, end) { + let rect = first_rect(start, end); + if upstream && char_pos > 0 { + let previous_start = offsets.source_to_builder(para.prev_grapheme_offset(char_pos)); + if let (Some(previous), Some(rect)) = (first_rect(previous_start, start), rect) { + if previous.top() < rect.top() { + return Rect::from_xywh( + previous.right(), + previous.top(), + previous.width(), + previous.height(), + ); + } + } + } + match rect { Some(rect) => rect, None if char_pos == 0 => default_rect(), None => { @@ -479,6 +720,7 @@ mod tests { FontFamily, FontStyle, GrowType, Paragraph, TextAlign, TextDirection, TextSpan, }; use crate::uuid::Uuid; + use crate::wasm::text_editor::CursorDirection; use skia_safe::textlayout::{ FontCollection, ParagraphBuilder, ParagraphStyle, TextStyle, TypefaceFontProvider, }; @@ -906,4 +1148,252 @@ mod tests { assert!((fill.left - stroke.left).abs() < 0.01); } } + + /// Family of the Japanese test spans. + fn japanese() -> FontFamily { + FontFamily::new(Uuid::nil(), 700, FontStyle::Normal) + } + + /// Headless resources with a Noto Sans JP subset as `japanese()`. Its + /// notdef glyph is 1em wide, so every character takes a full em. + fn japanese_resources() -> RenderResources { + let mut resources = RenderResources::try_new_headless().expect("headless resources"); + resources + .fonts + .add( + japanese(), + crate::shapes::text_vertical::test_support::VPAL_TEST_FONT, + false, + false, + ) + .expect("test font"); + resources + } + + /// A laid-out fixed Japanese text `width` by `height` with one paragraph + /// of `spans` (text, warichu), set vertically when `vertical`. Lines are + /// taller than the characters, as with the default line height. + fn japanese_shape(spans: &[(&str, bool)], width: f32, height: f32, vertical: bool) -> Shape { + crate::globals::design_init(); + let spans = spans + .iter() + .map(|(text, warichu)| TextSpan { + text: text.to_string(), + font_family: japanese(), + font_size: 20.0, + line_height: 1.4, + warichu: *warichu, + ..TextSpan::default() + }) + .collect(); + let mut paragraph = Paragraph::new( + TextAlign::Left, + TextDirection::LTR, + None, + None, + 1.0, + 0.0, + spans, + ); + paragraph.set_language("ja".to_owned()); + if vertical { + paragraph.set_writing_mode(crate::shapes::WritingMode::VerticalRl); + } + let mut content = + TextContent::new(Rect::from_xywh(0.0, 0.0, width, height), GrowType::Fixed); + content.add_paragraph(paragraph); + content.update_layout(Rect::from_xywh(0.0, 0.0, width, height)); + let mut shape = Shape::new(Uuid::nil()); + shape.set_shape_type(Type::Text(content)); + shape.set_selrect(0.0, 0.0, width, height); + shape + } + + fn content_of(shape: &Shape) -> &TextContent { + let Type::Text(content) = &shape.shape_type else { + unreachable!() + }; + content + } + + /// Caret offset after each key, starting at `start`. + fn walk(shape: &Shape, start: usize, keys: Vec) -> Vec { + let content = content_of(shape); + let mut editor = TextEditorState::new(); + editor + .selection + .set_caret(TextPositionWithAffinity::new_downstream_affinity(0, start)); + keys.into_iter() + .map(|key| { + editor.move_cursor(content, shape, key, false, false); + editor.selection.focus.offset + }) + .collect() + } + + fn caret_at(shape: &Shape, position: TextPositionWithAffinity) -> Rect { + let mut editor = TextEditorState::new(); + editor.selection.set_caret(position); + cursor_rect(&editor, content_of(shape), shape).expect("caret") + } + + #[test] + fn up_and_down_move_by_line_and_keep_the_caret_position() { + let mut resources = japanese_resources(); + let _guard = TestRenderResourcesGuard::install(&mut resources); + let shape = japanese_shape( + &[("あいうえおかきくけこさしすせそ", false)], + 60.0, + 200.0, + false, + ); + let lines = content_of(&shape).layout.paragraphs[0][0].get_line_metrics(); + assert!(lines.len() >= 3, "the text wraps into lines"); + let per_line = lines[0].end_index - lines[0].start_index; + use CursorDirection::{LineAfter as Down, LineBefore as Up}; + assert_eq!( + walk(&shape, 1, vec![Down, Down, Up, Up]), + vec![1 + per_line, 1 + 2 * per_line, 1 + per_line, 1] + ); + assert_eq!(walk(&shape, 1, vec![Up]), vec![0], "up from the first line"); + } + + #[test] + fn home_and_end_go_to_the_edges_of_the_visual_line() { + let mut resources = japanese_resources(); + let _guard = TestRenderResourcesGuard::install(&mut resources); + let shape = japanese_shape( + &[("あいうえおかきくけこさしすせそ", false)], + 60.0, + 200.0, + false, + ); + let lines = content_of(&shape).layout.paragraphs[0][0].get_line_metrics(); + let per_line = lines[0].end_index - lines[0].start_index; + let start = per_line + 1; + assert_eq!( + walk(&shape, start, vec![CursorDirection::LineStart]), + vec![per_line] + ); + assert_eq!( + walk( + &shape, + start, + vec![CursorDirection::LineEnd, CursorDirection::LineEnd] + ), + vec![2 * per_line, 2 * per_line], + "End stays at the end of the line" + ); + let end = caret_at( + &shape, + TextPositionWithAffinity::new_upstream_affinity(0, 2 * per_line), + ); + let middle = caret_at( + &shape, + TextPositionWithAffinity::new_downstream_affinity(0, start), + ); + assert!( + (end.top() - middle.top()).abs() < 0.01 && end.left() > middle.left(), + "the line end is drawn on its own line: {end:?} vs {middle:?}" + ); + } + + const NOTE_SPANS: [(&str, bool); 3] = [ + ("東京の本社(", false), + ("二〇二六年に移転した新しい建物", true), + ("あ)で会議を行う。", false), + ]; + + #[test] + fn up_and_down_step_between_the_halves_of_a_warichu_note() { + let mut resources = japanese_resources(); + let _guard = TestRenderResourcesGuard::install(&mut resources); + let shape = japanese_shape(&NOTE_SPANS, 400.0, 200.0, false); + use CursorDirection::{LineAfter as Down, LineBefore as Up}; + // 6..14 is the first half of the note, 14..21 the second. + let steps = walk(&shape, 8, vec![Down, Up]); + assert!( + (14..=21).contains(&steps[0]), + "down from the first half lands in the second: {steps:?}" + ); + assert_eq!(steps[1], 8, "and up comes back"); + } + + #[test] + fn clicks_on_a_warichu_note_keep_to_the_half_under_the_pointer() { + let mut resources = japanese_resources(); + let _guard = TestRenderResourcesGuard::install(&mut resources); + let shape = japanese_shape(&NOTE_SPANS, 400.0, 200.0, false); + let content = content_of(&shape); + let hit = |x: f32, y: f32| { + content + .get_caret_position_from_shape_coords( + &Point::new(x, y), + &shape.selrect, + crate::shapes::VerticalAlign::Top, + ) + .expect("hit") + }; + let first = caret_at( + &shape, + TextPositionWithAffinity::new_downstream_affinity(0, 7), + ); + let lines = content.layout.paragraphs[0][0].get_line_metrics(); + let line_top = (lines[0].baseline - lines[0].ascent) as f32; + assert!(line_top < first.top(), "the line is taller than the note"); + let above = hit(first.center_x(), (line_top + first.top()) / 2.0); + assert!( + (6..14).contains(&above.offset), + "above the first half picks it, got {}", + above.offset + ); + + let last = caret_at( + &shape, + TextPositionWithAffinity::new_downstream_affinity(0, 13), + ); + let split = hit(last.right() - 0.1, last.center_y()); + assert_eq!(split.offset, 14); + assert!(split.is_upstream(), "the end of the first half is upstream"); + let caret = caret_at(&shape, split); + assert!( + (caret.top() - last.top()).abs() < 0.01 && caret.left() >= last.right() - 0.01, + "drawn after the half's last character: {caret:?} vs {last:?}" + ); + } + + #[test] + fn left_and_right_move_across_vertical_columns() { + let mut resources = japanese_resources(); + let _guard = TestRenderResourcesGuard::install(&mut resources); + let shape = japanese_shape( + &[("あいうえおかきくけこさしすせそ", false)], + 200.0, + 60.0, + true, + ); + let layout = content_of(&shape).vertical_layout(&shape.selrect); + assert!(layout.columns.len() >= 3, "the text wraps into columns"); + let per_column = (0..15) + .find(|offset| { + text_vertical::caret_rect_with_affinity(&layout, 0, *offset, false) + .expect("caret") + .left() + < layout.columns[0].x + }) + .expect("a second column"); + use CursorDirection::{Backward as Left, Forward as Right}; + assert_eq!( + walk(&shape, 1, vec![Left, Left, Right, Right]), + vec![1 + per_column, 1 + 2 * per_column, 1 + per_column, 1] + ); + assert_eq!( + walk(&shape, per_column + 1, vec![CursorDirection::LineStart]), + vec![per_column] + ); + assert_eq!( + walk(&shape, per_column + 1, vec![CursorDirection::LineEnd]), + vec![2 * per_column] + ); + } } diff --git a/render-wasm/src/shapes/text.rs b/render-wasm/src/shapes/text.rs index a13898096b..23d513eee6 100644 --- a/render-wasm/src/shapes/text.rs +++ b/render-wasm/src/shapes/text.rs @@ -221,6 +221,12 @@ impl TextPositionWithAffinity { } } + /// True when the position belongs to the end of what comes before it, + /// such as the end of a wrapped line rather than the start of the next. + pub fn is_upstream(&self) -> bool { + self.position_with_affinity.affinity == Affinity::Upstream + } + pub fn new_upstream_affinity(paragraph: usize, offset: usize) -> Self { Self { position_with_affinity: PositionWithAffinity { @@ -1324,13 +1330,20 @@ impl TextContent { .map_or(0.0, |(plan, model)| plan.x_offset(model, selrect.width())); let para_pt = Point::new(point.x - x_offset, point.y - start_y); if let Some(paragraph) = self.paragraphs().get(paragraph_index) { - if let Some(original_position) = + if let Some((original_position, upstream)) = horizontal_warichu_hit_test(paragraph, layout_paragraph, para_pt) { - return Some(TextPositionWithAffinity::new_downstream_affinity( - paragraph_index, - original_position, - )); + return Some(if upstream { + TextPositionWithAffinity::new_upstream_affinity( + paragraph_index, + original_position, + ) + } else { + TextPositionWithAffinity::new_downstream_affinity( + paragraph_index, + original_position, + ) + }); } } let position_with_affinity = diff --git a/render-wasm/src/shapes/text_horizontal/mod.rs b/render-wasm/src/shapes/text_horizontal/mod.rs index b06fa09bbb..3a0f7de406 100644 --- a/render-wasm/src/shapes/text_horizontal/mod.rs +++ b/render-wasm/src/shapes/text_horizontal/mod.rs @@ -42,7 +42,7 @@ use skia_safe::{ ParagraphBuilder, ParagraphStyle, PlaceholderAlignment, PlaceholderStyle, RectHeightStyle, RectWidthStyle, TextBaseline, }, - Canvas, Contains, Font, FontMgr, GlyphId, + Canvas, Font, FontMgr, GlyphId, }; /// True when a paragraph with layout texts `texts` needs the Japanese passes: diff --git a/render-wasm/src/shapes/text_horizontal/warichu.rs b/render-wasm/src/shapes/text_horizontal/warichu.rs index 94caded011..89d5c91b89 100644 --- a/render-wasm/src/shapes/text_horizontal/warichu.rs +++ b/render-wasm/src/shapes/text_horizontal/warichu.rs @@ -46,13 +46,37 @@ fn horizontal_warichu_boxes<'a>( boxes } +/// Vertical extent (top, bottom) of the laid-out line that holds `rect`. +fn line_band(laid_out: &LayoutParagraph, rect: &skia::Rect) -> (f32, f32) { + laid_out + .get_line_metrics() + .iter() + .map(|line| { + ( + (line.baseline - line.ascent) as f32, + (line.baseline + line.descent) as f32, + ) + }) + .find(|(top, bottom)| rect.center_y() >= *top && rect.center_y() <= *bottom) + .unwrap_or((rect.top(), rect.bottom())) +} + +/// Source offset of the caret for a point on a warichu note, and whether it +/// is upstream: at the end of the first sub-line, not the start of the +/// second. The note takes the points over its width across its whole line: +/// above the note counts as the first sub-line, below it as the second. pub(crate) fn horizontal_warichu_hit_test( paragraph: &Paragraph, laid_out: &LayoutParagraph, point: Point, -) -> Option { +) -> Option<(usize, bool)> { for (span, source_start, _, rect) in horizontal_warichu_boxes(paragraph, laid_out) { - if !rect.contains(&point) { + let (band_top, band_bottom) = line_band(laid_out, &rect); + if point.x < rect.left() + || point.x >= rect.right() + || point.y < band_top + || point.y >= band_bottom + { continue; } let split = warichu_split_chars(&span.apply_text_transform()); @@ -64,16 +88,21 @@ pub(crate) fn horizontal_warichu_hit_test( (0, split) }; let fraction = ((point.x - rect.left()) / rect.width().max(0.01)).clamp(0.0, 1.0); - let within = (fraction * line_len as f32).round() as usize; - return Some(source_start + line_start + within.min(line_len)); + let within = ((fraction * line_len as f32).round() as usize).min(line_len); + let upstream = !second && within == line_len && line_len < total; + return Some((source_start + line_start + within, upstream)); } None } +/// Caret rect at `source_offset` inside a warichu note, or None outside +/// every note. The offset where the sub-lines meet is drawn at the end of the +/// first sub-line when `upstream`, else at the start of the second. pub(crate) fn horizontal_warichu_caret_rect( paragraph: &Paragraph, laid_out: &LayoutParagraph, source_offset: usize, + upstream: bool, ) -> Option { for (span, source_start, source_end, rect) in horizontal_warichu_boxes(paragraph, laid_out) { if source_offset < source_start || source_offset > source_end { @@ -82,7 +111,8 @@ pub(crate) fn horizontal_warichu_caret_rect( let split = warichu_split_chars(&span.apply_text_transform()); let local = source_offset - source_start; let total = source_end - source_start; - let (line_start, line_len, top) = if local >= split { + let second = local > split || (local == split && !upstream); + let (line_start, line_len, top) = if second { (split, total - split, rect.top() + rect.height() / 2.0) } else { (0, split, rect.top()) @@ -99,6 +129,34 @@ pub(crate) fn horizontal_warichu_caret_rect( None } +/// Caret moved to the other sub-line of the warichu note holding +/// `source_offset`, keeping `x`: down from the first sub-line, up from the +/// second. None when the caret is outside every note or the move leaves it. +pub(crate) fn horizontal_warichu_step( + paragraph: &Paragraph, + laid_out: &LayoutParagraph, + source_offset: usize, + upstream: bool, + x: f32, + down: bool, +) -> Option<(usize, bool)> { + let caret = horizontal_warichu_caret_rect(paragraph, laid_out, source_offset, upstream)?; + let (_, _, _, rect) = horizontal_warichu_boxes(paragraph, laid_out) + .into_iter() + .find(|(_, start, end, _)| (*start..=*end).contains(&source_offset))?; + let second = caret.top() > rect.top() + rect.height() / 4.0; + if down == second { + return None; + } + let y = if down { + rect.top() + rect.height() * 0.75 + } else { + rect.top() + rect.height() * 0.25 + }; + let x = x.clamp(rect.left(), rect.right() - 0.01); + horizontal_warichu_hit_test(paragraph, laid_out, Point::new(x, y)) +} + pub(crate) fn horizontal_warichu_range_rects( paragraph: &Paragraph, laid_out: &LayoutParagraph, diff --git a/render-wasm/src/shapes/text_vertical/mod.rs b/render-wasm/src/shapes/text_vertical/mod.rs index 2b5b5e35dc..ede0fa8807 100644 --- a/render-wasm/src/shapes/text_vertical/mod.rs +++ b/render-wasm/src/shapes/text_vertical/mod.rs @@ -45,4 +45,7 @@ pub use paint::{ paint_glyphs, paint_grid, paint_layout, paint_shadow, paint_shadow_silhouette, paint_stroke, paint_text_vertical, paint_text_vertical_with, vertical_text_paths, GlyphOutput, }; -pub use positions::{caret_from_point, caret_rect, intersects, position_data, range_rects}; +pub use positions::{ + caret_column_edge, caret_column_step, caret_from_point, caret_rect_with_affinity, intersects, + position_data, range_rects, +}; diff --git a/render-wasm/src/shapes/text_vertical/positions.rs b/render-wasm/src/shapes/text_vertical/positions.rs index 4ed2c1bf8e..c2445a83bf 100644 --- a/render-wasm/src/shapes/text_vertical/positions.rs +++ b/render-wasm/src/shapes/text_vertical/positions.rs @@ -472,19 +472,100 @@ pub fn caret_from_point(layout: &VerticalLayout, x: f32, y: f32) -> Option<(usiz )) } +/// Caret one column over from `(paragraph, offset)` at the flow position +/// `y`, in content-local coordinates: the column on the right when +/// `toward_start`, else the one on the left. Inside a warichu note its other +/// sub-line comes first; entering a note lands on the sub-line nearest the +/// caret. None when no column lies that way. +pub fn caret_column_step( + layout: &VerticalLayout, + paragraph: usize, + offset: usize, + upstream: bool, + toward_start: bool, + y: f32, +) -> Option<(usize, usize)> { + let rect = caret_rect_with_affinity(layout, paragraph, offset, upstream)?; + let index = column_at(layout, rect.center_x()); + let column = &layout.columns[index]; + let centre = column_base_center(column); + let quarter = column.base_width / 4.0; + // Warichu carets cover one half of the base band (see `caret_rect`). + let first_sub_line = rect.left() >= centre - 0.01; + let second_sub_line = rect.right() <= centre + 0.01; + if first_sub_line && !toward_start { + return caret_from_point(layout, centre - quarter, y); + } + if second_sub_line && toward_start { + return caret_from_point(layout, centre + quarter, y); + } + let target = if toward_start { + index.checked_sub(1)? + } else { + index + 1 + }; + let column = layout.columns.get(target)?; + let centre = column_base_center(column); + let quarter = column.base_width / 4.0; + let x = if toward_start { + centre - quarter + } else { + centre + quarter + }; + caret_from_point(layout, x, y) +} + +/// Caret at the start (`end` false) or the end of the column holding +/// `(paragraph, offset)`. The end of a column that is not the paragraph's +/// last is the next column's start: draw it upstream. +pub fn caret_column_edge( + layout: &VerticalLayout, + paragraph: usize, + offset: usize, + upstream: bool, + end: bool, +) -> Option<(usize, usize)> { + let rect = caret_rect_with_affinity(layout, paragraph, offset, upstream)?; + let index = column_at(layout, rect.center_x()); + let centre = column_base_center(&layout.columns[index]); + let y = if end { f32::MAX } else { f32::MIN }; + caret_from_point(layout, centre, y) +} + /// Caret rect for a paragraph-relative Unicode scalar offset, in /// content-local coordinates. It spans the column width; its height is the /// extent of the character at the offset (overtype carets cover the glyph), /// or zero after the last character. +#[cfg(test)] pub fn caret_rect(layout: &VerticalLayout, paragraph: usize, offset: usize) -> Option { + caret_rect_with_affinity(layout, paragraph, offset, false) +} + +/// `caret_rect`, but an `upstream` offset that starts a column is drawn at +/// the end of the column before it. +pub fn caret_rect_with_affinity( + layout: &VerticalLayout, + paragraph: usize, + offset: usize, + upstream: bool, +) -> Option { let (col_start, _) = *layout.paragraph_columns.get(paragraph)?; let mut result: Option = None; + let mut previous_column = None; for cell in layout.cells.iter().filter(|c| c.paragraph == paragraph) { let (cell_start, cell_end) = cell_scalar_range(layout, cell)?; if cell_start > offset { continue; } + if upstream + && cell_start == offset + && result.is_some() + && previous_column != Some(cell.column) + { + break; + } + previous_column = Some(cell.column); let column = &layout.columns[cell.column]; let chars = (cell_end - cell_start).max(1); let rect = if offset >= cell_end { diff --git a/render-wasm/src/state/text_editor.rs b/render-wasm/src/state/text_editor.rs index 4d7fbae9a6..aa5334e969 100644 --- a/render-wasm/src/state/text_editor.rs +++ b/render-wasm/src/state/text_editor.rs @@ -3,7 +3,7 @@ use macros::ToJs; use crate::shapes::{ - Fill, FontStyle, TextAlign, TextContent, TextDecoration, TextDirection, + Fill, FontStyle, Shape, TextAlign, TextContent, TextDecoration, TextDirection, TextPositionWithAffinity, TextTransform, VerticalAlign, }; use crate::uuid::Uuid; @@ -364,6 +364,10 @@ pub struct TextEditorState { pub last_blink_time_ms: f32, pub current_styles: TextEditorStyles, pending_events: Vec, + /// Position along the line (x, or y in vertical text) that consecutive + /// line moves keep, and the caret the last one left; any other caret + /// change drops it. + line_goal: Option<(f32, TextPositionWithAffinity)>, } impl TextEditorState { @@ -386,6 +390,7 @@ impl TextEditorState { last_blink_time_ms: 0.0, pending_events: Vec::new(), current_styles: TextEditorStyles::new(), + line_goal: None, } } @@ -883,9 +888,12 @@ impl TextEditorState { self.push_event(TextEditorEvent::NeedsLayout); } + /// Moves the caret, or the selection focus when `extend_selection`. Line + /// moves and line edges follow the layout of `text_content` in `shape`. pub fn move_cursor( &mut self, text_content: &TextContent, + shape: &Shape, direction: CursorDirection, word_boundary: bool, extend_selection: bool, @@ -950,6 +958,37 @@ impl TextEditorState { direction }; + // A goal left by the previous line move, if the caret is still there. + let goal = self + .line_goal + .filter(|(_, at)| *at == focus && at.is_upstream() == focus.is_upstream()) + .map(|(goal, _)| goal); + let mut kept_goal = None; + let mut line_step = |before: bool| match crate::render::text_editor::caret_line_step( + text_content, + shape, + &focus, + before, + goal, + ) { + Some((cursor, goal)) => { + kept_goal = Some(goal); + cursor + } + None if before => text_helpers::move_cursor_up(&focus, paragraphs, text_content), + None => text_helpers::move_cursor_down(&focus, paragraphs, text_content), + }; + let line_edge = |end: bool| { + crate::render::text_editor::caret_line_edge(text_content, shape, &focus, end) + .unwrap_or_else(|| { + if end { + text_helpers::move_cursor_line_end(&focus, paragraphs) + } else { + text_helpers::move_cursor_line_start(&focus, paragraphs) + } + }) + }; + let new_cursor = match adjusted_direction { CursorDirection::Backward => { text_helpers::move_cursor_backward(&focus, paragraphs, word_boundary) @@ -957,20 +996,17 @@ impl TextEditorState { CursorDirection::Forward => { text_helpers::move_cursor_forward(&focus, paragraphs, word_boundary) } - CursorDirection::LineBefore => { - text_helpers::move_cursor_up(&focus, paragraphs, text_content) - } - CursorDirection::LineAfter => { - text_helpers::move_cursor_down(&focus, paragraphs, text_content) - } + CursorDirection::LineBefore => line_step(true), + CursorDirection::LineAfter => line_step(false), CursorDirection::LineStart if word_boundary => TextPositionWithAffinity::empty(), CursorDirection::LineEnd if word_boundary => text_helpers::move_cursor_line_end( &TextPositionWithAffinity::new_downstream_affinity(paragraphs.len() - 1, 0), paragraphs, ), - CursorDirection::LineStart => text_helpers::move_cursor_line_start(&focus, paragraphs), - CursorDirection::LineEnd => text_helpers::move_cursor_line_end(&focus, paragraphs), + CursorDirection::LineStart => line_edge(false), + CursorDirection::LineEnd => line_edge(true), }; + self.line_goal = kept_goal.map(|goal| (goal, new_cursor)); if extend_selection { self.selection.extend_to(new_cursor); @@ -1144,7 +1180,13 @@ mod tests { editor.selection.set_caret(pos(12)); editor.selection.extend_to(pos(15)); - editor.move_cursor(&content, CursorDirection::Backward, false, false); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Backward, + false, + false, + ); assert!(editor.selection.is_collapsed()); assert_eq!(editor.selection.focus.offset, 12); @@ -1158,7 +1200,13 @@ mod tests { editor.selection.set_caret(pos(11)); editor.selection.extend_to(pos(9)); - editor.move_cursor(&content, CursorDirection::Forward, false, false); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Forward, + false, + false, + ); assert!(editor.selection.is_collapsed()); assert_eq!(editor.selection.focus.offset, 11); @@ -1170,7 +1218,13 @@ mod tests { let mut editor = TextEditorState::new(); editor.select_all(&content); - editor.move_cursor(&content, CursorDirection::Backward, false, false); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Backward, + false, + false, + ); assert!(editor.selection.is_collapsed()); assert_eq!(editor.selection.focus.offset, 0); @@ -1182,7 +1236,13 @@ mod tests { let mut editor = TextEditorState::new(); editor.select_all(&content); - editor.move_cursor(&content, CursorDirection::Forward, false, false); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Forward, + false, + false, + ); assert!(editor.selection.is_collapsed()); assert_eq!(editor.selection.focus.offset, 5); @@ -1195,7 +1255,13 @@ mod tests { editor.selection.set_caret(pos(15)); editor.selection.extend_to(pos(12)); - editor.move_cursor(&content, CursorDirection::Backward, false, true); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Backward, + false, + true, + ); assert!(editor.selection.is_selection()); assert_eq!(editor.selection.anchor.offset, 15); @@ -1208,7 +1274,13 @@ mod tests { let mut editor = TextEditorState::new(); editor.selection.set_caret(pos(3)); - editor.move_cursor(&content, CursorDirection::Backward, false, false); + editor.move_cursor( + &content, + &Shape::new(Uuid::nil()), + CursorDirection::Backward, + false, + false, + ); assert!(editor.selection.is_collapsed()); assert_eq!(editor.selection.focus.offset, 2); diff --git a/render-wasm/src/wasm/text/helpers.rs b/render-wasm/src/wasm/text/helpers.rs index 881a7d4cb0..a707dd7eca 100644 --- a/render-wasm/src/wasm/text/helpers.rs +++ b/render-wasm/src/wasm/text/helpers.rs @@ -188,13 +188,13 @@ pub fn move_cursor_forward( TextPositionWithAffinity::new_downstream_affinity(para_idx, offset) } -/// Move cursor up by one line. +/// Move cursor to the paragraph before, keeping the offset. Fallback of +/// `caret_line_step` for text without a layout. pub fn move_cursor_up( cursor: &TextPositionWithAffinity, paragraphs: &[Paragraph], _text_content: &TextContent, ) -> TextPositionWithAffinity { - // TODO: Implement proper line-based navigation using line metrics if paragraphs.is_empty() || cursor.paragraph >= paragraphs.len() { return *cursor; } @@ -209,13 +209,13 @@ pub fn move_cursor_up( } } -/// Move cursor down by one line. +/// Move cursor to the paragraph after, keeping the offset. Fallback of +/// `caret_line_step` for text without a layout. pub fn move_cursor_down( cursor: &TextPositionWithAffinity, paragraphs: &[Paragraph], _text_content: &TextContent, ) -> TextPositionWithAffinity { - // TODO: Implement proper line-based navigation using line metrics if paragraphs.is_empty() || cursor.paragraph >= paragraphs.len() { return *cursor; } @@ -231,21 +231,21 @@ pub fn move_cursor_down( } } -/// Move cursor to start of current line. +/// Move cursor to the start of its paragraph. Fallback of `caret_line_edge` +/// for text without a layout. pub fn move_cursor_line_start( cursor: &TextPositionWithAffinity, _paragraphs: &[Paragraph], ) -> TextPositionWithAffinity { - // TODO: Implement proper line-start using line metrics TextPositionWithAffinity::new_downstream_affinity(cursor.paragraph, 0) } -/// Move cursor to end of current line. +/// Move cursor to the end of its paragraph. Fallback of `caret_line_edge` +/// for text without a layout, and the target of Ctrl+End. pub fn move_cursor_line_end( cursor: &TextPositionWithAffinity, paragraphs: &[Paragraph], ) -> TextPositionWithAffinity { - // TODO: Implement proper line-end using line metrics let char_count = paragraph_char_count(¶graphs[cursor.paragraph]); TextPositionWithAffinity::new_downstream_affinity(cursor.paragraph, char_count) } diff --git a/render-wasm/src/wasm/text_editor.rs b/render-wasm/src/wasm/text_editor.rs index 6b9d9dc2cd..3f6994a6b3 100644 --- a/render-wasm/src/wasm/text_editor.rs +++ b/render-wasm/src/wasm/text_editor.rs @@ -693,6 +693,7 @@ pub extern "C" fn text_editor_move_cursor( get_text_editor_state().move_cursor( text_content, + shape, direction, word_boundary, extend_selection,