PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: show a shaped run in one text object instead of one per glyph
komo1iddin2109c6785e8d
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex b542142df..3ba5ce5eb 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -4184,6 +4184,60 @@ fn a_new_character_comes_from_the_source_fonts_own_embedded_program() {}}+#[test]+fn a_shaped_run_is_one_text_object_with_each_glyph_where_shaping_put_it() {+ let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");+ let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Stable text) Tj ET");+ let resource = text::register_text_font(&mut doc, 0, inter).unwrap();+ // Marks shaped beside their letters (q́, x̣) and one stacked above another (ñ̄).+ let typed = "q\u{301}x\u{323} n\u{303}\u{304} Cafe\u{301}";+ let style = text::BlockStyle { width: Some(400.0), resource: Some(resource), ..Default::default() };+ text::rewrite_block(&mut doc, 0, 0, Some(typed), &style).unwrap();+ assert_eq!(text::text_blocks(&reopen(&doc), 0).unwrap()[0].editor_text, typed);+ let ops = pdfcraft_content::parse(&page_content_bytes(&doc, 0)).ops;+ let start = ops.iter().position(|o| o.is("BDC")).unwrap();+ let end = start + ops[start..].iter().position(|o| o.is("EMC")).unwrap();+ let run = &ops[start..end];+ let count = |name: &str| run.iter().filter(|o| o.is(name)).count();+ assert_eq!((count("BT"), count("Tm"), count("Tj")), (1, 1, 0), "{run:?}");+ // Each glyph's origin, read back with the text-space displacements of ISO 32000-1 §9.4.4.+ let font = run.iter().find(|o| o.is("Tf")).unwrap();+ let (resource, size) = (font.operands[0].as_name().unwrap().to_vec(), font.operands[1].as_f64().unwrap());+ let page = pdfcraft_model::pages(&doc).remove(0);+ let resources = doc.resolve(page.dict.get(b"Resources").unwrap()).as_dict().unwrap().clone();+ let fonts = doc.resolve(resources.get(b"Font").unwrap()).as_dict().unwrap().clone();+ let metrics = pdfcraft_fonts::pdf::Metrics::from_dict(&doc, doc.resolve(fonts.get(&resource).unwrap()).as_dict().unwrap());+ let (mut x, mut rise, mut drawn) = (0.0, 0.0, Vec::new());+ for op in run {+ match op.op.as_slice() {+ b"Ts" => rise = op.operands[0].as_f64().unwrap(),+ b"Tc" | b"Tw" => assert_eq!(op.operands[0].as_f64(), Some(0.0), "{run:?}"),+ b"Tz" => assert_eq!(op.operands[0].as_f64(), Some(100.0), "{run:?}"),+ b"TJ" => {+ for item in op.operands[0].as_array().unwrap() {+ match item.as_string() {+ Some(s) => {+ for code in s.bytes.chunks(2) {+ drawn.push((x, rise));+ x += metrics.width(u32::from(u16::from_be_bytes([code[0], code[1]]))) * size;+ }+ }+ None => x -= item.as_f64().unwrap() / 1000.0 * size,+ }+ }+ }+ _ => {}+ }+ }+ let shaped = pdfcraft_fonts::source_shaping::shape(inter, typed).unwrap();+ assert_eq!(drawn.len(), shaped.glyphs.len());+ assert!(shaped.glyphs.iter().any(|g| g.position[1] != 0.0), "a mark is raised");+ for (glyph, (x, y)) in shaped.glyphs.iter().zip(&drawn) {+ assert!((glyph.position[0] * size - x).abs() < 1e-3 && (glyph.position[1] * size - y).abs() < 1e-3, "{glyph:?} at {x}, {y}");+ }+ assert_eq!(rise, 0.0, "the rise is reset after the run");+}+#[test]fn a_subset_program_is_not_trusted_for_new_characters_and_the_error_names_the_character() {let mut doc = embedded_program_page("BT /F1 12 Tf 72 700 Td (Stable text) Tj ET", "ABCDEF+Inter-Regular");diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 2d7baf519..d4915e00d 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -753,24 +753,59 @@ pub(super) fn rewrite_styled_block(properties.set(b"ActualText".to_vec(), Object::String(PdfString::text(&string)));block_ops.push(Op::new("BDC", vec![Object::name("Span"), Object::Dict(properties)]));state.font = Some((resource.clone(), size_of(source, item.1)));- // Absolute glyph matrices preserve marks and contextual positions; font-program- // codes are separate from Unicode and ToUnicode/ActualText keep logical text.+ // One text object for the run: each glyph is placed where shaping put it by a TJ+ // adjustment from where the glyph before it ends (its advance in the embedded+ // font's widths), and raised by the text rise for a mark set above or below+ // (ISO 32000-1 §9.4.3, §9.3.7). Font-program codes are separate from Unicode;+ // ToUnicode and ActualText keep the logical text.let size = size_of(source, item.1);- let mut extra = 0.0;+ let per_unit = 1000.0 / size;+ if !per_unit.is_finite() {+ return Err(EditError::Invalid("the shaped text has no size".into()));+ }+ let shown = fonts+ .get(resource.as_bytes())+ .and_then(|f| doc.resolve(f).as_dict().cloned())+ .map(|d| Metrics::from_dict(doc, &d))+ .ok_or_else(|| EditError::Invalid("shaped font is missing".into()))?;+ // Spacing is part of each glyph's position, so the run itself has none.+ let (char_spacing, word_spacing, rise) = (state.char_spacing, state.word_spacing, state.rise);+ state.char_spacing = 0.0;+ state.word_spacing = 0.0;+ block_ops.push(Op::new("BT", vec![]));+ block_ops.extend(state.ops());+ block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));+ // `pen`: where the next glyph would start, in thousandths of the font size.+ let (mut pen, mut extra, mut raised) = (0.0, 0.0, rise);+ let mut shown_glyphs: Vec<Object> = Vec::new();for (i, glyph) in shaped.glyphs.iter().enumerate() {- let mut matrix = tm;- let x = (glyph.position[0] * size + extra) * state.scale;- let y = glyph.position[1] * size;- matrix[4] += matrix[0] * x + matrix[2] * y;- matrix[5] += matrix[1] * x + matrix[3] * y;+ let target = (glyph.position[0] * size + extra) * per_unit;+ let glyph_rise = rise + glyph.position[1] * size;+ if (glyph_rise - raised).abs() > 1e-9 || shown_glyphs.len() >= 4096 {+ if !shown_glyphs.is_empty() {+ block_ops.push(Op::new("TJ", vec![Object::Array(std::mem::take(&mut shown_glyphs))]));+ }+ if (glyph_rise - raised).abs() > 1e-9 {+ block_ops.push(Op::new("Ts", vec![n(glyph_rise)]));+ raised = glyph_rise;+ }+ }+ if (target - pen).abs() > 1e-6 {+ shown_glyphs.push(n(pen - target));+ }let code = u16::try_from(i + 1).map_err(|_| EditError::Invalid("shaped glyph limit".into()))?;- block_ops.push(Op::new("BT", vec![]));- block_ops.extend(state.ops());- block_ops.push(Op::new("Tm", matrix.map(n).to_vec()));- block_ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(code.to_be_bytes().to_vec()))]));- block_ops.push(Op::new("ET", vec![]));- extra += state.char_spacing * glyph.text.chars().count() as f64 + state.word_spacing * glyph.text.matches(' ').count() as f64;+ shown_glyphs.push(Object::String(PdfString::literal(code.to_be_bytes().to_vec())));+ pen = target + shown.width(u32::from(code)) * 1000.0;+ extra += char_spacing * glyph.text.chars().count() as f64 + word_spacing * glyph.text.matches(' ').count() as f64;+ }+ if !shown_glyphs.is_empty() {+ block_ops.push(Op::new("TJ", vec![Object::Array(shown_glyphs)]));}+ if (raised - rise).abs() > 1e-9 {+ block_ops.push(Op::new("Ts", vec![n(rise)]));+ }+ block_ops.push(Op::new("ET", vec![]));+ (state.char_spacing, state.word_spacing) = (char_spacing, word_spacing);block_ops.push(Op::new("EMC", vec![]));segment_width = (shaped.advance * size + extra) * state.scale * source.origin.k;} else {diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.mdindex e8bb03b9a..db589996d 100644--- a/docs/editing-existing-text.md+++ b/docs/editing-existing-text.md@@ -49,7 +49,9 @@ format that selection. Automation supports up to 1024 disjoint UTF-8 byte rangessame properties; invalid or overlapping ranges fail atomically. Untouched source formattingsurvives. OpenType shaping uses the selected/source face's substitution and positioningrules, preserves marks and ligatures, and applies Unicode bidi ordering for a single face.-Logical text remains available after save/reopen through ToUnicode and ActualText.+Each shaped run is one text object: its glyphs are shown in one `TJ` array whose adjustments+place each glyph where shaping put it, and a mark set above or below its letter is raised+with the text rise. Logical text remains available after save/reopen through ToUnicode and ActualText.Added Arabic text records ActualText per shaped line for copying and searching in typing order.ActualText already supplies typing order, so the editor preserves it without applyinga second bidi reversal; adjacent visual glyph runs still recover their own reading order.