Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M7: work out each font's space width once per paragraph rewrite (#2616) (#3297)

mtlcl41016f36810cc68
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index 99fae205e..374894a53 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -1473,6 +1473,65 @@ fn skia_subset_page() -> Document {
doc
}
+/// #2616: a subset whose ToUnicode has no space (as LaTeX and Sphinx output often has, spacing
+/// words with TJ kerning) makes finding the space width read every font on the page. That ran
+/// for every character of a multi-row draft, so each keystroke in a long paragraph took half a
+/// second. It runs once per font now, however long the paragraph.
+#[test]
+fn a_long_draft_in_a_font_without_a_space_works_out_the_space_width_once() {
+ // Two rows of one paragraph (14 pt apart) in the Chrome-style subset of `skia_subset_page`,
+ // whose ToUnicode here has no entry for the space glyph.
+ let mut doc =
+ text_page("BT /F3 12 Tf 72 700 Td <0177031602E001FB03050255> Tj ET BT /F3 12 Tf 72 686 Td <008D0266035402FE01FB030503E6> Tj ET");
+ let program = doc.add(Object::Stream(Stream::flate(Dict::new(), include_bytes!("../../../assets/fonts/Inter-Regular.ttf"))));
+ let unicode = doc.add(Object::Stream(Stream::flate(
+ Dict::new(),
+ b"1 begincodespacerange <0000> <FFFF> endcodespacerange 12 beginbfchar <0177> <0050> <0316> <006F> <02E0> <006C> <01FB> <0061> <0305> <006E> <0255> <0064> <008D> <0047> <0266> <0065> <0354> <0072> <02FE> <006D> <03E6> <0079> <1000> <007A> endbfchar",
+ )));
+ let widths: Vec<Object> =
+ [(0x8D, 746), (0x177, 639), (0x1FB, 551), (0x255, 612), (0x266, 583), (0x2E0, 242), (0x2FE, 876), (0x305, 591), (0x316, 600)]
+ .into_iter()
+ .chain([(0x354, 376), (0x3E6, 515)])
+ .flat_map(|(cid, width)| [Object::Int(cid), Object::Array(vec![Object::Int(width)])])
+ .collect();
+ let descriptor = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("FontDescriptor")),
+ (b"FontName".to_vec(), Object::name("BAAAAA+SampleSans")),
+ (b"Flags".to_vec(), Object::Int(32)),
+ (b"FontFile2".to_vec(), Object::Ref(program)),
+ ]);
+ let cid_font = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("Font")),
+ (b"Subtype".to_vec(), Object::name("CIDFontType2")),
+ (b"BaseFont".to_vec(), Object::name("BAAAAA+SampleSans")),
+ (b"CIDToGIDMap".to_vec(), Object::name("Identity")),
+ (b"DW".to_vec(), Object::Int(562)),
+ (b"W".to_vec(), Object::Array(widths)),
+ (b"FontDescriptor".to_vec(), Object::Dict(descriptor)),
+ ]);
+ let font = Dict::from_iter([
+ (b"Type".to_vec(), Object::name("Font")),
+ (b"Subtype".to_vec(), Object::name("Type0")),
+ (b"BaseFont".to_vec(), Object::name("BAAAAA+SampleSans")),
+ (b"Encoding".to_vec(), Object::name("Identity-H")),
+ (b"DescendantFonts".to_vec(), Object::Array(vec![Object::Dict(cid_font)])),
+ (b"ToUnicode".to_vec(), Object::Ref(unicode)),
+ ]);
+ let p = pdfcraft_model::pages(&doc)[0].obj;
+ let fonts = Dict::from_iter([(b"F3".to_vec(), Object::Dict(font))]);
+ doc.update_dict(p, |d| d.set(b"Resources".to_vec(), Object::Dict(Dict::from_iter([(b"Font".to_vec(), Object::Dict(fonts))])))).unwrap();
+ let blocks = text::text_blocks(&doc, 0).unwrap();
+ assert_eq!(blocks.len(), 1, "one paragraph: {:?}", blocks.iter().map(|b| &b.text).collect::<Vec<_>>());
+ let draft = "Poland and Germany
+"
+ .repeat(20);
+ text::SOURCE_SPACE_CALLS.with(|c| c.set(0));
+ let layout = text::text_edit_layout(&doc, 0, 0, draft.trim_end(), &text::BlockStyle::default()).unwrap();
+ let calls = text::SOURCE_SPACE_CALLS.with(std::cell::Cell::get);
+ assert!(layout.draft_rect.is_some_and(|r| r[2] > r[0]), "laid out: {:?}", layout.draft_rect);
+ assert!(calls <= 8, "the space width was worked out {calls} times for {} characters", draft.len());
+}
+
#[test]
fn a_subset_keeps_its_font_for_glyphs_left_to_the_default_width() {
let doc = skia_subset_page();
diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rs
index e4eaaa641..45bb93919 100644
--- a/crates/edit/src/text.rs
+++ b/crates/edit/src/text.rs
@@ -1661,7 +1661,15 @@ fn source_encodes(metrics: &Metrics, text: &str) -> bool {
text.split(' ').all(|word| metrics.encode(word).is_some())
}
+#[cfg(test)]
+thread_local! {
+ /// How often [`source_space`] ran on this thread, for the test that pins it out of per-character loops.
+ pub(crate) static SOURCE_SPACE_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
fn source_space(doc: &Document, fonts: &Dict, metrics: &Metrics) -> f64 {
+ #[cfg(test)]
+ SOURCE_SPACE_CALLS.with(|c| c.set(c.get().saturating_add(1)));
let width = |m: &Metrics| m.encode(" ").map(|b| m.codes(&b).iter().map(|(c, _)| m.width(*c)).sum::<f64>());
if let Some(w) = width(metrics) {
return w;
diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rs
index 8e34e0bdf..e08068d9f 100644
--- a/crates/edit/src/text_regions.rs
+++ b/crates/edit/src/text_regions.rs
@@ -489,6 +489,20 @@ pub(super) fn rewrite_styled_block(
};
// A source run may carry TJ kerning/justification that is absent from its text state.
// Keep its measured advance when rebuilding the run instead of making it wrap on entry.
+ // Each font's space width, worked out once: when a font can't show a space, finding one
+ // reads every font on the page, and doing that for every character of a paragraph made each
+ // keystroke in a long paragraph take half a second (#2616).
+ // Only for the fonts the paragraph uses, when first asked: working out every page font's width
+ // up front would scan the page once per font for a short edit on a page of many fonts.
+ let spaces: std::cell::RefCell<HashMap<String, f64>> = std::cell::RefCell::new(HashMap::new());
+ let space_of = |name: &str, m: &Metrics| {
+ if let Some(w) = spaces.borrow().get(name) {
+ return *w;
+ }
+ let w = source_space(doc, &fonts, m);
+ spaces.borrow_mut().insert(name.to_owned(), w);
+ w
+ };
let mut calibration = HashMap::new();
for (index, source) in lines.iter().enumerate() {
if let Some(m) = metrics.get(&source.font) {
@@ -496,7 +510,7 @@ pub(super) fn rewrite_styled_block(
m,
&source.text,
source.origin.state.font.as_ref().map_or(1.0, |(_, s)| *s),
- source_space(doc, &fonts, m),
+ space_of(&source.font, m),
source.origin.state.char_spacing,
source.origin.state.word_spacing,
) * source.origin.state.scale
@@ -513,7 +527,7 @@ pub(super) fn rewrite_styled_block(
m,
&item.0.to_string(),
size_of(source, item.1),
- source_space(doc, &fonts, m),
+ space_of(&item.2, m),
overrides
.get(&item.1)
.and_then(|r| r.char_spacing)
@@ -778,7 +792,7 @@ pub(super) fn rewrite_styled_block(
m,
&string,
size_of(source, item.1),
- source_space(doc, &fonts, m),
+ spaces.borrow().get(&item.2).copied().unwrap_or_else(|| source_space(doc, &fonts, m)),
state.char_spacing,
state.word_spacing,
)?);