PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: rewrap Chinese and Japanese text between characters (#1827)
komo1iddinb18639c24233
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex 336e948ae..0fb7e3eee 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -633,6 +633,7 @@ pub mod images;pub use images::{ImageChange, PageImage, change_image, page_images, reading_images, rect_to_rect, turn_about_centre};pub mod bidi;pub mod indic;+mod linebreak;pub mod text;pub use text::{BlockStyle, LineEdit, RangeStyle, TextBlock, TextLine, clear_block, reading_blocks, replace_block, replace_line, rewrite_block, text_blocks,diff --git a/crates/edit/src/linebreak.rs b/crates/edit/src/linebreak.rsnew file mode 100644index 000000000..a4682679f--- /dev/null+++ b/crates/edit/src/linebreak.rs@@ -0,0 +1,124 @@+//! Where a row of rewrapped text may end besides a space: between two characters when either is+//! written without spaces between words (Chinese and Japanese ideographs and kana), following the+//! simple cases of Unicode line breaking (UAX #14, class ID). The row must not then begin with a+//! character that closes or follows (closing brackets and quotes, commas and full stops, small+//! kana, the prolonged sound mark, iteration marks) or end with one that opens (opening brackets+//! and quotes, currency signs before an amount): the line-start and line-end prohibitions of+//! JIS X 4051 ("kinsoku"), which UAX #14 gives as classes CL, CP, EX, IS, NS and OP, PR.+//!+//! Korean is written with spaces between words and keeps breaking only there; so does Thai, whose+//! words need a dictionary to find.++/// Writing with no spaces between words, where a row may end between two characters (UAX #14 ID).+fn ideographic(c: char) -> bool {+ matches!(c,+ '\u{2e80}'..='\u{2fdf}' // CJK radicals, Kangxi radicals+ | '\u{3000}'..='\u{303f}' // CJK symbols and punctuation+ | '\u{3040}'..='\u{30ff}' // hiragana, katakana+ | '\u{3190}'..='\u{31ff}' // kanbun, CJK strokes, katakana phonetic extensions+ | '\u{3400}'..='\u{4dbf}' // CJK extension A+ | '\u{4e00}'..='\u{9fff}' // CJK unified ideographs+ | '\u{f900}'..='\u{faff}' // CJK compatibility ideographs+ | '\u{fe30}'..='\u{fe4f}' // CJK compatibility forms+ | '\u{ff00}'..='\u{ffef}' // half-width and full-width forms+ | '\u{20000}'..='\u{3fffd}' // supplementary ideographic planes+ )+}++/// Characters that must not begin a row: closing brackets and quotes, and the punctuation, small+/// kana and marks that belong to the character before them (UAX #14 CL, CP, EX, IS, NS). The+/// ideographic space breaks after itself, not before (BA): it is Japanese spacing and indentation.+fn no_start(c: char) -> bool {+ matches!(c,+ ')' | ']' | '}' | '»' | '’' | '”' | '!' | '?' | ',' | '.' | ':' | ';' | '%' | '‰' | '°' | '℃'+ | '‐' | '–' | '〜' | '‼' | '⁇' | '⁈' | '⁉' | '・' | '\u{3000}'+ | '、' | '。' | '〃' | '〆' | '々' | '〻' | '〕' | '〉' | '》' | '」' | '』' | '】' | '〙' | '〗' | '〟' | '〞'+ | 'ぁ' | 'ぃ' | 'ぅ' | 'ぇ' | 'ぉ' | 'っ' | 'ゃ' | 'ゅ' | 'ょ' | 'ゎ' | 'ゕ' | 'ゖ'+ | 'ァ' | 'ィ' | 'ゥ' | 'ェ' | 'ォ' | 'ッ' | 'ャ' | 'ュ' | 'ョ' | 'ヮ' | 'ヵ' | 'ヶ'+ | '゛' | '゜' | 'ゝ' | 'ゞ' | '゠' | 'ー' | 'ヽ' | 'ヾ'+ | '\u{31f0}'..='\u{31ff}' // small katakana for Ainu+ | '!' | '%' | ')' | ',' | '.' | ':' | ';' | '?' | ']' | '}' | '⦆' | '~'+ | '。' | '」' | '、' | '・' | 'ー' | '゙' | '゚'+ | '\u{ff67}'..='\u{ff6f}' // small half-width katakana+ )+}++/// Characters that must not end a row: opening brackets and quotes, and currency signs written+/// before an amount (UAX #14 OP, PR).+fn no_end(c: char) -> bool {+ matches!(+ c,+ '(' | '['+ | '{'+ | '«'+ | '‘'+ | '“'+ | '$'+ | '£'+ | '¥'+ | '€'+ | '〈'+ | '《'+ | '「'+ | '『'+ | '【'+ | '〔'+ | '〖'+ | '〘'+ | '〝'+ | '('+ | '['+ | '{'+ | '⦅'+ | '「'+ | '$'+ | '£'+ | '¥'+ )+}++/// Whether a row may end between `before` and `after`, neither of them a space.+pub(crate) fn between(before: char, after: char) -> bool {+ (ideographic(before) || ideographic(after)) && !no_start(after) && !no_end(before)+}++/// `word` (text without spaces) cut where a row may end inside it; the pieces join with nothing.+pub(crate) fn pieces(word: &str) -> Vec<&str> {+ let mut out = Vec::new();+ let mut start = 0;+ let mut prev: Option<char> = None;+ for (at, c) in word.char_indices() {+ if let Some(before) = prev+ && between(before, c)+ {+ out.extend(word.get(start..at));+ start = at;+ }+ prev = Some(c);+ }+ out.extend(word.get(start..).filter(|rest| !rest.is_empty()));+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn ideographs_and_kana_break_between_characters_except_around_kinsoku_marks() {+ assert_eq!(pieces("日本語の文章"), ["日", "本", "語", "の", "文", "章"]);+ // Closing punctuation and small kana stay with the character before them; an opening+ // bracket stays with the one after it.+ assert_eq!(pieces("ちょっと、「はい」。"), ["ちょっ", "と、", "「は", "い」。"]);+ assert_eq!(pieces("コーヒー"), ["コー", "ヒー"]);+ assert_eq!(pieces("(例)です"), ["(例)", "で", "す"]);+ // Latin text inside a Japanese sentence breaks before and after it, never inside it.+ assert_eq!(pieces("PDFを編集"), ["PDF", "を", "編", "集"]);+ assert_eq!(pieces("価格は¥100です"), ["価", "格", "は", "¥100", "で", "す"]);+ // Words of space-separated writing are never cut.+ assert_eq!(pieces("wrapping"), ["wrapping"]);+ assert_eq!(pieces("한국어"), ["한국어"]);+ assert_eq!(pieces(""), Vec::<&str>::new());+ assert!(!between('a', 'b') && between('字', 'a') && !between('字', '。') && !between('「', '字'));+ }+}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex e72af1acc..9f99349b8 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3742,3 +3742,25 @@ fn draft_layout_matches_the_paragraph_an_applied_edit_draws() {assert_eq!(layout.source_rect, source.rect);}}++#[test]+fn japanese_paragraphs_wrap_between_characters_without_closing_marks_at_a_row_start() {+ if pdfcraft_fonts::document_japanese_font().is_none() {+ eprintln!("skipping the Japanese wrapping checks: built without craft-fonts (set CRAFT_FONTS_DIR)");+ return;+ }+ let text = "日本語の文章は単語の間に空白がないので、どの文字の間でも行を折り返せます。ただし「句読点」や小さい「っ」は行頭に来ません。";+ // One paragraph (the single-style path), and a heading row before it (the row editor's path).+ for draft in [text.to_string(), format!("見出し\n{text}")] {+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Placeholder text) Tj ET");+ text::rewrite_block(&mut doc, 0, 0, Some(&draft), &text::BlockStyle { width: Some(120.0), ..Default::default() }).unwrap();+ let block = text::text_blocks(&reopen(&doc), 0).unwrap().remove(0);+ let rows: Vec<&str> = block.editor_text.split('\n').collect();+ assert!(rows.len() > 4, "{rows:?}");+ assert_eq!(rows.concat(), draft.replace('\n', ""), "no space is added between the pieces");+ assert!(block.rect[2] - block.rect[0] <= 120.5, "{:?} {rows:?}", block.rect);+ for row in &rows {+ assert!(!row.starts_with(['、', '。', '」', 'っ']) && !row.ends_with('「'), "{row:?} in {rows:?}");+ }+ }+}diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex 07ce62ade..8fa394194 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -1652,17 +1652,24 @@ fn paragraph_separator(c: char) -> bool {c.is_whitespace() && c != '\u{3000}'}-/// Greedy word wrapping to `width` with `advance` giving a string's width.+/// Greedy word wrapping to `width` with `advance` giving a string's width. A row may also end+/// inside a word of Chinese or Japanese text ([`crate::linebreak`]); those pieces join without a space.fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {let mut out = Vec::new();let mut line = String::new();for word in text.split(paragraph_separator).filter(|word| !word.is_empty()) {- let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };- if !line.is_empty() && advance(&candidate) > width {- out.push(std::mem::take(&mut line));- line = word.to_string();- } else {- line = candidate;+ for (i, piece) in crate::linebreak::pieces(word).into_iter().enumerate() {+ let candidate = match (line.is_empty(), i) {+ (true, _) => piece.to_string(),+ (false, 0) => format!("{line} {piece}"),+ (false, _) => format!("{line}{piece}"),+ };+ if !line.is_empty() && advance(&candidate) > width {+ out.push(std::mem::take(&mut line));+ line = piece.to_string();+ } else {+ line = candidate;+ }}}if !line.is_empty() || out.is_empty() {@@ -2260,6 +2267,17 @@ mod tests {assert_eq!(wrap(" \tA B\r\nC ", 3.0, width), ["A B", "C"]);}+ #[test]+ fn japanese_text_wraps_between_characters_but_not_before_closing_marks() {+ let width = |s: &str| s.chars().count() as f64;+ assert_eq!(wrap("日本語の文章です。", 3.0, width), ["日本語", "の文章", "です。"]);+ // The comma can't begin a row, so the character before it moves down with it.+ assert_eq!(wrap("あいう、えお", 3.0, width), ["あい", "う、え", "お"]);+ // Pieces of one word join without a space; separate words keep theirs.+ assert_eq!(wrap("Edit PDFを編集", 6.0, width), ["Edit", "PDFを編集"]);+ assert_eq!(wrap("一行目 二行目", 4.0, width), ["一行目 ", "二行目"]);+ }+#[test]fn fallback_face_moves_on_when_the_best_face_lacks_a_character() {static JPAN: &[&str] = &["Jpan"];diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 59e160702..aec597088 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -571,7 +571,11 @@ pub(super) fn rewrite_styled_block(}let mut end = at + 1;if !item.0.is_whitespace() {- while chars.get(end).is_some_and(|c| !c.0.is_whitespace()) {+ // A word ends at a space, or where Chinese or Japanese text may break between characters.+ while let (Some(before), Some(c)) = (chars.get(end - 1), chars.get(end))+ && !c.0.is_whitespace()+ && !crate::linebreak::between(before.0, c.0)+ {end += 1;}}diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.mdindex 9708cf17e..233e5ac59 100644--- a/docs/editing-existing-text.md+++ b/docs/editing-existing-text.md@@ -31,6 +31,13 @@ this works only when that build input actually contains the full face. This chanadd a font binary or change the release font pin. Fonts shared by releases belong in`storytold/craft-fonts` under the repository's asset rules.+Rewrapped Chinese and Japanese text, which has no spaces between words, may break between any+two characters. A row never begins with closing punctuation, a closing bracket or quote, a small+kana or the prolonged sound mark, and never ends with an opening bracket or quote or a currency+sign before an amount: the line-start and line-end rules of JIS X 4051, as in Unicode line+breaking (UAX #14). Latin words inside such text are not split. Korean and Thai still break only+at spaces.+Select text within the editor before changing size, colour, font, underline or spacing toformat that selection. Automation supports up to 1024 disjoint UTF-8 byte ranges with thesame properties; invalid or overlapping ranges fail atomically. Untouched source formatting