Merge pull request #9128 from dotCooCoo/fix/print-fonts-setting

Print: the Fonts setting chooses how PostScript output sends type
This commit is contained in:
BFlat authored and GitHub committed 2026-11-24 16:06:58 +07:00
commit c3c02f81e0
11 files changed
+786 -16

No files matched your search

+8 -3
View File
@@ -5,7 +5,7 @@
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_eps::{Level, PrintJob, PrintPage};
use vectorcraft_eps::{Level, PrintFonts, PrintJob, PrintPage};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre Line truncated
has_doc,
setup
),
@@ -276,6 +276,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string());
}
let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness);
let fonts = match set.graphics.fonts {
vectorcraft_pdf::FontDownload::None => PrintFonts::Resident,
vectorcraft_pdf::FontDownload::Subset => PrintFonts::Subset,
vectorcraft_pdf::FontDownload::Complete => PrintFonts::Complete,
};
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
let pages: Vec<PrintPage> = plan
@@ -294,7 +299,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
ink: sh.ink.as_ref().map(|i| (i.name.as_str(), i.frequency, i.angle)),
})
.collect();
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness };
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness, fonts };
let out = vectorcraft_eps::print(&pages, &plan.order, &job).map_err(|e| bad(PRINT, e))?;
for w in plan.warnings.iter().chain(&out.warnings) {
if !warnings.contains(w) {
+30
View File
@@ -125,3 +125,33 @@ fn type_that_does_not_fit_its_frame_is_named_when_its_artboard_prints() {
let (_, v) = print_ps(&mut s, json!({"settings": {"artboards": "range", "range": "1"}}));
assert_eq!(over(&v), 0, "{v}");
}
/// Graphics › Fonts reaches the PostScript output: Subset (the default) sends each page the
/// glyphs it shows, None names the printer's font and sends none, Complete sends every glyph once
/// before the first page. PDF output notes that it embeds subsets.
#[test]
fn the_fonts_setting_chooses_how_type_is_sent() {
let mut s = session(1);
s.execute("text.create", &json!({"x": 20, "y": 100, "text": "Ab", "size": 24})).unwrap();
assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["graphics"]["fonts"], "subset");
let fonts = |s: &mut Session, f: &str| print_ps(s, json!({"settings": {"graphics": {"fonts": f}}}));
let (ps, _) = print_ps(&mut s, json!({}));
let page = ps.split("%%Page: ").nth(1).unwrap();
assert_eq!(page.matches("/FontType 3 def").count(), 1, "{ps}");
assert_eq!(page.matches("> show").count(), 2, "{page}");
assert_eq!(dsc(&ps, "DocumentSuppliedResources"), ["font VCft0.0"]);
let (ps, v) = fonts(&mut s, "none");
assert!(!ps.contains("FontType") && !ps.contains("%%BeginResource"), "{ps}");
assert_eq!(dsc(&ps, "DocumentNeededResources").len(), 1, "{ps}");
assert!(v["warnings"].to_string().contains("the printer needs the font"), "{v}");
let (ps, _) = fonts(&mut s, "complete");
let (head, pages) = ps.split_once("%%EndSetup").unwrap();
assert!(head.contains("/FontType 3 def") && !pages.contains("FontType") && pages.contains("> show"), "{ps}");
let (ps, _) = fonts(&mut s, "subset");
assert_eq!(ps.split("%%Page: ").nth(1).unwrap().matches("/FontType 3 def").count(), 1);
// PDF output embeds subsets whatever the setting, and says so.
for (f, noted) in [("none", true), ("subset", false), ("complete", true)] {
let v = s.execute("file.print", &json!({"settings": {"graphics": {"fonts": f}}})).unwrap();
assert_eq!(v["warnings"].to_string().contains("PDF print embeds subsets"), noted, "{f}: {v}");
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ pub use import::{
family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page,
};
pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask};
pub use print::{PrintJob, PrintPage, print};
pub use print::{PrintFonts, PrintJob, PrintPage, print};
use vectorcraft_doc::Document;
use vectorcraft_geom::{Point, Rect};
+75 -9
View File
@@ -2,6 +2,7 @@
//! document walk the EPS writer uses, in one DSC-conforming file: a page per sheet with its paper
//! size, the ink and halftone screen of a separation, the flatness, and film negatives.
use std::cell::RefCell;
use std::fmt::Write;
use kurbo::{Shape, Vec2};
@@ -11,6 +12,11 @@ use vectorcraft_geom::{Affine, Rect};
use crate::scene::{Page, Scene};
use crate::{EpsOptions, EpsOutput, Level, comments, ps};
pub(crate) mod fonts;
pub use fonts::PrintFonts;
use fonts::{FontJob, UsedGlyphs};
/// One sheet of a print job (see the PDF writer's print plan for how the spaces relate).
#[derive(Clone, Debug)]
pub struct PrintPage<'a> {
@@ -47,6 +53,8 @@ pub struct PrintJob {
pub created: Option<i64>,
/// The flatness curves are drawn with (device pixels); `None`: the device's own.
pub flatness: Option<f64>,
/// How the type is written: as outlines, or shown through fonts.
pub fonts: PrintFonts,
}
/// Every number of `a` finite?
@@ -55,8 +63,9 @@ fn finite(a: Affine) -> bool {
}
/// The program that draws sheet `p` (its page setup and content, without the DSC page comment),
/// and what its walks found.
fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
/// and what its walks found. Its type is shown through the job's `fonts`; the page setup defines
/// the fonts it shows, except the ones a Complete job defines in its setup.
fn sheet(p: &PrintPage, job: &PrintJob, fonts: Option<&RefCell<FontJob>>) -> Result<(String, Vec<Page>), String> {
let (w, h) = p.size;
let r = p.area;
if !(w.is_finite() && h.is_finite() && w >= 1.0 && h >= 1.0 && [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
@@ -70,7 +79,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
}
let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() };
let art_opts = opts(r);
let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run();
let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).with_fonts(fonts).run();
// The marks' area: the drawing space the page shows (within the tile).
let paper = Rect::new(0.0, 0.0, w, h);
let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper };
@@ -79,7 +88,12 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
// the copies show.
let shown = moves.iter().map(|m| shown - *m).reduce(|a, b| a.union(b)).unwrap_or(shown);
let marks_opts = opts(shown);
let marks = p.marks.map(|m| Scene::new(p.doc, &marks_opts).run_node(m));
let marks = p.marks.map(|m| Scene::new(p.doc, &marks_opts).with_fonts(fonts).run_node(m));
let mut page_fonts = String::new();
if let Some(f) = fonts.filter(|f| f.borrow().mode != PrintFonts::Complete) {
let used = used_glyphs(std::iter::once(&art).chain(marks.as_ref()));
f.borrow_mut().define(&used, &mut page_fonts)?;
}
let mut s = String::with_capacity(art.body.len() + art.setup.len() + 1024);
let (wi, hi) = (w.ceil() as i64, h.ceil() as i64);
let _ = writeln!(s, "%%PageBoundingBox: 0 0 {wi} {hi}");
@@ -89,6 +103,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec<Page>), String> {
}
s.push_str("%%BeginPageSetup\n");
let _ = writeln!(s, "/setpagedevice where {{pop << /PageSize [{} {}] >> setpagedevice}} if", ps::num(w), ps::num(h));
s.push_str(&page_fonts);
s.push_str("%%EndPageSetup\nVCdict begin\nq\n");
if p.negative {
// Ink becomes clear and paper black: the inverted transfer paints the paper's white black.
@@ -149,8 +164,25 @@ pub fn print(pages: &[PrintPage], order: &[usize], job: &PrintJob) -> Result<Eps
let mut drawn = Vec::with_capacity(pages.len());
let mut custom: Vec<(String, [f32; 4])> = vec![];
let mut warnings: Vec<String> = vec![];
for p in pages {
let (s, found) = sheet(p, job)?;
let fonts = (job.fonts != PrintFonts::Outlines).then(|| RefCell::new(FontJob::new(job.fonts)));
let mut used = UsedGlyphs::new();
// Only the sheets `order` prints are drawn: the fonts, warnings and colors of the others stay
// out of the file.
let mut printed = vec![false; pages.len()];
for i in order {
if let Some(p) = printed.get_mut(*i) {
*p = true;
}
}
for (p, printed) in pages.iter().zip(printed) {
if !printed {
drawn.push(String::new());
continue;
}
let (s, found) = sheet(p, job, fonts.as_ref())?;
for (face, gids) in used_glyphs(&found) {
used.entry(face).or_default().extend(gids);
}
for page in found {
for c in page.custom {
if !custom.iter().any(|(n, _)| *n == c.0) {
@@ -165,23 +197,57 @@ pub fn print(pages: &[PrintPage], order: &[usize], job: &PrintJob) -> Result<Eps
}
drawn.push(s);
}
// A Complete job defines every glyph of each face it shows once, before the first page.
let (mut setup, mut setting_notes, mut resources) = (String::new(), vec![], vec![]);
if let Some(f) = &fonts {
let mut f = f.borrow_mut();
let used = if f.mode == PrintFonts::Complete { f.every_glyph(&used) } else { used };
if f.mode == PrintFonts::Complete {
f.define(&used, &mut setup)?;
}
resources = f.resources(&used);
for w in f.warnings.drain(..) {
if !warnings.contains(&w) {
warnings.push(w);
}
}
setting_notes.append(&mut f.notes);
}
let (w, h) = pages.iter().fold((0.0f64, 0.0f64), |(w, h), p| (w.max(p.size.0), h.max(p.size.1)));
let size: usize = order.iter().filter_map(|i| drawn.get(*i)).map(String::len).sum();
let mut s = String::with_capacity(size + 4096);
let mut s = String::with_capacity(size + setup.len() + 4096);
s.push_str("%!PS-Adobe-3.0\n"); // brand-ok: the DSC version line every conforming file starts with
comments(&mut s, &job.title, job.created, job.level, &custom);
// The printer's fonts the job needs, or the fonts it sends.
let key = if job.fonts == PrintFonts::Resident { "%%DocumentNeededResources: " } else { "%%DocumentSuppliedResources: " };
for (i, name) in resources.iter().enumerate() {
let _ = writeln!(s, "{}font {name}", if i == 0 { key } else { "%%+ " });
}
let _ = writeln!(s, "%%BoundingBox: 0 0 {} {}", w.ceil() as i64, h.ceil() as i64);
let _ = writeln!(s, "%%Pages: {}\n%%PageOrder: Ascend\n%%EndComments", order.len());
s.push_str("%%BeginProlog\n");
s.push_str(ps::PROLOG);
s.push_str("%%EndProlog\n%%BeginSetup\n%%EndSetup\n");
s.push_str("%%EndProlog\n%%BeginSetup\n");
s.push_str(&setup);
s.push_str("%%EndSetup\n");
for (n, i) in order.iter().enumerate() {
let page = drawn.get(*i).ok_or("a page out of range")?;
let _ = writeln!(s, "%%Page: {0} {0}", n + 1);
s.push_str(page);
}
s.push_str("%%Trailer\n%%EOF\n");
Ok(EpsOutput { bytes: s.into_bytes(), warnings, setting_notes: vec![] })
Ok(EpsOutput { bytes: s.into_bytes(), warnings, setting_notes })
}
/// The glyphs `pages` showed through the job's fonts, together.
fn used_glyphs<'p>(pages: impl IntoIterator<Item = &'p Page>) -> UsedGlyphs {
let mut used = UsedGlyphs::new();
for page in pages {
for (face, gids) in &page.fonts {
used.entry(*face).or_default().extend(gids);
}
}
used
}
#[cfg(test)]
+276
View File
@@ -0,0 +1,276 @@
//! The fonts a print job shows its type in: Type 3 fonts drawn from the faces' own outlines, sent
//! with the pages that use them or once for the whole job, or the printer's own copy of each font,
//! asked for by its PostScript name.
//!
//! A face's glyphs are shown through fonts of at most 256 glyphs each: glyph `gid` is code
//! `gid % 256` of the face's font number `gid / 256`, so every page and the job's setup name each
//! glyph the same way.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write;
use std::sync::Arc;
use craft_ps::write::{PathOps, push_path};
use kurbo::{BezPath, Shape};
use vectorcraft_text::FontFace;
use vectorcraft_text::embed::Embedding;
use crate::ps;
/// How a print job writes its type.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum PrintFonts {
/// As glyph outlines in the art: no fonts.
#[default]
Outlines,
/// In the printer's copy of each font, asked for by its PostScript name: no font program is
/// sent, and a printer without the font substitutes another.
Resident,
/// In fonts holding the glyphs each page shows, sent with that page.
Subset,
/// In fonts holding every glyph of each face the job shows, sent once before the first page.
Complete,
}
/// Most bytes the font definitions of one page, or of a job's setup, may take.
pub(crate) const MAX_FONTS: usize = 64 << 20;
/// The glyphs a walk showed through fonts: the job's index of each face → its glyph ids.
pub(crate) type UsedGlyphs = BTreeMap<usize, BTreeSet<u32>>;
/// One face the job shows type in.
struct JobFace {
face: Arc<FontFace>,
/// Its type is shown through fonts (false: drawn as outlines, for its license).
shown: bool,
}
/// The fonts of a whole job, shared by the walks of its sheets.
pub(crate) struct FontJob {
pub mode: PrintFonts,
/// Most bytes the font definitions of one page, or of the job's setup, may take
/// ([`MAX_FONTS`]).
pub max: usize,
/// The faces in the order the job first shows them.
faces: Vec<JobFace>,
/// Face id ([`FontFace::id`]) → its index in `faces`.
by_id: HashMap<u32, usize>,
/// Glyph names in the faces' `post` or `CFF` tables, read once ([`PrintFonts::Resident`]).
names: HashMap<(usize, u32), Option<String>>,
/// What prints otherwise than the mode asks.
pub warnings: Vec<String>,
/// Notes on the mode: the fonts the printer must have.
pub notes: Vec<String>,
}
/// The name a job's font number `chunk` of face `face` is defined and shown by.
pub(crate) fn font_name(face: usize, chunk: u32) -> String {
format!("VCft{face}.{chunk}")
}
/// The face's name as the warnings give it.
fn display_name(face: &FontFace) -> String {
format!("{} {}", face.family, face.style)
}
/// Is `name` a glyph name a PostScript name literal can carry as it is?
fn plain_name(name: &str) -> bool {
!name.is_empty() && name.len() <= 127 && name.bytes().all(|b| b.is_ascii_graphic() && !b"[](){}<>/%".contains(&b))
}
fn push_unique(v: &mut Vec<String>, s: String) {
if !v.contains(&s) {
v.push(s);
}
}
impl FontJob {
pub fn new(mode: PrintFonts) -> Self {
Self { mode, max: MAX_FONTS, faces: vec![], by_id: HashMap::new(), names: HashMap::new(), warnings: vec![], notes: vec![] }
}
/// The job's index of the face of glyph `gid` of face `id`, and the face's units per em, when
/// the glyph is shown through a font; `None` when it is drawn as an outline. `elements` is the
/// number of path elements of the glyph's outline in the layout: an outline the layout changed
/// from the face's own is drawn as it is.
pub fn glyph(&mut self, id: u32, gid: u32, elements: usize) -> Option<(usize, f64)> {
let i = self.face(id)?;
let face = self.faces.get(i)?.face.clone();
if vectorcraft_text::FontDb::global().outline(&face, gid).elements().len() != elements {
return None;
}
if self.mode == PrintFonts::Resident && self.glyph_name(i, gid).is_none() {
push_unique(
&mut self.warnings,
format!("some glyphs of the font “{}” have no names to ask the printer's copy for: they print as outlines", display_name(&face)),
);
return None;
}
Some((i, face.units_per_em()))
}
/// The job's index of face `id` when its type is shown through fonts.
fn face(&mut self, id: u32) -> Option<usize> {
if let Some(i) = self.by_id.get(&id) {
return self.faces.get(*i).filter(|f| f.shown).map(|_| *i);
}
let face = vectorcraft_text::FontDb::global().face_by_id(id)?;
let name = display_name(&face);
let shown = match (self.mode, face.embedding()) {
(PrintFonts::Outlines, _) => false,
(PrintFonts::Resident, _) => {
push_unique(&mut self.notes, format!("Fonts: None: the printer needs the font “{}” ({})", face.postscript_name(), name));
true
}
(PrintFonts::Subset | PrintFonts::Complete, Embedding::Forbidden) => {
push_unique(
&mut self.warnings,
format!("the license of the font “{name}” doesn't allow sending it to the printer: its type prints as outlines"),
);
false
}
(PrintFonts::Subset, Embedding::Whole) => {
push_unique(
&mut self.warnings,
format!("the font “{name}” may only be sent whole, and Fonts is Subset: its type prints as outlines (Complete sends it)"),
);
false
}
(PrintFonts::Subset | PrintFonts::Complete, _) => face.units_per_em() > 0.0,
};
let i = self.faces.len();
self.faces.push(JobFace { face, shown });
self.by_id.insert(id, i);
shown.then_some(i)
}
/// The name of glyph `gid` of the job's face `i` that a PostScript name literal can carry.
fn glyph_name(&mut self, i: usize, gid: u32) -> Option<String> {
if let Some(n) = self.names.get(&(i, gid)) {
return n.clone();
}
let name = self.faces.get(i).and_then(|f| f.face.glyph_name(gid)).filter(|n| plain_name(n) && n != ".notdef");
self.names.insert((i, gid), name.clone());
name
}
/// Every glyph of every face the job shows through fonts ([`PrintFonts::Complete`]).
pub fn every_glyph(&self, used: &UsedGlyphs) -> UsedGlyphs {
used.keys().filter_map(|i| Some((*i, (0..self.faces.get(*i)?.face.glyph_count()).collect()))).collect()
}
/// The fonts `used` names, as DSC resource names: the printer's fonts with
/// [`PrintFonts::Resident`], else the fonts the job defines.
pub fn resources(&self, used: &UsedGlyphs) -> Vec<String> {
let mut out = vec![];
for (i, gids) in used {
match self.faces.get(*i) {
Some(f) if self.mode == PrintFonts::Resident => push_unique(&mut out, f.face.postscript_name()),
Some(_) => {
for chunk in gids.iter().map(|g| g >> 8).collect::<BTreeSet<_>>() {
push_unique(&mut out, font_name(*i, chunk));
}
}
None => {}
}
}
out
}
/// Append the definitions of the fonts that show `used` to `s`: Type 3 fonts holding those
/// glyphs, or, with [`PrintFonts::Resident`], the printer's fonts with an encoding naming them.
/// An error, before `s` holds any of them, when they would take more than [`Self::max`] bytes.
pub fn define(&mut self, used: &UsedGlyphs, s: &mut String) -> Result<(), String> {
let mut out = String::new();
self.define_into(used, &mut out)?;
s.push_str(&out);
Ok(())
}
fn define_into(&mut self, used: &UsedGlyphs, s: &mut String) -> Result<(), String> {
for (i, gids) in used {
let Some(face) = self.faces.get(*i).map(|f| f.face.clone()) else { continue };
let mut chunks: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
for g in gids {
chunks.entry(g >> 8).or_default().push(*g);
}
let ps_name = face.postscript_name();
if self.mode == PrintFonts::Resident {
let _ = writeln!(s, "%%IncludeResource: font {ps_name}");
}
for (chunk, gids) in chunks {
let name = font_name(*i, chunk);
if self.mode == PrintFonts::Resident {
// The printer's font, with an encoding that gives each glyph its code.
let _ = writeln!(s, "/{ps_name} findfont dup length dict begin\n{{1 index /FID ne {{def}} {{pop pop}} ifelse}} forall");
s.push_str("/Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for\n");
for g in gids {
if let Some(n) = self.glyph_name(*i, g) {
let _ = writeln!(s, "Encoding {} /{n} put", g & 0xff);
}
}
let _ = writeln!(s, "currentdict end /{name} exch definefont pop");
} else if !type3(s, &name, &face, &gids, self.max.saturating_sub(s.len())) {
return Err(too_large(&face, self.max));
}
if s.len() > self.max {
return Err(too_large(&face, self.max));
}
}
}
Ok(())
}
}
fn too_large(face: &FontFace, max: usize) -> String {
let size = if max >= 1 << 20 { format!("{} MB", max >> 20) } else { format!("{} KB", max >> 10) };
format!("the fonts to send take more than {size} (the font “{}” has {} glyphs): choose Fonts: Subset", display_name(face), face.glyph_count())
}
/// Append Type 3 font `name` holding glyphs `gids` of `face` (one font number: codes `gid % 256`)
/// to `s`, drawn from the face's outlines in its font units, y up. False, with nothing added to
/// `s`, when its glyph procedures take more than `room` bytes.
fn type3(s: &mut String, name: &str, face: &FontFace, gids: &[u32], room: usize) -> bool {
let db = vectorcraft_text::FontDb::global();
let upem = face.units_per_em();
let flip = kurbo::Affine::FLIP_Y;
let mut procs = String::new();
let mut bbox: Option<kurbo::Rect> = None;
for g in gids {
let outline: BezPath = flip * (*db.outline(face, *g)).clone();
let b = if outline.elements().is_empty() { kurbo::Rect::ZERO } else { outline.bounding_box() };
if !outline.elements().is_empty() {
bbox = Some(bbox.map_or(b, |r| r.union(b)));
}
let _ = write!(procs, "/g{g} {{{} 0 ", ps::num(face.advance(*g)));
ps::push_nums(&mut procs, &[b.x0, b.y0, b.x1, b.y1]);
procs.push_str("setcachedevice\n");
if !outline.elements().is_empty() {
push_path(&mut procs, &outline, PathOps::STANDARD);
procs.push_str("fill\n");
}
procs.push_str("} bind def\n");
if procs.len() > room {
return false;
}
}
let b = bbox.unwrap_or(kurbo::Rect::ZERO);
let _ = writeln!(s, "%%BeginResource: font {name}");
let _ = writeln!(s, "/{name} 10 dict begin\n/FontType 3 def");
s.push_str("/FontMatrix [");
ps::push_num_places(s, 1.0 / upem, 9);
s.push_str(" 0 0 ");
ps::push_num_places(s, 1.0 / upem, 9);
s.push_str(" 0 0] def\n/FontBBox [");
ps::push_nums(s, &[b.x0, b.y0, b.x1, b.y1]);
s.push_str("] def\n/Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for\n");
for g in gids {
let _ = writeln!(s, "Encoding {} /g{g} put", g & 0xff);
}
let _ = writeln!(s, "/CharProcs {} dict def\nCharProcs begin\n/.notdef {{0 0 0 0 0 0 setcachedevice}} bind def", gids.len() + 1);
s.push_str(&procs);
s.push_str("end\n/BuildGlyph {exch /CharProcs get exch 2 copy known not {pop /.notdef} if get exec} bind def\n");
s.push_str("/BuildChar {1 index /Encoding get exch get 1 index /BuildGlyph get exec} bind def\n");
s.push_str("currentdict end definefont pop\n%%EndResource\n");
true
}
+248
View File
@@ -416,3 +416,251 @@ fn an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_with
let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0));
assert_keeps_the_ink_below(&[("faint", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan")]);
}
/// A 200 × 100 pt document with `words` at 24 pt in black, in family `family`.
fn typed(words: &str, family: &str) -> Document {
let mut d = Document::new(200.0, 100.0);
let layer = d.layers[0].id;
let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() };
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), words, style))));
d.insert(Some(layer), 0, n).unwrap();
d
}
/// The regular face of `family`.
fn face_of(family: &str) -> std::sync::Arc<vectorcraft_text::FontFace> {
vectorcraft_text::FontDb::global().face(family, "Regular").unwrap()
}
/// The bundled fallback face as another family `family` (13 characters, like the bundled name),
/// whose license flags (OS/2 `fsType`) are `fs`.
fn licensed(family: &str, fs: u16) -> String {
let fallback = vectorcraft_text::FALLBACK_FAMILY;
let mut bytes = face_of(fallback).file_data().to_vec();
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(utf16(fallback), utf16(family)), (fallback.as_bytes().to_vec(), family.as_bytes().to_vec())] {
assert_eq!(from.len(), to.len());
let mut at = 0;
while let Some(i) = bytes[at..].windows(from.len()).position(|w| w == from) {
bytes[at + i..at + i + from.len()].copy_from_slice(&to);
at += i + from.len();
}
}
let tables = u16::from_be_bytes([bytes[4], bytes[5]]) as usize;
let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &bytes[*r..*r + 4] == b"OS/2").unwrap();
let off = u32::from_be_bytes(bytes[os2 + 8..os2 + 12].try_into().unwrap()) as usize;
bytes[off + 8..off + 10].copy_from_slice(&fs.to_be_bytes());
vectorcraft_text::FontDb::global().add_font(bytes);
assert!(vectorcraft_text::FontDb::global().has_family(family));
family.into()
}
/// The job's setup and each page's program.
fn sections(ps: &str) -> (&str, Vec<&str>) {
let setup = ps.split_once("%%BeginSetup\n").and_then(|(_, rest)| rest.split_once("%%EndSetup")).map_or("", |(setup, _)| setup);
(setup, ps.split("%%Page: ").skip(1).collect())
}
/// How many glyph procedures the Type 3 fonts in `ps` define.
fn procs(ps: &str) -> usize {
ps.lines().filter(|l| l.starts_with("/g") && l.ends_with("setcachedevice")).count()
}
fn fonts_job(fonts: PrintFonts) -> PrintJob {
PrintJob { fonts, ..PrintJob::default() }
}
#[test]
fn type_prints_as_outlines_unless_the_job_sends_fonts() {
assert_eq!(PrintJob::default().fonts, PrintFonts::Outlines);
let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY);
let ps = text(&print(&[page(&d, None)], &[0], &PrintJob::default()).unwrap());
assert!(!ps.contains("FontType") && !ps.contains("> show") && !ps.contains("Resources:"), "{ps}");
}
#[test]
fn subset_downloads_used_glyphs_once_per_page() {
let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY);
let sheets = [page(&d, None), PrintPage { ink: Some(("Black", 60.0, 45.0)), ..page(&d, None) }];
for level in [Level::Two, Level::Three] {
let out = print(&sheets, &[0, 1, 0], &PrintJob { level, ..fonts_job(PrintFonts::Subset) }).unwrap();
let ps = text(&out);
assert!(ps.contains("%%DocumentSuppliedResources: font VCft0.0\n"), "{ps}");
let (setup, pages) = sections(&ps);
assert!(!setup.contains("FontType"), "{setup}");
assert_eq!(pages.len(), 3);
for p in pages {
// Each printed page, copies and plates included, defines the font with A and B alone.
let (page_setup, body) = p.split_once("%%EndPageSetup").unwrap();
assert_eq!(page_setup.matches("/FontType 3 def").count(), 1, "{page_setup}");
assert_eq!(procs(page_setup), 2, "{page_setup}");
assert_eq!(body.matches("> show").count(), 3, "{body}");
assert!(body.contains("/VCft0.0 findfont"), "{body}");
assert_eq!(procs(body), 0);
}
assert!(out.warnings.is_empty() && out.setting_notes.is_empty(), "{:?} {:?}", out.warnings, out.setting_notes);
}
// Read back, the type the font shows draws where its outlines do.
let area = Rect::new(36.0, 36.0, 236.0, 136.0);
let drawn = |fonts| {
let out = print(&sheets[..1], &[0], &fonts_job(fonts)).unwrap();
render_region(&crate::import(&out.bytes).unwrap().document, area, 2.0)
};
let (outlined, shown) = (drawn(PrintFonts::Outlines), drawn(PrintFonts::Subset));
assert!(outlined.ink() > 200, "{}", outlined.ink());
let (a, b) = (outlined.ink() as f64, shown.ink() as f64);
assert!((a - b).abs() < a * 0.05, "outlines {a} px, fonts {b} px");
vectorcraft_testkit::raster::assert_similar(&outlined, &shown, 24.0, 0.002);
}
#[test]
fn complete_downloads_whole_font_once_before_pages() {
let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY);
let glyphs = face_of(vectorcraft_text::FALLBACK_FAMILY).glyph_count() as usize;
assert!(glyphs > 256, "{glyphs}");
let out = print(&[page(&d, None)], &[0, 0], &fonts_job(PrintFonts::Complete)).unwrap();
let ps = text(&out);
let (setup, pages) = sections(&ps);
// Every glyph of the face, in fonts of 256 glyphs, before the first page.
assert_eq!(procs(setup), glyphs);
assert_eq!(setup.matches("/FontType 3 def").count(), glyphs.div_ceil(256));
let header = ps.split_once("%%EndComments").unwrap().0;
let supplied = header.lines().filter(|l| l.starts_with("%%DocumentSuppliedResources: font ") || l.starts_with("%%+ font VCft")).count();
assert_eq!(supplied, glyphs.div_ceil(256), "{header}");
assert_eq!(pages.len(), 2);
for p in pages {
assert!(!p.contains("FontType") && procs(p) == 0, "{p}");
assert_eq!(p.matches("> show").count(), 3);
}
assert!(out.warnings.is_empty() && out.setting_notes.is_empty(), "{:?} {:?}", out.warnings, out.setting_notes);
// A sheet the order doesn't print sends no font, in any mode.
let plain = doc();
for fonts in [PrintFonts::Complete, PrintFonts::Subset, PrintFonts::Resident] {
let out = print(&[page(&plain, None), page(&d, None)], &[0], &fonts_job(fonts)).unwrap();
let ps = text(&out);
assert!(!ps.contains("FontType") && !ps.contains("Resources:") && !ps.contains("findfont"), "{fonts:?}: {ps}");
assert!(out.setting_notes.is_empty(), "{fonts:?}: {:?}", out.setting_notes);
}
}
#[test]
fn none_references_font_without_downloading_it() {
let face = face_of(vectorcraft_text::FALLBACK_FAMILY);
let name = face.postscript_name();
let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY);
let out = print(&[page(&d, None)], &[0, 0], &fonts_job(PrintFonts::Resident)).unwrap();
let ps = text(&out);
assert!(!ps.contains("FontType") && !ps.contains("setcachedevice") && !ps.contains("%%BeginResource"), "{ps}");
assert!(ps.contains(&format!("%%DocumentNeededResources: font {name}\n")), "{ps}");
let (_, pages) = sections(&ps);
assert_eq!(pages.len(), 2);
for p in pages {
let (page_setup, body) = p.split_once("%%EndPageSetup").unwrap();
assert!(page_setup.contains(&format!("%%IncludeResource: font {name}\n")), "{page_setup}");
// The printer's font, re-encoded with the names of the glyphs the page shows.
assert!(page_setup.contains(&format!("/{name} findfont dup length dict begin")), "{page_setup}");
assert!(page_setup.contains(" /A put\n") && page_setup.contains(" /B put\n"), "{page_setup}");
assert_eq!(body.matches("> show").count(), 3, "{body}");
}
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes.len(), 1, "{:?}", out.setting_notes);
assert!(out.setting_notes[0].contains(&name), "{:?}", out.setting_notes);
}
#[test]
fn forbidden_font_stays_art_with_a_note() {
let locked = licensed("Locked Sans 3", 0x0002);
let whole = licensed("Entire Sans 3", 0x0100);
let fonts_of = |family: &str, fonts| {
let d = typed("AB", family);
let out = print(&[page(&d, None)], &[0], &fonts_job(fonts)).unwrap();
(text(&out), out.warnings)
};
for fonts in [PrintFonts::Subset, PrintFonts::Complete] {
let (ps, warnings) = fonts_of(&locked, fonts);
assert!(!ps.contains("FontType") && !ps.contains("> show"), "{ps}");
assert!(warnings.iter().any(|w| w.contains(&locked) && w.contains("doesn't allow")), "{warnings:?}");
}
// A font that may only be sent whole prints as outlines in a subset job and is sent complete.
let (ps, warnings) = fonts_of(&whole, PrintFonts::Subset);
assert!(!ps.contains("FontType") && !ps.contains("> show"), "{ps}");
assert!(warnings.iter().any(|w| w.contains(&whole) && w.contains("whole")), "{warnings:?}");
let (ps, warnings) = fonts_of(&whole, PrintFonts::Complete);
assert!(sections(&ps).0.contains("/FontType 3 def") && ps.contains("> show"), "{ps}");
assert!(warnings.is_empty(), "{warnings:?}");
// None sends no font program, so the license doesn't keep it from naming the font.
let (ps, warnings) = fonts_of(&locked, PrintFonts::Resident);
assert!(ps.contains("> show") && !ps.contains("FontType"), "{ps}");
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn complete_large_font_fails_before_partial_output() {
let face = face_of(vectorcraft_text::FALLBACK_FAMILY);
let gid = face.glyph_for('A');
let elements = vectorcraft_text::FontDb::global().outline(&face, gid).elements().len();
let mut job = fonts::FontJob::new(PrintFonts::Complete);
let (i, _) = job.glyph(face.id(), gid, elements).unwrap();
let used = job.every_glyph(&fonts::UsedGlyphs::from([(i, std::collections::BTreeSet::from([gid]))]));
job.max = 64 << 10;
let mut s = String::from("before\n");
let e = job.define(&used, &mut s).unwrap_err();
assert!(e.contains("64 KB") && e.contains("Subset"), "{e}");
assert_eq!(s, "before\n");
// With room, every glyph is defined.
job.max = fonts::MAX_FONTS;
job.define(&used, &mut s).unwrap();
assert_eq!(procs(&s), face.glyph_count() as usize);
}
#[test]
fn type_left_out_for_the_page_limit_sends_none_of_its_glyphs() {
let family = vectorcraft_text::FALLBACK_FAMILY;
let face = face_of(family);
let kept = typed("A", family);
let mut both = kept.clone();
let layer = both.layers[0].id;
let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() };
let n = Node::new(both.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 90.0), "BCDEFGH", style))));
both.insert(Some(layer), 1, n).unwrap();
let o = EpsOptions { region: kept.artboards[0].rect, ..EpsOptions::default() };
let walk = |d: &Document, max: usize| {
let job = RefCell::new(fonts::FontJob::new(PrintFonts::Subset));
crate::scene::Scene::new(d, &o).with_fonts(Some(&job)).with_max_body(max).run()
};
let alone = walk(&kept, usize::MAX);
assert_eq!(alone.fonts.values().map(|g| g.len()).sum::<usize>(), 1, "{:?}", alone.fonts);
// The second object passes the limit and is left out: only the glyph of the first is used.
let page = walk(&both, alone.body.len() + 10);
assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings);
assert_eq!(page.body, alone.body);
assert_eq!(page.fonts, alone.fonts);
assert!(page.fonts.values().all(|g| g.contains(&face.glyph_for('A'))), "{:?}", page.fonts);
}
#[test]
fn ruby_prints_as_outlines_where_the_canvas_draws_it() {
let family = vectorcraft_text::FALLBACK_FAMILY;
let mut d = Document::new(200.0, 100.0);
let layer = d.layers[0].id;
let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() };
let mut t = TextObject::point(Point::new(20.0, 60.0), "AB", style);
t.ruby = vec![vectorcraft_doc::RubySpan::new(0, 2, "xy")];
let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t)));
d.insert(Some(layer), 0, n).unwrap();
let area = Rect::new(36.0, 36.0, 236.0, 136.0);
let drawn = |fonts| {
let out = print(&[page(&d, None)], &[0], &fonts_job(fonts)).unwrap();
(text(&out), render_region(&crate::import(&out.bytes).unwrap().document, area, 2.0))
};
let (_, outlined) = drawn(PrintFonts::Outlines);
for fonts in [PrintFonts::Subset, PrintFonts::Complete] {
let (ps, shown) = drawn(fonts);
// The base text shows through the font; its reading is drawn as outlines, in place.
assert_eq!(ps.matches("> show").count(), 2, "{fonts:?}: {ps}");
if fonts == PrintFonts::Subset {
assert_eq!(procs(&ps), 2, "{ps}");
}
vectorcraft_testkit::raster::assert_similar(&outlined, &shown, 24.0, 0.002);
}
}
+103 -3
View File
@@ -2,6 +2,7 @@
//! space (the page's first operator maps it onto PostScript's y-up space). Mirrors the PDF
//! writer's walk, without transparency.
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
@@ -14,6 +15,7 @@ use vectorcraft_doc::{
use vectorcraft_effects::stroke::{self, WrittenShape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2};
use crate::print::fonts::{FontJob, UsedGlyphs, font_name};
use crate::ps::{self, clip_op, fill_op, push_nums, push_path};
use crate::{EpsOptions, Level, Overprint};
@@ -149,6 +151,8 @@ pub(crate) struct Page {
pub body: String,
pub custom: Vec<(String, [f32; 4])>,
pub warnings: Vec<String>,
/// The glyphs shown through the print job's fonts ([`Scene::with_fonts`]).
pub fonts: UsedGlyphs,
}
/// The colour spaces process colours are written in.
@@ -287,6 +291,14 @@ pub(crate) struct Scene<'a> {
/// The gradient being painted overprints on a plate: where it is paper white it puts none of
/// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]).
keep_below: bool,
/// The print job's fonts: type in a solid fill is shown through them (`None`: drawn as
/// outlines).
fonts: Option<&'a RefCell<FontJob>>,
/// The glyphs shown through `fonts`.
used: UsedGlyphs,
/// The glyphs `used` gained, in the order it gained them: an object left out for the page
/// limit takes its own back out of `used` ([`Self::forget_glyphs`]).
used_order: Vec<(usize, u32)>,
}
impl<'a> Scene<'a> {
@@ -317,9 +329,18 @@ impl<'a> Scene<'a> {
nest: 0,
plate: false,
keep_below: false,
fonts: None,
used: UsedGlyphs::new(),
used_order: vec![],
}
}
/// This scene showing type through the print job's fonts `fonts`.
pub fn with_fonts(mut self, fonts: Option<&'a RefCell<FontJob>>) -> Self {
self.fonts = fonts;
self
}
/// This scene drawing a separation's plate when `plate` is true: an overprinting gradient
/// paints only where it puts the plate's ink down, as an overprinting solid color that puts
/// none down is drawn as nothing on it.
@@ -400,7 +421,7 @@ impl<'a> Scene<'a> {
.filter(|(n, ..)| n != vectorcraft_color::swatch::REGISTRATION)
.map(|(_, colorant, cmyk)| (colorant.clone(), *cmyk))
.collect();
Page { setup: self.setup, body: self.body, custom, warnings: self.warnings }
Page { setup: self.setup, body: self.body, custom, warnings: self.warnings, fonts: self.used }
}
fn warn(&mut self, w: &str) {
@@ -544,7 +565,7 @@ impl<'a> Scene<'a> {
_ => {}
}
self.note_losses(n);
let (was, placed, codes) = (self.body.len(), self.placements.len(), self.codes.len());
let (was, placed, codes, glyphs) = (self.body.len(), self.placements.len(), self.codes.len(), self.used_order.len());
match &n.kind {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
children.iter().for_each(|c| self.node(c, false));
@@ -605,10 +626,23 @@ impl<'a> Scene<'a> {
self.body.truncate(was);
self.unplace(placed);
self.forget_codes(codes);
self.forget_glyphs(glyphs);
self.warn(TOO_LARGE);
}
}
/// Take the glyphs `used` gained after its first `n` back out of it.
fn forget_glyphs(&mut self, n: usize) {
for (face, gid) in self.used_order.drain(n.min(self.used_order.len())..) {
if let Some(gids) = self.used.get_mut(&face) {
gids.remove(&gid);
if gids.is_empty() {
self.used.remove(&face);
}
}
}
}
/// How long the page body will be: what is written and what its image placements add.
fn size(&self) -> usize {
self.body.len().saturating_add(self.pending)
@@ -901,8 +935,18 @@ impl<'a> Scene<'a> {
let _ = writeln!(self.body, "{} cm", ps::matrix(t.xf));
for (i, run) in t.runs.iter().enumerate() {
let mut bp = BezPath::new();
// With the job's fonts, a run in a solid fill shows its glyphs through them; `art`
// holds the outlines of those it draws as art.
let fonts = if matches!(run.style.fill, Paint::Solid { .. }) { self.fonts } else { None };
let mut shown = vec![];
let mut art = BezPath::new();
for g in layout.glyphs.iter().filter(|g| g.run == i) {
bp.extend(g.outline.iter());
match fonts.and_then(|f| self.font_of(f, g)) {
Some((face, upem)) => shown.push((face, upem, g)),
None if fonts.is_some() => art.extend(g.outline.iter()),
None => {}
}
// Colour bitmap glyphs (emoji): their images, which the run's paint doesn't paint.
if let Some((image, to_text)) = g.placed_image() {
let key = format!("\u{0}glyph\u{0}{}", image.blob.content_key());
@@ -916,11 +960,21 @@ impl<'a> Scene<'a> {
// Ruby (furigana) glyphs in their base text's run's paint, as the canvas draws them.
for g in layout.ruby.iter().filter(|g| g.run == i) {
bp.extend(g.outline.iter());
if fonts.is_some() {
art.extend(g.outline.iter());
}
}
if bp.elements().is_empty() {
continue;
}
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
if fonts.is_none() {
self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
} else {
self.show(&shown, &run.style.fill, run.style.overprint_fill);
if !art.elements().is_empty() {
self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill);
}
}
if run.style.has_stroke() {
// Character strokes are drawn in text space, with their cap, join and dashes.
self.stroke(&bp, FillRule::NonZero, &run.style.stroke_layer(), layout.bounds);
@@ -948,6 +1002,52 @@ impl<'a> Scene<'a> {
}
}
/// The job's index of the face of glyph `g` and its units per em when `g` is shown through
/// the job's fonts `fonts` (recorded in `used`); `None` when it is drawn as an outline: a glyph
/// with no outline, a color glyph, one bent along a path, or one its face's fonts don't show.
fn font_of(&mut self, fonts: &RefCell<FontJob>, g: &vectorcraft_text::PositionedGlyph) -> Option<(usize, f64)> {
if g.outline.elements().is_empty() || g.bend.is_some() || g.image.is_some() || g.colour.is_some() || !invertible(g.xf) {
return None;
}
let (face, upem) = fonts.borrow_mut().glyph(g.font_id, g.gid, g.outline.elements().len())?;
if self.used.entry(face).or_default().insert(g.gid) {
self.used_order.push((face, g.gid));
}
Some((face, upem))
}
/// Show `glyphs` (the job's index of each one's face, its units per em, the glyph) through the
/// job's fonts in solid paint `p`: each glyph at its own place, through a font made for its
/// size and slant.
fn show(&mut self, glyphs: &[(usize, f64, &vectorcraft_text::PositionedGlyph)], p: &Paint, overprint: bool) {
let Paint::Solid { color, swatch, tint } = p else { return };
if glyphs.is_empty() {
return;
}
let on = self.overprint_on(overprint);
let ink = self.solid(color, swatch.as_deref(), *tint);
self.set_ink(ink);
let mut current: Option<(String, [f64; 4])> = None;
for (face, upem, g) in glyphs {
// Font units (y up) → text space: the glyph's own map after the flip to y down.
let [a, b, c, d, e, f] = (g.xf * Affine::scale_non_uniform(*upem, -*upem)).as_coeffs();
let name = font_name(*face, g.gid >> 8);
let key = (name, [a, b, c, d]);
if current.as_ref() != Some(&key) {
let _ = write!(self.body, "/{} findfont [", key.0);
for v in [a, b, c, d] {
ps::push_num_places(&mut self.body, v, 6);
self.body.push(' ');
}
self.line("0 0] makefont setfont");
current = Some(key);
}
push_nums(&mut self.body, &[e, f]);
let _ = writeln!(self.body, "moveto <{:02x}> show", g.gid & 0xff);
}
self.overprint_off(on);
}
// ---------- gradients ----------
/// The colour space a gradient's stops are written in, and its stops in it from offset 0 to 1
+8
View File
@@ -481,6 +481,14 @@ impl<'a> Job<'a> {
if !postscript && !set.graphics.auto_flatness {
setting_notes.push("a fixed flatness is not written yet: the output device flattens curves".into());
}
// PDF output embeds a subset of each font its license allows, as a saved PDF does;
// PostScript output follows Fonts.
if !postscript && set.graphics.fonts != FontDownload::Subset {
setting_notes.push(format!(
"PDF print embeds subsets of the fonts whose licenses allow it and draws the others as outlines: Fonts: {} applies to PostScript output",
set.graphics.fonts.label()
));
}
Ok(Self { doc, layouts, tiles, inks, document_inks, plates, sheets, warnings, setting_notes })
}
+22
View File
@@ -1377,3 +1377,25 @@ fn separations_use_the_cmyk_profile_assigned_to_the_document() {
d.color_profiles.cmyk = Some(vectorcraft_color::cms::DEVICE_CMYK.into());
assert_eq!(cyan(&d), 0.0, "Device CMYK puts a neutral grey on the black plate only");
}
/// PDF print embeds font subsets (where the font's license allows it) whatever Fonts says: None
/// and Complete get a note in the print
/// and its preview, Subset none. PostScript output, which follows Fonts, gets none.
#[test]
fn non_subset_font_choices_report_pdf_subset_output() {
let d = doc(200.0, 100.0, &[(Rect::new(10.0, 10.0, 60.0, 60.0), rgb(1.0, 0.0, 0.0))]);
for (fonts, label) in [("none", Some("None")), ("subset", None), ("complete", Some("Complete"))] {
let v = json!({"graphics": {"fonts": fonts}});
let note = |notes: &[String]| notes.iter().filter(|n| n.starts_with("PDF print embeds subsets")).cloned().collect::<Vec<_>>();
let want: Vec<String> = label
.map(|l| {
format!("PDF print embeds subsets of the fonts whose licenses allow it and draws the others as outlines: Fonts: {l} applies to PostScript output")
})
.into_iter()
.collect();
assert_eq!(note(&job(&d, v.clone()).setting_notes), want, "{fonts}");
assert_eq!(note(&preview(&d, &settings(v.clone())).unwrap().setting_notes), want, "{fonts}");
let plan = plan(&d, &PrintOptions { settings: settings(v), postscript: true, ..Default::default() }).unwrap();
assert!(note(&plan.setting_notes).is_empty(), "{fonts}: {:?}", plan.setting_notes);
}
}
+14
View File
@@ -10428,6 +10428,20 @@ DSC: `%%Pages` is the page count (copies included), each `%%Page` sets its paper
(`setflat`), negatives invert the transfer, and the marks print in Registration. PostScript has no transparency: it
is flattened first with `flattenerPreset` (`medium` by default; `high`, `low` or a saved one), with a warning.
The Graphics section's Fonts setting (`settings.graphics.fonts`) sets how the PostScript file carries type in a solid
fill, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=418)
describes the three choices. `subset` (the default) defines, in each page's setup, Type 3 fonts drawn from the face's
outlines that hold only the glyphs that page shows; copies and plates of a page define them again. `complete` defines
every glyph of each face the job shows once, in the job's setup, before the first page, and the job fails with an
error when those definitions would take more than 64 MB. `none` sends no font program: each page asks for the printer's
copy of the font by its PostScript name (`%%DocumentNeededResources`, `%%IncludeResource`) and gives each glyph's name
in an encoding, and a note names every font the printer needs. The file lists the fonts it sends in
`%%DocumentSuppliedResources`. Type that the fonts don't carry prints as outlines, as before: type in a gradient or
pattern, color glyphs, glyphs bent along a curved path, ruby, and with `none` a glyph the font gives no name. So does type in a
font whose license forbids embedding, and, with `subset`, a font that may only be embedded whole; both with a warning
naming the font. With any of the three, PDF output embeds subsets of the fonts whose licenses allow it and draws the
others as outlines, and `none` or `complete` adds a note saying so.
```json
{"name":"run_command","arguments":{"command":"file.print","params":{"path":"/tmp/job.ps","level":2,"settings":{"output":{"mode":"separations"}}}}}
```
+1
View File
@@ -2399,6 +2399,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged.
- The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged.
- On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells whose 8-bit samples carry none of the plate's ink out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate`, `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` and `print::tests::an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`.
- The Print dialog's Graphics section's Fonts setting now reaches PostScript output, with the three choices [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=418) describes: Subset (the default) sends each page Type 3 fonts holding only the glyphs that page shows, Complete sends every glyph of each font once before the first page (an error past 64 MB), and None sends no font and asks for the printer's own by its PostScript name, with a note naming each one. Type in a gradient or pattern, color glyphs, glyphs bent along a curved path, ruby, a glyph without a name under None, and fonts whose license forbids embedding (or allows only whole embedding, under Subset) print as outlines as before, the license cases with a warning. PDF print still embeds subsets of the fonts whose licenses allow it and draws the others as outlines, and None or Complete adds a note saying so. The outlines-as-fallback and the size limit are VectorCraft's own rules. Evidence: `print::tests::subset_downloads_used_glyphs_once_per_page`, `print::tests::complete_downloads_whole_font_once_before_pages`, `print::tests::none_references_font_without_downloading_it`, `print::tests::forbidden_font_stays_art_with_a_note`, `print::tests::complete_large_font_fails_before_partial_output` (`vectorcraft-eps`), `tests::printps::the_fonts_setting_chooses_how_type_is_sent`, `tests::print::non_subset_font_choices_report_pdf_subset_output` (`vectorcraft-pdf`). Print scores and hours are unchanged.
- The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged.
- The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged.
- A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626).