PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: keep line breaks when editing a multi-line paragraph (#1443) (#1486)
Raj Patela790a046a57e
diff --git a/ROADMAP.md b/ROADMAP.mdindex c7fc87944..6c41bce09 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -210,6 +210,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md- **2026-10-12 (M7, #1316):** Replacing a line or paragraph no longer removes a distinct neighbour whose glyph box overlaps the edited line. A second drawing is removed only when it also sits on the same baseline, so fake-bold and invisible copies still go. Synthetic regressions cover 6 pt leading, the same word on the next line, ordinary spacing, a separate paragraph, same-position copies, and incremental and full save/reopen. Estimates unchanged.- **2026-10-12 (M5, comment shortcuts):** Ctrl+Enter posts highlight comment text and replies; Shift+Enter adds a newline. Replies keep Enter-to-post, and floating comment composers only submit from their focused editor. Estimates unchanged.+- **2026-10-12 (M7, #1443):** Adding a word to a multi-line paragraph no longer reflows or merges its lines. Two causes: in Chrome- and Skia-made subset fonts, `/W` leaves out glyphs of the `/DW` width, which were treated as missing, so unchanged rows measured too wide and rewrapped (and new letters fell back to Helvetica); and lines drawn turned on the page (a landscape page drawn a quarter turn round) were compared along the page's x axis, so all of them became one line. Lines and rows are now found along each text's own baseline, a turned paragraph is rewritten in its own text space, and that rewrite keeps explicit line breaks. Formatting part of turned text is refused rather than misplaced. Synthetic regressions cover three turns and a default-width subset. Estimates unchanged.- **2026-10-12 (M1, #1339):** An incremental save of an unchanged classic-table file used to append `xref` and then `trailer` with no subsection, which qpdf reports as a damaged file. The section now has a zero-length subsection, so no object entry changes and a trailer-only edit is still written. Estimates unchanged.- **2026-10-12 (M12, auto-tag preview):** The engine and `accessibility_autotag_preview` propose paragraph and large-heading roles for bounded text blocks on one page, with locations and reasons. Every proposal needs review; images remain unclassified. No PDF tags are written yet. Synthetic tool tests cover normal text, a larger heading, bounds and unchanged source bytes. Estimates unchanged.- **2026-10-12 (M10, editing OCR text on scans):** Editing a recognised word on a scanned page now changes what the page shows. Before, the rewrite stayed invisible OCR text, so the scan still showed the old word; on a form, the whole OCR layer also grouped into one paragraph that rewrapped when one word changed. OCR words now group into phrases (a table cell or a tab stop splits them, and lines stay apart); an edit draws the phrase visibly in the scan's sampled ink colour over a cover in the sampled paper colour, keeping each word's width and growing rightwards. The editor covers the scanned word while typing. OCR words are now sized from their letters (a capitals-only word's box spans the cap height, not the full ascender-descender span), so recognised and rewritten text is as tall as the scanned word and sits on its baseline. Five engine tests on synthetic scans and a kittest UI test; `ocr.editable-text-output` is partial.diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex e4c49d741..aab8134bb 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3838,6 +3838,104 @@ fn subset_indic_font_without_legacy_name_keeps_logical_text() {assert_eq!(lines[0].text, "\u{092C}\u{0922}\u{093C}\u{093F}\u{092F}\u{093E}");}+/// Lines of a paragraph drawn turned on the page (a landscape page drawn a quarter turn round)+/// are separate rows, and adding a word keeps them apart (#1443).+#[test]+fn turned_paragraph_keeps_its_line_breaks_when_a_word_is_added() {+ for cm in ["0 1 -1 0 600 0", "0 -1 1 0 0 800", "-1 0 0 -1 600 800"] {+ let original =+ text_page(&format!("q {cm} cm BT /F1 12 Tf 72 500 Td (First line here) Tj 0 -14 Td (Second line) Tj 0 -14 Td (Third) Tj ET Q"));+ let block = text::text_blocks(&original, 0).unwrap().remove(0);+ assert_eq!(block.editor_text, "First line here\nSecond line\nThird", "{cm}");+ let mut doc = original.clone();+ text::rewrite_block(&mut doc, 0, 0, Some("First line here\nSecond line\nThird added"), &text::BlockStyle::default()).unwrap();+ let reopened = reopen(&doc);+ assert_eq!(text::text_blocks(&reopened, 0).unwrap()[0].editor_text, "First line here\nSecond line\nThird added", "{cm}");+ let (before, after) = (text::text_lines(&original, 0).unwrap(), text::text_lines(&reopened, 0).unwrap());+ assert_eq!(after.len(), 3, "{cm}");+ for (a, b) in after.iter().zip(&before).take(2) {+ assert!(close(a.rect, b.rect), "{cm}: untouched rows stay put: {:?} {:?}", a.rect, b.rect);+ }+ // The last row grows along its own baseline from where it started.+ let (grown, old) = (after[2].rect, before[2].rect);+ assert!((0..2).all(|i| grown[i] <= old[i] + 0.01) && (2..4).all(|i| grown[i] >= old[i] - 0.01), "{cm}: {grown:?} {old:?}");+ assert!((after[2].origin_baseline() - before[2].origin_baseline()).abs() < 0.01, "{cm}");+ }+ // A turned single line grows rather than wrapping across the page's other axis.+ let mut doc = text_page("BT /F1 12 Tf 0 1 -1 0 300 300 Tm (Only line) Tj ET");+ text::rewrite_block(&mut doc, 0, 0, Some("Only line with several more words added"), &text::BlockStyle::default()).unwrap();+ let blocks = text::text_blocks(&reopen(&doc), 0).unwrap();+ assert_eq!(blocks[0].editor_text, "Only line with several more words added");+ // Formatting part of turned text isn't laid out yet: refused, not drawn along the page's x axis.+ let mut doc = text_page("BT /F1 12 Tf 0 1 -1 0 300 300 Tm (Only line) Tj ET");+ let range = text::RangeStyle {+ range: 0..4,+ family: None,+ resource: None,+ size: Some(20.0),+ color: None,+ underline: None,+ char_spacing: None,+ scale: None,+ };+ let style = text::BlockStyle { ranges: vec![range], ..Default::default() };+ assert!(text::rewrite_block(&mut doc, 0, 0, Some("Only line"), &style).is_err());+}++/// A paragraph in a Chrome-style subset font: `/W` leaves out the glyphs of the `/DW` width.+/// Adding a word keeps every row as it was and shows the word in the page's own font (#1443).+#[test]+fn default_width_subset_paragraph_keeps_its_rows_when_a_word_is_added() {+ let hex = |s: &str| s.chars().map(|c| format!("00{:02X}", u32::from(c))).collect::<String>();+ let rows = ["This is the first line", "the second", "and third"];+ let content = rows+ .iter()+ .enumerate()+ .map(|(i, row)| format!("BT /F3 12 Tf 1 0 0 1 72 {} Tm <{}> Tj ET", 700 - 14 * i, hex(row)))+ .collect::<Vec<_>>()+ .join(" ");+ let mut doc = text_page(&content);+ let cmap = b"/CIDInit /ProcSet findresource begin 1 begincodespacerange <0000> <FFFF> endcodespacerange \+ 1 beginbfrange <0020> <007E> <0020> endbfrange end";+ let to_unicode = doc.add(Object::Stream(Stream::from_raw(Dict::new(), cmap.to_vec())));+ let mut cid = Dict::new();+ cid.set(b"Type".to_vec(), Object::name("Font"));+ cid.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));+ cid.set(b"BaseFont".to_vec(), Object::name("AAAAAA+LiberationSans"));+ cid.set(b"CIDToGIDMap".to_vec(), Object::name("Identity"));+ cid.set(b"DW".to_vec(), Object::Int(500));+ cid.set(+ b"W".to_vec(),+ Object::Array(vec![Object::Int(32), Object::Array(vec![Object::Int(278)]), Object::Int(84), Object::Array(vec![Object::Int(611)])]),+ );+ let mut font = Dict::new();+ font.set(b"Type".to_vec(), Object::name("Font"));+ font.set(b"Subtype".to_vec(), Object::name("Type0"));+ font.set(b"BaseFont".to_vec(), Object::name("AAAAAA+LiberationSans"));+ font.set(b"Encoding".to_vec(), Object::name("Identity-H"));+ font.set(b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid)]));+ font.set(b"ToUnicode".to_vec(), Object::Ref(to_unicode));+ let font = doc.add(Object::Dict(font));+ let page = pdfcraft_model::pages(&doc)[0].clone();+ let mut resources = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().unwrap().clone();+ let mut fonts = doc.resolve(resources.get(b"Font").unwrap()).as_dict().unwrap().clone();+ fonts.set(b"F3".to_vec(), Object::Ref(font));+ resources.set(b"Font".to_vec(), Object::Dict(fonts));+ doc.update_dict(page.obj, |d| d.set(b"Resources".to_vec(), Object::Dict(resources))).unwrap();+ let block = text::text_blocks(&doc, 0).unwrap().remove(0);+ assert_eq!(block.editor_text, rows.join("\n"));+ let before = text::text_lines(&doc, 0).unwrap();+ let edit = text::rewrite_block(&mut doc, 0, 0, Some(&format!("{} added", block.editor_text)), &text::BlockStyle::default()).unwrap();+ assert_eq!(edit.substituted, None, "the subset shows every letter of the new word");+ let reopened = reopen(&doc);+ assert_eq!(text::text_blocks(&reopened, 0).unwrap()[0].editor_text, "This is the first line\nthe second\nand third added");+ let after = text::text_lines(&reopened, 0).unwrap();+ for (a, b) in after.iter().zip(&before).take(2) {+ assert_eq!(a.text, b.text);+ assert!(close(a.rect, b.rect), "untouched rows keep their place and width: {:?} {:?}", a.rect, b.rect);+ }+}+/// An added item is written out as a specific standard-14 face (`/Times-Italic`, `/Helvetica-Bold`/// …), so it has to be *measured* with that same face. Measuring the upright face while writing/// the italic one mis-sizes every box: Times-Italic `A` is 611 against Times-Roman's 722.diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex 802e0a846..9c83cf9a3 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -450,6 +450,47 @@ impl TextLine {let m = Matrix(self.origin.tm).then(&Matrix(self.origin.ctm)).0;m[1].atan2(m[0]).to_degrees()}++ /// The unit direction its baseline runs in, in user space.+ fn direction(&self) -> (f64, f64) {+ direction(&Matrix(self.origin.tm).then(&Matrix(self.origin.ctm)))+ }++ /// Whether it reads left to right along the page's x axis (most text; a page drawn+ /// turned a quarter, as landscape pages often are, isn't).+ pub(crate) fn upright(&self) -> bool {+ let (x, y) = self.direction();+ (x - 1.0).abs() < 1e-3 && y.abs() < 1e-3+ }++ /// Where it starts as `(along, across)` its baseline: user space turned to the text's direction.+ fn frame_origin(&self) -> (f64, f64) {+ to_frame(self.direction(), (self.origin.x, self.origin.baseline))+ }++ /// Its box in the same frame, `[along0, across0, along1, across1]` (for upright text, `rect`).+ fn frame_rect(&self) -> [f64; 4] {+ let dir = self.direction();+ let r = self.rect;+ [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])]+ .into_iter()+ .map(|p| to_frame(dir, p))+ .fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)])+ }+}++/// The unit x axis of a text rendering matrix in user space (`(1, 0)` when it is degenerate).+fn direction(m: &Matrix) -> (f64, f64) {+ let (x, y) = (m.0[0], m.0[1]);+ let length = x.hypot(y);+ if length.is_finite() && length > 1e-9 { (x / length, y / length) } else { (1.0, 0.0) }+}++/// User-space point `p` as `(along, across)` a baseline running in unit direction `dir`. Upright+/// text (`dir` = `(1, 0)`) keeps its coordinates, so lines and rows of turned text are found the+/// same way (#1443).+fn to_frame(dir: (f64, f64), p: (f64, f64)) -> (f64, f64) {+ (p.0 * dir.0 + p.1 * dir.1, p.1 * dir.0 - p.0 * dir.1)}/// What replacing a line did.@@ -603,6 +644,7 @@ struct Shown {baseline: f64,start_x: f64,end_x: f64,+ end_y: f64,bt: usize,font: Vec<u8>,base_font: String,@@ -617,6 +659,43 @@ struct Shown {actual_text: bool,}+impl Shown {+ /// The unit direction of its baseline, where it starts and ends along it, and the baseline's+ /// offset across it (for upright text: the user-space x, x and y).+ fn span(&self) -> ((f64, f64), f64, f64, f64) {+ let dir = direction(&self.tm.then(&self.state.ctm));+ let (start, across) = to_frame(dir, (self.start_x, self.baseline));+ (dir, start, to_frame(dir, (self.end_x, self.end_y)).0, across)+ }+}++/// Where the previous run of a line ended: its text object, baseline direction, offset across+/// the baseline, end along it and size.+#[derive(Clone, Copy)]+struct Pen {+ bt: usize,+ dir: (f64, f64),+ across: f64,+ end: f64,+ size: f64,+}++impl Pen {+ fn after(s: &Shown) -> Self {+ let (dir, _, end, across) = s.span();+ Pen { bt: s.bt, dir, across, end, size: s.size.max(1.0) }+ }++ /// Whether `s` could continue the same line on geometry alone: on the same baseline, starting+ /// at most a word gap (`reach` sizes) after it. Also the gap along the baseline.+ fn continues(&self, s: &Shown, reach: f64) -> (bool, f64) {+ let (dir, start, _, across) = s.span();+ let gap = start - self.end;+ let same_dir = (dir.0 - self.dir.0).abs() < 1e-3 && (dir.1 - self.dir.1).abs() < 1e-3;+ (same_dir && (across - self.across).abs() < self.size * 0.3 && gap > -self.size && gap < self.size * reach, gap)+ }+}+/// The graphics state carried from one of a page's content streams to the next: the streams/// are one stream in pieces (§7.8.2), so a `cm` (AutoCAD scales the whole page in the first/// stream), an unbalanced `q`, the font and the colour still apply in the streams after it.@@ -705,6 +784,7 @@ fn interpret(first.text = logical;first.start_x = first.rect[0];first.end_x = first.rect[2];+ first.end_y = first.baseline;first.advance = (first.end_x - first.start_x) / first.tm.then(&first.state.ctm).0[0].abs().max(1e-6);out.push(first);}@@ -887,6 +967,7 @@ fn interpret(baseline: start.1,start_x: start.0,end_x: end.0,+ end_y: end.1,bt,font: name,base_font: m.base_font.clone(),@@ -923,7 +1004,7 @@ pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditErrolet pieces = Pieces::join(&content_streams(doc, &p.dict).into_iter().map(|(_, d)| d).collect::<Vec<_>>());let ops = pieces.parse().ops;let shown = interpret(doc, &ops, &fonts_res, &mut cache, &mut carry, None, true);- let mut last: Option<(usize, usize, f64, f64, f64)> = None; // (piece, bt, baseline, end_x, size)+ let mut last: Option<(usize, Pen)> = None; // the stream piece and where its last run endedfor mut s in shown {// A single RTL glyph's ActualText (e.g. lam-alef) is an inline ligature, not a// separate logical line. Put its letters into visual order before joining the@@ -936,7 +1017,9 @@ pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditErro// A line belongs to one stream piece. Within it, PDF producers often put every word// in its own BT/ET: geometry and text state, not object boundaries, define a line.let si = ops.get(s.op).map_or(0, |op| pieces.pieces_of(op).0);- let joins = last.is_some_and(|(piece, bt, base, end, size)| {+ let joins = last.is_some_and(|(piece, pen)| {+ let bt = pen.bt;+ let (near, gap) = pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 });piece == si&& lines.last().is_some_and(|l| l.scope == s.scope && l.logical_order == s.logical_order)&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))@@ -945,15 +1028,13 @@ pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditErro|| lines.last().is_some_and(|l| {(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color}))- && (s.baseline - base).abs() < size * 0.3- && s.start_x > end - size- && s.start_x - end < size * if bt == s.bt { 3.0 } else { 1.5 }+ && near// An OCR layer is one text object over the whole scan: its words continue a line// only across a word space, not across a table cell or a tab stop.- && (s.state.render_mode != 3 || s.start_x - end < size * 0.6)+ && (s.state.render_mode != 3 || gap < pen.size * 0.6)});if joins && let Some(l) = lines.last_mut() {- let gap = s.start_x - last.map_or(s.start_x, |x| x.3);+ let gap = last.map_or(0.0, |(_, pen)| pen.continues(&s, 0.0).1);if gap > l.size * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {l.text.push(' ');}@@ -998,7 +1079,7 @@ pub fn text_lines(doc: &Document, page: usize) -> Result<Vec<TextLine>, EditErro},});}- last = Some((si, s.bt, s.baseline, s.end_x, s.size.max(1.0)));+ last = Some((si, Pen::after(&s)));}// Content streams draw right-to-left lines in visual order; the editor works in typing order.for l in lines.iter_mut().filter(|l| !l.logical_order) {@@ -1028,8 +1109,9 @@ fn compatible_word(line: &TextLine, shown: &Shown) -> bool {/// The line `s` continues, or a new one: `last` is the previous run of the same stream/// (`bt`, baseline, end x, size).-fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<(usize, f64, f64, f64)>, s: Shown, stream: usize) {- let joins = last.is_some_and(|(bt, base, end, size)| {+fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream: usize) {+ let joins = last.is_some_and(|pen| {+ let bt = pen.bt;lines.last().is_some_and(|l| l.scope == s.scope && l.logical_order == s.logical_order)&& (bt == s.bt || lines.last().is_some_and(|l| compatible_word(l, &s)))&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, s.face.as_deref())))@@ -1037,12 +1119,10 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<(usize, f64, f64, f64)|| lines.last().is_some_and(|l| {(s.size - l.size).abs() < 0.01 && s.bold == l.bold && s.italic == l.italic && fill_color(&s.state.fill) == l.color}))- && (s.baseline - base).abs() < size * 0.3- && s.start_x > end - size- && s.start_x - end < size * if bt == s.bt { 3.0 } else { 1.5 }+ && pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }).0});if joins && let Some(l) = lines.last_mut() {- let gap = s.start_x - last.map_or(s.start_x, |x| x.2);+ let gap = last.map_or(0.0, |pen| pen.continues(&s, 0.0).1);if gap > l.size * 0.2 && !l.text.ends_with(' ') && !s.text.starts_with(' ') {l.text.push(' ');}@@ -1086,7 +1166,7 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<(usize, f64, f64, f64)},});}- *last = Some((s.bt, s.baseline, s.end_x, s.size.max(1.0)));+ *last = Some(Pen::after(&s));}/// How deep form XObjects nest before reading stops (they may also refer to themselves).@@ -1817,28 +1897,32 @@ fn paragraph_separator(c: char) -> bool {c.is_whitespace() && c != '\u{3000}'}-/// 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.+/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a+/// new line. 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()) {- 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;+ for row in text.split('\n') {+ let mut line = String::new();+ let start = out.len();+ for word in row.split(paragraph_separator).filter(|word| !word.is_empty()) {+ 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() {- out.push(line);+ if !line.is_empty() || out.len() == start {+ out.push(line);+ }}out}@@ -1938,8 +2022,15 @@ fn rewrite_block_from("formatting part of right-to-left (Hebrew) text, or choosing a document font for it, isn't supported yet".into(),));}+ // Text turned on the page (a landscape page drawn a quarter turn round) is rewritten in its+ // own text space below; the styled region path lays rows out along the page's x axis.+ let upright = members.iter().all(|line| line.upright());+ if !upright && (!style.ranges.is_empty() || style.resource.is_some()) {+ return Err(EditError::Invalid("formatting part of turned text, or choosing a document font for it, isn't supported yet".into()));+ }let visual_indic = members.iter().any(|line| line.visual_order);- if !hebrew+ if upright+ && !hebrew&& !visual_indic&& (!style.ranges.is_empty()|| style.resource.is_some()@@ -1959,7 +2050,15 @@ fn rewrite_block_from(let streams = content_streams(doc, &p.dict);let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());let ops = pieces.parse().ops;- let text = text.unwrap_or(&b.text).split(paragraph_separator).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" ");+ // Explicit line breaks stay (#1443); within a line, runs of white space become one space.+ let text = text+ .unwrap_or(&b.text)+ .split('\n')+ .map(|row| row.split(paragraph_separator).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" "))+ .collect::<Vec<_>>()+ .join("\n");+ // The characters to show, for choosing fonts: the breaks are moves, not glyphs.+ let flat = text.replace('\n', " ");let o = &first.origin;let (font_name, old_size) = o.state.font.clone().ok_or_else(|| EditError::Invalid("the paragraph has no font".into()))?;let k = o.k.max(1e-6);@@ -1976,7 +2075,7 @@ fn rewrite_block_from(let o_state = ts_state.clone();let metrics = fonts_res.get(font_name.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));let visual_indic = metrics.as_ref().is_some_and(|m| m.visual_order) || first.visual_order;- let indic_text = if visual_indic { crate::indic::to_visual(&text) } else { text.clone() };+ let indic_text = if visual_indic { crate::indic::to_visual(&flat) } else { flat.clone() };let reuse = style.family.is_none() && style.bold.is_none() && metrics.as_ref().is_some_and(|m| source_encodes(m, &indic_text));let space = metrics.as_ref().map_or(0.33, |m| source_space(doc, &fonts_res, m));// The chosen style also determines the real Japanese fallback outlines and advances.@@ -1991,14 +2090,22 @@ fn rewrite_block_from(}// Right-to-left text (more Hebrew or Arabic letters than Latin) is right-aligned unless an// alignment is asked for, and a single right-to-left line keeps its right edge as it grows.- let rtl = crate::bidi::rtl_base(&text);- let anchored_right = rtl && style.width.is_none() && members.len() == 1;+ let rtl = crate::bidi::rtl_base(&flat);+ let anchored_right = rtl && upright && style.width.is_none() && members.len() == 1;+ // The paragraph's width along its lines: in user space unless it is turned.+ let frame = if upright {+ b.rect+ } else {+ members.iter().map(|l| l.frame_rect()).reduce(|a, f| [a[0].min(f[0]), a[1].min(f[1]), a[2].max(f[2]), a[3].max(f[3])]).unwrap_or(b.rect)+ };// A paragraph keeps its width (or takes the one asked for); a single line grows to the right// (to the left when right-to-left), up to the page's margin.let width = match style.width {// Capped at the largest page PDF allows (14 400 pt).Some(w) if w.is_finite() => w.clamp(size * k, 14_400.0),Some(_) => return Err(EditError::Invalid("the paragraph's width must be a number".into())),+ // Turned text: the page's margins are along another axis. A single line grows (below).+ None if !upright => (frame[2] - frame[0]).max(size * k),None if anchored_right => (b.rect[2] - b.rect[0]).max(size * k).max(b.rect[2] + dx - (p.crop(doc)[0] + 36.0)),None if members.len() == 1 => (b.rect[2] - b.rect[0]).max(size * k).max(p.crop(doc)[2] - 36.0 - (b.rect[0] + dx)),None => (b.rect[2] - b.rect[0]).max(size * k),@@ -2021,7 +2128,7 @@ fn rewrite_block_from(} else {None};- let type3 = if !reuse && needs_type3(&text) { Some(type3_font(doc, &mut fonts_res, &text, family, bold, max_glyphs)?) } else { None };+ let type3 = if !reuse && needs_type3(&flat) { Some(type3_font(doc, &mut fonts_res, &flat, family, bold, max_glyphs)?) } else { None };let advance = |s: &str| -> f64 {let t = match (&metrics, reuse) {(Some(m), true) => {@@ -2042,6 +2149,13 @@ fn rewrite_block_from(};t * o_state.scale * k};+ // A turned single line grows to fit, as far as the largest page PDF allows.+ let width = if !upright && style.width.is_none() && members.len() == 1 {+ text.split('\n').map(&advance).fold(width, f64::max).min(14_400.0)+ } else {+ width+ };+ let right_edge = if anchored_right { right_edge } else { width };let wrapped = wrap(&text, width + 0.5, advance);let mut substituted = None;let new_font = !reuse;@@ -2053,11 +2167,11 @@ fn rewrite_block_from(let first = fallback.names.first().cloned().ok_or_else(no_japanese_font)?;(first, Box::new(move |s: &str| type3_encode(&fallback, s)))} else {- let win = pdfcraft_fonts::win_ansi(&text);+ let win = pdfcraft_fonts::win_ansi(&flat);let back: String = win.iter().map(|c| char::from_u32(u32::from(*c)).unwrap_or('?')).collect();let base = family.base_font(bold, italic);- if text.chars().zip(back.chars()).any(|(a, c)| c == '?' && a != '?') {- return Err(EditError::Invalid(format!("\"{text}\" has characters neither {} nor {base} can show", b.base_font)));+ if flat.chars().zip(back.chars()).any(|(a, c)| c == '?' && a != '?') {+ return Err(EditError::Invalid(format!("\"{flat}\" has characters neither {} nor {base} can show", b.base_font)));}let mut f = Dict::new();f.set(b"Type".to_vec(), Object::name("Font"));@@ -2075,7 +2189,16 @@ fn rewrite_block_from(// Line spacing in text space: the paragraph's own (scaled with the size), or 1.2 × the size.let lead = match style.line_spacing {Some(m) => size * m.clamp(0.5, 5.0),- None if members.len() > 1 => (members[0].origin.baseline - members[1].origin.baseline) / k * size / old_size,+ // From the first two rows (a row may hold several runs).+ None if let Some((upper, lower)) = b+ .rows+ .first()+ .zip(b.rows.get(1))+ .and_then(|(upper, lower)| upper.first().zip(lower.first()))+ .and_then(|(upper, lower)| lines.get(*upper).zip(lines.get(*lower))) =>+ {+ (upper.frame_origin().1 - lower.frame_origin().1) / k * size / old_size+ }None if o_state.leading > 0.0 => o_state.leading,None => size * 1.2,};diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex aec597088..0f6a25161 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -25,6 +25,12 @@ fn row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {row.iter().filter_map(|i| lines.get(*i)).map(|l| l.rect).reduce(union)}+/// [`row_rect`] in its text's own frame ([`TextLine::frame_rect`]), so rows of turned text+/// compare along and across their baselines.+fn frame_row_rect(row: &[usize], lines: &[TextLine]) -> Option<[f64; 4]> {+ row.iter().filter_map(|i| lines.get(*i)).map(TextLine::frame_rect).reduce(union)+}+pub(super) fn group_blocks(lines: &[TextLine]) -> Vec<TextBlock> {group_layout(lines, true)}@@ -62,14 +68,14 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {let mut rows: Vec<Vec<usize>> = Vec::new();for (i, line) in lines.iter().enumerate() {let joins = rows.last().and_then(|r| r.last()).and_then(|i| lines.get(*i)).is_some_and(|prev| {- let gap = line.rect[0] - prev.rect[2];+ let gap = line.frame_rect()[0] - prev.frame_rect()[2];// OCR words (invisible text over a scan) join only across a word space: a wider gap// is a table cell or a tab stop, which a rewrite would close up.let scanned = !mixed || (invisible(prev) == invisible(line) && (!invisible(line) || gap < prev.size.max(line.size) * 0.6));scanned&& (mixed || same_style(prev, line))&& same_plane(prev, line)- && (prev.origin.baseline - line.origin.baseline).abs() < prev.size.min(line.size) * 0.2+ && (prev.frame_origin().1 - line.frame_origin().1).abs() < prev.size.min(line.size) * 0.2&& gap >= -prev.size.min(line.size) * 0.2&& gap < prev.size.max(line.size) * 1.5// Separate same-style text objects that merely touch or overlap, with no space@@ -90,14 +96,15 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {let mut blocks: Vec<TextBlock> = Vec::new();for row in rows {let Some(first) = row.first().and_then(|i| lines.get(*i)) else { continue };- let Some(rect) = row_rect(&row, lines) else { continue };+ let (Some(rect), Some(frame)) = (row_rect(&row, lines), frame_row_rect(&row, lines)) else { continue };let joins = blocks.last().is_some_and(|block| {let Some(prev_row) = block.rows.last() else { return false };let Some(prev) = prev_row.first().and_then(|i| lines.get(*i)) else { return false };- let Some(pr) = row_rect(prev_row, lines) else { return false };- let gap = prev.origin.baseline - first.origin.baseline;+ let Some(pr) = frame_row_rect(prev_row, lines) else { return false };+ let gap = prev.frame_origin().1 - first.frame_origin().1;let tol = prev.size.max(first.size).max(1.0);- let aligned = (pr[0] - rect[0]).abs() < tol || ((pr[0] + pr[2] - rect[0] - rect[2]) / 2.0).abs() < tol || (pr[2] - rect[2]).abs() < tol;+ let aligned =+ (pr[0] - frame[0]).abs() < tol || ((pr[0] + pr[2] - frame[0] - frame[2]) / 2.0).abs() < tol || (pr[2] - frame[2]).abs() < tol;// OCR lines stay apart: the scan fixes where each one is, so they never rewrap together.(!mixed || !(invisible(prev) || invisible(first)))&& (mixed || same_style(prev, first))@@ -135,7 +142,7 @@ fn group_layout(lines: &[TextLine], mixed: bool) -> Vec<TextBlock> {if let Some(prev) = block.lines.last().filter(|i| row.contains(i)).and_then(|i| lines.get(*i))&& !row_text.ends_with(char::is_whitespace)&& !line.text.starts_with(char::is_whitespace)- && line.rect[0] - prev.rect[2] > line.size * 0.12+ && line.frame_rect()[0] - prev.frame_rect()[2] > line.size * 0.12{row_text.push(' ');block.editor_text.push(' ');diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rsindex 122678a92..3ad34eead 100644--- a/crates/fonts/src/pdf.rs+++ b/crates/fonts/src/pdf.rs@@ -37,6 +37,9 @@ pub struct Metrics {/// Code → CID for embedded non-identity CMaps (`cidrange` / `cidchar`).cid_map: Vec<(u32, u32, u32)>,default: f64,+ /// Composite fonts with an explicit `/DW`: `/W` may leave out the glyphs that have that+ /// width (Chrome and Skia do), so a CID missing from `/W` is not a missing glyph.+ explicit_default: bool,/// The standard-14 face to measure with when the dictionary carries no `/Widths`.std14: Option<crate::Std14>,/// Glyph units → text space (0.001, or `/FontMatrix[0]` for Type 3).@@ -560,6 +563,7 @@ impl Metrics {cid_ranges: Vec::new(),cid_map: Vec::new(),default: 500.0,+ explicit_default: false,std14: Some(crate::Std14::Helvetica),scale: 0.001,ascent: 0.9,@@ -650,6 +654,7 @@ impl Metrics {.unwrap_or_default();if let Some(dw) = desc.get(b"DW").and_then(|d| doc.resolve(d).as_f64()) {m.default = dw;+ m.explicit_default = true;}if let Some(w) = desc.get(b"W").map(|w| doc.resolve(w)).and_then(|w| w.as_array().cloned()) {let mut i = 0;@@ -788,6 +793,8 @@ impl Metrics {}/// Whether the font has a glyph for `code` (subset fonts lack the glyphs they don't use).+ /// Only asked for codes the font's Unicode mapping gives: a subset's `ToUnicode` lists the+ /// glyphs it kept, while its `/W` leaves out those of the default width (#1443).fn has_glyph(&self, code: u32) -> bool {if self.composite {let cid = self.cid(code);@@ -796,7 +803,10 @@ impl Metrics {return self.cid_widths.contains_key(&cid)|| self.cid_ranges.iter().any(|(a, b, _)| cid >= *a && cid <= *b)|| !self.subset- || self.outlined_cids.get(cid as usize / 64).is_some_and(|w| (*w >> (cid % 64)) & 1 == 1);+ || self.outlined_cids.get(cid as usize / 64).is_some_and(|w| (*w >> (cid % 64)) & 1 == 1)+ // No readable TrueType program to ask (e.g. CFF or missing): an explicit /DW+ // still says /W may leave out glyphs of that width (#1443).+ || (self.outlined_cids.is_empty() && self.explicit_default);}match code.checked_sub(self.first).and_then(|i| self.widths.get(i as usize)) {Some(w) => *w > 0.0 || code == 32,@@ -1374,6 +1384,48 @@ mod tests {assert_eq!(m.encode("Z"), None);}+ /// Chrome's subsets leave the glyphs of `/DW` width out of `/W` (#1443): "s" (CID 0x56) is+ /// still in the font, but nothing is when the font gives no default width to point at.+ #[test]+ fn composite_subset_glyphs_of_the_default_width_are_present() {+ let metrics = |dw: bool| {+ let mut doc = Document::new_empty();+ let cmap = b"/CIDInit /ProcSet findresource begin 1 begincodespacerange <0000> <FFFF> endcodespacerange \+ 1 beginbfrange <0055> <0057> <0072> endbfrange end";+ let tu = doc.add(Object::Stream(Stream::from_raw(Dict::new(), cmap.to_vec())));+ let mut desc = Dict::new();+ desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));+ if dw {+ desc.set(b"DW".to_vec(), Object::Int(500));+ }+ desc.set(+ b"W".to_vec(),+ Object::Array(vec![+ Object::Int(0x55),+ Object::Array(vec![Object::Int(333)]),+ Object::Int(0x57),+ Object::Array(vec![Object::Int(277)]),+ ]),+ );+ let f = font(+ &mut doc,+ vec![+ ("Subtype", Object::name("Type0")),+ ("BaseFont", Object::name("AAAAAA+LiberationSans")),+ ("Encoding", Object::name("Identity-H")),+ ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),+ ("ToUnicode", Object::Ref(tu)),+ ],+ );+ Metrics::from_dict(&doc, &f)+ };+ let chrome = metrics(true);+ assert_eq!(chrome.encode("rst").as_deref(), Some(&[0, 0x55, 0, 0x56, 0, 0x57][..]));+ assert_eq!(chrome.width(0x56), 0.5);+ assert_eq!(chrome.encode("x"), None, "a character the ToUnicode map doesn't give");+ assert_eq!(metrics(false).encode("s"), None);+ }+/// A `/W` run that starts at the last CID stops there instead of overflowing onto CID 0.#[test]fn composite_width_run_past_the_last_cid_is_dropped() {diff --git a/docs/roadmap.md b/docs/roadmap.mdindex a51e6c902..01ba25378 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -179,6 +179,7 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st| Date | Change | Summary ||---|---|---|| 2026-10-12 | minor | M1 #1338: a full rewrite keeps unknown trailer entries and objects reachable only from them. Estimates unchanged. |+| 2026-10-12 | minor | M7 #1443: adding a word to a multi-line paragraph keeps its line breaks. Composite subset fonts whose `/W` leaves out default-width glyphs (Chrome, Skia) no longer measure those letters as missing, and paragraphs drawn turned on the page group into rows along their own baselines. Estimates unchanged. || 2026-10-14 | minor | M14: Italian catalog completed (2,528 entries) and dropped from the ≈ 2,000–2,140-entry group; estimates unchanged || 2026-10-12 | minor | M4 #1310 #1311 #1312: undo back to the opened file is clean, Revert returns to the last saved file, and the next save keeps that revision. Estimates unchanged. || 2026-10-14 | minor | M5: reconciled PR #1457 with upstream main, preserving comment submission shortcuts and upstream roadmap progress. Estimates unchanged. |