Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

PDF: small caps and substituted figures keep their text

aiongg279309ad1203
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3dd7c25b3..b7ac073fd 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -125,6 +125,8 @@ pub struct PlacedGlyph {
pub style: u32,
pub byte: usize,
pub len: usize,
+ /// Text of a generated glyph (see [`shape::Glyph::generated_text`]).
+ pub generated_text: Option<Box<str>>,
/// Control characters (tabs, breaks, markers' carriers) are not drawn.
pub visible: bool,
/// Stays upright in vertical frames (CJK ideographs, kana, hangul, full-width forms).
@@ -2412,7 +2414,18 @@ fn layout_line(
}
// One tatweel stretched over the gap (overlapping its neighbours a little).
let k = (l + 0.4) / w;
- out.push(PlacedGlyph { gid, x: at - 0.2, y: -g.shift, adv: 0.0, sx: g.sx * k, len: 0, upright: false, tcy: None, ..place(g, at) });
+ out.push(PlacedGlyph {
+ gid,
+ x: at - 0.2,
+ y: -g.shift,
+ adv: 0.0,
+ sx: g.sx * k,
+ len: 0,
+ generated_text: None,
+ upright: false,
+ tcy: None,
+ ..place(g, at)
+ });
}
(out, x, ratio)
}
@@ -2529,6 +2542,7 @@ fn tab_leader(tab: &Glyph, leader: &str, x: f64, w: f64, origin: f64, out: &mut
style: tab.style,
byte: tab.byte,
len: 0,
+ generated_text: None,
visible: true,
upright: false,
tcy: None,
@@ -2634,6 +2648,7 @@ fn place(g: &Glyph, x: f64) -> PlacedGlyph {
style: g.style,
byte: g.byte,
len: g.len,
+ generated_text: g.generated_text.clone(),
visible,
upright: g.upright,
tcy: g.tcy,
@@ -2659,6 +2674,9 @@ fn prepend_label(
.glyphs
.into_iter()
.map(|mut g| {
+ if g.generated_text.is_none() {
+ g.generated_text = Some(label.get(g.byte..g.byte + g.len).unwrap_or("").into());
+ }
g.byte = at;
g.len = 0;
g
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
index cea4a5545..d27ff428e 100644
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@ -29,6 +29,7 @@ fn set(base: &PlacedGlyph, text: &str, size: f64, base_size: f64) -> (Vec<Placed
sx: k,
sy: k,
len: 0,
+ generated_text: None,
visible: true,
upright: upright_in_vertical(ch),
tcy: None,
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 1e1af40a7..a7bf99a62 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -18,6 +18,10 @@ pub struct Glyph {
pub len: usize,
/// First source character of the cluster (special characters keep their code).
pub ch: char,
+ /// What a generated glyph (page number, list label) reads as in exported text, since its
+ /// `byte..byte + len` holds a marker or nothing: the cluster's text on its first glyph, empty
+ /// on the others. `None` for story text, which reads as its source bytes.
+ pub generated_text: Option<Box<str>>,
/// Advance in points (tracking and horizontal scale applied).
pub adv: f64,
pub dx: f64,
@@ -764,6 +768,7 @@ fn control_glyph(face: &Arc<FontFace>, p: &CharProps, auto_leading: TypeEnv, sty
byte,
len: ch.len_utf8(),
ch,
+ generated_text: None,
adv: 0.0,
dx: 0.0,
dy: 0.0,
@@ -858,6 +863,15 @@ fn shape_segment(
(cl, end.saturating_sub(cl), text[cl..].chars().next().unwrap_or(' '))
};
let last_in_cluster = gi + 1 == n || shaped[gi + 1].cluster != sg.cluster;
+ // Only the first glyph of a cluster owns the bytes (so ranges partition the text).
+ let first_in_cluster = gi == 0 || shaped[gi - 1].cluster != sg.cluster;
+ let generated_text = replacement.map(|src| {
+ if !first_in_cluster {
+ return Box::from("");
+ }
+ let end = shaped[gi + 1..].iter().map(|r| r.cluster).find(|&c| c > sg.cluster).unwrap_or(src.len());
+ Box::from(src.get(sg.cluster..end).unwrap_or(""))
+ });
// Upright: down the line is the shaper's -y, across it (text space -y) its x.
let mut adv = if up { -(sg.y_advance as f64) * k_v } else { sg.x_advance as f64 * k * hs };
let (dx, dy) = if up {
@@ -871,8 +885,6 @@ fn shape_segment(
} else if last_in_cluster {
adv += tracking + manual;
}
- // Only the first glyph of a cluster owns the bytes (so ranges partition the text).
- let first_in_cluster = gi == 0 || shaped[gi - 1].cluster != sg.cluster;
let mark = face.glyph_is_mark(sg.gid);
let mark_x = if mark { p.diacritic_x_offset.clamp(-1000.0, 1000.0) / 1000.0 * p.size * hs } else { 0.0 };
let mark_y = if mark { p.diacritic_y_offset.clamp(-1000.0, 1000.0) / 1000.0 * p.size * p.v_scale } else { 0.0 };
@@ -882,6 +894,7 @@ fn shape_segment(
byte,
len: if first_in_cluster || replacement.is_some() { len } else { 0 },
ch,
+ generated_text,
adv,
dx: dx + mark_x,
dy: dy - mark_y,
@@ -948,5 +961,6 @@ pub(crate) fn hyphen_after(g: &Glyph) -> Glyph {
h.byte = g.byte + g.len;
h.len = 0;
h.ch = '-';
+ h.generated_text = None;
h
}
diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs
index 9ac53d057..707ce9505 100644
--- a/crates/pdf/src/tests.rs
+++ b/crates/pdf/src/tests.rs
@@ -446,3 +446,37 @@ fn column_rules_are_drawn() {
assert!((xs[0] - 214.0).abs() < 0.01 && (xs[1] - 398.0).abs() < 0.01, "{xs:?}");
assert!(rules(false).is_empty());
}
+
+#[test]
+fn small_caps_and_small_cap_figures_extract_as_typed() {
+ // Source Sans 3 substitutes letters and figures under `smcp` / `c2sc` (`one` → `one.s`),
+ // in typed text, in a page number and in a list label alike (each with its own figures, so
+ // one's mapping can't stand in for another's).
+ use designcraft_doc::{Capitalization, ListType, story::PAGE_NUMBER};
+ for caps in [Capitalization::SmallCaps, Capitalization::OpenTypeAllSmallCaps] {
+ let text = format!("Abc 234 x{PAGE_NUMBER}\nItem");
+ let mut d = doc_with_text(&text);
+ let sid = *d.stories.keys().next().unwrap();
+ let st = d.story_mut(sid).unwrap();
+ st.format_paras(0..text.len(), |f| {
+ f.chars.font_family = Some("Source Sans 3".into());
+ f.chars.capitalization = Some(caps);
+ });
+ st.format_paras(text.len() - 1..text.len(), |f| {
+ f.para.list_type = Some(ListType::Numbers);
+ f.para.start_at = Some(Some(5));
+ });
+ let got = extract_text(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap()).concat();
+ assert!(!got.contains('\u{FFFD}'), "{caps:?}: {got:?}");
+ assert_eq!(got.split_whitespace().collect::<Vec<_>>(), ["Abc", "234", "x15.Item"], "{caps:?}: {got:?}");
+ }
+ // All small caps draws `A` and `a` with one glyph, which one ToUnicode entry can't cover: the
+ // second spelling goes out as ActualText (which this extractor doesn't read).
+ let mut d = doc_with_text("Aa");
+ let sid = *d.stories.keys().next().unwrap();
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.font_family = Some("Source Sans 3".into());
+ f.over.capitalization = Some(Capitalization::OpenTypeAllSmallCaps);
+ });
+ assert!(uncompressed(&d, PdfOptions::default()).contains("/ActualText"));
+}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index bf59efded..40635d407 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -263,8 +263,19 @@ impl Exporter<'_> {
} else if g.len == 0 && prev_src == Some(g.byte) && !ranges.is_empty() {
// Second glyph of a multi-glyph cluster: share the cluster's text.
ranges[ranges.len() - 1].clone()
+ } else if let Some(t) = g.generated_text.as_deref().filter(|t| !t.is_empty() && !t.chars().any(is_marker)) {
+ // Generated text (page numbers, list labels): its own characters, which a glyph
+ // the font substituted (small-cap or old-style figures) can't be mapped back to.
+ prev_src = None;
+ let a = text.len();
+ text.push_str(t);
+ a..text.len()
+ } else if g.generated_text.as_deref() == Some("") && !ranges.is_empty() {
+ // Later glyph of a generated cluster.
+ prev_src = None;
+ ranges[ranges.len() - 1].clone()
} else {
- // Inserted glyphs (page numbers, list labels, hyphens): map back through the font.
+ // Other inserted glyphs (hyphens, tab leaders, ruby): map back through the font.
prev_src = None;
match cmap.get(&g.gid) {
Some(c) => {