mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
* PDF import: keep embedded fonts for text whose family isn't installed Glyphs drawn in an embedded font whose family isn't available are gathered during import and built into one small TrueType font per family and style, kept with the document (font/ttf blob). Text objects record the fonts and a hash of their text: layout and rendering draw them in the kept font until the text is edited (undo restores it) or the family is installed. Lines are spaced against the file's own widths with per-glyph placement (#3756). * PDF import: satisfy crate layering constraints without format dev-dep * FileFont: negate us_win_descent in i32 to prevent overflow on extreme negative descenders * PDF import: a kept font carries the file font's licence flags, and the docs say what that means Review of #4569: the fsType of the file's font is copied to the font built from its glyphs (a test pins it against Embedding), so exports honour it; the docs state the limits, that the file's font program is not parsed, and that a saved file carries third-party glyphs. * PDF import: a glyph curve far outside any glyph is left out; docs say what the limits and the font program mean CodeRabbit on #4569: coordinates beyond 1e6 font units are refused before the curve is subdivided. The docs say the 64-font limit is what draws one type object and that the file's font program is read only for its licence flags and metrics. * PDF import: two programs of one font keep the stricter licence flags; the docs cite their sources CodeRabbit on #4569: embedded programs of one family and style share one built font, which kept the first program's fsType; it now takes the stricter of the two, whichever came first. The docs entry cites the Acrobat Help pages and the OpenType fsType specification. * fmt * PDF import: embedded fonts are on by default, with an opt-out preference Owner decision on #4568. Preferences > File Handling > Use fonts embedded in imported PDFs (pdfImportEmbeddedFonts, on by default) and the embeddedFonts param of document.open and file.place: off, a PDF's type in a font the machine lacks is set in the fallback font with the missing-font warning, as before. One test each for on and off, one for the preference reaching the options. * fmt after merging main * docs: restore the status lines damaged by merges (main's line plus this PR's note) * PDF import: set embedded_fonts through a builder method (keeps read_opened under the complexity limit) * PDF import: move the missing-font notes out of read_opened (complexity limit after the merge) * #4569: isolate file-font resources and reclaim live faces (UNVERIFIED) * Preserve carried-font ownership across placement and recovery * Fix carried-font regression test dependencies and unwind probe * Use explicit OS2 heights in owned-font reference regression * Keep native font regression artwork inside document layers * fix(engine): bind file fonts when reading document profiles * test(engine): initialize file-font leases in new image fixtures * test: complete file-font lease initialization in image fixtures * docs: keep the #4568 entry in the file-format parity status line * fix(pdf): keep a line with another glyph for the same character as outlines (review) A font kept with the document has one glyph per character. A glyph of the file's font that differs from the one already kept for its character (a stylistic alternate that maps to the same Unicode scalar) marks its line, which is imported as outlines so each glyph draws as the file does. * docs: resolve the leftover status-line conflict * Placed document blob: give the new ImageBlob literal its file_font * Test: a PDF's two glyphs for one character survive a native save and reopen as the file draws them * Test: move the native save and reopen half of the two-glyphs regression to the engine (layers: no format dev-dep in pdf) * Fix embedded-font preference help and English fallback checks * Format embedded-font preference help with the workspace edition --------- Co-authored-by: FredApps <[email protected]> Co-authored-by: skylartaylor <[email protected]>
596 lines
31 KiB
Rust
596 lines
31 KiB
Rust
//! `document.open` PDF options `textAs` and `layers`.
|
|
|
|
use serde_json::{Value, json};
|
|
use vectorcraft_doc::NodeKind;
|
|
use vectorcraft_pdf::TextAs;
|
|
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
|
|
|
|
use super::*;
|
|
|
|
fn open(s: &mut Session, bytes: &[u8], extra: Value) -> crate::Result<Value> {
|
|
let mut p = json!({"name": "art.pdf", "dataBase64": vectorcraft_format::base64_encode(bytes)});
|
|
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
|
o.extend(e);
|
|
}
|
|
s.execute("document.open", &p)
|
|
}
|
|
|
|
fn kinds(s: &Session) -> Vec<&'static str> {
|
|
let mut out = vec![];
|
|
s.active().unwrap().doc.walk(|n| out.push(n.kind_label()));
|
|
out
|
|
}
|
|
|
|
#[test]
|
|
fn text_opens_as_type_or_outlines() {
|
|
let page = PdfPage {
|
|
resources: "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>".into(),
|
|
..PdfPage::new(200.0, 100.0, "BT /F1 12 Tf 10 50 Td (Hello) Tj ET")
|
|
};
|
|
let bytes = pdf(&[page], None);
|
|
let mut s = Session::new();
|
|
open(&mut s, &bytes, json!({})).unwrap();
|
|
assert!(kinds(&s).contains(&"Type"), "{:?}", kinds(&s));
|
|
let r = open(&mut s, &bytes, json!({"textAs": "outlines"})).unwrap();
|
|
assert!(!kinds(&s).contains(&"Type"));
|
|
assert!(r["warnings"].to_string().contains("outlines"), "{r}");
|
|
let e = open(&mut s, &bytes, json!({"textAs": "glyphs"})).unwrap_err().to_string();
|
|
assert!(e.contains("textAs must be one of text, outlines"), "{e}");
|
|
}
|
|
|
|
fn live_text_pdf() -> Vec<u8> {
|
|
let page = |text: &str| PdfPage {
|
|
resources: "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>".into(),
|
|
..PdfPage::new(200.0, 100.0, &format!("BT /F1 12 Tf 10 50 Td ({text}) Tj ET"))
|
|
};
|
|
pdf(&[page("First page"), page("Second page")], None)
|
|
}
|
|
|
|
fn live_texts(s: &Session) -> Vec<String> {
|
|
let mut texts = vec![];
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if let NodeKind::Text(t) = &n.kind {
|
|
texts.push(t.plain_text());
|
|
}
|
|
});
|
|
texts
|
|
}
|
|
|
|
#[test]
|
|
fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() {
|
|
let bytes = live_text_pdf();
|
|
let dir = vectorcraft_testkit::TempDir::new("pdf-place-live-text");
|
|
let path = dir.join("text.pdf");
|
|
std::fs::write(&path, &bytes).unwrap();
|
|
for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] {
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
|
let mut p = source;
|
|
p["page"] = json!(2);
|
|
let r = s.execute("file.place", &p).unwrap();
|
|
assert_eq!(live_texts(&s), ["Second page"], "{r}");
|
|
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn pdf_clipboard_paste_keeps_live_text_on_the_selected_page() {
|
|
let bytes = live_text_pdf();
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
|
let r = s.execute("clipboard.importPdf", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "page": 2})).unwrap();
|
|
s.execute("edit.paste", &json!({})).unwrap();
|
|
assert_eq!(live_texts(&s), ["Second page"], "{r}");
|
|
assert!(!r["warnings"].to_string().contains("outlines"), "{r}");
|
|
}
|
|
|
|
#[test]
|
|
fn pdf_place_honors_explicit_text_outlines() {
|
|
let bytes = live_text_pdf();
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
|
let r =
|
|
s.execute("file.place", &json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "textAs": "outlines"})).unwrap();
|
|
assert!(live_texts(&s).is_empty());
|
|
assert!(r["warnings"].to_string().contains("outlines"), "{r}");
|
|
}
|
|
|
|
#[test]
|
|
fn layers_option_keeps_or_flattens_optional_content() {
|
|
let (a, b) = (first_extra(1), first_extra(1) + 1);
|
|
let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << /OFF [{b} 0 R] >> >> ");
|
|
let page = PdfPage {
|
|
resources: format!("/Properties << /A {a} 0 R /B {b} 0 R >>"),
|
|
..PdfPage::new(100.0, 100.0, "/OC /A BDC 0 g 0 0 10 10 re f EMC /OC /B BDC 0 g 20 20 10 10 re f EMC")
|
|
};
|
|
let bytes = pdf_with_catalog(&[page], &["<< /Type /OCG /Name (Ink) >>", "<< /Type /OCG /Name (Notes) >>"], &catalog, None);
|
|
let mut s = Session::new();
|
|
open(&mut s, &bytes, json!({})).unwrap();
|
|
let layers: Vec<(String, bool)> = s.active().unwrap().doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect();
|
|
assert_eq!(layers, [("Ink".to_string(), true), ("Notes".to_string(), false)]);
|
|
open(&mut s, &bytes, json!({"layers": false})).unwrap();
|
|
let doc = &s.active().unwrap().doc;
|
|
assert_eq!(doc.layers.len(), 1);
|
|
assert_eq!(doc.layers[0].children().unwrap().len(), 1, "the hidden art is left out");
|
|
assert!(matches!(doc.layers[0].kind, NodeKind::Layer { .. }));
|
|
assert!(open(&mut s, &bytes, json!({"layers": "no"})).unwrap_err().to_string().contains("layers must be true or false"));
|
|
}
|
|
|
|
/// A PDF-compatible `.ai` without the editor's private data opens its layers from its optional
|
|
/// content groups, whose names without a byte order mark are PDFDocEncoding.
|
|
#[test]
|
|
fn ai_layer_names_are_read_as_pdf_doc_encoding() {
|
|
let (a, b) = (first_extra(1), first_extra(1) + 1);
|
|
let catalog = format!("/OCProperties << /OCGs [{a} 0 R {b} 0 R] /D << >> >> ");
|
|
let page = PdfPage {
|
|
resources: format!("/Properties << /A {a} 0 R /B {b} 0 R >>"),
|
|
..PdfPage::new(100.0, 100.0, "/OC /A BDC 0 g 0 0 10 10 re f EMC /OC /B BDC 0 g 20 20 10 10 re f EMC")
|
|
};
|
|
let bytes = pdf_with_catalog(&[page], &[r"<< /Type /OCG /Name (Art\205final) >>", "<< /Type /OCG /Name (Notes) >>"], &catalog, None);
|
|
let mut s = Session::new();
|
|
s.execute("document.open", &json!({"name": "art.ai", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
|
let names: Vec<String> = s.active().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
|
|
assert_eq!(names, ["Art\u{2013}final", "Notes"]);
|
|
}
|
|
|
|
#[test]
|
|
fn load_options_read_text_and_layers() {
|
|
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false, "hiddenLayers": true, "embeddedFonts": false})).unwrap();
|
|
assert_eq!((o.text_as, o.layers, o.hidden_layers, o.embedded_fonts), (TextAs::Outlines, false, true, false));
|
|
assert!(o.is_partial(), "without its hidden layers, Save doesn't write the file back");
|
|
let d = LoadOptions::default();
|
|
assert_eq!((d.text_as, d.layers, d.is_partial()), (TextAs::Text, true, false));
|
|
assert_eq!((d.hidden_layers, d.embedded_fonts), (false, true));
|
|
let n = LoadOptions { native: false, ..Default::default() };
|
|
assert!(n.is_partial(), "without the document it carries, Save doesn't write the file back");
|
|
}
|
|
|
|
#[test]
|
|
fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
|
|
let page = PdfPage {
|
|
resources: "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Zyxwvu-Serif >> >>".into(),
|
|
..PdfPage::new(200.0, 100.0, "BT /F1 12 Tf 10 50 Td (Hello) Tj ET")
|
|
};
|
|
let mut s = Session::new();
|
|
let r = open(&mut s, &pdf(&[page], None), json!({})).unwrap();
|
|
let fonts = s.execute("text.fonts", &json!({})).unwrap();
|
|
let family = fonts[0]["family"].as_str().unwrap().to_string();
|
|
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
|
|
assert!(r["warnings"].to_string().contains(&family), "opening lists it: {r}");
|
|
let warned = |s: &mut Session, p: Value| {
|
|
let w = s.execute("document.serialize", &p).unwrap()["warnings"].to_string();
|
|
w.contains(&family) && w.contains(vectorcraft_text::FALLBACK_FAMILY)
|
|
};
|
|
for p in [
|
|
json!({"format": "pdf"}),
|
|
json!({"format": "pdf", "advanced": {"outlineText": false}}),
|
|
json!({"format": "png"}),
|
|
json!({"format": "eps"}),
|
|
json!({"format": "emf"}),
|
|
json!({"format": "svg", "outlineText": true}),
|
|
json!({"format": "svg", "embedFonts": true}),
|
|
] {
|
|
assert!(warned(&mut s, p.clone()), "{p}");
|
|
}
|
|
// Live SVG type and the native file name the font itself.
|
|
for p in [json!({"format": "svg", "outlineText": false}), json!({"format": "vectorcraft"}), json!({"format": "txt"})] {
|
|
assert!(!warned(&mut s, p.clone()), "{p}");
|
|
}
|
|
let pdf_export = s.execute("document.exportPdf", &json!({})).unwrap();
|
|
assert!(pdf_export["warnings"].to_string().contains(&family), "{pdf_export}");
|
|
s.execute("text.replaceFont", &json!({"from": {"family": family}, "to": {"family": "Source Serif 4"}})).unwrap();
|
|
assert!(!warned(&mut s, json!({"format": "pdf"})), "replaced: nothing is substituted");
|
|
}
|
|
|
|
/// A page in a font the file carries that no machine has (`Zyxwvu-Serif`: a
|
|
/// simple TrueType font in WinAnsiEncoding, its program the bundled Source Serif 4's).
|
|
fn carried_font_pdf(content: &str, height: f64) -> Vec<u8> {
|
|
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
|
|
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
|
|
let widths: Vec<String> =
|
|
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
|
|
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
|
|
let n = first_extra(1);
|
|
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(300.0, height, content) };
|
|
let font = format!(
|
|
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
|
|
widths.join(" "),
|
|
n + 1
|
|
);
|
|
let descriptor = format!(
|
|
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
|
|
n + 2
|
|
);
|
|
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
|
|
pdf_with(&[page], &[&font, &descriptor, &file], None)
|
|
}
|
|
|
|
/// The glyphs of the active document's type (document space origins) and how many come from fonts
|
|
/// files carried.
|
|
fn glyphs(s: &Session) -> (Vec<kurbo::Point>, usize) {
|
|
let db = vectorcraft_text::FontDb::global();
|
|
let (mut at, mut carried) = (vec![], 0);
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if let NodeKind::Text(t) = &n.kind {
|
|
for g in vectorcraft_text::layout(db, t).glyphs {
|
|
at.push(t.xf * g.origin);
|
|
carried += usize::from(db.is_file_font(g.font_id));
|
|
}
|
|
}
|
|
});
|
|
(at, carried)
|
|
}
|
|
|
|
/// Type in a font the PDF carries that isn't installed keeps the file's look until it is edited:
|
|
/// no export says it is substituted, it saves and reopens so, and it stays listed as missing. Edited,
|
|
/// it takes the substitute, which exports then name.
|
|
#[test]
|
|
fn type_in_a_font_the_pdf_carries_keeps_its_look_until_edited() {
|
|
let mut s = Session::new();
|
|
let r = open(&mut s, &carried_font_pdf("BT /F1 24 Tf 20 50 Td (Hamburg Zoo) Tj ET", 100.0), json!({})).unwrap();
|
|
let fonts = s.execute("text.fonts", &json!({})).unwrap();
|
|
let family = fonts[0]["family"].as_str().unwrap().to_string();
|
|
assert_eq!(fonts[0]["status"], "missing", "{fonts}");
|
|
assert!(r["warnings"].to_string().contains("until their text is edited"), "{r}");
|
|
let missing = s.execute("text.missingFonts", &json!({})).unwrap();
|
|
assert!(missing["fonts"].to_string().contains(&family), "still missing: {missing}");
|
|
let (at, carried) = glyphs(&s);
|
|
assert_eq!((at.len(), carried), (11, 11), "every glyph the file's");
|
|
let warned = |s: &mut Session| s.execute("document.serialize", &json!({"format": "png"})).unwrap()["warnings"].to_string().contains(&family);
|
|
assert!(!warned(&mut s), "drawn as the file draws it: not substituted");
|
|
// Saved and opened again: the same.
|
|
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
|
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
|
|
assert_eq!(glyphs(&s), (at.clone(), carried));
|
|
// Edited: the substitute, which exports name, and the font still missing.
|
|
let mut id = None;
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if matches!(n.kind, NodeKind::Text(_)) {
|
|
id = Some(n.id);
|
|
}
|
|
});
|
|
let id = id.unwrap();
|
|
let preflight = |s: &mut Session| s.execute("document.preflight", &json!({})).unwrap()["findings"].clone();
|
|
assert!(!preflight(&mut s).to_string().contains(&family), "carried font is not substituted");
|
|
s.execute("text.setText", &json!({"id": id, "text": "Hamburg Zoo!"})).unwrap();
|
|
assert_eq!(glyphs(&s).1, 0, "edited: no glyph from the file's font");
|
|
assert!(warned(&mut s), "edited: substituted");
|
|
let findings = preflight(&mut s);
|
|
assert!(
|
|
findings.as_array().unwrap().iter().any(|f| f["code"] == "missingFont"
|
|
&& f["name"].as_str().is_some_and(|n| n.contains(&family))
|
|
&& f["ids"].as_array().is_some_and(|ids| ids.contains(&json!(id.0)))),
|
|
"preflight identifies the substituted text owner: {findings}"
|
|
);
|
|
assert!(s.execute("text.missingFonts", &json!({})).unwrap()["fonts"].to_string().contains(&family));
|
|
// Undone: the file's look again.
|
|
s.execute("edit.undo", &json!({})).unwrap();
|
|
assert_eq!(glyphs(&s), (at, carried));
|
|
assert!(!preflight(&mut s).to_string().contains(&family), "undo restores the carried font");
|
|
}
|
|
|
|
#[test]
|
|
fn wrapped_carried_font_keeps_pdf_positions_after_native_reopen() {
|
|
let db = vectorcraft_text::FontDb::global();
|
|
let serif = db.face("Source Serif 4", "Regular").unwrap();
|
|
let fallback = db.face(vectorcraft_text::FALLBACK_FAMILY, "Regular").unwrap();
|
|
let advance = |face: &vectorcraft_text::FontFace| face.advance(face.glyph_for('H')) / face.units_per_em();
|
|
assert!((advance(&serif) - advance(&fallback)).abs() > 0.01, "fixture must differ from the substitute");
|
|
let content = "BT /F1 24 Tf 20 160 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 100 Td (Hamburg Zoo ) Tj ET BT /F1 24 Tf 20 40 Td (Hamburg Zoo) Tj ET";
|
|
let bytes = carried_font_pdf(content, 200.0);
|
|
let mut reference = Session::new();
|
|
open(&mut reference, &bytes, json!({"textAs": "outlines"})).unwrap();
|
|
let want = glyph_ink(&reference, false);
|
|
assert_eq!(want.len(), 3);
|
|
let mut s = Session::new();
|
|
open(&mut s, &bytes, json!({})).unwrap();
|
|
let compare = |s: &Session| {
|
|
let mut areas = 0;
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if let NodeKind::Text(t) = &n.kind {
|
|
assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "wrapped text must stay one area");
|
|
assert_eq!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines.len(), 3);
|
|
areas += 1;
|
|
}
|
|
});
|
|
assert_eq!(areas, 1);
|
|
let got = glyph_ink(s, false);
|
|
assert_eq!(got.len(), want.len());
|
|
for (got, want) in got.iter().zip(&want) {
|
|
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
|
|
assert!(off < 0.25, "{got:?} is {off} pt from {want:?}");
|
|
}
|
|
};
|
|
compare(&s);
|
|
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
|
s.execute("document.open", &json!({"name": "wrapped.vectorcraft", "dataBase64": native})).unwrap();
|
|
compare(&s);
|
|
}
|
|
|
|
fn owned_font_document(family: &str, width: f64) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
|
|
use kurbo::{Point, Rect, Shape};
|
|
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, TextObject};
|
|
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
|
|
|
|
let info = FileFontInfo { family: family.into(), style: "Regular".into(), ..Default::default() };
|
|
let g = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
|
|
let blob = ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap());
|
|
let mut doc = Document::new(100.0, 100.0);
|
|
doc.images.insert("chosen".into(), blob.clone());
|
|
let mut t = TextObject::point(Point::new(10.0, 40.0), "x", CharStyle { font_family: family.into(), size: 20.0, ..Default::default() });
|
|
t.file_fonts = Some(Box::new(FileFonts::new(vec![FileFont { family: family.into(), style: "Regular".into(), key: "chosen".into() }], "x")));
|
|
let id = doc.alloc_id();
|
|
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
|
(doc, blob, id)
|
|
}
|
|
|
|
/// No machine fonts are needed: the two native documents own different synthetic glyphs under
|
|
/// the same key. Paste must relink its own bytes, including after closing the source tab.
|
|
#[test]
|
|
fn owned_file_fonts_survive_native_open_close_clipboard_undo_and_export() {
|
|
use vectorcraft_doc::Document;
|
|
use vectorcraft_text::FontDb;
|
|
|
|
const FAMILY: &str = "Native Owned File Font Regression";
|
|
let open_native = |s: &mut Session, doc: &Document| {
|
|
let bytes = vectorcraft_format::save_file(doc);
|
|
s.execute("document.open", &json!({"name": "font.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap()
|
|
};
|
|
let face_of = |s: &Session, id| {
|
|
let NodeKind::Text(t) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
|
|
let g = &vectorcraft_text::layout(FontDb::global(), t).glyphs[0];
|
|
FontDb::global().face_by_id(g.font_id).unwrap()
|
|
};
|
|
let (a, a_blob, a_id) = owned_font_document(FAMILY, 200.0);
|
|
let (b, b_blob, b_id) = owned_font_document(FAMILY, 800.0);
|
|
let mut s = Session::new();
|
|
open_native(&mut s, &a);
|
|
let a_index = s.active_index().unwrap();
|
|
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
|
|
open_native(&mut s, &b);
|
|
let b_index = s.active_index().unwrap();
|
|
let carried = face_of(&s, b_id).id();
|
|
assert_eq!(face_of(&s, b_id).file_data(), b_blob.bytes.as_slice());
|
|
s.execute("select.set", &json!({"ids": [b_id.0]})).unwrap();
|
|
s.execute("edit.copy", &json!({})).unwrap();
|
|
assert!(s.close_document(b_index));
|
|
assert!(s.set_active(a_index));
|
|
let pasted = s.execute("edit.pasteInPlace", &json!({})).unwrap();
|
|
assert!(pasted["warnings"].as_array().unwrap().is_empty(), "{pasted}");
|
|
assert!(pasted["renamed"].as_array().unwrap().iter().any(|v| v["kind"] == "image" && v["from"] == "chosen"));
|
|
let id = vectorcraft_doc::NodeId(pasted["ids"][0].as_u64().unwrap());
|
|
assert_eq!(face_of(&s, id).id(), carried);
|
|
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
|
|
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
|
|
s.execute("edit.undo", &json!({})).unwrap();
|
|
s.execute("edit.redo", &json!({})).unwrap();
|
|
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
|
|
for options in [json!({"format": "pdf", "advanced": {"outlineText": false}}), json!({"format": "svg", "embedFonts": true})] {
|
|
let svg = options["format"] == "svg";
|
|
let exported = s.execute("document.serialize", &options).unwrap();
|
|
if svg {
|
|
let text = exported["text"].as_str().unwrap();
|
|
assert_eq!(text.matches("@font-face").count(), 2, "both distinct owned faces are embedded");
|
|
} else {
|
|
let bytes = vectorcraft_format::base64_decode(exported["dataBase64"].as_str().unwrap()).unwrap();
|
|
assert!(bytes.starts_with(b"%PDF-"));
|
|
}
|
|
// SVG may warn that the same CSS description cannot distinguish these two x glyphs.
|
|
assert!(!exported["warnings"].to_string().contains(vectorcraft_text::FALLBACK_FAMILY), "{exported}");
|
|
}
|
|
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
|
|
s.execute("document.open", &json!({"name": "pasted.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
|
assert_eq!(face_of(&s, id).file_data(), b_blob.bytes.as_slice());
|
|
assert_eq!(face_of(&s, a_id).file_data(), a_blob.bytes.as_slice());
|
|
|
|
let mut unowned = b.clone();
|
|
unowned.images.clear();
|
|
let report = open_native(&mut s, &unowned);
|
|
assert!(report["warnings"].to_string().contains(FAMILY));
|
|
assert_eq!(glyphs(&s).1, 0, "a metadata-only reference cannot borrow any open document's font");
|
|
}
|
|
|
|
/// Place owns its carried font even after the decoded source is dropped, whether the destination
|
|
/// reuses an equal unbound blob or renames a key occupied by another font.
|
|
#[test]
|
|
fn placed_fonts_keep_owned_bytes_after_resource_reuse_or_name_collision() {
|
|
use vectorcraft_doc::Document;
|
|
use vectorcraft_text::FontDb;
|
|
|
|
const FAMILY: &str = "Placed Owned Font Regression";
|
|
let (source, expected, _) = owned_font_document(FAMILY, 200.0);
|
|
let bytes = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&source));
|
|
for same_bytes in [true, false] {
|
|
let mut host = Document::new(100.0, 100.0);
|
|
let blob = if same_bytes { expected.clone() } else { owned_font_document(FAMILY, 800.0).1 };
|
|
host.images.insert("chosen".into(), blob);
|
|
let mut s = Session::new();
|
|
s.add_document(host, None);
|
|
let placed = s.execute("file.place", &json!({"name": "font.vectorcraft", "dataBase64": bytes, "link": false})).unwrap();
|
|
assert!(placed["warnings"].as_array().unwrap().is_empty(), "{placed}");
|
|
let check = |s: &Session| {
|
|
let db = FontDb::global();
|
|
let mut drawn = 0;
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if let NodeKind::Text(t) = &n.kind {
|
|
for g in vectorcraft_text::layout(db, t).glyphs {
|
|
assert!(db.is_file_font(g.font_id), "the destination, not a source cache, owns the font");
|
|
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice());
|
|
drawn += 1;
|
|
}
|
|
}
|
|
});
|
|
assert_eq!(drawn, 1);
|
|
};
|
|
check(&s);
|
|
s.execute("edit.undo", &json!({})).unwrap();
|
|
assert_eq!(glyphs(&s).1, 0);
|
|
s.execute("edit.redo", &json!({})).unwrap();
|
|
check(&s);
|
|
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap();
|
|
let reopened = s.execute("document.open", &json!({"name": "placed.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
|
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
|
|
check(&s);
|
|
}
|
|
}
|
|
|
|
fn linked_owned_font_document(family: &str) -> (vectorcraft_doc::Document, vectorcraft_doc::ImageBlob, vectorcraft_doc::NodeId) {
|
|
use kurbo::Affine;
|
|
use vectorcraft_doc::{Document, ImageBlob, LinkInfo, Node, PlacedDocument};
|
|
|
|
let (source, expected, _) = owned_font_document(family, 200.0);
|
|
let bytes = vectorcraft_format::save_file(&source);
|
|
let blob = ImageBlob::new("application/json", bytes);
|
|
let key = format!("placed-font-{}", blob.content_key());
|
|
let mut host = Document::new(100.0, 100.0);
|
|
host.images.insert("chosen".into(), owned_font_document(family, 800.0).1);
|
|
host.images.insert(key.clone(), blob);
|
|
let placed = PlacedDocument {
|
|
key,
|
|
link: LinkInfo::new("/font-placement-regression.vectorcraft"),
|
|
bounding: false,
|
|
page_box: Default::default(),
|
|
width: 100.0,
|
|
height: 100.0,
|
|
xf: Affine::IDENTITY,
|
|
placement: Default::default(),
|
|
};
|
|
let id = host.alloc_id();
|
|
host.insert(Some(host.layers[0].id), usize::MAX, Node::new(id, NodeKind::PlacedDocument(Box::new(placed)))).unwrap();
|
|
(host, expected, id)
|
|
}
|
|
|
|
/// Break Link and older-version saves must preserve the placed file's own bytes rather than bind
|
|
/// text to the host's unrelated font under the same key when reopened.
|
|
#[test]
|
|
fn placed_carried_fonts_survive_break_link_and_older_version_save() {
|
|
use vectorcraft_text::FontDb;
|
|
|
|
for break_link in [true, false] {
|
|
let family = if break_link { "Break Link Owned Font Regression" } else { "Older Save Owned Font Regression" };
|
|
let (host, expected, id) = linked_owned_font_document(family);
|
|
let mut s = Session::new();
|
|
s.add_document(host, None);
|
|
if break_link {
|
|
let embedded = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap();
|
|
assert_eq!(embedded["embedded"], json!([id.0]), "{embedded}");
|
|
assert_eq!(glyphs(&s).1, 1);
|
|
}
|
|
let version = if break_link { vectorcraft_format::VERSION } else { vectorcraft_format::VERSION - 1 };
|
|
let saved = s.execute("document.serialize", &json!({"format": "vectorcraft", "version": version, "preview": false})).unwrap();
|
|
let reopened = s.execute("document.open", &json!({"name": "placed-font.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
|
|
assert!(reopened["warnings"].as_array().unwrap().is_empty(), "{reopened}");
|
|
let db = FontDb::global();
|
|
let mut drawn = 0;
|
|
s.doc().unwrap().doc.walk(|n| {
|
|
if let NodeKind::Text(t) = &n.kind {
|
|
for g in vectorcraft_text::layout(db, t).glyphs {
|
|
assert!(db.is_file_font(g.font_id));
|
|
assert_eq!(db.face_by_id(g.font_id).unwrap().file_data(), expected.bytes.as_slice(), "{family}");
|
|
drawn += 1;
|
|
}
|
|
}
|
|
});
|
|
assert_eq!(drawn, 1, "{family}");
|
|
assert!(!s.doc().unwrap().doc.has_placed(), "the reopened art is editable, not a linked source");
|
|
}
|
|
}
|
|
|
|
/// Glyphs `a`, `b`, `a` in an unavailable carried font, all named `a` by ToUnicode.
|
|
fn two_glyphs_for_one_character_pdf(content: &str) -> Vec<u8> {
|
|
let data = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/fonts/SourceSerif4-Regular.ttf")).unwrap();
|
|
let face = vectorcraft_text::FontDb::global().face("Source Serif 4", "Regular").unwrap();
|
|
let widths: Vec<String> =
|
|
(32u8..=126).map(|c| format!("{:.0}", face.advance(face.glyph_for(char::from(c))) * 1000.0 / face.units_per_em())).collect();
|
|
let hex: String = data.iter().map(|b| format!("{b:02x}")).collect();
|
|
let n = first_extra(1);
|
|
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(400.0, 200.0, content) };
|
|
let font = format!(
|
|
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+Zyxwvu-Serif /FirstChar 32 /LastChar 126 /Widths [{}] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R /ToUnicode {} 0 R >>",
|
|
widths.join(" "),
|
|
n + 1,
|
|
n + 3
|
|
);
|
|
let descriptor = format!(
|
|
"<< /Type /FontDescriptor /FontName /ABCDEF+Zyxwvu-Serif /Flags 34 /FontBBox [-500 -300 1500 1000] /ItalicAngle 0 /Ascent 900 /Descent -300 /CapHeight 660 /StemV 80 /FontFile2 {} 0 R >>",
|
|
n + 2
|
|
);
|
|
let file = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
|
|
let cmap = "/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00> <FF> endcodespacerange 2 beginbfchar <61> <0061> <62> <0061> endbfchar endcmap CMapName currentdict /CMap defineresource pop end end";
|
|
let tounicode = format!("<< /Length {} >>\nstream\n{cmap}\nendstream", cmap.len() + 1);
|
|
pdf_with(&[page], &[&font, &descriptor, &file, &tounicode], None)
|
|
}
|
|
|
|
/// The three glyph ink boxes, grouped by x for the TJ fixture or by y for separate lines.
|
|
fn glyph_ink(s: &Session, across: bool) -> Vec<kurbo::Rect> {
|
|
use kurbo::Shape;
|
|
let db = vectorcraft_text::FontDb::global();
|
|
let mut lines: [Option<kurbo::Rect>; 3] = [None; 3];
|
|
let mut add = |path: &kurbo::BezPath| {
|
|
let els = path.elements();
|
|
let mut start = 0;
|
|
for end in (1..=els.len()).filter(|&e| e == els.len() || matches!(els[e], kurbo::PathEl::MoveTo(_))) {
|
|
let ink = kurbo::BezPath::from_vec(els[start..end].to_vec()).bounding_box();
|
|
let line = if across {
|
|
usize::from(ink.center().x > 90.0) + usize::from(ink.center().x > 230.0)
|
|
} else {
|
|
usize::from(ink.center().y > 70.0) + usize::from(ink.center().y > 130.0)
|
|
};
|
|
lines[line] = Some(lines[line].map_or(ink, |l| l.union(ink)));
|
|
start = end;
|
|
}
|
|
};
|
|
s.doc().unwrap().doc.walk(|n| match &n.kind {
|
|
NodeKind::Text(t) => vectorcraft_text::layout(db, t).glyphs.iter().for_each(|g| add(&(t.xf * g.outline.clone()))),
|
|
NodeKind::Path { path, .. } => add(&path.to_bezpath()),
|
|
_ => {}
|
|
});
|
|
lines.into_iter().flatten().collect()
|
|
}
|
|
|
|
/// Two different glyphs of a carried font for one character can't both go into the font kept with
|
|
/// the document, which has one glyph per character, so the line with the other glyph is outlines.
|
|
/// Opened, saved in the native format and opened again, each glyph is still the one the file draws,
|
|
/// where it draws it: the same page opened as outlines is the reference.
|
|
#[test]
|
|
fn two_glyphs_for_one_character_survive_a_native_save_and_reopen() {
|
|
let content = "BT /F1 30 Tf 20 160 Td (a) Tj ET BT /F1 30 Tf 20 100 Td (b) Tj ET BT /F1 30 Tf 20 40 Td (a) Tj ET";
|
|
assert_carried_glyph_roundtrip(content, false);
|
|
}
|
|
|
|
#[test]
|
|
fn conflicting_carried_glyphs_in_a_filled_and_stroked_tj_survive_native_reopen() {
|
|
let content = "BT 2 Tr /F1 30 Tf 20 100 Td [(a) -3500 (b) -3500 (a)] TJ 0 Tr ET";
|
|
assert_carried_glyph_roundtrip(content, true);
|
|
}
|
|
|
|
fn assert_carried_glyph_roundtrip(content: &str, across: bool) {
|
|
let bytes = two_glyphs_for_one_character_pdf(content);
|
|
let mut reference_session = Session::new();
|
|
open(&mut reference_session, &bytes, json!({"textAs": "outlines"})).unwrap();
|
|
let reference = glyph_ink(&reference_session, across);
|
|
assert_eq!(reference.len(), 3, "the file draws three glyphs: {reference:?}");
|
|
assert!((reference[0].height() - reference[1].height()).abs() > 2.0, "the file's two glyphs differ in shape: {reference:?}");
|
|
assert!((reference[0].height() - reference[2].height()).abs() < 0.01, "the first and third are the same glyph: {reference:?}");
|
|
|
|
let mut s = Session::new();
|
|
open(&mut s, &bytes, json!({})).unwrap();
|
|
assert!(
|
|
live_texts(&s).iter().any(|t| t == "a") && live_texts(&s).len() < 3,
|
|
"some glyphs stay type, the other is outlines: {:?}",
|
|
live_texts(&s)
|
|
);
|
|
let close = |s: &Session, what: &str| {
|
|
let got = glyph_ink(s, across);
|
|
assert_eq!(got.len(), reference.len(), "{what}: {got:?}");
|
|
for (got, want) in got.iter().zip(&reference) {
|
|
let off = (got.x0 - want.x0).abs().max((got.x1 - want.x1).abs()).max((got.y0 - want.y0).abs()).max((got.y1 - want.y1).abs());
|
|
assert!(off < 0.25, "{what}: {got:?} is {off} pt from the file's {want:?}");
|
|
}
|
|
};
|
|
close(&s, "opened");
|
|
let native = s.execute("document.serialize", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].as_str().unwrap().to_string();
|
|
s.execute("document.open", &json!({"name": "kept.vectorcraft", "dataBase64": native})).unwrap();
|
|
close(&s, "saved and reopened");
|
|
}
|