.ai import: type takes the installed copy that sets its PDF part's widths

When several installed faces answer to a text document font record's
PostScript name and the record keeps no version (no key 5), type was set in
whichever copy loaded first. Two copies can share the PostScript name, family
and style and differ only in their widths (two releases of one font): the type
then set at other widths than the file's own page, and envelopes of it could
fail their drawn-art check. #6983 left this case out, as only the page's
widths tell such copies apart.

- `Opened::page_widths` (crates/pdf/src/page_widths.rs) reads the widths the
  pages give the characters of each font they set type in, from the font
  dictionaries alone and without importing any page: a simple font's
  `Widths` from `FirstChar`, a composite font's descendant's `W` under an
  `Identity-H`/`Identity-V` CMap, each code's character from the font's
  `ToUnicode` map or, for a simple font without one whose `Encoding` is
  `WinAnsiEncoding`, from that encoding (ISO 32000-1 9.6.2, 9.7.4.3, 9.10.3,
  Annex D.2), by `BaseFont` without its subset tag. Zero widths (codes a
  subset doesn't use) are left out; subsets that give a character two widths
  give none.
- Its cost is bounded by the file: each resource dictionary is walked once,
  however many pages and forms share it, within 65,536 entries for the whole
  file, 256 fonts and 4,096 forms; a width array that fonts share by
  reference is read once, and none past 4 MB of them; a `ToUnicode` map is
  parsed once for all the fonts that name it, and one over 256 KB decoded,
  or past 4 MB of maps in all (each charged at most what could be decoded
  of it), is left unread. `cid_ranges` reads a `W` list's values as it
  takes them instead of collecting the whole list. A font's widths are
  shared, not copied.
- `postscript_face` (crates/eps/src/import/text.rs) takes, among the faces
  of the record's name, the first that sets those characters (the first 512
  in code-point order) each within 1/1000 em. With no widths, one face, a
  version in the record, or no face that sets them all, the pick is the one
  before. The face found first is checked before any other is loaded, and
  the records of one name and version share their widths and their answer,
  so each font resolves once whatever the number of records.
- The widths reach the text document through `Structure::page_widths` and
  `Texts::with_page_widths`; the engine reads them once per open and passes
  them to `ai_layers_alone`, `AiLayers::with_page_widths` and `ai_alone_with`
  when it reads a `.ai`'s editing copy beside a PDF part (not for a
  placeholder page).
- `without_subset_tag` replaces two copies of the subset-tag strip in the PDF
  import, and `replacement` (a `ToUnicode` value that names no character) is
  shared with it.
- A fuzz target feeds hostile font dictionaries, `ToUnicode` maps and forms
  that draw themselves to the reader.

Measured on 224 users' files (used locally, never committed): 3 font records
in 3 files change copy, each now within 0.5/1000 em of its page; those 3
renders, and no others, change, all closer to the file's own page; envelopes
of type that open live go from 185 to 186, none fewer in any file; no file
opens another way.

Refs #6983

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jmverges
2026-11-16 07:18:04 +00:00
parent b4d45f2b0d
commit 546d274e6e
22 changed files with 1111 additions and 92 deletions
+16 -8
View File
@@ -255,12 +255,15 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions)
return None;
}
let private = opened.illustrator_data()?;
Some(editing_copy_alone(&private, opts))
// A placeholder page's fonts aren't the art's.
Some(editing_copy_alone(&private, opts, Default::default()))
}
/// [`from_editing_data_alone`] of `private`, the editor's copy already read.
fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone_with(private, opts.legacy_names)
/// [`from_editing_data_alone`] of `private`, the editor's copy already read, with `widths`, the
/// widths the file's PDF part gives the characters of its fonts, which tell installed copies of a
/// font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]).
fn editing_copy_alone(private: &[u8], opts: &LoadOptions, widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>)> {
vectorcraft_eps::ai_alone_with(private, opts.legacy_names, widths)
.map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})")))
}
@@ -444,6 +447,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
Err(e) => Err(err(e)),
};
let mut read = restore_or_import(editing, || {
// The widths the PDF part gives the characters of its fonts, which tell installed
// copies of a font apart: read once, when the editing copy is.
let page_widths = std::cell::OnceCell::new();
let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone();
// Type all from the text document and nothing that needs the PDF part: the layers
// alone, the PDF part not imported. Else what was read of the layers is kept for
// reading them with the PDF part.
@@ -451,7 +458,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?)))
{
let pages = o.trim_pages();
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names) {
match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) {
Ok((mut doc, warnings)) => {
doc.setup.bleed = pages.bleed;
editing_data = true;
@@ -473,9 +480,9 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// decoded draws nothing either): its notes are at most the page's own.
let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w));
let copy_alone = || match &private {
Some(private) => Some(editing_copy_alone(private, opts)),
Some(private) => Some(editing_copy_alone(private, opts, widths())),
None if layers.is_some() => {
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts))
opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths()))
}
None => None,
};
@@ -487,7 +494,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
let (doc, warnings, read) = match alone {
Some((doc, warnings)) => (doc, warnings, true),
None => {
let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode));
let layers =
layers.or_else(|| private.as_deref().map(|p| vectorcraft_eps::AiLayers::decode(p).with_page_widths(widths())));
through_editing_data(layers, opts, r.document, r.warnings, r.user_unit)
}
};
@@ -2072,3 +2072,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() {
assert_eq!(r["restored"], json!(true), "{r}");
assert_eq!(open_rows(&s).1, ["Art", "Hidden"]);
}
/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the
/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in
/// a subset of that font that gives each character the width `width` gives it, in thousandths of an
/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is
/// 200 × 100 pt, and the page `page_width` × 100.
fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec<u8> {
let story = "Hamburg";
let n = story.chars().count() + 1;
let document = format!(
"/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\
/1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \
/6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \
/1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \
<< /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n"
);
let lines: Vec<String> = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
let (art, drawn) =
if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") };
let body = format!(
"%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n",
ai::layer("Art", &art),
lines.join("\n")
);
let data = ai::editing_data(200.0, 100.0, &body);
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect();
let page = PdfPage {
resources: format!(
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
widths.join(" ")
),
entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)),
// A page that is only type, with its art box, isn't a placeholder.
art: Some([0.0, 0.0, page_width, 100.0]),
..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET"))
};
pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None)
}
/// Type from the text document of a `.ai` whose font record keeps no version, where two installed
/// copies of the font share its PostScript name, family and style and differ in their widths, is
/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether
/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF
/// part is only type (read after the layers alone, on a page of another size, were not used).
#[test]
fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() {
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular"));
let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() };
// (a square beside the type, the page's width, the options, whether the PDF part is imported)
let cases = [
(true, 200.0, &LoadOptions::default(), false),
(true, 200.0, &trim, true),
(false, 200.0, &LoadOptions::default(), false),
(false, 200.0, &trim, true),
(false, 260.0, &LoadOptions::default(), true),
];
for (square, page_width, opts, imported) in cases {
let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width);
let before = vectorcraft_pdf::imports_of(&file);
let loaded = load_with("copies.ai", &file, opts).unwrap();
let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings);
assert!(loaded.editing_data, "{case}");
assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}");
let art = loaded.doc.layers[0].children().unwrap();
assert_eq!(art.len(), 1 + usize::from(square), "{case}");
let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") };
assert_eq!(t.plain_text(), "Hamburg");
assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}");
}
}
/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded
/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives.
fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> {
let db = vectorcraft_text::FontDb::global();
for (inter, version) in [(true, "1.0"), (false, "1.1")] {
let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap();
assert_eq!(db.add_font(font), 1);
}
let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap();
move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em()
}
/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that
/// copy's version in its font record, so it opens in the same copy again, from the editing copy
/// alone as from the whole file.
#[test]
fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() {
let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular"));
let mut s = Session::new();
let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap();
let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap();
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let versions = |doc: &vectorcraft_doc::Document| -> Vec<String> {
let art = doc.layers[0].children().unwrap();
art.iter()
.filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None })
.collect()
};
assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}");
let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap();
assert!(loaded.editing_data, "{:?}", loaded.warnings);
assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings);
let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap();
assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]);
}
+54 -1
View File
@@ -6,7 +6,8 @@
//! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files,
//! opcodes with random contents) opened or placed, nor EPS and PostScript files
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a
//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the
//! font files a folder search reads (damaged fonts, collections whose headers give any count of
//! faces), nor scripts written for the reference app checked without running them (garbage,
@@ -896,6 +897,58 @@ proptest! {
}
}
/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any
/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite
/// font's `W` of any shape, and the `ToUnicode` map of object 5.
fn arb_width_font() -> impl Strategy<Value = String> {
(
prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]),
prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]),
prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]),
prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12),
prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10),
prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]),
any::<bool>(),
)
.prop_map(|(subtype, encoding, first, widths, w, name, mapped)| {
let map = if mapped { "/ToUnicode 5 0 R" } else { "" };
format!(
"<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \
/DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>",
widths.join(" "),
w.join(" ")
)
})
}
proptest! {
#![proptest_config(config())]
/// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read
/// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that
/// draw themselves.
#[test]
fn pdf_font_widths_never_panic(
fonts in prop::collection::vec(arb_width_font(), 1..4),
cmap in prop::collection::vec(prop::sample::select(vec![
"begincmap", "1 begincodespacerange", "<0000> <FFFF>", "<00> <FF>", "endcodespacerange", "2 beginbfchar", "<0001> <0041>",
"<0002> <D800>", "<41> <FFFD>", "1 beginbfrange", "<0000> <FFFF> <0000>", "<FFFF> <0000> <0041>", "<0001> <0003> [<0041> <0042>]",
"endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar",
]), 0..12),
) {
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
let map = cmap.join("\n");
let form = format!(
"<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream",
fonts[0]
);
let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()];
let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more);
let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths()));
prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}");
}
}
/// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a
/// broken `#` escape, a number with a stray `-`).
fn arb_dict_value() -> impl Strategy<Value = &'static str> {
+2 -2
View File
@@ -612,7 +612,7 @@ fn font_name(st: &CharStyle) -> FontRecord {
.collect();
let name = face.postscript_name();
// The reader takes the face of a name alone as `postscript_face` finds it.
let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id());
let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id());
let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() };
FontRecord { name, truetype: face.is_truetype(), design, version }
}
@@ -659,7 +659,7 @@ fn fixed(v: f32) -> i64 {
fn font_kept(st: &CharStyle) -> bool {
let record = font_name(st);
let version = crate::import::record_version(&record.version);
let (family, style, read) = crate::import::document_font(&record.name, version);
let (family, style, read) = crate::import::document_font(&record.name, version, None);
let db = vectorcraft_text::FontDb::global();
let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id());
family == st.font_family
+1 -1
View File
@@ -564,7 +564,7 @@ impl Reader<'_> {
st.cmap = cmap;
// The installed face of that PostScript name, as type from a text document
// takes it; else the name split into a family and style.
let text = super::super::super::text::named_font(name, None);
let text = super::super::super::text::named_font(name, None, None);
let (family, style, version) = text.unwrap_or_else(|| {
let (family, style) = super::super::super::text::family_style(name);
(family, style, None)
+4
View File
@@ -217,6 +217,10 @@ pub struct Structure {
/// name of the art style that gives each: the styles that are one paint, a pattern this read
/// (see `ate::Texts::with_patterns`).
pub text_patterns: HashMap<String, Paint>,
/// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies
/// of a font apart for type whose font record keeps no version (see
/// `ate::Texts::with_page_widths`): none until the importer sets them.
pub page_widths: vectorcraft_pdf::PageWidths,
/// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not.
pub canvas_scale: f64,
/// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its
@@ -1395,6 +1395,7 @@ impl<'a> Reader<'a> {
},
styles_read,
text_patterns,
page_widths: Default::default(),
canvas_scale: self.canvas_scale,
symbols_own_size: self.symbols_own_size,
xml_ids: self.xml_ids,
+60 -8
View File
@@ -23,6 +23,7 @@
//! a layout has its point type's anchor at its frame's point. See [`Story::place`].
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen};
use vectorcraft_color::{Color, Paint};
@@ -564,15 +565,20 @@ struct DocFont {
/// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed
/// copies of one font apart.
version: Option<String>,
/// [`Self::font`]'s answer, found once for every run that names the record.
font: std::sync::OnceLock<Font>,
/// The widths the file's page gives the font's characters, when it has them
/// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record
/// of the font shares them.
widths: Option<Arc<vectorcraft_pdf::FontWidths>>,
/// [`Self::font`]'s answer, found once for every run that names the record, and shared by the
/// records of the same name and version, which give the same answer.
font: Arc<std::sync::OnceLock<Font>>,
}
impl DocFont {
/// The font type set in this record's font takes: the installed copy it names
/// ([`super::text::document_font`]).
fn font(&self) -> &Font {
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref()))
self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref()))
}
}
@@ -616,6 +622,17 @@ impl Texts {
Texts { patterns, ..self }
}
/// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`])
/// gives the characters of its fonts, by each record's PostScript name: a record that keeps no
/// version is set in the installed copy of its font that sets them at those widths
/// ([`super::text::postscript_face`]).
pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts {
for f in &mut self.fonts {
f.widths = page.widths(super::text::bare_name(&f.name)).cloned();
}
self
}
/// The text document in the editing copy `data`, if it has one that can be read.
pub(super) fn read(data: &[u8]) -> Option<Texts> {
fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> {
@@ -643,6 +660,8 @@ impl Texts {
return None;
}
let doc = names::numbered(read(&bytes)?);
// Records of one name and version share their answer.
let mut answers: HashMap<(String, Option<String>), Arc<std::sync::OnceLock<Font>>> = HashMap::new();
let fonts = doc
.get("0")?
.get("1")?
@@ -652,11 +671,10 @@ impl Texts {
.map(|f| {
let record = f.get("0").and_then(|f| f.get("0"));
let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str);
DocFont {
name: text("0").unwrap_or_default().to_string(),
version: text("5").and_then(record_version).map(str::to_string),
font: std::sync::OnceLock::new(),
}
let name = text("0").unwrap_or_default().to_string();
let version = text("5").and_then(record_version).map(str::to_string);
let font = answers.entry((name.clone(), version.clone())).or_default().clone();
DocFont { name, version, widths: None, font }
})
.collect();
let main = doc.get("1")?;
@@ -1592,6 +1610,40 @@ fn art_scale(to_doc: Affine) -> f64 {
mod tests {
use super::*;
/// The records of a text document's font list that name one font share the widths the file's
/// page gives it and the face they resolve to, however many there are: 20,000 records of a font
/// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record
/// of another version is resolved apart.
#[test]
fn records_of_one_font_share_its_page_widths_and_answer() {
let n = 20_000;
let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>";
let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n");
let data =
format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes()));
let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n16 beginbfrange\n");
for hi in 1..=16u32 {
cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n"));
}
cmap.push_str("endbfrange\nendcmap\n");
let extra = vectorcraft_testkit::pdf::first_extra(1);
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>"
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths();
let shared = widths.widths("Sharetest-Regular").unwrap();
assert_eq!(shared.len(), 4096);
let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths);
assert_eq!(texts.fonts.len(), n + 1);
assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared))));
let first = &texts.fonts[0].font;
assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first)));
assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart");
}
#[test]
fn right_to_left_paragraphs_swap_left_and_right_alignment() {
let texts = Texts {
+17 -8
View File
@@ -178,17 +178,25 @@ impl ReadText {
self.frames.get_or_insert_with(|| ai::text_frames(data))
}
/// The text document of `data` ([`Texts::read`]), if it has one that can be read.
fn texts(&mut self, data: &[u8]) -> Option<&Texts> {
/// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths
/// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given
/// when it is first read, before any of its fonts is found: each is found once, with the widths
/// it has then. Every check and build of one open passes the same widths.
fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> {
self.forget_in_tests();
self.texts.get_or_insert_with(|| Texts::read(data)).as_ref()
self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref()
}
/// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]).
fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap<String, vectorcraft_color::Paint>) -> Option<&Texts> {
fn texts_with(
&mut self,
data: &[u8],
patterns: std::collections::HashMap<String, vectorcraft_color::Paint>,
page_widths: &vectorcraft_pdf::PageWidths,
) -> Option<&Texts> {
self.forget_in_tests();
let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns));
self.texts.insert(texts).as_ref()
let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths)));
self.texts.insert(read.map(|t| t.with_patterns(patterns))).as_ref()
}
}
@@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo
for info in &mut infos {
info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone())));
}
let Some(texts) = text.texts(data) else { return false };
let Some(texts) = text.texts(data, &structure.page_widths) else { return false };
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
let stories: Vec<Option<Arc<Story>>> = infos
.iter()
@@ -336,6 +344,7 @@ pub(super) fn build_weighing(
envelopes_drawn,
styles_read,
text_patterns,
page_widths,
canvas_scale,
symbols_own_size,
xml_ids,
@@ -496,7 +505,7 @@ pub(super) fn build_weighing(
// The page's type that needs no text object of the layers: the layers' own legacy text, or
// placed files that show it.
let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?;
let texts = text.texts_with(data, text_patterns);
let texts = text.texts_with(data, text_patterns, &page_widths);
// Each story is read once, however many text objects name it.
let mut read: std::collections::BTreeMap<u32, Option<Arc<Story>>> = Default::default();
let stories: Vec<Option<Arc<Story>>> = infos
+52 -17
View File
@@ -149,7 +149,7 @@ pub fn layered_ai_from(
all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part"));
all
};
let AiLayers { data, structure, alone, mut text } = layers;
let AiLayers { data, structure, alone, mut text, page_widths } = layers;
let data = match data {
Ok(data) => data,
Err(why) => return (visible, unread(warnings, &why), false),
@@ -189,10 +189,17 @@ pub fn layered_ai_from(
add_notes(&mut all, read.notes());
(visible, all, false)
};
// The layers read, with the widths the PDF part gives the characters of its fonts.
let read = || {
ai::read_over_page(&data, false, names).map(|mut structure| {
structure.page_widths = page_widths.clone();
structure
})
};
// The envelopes of type the page doesn't hold against layers that don't draw as it, and how many
// envelopes of type the layers had.
let (mut free, mut count) = (None, 0);
let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| {
let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| {
count = structure.warped_type.envelope_count();
build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text)
});
@@ -205,7 +212,7 @@ pub fn layered_ai_from(
let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers));
if !live
&& let Some((mut done, notes)) = alone.and_then(|(pages, unit)| {
let mut structure = ai::read_over_page(&data, false, names).ok()?;
let mut structure = read().ok()?;
// With none free, nothing needs settling again: every envelope keeps its drawn art.
if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) {
structure.warped_type.open_alone(free, count);
@@ -244,32 +251,41 @@ fn holds_type_envelope(nodes: &[Arc<Node>]) -> bool {
/// reading it, when the file's text document makes all of its type and nothing in its layers needs
/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the
/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part
/// is imported. `names`: the encoding of names that aren't UTF-8.
pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec<String>), AiLayers> {
/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the
/// PDF part gives the characters of its fonts, which tell installed copies of a font apart
/// ([`AiLayers::with_page_widths`]).
pub fn ai_layers_alone(
private: &[u8],
pages: &[(f64, f64)],
unit: f64,
names: ai::NameEncoding,
page_widths: vectorcraft_pdf::PageWidths,
) -> Result<(Document, Vec<String>), AiLayers> {
let data = match ai::decode_private(private) {
Ok(data) => data,
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }),
Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }),
};
if !has_layers(&data) {
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() });
return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths });
}
// An image past the hard limits is read as an unread box, which the PDF part's art replaces.
let structure = match ai::read_over_page(&data, false, names) {
let mut structure = match ai::read_over_page(&data, false, names) {
Ok(structure) => structure,
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }),
Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }),
};
structure.page_widths = page_widths.clone();
let mut text = Box::<ReadText>::default();
// An envelope of type opens live only where the layers with it draw as the page, as the other
// live envelopes do: the PDF part is imported to compare them with. Should none open live, the
// layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]).
if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() {
let alone = Some((pages.to_vec(), unit));
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text });
return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths });
}
match build_without_page(structure, &data, pages, unit, &mut text) {
Ok(Ok((doc, notes))) => Ok((doc, notes)),
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }),
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }),
Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }),
Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }),
}
}
@@ -286,12 +302,27 @@ pub struct AiLayers {
alone: Option<(Vec<(f64, f64)>, f64)>,
/// The text objects' frames and the text document of the editing copy, as far as they were read.
text: Box<ReadText>,
/// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]).
page_widths: vectorcraft_pdf::PageWidths,
}
impl AiLayers {
/// The editing copy `private` (as [`layered_ai`] takes it), decoded.
pub fn decode(private: &[u8]) -> Self {
Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default() }
Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default(), page_widths: Default::default() }
}
/// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of
/// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no
/// version is set in the installed copy of its font that sets them at those widths, where
/// several copies answer to its name. The layers read before take them too, and a text document
/// read before is read again with them, since its fonts are found once, with the widths they had
/// then.
pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self {
if let Some(Ok(structure)) = &mut self.structure {
structure.page_widths = page_widths.clone();
}
Self { page_widths, text: Box::default(), ..self }
}
}
@@ -581,13 +612,17 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) {
/// Editing data written on a large canvas comes in at its declared scale: no page holds the size.
/// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]).
pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
ai_alone_with(private, ai::NameEncoding::default())
ai_alone_with(private, ai::NameEncoding::default(), Default::default())
}
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`.
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec<String>), String> {
/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the
/// file's PDF part gives the characters of its fonts when it has one that holds the art
/// ([`AiLayers::with_page_widths`]).
pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec<String>), String> {
let data = ai::decode_private(private)?;
build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0)
let mut structure = ai::read_in(&data, true, names)?;
structure.page_widths = page_widths;
build_from(structure, &data, None, Page::Artboard, false, false, 1.0)
}
/// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height)
+108 -9
View File
@@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() {
assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1");
}
/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of
/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em.
fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
let widths: Vec<String> = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect();
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>",
widths.join(" ")
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths()
}
/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives
/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths.
fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths {
let chars: Vec<char> = text.chars().collect();
let pairs: Vec<String> = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect();
let cmap = format!(
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n",
pairs.len(),
pairs.join("\n")
);
let w: Vec<String> = chars.iter().map(|c| width(*c).to_string()).collect();
let extra = vectorcraft_testkit::pdf::first_extra(1);
let font = format!(
"/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>",
w.join(" ")
);
let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") };
let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None);
vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths()
}
/// The advance of `c` in installed `face`, in thousandths of an em.
fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 {
face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em()
}
/// The version of the face that type from the text document of a `.ai` whose font record is
/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the
/// widths its PDF part gives the characters of its fonts.
fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String {
let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1);
let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc));
let names = crate::NameEncoding::default();
let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") };
let texts = text_of(&d.layers[0]);
assert_eq!(texts.len(), 1, "{record}: {notes:?}");
vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone()
}
/// Two installed copies of one font can share its PostScript name, family and style, and differ
/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no
/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF
/// part gives them, also when the record spells the name with other punctuation. Without those
/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first
/// loaded); a version the record keeps decides first. The widths of a simple font in
/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart.
#[test]
fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() {
install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]);
let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular");
let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone();
let (old, new) = (copy("1.0"), copy("1.1"));
assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths");
let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c));
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0");
// Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's.
let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by);
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0");
// A record whose name differs from the copies' in punctuation alone, as its PDF part's font.
assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1");
// Widths of another font, or no copy setting the characters at the PDF part's widths.
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0");
// A version the record keeps picks the copy, and one that isn't installed gives the copy it gave.
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0");
assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0");
// The widths of a composite font.
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1");
assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0");
// A font installed once is set in that copy whatever the widths.
install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]);
assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0");
// Of several copies that set the characters at the widths, the first in the order the faces
// are found (the first loaded).
install(&[
(true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")),
(false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")),
(false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")),
]);
assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1");
}
/// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character
/// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large
/// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point
@@ -6051,7 +6150,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
// A PDF part the layers don't draw as.
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names);
assert!(read, "{notes:?}");
@@ -6060,7 +6159,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() {
assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}");
assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}");
// A PDF part that draws as those layers, with the drawn art: the envelope opens live.
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names);
assert!(read, "{notes:?}");
let (envelopes, loose) = envelopes_and_type(&d);
@@ -6088,7 +6187,7 @@ fn layers_that_open_alone_read_their_text_once() {
let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]);
let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1)));
let file = private(&native_with_text(&art, &doc));
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok();
let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok();
let (opened, texts, frames) = text_reads(false, open);
let Some((d, notes)) = opened else { panic!("didn't open without the page") };
assert_eq!((texts, frames), (1, 1), "{notes:?}");
@@ -6107,7 +6206,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() {
let file = private(&native_with_text(&art, "not a text document"));
let names = crate::NameEncoding::default();
let open = || {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names)
};
let (opened, texts, frames) = text_reads(false, open);
@@ -6134,7 +6233,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() {
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// A PDF part the layers don't draw as: they open alone, after a build with the page and one without.
@@ -6218,7 +6317,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr
let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn));
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names);
assert!(read, "{notes:?}");
let (envelopes, loose) = envelopes_and_type(&d);
@@ -6312,7 +6411,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// The layers alone, with the envelope's drawn art: what the page draws.
@@ -6355,7 +6454,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document, trust: bool| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names)
};
let (mut page, _, _) = open(pdf_part(80.0, 80.0), false);
@@ -6394,7 +6493,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do
let file = private(&native_with_text(&layer("Art", true, &art), &doc));
let names = crate::NameEncoding::default();
let open = |page: Document| {
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") };
let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") };
crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names)
};
// The layers alone, with the drawn art of both envelopes, but the first's: the page draws
+51 -18
View File
@@ -44,7 +44,7 @@ fn style_word(w: &str) -> String {
/// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy
/// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`).
fn bare_name(name: &str) -> &str {
pub(super) fn bare_name(name: &str) -> &str {
let name = match name.split_once('+') {
Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
@@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str {
}
/// The font of type that a text document's font record names: by `name`, its PostScript name, and
/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that
/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the
/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the
/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face
/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`])
/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is
/// Microsoft YaHei). → (family, style, version).
///
/// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family
pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option<String>) {
named_font(name, version).unwrap_or_else(|| {
pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option<String>) {
named_font(name, version, widths).unwrap_or_else(|| {
let (family, style) = family_style(name);
let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family);
(family, style, None)
@@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin
}
/// The font of type set in the installed face of PostScript name `name` (a subset prefix and a
/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and
/// style, and its version when the family and style alone resolve to another installed copy of
/// the font. A library can keep two copies under one family and style that differ in their
/// PostScript names or their versions, and draw the same text at different widths. → (family,
/// style, version); `None` when no installed face has the name.
pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option<String>)> {
let face = postscript_face(bare_name(name), version)?;
/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths`
/// ([`postscript_face`]): that face's own family and style, and its version when the family and
/// style alone resolve to another installed copy of the font. A library can keep two copies under
/// one family and style that differ in their PostScript names or their versions, and draw the same
/// text at different widths. → (family, style, version); `None` when no installed face has the name.
pub(crate) fn named_font(
name: &str,
version: Option<&str>,
widths: Option<&vectorcraft_pdf::FontWidths>,
) -> Option<(String, String, Option<String>)> {
let face = postscript_face(bare_name(name), version, widths)?;
// As the PDF import names a version: only one that the family and style don't resolve to.
let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style);
let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone());
Some((face.family.clone(), face.style.clone(), version))
}
/// How far an installed face's advance may be from the width a page gives a character, in
/// thousandths of an em, for the face to set it at that width: files write widths rounded.
const PAGE_WIDTH_SLACK: f64 = 1.0;
/// The most characters of a page's font [`sets_page_widths`] compares.
const MAX_WIDTHS_COMPARED: usize = 512;
/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`])
/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters
/// in code-point order are compared; a character the face has no glyph for isn't set at its width.
fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool {
let k = 1000.0 / face.units_per_em();
widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| {
let gid = face.glyph_for(*c);
gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK
})
}
/// The installed face of PostScript name `name` (without a subset prefix), among the installed
/// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there
/// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named
/// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in
/// `version` when it is installed, else the first. `None` when no installed face has the name.
/// `version` when it is installed. Without a version, copies whose names, family and style are all
/// one can still set the type at other widths: of those, the first that sets the characters of
/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which
/// compares the first 512 characters). Else the first. `None` when no installed face has the name.
///
/// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces
pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option<Arc<vectorcraft_text::FontFace>> {
pub(crate) fn postscript_face(
name: &str,
version: Option<&str>,
widths: Option<&vectorcraft_pdf::FontWidths>,
) -> Option<Arc<vectorcraft_text::FontFace>> {
let db = vectorcraft_text::FontDb::global();
let found = db.find_postscript(name)?;
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) {
let widths = widths.filter(|_| version.is_none());
let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w));
if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) {
return Some(found);
}
let faces = db.postscript_faces(name);
let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect();
let pool = if named.is_empty() { faces } else { named };
let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned());
Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found))
let by_widths = || pool.iter().find(|f| on_page(f)).cloned();
Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found))
}
/// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the
@@ -620,7 +653,7 @@ impl Interp<'_> {
}
// The installed face of that PostScript name, as type from a text document takes it; else
// the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei".
let (font_family, font_style, font_version) = document_font(&name, None);
let (font_family, font_style, font_version) = document_font(&name, None, None);
let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() };
let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() };
let mut t = TextObject::point(Point::ZERO, text, style);
+1
View File
@@ -38,6 +38,7 @@ mod entry;
mod reshaped;
mod state;
pub(crate) use cid::replacement;
#[cfg(test)]
pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical};
#[cfg(any(test, feature = "read-count"))]
+1 -5
View File
@@ -842,11 +842,7 @@ impl<'p> Builder<'p> {
let data = o.font_data();
let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone()));
let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic));
// A subset's six-letter tag.
let ps = name.as_deref().map(|n| match n.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(),
_ => n.to_string(),
});
let ps = name.as_deref().map(|n| crate::import_scan::without_subset_tag(n).to_string());
let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps));
let n = match (installed, name) {
(Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) },
+1 -1
View File
@@ -70,7 +70,7 @@ impl CidText {
}
/// A ToUnicode value that names no character: U+FFFD alone (#708).
pub(super) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool {
pub(crate) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool {
use craft_pdf::interpret::hayro_cmap::BfString;
match u {
BfString::Char(c) => *c == char::REPLACEMENT_CHARACTER,
+22 -6
View File
@@ -1041,19 +1041,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option<Vertical>
/// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]`
/// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the
/// range. At most [`MAX_CIDS`] CIDs are read.
fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per`
/// is 1 or 3.
pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
let mut it = a.flex_iter();
let mut read = 0;
loop {
if let Some((first, list)) = it.next::<(u32, Array<'_>)>() {
let values: Vec<f64> = list.iter::<f64>().collect();
for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) {
// Read as they are given, no more than the CIDs read take.
let mut values = list.iter::<f64>();
let mut v = [0.0; 3];
for cid in first..=u32::MAX {
let Some(group) = v.get_mut(..per) else { return };
if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) {
break;
}
read += 1;
if read > MAX_CIDS {
return;
}
each(cid, v);
each(cid, group);
}
} else if per == 1
&& let Some((first, last, w)) = it.next::<(u32, u32, f64)>()
@@ -1081,11 +1088,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) {
}
}
/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO
/// 32000-1 §9.6.4).
pub(crate) fn without_subset_tag(name: &str) -> &str {
match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest,
_ => name,
}
}
/// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its
/// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its
/// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one,
/// the `BaseFont` without the CMap's name on its end.
fn font_name(f: &Dict<'_>) -> Option<String> {
pub(crate) fn font_name(f: &Dict<'_>) -> Option<String> {
if f.get::<Name<'_>>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") {
if let Some(base) = f.get::<Name<'_>>(b"BaseFont") {
return Some(String::from_utf8_lossy(base.as_ref()).into_owned());
+1 -5
View File
@@ -1148,11 +1148,7 @@ impl Families {
/// The family and style of a font with base (PostScript) name `name`, or of weight `weight`
/// and slant `italic` when the name has no style; whether the family is available.
pub fn resolve(&self, name: &str, weight: Option<u32>, italic: bool) -> (String, String, bool) {
// A subset's six-letter tag.
let name = match name.split_once('+') {
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest,
_ => name,
};
let name = crate::import_scan::without_subset_tag(name);
// An installed face of that exact PostScript name: its own family and style.
if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) {
return (family, style, true);
+2
View File
@@ -61,6 +61,7 @@ mod lab_spot;
mod linearize;
mod marks;
mod output;
mod page_widths;
mod pages;
mod patch;
mod pdfx;
@@ -83,6 +84,7 @@ pub use import::{
INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE,
holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note,
};
pub use page_widths::{FontWidths, PageWidths};
#[cfg(any(test, feature = "read-count"))]
pub use pages::reads_of;
pub use pages::{
+598
View File
@@ -0,0 +1,598 @@
//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font
//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a
//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for
//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1
//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2).
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use craft_pdf::interpret::hayro_cmap::{BfString, CMap};
use craft_pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream};
use craft_pdf::syntax::page::Resources;
use crate::import::replacement;
use crate::import_scan::{cid_ranges, font_name, without_subset_tag};
/// The most fonts read.
const MAX_FONTS: usize = 256;
/// The most form XObjects looked into, and how deep they may nest.
const MAX_FORMS: usize = 4096;
const MAX_FORM_DEPTH: u32 = 16;
/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the
/// file together (one budget for the whole file, not one a page).
const MAX_KEYS: usize = 1 << 16;
/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts
/// share by reference is read once. A subset's array is a few kilobytes.
const MAX_WIDTH_TEXT: usize = 4 << 20;
/// The most characters of a font kept.
const MAX_CHARS: usize = 4096;
/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one
/// is left unread.
const MAX_TO_UNICODE: usize = 256 << 10;
/// The most bytes of `ToUnicode` maps decoded, all fonts together.
const MAX_TO_UNICODE_TOTAL: usize = 4 << 20;
/// How far apart two widths a file gives one character of one font may be and still be one width,
/// in thousandths of an em: files write widths rounded.
const SAME_WIDTH: f32 = 1.0;
/// The widths a page gives the characters of one font, in thousandths of an em, by character.
pub type FontWidths = BTreeMap<char, f32>;
/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts
/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what
/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type
/// its text document holds, so they tell installed copies of one font apart. A font whose subsets
/// give one character two widths gives none. Cloning it, or a font's widths, shares them.
#[derive(Clone, Debug, Default)]
pub struct PageWidths {
fonts: Arc<HashMap<String, Arc<FontWidths>>>,
}
impl PageWidths {
/// Each character the pages set in the font of PostScript name `name` (exactly, without a
/// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in
/// that font, or its subsets give a character two widths.
pub fn widths(&self, name: &str) -> Option<&Arc<FontWidths>> {
self.fonts.get(name)
}
}
/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One
/// dictionary that pages or forms share is read from the same place each time (one in an object
/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents
/// would hash it again for each of them.
fn dict_key(d: &Dict<'_>) -> (usize, usize) {
let text = d.data();
(text.as_ptr() as usize, text.len())
}
/// Each CID a composite font's `W` gives a width, and that width.
type CidWidths = Rc<[(u32, f32)]>;
/// What [`page_widths`] has read so far.
#[derive(Default)]
struct Walk {
/// Each font's characters and widths; `None` when two subsets disagree.
fonts: HashMap<String, Option<FontWidths>>,
/// The font dictionaries, form XObjects and resource dictionaries already looked at.
seen_fonts: HashSet<(usize, usize)>,
seen_forms: HashSet<ObjectIdentifier>,
walked: HashSet<(usize, usize)>,
/// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read.
maps: HashMap<ObjectIdentifier, Option<Rc<CMap>>>,
/// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256
/// numbers) and a composite font's `W` (each CID and its width).
simple_widths: HashMap<ObjRef, Option<Rc<[f32]>>>,
cid_widths: HashMap<ObjRef, Option<CidWidths>>,
/// How many entries of resource dictionaries have been looked at.
looked: usize,
/// How many bytes of `ToUnicode` maps have been decoded.
decoded: usize,
/// How many width arrays have been read, and how many bytes of them.
arrays_read: usize,
width_text: usize,
}
impl Walk {
/// Note `widths`, characters of the font of PostScript name `name` and their widths. A width
/// another subset gave the character already must be the same.
fn add(&mut self, name: String, widths: Vec<(char, f32)>) {
let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new()));
let Some(have) = slot else { return };
for (c, w) in widths {
if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) {
*slot = None;
return;
}
if have.len() < MAX_CHARS {
have.insert(c, w);
}
}
}
/// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been.
fn look(&mut self) -> bool {
self.looked += 1;
self.looked <= MAX_KEYS
}
/// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to
/// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach
/// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it,
/// at most the limit: a stream written plain comes back whole without being decoded.
fn character_map(&mut self, s: &Stream<'_>) -> Option<Rc<CMap>> {
let id = s.obj_id();
if !self.maps.contains_key(&id) {
let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1);
let data = s.decoded_within(left).ok();
self.decoded += data.as_ref().map_or(left, |d| d.len().min(left));
let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None));
self.maps.insert(id, map.map(Rc::new));
}
self.maps.get(&id)?.clone()
}
/// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it.
fn width_array<'a>(&mut self, array: Option<Array<'a>>) -> Option<Array<'a>> {
let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?;
self.arrays_read += 1;
self.width_text += array.data().len();
Some(array)
}
/// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name
/// the same array.
fn simple_widths(&mut self, f: &Dict<'_>) -> Option<Rc<[f32]>> {
let read = |w: &mut Self| w.width_array(f.get::<Array<'_>>(b"Widths")).map(|a| a.iter::<f32>().take(256).collect::<Rc<[f32]>>());
let Some(r) = f.get_ref(b"Widths") else { return read(self) };
if let Some(have) = self.simple_widths.get(&r) {
return have.clone();
}
let got = read(self);
self.simple_widths.insert(r, got.clone());
got
}
/// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all
/// the fonts that name the same array.
fn cid_widths(&mut self, d: &Dict<'_>) -> Option<CidWidths> {
let read = |w: &mut Self| {
let a = w.width_array(d.get::<Array<'_>>(b"W"))?;
let mut out = Vec::new();
cid_ranges(&a, 1, |cid, v| {
if let [w0] = v {
out.push((cid, *w0 as f32));
}
});
Some(out.into())
};
let Some(r) = d.get_ref(b"W") else { return read(self) };
if let Some(have) = self.cid_widths.get(&r) {
return have.clone();
}
let got = read(self);
self.cid_widths.insert(r, got.clone());
got
}
}
/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw.
pub(crate) fn page_widths<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> PageWidths {
let walk = walk(pages);
let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect();
PageWidths { fonts: Arc::new(fonts) }
}
/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once,
/// though pages and forms share it; a form without resources of its own takes those of what draws
/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at.
fn walk<'a>(pages: impl IntoIterator<Item = &'a Resources<'a>>) -> Walk {
let mut w = Walk::default();
let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect();
while let Some((res, depth)) = stack.pop() {
if w.walked.insert(dict_key(&res.fonts)) {
for key in res.fonts.keys() {
if w.seen_fonts.len() >= MAX_FONTS || !w.look() {
break;
}
let Some(f) = res.fonts.get::<Dict<'_>>(key.as_ref()) else { continue };
if w.seen_fonts.insert(dict_key(&f))
&& let Some((name, widths)) = font_widths(&f, &mut w)
{
w.add(name, widths);
}
}
}
if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) {
continue;
}
for key in res.x_objects.keys() {
if w.seen_forms.len() >= MAX_FORMS || !w.look() {
break;
}
let Some(s) = res.x_objects.get::<Stream<'_>>(key.as_ref()) else { continue };
let d = s.dict();
let form = d.get::<Name<'_>>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form");
if let (true, Some(own)) = (form, d.get::<Dict<'_>>(b"Resources"))
&& w.seen_forms.insert(s.obj_id())
{
stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1));
}
}
}
w
}
/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each
/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode`
/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding;
/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A
/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its
/// widths are in its own glyph space) and a font whose codes' characters can't be told.
fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> {
let subtype = f.get::<Name<'_>>(b"Subtype")?;
if subtype.as_ref() == b"Type3" {
return None;
}
let name = without_subset_tag(&font_name(f)?).to_string();
let composite = subtype.as_ref() == b"Type0";
let encoding = f.get::<Name<'_>>(b"Encoding");
let to_unicode = f.get::<Stream<'_>>(b"ToUnicode").and_then(|s| walk.character_map(&s));
let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding");
if to_unicode.is_none() && !win_ansi {
return None;
}
let char_of = |code: u32| match &to_unicode {
Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) {
Some(BfString::Char(c)) => Some(c),
_ => None,
},
None => win_ansi_char(code),
};
let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w);
let mut widths = Vec::new();
if composite {
if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) {
return None;
}
let d = f.get::<Array<'_>>(b"DescendantFonts").and_then(|a| a.iter::<Dict<'_>>().next())?;
for (cid, w) in walk.cid_widths(&d)?.iter() {
if widths.len() >= MAX_CHARS {
break;
}
if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) {
widths.push((c, w));
}
}
} else {
let first = f.get::<u32>(b"FirstChar")?;
// A simple font's codes are bytes.
for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) {
if let (Some(c), Some(w)) = (char_of(code), width(*w)) {
widths.push((c, w));
}
}
}
Some((name, widths))
}
/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252
/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which
/// it gives the space and the hyphen a second time.
fn win_ansi_char(code: u32) -> Option<char> {
/// Codes 128 to 159; `\0` where the encoding has no character.
const HIGH: [char; 32] = [
'\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}',
'\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}',
'\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}',
];
match code {
0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code),
0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'),
_ => None,
}
}
#[cfg(test)]
mod tests {
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
/// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`.
fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String {
format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>")
}
/// The pages' fonts are read from their resources and from the forms they draw, a subset's
/// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out)
/// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one
/// font come together; a font whose subsets give a character two widths, a font in another
/// encoding without a `ToUnicode` map, and a Type 3 font give none.
#[test]
fn the_pages_give_each_font_the_widths_of_its_characters() {
let extra = first_extra(2);
let fonts = [
simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"),
simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"),
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \
/DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>"
),
simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"),
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>"
),
"<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>"
.to_string(),
simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"),
];
let resources = |fonts: &[String], more: &str| {
let list: Vec<String> = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect();
format!("/Font << {} >> {more}", list.join(" "))
};
let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") };
let second = PdfPage {
resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""),
..PdfPage::new(100.0, 100.0, "")
};
let cmap =
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n";
let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480");
let file = pdf_with(
&[first, second],
&[
&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()),
&format!(
"<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream"
),
],
None,
);
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>());
assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)]));
assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)]));
assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)]));
assert_eq!(got("Formed"), Some(vec![('a', 480.0)]));
for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] {
assert_eq!(got(none), None, "{none}");
}
}
/// [`super::walk`] of the pages of `file`.
fn walked(file: &[u8]) -> super::Walk {
let o = crate::open_pdf(file, None).unwrap();
let pages = o.pdf.pages();
super::walk(pages.iter().map(|p| p.resources()))
}
/// Each resource dictionary is walked once: forms without resources of their own (which take
/// those of what draws them), forms that share one, and pages that share one look at each
/// entry once, so a file of thousands of them reads in time in proportion to it.
#[test]
fn shared_resources_are_walked_once() {
let n = 4000;
let extra = first_extra(1);
let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500");
// Forms without resources, then forms that share one resource dictionary (the last object).
let shared = extra + 2 * n;
let forms: Vec<String> = (0..2 * n)
.map(|i| {
let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") };
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream")
})
.chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600"))))
.collect();
let names: Vec<String> = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect();
let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let refs: Vec<&str> = forms.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed"));
// The page's font and forms, and the shared dictionary's font.
assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked);
// A thousand pages that share one font dictionary of 4000 entries.
let pages_n = 1000;
let extra = first_extra(pages_n);
let entries: Vec<String> = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect();
let objects: Vec<String> = std::iter::once(format!("<< {} >>", entries.join(" ")))
.chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500")))
.collect();
let pages: Vec<PdfPage> =
(0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect();
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&pages, &refs, None));
assert_eq!(w.fonts.len(), 50);
assert!(w.looked <= n, "{} entries looked at", w.looked);
}
/// Past [`super::MAX_FONTS`] fonts no more entries are looked at.
#[test]
fn fonts_past_the_most_read_are_not_looked_at() {
let fonts: Vec<String> =
(0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let w = walked(&pdf_with(&[page], &[], None));
assert_eq!(w.fonts.len(), super::MAX_FONTS);
assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked);
}
/// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font
/// dictionary of more entries than that, all naming one font, is looked at that far.
#[test]
fn entries_past_the_most_looked_at_are_left() {
let extra = first_extra(1);
let entries: Vec<String> = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect();
let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None));
assert_eq!(w.fonts.len(), 1);
assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked);
}
/// A width array that fonts share by reference is read once for all of them: 128 composite
/// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers.
#[test]
fn a_width_array_fonts_share_is_read_once() {
let numbers = 100_000;
let big: String = std::iter::repeat_n("500 ", numbers).collect();
let extra = first_extra(1);
let cmap = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n";
let fonts: Vec<String> = (0..256)
.map(|i| {
if i % 2 == 0 {
format!(
"/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>",
extra + 1
)
} else {
format!(
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
extra + 2
)
}
})
.collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let file = pdf_with(
&[page],
&[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")],
None,
);
let w = walked(&file);
assert_eq!(w.arrays_read, 2);
assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text);
assert_eq!(w.fonts.len(), 256);
assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0))));
}
/// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with
/// an array of a million bytes, the sixth gives no widths.
#[test]
fn width_arrays_past_the_most_read_are_left() {
let big: String = std::iter::repeat_n("500 ", 250_000).collect();
let extra = first_extra(1);
let fonts: Vec<String> = (0..6)
.map(|i| {
format!(
"/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>",
extra + i
)
})
.collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let arrays: Vec<String> = (0..6).map(|_| format!("[{big}]")).collect();
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert_eq!(w.arrays_read, 5);
assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5);
}
/// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an
/// incomplete last group left out) and a range's to each, and reads no more of a long list than
/// the CIDs it takes.
#[test]
fn cid_ranges_give_each_cid_its_values() {
let extra = first_extra(1);
let long: String = std::iter::repeat_n("7 ", 70_000).collect();
let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")];
let page = PdfPage {
resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2),
..PdfPage::new(10.0, 10.0, "")
};
let refs: Vec<&str> = arrays.iter().map(String::as_str).collect();
let file = pdf_with(&[page], &refs, None);
let o = crate::open_pdf(&file, None).unwrap();
let pages = o.pdf.pages();
let props = &pages.iter().next().unwrap().resources().properties;
let ranges = |key: &str, per: usize| {
let mut out = vec![];
crate::import_scan::cid_ranges(&props.get::<craft_pdf::syntax::object::Array<'_>>(key).unwrap(), per, |cid, v| {
out.push((cid, v.to_vec()))
});
out
};
let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::<Vec<_>>();
assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)]));
assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]);
assert_eq!(ranges("C", 1).len(), 65_536);
}
/// A `ToUnicode` map written plain and longer than the limits is charged no more than a
/// decoded one could be: the small maps of the other fonts are still read.
#[test]
fn a_long_plain_map_leaves_the_others_read() {
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 {
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
}
big.push_str("endcmap\n");
let small = "begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n";
let extra = first_extra(1);
let cid = |name: &str, map: usize| {
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
extra + map
)
};
let n = 40;
let fonts: Vec<String> =
std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let objects: Vec<String> = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len()))
.chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len())))
.collect();
let refs: Vec<&str> = objects.iter().map(String::as_str).collect();
let w = walked(&pdf_with(&[page], &refs, None));
assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big"));
assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n);
assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded);
}
/// A `ToUnicode` map is parsed once however many fonts name it, and one longer than
/// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or
/// compressed: its fonts give no widths.
#[test]
fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() {
use std::io::Write as _;
let small =
"begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string();
let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n");
while big.len() <= super::MAX_TO_UNICODE {
big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n");
}
big.push_str("endcmap\n");
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
z.write_all(big.as_bytes()).unwrap();
let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect();
let extra = first_extra(1);
let cid = |name: &str, map: usize| {
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \
/DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>",
extra + map
)
};
let fonts: Vec<String> = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect();
let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") };
let file = pdf_with(
&[page],
&[
&format!("<< /Length {} >>\nstream\n{small}endstream", small.len()),
&format!("<< /Length {} >>\nstream\n{big}endstream", big.len()),
&format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1),
],
None,
);
let w = walked(&file);
assert_eq!(w.maps.len(), 3, "each map parsed once");
// Each long one charged up to just past the limit.
assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded);
assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread");
let widths = crate::open_pdf(&file, None).unwrap().page_widths();
assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::<Vec<_>>()), Some(vec![('A', 500.0)]));
assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none());
// Every font of the name shares one map of its widths.
assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap()));
}
}
+7
View File
@@ -276,6 +276,13 @@ impl Opened {
crate::file_info::file_info_in(&self.pdf)
}
/// The widths the pages give the characters of the fonts they set type in, from the fonts'
/// dictionaries ([`crate::PageWidths`]), without importing any page's art.
pub fn page_widths(&self) -> crate::PageWidths {
let pages = self.pdf.pages();
crate::page_widths::page_widths(pages.iter().map(|p| p.resources()))
}
/// How many pages the PDF has, as [`info`] lists them.
pub fn page_count(&self) -> usize {
self.pdf.pages().len()
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long