PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Edit text: per-run q/Q, /LW from gs, and a Tr partway through a line starts a run (#3508, #3509)
luis.pereira9163f29090c3
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 7b46cdfc2..20a6a7b64 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -6573,8 +6573,8 @@ fn a_flatten_refused_on_a_later_page_changes_nothing() {}/// How each glyph-showing operator on page 0 is painted, read the way a renderer reads the page:-/// its text, `Tr`, stroke colour operators, line width and the ExtGStates selected before it,-/// following `q`/`Q`.+/// its text, `Tr`, stroke colour operators, line width (from `w` or an ExtGState's `/LW`) and+/// the ExtGStates selected before it, following `q`/`Q`.#[derive(Clone, Debug, PartialEq)]struct Painted {text: String,@@ -6586,6 +6586,9 @@ struct Painted {fn painted_shows(doc: &Document) -> Vec<Painted> {let (_, ops) = joined_ops(doc);+ let p = &pdfcraft_model::pages(doc)[0];+ let res = doc.resolve(p.dict.get(b"Resources").unwrap());+ let ext = res.as_dict().unwrap().get(b"ExtGState").map(|g| doc.resolve(g).as_dict().cloned().unwrap()).unwrap_or_default();let mut state = Painted { text: String::new(), render_mode: 0, stroke: Vec::new(), line_width: 1.0, gs: Vec::new() };let mut stack = Vec::new();let mut out = Vec::new();@@ -6598,7 +6601,12 @@ fn painted_shows(doc: &Document) -> Vec<Painted> {b"G" | b"RG" | b"K" | b"CS" => state.stroke = vec![show(&op)],b"SC" | b"SCN" => state.stroke.push(show(&op)),b"w" => state.line_width = op.num(0).unwrap(),- b"gs" => state.gs.push(String::from_utf8_lossy(op.name(0).unwrap()).into_owned()),+ b"gs" => {+ let name = op.name(0).unwrap();+ state.gs.push(String::from_utf8_lossy(name).into_owned());+ let lw = ext.get(name).and_then(|g| doc.resolve(g).as_dict().and_then(|g| g.get(b"LW")).and_then(|w| w.as_f64()));+ state.line_width = lw.unwrap_or(state.line_width);+ }b"Tj" => {let Some(Object::String(s)) = op.operands.last() else { continue };if !s.bytes.is_empty() {@@ -6611,15 +6619,18 @@ fn painted_shows(doc: &Document) -> Vec<Painted> {out}-/// A page with Helvetica as /F1 and /GS1, an ExtGState that paints at 20 % opacity.+/// A page with Helvetica as /F1, /GS1, an ExtGState that paints at 20 % opacity, /GS2, one that+/// sets the line width to 4, and /GS3, another at 20 % opacity.fn faint_page(content: &str) -> Document {build(&["<< /Type /Catalog /Pages 2 0 R >>","<< /Type /Pages /Kids [3 0 R] /Count 1 >>",- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /ExtGState << /GS1 6 0 R >> >> >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /ExtGState << /GS1 6 0 R /GS2 7 0 R /GS3 8 0 R >> >> >>",&format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>","<< /Type /ExtGState /ca 0.2 >>",+ "<< /Type /ExtGState /LW 4 >>",+ "<< /Type /ExtGState /ca 0.2 >>",])}@@ -6678,3 +6689,80 @@ fn a_styled_rewrite_keeps_the_paint_state_set_inside_the_text_object() {assert_eq!(s.gs, ["GS1"], "{s:?}: {joined}");}}++/// A `gs` has no inverse, so one run's ExtGState stayed in force for the runs the styled rewrite+/// drew after it. Two ExtGStates at the same opacity paint the same (see `Paint`), so their runs+/// share a paragraph, but either may set what that doesn't compare (a dash, a line cap): each run+/// is drawn with only the ones its source selected.+#[test]+fn a_styled_rewrite_does_not_carry_one_runs_extgstate_into_the_next() {+ // "FAI" ends at 40 + 72 * (0.611 + 0.667 + 0.278) = 152.032; "NT" is blue, so another run.+ let content = "q BT /GS3 gs /F1 72 Tf 40 400 Td (FAI) Tj ET Q BT /GS1 gs /F1 72 Tf 0 0 1 rg 152.032 400 Td (NT) Tj ET+";+ for new in ["FAINT", "FAINTS"] {+ let mut doc = faint_page(content);+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ let shows = painted_shows(&doc);+ let joined = streams(&doc, 0).join(+ "+",+ );+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");+ let gs: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.gs.as_slice())).collect();+ assert_eq!(gs.first(), Some(&("FAI", ["GS3".to_string()].as_slice())), "{gs:?}: {joined}");+ assert!(gs.iter().skip(1).all(|(_, gs)| *gs == ["GS1"]), "{gs:?}: {joined}");+ }+}++/// An ExtGState's `/LW` sets the line width as `w` does: `2 w /GS2 gs` (`/LW 4`) outlines at 4,+/// and the rewrite replayed `/GS2 gs` and then `2 w`. `/GS2 gs 1 w` outlines at 1, and the+/// rewrite replayed only `/GS2 gs`, since 1 is the initial width.+#[test]+fn a_rewritten_paragraph_keeps_the_line_width_an_extgstate_set() {+ for (content, width) in [+ ("BT /F1 72 Tf 1 Tr 2 w /GS2 gs 40 400 Td (OUTLINE) Tj ET\n", 4.0),+ ("BT /F1 72 Tf 1 Tr /GS2 gs 2 w 40 400 Td (OUTLINE) Tj ET\n", 2.0),+ ("BT /F1 72 Tf 1 Tr /GS2 gs 1 w 40 400 Td (OUTLINE) Tj ET\n", 1.0),+ ] {+ assert_eq!(painted_shows(&faint_page(content))[0].line_width, width, "the fixture: {content}");+ for new in ["OUTLINE", "OUTLINED"] {+ let mut doc = faint_page(content);+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ let shows = painted_shows(&doc);+ assert_eq!(+ shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.line_width)).collect::<Vec<_>>(),+ [(new, 1, width)],+ "{content} -> {new}: {}",+ streams(&doc, 0).join("\n")+ );+ }+ }+}++/// A line is rewritten in the state of its first run, so outline text partway through a text+/// object came back filled: "FAI" filled and "NT" a red outline came back all filled. The change+/// of `Tr` now starts a run. (A `gs` partway already starts a paragraph; see `Paint`.)+#[test]+fn a_rendering_mode_partway_through_a_line_starts_a_run_of_its_own() {+ let content = "BT /F1 72 Tf 40 400 Td (FAI) Tj 1 Tr 1 0 0 RG 2 w (NT) Tj ET+";+ for new in ["FAINT", "FAINTS"] {+ let mut doc = faint_page(content);+ assert_eq!(text::text_blocks(&doc, 0).unwrap()[0].rows[0].len(), 2, "two runs on one row");+ text::rewrite_block(&mut doc, 0, 0, Some(new), &BlockStyle::default()).unwrap();+ let doc = reopen(&doc);+ let shows = painted_shows(&doc);+ let joined = streams(&doc, 0).join(+ "+",+ );+ assert_eq!(shows.iter().map(|s| s.text.as_str()).collect::<String>(), new, "{joined}");+ let modes: Vec<_> = shows.iter().map(|s| (s.text.as_str(), s.render_mode, s.stroke.as_slice(), s.line_width)).collect();+ assert_eq!(modes.first().map(|m| (m.0, m.1)), Some(("FAI", 0)), "{modes:?}: {joined}");+ let outline = ["1 0 0 RG".to_string()];+ assert!(modes.iter().skip(1).all(|m| (m.1, m.2, m.3) == (1, outline.as_slice(), 2.0)), "{modes:?}: {joined}");+ }+}diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex 601970c4d..faa69c95a 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -255,6 +255,9 @@ impl TextState {////// Only fill, stroke and fill-then-stroke (`Tr` 0–2) are restated: invisible text is revealed/// by [`reveal_ops`] and clipping text is refused, so neither is ever drawn this way.+ ///+ /// A `gs` has no inverse, so a selection `current` has and this state doesn't stays in force:+ /// run these inside a `q`/`Q` that starts from `current`, one per state drawn.fn paint_ops(&self, current: &TextState) -> Vec<Op> {let n = pdfcraft_content::num;let mut v = Vec::new();@@ -263,6 +266,8 @@ impl TextState {for name in self.ext_gstate.iter().skip(shared) {v.push(Op::new("gs", vec![Object::Name(name.clone())]));}+ // A reselected ExtGState may set `/LW`, so the width (already the effective one) follows it.+ let reselected = !v.is_empty();if self.stroke != current.stroke {if self.stroke.is_empty() {// The initial stroke colour: black in DeviceGray.@@ -272,7 +277,7 @@ impl TextState {}}let width = self.line_width.unwrap_or(1.0);- if width != current.line_width.unwrap_or(1.0) {+ if reselected || width != current.line_width.unwrap_or(1.0) {v.push(Op::new("w", vec![n(width)]));}if (0..=2).contains(&self.render_mode) && self.render_mode != current.render_mode {@@ -660,7 +665,7 @@ struct Ts {unreadable: Option<Rc<str>>,/// The operators that set the current stroke colour (`G`, `RG`, `K`, or `CS` + `SC`/`SCN`).stroke: Vec<Op>,- /// The line width a `w` set (`None`: the initial 1.0).+ /// The line width a `w` or an ExtGState's `/LW` set (`None`: the initial 1.0).line_width: Option<f64>,/// The ExtGState resources selected with `gs`, oldest first (see [`select_gs`]).ext_gstate: Vec<Vec<u8>>,@@ -1147,6 +1152,9 @@ fn interpret(let params = op.name(0).and_then(|name| states.get(name)).map(|p| doc.resolve(p));if let Some(params) = params.as_deref().and_then(Object::as_dict) {ts.gs.apply(doc, params);+ // `/LW` sets the line width as `w` does (ISO 32000-2 §8.4.5).+ let lw = params.get(b"LW").and_then(|w| doc.resolve(w).as_f64()).filter(|w| w.is_finite());+ ts.line_width = lw.or(ts.line_width);}}b"Do" => {@@ -1426,7 +1434,11 @@ fn text_lines_in(doc: &Document, p: &pdfcraft_model::Page, actual_text: bool) ->&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))&& (s.text.trim().is_empty()|| 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.size - l.size).abs() < 0.01+ && s.bold == l.bold+ && s.italic == l.italic+ && fill_color(&s.state.fill) == l.color+ && same_paint(l, &s.state)}))&& near// An OCR layer is one text object over the whole scan: its words continue a line@@ -1532,7 +1544,11 @@ fn add_shown(lines: &mut Vec<TextLine>, last: &mut Option<Pen>, s: Shown, stream&& (s.text.trim().is_empty() || lines.last().is_some_and(|l| same_font(l, &s.font, &s.base_font, s.face.as_deref())))&& (s.text.trim().is_empty()|| 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.size - l.size).abs() < 0.01+ && s.bold == l.bold+ && s.italic == l.italic+ && fill_color(&s.state.fill) == l.color+ && same_paint(l, &s.state)}))&& pen.continues(&s, if bt == s.bt { 3.0 } else { 1.5 }).0});@@ -1892,6 +1908,26 @@ fn same_font(line: &TextLine, font: &[u8], base_font: &str, face: Option<&str>)line.font.as_bytes() == font || same_base_font(&line.base_font, base_font) || (line.face.is_some() && line.face.as_deref() == face)}+/// Whether a run painted with `ts` continues `line` as it is painted: a line is rewritten in the+/// state of its first run, so a `Tr`, stroke colour or line width that changes partway starts+/// another run (see [`TextState::paint_ops`]; the `gs` parameters are compared as [`Paint`]).+/// The stroke colour and width only count for text that is stroked, so a rule drawn between two+/// words doesn't split their line.+///+/// Only the visible modes (`Tr` 0–2) that `paint_ops` restates are compared: a line that goes on+/// as invisible or clipping text stays one line, which the clipping refusal reads whole (#3447).+///+/// Known gap: two ExtGStates with the same transparency but another parameter that [`Paint`]+/// doesn't compare (a dash `/D`, a line cap `/LC`) still join one line, which is then rewritten+/// with the first run's selections. Comparing the names here would split lines #3310 keeps whole.+fn same_paint(line: &TextLine, ts: &Ts) -> bool {+ let a = &line.origin.state;+ let visible = |m: i64| (0..=2).contains(&m);+ let same_mode = a.render_mode == ts.render_mode || !visible(a.render_mode) || !visible(ts.render_mode);+ let stroked = matches!((a.render_mode, ts.render_mode), (1 | 2, 1 | 2));+ same_mode && (!stroked || (a.stroke == ts.stroke && a.line_width == ts.line_width))+}+/// Whether two `/BaseFont` names name the same font: a subset's six-letter tag and `+` prefix do/// not change the font (ISO 32000-2 §9.6.4), so `ABCDEF+Arial` and `GHIJKL+Arial` are one font./// A name that is missing, or only a tag (`ABCDEF+`), names no font and matches nothing.diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 57b247638..06bed248b 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -811,9 +811,6 @@ pub(super) fn rewrite_styled_block(.any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !drop.contains(&(o.bt_op + i)));// What is in force where the rewrite is drawn, and what the text after it expects.let after = if split { &o.state } else { &o.bt_state };- // How the block paints text so far: each run restates what its source set inside its text- // object (`gs`, stroke, line width, `Tr`; #3508/#3509) when it differs.- let mut paint = after.clone();for (row, _) in rows.iter().zip(&kept).filter(|(_, k)| !**k) {let text: String = row.iter().map(|v| v.0).collect();if pdfcraft_fonts::source_shaping::required(&text) && row.first().is_some_and(|first| row.iter().any(|v| v.1 != first.1 || v.2 != first.2)) {@@ -924,9 +921,11 @@ pub(super) fn rewrite_styled_block(tm[4] += ax;tm[5] += ay;let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);- block_ops.extend(state.paint_ops(&paint));- // Only the painting fields are read from `paint`.- paint.clone_from(&state);+ // Each run in its own graphics state, restating what its source set inside its text+ // object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is+ // drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.+ block_ops.push(Op::new("q", vec![]));+ block_ops.extend(state.paint_ops(after));if let Some((_, shaped, _)) = shaped_runs.get(&(row_index, pos)) {let resource = glyph_resources.get(&(row_index, pos)).ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;let mut properties = Dict::new();@@ -1007,16 +1006,13 @@ pub(super) fn rewrite_styled_block(let underline_size = size_of(source, item.1) * source.origin.k;let (x0, y0) = back.apply(x - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);let (x1, y1) = back.apply(x + segment_width - o.ctm[4], baseline - o.ctm[5] - underline_size * 0.12);- let stroke = Op::new("RG", vec![n(r), n(g), n(b)]);- let width = underline_size * 0.06 / o.ctm[2].hypot(o.ctm[3]).max(1e-6);- block_ops.push(stroke.clone());- block_ops.push(Op::new("w", vec![n(width)]));- paint.stroke = vec![stroke];- paint.line_width = Some(width);+ block_ops.push(Op::new("RG", vec![n(r), n(g), n(b)]));+ block_ops.push(Op::new("w", vec![n(underline_size * 0.06 / o.ctm[2].hypot(o.ctm[3]).max(1e-6))]));block_ops.push(Op::new("m", vec![n(x0), n(y0)]));block_ops.push(Op::new("l", vec![n(x1), n(y1)]));block_ops.push(Op::new("S", vec![]));}+ block_ops.push(Op::new("Q", vec![]));x += segment_width;pos = end;}