mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 02:44:24 +01: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 <FredApps@users.noreply.github.com> Co-authored-by: skylartaylor <hi@skylar.cc>
This commit is contained in:
80 files changed
+2822
-216
No files matched your search
Generated
+1
@@ -7254,6 +7254,7 @@ dependencies = [
|
||||
"icu_segmenter",
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"serde_json",
|
||||
"skrifa 0.47.0",
|
||||
"subsetter",
|
||||
"unicode-bidi",
|
||||
|
||||
@@ -880,7 +880,7 @@ fn image_and_fill_doc(fill: Paint) -> Document {
|
||||
Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))),
|
||||
]
|
||||
});
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
|
||||
d
|
||||
}
|
||||
|
||||
@@ -974,7 +974,10 @@ fn images_can_be_left_out_with_their_files() {
|
||||
assert_eq!(out.setting_notes, [IMAGES_OFF]);
|
||||
// An image that can't be decoded is not read when images are left out.
|
||||
let mut broken = d.clone();
|
||||
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
|
||||
broken.images.insert(
|
||||
"raster-1".into(),
|
||||
ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None, file_font: Default::default() },
|
||||
);
|
||||
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
|
||||
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
|
||||
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
|
||||
@@ -1379,7 +1382,7 @@ fn images_link_png_or_jpeg_files() {
|
||||
};
|
||||
vec![Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
|
||||
});
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
let e = entities(&out);
|
||||
assert_eq!(kind(&e[0]), "IMAGE");
|
||||
@@ -1422,7 +1425,7 @@ fn images_without_pixels_are_left_out_with_one_note() {
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None });
|
||||
d.images.insert("raster-2".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(vec![]), proxy: None, file_font: Default::default() });
|
||||
let out = export(&d, &opts(&d)).unwrap();
|
||||
assert!(entities(&out).is_empty() && out.images.is_empty());
|
||||
assert_eq!(out.warnings, ["an image has no pixels and was left out"]);
|
||||
@@ -1583,7 +1586,7 @@ fn drawings_doc() -> Document {
|
||||
});
|
||||
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() });
|
||||
d
|
||||
}
|
||||
|
||||
|
||||
@@ -134,10 +134,10 @@ pub use text::GlyphForm;
|
||||
pub use text::PATH_LEAD_MAX;
|
||||
pub use text::WarichuAlign;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, PathAlign, PathEffect, RubyAlign,
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FILE_FONT_MIME, FileFont, FileFontFace, FileFonts,
|
||||
FirstBaseline, HyphenationOptions, InlineArt, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection,
|
||||
ParaStyle, PathAlign, PathEffect, RubyAlign, RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind,
|
||||
TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
|
||||
@@ -130,7 +130,7 @@ pub fn hash_reader_within(r: impl std::io::Read, max: u64) -> std::io::Result<(S
|
||||
impl ImageBlob {
|
||||
/// A blob of encoded image `bytes` of type `mime`, without a preview.
|
||||
pub fn new(mime: impl Into<String>, bytes: Vec<u8>) -> Self {
|
||||
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None }
|
||||
Self { mime: mime.into(), bytes: Arc::new(bytes), proxy: None, file_font: Default::default() }
|
||||
}
|
||||
|
||||
/// This blob with a preview of at most [`PROXY_SIZE`] pixels a side (PNG), when the image is
|
||||
|
||||
@@ -461,7 +461,7 @@ fn read_preview(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocu
|
||||
doc.layers.clear();
|
||||
doc.swatches.clear();
|
||||
let mime = if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { "image/png" };
|
||||
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None });
|
||||
doc.images.insert("preview".into(), ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: None, file_font: Default::default() });
|
||||
let xf = Affine::scale_non_uniform(frame.width() / w as f64, frame.height() / h as f64);
|
||||
let im = ImageObject { key: "preview".into(), width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
|
||||
let art = Node::new(art_id(), NodeKind::Group { children: vec![Arc::new(Node::new(art_id(), NodeKind::Image(Box::new(im))))], clip: false });
|
||||
@@ -519,6 +519,9 @@ fn rename(n: &mut Node, prefix: &str) {
|
||||
paint(&mut r.style.fill);
|
||||
paint(&mut r.style.stroke);
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| *key = format!("{prefix}{key}"));
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
im.key = format!("{prefix}{}", im.key);
|
||||
|
||||
@@ -154,8 +154,9 @@ pub struct Symbol {
|
||||
pub dynamic: bool,
|
||||
}
|
||||
|
||||
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
/// Encoded image bytes (PNG/JPEG/WebP…) shared by image objects, and the fonts files carried for
|
||||
/// type ([`crate::FileFonts`], MIME [`crate::FILE_FONT_MIME`]), which save and travel the same way.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct ImageBlob {
|
||||
pub mime: String,
|
||||
#[serde(skip)]
|
||||
@@ -164,4 +165,32 @@ pub struct ImageBlob {
|
||||
/// linked images show this blob, and what `bytes` hold while the linked file can't be read.
|
||||
#[serde(skip)]
|
||||
pub proxy: Option<Arc<Vec<u8>>>,
|
||||
/// Runtime ownership of an admitted font face. Image resources (including undo and clipboard
|
||||
/// copies) own it; cached text nodes carry only weak references.
|
||||
#[serde(skip)]
|
||||
pub file_font: std::sync::Mutex<Option<Arc<dyn crate::FileFontFace>>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ImageBlob {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ImageBlob").field("mime", &self.mime).field("bytes", &self.bytes).field("proxy", &self.proxy).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for ImageBlob {
|
||||
fn clone(&self) -> Self {
|
||||
let mut owner = self.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if owner.as_ref().is_some_and(|face| {
|
||||
self.mime != crate::FILE_FONT_MIME || (!std::ptr::eq(face.bytes(), self.bytes.as_slice()) && face.bytes() != self.bytes.as_slice())
|
||||
}) {
|
||||
*owner = None;
|
||||
}
|
||||
Self { mime: self.mime.clone(), bytes: self.bytes.clone(), proxy: self.proxy.clone(), file_font: std::sync::Mutex::new(owner.clone()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for ImageBlob {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.mime == other.mime && self.bytes == other.bytes && self.proxy == other.proxy
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
|
||||
mod area;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod file_fonts;
|
||||
mod kinsoku_set;
|
||||
mod object;
|
||||
mod para_style;
|
||||
@@ -26,6 +27,7 @@ pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub use file_fonts::{FILE_FONT_MIME, FileFont, FileFontFace, FileFonts, MAX_FILE_FONTS, text_hash};
|
||||
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
|
||||
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
|
||||
pub use para_style::{
|
||||
@@ -131,6 +133,10 @@ pub struct TextObject {
|
||||
/// file saves the count only when it is not 0.
|
||||
#[serde(default, rename = "listCount", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub list_count: u32,
|
||||
/// The fonts the file this type came from carried for fonts that aren't available here,
|
||||
/// which draw it until its text is edited ([`FileFonts`]); `None` for other type.
|
||||
#[serde(default, rename = "fileFonts", skip_serializing_if = "Option::is_none")]
|
||||
pub file_fonts: Option<Box<FileFonts>>,
|
||||
/// Threaded text: as [`Self::list_count`], the counts the earlier frames carry into this frame
|
||||
/// at list levels 2 on, level 2 first ([`ListCounts::from_parts`]). Empty when they are all 0,
|
||||
/// and the file saves them only when not empty. A file's longer list opens with the first 8.
|
||||
|
||||
@@ -7,6 +7,9 @@ pub struct CharStyle {
|
||||
pub font_family: String,
|
||||
#[serde(default = "regular")]
|
||||
pub font_style: String,
|
||||
/// Internal layout selection from a validated file-font binding, never read from a file.
|
||||
#[serde(skip)]
|
||||
pub file_font_id: Option<u32>,
|
||||
/// Which installed version of the font (its version string) when several versions of the
|
||||
/// family and style are installed and the text was set in one the family and style alone
|
||||
/// wouldn't pick (an imported file's type matched to it); None = the one they pick.
|
||||
@@ -656,6 +659,7 @@ impl Default for CharStyle {
|
||||
Self {
|
||||
font_family: "Source Sans 3".into(),
|
||||
font_style: "Regular".into(),
|
||||
file_font_id: None,
|
||||
font_version: None,
|
||||
font_axes: std::collections::BTreeMap::new(),
|
||||
size: 12.0,
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The MIME type of a font a file carried ([`FileFonts`]), kept among the document's image blobs
|
||||
/// ([`crate::Document::images`]).
|
||||
pub const FILE_FONT_MIME: &str = "font/ttf";
|
||||
|
||||
/// The most fonts of [`FileFonts`] that draw one type object (a file's list may be longer: the rest
|
||||
/// are left out).
|
||||
pub const MAX_FILE_FONTS: usize = 64;
|
||||
|
||||
/// The fonts a file carried for type whose fonts aren't available here (a PDF's embedded fonts),
|
||||
/// kept with the document among its image blobs ([`crate::Document::images`], MIME
|
||||
/// [`FILE_FONT_MIME`]). A file embeds its fonts so that readers see its text in its own fonts
|
||||
/// rather than substitutes (Acrobat Help, PDF fonts,
|
||||
/// <https://helpx.adobe.com/acrobat/using/pdf-fonts.html>); editing text in a font that isn't
|
||||
/// installed sets it in a substitute (Acrobat Help, Edit text in PDFs,
|
||||
/// <https://helpx.adobe.com/acrobat/using/edit-text-pdfs1.html>). So the type is drawn in these,
|
||||
/// as the file drew it, while its text is the one the file had and a font it names isn't
|
||||
/// available: once its text is edited (or that font is installed) it takes the font it names, or
|
||||
/// its substitute. Its runs keep naming the file's fonts, so they stay listed as missing.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct FileFonts {
|
||||
/// The font kept for each family and style the runs name.
|
||||
pub fonts: Vec<FileFont>,
|
||||
/// The text as the file had it ([`text_hash`] of the plain text).
|
||||
pub text: u64,
|
||||
/// Validated runtime resources; serialized keys alone never authorize a font lookup.
|
||||
#[serde(skip)]
|
||||
resources: Vec<(String, u32, std::sync::Weak<dyn FileFontFace>)>,
|
||||
}
|
||||
|
||||
impl FileFonts {
|
||||
/// `fonts` for type whose text is `text`.
|
||||
pub fn new(fonts: Vec<FileFont>, text: &str) -> Self {
|
||||
Self { fonts, text: text_hash([text]), resources: vec![] }
|
||||
}
|
||||
|
||||
/// The runtime face bound to this reference by its owning document.
|
||||
pub fn face(&self, key: &str) -> Option<Arc<dyn FileFontFace>> {
|
||||
self.resources.iter().find(|(k, _, _)| k == key).and_then(|(_, _, face)| face.upgrade())
|
||||
}
|
||||
|
||||
/// Replace validated bindings, returning whether their runtime identity changed.
|
||||
pub fn bind(&mut self, resources: Vec<(String, Arc<dyn FileFontFace>)>) -> bool {
|
||||
let changed = self.resources.len() != resources.len()
|
||||
|| self.resources.iter().zip(&resources).any(|((a, id, _), (b, face))| a != b || *id != face.id());
|
||||
self.resources = resources.into_iter().map(|(key, face)| (key, face.id(), Arc::downgrade(&face))).collect();
|
||||
changed
|
||||
}
|
||||
|
||||
/// Remap serialized and validated runtime resource keys together when art changes namespaces.
|
||||
/// The callback applies the same mapping to each occurrence of an original key.
|
||||
pub fn map_keys(&mut self, mut map: impl FnMut(&mut String)) {
|
||||
for font in &mut self.fonts {
|
||||
map(&mut font.key);
|
||||
}
|
||||
for (key, _, _) in &mut self.resources {
|
||||
map(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for FileFonts {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.fonts == other.fonts
|
||||
&& self.text == other.text
|
||||
&& self.resources.len() == other.resources.len()
|
||||
&& self.resources.iter().zip(&other.resources).all(|((a, aid, _), (b, bid, _))| a == b && aid == bid)
|
||||
}
|
||||
}
|
||||
|
||||
/// A runtime file-font resource owned by image blobs, undo snapshots and clipboard resources.
|
||||
/// The text engine implements this interface without making the document depend on it.
|
||||
pub trait FileFontFace: Send + Sync {
|
||||
fn id(&self) -> u32;
|
||||
fn bytes(&self) -> &[u8];
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for dyn FileFontFace {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("FileFontFace").field("id", &self.id()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// One font of [`FileFonts`]: the family and style type names it by, and its blob.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FileFont {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
/// The font's blob among the document's image blobs.
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
/// A hash of the text `parts` make one after another (64-bit FNV-1a of its UTF-8 bytes): the same
|
||||
/// on every machine and in every version, as a saved [`FileFonts::text`] needs.
|
||||
pub fn text_hash<'a>(parts: impl IntoIterator<Item = &'a str>) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in parts.into_iter().flat_map(str::bytes) {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::area::{AreaOptions, PathAlign, PathEffect};
|
||||
use super::char_style::CharStyle;
|
||||
use super::file_fonts::{FileFont, MAX_FILE_FONTS, text_hash};
|
||||
use super::para_style::{JustificationOptions, ParaStyle};
|
||||
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
|
||||
use super::tabs_lists::{ListCounts, ParaList};
|
||||
@@ -126,6 +127,7 @@ impl TextObject {
|
||||
system_layout: false,
|
||||
fractional_widths: true,
|
||||
list_count: 0,
|
||||
file_fonts: None,
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
@@ -144,6 +146,17 @@ impl TextObject {
|
||||
pub fn plain_text(&self) -> String {
|
||||
self.runs.iter().map(|r| r.text.as_str()).collect()
|
||||
}
|
||||
/// The fonts the file this type came from carried ([`FileFonts`]) while its text is still the
|
||||
/// file's (at most [`MAX_FILE_FONTS`]); none once it was edited, and for other type.
|
||||
pub fn file_fonts_in_use(&self) -> &[FileFont] {
|
||||
match self.file_fonts.as_deref() {
|
||||
Some(f) if f.text == text_hash(self.runs.iter().map(|r| r.text.as_str())) => {
|
||||
f.fonts.get(..f.fonts.len().min(MAX_FILE_FONTS)).unwrap_or_default()
|
||||
}
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Does layout stack some of this type's characters as warichu ([`CharStyle::warichu`])? Not
|
||||
/// on a path, which sets them as they are. Exports that write live text write such type as
|
||||
/// outlines, as they do ruby: their text can't place the stacked lines.
|
||||
|
||||
@@ -801,3 +801,30 @@ fn auto_alignment_saves_readable_by_older_builds() {
|
||||
// Files from before the flag keep their alignment.
|
||||
assert_eq!(serde_json::from_str::<ParaStyle>(r#"{"justify":"Center"}"#).unwrap().justify, Justify::Center);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_fonts_draw_type_only_while_its_text_is_the_files() {
|
||||
use super::file_fonts::*;
|
||||
use super::*;
|
||||
// The hash is the same everywhere and in every version (saved files carry it).
|
||||
assert_eq!(text_hash([""]), 0xcbf2_9ce4_8422_2325);
|
||||
assert_eq!(text_hash(["Ham", "burg"]), text_hash(["Hamburg"]));
|
||||
assert_ne!(text_hash(["Hamburg"]), text_hash(["Hamburh"]));
|
||||
let font = FileFont { family: "Source Serif 9".into(), style: "Regular".into(), key: "k".into() };
|
||||
let mut t = TextObject::point(Point::ZERO, "Ham", CharStyle::default());
|
||||
t.runs.push(TextRun::new("burg", CharStyle::default()));
|
||||
assert!(t.file_fonts_in_use().is_empty());
|
||||
t.file_fonts = Some(Box::new(FileFonts::new(vec![font.clone()], "Hamburg")));
|
||||
assert_eq!(t.file_fonts_in_use(), std::slice::from_ref(&font));
|
||||
// Saved and read back.
|
||||
let json = serde_json::to_string(&t).unwrap();
|
||||
assert!(json.contains(r#""fileFonts":{"fonts":[{"family":"Source Serif 9","style":"Regular","key":"k"}]"#), "{json}");
|
||||
assert_eq!(serde_json::from_str::<TextObject>(&json).unwrap(), t);
|
||||
// Edited: none.
|
||||
t.runs[1].text.push('s');
|
||||
assert!(t.file_fonts_in_use().is_empty());
|
||||
// A file's list past the cap: the first ones.
|
||||
t.runs[1].text.pop();
|
||||
t.file_fonts.as_mut().unwrap().fonts = vec![font; MAX_FILE_FONTS + 5];
|
||||
assert_eq!(t.file_fonts_in_use().len(), MAX_FILE_FONTS);
|
||||
}
|
||||
@@ -409,7 +409,8 @@ fn a_mask_that_hides_nothing_keeps_the_link() {
|
||||
#[test]
|
||||
fn color_mask_refuses_previews_and_images_too_large() {
|
||||
let preview = std::sync::Arc::new(framed());
|
||||
let (mut s, id) = linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
|
||||
let (mut s, id) =
|
||||
linked("missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
|
||||
let e = s.execute(COLOR_MASK, &hide_white()).unwrap_err().to_string();
|
||||
assert!(e.contains(COLOR_MASK) && e.contains("the linked image shows its preview: embed or relink it first"), "{e}");
|
||||
assert_eq!(mask_of(doc(&s), id), None);
|
||||
|
||||
@@ -525,7 +525,12 @@ fn a_linked_image_is_embedded_and_one_that_shows_its_preview_is_refused() {
|
||||
assert_eq!(im.placement, clip, "its Placement Options kept, as Embed keeps them");
|
||||
// Pixels the file wasn't read for: the preview, as an image whose file is missing shows it.
|
||||
let preview = Arc::new(bytes);
|
||||
let missing = place_linked(&mut s, "missing", ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) }, (12, 10));
|
||||
let missing = place_linked(
|
||||
&mut s,
|
||||
"missing",
|
||||
ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() },
|
||||
(12, 10),
|
||||
);
|
||||
let before = (image_of(&s, missing), undo_len(&s));
|
||||
let e = s.execute(C, &json!({})).unwrap_err();
|
||||
assert!(e.to_string().contains("the linked image shows its preview: embed or relink it first"), "{e}");
|
||||
|
||||
@@ -159,6 +159,10 @@ fn node_refs(n: &Node, f: Visit) {
|
||||
for s in t.para_styles().filter_map(|pa| pa.style_name.as_ref()) {
|
||||
f(Ref::Name(Res::ParaStyle, s));
|
||||
}
|
||||
// The fonts its file carried travel with it, as images do.
|
||||
for ff in t.file_fonts.iter().flat_map(|ff| &ff.fonts) {
|
||||
f(Ref::Name(Res::Image, &ff.key));
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => f(Ref::Name(Res::Image, &im.key)),
|
||||
NodeKind::PlacedDocument(pl) => f(Ref::Name(Res::Image, &pl.key)),
|
||||
@@ -807,6 +811,9 @@ impl Relink {
|
||||
if relaid {
|
||||
refresh_bounds(t);
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| self.name(Res::Image, key));
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
|
||||
NodeKind::PlacedDocument(pl) => self.name(Res::Image, &mut pl.key),
|
||||
@@ -1134,6 +1141,8 @@ pub(crate) struct Imported {
|
||||
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
|
||||
/// renamed, or a copy added renamed by an earlier paste.
|
||||
pub renamed: Vec<Value>,
|
||||
/// File-font resources refused while binding pasted type.
|
||||
pub warnings: Vec<String>,
|
||||
/// The graph designs the pasted graphs draw with that the document has under the same name
|
||||
/// and that would draw them otherwise than the art they were pasted with: the document keeps
|
||||
/// its own, and the pasted graphs are drawn again with it.
|
||||
@@ -1158,13 +1167,18 @@ impl Imported {
|
||||
}
|
||||
}
|
||||
/// Point a pasted copy at the document's resources. A pie's legend labels in wedges that now show a color of the
|
||||
/// other darkness take the contrast a redraw sets there.
|
||||
pub(crate) fn apply(&self, n: &mut Node) {
|
||||
/// other darkness take the contrast a redraw sets there. Fonts the copy carries are bound to the faces `d` holds.
|
||||
pub(crate) fn apply(&mut self, n: &mut Node, d: &Document) {
|
||||
if self.relinks {
|
||||
let shades = super::super::graph::wedge_shades(n);
|
||||
self.relink.node(n);
|
||||
super::super::graph::follow_wedge_shades(n, &shades);
|
||||
}
|
||||
for note in vectorcraft_text::FontDb::global().bind_node_file_fonts(n, &|key| d.images.get(key)) {
|
||||
if !self.warnings.contains(¬e) {
|
||||
self.warnings.push(note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1462,6 +1476,7 @@ impl Clipboard {
|
||||
&& out.relink.colors.is_empty()
|
||||
&& out.relink.kinsoku.is_empty()
|
||||
&& used.styles.is_empty());
|
||||
out.warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(d));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -1552,7 +1552,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| {
|
||||
// Converted colors are compared with the document's resources, as another document's are
|
||||
// (`Clipboard::import_into`); its images are still the document's own.
|
||||
let imported = clip.import_into(d, choices, same_doc)?;
|
||||
let mut imported = clip.import_into(d, choices, same_doc)?;
|
||||
// Draw Inside: the clip group of the object drawn into, made on the first paste.
|
||||
let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?;
|
||||
let artboards: Vec<usize> = boards
|
||||
@@ -1570,7 +1570,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let mut c = d.reid(n);
|
||||
// A pasted symbol set packs from the density recorded for it at Copy.
|
||||
d.carry_set_densities(n, &c, &clip.set_densities);
|
||||
imported.apply(&mut c);
|
||||
imported.apply(&mut c, d);
|
||||
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
|
||||
if xf != Affine::IDENTITY {
|
||||
// A cross-document drag carries the graphic's appearance with it,
|
||||
@@ -1698,6 +1698,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
"added": imported.added,
|
||||
"merged": imported.merged,
|
||||
"renamed": imported.renamed,
|
||||
"warnings": imported.warnings,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -79,10 +79,10 @@ pub(crate) use encode::{anti_alias, background, with_single_artboard};
|
||||
pub(crate) use export::with_artboard_fills;
|
||||
pub(crate) use export::{EXPORT_PARAMS, export_crop, isolated};
|
||||
pub use export::{export_doc, export_source, selection_doc, unused_option_notes};
|
||||
pub(crate) use load::decode_native_file;
|
||||
use load::err;
|
||||
pub(crate) use load::import_svg;
|
||||
pub(crate) use load::is_placeholder;
|
||||
pub(crate) use load::native_file;
|
||||
pub(crate) use load::page_or_editing_data;
|
||||
pub(crate) use load::source;
|
||||
pub use load::{
|
||||
|
||||
@@ -193,8 +193,11 @@ fn restore_or_import(
|
||||
let mut fallback = None;
|
||||
if let Some((intact, bytes)) = editing {
|
||||
let native = if intact { bytes() } else { None };
|
||||
match native.and_then(|b| native_file(&b).ok()) {
|
||||
Some((doc, _, warnings)) => return Ok((doc, warnings, true)),
|
||||
match native.and_then(|b| decode_native_file(&b).ok()) {
|
||||
Some((mut doc, _, mut warnings)) => {
|
||||
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
|
||||
return Ok((doc, warnings, true));
|
||||
}
|
||||
None => fallback = Some(if intact { EDITING_DAMAGED } else { EDITING_STALE }),
|
||||
}
|
||||
}
|
||||
@@ -205,9 +208,9 @@ fn restore_or_import(
|
||||
Ok((doc, warnings, false))
|
||||
}
|
||||
|
||||
/// A native file's document and details, the colour profiles it carries installed where missing
|
||||
/// (with a warning for each that can't be used).
|
||||
pub(crate) fn native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
|
||||
/// Decode a native file and install its colour profiles, preserving profile and depth warnings.
|
||||
/// The caller must assemble any external resources and bind file fonts before layout.
|
||||
pub(crate) fn decode_native_file(bytes: &[u8]) -> Result<(Document, vectorcraft_format::FileInfo, Vec<String>)> {
|
||||
let f = vectorcraft_format::load_file(bytes).map_err(err)?;
|
||||
let mut warnings = super::native::install_profiles(f.profiles);
|
||||
warnings.extend(f.depth_notes);
|
||||
@@ -424,7 +427,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
})?
|
||||
}
|
||||
"vectorcraft" | "template" => {
|
||||
let (d, info, warnings) = native_file(bytes)?;
|
||||
let (mut d, info, mut warnings) = decode_native_file(bytes)?;
|
||||
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut d));
|
||||
native_pdf_compatible = Some(info.pdf_compatible);
|
||||
converted = info.is_old() || super::extension(name) == vectorcraft_format::LEGACY_EXTENSION;
|
||||
(d, warnings, false)
|
||||
@@ -688,7 +692,8 @@ pub fn open_bytes(s: &mut Session, name: &str, bytes: &[u8], path: Option<String
|
||||
/// [`open_bytes`] with the `document.open` options in `p` ([`LoadOptions::from_params`]).
|
||||
pub fn open_bytes_with(s: &mut Session, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value> {
|
||||
let update_links = s.prefs.update_links == "automatically";
|
||||
open_read(s, read_for_open(name, bytes, path, p, update_links, s.prefs.low_res_proxy_eps)?)
|
||||
let p = s.prefs.with_pdf_font_choice(p);
|
||||
open_read(s, read_for_open(name, bytes, path, &p, update_links, s.prefs.low_res_proxy_eps)?)
|
||||
}
|
||||
|
||||
/// A file read for `document.open` but not opened yet ([`read_for_open`], [`open_read`]).
|
||||
@@ -860,7 +865,11 @@ impl ReadFile {
|
||||
let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return };
|
||||
let base = crate::cmd::links::LinkBase::file(self.path.as_deref());
|
||||
self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut self.loaded.doc);
|
||||
for note in Session::refresh_text_bounds(&mut self.loaded.doc) {
|
||||
if !self.loaded.warnings.contains(¬e) {
|
||||
self.loaded.warnings.push(note);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The policies with the profile answer and the color mode `colorMode` asks for, once; the
|
||||
|
||||
@@ -47,6 +47,10 @@ pub struct LoadOptions {
|
||||
/// A `.ai` opens from its editing copy even where that draws differently from its PDF part
|
||||
/// (which can be older than it), with a warning, instead of from the PDF part.
|
||||
pub trust_editing_data: bool,
|
||||
/// A PDF's type in a font it embeds and this machine lacks is drawn in the file's own glyphs
|
||||
/// (default; the `embeddedFonts` param, and Preferences › File Handling › Use fonts embedded in
|
||||
/// imported PDFs for opens and places that give none).
|
||||
pub embedded_fonts: bool,
|
||||
/// The encoding names in a `.ai` or EPS's editing data are read in when they aren't UTF-8
|
||||
/// (`legacyNameEncoding`).
|
||||
pub legacy_names: vectorcraft_eps::NameEncoding,
|
||||
@@ -74,6 +78,7 @@ impl Default for LoadOptions {
|
||||
editing_data: true,
|
||||
trust_editing_data: false,
|
||||
legacy_names: vectorcraft_eps::NameEncoding::default(),
|
||||
embedded_fonts: true,
|
||||
native: true,
|
||||
link_pages: false,
|
||||
}
|
||||
@@ -84,7 +89,7 @@ impl LoadOptions {
|
||||
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `importSlices` (true | false), `editingData` (true | false | `always`),
|
||||
/// `importSlices` (true | false), `editingData` (true | false | `always`), `embeddedFonts` (true | false),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
|
||||
/// false) and `dxf` (the DXF import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
@@ -135,6 +140,10 @@ impl LoadOptions {
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
let embedded_fonts = match p.get("embeddedFonts").filter(|v| !v.is_null()) {
|
||||
None => true,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "embeddedFonts must be true or false"))?,
|
||||
};
|
||||
Ok(Self {
|
||||
pages,
|
||||
crop,
|
||||
@@ -148,6 +157,7 @@ impl LoadOptions {
|
||||
dxf,
|
||||
editing_data,
|
||||
trust_editing_data,
|
||||
embedded_fonts,
|
||||
legacy_names,
|
||||
native: true,
|
||||
link_pages,
|
||||
@@ -177,6 +187,7 @@ impl LoadOptions {
|
||||
text_as: self.text_as,
|
||||
layers: self.layers,
|
||||
uncalibrated_rgb: editor_document,
|
||||
embedded_fonts: self.embedded_fonts,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
@@ -219,7 +230,15 @@ pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opene
|
||||
|
||||
/// The import options of [`page_document`].
|
||||
fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
|
||||
ImportOptions {
|
||||
pages: Some(vec![page]),
|
||||
crop: o.crop,
|
||||
password: o.password.clone(),
|
||||
text_as: o.text_as,
|
||||
layers: false,
|
||||
embedded_fonts: o.embedded_fonts,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_pdf::TextAs;
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with_catalog};
|
||||
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf, pdf_with, pdf_with_catalog};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -135,11 +135,12 @@ fn ai_layer_names_are_read_as_pdf_doc_encoding() {
|
||||
|
||||
#[test]
|
||||
fn load_options_read_text_and_layers() {
|
||||
let o = LoadOptions::from_params("x", &json!({"textAs": "Outlines", "layers": false})).unwrap();
|
||||
assert_eq!((o.text_as, o.layers), (TextAs::Outlines, false));
|
||||
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");
|
||||
}
|
||||
@@ -180,3 +181,415 @@ fn exports_that_draw_type_in_a_missing_font_say_it_is_the_fallback_font() {
|
||||
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");
|
||||
}
|
||||
@@ -484,10 +484,17 @@ pub(super) fn used_fonts(d: &Document) -> BTreeSet<UsedFont> {
|
||||
/// in `art` (art read from a file, its resources in `d`), the type in opacity masks included. The
|
||||
/// pattern being edited is read from the editing layer only.
|
||||
pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
|
||||
fonts_of(d, art, false)
|
||||
}
|
||||
|
||||
/// [`art_fonts`]; `drawn`: only those the type is drawn in, not the fonts of runs drawn in a font
|
||||
/// their file carried ([`in_file_fonts`]).
|
||||
fn fonts_of(d: &Document, art: &[Node], drawn: bool) -> BTreeSet<UsedFont> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
let mut add = |n: &Node| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
fonts.extend(t.runs.iter().flat_map(run_fonts));
|
||||
let file = if drawn { in_file_fonts(t) } else { vec![] };
|
||||
fonts.extend(t.runs.iter().filter(|r| !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str()))).flat_map(run_fonts));
|
||||
}
|
||||
};
|
||||
let patterns = d.patterns.iter().filter(|p| !pattern_being_edited(d, &p.name)).flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
@@ -659,21 +666,25 @@ impl<'a> Printed<'a> {
|
||||
}
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Text(_) => {
|
||||
NodeKind::Text(t) => {
|
||||
if overflows && self.own {
|
||||
self.overflow.insert(n.id);
|
||||
}
|
||||
if overflows && let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
p.overflow.insert(owner);
|
||||
}
|
||||
let file = in_file_fonts(t);
|
||||
for r in runs {
|
||||
let fonts = run_fonts(r);
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
for font in &fonts {
|
||||
p.fonts.entry(font.clone()).or_default().insert(owner);
|
||||
// Drawn in a font its file carried: printed as the file drew it.
|
||||
if !file.contains(&(r.style.font_family.as_str(), r.style.font_style.as_str())) {
|
||||
let fonts = run_fonts(r);
|
||||
if let (Some(p), Some(owner)) = (&mut self.preflight, self.owner) {
|
||||
for font in &fonts {
|
||||
p.fonts.entry(font.clone()).or_default().insert(owner);
|
||||
}
|
||||
}
|
||||
self.fonts.extend(fonts);
|
||||
}
|
||||
self.fonts.extend(fonts);
|
||||
// Inline graphics draw their symbols' art.
|
||||
if let Some(art) = r.inline.as_ref().filter(|_| draws_inline(r)) {
|
||||
self.symbol(&art.symbol);
|
||||
@@ -757,9 +768,18 @@ fn drawn_runs(t: &vectorcraft_doc::TextObject) -> (Vec<&TextRun>, bool) {
|
||||
|
||||
/// What an export that draws type (as outlines, embedded fonts or pixels) says when `d` uses font
|
||||
/// families that aren't available (their type is drawn in the fallback font, not the font it
|
||||
/// names) or styles that its family doesn't have (the closest style is drawn).
|
||||
/// names) or styles that its family doesn't have (the closest style is drawn). Type drawn in a
|
||||
/// font its file carried isn't substituted.
|
||||
pub(super) fn substitution_warning(d: &Document) -> Option<String> {
|
||||
substitution_warning_of(used_fonts(d))
|
||||
substitution_warning_of(fonts_of(d, &[], true))
|
||||
}
|
||||
|
||||
/// The families and styles of the runs of `t` drawn in a font its file carried
|
||||
/// ([`vectorcraft_text::FontDb::file_faces`]): drawn as the file drew them, not in a substitute,
|
||||
/// though the font they name isn't available.
|
||||
fn in_file_fonts(t: &vectorcraft_doc::TextObject) -> Vec<(&str, &str)> {
|
||||
let faces = vectorcraft_text::FontDb::global().file_faces(t);
|
||||
t.runs.iter().zip(faces).filter(|(_, f)| f.is_some()).map(|(r, _)| (r.style.font_family.as_str(), r.style.font_style.as_str())).collect()
|
||||
}
|
||||
|
||||
/// [`substitution_warning`] for type set in `fonts`.
|
||||
|
||||
@@ -563,7 +563,7 @@ pub(crate) fn full_linked_images<'a>(d: &'a Document, base: LinkBase) -> (Cow<'a
|
||||
Some(f) if img.blob.bytes.as_slice() == bytes.as_slice() => f.mime.to_string(),
|
||||
_ => img.blob.mime.clone(),
|
||||
};
|
||||
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview });
|
||||
out.images.insert(key, ImageBlob { mime, bytes: img.blob.bytes, proxy: preview, file_font: Default::default() });
|
||||
}
|
||||
let mut warnings = vec![];
|
||||
match previews.len() {
|
||||
|
||||
@@ -960,10 +960,11 @@ impl Session {
|
||||
let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?;
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
// them, so the new document's assigned profiles draw and are saved with it.
|
||||
let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
let (mut doc, _, mut warnings) = super::fileio::decode_native_file(&bytes).map_err(|e| e.to_string())?;
|
||||
// Linked images in its symbols, patterns and brushes are read from their files, as placing
|
||||
// a document reads them.
|
||||
super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&file)), false, false);
|
||||
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
|
||||
Ok(Some(ReadProfile { doc, file, warnings }))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,7 +786,7 @@ fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
(true, _) => return Err(bad(PLACE, "replace: select the one object to replace")),
|
||||
};
|
||||
let replaced = old.and_then(|id| st.doc.node(id)).cloned();
|
||||
Ok(PlaceJob { doc: st.uid, params: p.clone(), old, replaced, target: board_at(&st.doc, at) })
|
||||
Ok(PlaceJob { doc: st.uid, params: s.prefs.with_pdf_font_choice(p), old, replaced, target: board_at(&st.doc, at) })
|
||||
}
|
||||
|
||||
/// Place the file `read` holds in the active document.
|
||||
|
||||
@@ -72,6 +72,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
|
||||
paint_refs(&mut r.style.fill, f);
|
||||
paint_refs(&mut r.style.stroke, f);
|
||||
}
|
||||
if let Some(fonts) = &mut t.file_fonts {
|
||||
fonts.map_keys(|key| f(Ref::Image(key)));
|
||||
}
|
||||
}
|
||||
NodeKind::Image(im) => f(Ref::Image(&mut im.key)),
|
||||
NodeKind::PlacedDocument(pl) => f(Ref::Image(&mut pl.key)),
|
||||
@@ -352,6 +355,19 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
|
||||
dst.images.insert(new.to_string(), blob.clone());
|
||||
}
|
||||
}
|
||||
// Equal font bytes can reuse an existing image entry whose runtime lease is still empty.
|
||||
// Transfer the validated source lease too: cached text nodes hold only weak references.
|
||||
for (old, (new, copy)) in &images {
|
||||
if *copy {
|
||||
continue;
|
||||
}
|
||||
let Some(blob) = src.images.get(old).filter(|b| b.mime == vectorcraft_doc::FILE_FONT_MIME) else { continue };
|
||||
let Some(target) = new.as_ref().and_then(|key| dst.images.get_mut(key)) else { continue };
|
||||
let owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(face) = owner.as_ref().filter(|face| std::ptr::eq(face.bytes(), blob.bytes.as_slice()) || face.bytes() == blob.bytes.as_slice()) {
|
||||
*target.file_font.get_mut().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
|
||||
}
|
||||
}
|
||||
for (old, new) in copies(&symbols) {
|
||||
if let Some(mut def) = src.symbols.iter().find(|s| s.name == old).cloned() {
|
||||
def.name = new.to_string();
|
||||
|
||||
@@ -333,7 +333,7 @@ fn read_source(
|
||||
}
|
||||
let a = opened_document_art(name, (bytes, opened), path, page, bounding, page_box, cmd)?;
|
||||
let bytes = shared.cloned().unwrap_or_else(|| Arc::new(bytes.to_vec()));
|
||||
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None };
|
||||
let mut blob = ImageBlob { mime: mime(name, &bytes).into(), bytes, proxy: None, file_font: Default::default() };
|
||||
let shown = PlacedDocument {
|
||||
link: LinkInfo { page: Some(page), ..LinkInfo::new(path.unwrap_or(name)) },
|
||||
key: key.clone(),
|
||||
@@ -468,7 +468,10 @@ pub(crate) fn full_documents(d: &Document) -> (Cow<'_, Document>, Vec<String>) {
|
||||
let Some(blob) = out.images.get(&p.key) else { continue };
|
||||
match vectorcraft_doc::placed_document::full_bytes(&p, blob) {
|
||||
Some(bytes) => {
|
||||
out.images.insert(p.key.clone(), ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone() });
|
||||
out.images.insert(
|
||||
p.key.clone(),
|
||||
ImageBlob { mime: mime(p.link.name(), &bytes).into(), bytes, proxy: blob.proxy.clone(), file_font: Default::default() },
|
||||
);
|
||||
}
|
||||
None => {
|
||||
previews.insert(p.key);
|
||||
|
||||
@@ -396,6 +396,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
|
||||
p!("recoveryOffForComplex", "File Handling", "Data Recovery", "Turn off Data Recovery for complex documents", bool),
|
||||
p!("recentFilesCount", "File Handling", "Files", "Number of Recent Files to Display", int(0, 30)),
|
||||
p!("lowResProxyEps", "File Handling", "Files", "Use Low Resolution Proxy for Linked EPS", bool),
|
||||
p!("pdfImportEmbeddedFonts", "File Handling", "Files", "Use fonts embedded in imported PDFs", bool),
|
||||
p!("antiAliasedBitmaps", "File Handling", "Files", "Display Bitmaps as Anti-aliased Images in Pixel Preview", bool),
|
||||
p!(
|
||||
"updateLinks",
|
||||
|
||||
@@ -1458,7 +1458,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
|
||||
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
|
||||
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
|
||||
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
|
||||
let (mut doc, _, mut warnings) = fileio::native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
|
||||
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
|
||||
// A frame whose first paragraph continues from the frame before draws it without the
|
||||
// paragraph's first-line indent and list marker.
|
||||
super::threads::mark_continued(&mut doc);
|
||||
@@ -1473,7 +1473,7 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
|
||||
};
|
||||
match read {
|
||||
Ok(data) => {
|
||||
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None };
|
||||
let mut blob = ImageBlob { mime: r.mime.clone(), bytes: data, proxy: None, file_font: Default::default() };
|
||||
// Until the linked file is read, the preview stands in for it.
|
||||
if r.proxy {
|
||||
blob.proxy = Some(blob.bytes.clone());
|
||||
@@ -1510,6 +1510,8 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
|
||||
let links_from = meta.path.clone().or_else(|| meta.links_from.clone());
|
||||
let base = super::links::LinkBase::file(links_from.as_deref());
|
||||
let links = super::links::resolve(&mut doc, base, s.prefs.update_links == "automatically", s.prefs.low_res_proxy_eps);
|
||||
// Bind only after the copy's external resources and linked files have been restored.
|
||||
warnings.extend(Session::refresh_text_bounds(&mut doc));
|
||||
let index = s.add_document(doc, meta.path.clone());
|
||||
let st = s.doc_mut()?;
|
||||
st.recovered = true;
|
||||
|
||||
@@ -1850,6 +1850,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
system_layout: false,
|
||||
fractional_widths: true,
|
||||
list_count: 0,
|
||||
file_fonts: None,
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
@@ -2158,6 +2159,7 @@ fn headline_tracking(t: &TextObject, target: f64) -> Option<f64> {
|
||||
system_layout: t.system_layout,
|
||||
fractional_widths: t.fractional_widths,
|
||||
list_count: 0,
|
||||
file_fonts: None,
|
||||
list_level_counts: Vec::new(),
|
||||
cached_bounds: None,
|
||||
cached_baselines: Vec::new(),
|
||||
|
||||
@@ -281,6 +281,10 @@ pub struct Prefs {
|
||||
pub recovery_off_for_complex: bool,
|
||||
pub recent_files_count: u32,
|
||||
pub low_res_proxy_eps: bool,
|
||||
/// File Handling › Use fonts embedded in imported PDFs: type in a font a PDF embeds and this
|
||||
/// machine lacks is drawn in the file's own glyphs (on by default); off, it is set in the
|
||||
/// fallback font with the missing-font warning (#4568).
|
||||
pub pdf_import_embedded_fonts: bool,
|
||||
pub anti_aliased_bitmaps: bool,
|
||||
pub update_links: String,
|
||||
/// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app
|
||||
@@ -446,6 +450,17 @@ pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0);
|
||||
|
||||
impl Prefs {
|
||||
/// The `document.open` / place params `p` with `embeddedFonts: false` added when Preferences
|
||||
/// › File Handling › Use fonts embedded in imported PDFs is off and `p` gives no choice of its own.
|
||||
pub fn with_pdf_font_choice(&self, p: &serde_json::Value) -> serde_json::Value {
|
||||
if self.pdf_import_embedded_fonts || p.get("embeddedFonts").is_some_and(|v| !v.is_null()) {
|
||||
return p.clone();
|
||||
}
|
||||
let mut out = if p.is_object() { p.clone() } else { serde_json::json!({}) };
|
||||
out["embeddedFonts"] = serde_json::json!(false);
|
||||
out
|
||||
}
|
||||
|
||||
/// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not
|
||||
/// checked against the range, so a value outside it is brought inside, and one that is not a
|
||||
/// number gives the default.
|
||||
@@ -592,6 +607,7 @@ impl Default for Prefs {
|
||||
recovery_off_for_complex: false,
|
||||
recent_files_count: 20,
|
||||
low_res_proxy_eps: false,
|
||||
pdf_import_embedded_fonts: true,
|
||||
anti_aliased_bitmaps: false,
|
||||
update_links: s("askWhenModified"),
|
||||
pdf_text_as: s("text"),
|
||||
|
||||
@@ -293,7 +293,9 @@ impl Session {
|
||||
/// what is fitted to type's bounds (an envelope warping it) would come out differently. That
|
||||
/// holds for the type in symbol definitions, pattern tiles, graph designs and opacity masks too,
|
||||
/// not only in the layers (#1738).
|
||||
pub(crate) fn refresh_text_bounds(doc: &mut Document) {
|
||||
pub(crate) fn refresh_text_bounds(doc: &mut Document) -> Vec<String> {
|
||||
// The fonts files carried for their type draw it ([`vectorcraft_doc::FileFonts`]).
|
||||
let warnings = vectorcraft_text::FontDb::global().bind_document_file_fonts(doc);
|
||||
// Inline graphics in text take their size from their symbols' art (not saved either).
|
||||
doc.resolve_inline_art();
|
||||
let mut uncached = |t: &TextObject| t.cached_bounds.is_none();
|
||||
@@ -303,6 +305,7 @@ impl Session {
|
||||
// The symbols' type is measured now: the inline graphics showing those symbols take their
|
||||
// art's measured size, a symbol's type before the type that shows that symbol inline.
|
||||
doc.resolve_inline_art_with(&mut cmd::typecmd::refresh_bounds_for_first_frame);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Measure the type in open document `index` that `stale` picks (in its trees as
|
||||
@@ -344,6 +347,8 @@ impl Session {
|
||||
// (importers and the native reader have seen to theirs already, with a warning).
|
||||
doc.limit_depth();
|
||||
cmd::compositefonts::filter_loaded(&mut doc);
|
||||
// Importers report binding failures; programmatic additions still need owned resources.
|
||||
let _ = vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc);
|
||||
// Inline graphics in text take their size from their symbols' art (not saved).
|
||||
doc.resolve_inline_art();
|
||||
// Ruler guides a reader left in the saved list become nodes on their layers.
|
||||
|
||||
@@ -481,7 +481,7 @@ fn eps_export_still_flattens_a_colorize_paint_on_a_color_image() {
|
||||
fn a_colorized_missing_link_placeholder_is_not_flattened() {
|
||||
let mut s = session();
|
||||
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
|
||||
s.edit("Colorize", |d, _| {
|
||||
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
|
||||
Ok(())
|
||||
@@ -502,7 +502,7 @@ fn a_colorized_missing_link_placeholder_is_not_flattened() {
|
||||
fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
|
||||
let mut s = session();
|
||||
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
|
||||
s.edit("Colorize", |d, _| {
|
||||
d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
|
||||
Ok(())
|
||||
@@ -523,7 +523,7 @@ fn a_fill_color_recolors_a_colorized_missing_link_placeholder() {
|
||||
fn a_colorized_missing_link_placeholder_in_a_spot_color_refuses_a_process_color() {
|
||||
let mut s = session();
|
||||
let bytes = std::sync::Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
|
||||
let id = image(&mut s, "pic", ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
|
||||
s.execute("swatch.new", &json!({"name": "Ink 2", "color": {"c": 100, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
|
||||
s.edit("Colorize", |d, _| {
|
||||
let ink = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
|
||||
@@ -1019,8 +1019,15 @@ fn package_copies_held_postscript_only_for_a_placed_document_with_a_postscript_n
|
||||
im.link.as_mut().unwrap().path = logo_ai.clone();
|
||||
im.link.as_mut().unwrap().relative = None;
|
||||
let key = im.key.clone();
|
||||
d.images
|
||||
.insert(key, vectorcraft_doc::ImageBlob { mime: "application/postscript".into(), bytes: std::sync::Arc::new(eps.to_vec()), proxy: None });
|
||||
d.images.insert(
|
||||
key,
|
||||
vectorcraft_doc::ImageBlob {
|
||||
mime: "application/postscript".into(),
|
||||
bytes: std::sync::Arc::new(eps.to_vec()),
|
||||
proxy: None,
|
||||
file_font: Default::default(),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
@@ -999,7 +999,10 @@ fn a_placed_brush_whose_art_uses_a_renamed_image_is_copied() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
s.edit("Brush", |d, _| {
|
||||
d.images.insert("k".into(), vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
|
||||
d.images.insert(
|
||||
"k".into(),
|
||||
vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() },
|
||||
);
|
||||
let im = vectorcraft_doc::ImageObject {
|
||||
key: "k".into(),
|
||||
width: 2,
|
||||
|
||||
@@ -2979,6 +2979,26 @@ fn snap_to_glyph_options_read_set_and_reset() {
|
||||
assert_eq!(s.execute("view.snapToGlyph.options", &json!({})).unwrap(), all);
|
||||
}
|
||||
|
||||
/// File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default)
|
||||
/// reaches Open and Place as the `embeddedFonts` choice, unless a call gives its own (#4568).
|
||||
#[test]
|
||||
fn the_embedded_fonts_preference_reaches_the_import_options() {
|
||||
use crate::cmd::fileio::LoadOptions;
|
||||
let mut s = Session::new();
|
||||
assert!(s.prefs.pdf_import_embedded_fonts, "on by default");
|
||||
let on = s.prefs.with_pdf_font_choice(&json!({}));
|
||||
assert!(LoadOptions::from_params("x", &on).unwrap().embedded_fonts);
|
||||
s.execute("prefs.set", &json!({"key": "pdfImportEmbeddedFonts", "value": false})).unwrap();
|
||||
let off = s.prefs.with_pdf_font_choice(&json!({"page": 2}));
|
||||
assert_eq!(off["page"], 2, "the call's own params stay");
|
||||
assert!(!LoadOptions::from_params("x", &off).unwrap().embedded_fonts);
|
||||
assert!(!LoadOptions::from_params("x", &s.prefs.with_pdf_font_choice(&Value::Null)).unwrap().embedded_fonts);
|
||||
// A call that says so wins over the preference.
|
||||
let own = s.prefs.with_pdf_font_choice(&json!({"embeddedFonts": true}));
|
||||
assert!(LoadOptions::from_params("x", &own).unwrap().embedded_fonts);
|
||||
assert!(LoadOptions::from_params("x", &json!({"embeddedFonts": "yes"})).is_err());
|
||||
}
|
||||
|
||||
/// Pixel Snapping Options: `view.snapToPixel.options` reads and sets While Drawing, While Moving
|
||||
/// and While Scaling, all on by default, kept as the `pixelSnap` preference group; bad keys and
|
||||
/// values change nothing, preferences saved without the group read it as all on, and resetting the
|
||||
|
||||
@@ -69,6 +69,77 @@ fn native_recovery_copies_leave_out_the_pdf() {
|
||||
assert_eq!(vectorcraft_format::load(&bytes).unwrap().node_count(), s.doc().unwrap().doc.node_count());
|
||||
}
|
||||
|
||||
const RECOVERY_FONT_FAMILY: &str = "Recovery Carried Font Regression";
|
||||
const RECOVERY_FONT_BYTES: &[u8] = include_bytes!("../../../../assets/fonts/Inter-Regular.ttf");
|
||||
|
||||
fn carried_font_copy() -> (Arc<MemoryStore>, vectorcraft_doc::NodeId) {
|
||||
use vectorcraft_doc::{CharStyle, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeKind, TextObject};
|
||||
|
||||
let (mut s, store) = session();
|
||||
let doc = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.images.insert("recovered-font".into(), ImageBlob::new(FILE_FONT_MIME, RECOVERY_FONT_BYTES.to_vec()));
|
||||
// An uninstalled family ensures the fixture must be read from the recovered resource.
|
||||
let style = CharStyle { font_family: RECOVERY_FONT_FAMILY.into(), size: 20.0, ..Default::default() };
|
||||
let mut text = TextObject::point(kurbo::Point::new(10.0, 40.0), "x", style);
|
||||
text.file_fonts = Some(Box::new(FileFonts::new(
|
||||
vec![FileFont { family: RECOVERY_FONT_FAMILY.into(), style: "Regular".into(), key: "recovered-font".into() }],
|
||||
"x",
|
||||
)));
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(Some(doc.layers[0].id), usize::MAX, Node::new(id, NodeKind::Text(Box::new(text)))).unwrap();
|
||||
let saved = s.execute("file.recovery.save", &json!({})).unwrap();
|
||||
let file = saved["saved"][0]["file"].as_str().unwrap();
|
||||
let lean = vectorcraft_format::load(&store.read(&format!("{file}.vectorcraft")).unwrap()).unwrap();
|
||||
assert!(lean.images.is_empty(), "the font travels in the recovery store, not the document entry");
|
||||
drop(s);
|
||||
(store, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovered_carried_fonts_bind_after_their_resources_are_restored() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
use vectorcraft_text::FontDb;
|
||||
|
||||
let (store, id) = carried_font_copy();
|
||||
let mut s = relaunch(&store);
|
||||
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
|
||||
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
|
||||
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
|
||||
assert!(reply["restored"][0]["warnings"].as_array().unwrap().is_empty(), "{reply}");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.images["recovered-font"].bytes.as_slice(), RECOVERY_FONT_BYTES);
|
||||
let NodeKind::Text(text) = &doc.node(id).unwrap().kind else { panic!("text") };
|
||||
let db = FontDb::global();
|
||||
let laid = vectorcraft_text::layout(db, text);
|
||||
assert_eq!(laid.glyphs.len(), 1);
|
||||
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
|
||||
assert_eq!(face.file_data(), RECOVERY_FONT_BYTES, "layout uses the recovered font's exact bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovered_missing_or_corrupt_carried_fonts_report_the_actual_refusal() {
|
||||
for missing in [true, false] {
|
||||
let (store, id) = carried_font_copy();
|
||||
let blob = store.list().unwrap().into_iter().find(|name| name.ends_with(".blob")).unwrap();
|
||||
if missing {
|
||||
store.remove(&blob).unwrap();
|
||||
} else {
|
||||
store.write(&blob, b"not a font").unwrap();
|
||||
}
|
||||
let mut s = relaunch(&store);
|
||||
let reply = s.execute("file.recovery.restore", &json!({})).unwrap();
|
||||
assert_eq!(reply["restored"].as_array().unwrap().len(), 1, "{reply}");
|
||||
assert!(reply["failed"].as_array().unwrap().is_empty(), "{reply}");
|
||||
let warnings = reply["restored"][0]["warnings"].as_array().unwrap();
|
||||
assert!(
|
||||
warnings.iter().any(|note| note.as_str().is_some_and(|note| note.contains(RECOVERY_FONT_FAMILY) && note.contains("substitute"))),
|
||||
"missing={missing}: {reply}"
|
||||
);
|
||||
let vectorcraft_doc::NodeKind::Text(text) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("text") };
|
||||
assert!(vectorcraft_text::FontDb::global().file_faces(text).is_empty(), "missing={missing}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restored_recovery_copies_keep_the_original_pdf_preference() {
|
||||
let dir = crate::tests_links::Folder::new("recovered-pdf-preference");
|
||||
|
||||
@@ -662,7 +662,7 @@ impl<'a> Reader<'a> {
|
||||
};
|
||||
// The placeholder is all the document has of the file: what a missing link shows.
|
||||
let bytes = Arc::new(png);
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
|
||||
let key = linked_key(&blob, &path);
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
self.warn(LINKED_PLACEHOLDERS);
|
||||
@@ -905,7 +905,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
// The preview is all the document has of the file: what a missing link shows.
|
||||
let bytes = Arc::new(png);
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) };
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() };
|
||||
let key = linked_key(&blob, &path);
|
||||
let fresh = !self.doc.images.contains_key(&key);
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
|
||||
@@ -586,7 +586,7 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize
|
||||
let mut doc = f.document;
|
||||
for (k, img) in f.images {
|
||||
let bytes = bytes_of(&img).ok_or_else(|| FormatError::BadImage(k.clone()))?;
|
||||
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None };
|
||||
let mut blob = ImageBlob { mime: img.mime, bytes, proxy: None, file_font: Default::default() };
|
||||
// Until the linked file is read, the preview stands in for it.
|
||||
if img.proxy {
|
||||
blob.proxy = Some(blob.bytes.clone());
|
||||
|
||||
@@ -57,7 +57,9 @@ fn include_linked_files_keeps_the_files_bytes() {
|
||||
// Only the preview loaded (the file was never found): the preview is all there is to write.
|
||||
let mut missing = linked_doc();
|
||||
let preview = Arc::new(vec![9, 9]);
|
||||
missing.images.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
|
||||
missing
|
||||
.images
|
||||
.insert("k".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
|
||||
let out = save_with(&missing, &SaveOptions { include_linked: true, ..SaveOptions::default() }).unwrap();
|
||||
assert_eq!(json_of(&out)["images"]["k"]["proxy"], true);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ use super::{
|
||||
PathData, PathDrawMode, Pattern, PatternDef, Placement, Rect, Scan, Shape, SoftMask, StrokeProps, TextAs, TextLine, TextOverprint, TilingPattern,
|
||||
Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient,
|
||||
};
|
||||
use crate::import_fonts::program_facts;
|
||||
use vectorcraft_text::{FileFontInfo, FileGlyph};
|
||||
|
||||
/// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]):
|
||||
/// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own.
|
||||
@@ -51,6 +53,12 @@ fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool {
|
||||
}
|
||||
|
||||
impl<'p> Builder<'p> {
|
||||
/// Draw type in the fonts the file embeds (the default) or not ([`crate::ImportOptions::embedded_fonts`]).
|
||||
pub(super) fn with_embedded_fonts(mut self, on: bool) -> Self {
|
||||
self.embedded_fonts = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) fn new(next: u64, colors: Colors<'p>, text_as: TextAs, route: bool) -> Self {
|
||||
Self {
|
||||
colors,
|
||||
@@ -67,6 +75,7 @@ impl<'p> Builder<'p> {
|
||||
held: vec![],
|
||||
lost: None,
|
||||
text_as,
|
||||
embedded_fonts: true,
|
||||
actual: Default::default(),
|
||||
images: HashMap::new(),
|
||||
image_keys: HashMap::new(),
|
||||
@@ -80,6 +89,8 @@ impl<'p> Builder<'p> {
|
||||
font_names: HashMap::new(),
|
||||
families: None,
|
||||
missing_fonts: vec![],
|
||||
file_glyphs: crate::import_fonts::FileFontGlyphs::default(),
|
||||
file_fonts: HashMap::new(),
|
||||
cid_text: HashMap::new(),
|
||||
font_chars: HashMap::new(),
|
||||
matched: HashMap::new(),
|
||||
@@ -782,11 +793,15 @@ impl<'p> Builder<'p> {
|
||||
/// it was kept as them ([`Self::end_text`]).
|
||||
fn end_line(&mut self, mut line: TextLine, glyphs: Vec<GlyphRun>) -> bool {
|
||||
let held = std::mem::take(&mut line.held);
|
||||
let (line_conflict, line_type3) = (line.file_conflict, line.has_type3);
|
||||
// Type the file names itself (ActualText) is in reading order as it stands.
|
||||
let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3;
|
||||
let mut outlined = false;
|
||||
if let Some((t, opacity, facts)) = line.finish() {
|
||||
if checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink) {
|
||||
// A line with a glyph the file's font can't keep (another glyph for the same character)
|
||||
// is kept as outlines too, so each glyph draws as the file does.
|
||||
let conflict = line_conflict && !glyphs.is_empty() && !line_type3;
|
||||
if conflict || (checked && reshaped::reshapes(&t.plain_text()) && !reshaped::draws_as(&t, &facts.ink)) {
|
||||
outlined = true;
|
||||
if self.mask.is_some() {
|
||||
self.flush_glyphs();
|
||||
@@ -1461,10 +1476,8 @@ impl<'p> Builder<'p> {
|
||||
// vector's vx (from the font's `W2`, else half its width from `W` or `DW`) to the left of
|
||||
// the column's centre (ISO 32000-1 §9.7.4.3); vertical type centres each glyph on the
|
||||
// column. Half an em only for a full-width glyph (#722).
|
||||
let top = upright.then(|| {
|
||||
let vx = self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph));
|
||||
m * kurbo::Point::new(vx, 880.0)
|
||||
});
|
||||
let vx = upright.then(|| self.fonts.get(&key).and_then(|f| f.vertical.as_ref()).map_or(500.0, |v| v.centre(glyph)));
|
||||
let top = vx.map(|vx| m * kurbo::Point::new(vx, 880.0));
|
||||
// A horizontal line is gathered in visual order and put back in logical order as a whole:
|
||||
// a ligature's characters (lam-alef, lam-lam-heh) go in visual order too (#6072).
|
||||
let text = if top.is_none() { visual_glyph_text(text) } else { text };
|
||||
@@ -1507,8 +1520,31 @@ impl<'p> Builder<'p> {
|
||||
place(&mut line);
|
||||
self.text = Some(line);
|
||||
}
|
||||
let outline = o.outline();
|
||||
// A font the file carries for a family that isn't available: the glyph goes into the font
|
||||
// kept with the document, which draws the line as the file does ([`crate::import_fonts`]).
|
||||
if let Some(font) = self.file_font(key, o, &look) {
|
||||
if let Some(line) = &mut self.text {
|
||||
line.file_font = true;
|
||||
}
|
||||
let mut chars = text.chars();
|
||||
if let (Some(ch), None) = (chars.next(), chars.next()) {
|
||||
// A glyph set vertically has no horizontal width: its column's, twice its centre.
|
||||
let advance = match vx {
|
||||
Some(vx) => 2.0 * vx,
|
||||
None => width.map_or(500.0, f64::from),
|
||||
};
|
||||
if self.file_glyphs.wants(font, ch) {
|
||||
self.file_glyphs.add(font, FileGlyph { ch, outline: outline.clone(), advance });
|
||||
} else if self.file_glyphs.conflicts(font, ch, &outline, advance)
|
||||
&& let Some(line) = &mut self.text
|
||||
{
|
||||
line.file_conflict = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Its ink: a stroke the file draws as outlines of the glyphs is told by it.
|
||||
let mut ink = o.outline();
|
||||
let mut ink = outline;
|
||||
if top.is_none() {
|
||||
self.keep_glyph(o, m, drawn, opacity, scale, overprint);
|
||||
}
|
||||
@@ -1520,6 +1556,36 @@ impl<'p> Builder<'p> {
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The font among the glyphs gathered for fonts kept with the document that glyphs of font
|
||||
/// `key` (drawn with `look`) go into: when the file carries the font's program, no installed
|
||||
/// face has its PostScript name, and its family and style aren't available as named. Decided
|
||||
/// once per font.
|
||||
fn file_font(&mut self, key: u128, o: &craft_pdf::interpret::font::OutlineGlyph, look: &Look) -> Option<usize> {
|
||||
if let Some(f) = self.file_fonts.get(&key) {
|
||||
return *f;
|
||||
}
|
||||
// Not the interpreter's stand-in for a font the file doesn't carry.
|
||||
let carried = self.embedded_fonts && self.fonts.get(&key).is_some_and(|f| f.embedded) && o.font_data().is_none_or(|d| d.embedded);
|
||||
let installed = self.font_names.get(&key).is_some_and(|i| i.face.is_some());
|
||||
let available =
|
||||
|| vectorcraft_text::FontDb::global().resolve(&look.family, &look.style).is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact);
|
||||
let font = (carried && !installed && !look.family.trim().is_empty() && !available()).then(|| {
|
||||
let data = o.font_data();
|
||||
let (fs_type, metrics) = data.as_ref().map_or((None, None), |d| program_facts(d.data.as_ref().as_ref(), d.index));
|
||||
let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.and_then(|d| d.postscript_name)).unwrap_or_default();
|
||||
// A subset's six-letter tag.
|
||||
let postscript = match name.split_once('+') {
|
||||
Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(),
|
||||
_ => name,
|
||||
};
|
||||
let (ascent, descent) = metrics.unwrap_or_default();
|
||||
let info = || FileFontInfo { family: look.family.clone(), style: look.style.clone(), postscript, ascent, descent, fs_type };
|
||||
self.file_glyphs.font(&look.family, &look.style, info)
|
||||
});
|
||||
self.file_fonts.insert(key, font);
|
||||
font
|
||||
}
|
||||
}
|
||||
|
||||
/// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::{
|
||||
ImportReport, InterpreterCache, InterpreterSettings, InterpreterWarning, LayerColor, MAX_NESTING, Mutex, Node, NodeKind, Ocgs, Ordering, Paint,
|
||||
PdfError, Rect, Shape, Swatch, all_on, contains, hides_forms, scan_page, white_cover,
|
||||
};
|
||||
use crate::import_text::keep_file_fonts;
|
||||
|
||||
/// Mixed into an image's cache key when it is read white inside an alpha soft mask.
|
||||
pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa;
|
||||
@@ -242,6 +243,32 @@ pub fn imports_of(bytes: &[u8]) -> usize {
|
||||
IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The notes on the fonts the file draws with that aren't available: type in a font the file
|
||||
/// carries keeps its look until it is edited; the rest shows in the fallback font.
|
||||
fn warn_missing_fonts(b: &mut Builder, doc: &Document) {
|
||||
let mut bound = std::collections::HashSet::new();
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
for font in t.file_fonts_in_use() {
|
||||
if t.file_fonts.as_ref().and_then(|fonts| fonts.face(&font.key)).is_some() {
|
||||
bound.insert(font.family.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let (carried, missing): (Vec<String>, Vec<String>) = std::mem::take(&mut b.missing_fonts).into_iter().partition(|family| bound.contains(family));
|
||||
if !carried.is_empty() {
|
||||
b.warn(&format!(
|
||||
"fonts that aren't available show as the file draws them, in the fonts it carries, until their text is edited (then in the fallback font): {}",
|
||||
carried.join(", ")
|
||||
));
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
let list = missing.join(", ");
|
||||
b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The widest bleed of `pages` on each side (`[top, bottom, left, right]`, see [`crate::pages::bleed`]).
|
||||
fn widest_bleed<'p, 'd: 'p>(pages: impl Iterator<Item = &'p craft_pdf::syntax::page::Page<'d>>) -> [f64; 4] {
|
||||
pages.fold([0.0; 4], |widest, page| {
|
||||
@@ -278,7 +305,7 @@ fn read_opened(
|
||||
doc.artboards.clear();
|
||||
doc.layers.clear();
|
||||
let taken: Vec<String> = doc.swatches_iter().map(|s| s.name.clone()).chain(doc.swatch_groups.iter().map(|g| g.name.clone())).collect();
|
||||
let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route);
|
||||
let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route).with_embedded_fonts(opts.embedded_fonts);
|
||||
// The art of a group that is off (drawn as `all_on` turned it on) or doesn't print mustn't
|
||||
// show or print on its page's layer.
|
||||
b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print);
|
||||
@@ -437,6 +464,9 @@ fn read_opened(
|
||||
// The groups' layers stack as the pages mark them (the art outside them stays where it was
|
||||
// drawn): a group that first paints on a later page doesn't go on top of the others.
|
||||
stack_groups(&mut slots, &order);
|
||||
// The fonts the file carries for families that aren't available, kept with the document: the
|
||||
// type set in them is drawn in them and spaced from the file's own widths.
|
||||
let kept = std::mem::take(&mut b.file_glyphs).keep(&mut b.images);
|
||||
for (n, slot) in slots.into_iter().enumerate() {
|
||||
let mut layer = match slot {
|
||||
Slot::Page(l) => *l,
|
||||
@@ -447,6 +477,7 @@ fn read_opened(
|
||||
},
|
||||
};
|
||||
if let Some(art) = layer.children_mut() {
|
||||
keep_file_fonts(art, &b.lines, &kept, &b.images);
|
||||
crate::import_lines::rebuild(art, &b.lines);
|
||||
}
|
||||
doc.layers.push(Arc::new(layer));
|
||||
@@ -474,10 +505,7 @@ fn read_opened(
|
||||
if b.colors.mixed {
|
||||
b.warn("colours mixing several inks (DeviceN) were imported as RGB");
|
||||
}
|
||||
if !b.missing_fonts.is_empty() {
|
||||
let list = b.missing_fonts.join(", ");
|
||||
b.warn(&format!("fonts that aren't available show in the fallback font until they are: {list}"));
|
||||
}
|
||||
warn_missing_fonts(&mut b, &doc);
|
||||
// Before anything walks the tree by recursion (`fix_next_id` does): nested clips can be deeper
|
||||
// than the stack goes.
|
||||
let mut depth_notes = vec![];
|
||||
@@ -486,6 +514,7 @@ fn read_opened(
|
||||
doc.reserve_ids(b.next);
|
||||
|
||||
let mut warnings = b.warnings;
|
||||
warnings.extend(vectorcraft_text::FontDb::global().bind_document_file_fonts(&mut doc));
|
||||
if let Ok(v) = sink.lock() {
|
||||
for w in v.iter() {
|
||||
if !warnings.contains(w) {
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::{
|
||||
Affine, Arc, BezPath, BlendMode, Colors, Dash, Families, FillRule, FontNames, FunctionBudget, HashMap, HashSet, ImageBlob, LineCap, LineFacts,
|
||||
LineJoin, LumaData, MaskSpec, Node, NodeId, Paint, PathEl, PatternDef, Rect, Scan, StrokeLayer, StrokeProps, TextAs, TextLine, TypeStroke,
|
||||
};
|
||||
use crate::import_fonts::FileFontGlyphs;
|
||||
|
||||
/// Decoded RGBA pixels, width, height and hayro's scale factors.
|
||||
pub(super) type Decoded = (Vec<u8>, u32, u32, (f32, f32));
|
||||
@@ -127,6 +128,8 @@ pub(super) struct Builder<'p> {
|
||||
/// anything else drawn ([`Builder::flush_text`]).
|
||||
pub(super) lost: Option<crate::import_text::LostFills>,
|
||||
pub(super) text_as: TextAs,
|
||||
/// Fonts the file embeds are kept (ImportOptions::embedded_fonts).
|
||||
pub(super) embedded_fonts: bool,
|
||||
pub(super) actual: super::actual_text::ActualText,
|
||||
pub(super) images: HashMap<String, ImageBlob>,
|
||||
pub(super) image_keys: HashMap<u128, (String, u32, u32)>,
|
||||
@@ -150,6 +153,11 @@ pub(super) struct Builder<'p> {
|
||||
pub(super) font_names: HashMap<u128, FontInfo>,
|
||||
pub(super) families: Option<Families>,
|
||||
pub(super) missing_fonts: Vec<String>,
|
||||
/// The glyphs drawn in fonts the file carries for families that aren't available, for the
|
||||
/// fonts kept with the document ([`crate::import_fonts`]).
|
||||
pub(super) file_glyphs: FileFontGlyphs,
|
||||
/// Font (cache key) → its font among `file_glyphs`; `None`: its type takes the font it names.
|
||||
pub(super) file_fonts: HashMap<u128, Option<usize>>,
|
||||
/// Font (cache key) → its characters by glyph, for CID-keyed fonts embedded without a
|
||||
/// ToUnicode map.
|
||||
pub(super) cid_text: HashMap<u128, Option<Arc<CidText>>>,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! The fonts a PDF carries (embeds) for type whose fonts aren't available here: the glyphs it draws
|
||||
//! in each, gathered as its pages are read, become one font per family and style, kept with the
|
||||
//! document ([`vectorcraft_doc::FileFonts`]), that draws that type as the file did until its text
|
||||
//! is edited. A file embeds its fonts so that it shows in them wherever it is read (Acrobat Help,
|
||||
//! PDF fonts, <https://helpx.adobe.com/acrobat/using/pdf-fonts.html>).
|
||||
//!
|
||||
//! Each glyph comes as the interpreter draws it (an outline in thousandths of an em, whatever the
|
||||
//! font program: Type 1, CFF or TrueType, simple or CID-keyed) with the width the file gives it, for
|
||||
//! the character the file says it shows (its `ToUnicode` map, or what the import reads from the
|
||||
//! font program). The first glyph of each character is kept; a line using a different glyph for
|
||||
//! that character is imported as outlines instead.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use vectorcraft_doc::{FILE_FONT_MIME, ImageBlob};
|
||||
use vectorcraft_text::{FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font};
|
||||
|
||||
/// The most glyphs gathered from one file, in all its fonts (an outline is some hundreds of bytes;
|
||||
/// a CJK document uses a few thousand characters).
|
||||
const MAX_GLYPHS: usize = 200_000;
|
||||
|
||||
/// The licence flags (OS/2 `fsType`) of `a` and `b` that allow less: a restricted font beats one
|
||||
/// that may be embedded whole, which beats one that may be embedded as a subset. A font without
|
||||
/// flags reads as print and preview (4), as a font built from it does.
|
||||
fn stricter(a: Option<u16>, b: Option<u16>) -> Option<u16> {
|
||||
use vectorcraft_text::embed::Embedding;
|
||||
let rank = |f: Option<u16>| match Embedding::from_fs_type(f.unwrap_or(4)) {
|
||||
Embedding::Subset => 0,
|
||||
Embedding::Whole => 1,
|
||||
Embedding::Forbidden => 2,
|
||||
};
|
||||
if rank(b) > rank(a) { b } else { a }
|
||||
}
|
||||
|
||||
/// The glyphs gathered so far.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct FileFontGlyphs {
|
||||
fonts: Vec<Gathered>,
|
||||
/// Each font (family and style) by its index in `fonts`.
|
||||
index: HashMap<(String, String), usize>,
|
||||
/// Glyphs gathered, in all.
|
||||
count: usize,
|
||||
}
|
||||
|
||||
/// The glyphs of one family and style.
|
||||
struct Gathered {
|
||||
family: String,
|
||||
style: String,
|
||||
info: FileFontInfo,
|
||||
glyphs: Vec<FileGlyph>,
|
||||
/// Each character's glyph, by its index in `glyphs`.
|
||||
chars: HashMap<char, usize>,
|
||||
}
|
||||
|
||||
impl FileFontGlyphs {
|
||||
/// The font of `family` and `style` (made with `info` the first time): its index.
|
||||
pub fn font(&mut self, family: &str, style: &str, info: impl FnOnce() -> FileFontInfo) -> usize {
|
||||
if let Some(&i) = self.index.get(&(family.to_string(), style.to_string())) {
|
||||
// Two programs of one family and style share one font here: it takes the stricter
|
||||
// of their licence flags, so a restricted one's glyphs never read as permitted.
|
||||
if let Some(g) = self.fonts.get_mut(i) {
|
||||
g.info.fs_type = stricter(g.info.fs_type, info().fs_type);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
let i = self.fonts.len();
|
||||
self.fonts.push(Gathered { family: family.to_string(), style: style.to_string(), info: info(), glyphs: vec![], chars: HashMap::new() });
|
||||
self.index.insert((family.to_string(), style.to_string()), i);
|
||||
i
|
||||
}
|
||||
|
||||
/// Does font `font` still want a glyph for `ch` (none gathered yet, and room for it)?
|
||||
pub fn wants(&self, font: usize, ch: char) -> bool {
|
||||
self.count < MAX_GLYPHS && self.fonts.get(font).is_some_and(|f| f.glyphs.len() < MAX_FILE_GLYPHS && !f.chars.contains_key(&ch))
|
||||
}
|
||||
|
||||
/// Does font `font` hold a glyph for `ch` that differs from `outline` or `advance`? A font keeps
|
||||
/// one glyph per character, so a file's other glyph for it (a stylistic alternate that maps to
|
||||
/// the same character) can't go into it: the line it is on is kept as outlines instead.
|
||||
pub fn conflicts(&self, font: usize, ch: char, outline: &BezPath, advance: f64) -> bool {
|
||||
self.fonts
|
||||
.get(font)
|
||||
.and_then(|f| f.chars.get(&ch).and_then(|&i| f.glyphs.get(i)))
|
||||
.is_some_and(|g| g.outline != *outline || g.advance != advance)
|
||||
}
|
||||
|
||||
/// Gather `glyph` for font `font`.
|
||||
pub fn add(&mut self, font: usize, glyph: FileGlyph) {
|
||||
if !self.wants(font, glyph.ch) {
|
||||
return;
|
||||
}
|
||||
if let Some(f) = self.fonts.get_mut(font) {
|
||||
f.chars.insert(glyph.ch, f.glyphs.len());
|
||||
f.glyphs.push(glyph);
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts built from gathered glyphs, stored under their content keys. Only text that
|
||||
/// actually references one admits a runtime face, before it is respaced.
|
||||
pub fn keep(self, images: &mut HashMap<String, ImageBlob>) -> HashMap<(String, String), String> {
|
||||
let mut kept = HashMap::new();
|
||||
for f in self.fonts {
|
||||
let Some(bytes) = build_file_font(&f.info, &f.glyphs) else { continue };
|
||||
let blob = ImageBlob::new(FILE_FONT_MIME, bytes);
|
||||
let base = blob.content_key();
|
||||
let mut key = base.clone();
|
||||
let mut suffix = 1;
|
||||
while images.get(&key).is_some_and(|held| held != &blob) {
|
||||
key = format!("{base}-{suffix}");
|
||||
suffix += 1;
|
||||
}
|
||||
images.entry(key.clone()).or_insert(blob);
|
||||
kept.insert((f.family, f.style), key);
|
||||
}
|
||||
kept
|
||||
}
|
||||
}
|
||||
|
||||
/// What a font program the file embeds (`data`, a TrueType or OpenType file, or a bare CFF font)
|
||||
/// says of the font's licence (OS/2 `fsType`) and its ascent and descent (thousandths of an em).
|
||||
pub(crate) fn program_facts(data: &[u8], index: u32) -> (Option<u16>, Option<(f64, f64)>) {
|
||||
use skrifa::MetadataProvider;
|
||||
use skrifa::raw::TableProvider;
|
||||
let Ok(f) = skrifa::FontRef::from_index(data, index) else { return (None, None) };
|
||||
let fs_type = f.os2().ok().map(|o| o.fs_type());
|
||||
let m = f.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default());
|
||||
let k = 1000.0 / f64::from(m.units_per_em.max(1));
|
||||
let (ascent, descent) = (f64::from(m.ascent) * k, f64::from(m.descent) * k);
|
||||
let metrics = (ascent.is_finite() && descent.is_finite() && ascent > 0.0 && descent <= 0.0).then_some((ascent, descent));
|
||||
(fs_type, metrics)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two programs of one family and style are one font here, and its flags are the stricter
|
||||
/// of theirs whichever came first (CodeRabbit, #4569).
|
||||
#[test]
|
||||
fn two_programs_of_one_font_keep_the_stricter_licence() {
|
||||
for (first, second, want) in [
|
||||
(Some(4), Some(2), Some(2)),
|
||||
(Some(2), Some(4), Some(2)),
|
||||
(None, Some(0x0200), Some(0x0200)),
|
||||
(Some(4), Some(0x0108), Some(0x0108)),
|
||||
(Some(0x0108), Some(2), Some(2)),
|
||||
(Some(8), Some(4), Some(8)),
|
||||
(None, None, None),
|
||||
] {
|
||||
let mut g = FileFontGlyphs::default();
|
||||
let info = |fs_type| {
|
||||
move || FileFontInfo { family: "F".into(), style: "R".into(), postscript: "F-R".into(), ascent: 800.0, descent: -200.0, fs_type }
|
||||
};
|
||||
let a = g.font("F", "R", info(first));
|
||||
let b = g.font("F", "R", info(second));
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(g.fonts[a].info.fs_type, want, "{first:?} then {second:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,14 +7,14 @@
|
||||
//! - area type comes as a line of point type per line, each wrapped line ending in a space. Lines
|
||||
//! in a row sharing a left edge, font, size and leading (and paragraph spacing) are one area
|
||||
//! type object again, aligned left or justified, where laying its text out in the frame breaks
|
||||
//! it where the file does: else, as where its font isn't installed, they stay lines.
|
||||
//! it where the file does; otherwise they stay lines. Carried fonts are used for this check.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_color::BlendMode;
|
||||
use vectorcraft_doc::{AppearanceItem, CharStyle, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{AppearanceItem, CharStyle, FileFont, FileFonts, Justify, Node, NodeId, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::import_text::{LineFacts, median};
|
||||
@@ -258,6 +258,30 @@ fn laid_out(texts: &[(&TextObject, &LineFacts)], b: &Block, justify: Justify, wi
|
||||
}
|
||||
let mut t = (*first).clone();
|
||||
t.runs = runs;
|
||||
// The fonts the file carries that draw the lines draw them as one object too.
|
||||
let mut fonts: Vec<FileFont> = vec![];
|
||||
for f in texts.iter().flat_map(|(t, _)| t.file_fonts_in_use()) {
|
||||
if !fonts.contains(f) {
|
||||
fonts.push(f.clone());
|
||||
}
|
||||
}
|
||||
t.file_fonts = (!fonts.is_empty()).then(|| {
|
||||
let resources = fonts
|
||||
.iter()
|
||||
.take(vectorcraft_doc::text::MAX_FILE_FONTS)
|
||||
.filter_map(|font| {
|
||||
texts
|
||||
.iter()
|
||||
.find_map(|(line, _)| {
|
||||
line.file_fonts_in_use().iter().any(|f| f.key == font.key).then(|| line.file_fonts.as_ref()?.face(&font.key)).flatten()
|
||||
})
|
||||
.map(|face| (font.key.clone(), face))
|
||||
})
|
||||
.collect();
|
||||
let mut kept = FileFonts::new(fonts, &t.plain_text());
|
||||
kept.bind(resources);
|
||||
Box::new(kept)
|
||||
});
|
||||
t.para.justify = justify;
|
||||
t.para.space_before = b.space;
|
||||
let last = b.ys.last().copied()?;
|
||||
|
||||
+166
-88
@@ -4,16 +4,19 @@
|
||||
//! baseline, text rise, is baseline shift). Each glyph stays where the file drew it: the kerning
|
||||
//! and tracking the type takes put it there (#722). Fonts are named from the file's base font name (its
|
||||
//! subset prefix dropped, the family matched against the fonts available); a font that isn't
|
||||
//! available keeps its name, and the text shows in the fallback font until it is.
|
||||
//! available keeps its name. Where the file carries that font, its glyphs make a font kept with the
|
||||
//! document ([`crate::import_fonts`]) that draws the type as the file did until its text is
|
||||
//! edited ([`keep_file_fonts`]); otherwise the text shows in the fallback font until it is.
|
||||
//!
|
||||
//! Glyphs each turned a little further along a curve (type set on a path: apps write each glyph
|
||||
//! with its own placement) make one type-on-a-path object, its path through the glyphs' baseline.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{CharStyle, LineCap, LineJoin, Node, ParaDirection, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{CharStyle, FileFont, FileFonts, LineCap, LineJoin, Node, NodeId, NodeKind, ParaDirection, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_text::TextLayout;
|
||||
|
||||
/// One glyph's placement: its baseline origin, advance direction, size and horizontal scale.
|
||||
@@ -268,8 +271,13 @@ pub(crate) struct TextLine {
|
||||
/// The strokes of its glyphs' outlines drawn between them, one per glyph with ink so far
|
||||
/// (written right after the line).
|
||||
pub held: Vec<Node>,
|
||||
/// A glyph of the line is drawn in a font the file carries for a family that isn't available
|
||||
/// ([`keep_file_fonts`]).
|
||||
pub file_font: bool,
|
||||
/// Whether this line holds Type 3 font glyphs.
|
||||
pub has_type3: bool,
|
||||
/// A glyph of the line differs from the one its font keeps for the same character ([`crate::import_fonts::FileFontGlyphs::conflicts`]).
|
||||
pub file_conflict: bool,
|
||||
}
|
||||
|
||||
/// Where the file put a glyph: the glyph's index in the line, and its advance in the file's font
|
||||
@@ -368,6 +376,9 @@ pub(crate) struct LineFacts {
|
||||
/// Horizontal point type: how long the file set it, from its first glyph's origin to the end
|
||||
/// of its last glyph that isn't a space (points, along the baseline).
|
||||
pub length: f64,
|
||||
/// Set in a font the file carries for a family that isn't available: what its spacing is
|
||||
/// measured from, to measure it again once that font is kept ([`keep_file_fonts`]).
|
||||
pub respace: Option<Box<Spacing>>,
|
||||
}
|
||||
|
||||
/// The most a glyph on a curve turns from the one before it (about 20°).
|
||||
@@ -401,7 +412,9 @@ impl TextLine {
|
||||
drawn_spaces: vec![],
|
||||
drawn_space: None,
|
||||
held: vec![],
|
||||
file_font: false,
|
||||
has_type3: false,
|
||||
file_conflict: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1014,79 +1027,163 @@ impl TextLine {
|
||||
let angle = self.at.dir.atan2();
|
||||
// The glyphs' tops lean along the baseline (+x), up being -y in the type's own space.
|
||||
t.xf = Affine::translate(self.at.origin.to_vec2()) * Affine::rotate(angle) * Affine::skew(-self.at.slant, 0.0);
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Each glyph where the file put it (#722): the kerning (the font's, or none) and tracking
|
||||
// (one value for the line, or each character its own) that place them there.
|
||||
let placed = (self.upright.is_none() && t.para.direction.is_none())
|
||||
.then(|| place_each(&t, &self.slots, &self.baseline, path.as_ref(), self.at, self.at.size))
|
||||
.flatten()
|
||||
.map(|(runs, laid)| {
|
||||
t.runs = runs;
|
||||
laid.bounds
|
||||
});
|
||||
if let Some(path) = path {
|
||||
// Evenly spaced type keeps its length along the path: the path runs through the
|
||||
// glyphs' origins, one curve each, to the end of the last glyph, and tracking makes up
|
||||
// the difference from the advances.
|
||||
if placed.is_none() {
|
||||
let length: f64 = path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum();
|
||||
let laid = vectorcraft_text::layout(db, &t);
|
||||
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
|
||||
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let size = self.at.size;
|
||||
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
|
||||
let (tracking, spaces) = spacing(&laid, &[], length - natural, chars, size, spacing_em(&t, size));
|
||||
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
|
||||
}
|
||||
}
|
||||
t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(&path), start: 0.0, end: None };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.cached_bounds = Some(vectorcraft_text::layout(db, &t).bounds);
|
||||
return Some((t, self.opacity, facts));
|
||||
}
|
||||
let (start, along) = match self.upright {
|
||||
// How far along the line the file put each glyph: along the path through them (one curve
|
||||
// each), or along the baseline from the line's origin.
|
||||
let along: Vec<f64> = match &path {
|
||||
Some(bp) => std::iter::once(0.0)
|
||||
.chain(bp.segments().scan(0.0, |d, seg| {
|
||||
*d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3);
|
||||
Some(*d)
|
||||
}))
|
||||
.take(self.baseline.len())
|
||||
.collect(),
|
||||
None => self.baseline.iter().map(|p| (*p - self.at.origin).dot(self.at.dir)).collect(),
|
||||
};
|
||||
// Evenly spaced type on a path keeps its length along the path: the path runs through the
|
||||
// glyphs' origins, one curve each, to the end of the last glyph.
|
||||
let path_length =
|
||||
path.as_ref().map(|path| path.segments().take(self.baseline.len()).map(|seg| kurbo::ParamCurveArclen::arclen(&seg, 1e-3)).sum());
|
||||
let start = match self.upright {
|
||||
// Vertical point type (a column, or a single upright glyph) is anchored at the top
|
||||
// centre of its first em box.
|
||||
Some(u) => {
|
||||
Some(u) if path.is_none() => {
|
||||
t.vertical = true;
|
||||
t.xf = Affine::translate(u.top.to_vec2()) * Affine::rotate(angle);
|
||||
(self.at.origin, -self.at.up())
|
||||
-self.at.up()
|
||||
}
|
||||
_ => (self.at.origin, self.at.dir),
|
||||
_ => self.at.dir,
|
||||
};
|
||||
// Tracking that makes the line as long as in the file: the PDF placed each glyph, the
|
||||
// layout sets them by their advances. Spread over the gaps between characters (tracking
|
||||
// follows each character, the last one's past the end of the line). A horizontal line is
|
||||
// measured to its last glyph that isn't a space: the spaces after it were dropped.
|
||||
let length = (if t.vertical { self.next } else { self.visible } - start).dot(along);
|
||||
if !t.vertical {
|
||||
// A horizontal line is measured to its last glyph that isn't a space (the spaces after it
|
||||
// were dropped), a column to the end of its last glyph.
|
||||
let length = (if t.vertical { self.next } else { self.visible } - self.at.origin).dot(start);
|
||||
if path.is_none() && !t.vertical {
|
||||
facts.length = length;
|
||||
}
|
||||
// Placed glyph by glyph: laid out so already.
|
||||
if let Some(bounds) = placed {
|
||||
t.cached_bounds = Some(bounds);
|
||||
return Some((t, self.opacity, facts));
|
||||
if let Some(path) = &path {
|
||||
t.kind = TextKind::OnPath { path: vectorcraft_geom::PathData::from_bezpath(path), start: 0.0, end: None };
|
||||
t.xf = Affine::IDENTITY;
|
||||
}
|
||||
let laid = vectorcraft_text::layout(db, &t);
|
||||
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
|
||||
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let size = self.at.size;
|
||||
let mut bounds = laid.bounds;
|
||||
if chars > 1 && length.is_finite() && (length - natural).abs() > size * 0.01 {
|
||||
// The spaces read from gaps or drawn between glyphs keep their own place only in text
|
||||
// left in the file's order.
|
||||
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
|
||||
let gaps: Vec<(usize, f64)> = if t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] };
|
||||
let (tracking, spaces) = spacing(&laid, &gaps, length - natural, chars, size, spacing_em(&t, size));
|
||||
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
|
||||
// Tracked: laid out again for its bounds.
|
||||
bounds = vectorcraft_text::layout(db, &t).bounds;
|
||||
// The spaces read from gaps or drawn between glyphs keep their own place only in a line
|
||||
// left in the file's order (not along a path).
|
||||
let total: usize = t.runs.iter().map(|r| r.text.len()).sum();
|
||||
let gaps: Vec<(usize, f64)> =
|
||||
if path.is_none() && t.para.direction.is_none() { gaps.into_iter().filter(|(b, _)| *b < total).collect() } else { vec![] };
|
||||
let s = Spacing {
|
||||
runs: t.runs.clone(),
|
||||
slots: std::mem::take(&mut self.slots),
|
||||
// Glyph by glyph only in horizontal type in the file's order.
|
||||
along: (self.upright.is_none() && t.para.direction.is_none()).then_some(along),
|
||||
slant: if path.is_some() { 0.0 } else { self.at.slant },
|
||||
size: self.at.size,
|
||||
length: path_length.unwrap_or(length),
|
||||
gaps,
|
||||
};
|
||||
space_line(&mut t, &s);
|
||||
// Set in a font the file carries for a family that isn't available: spaced again once that
|
||||
// font is kept with the document ([`keep_file_fonts`]).
|
||||
if self.file_font {
|
||||
facts.respace = Some(Box::new(s));
|
||||
}
|
||||
t.cached_bounds = Some(bounds);
|
||||
Some((t, self.opacity, facts))
|
||||
}
|
||||
}
|
||||
|
||||
/// What a line's spacing is measured from: where the file put its glyphs. Kept with a line set in
|
||||
/// a font the file carries for a family that isn't available ([`LineFacts::respace`]), to be
|
||||
/// measured again against that font once it is kept with the document ([`keep_file_fonts`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Spacing {
|
||||
/// The line's runs, unspaced.
|
||||
runs: Vec<TextRun>,
|
||||
/// Where the file put each character ([`TextLine::slots`]).
|
||||
slots: Vec<Option<Slot>>,
|
||||
/// How far along the line (or its path) the file put each glyph (points); `None` when the
|
||||
/// glyphs aren't placed one by one (vertical type, type in visual order).
|
||||
along: Option<Vec<f64>>,
|
||||
/// The type's slant ([`Placement::slant`]; 0 on a path).
|
||||
slant: f64,
|
||||
size: f64,
|
||||
/// How long the file set the line (points): along its path, to the end of a column, or to
|
||||
/// the last glyph of a horizontal line that isn't a space.
|
||||
length: f64,
|
||||
/// The spaces read from gaps or drawn between glyphs: byte offset, width (points).
|
||||
gaps: Vec<(usize, f64)>,
|
||||
}
|
||||
|
||||
/// Space `t` (whose runs are `s`'s, unspaced) as the file did ([`Spacing`]): each glyph where the
|
||||
/// file put it (#722) with the kerning (the font's, or none) and tracking (one value for the line,
|
||||
/// or each character its own) that place them there ([`place_each`]); else tracking that makes
|
||||
/// the line as long as in the file (the PDF placed each glyph, the layout sets them by their
|
||||
/// advances), spread over the gaps between characters (tracking follows each character, the last
|
||||
/// one's past the end of the line). Its bounds are laid out too.
|
||||
fn space_line(t: &mut TextObject, s: &Spacing) {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
t.runs = s.runs.clone();
|
||||
let on_path = !matches!(t.kind, TextKind::Point);
|
||||
// Measured as point type: type on a path stops at the path's end, which tracking moves.
|
||||
let point = |t: &TextObject| TextObject { kind: TextKind::Point, ..t.clone() };
|
||||
let placed = s.along.as_ref().and_then(|along| place_each(&point(t), &s.slots, along, s.slant, s.size));
|
||||
if let Some((runs, laid)) = placed {
|
||||
t.runs = runs;
|
||||
t.cached_bounds = Some(if on_path { vectorcraft_text::layout(db, t).bounds } else { laid.bounds });
|
||||
return;
|
||||
}
|
||||
let laid = vectorcraft_text::layout(db, &point(t));
|
||||
let natural: f64 = laid.glyphs.iter().map(|g| g.advance).sum();
|
||||
let chars: usize = t.runs.iter().map(|r| r.text.chars().count()).sum();
|
||||
let mut bounds = (!on_path).then_some(laid.bounds);
|
||||
if chars > 1 && s.length.is_finite() && (s.length - natural).abs() > s.size * 0.01 {
|
||||
let (tracking, spaces) = spacing(&laid, &s.gaps, s.length - natural, chars, s.size, spacing_em(t, s.size));
|
||||
t.runs = tracked(std::mem::take(&mut t.runs), tracking, &spaces);
|
||||
// Tracked: laid out again for its bounds.
|
||||
bounds = None;
|
||||
}
|
||||
t.cached_bounds = Some(bounds.unwrap_or_else(|| vectorcraft_text::layout(db, t).bounds));
|
||||
}
|
||||
|
||||
/// The type among `nodes` (and in their groups) set in fonts the file carries for families that
|
||||
/// aren't available, now kept with the document as `kept` (family and style → the font's blob):
|
||||
/// drawn in them while its text is the file's ([`vectorcraft_doc::FileFonts`]), and spaced again
|
||||
/// from where the file put each glyph, measured against the file's own widths (not the stand-in's,
|
||||
/// which differ, #3756).
|
||||
pub(crate) fn keep_file_fonts(
|
||||
nodes: &mut [Arc<Node>],
|
||||
lines: &HashMap<NodeId, LineFacts>,
|
||||
kept: &HashMap<(String, String), String>,
|
||||
images: &HashMap<String, vectorcraft_doc::ImageBlob>,
|
||||
) {
|
||||
if kept.is_empty() {
|
||||
return;
|
||||
}
|
||||
for n in nodes.iter_mut() {
|
||||
if n.children().is_some_and(|c| !c.is_empty())
|
||||
&& let Some(children) = Arc::make_mut(n).children_mut()
|
||||
{
|
||||
keep_file_fonts(children, lines, kept, images);
|
||||
}
|
||||
let Some(s) = lines.get(&n.id).and_then(|f| f.respace.as_deref()) else { continue };
|
||||
let mut fonts: Vec<FileFont> = vec![];
|
||||
for r in &s.runs {
|
||||
let (family, style) = (&r.style.font_family, &r.style.font_style);
|
||||
if let Some(key) = kept.get(&(family.clone(), style.clone()))
|
||||
&& !fonts.iter().any(|f| f.family == *family && f.style == *style)
|
||||
{
|
||||
fonts.push(FileFont { family: family.clone(), style: style.clone(), key: key.clone() });
|
||||
}
|
||||
}
|
||||
if fonts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let NodeKind::Text(t) = &mut Arc::make_mut(n).kind {
|
||||
let text: String = s.runs.iter().map(|r| r.text.as_str()).collect();
|
||||
t.file_fonts = Some(Box::new(FileFonts::new(fonts, &text)));
|
||||
// A blob reference is not ownership until its actual document resource is bound.
|
||||
vectorcraft_text::FontDb::global().bind_file_fonts(t, |key| images.get(key));
|
||||
space_line(t, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where along the line (points) layout `laid` puts each character at a byte offset of `chars`
|
||||
/// (in order), and its advance: `None` for one inside another's cluster. Text in the file's order
|
||||
/// (left to right).
|
||||
@@ -1142,21 +1239,14 @@ fn restyled(t: &TextObject, kern: Option<f64>, own: &[f64]) -> Vec<TextRun> {
|
||||
/// file's widths (not the font's advances, which may be a hair off them) and kept on course where
|
||||
/// the differences add up ([`on_course`]).
|
||||
///
|
||||
/// The file put the glyph of each character with a [`Slot`] at `baseline` (one origin per glyph),
|
||||
/// measured along `path` (type on a path: one curve per glyph) or along `line`'s baseline from its
|
||||
/// origin, where a character shifted off it by its baseline shift draws that shift times `line`'s
|
||||
/// slant further along (the type's skew leans it so, as the file's text rise did). `None` when the
|
||||
/// font laid out isn't the file's (its advances differ from the file's): spacing measured against
|
||||
/// a stand-in's widths would keep the stand-in's differences once the font is installed; or when
|
||||
/// the glyphs can't be placed so (the layout joins characters the file drew apart).
|
||||
fn place_each(
|
||||
t: &TextObject,
|
||||
slots: &[Option<Slot>],
|
||||
baseline: &[Point],
|
||||
path: Option<&BezPath>,
|
||||
line: Placement,
|
||||
size: f64,
|
||||
) -> Option<(Vec<TextRun>, TextLayout)> {
|
||||
/// The file put the glyph of each character with a [`Slot`] `along` the line (points from its
|
||||
/// origin, or along its path), where a character shifted off the baseline by its baseline shift
|
||||
/// draws that shift times `slant` further along (the type's skew leans it so, as the file's text
|
||||
/// rise did). `None` when the font laid out isn't the file's (its advances differ from the file's):
|
||||
/// spacing measured against a stand-in's widths would keep the stand-in's differences once the
|
||||
/// font is installed; or when the glyphs can't be placed so (the layout joins characters the file
|
||||
/// drew apart).
|
||||
fn place_each(t: &TextObject, slots: &[Option<Slot>], along: &[f64], slant: f64, size: f64) -> Option<(Vec<TextRun>, TextLayout)> {
|
||||
let chars: Vec<usize> = t
|
||||
.runs
|
||||
.iter()
|
||||
@@ -1170,20 +1260,8 @@ fn place_each(
|
||||
if chars.len() < 2 || chars.len() != slots.len() || t.runs.iter().any(|r| r.inline.is_some()) {
|
||||
return None;
|
||||
}
|
||||
// How far along the line the file put each glyph.
|
||||
let along: Vec<f64> = match path {
|
||||
Some(bp) => std::iter::once(0.0)
|
||||
.chain(bp.segments().scan(0.0, |d, seg| {
|
||||
*d += kurbo::ParamCurveArclen::arclen(&seg, 1e-3);
|
||||
Some(*d)
|
||||
}))
|
||||
.take(baseline.len())
|
||||
.collect(),
|
||||
None => baseline.iter().map(|p| (*p - line.origin).dot(line.dir)).collect(),
|
||||
};
|
||||
// Each character's baseline shift, which the type's slant draws `slant` times as far along.
|
||||
let shifts: Vec<f64> = t.runs.iter().flat_map(|r| r.text.chars().map(move |_| r.style.baseline_shift)).collect();
|
||||
let slant = if path.is_some() { 0.0 } else { line.slant };
|
||||
// Each character's target: where the file put it, if it put it anywhere.
|
||||
let target: Vec<Option<(f64, Option<f64>)>> =
|
||||
slots.iter().zip(&shifts).map(|(s, shift)| s.and_then(|s| Some((*along.get(s.glyph)? - slant * shift, s.advance)))).collect();
|
||||
|
||||
@@ -51,6 +51,7 @@ mod forms;
|
||||
mod images;
|
||||
mod import;
|
||||
mod import_color;
|
||||
mod import_fonts;
|
||||
mod import_image;
|
||||
mod import_lines;
|
||||
mod import_mask;
|
||||
@@ -151,6 +152,10 @@ pub struct ImportOptions {
|
||||
/// The file is an editor's own document (`.ai`): RGB in its `ICCBased` spaces keeps its numbers
|
||||
/// (see `Colors::uncalibrated_rgb`). Off for PDFs, whose profiles stand.
|
||||
pub uncalibrated_rgb: bool,
|
||||
/// Type in a font the file embeds and this machine lacks is drawn in glyphs built from the
|
||||
/// file's own, kept with the document (default); off, it is set in the fallback font, with the
|
||||
/// missing-font warning, as before.
|
||||
pub embedded_fonts: bool,
|
||||
}
|
||||
|
||||
impl Default for ImportOptions {
|
||||
@@ -164,6 +169,7 @@ impl Default for ImportOptions {
|
||||
text_as: TextAs::default(),
|
||||
layers: true,
|
||||
uncalibrated_rgb: false,
|
||||
embedded_fonts: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ mod dashalign;
|
||||
mod diamond;
|
||||
mod editing;
|
||||
mod encrypt;
|
||||
mod file_fonts;
|
||||
mod file_info;
|
||||
mod focal;
|
||||
mod fx;
|
||||
|
||||
@@ -1547,7 +1547,7 @@ fn gray_freeform_points_are_written_as_black_ink_in_a_cmyk_document() {
|
||||
#[test]
|
||||
fn press_quality_writes_an_rgb_image_in_a_cmyk_document_as_cmyk() {
|
||||
let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128]));
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None };
|
||||
let blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() };
|
||||
let d = image_doc(blob, 4, 4);
|
||||
let press = builtin_presets().into_iter().find(|p| p.name == "Press Quality").unwrap().settings;
|
||||
assert_eq!(press.output.conversion, ColorConversion::PreserveNumbers);
|
||||
@@ -1569,7 +1569,7 @@ fn press_quality_writes_cmyk_in_an_rgb_document_too() {
|
||||
let ink = [0u8, 102, 255, 0];
|
||||
let tiff = ImageBlob::cmyk_tiff(&Inks::new(4, 4, flat(ink, 16)).unwrap()).unwrap();
|
||||
let rgb = image::RgbImage::from_fn(4, 4, |x, y| image::Rgb([(x * 60) as u8, (y * 60) as u8, 128]));
|
||||
let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None };
|
||||
let png_blob = ImageBlob { mime: "image/png".into(), bytes: Arc::new(png(rgb)), proxy: None, file_font: Default::default() };
|
||||
for (what, blob) in [("CMYK image", tiff), ("RGB image", png_blob)] {
|
||||
let mut d = image_doc(blob, 4, 4);
|
||||
d.color_mode = ColorMode::Rgb;
|
||||
|
||||
@@ -343,7 +343,8 @@ fn separations_colorize_masked_pixels_whose_own_pixels_are_a_preview() {
|
||||
let spot = Paint::Solid { color: Color::cmyk(0.0, 1.0, 1.0, 0.0), swatch: Some("Ink".into()), tint: 1.0 };
|
||||
let mut d = doc(ColorMode::Cmyk, Some(spot));
|
||||
let preview = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
|
||||
d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview) });
|
||||
d.images
|
||||
.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() });
|
||||
let img =
|
||||
craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, vec![0, 0, 255, 255])
|
||||
.unwrap();
|
||||
@@ -379,7 +380,8 @@ fn a_colorized_missing_link_placeholder_is_written_in_its_own_colors() {
|
||||
let placeholder = || {
|
||||
let mut d = doc(ColorMode::Cmyk, None);
|
||||
let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder().unwrap());
|
||||
d.images.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) });
|
||||
d.images
|
||||
.insert("pic".into(), ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() });
|
||||
d
|
||||
};
|
||||
let plain = placeholder();
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
//! Type in a font the PDF carries for a family that isn't installed keeps the file's glyphs and
|
||||
//! their places until its text is edited ([`vectorcraft_doc::FileFonts`]): drawn as it is in the
|
||||
//! same PDF whose font is installed, saved and read back so, and in the substitute once edited.
|
||||
|
||||
use craft_pdf::write::backend as krilla;
|
||||
use krilla::geom::Point as KPoint;
|
||||
use krilla::page::PageSettings;
|
||||
use krilla::text::{Font, GlyphId, KrillaGlyph, TextDirection};
|
||||
use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_doc::{Document, FILE_FONT_MIME, TextObject};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
use crate::tests::live_text::{SOURCE_SERIF, outlines, texts, uninstalled_serif};
|
||||
use crate::*;
|
||||
|
||||
/// Lines of (x, y from the top, size, text): kerned pairs, a long line, two sizes.
|
||||
const LINES: &[(f32, f32, f32, &str)] =
|
||||
&[(20.0, 40.0, 24.0, "AVATAR Toyota"), (20.0, 80.0, 11.0, "Wavy quartz jumps over 12 lazy dogs."), (20.0, 120.0, 30.0, "Ky Wo")];
|
||||
/// A line set glyph by glyph, each 2 pt further on than its advance (as `Tc` or `TJ` set it).
|
||||
const SPACED: (f32, f32, f32, &str) = (20.0, 160.0, 14.0, "Spaced out");
|
||||
|
||||
/// A page of [`LINES`] and [`SPACED`] in `font` (Source Serif 4 or a renamed copy), written as
|
||||
/// writers write type: a subset of the font embedded as a CID-keyed TrueType font (Identity-H) with
|
||||
/// a ToUnicode map.
|
||||
fn page_pdf(font: Vec<u8>) -> Vec<u8> {
|
||||
let mut pdf = krilla::Document::new();
|
||||
let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap());
|
||||
let mut s = page.surface();
|
||||
let kfont = Font::new(font.into(), 0).unwrap();
|
||||
for &(x, y, size, text) in LINES {
|
||||
s.draw_text(KPoint::from_xy(x, y), kfont.clone(), size, text, false, TextDirection::Auto);
|
||||
}
|
||||
let face = FontDb::global().face("Source Serif 4", "Regular").unwrap();
|
||||
let (x, y, size, text) = SPACED;
|
||||
let glyphs: Vec<KrillaGlyph> = text
|
||||
.char_indices()
|
||||
.map(|(i, c)| {
|
||||
let g = face.glyph_for(c);
|
||||
let advance = face.advance(g) / face.units_per_em() + 2.0 / f64::from(size);
|
||||
KrillaGlyph::new(GlyphId::new(g), advance as f32, 0.0, 0.0, 0.0, i..i + c.len_utf8(), None)
|
||||
})
|
||||
.collect();
|
||||
s.draw_glyphs(KPoint::from_xy(x, y), &glyphs, kfont, text, size, false);
|
||||
s.finish();
|
||||
page.finish();
|
||||
pdf.finish().unwrap()
|
||||
}
|
||||
|
||||
fn import(bytes: &[u8]) -> ImportReport {
|
||||
import_with_report(bytes, &ImportOptions::default()).unwrap()
|
||||
}
|
||||
|
||||
/// A drawn line: its text, and its glyphs' origins and ink boxes (document space).
|
||||
type DrawnLine = (String, Vec<(Point, Option<Rect>)>);
|
||||
|
||||
/// Each line `db` lays the type of `d` out in ([`DrawnLine`]), sorted by text.
|
||||
fn drawn(db: &FontDb, d: &Document) -> Vec<DrawnLine> {
|
||||
let mut out = vec![];
|
||||
for t in texts(d) {
|
||||
let lay = vectorcraft_text::layout(db, &t);
|
||||
let plain = t.plain_text();
|
||||
for (i, line) in lay.lines.iter().enumerate() {
|
||||
let glyphs = lay
|
||||
.glyphs
|
||||
.iter()
|
||||
.filter(|g| g.line == i)
|
||||
.map(|g| {
|
||||
let ink = (!g.outline.elements().is_empty()).then(|| (t.xf * g.outline.clone()).bounding_box());
|
||||
(t.xf * g.origin, ink)
|
||||
})
|
||||
.collect();
|
||||
out.push((plain[line.start..line.end].trim().to_string(), glyphs));
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
out
|
||||
}
|
||||
|
||||
/// The largest distance between the glyphs of `a` and `b`, line by line (their texts the same).
|
||||
fn farthest(a: &[DrawnLine], b: &[DrawnLine]) -> f64 {
|
||||
assert_eq!(a.iter().map(|l| &l.0).collect::<Vec<_>>(), b.iter().map(|l| &l.0).collect::<Vec<_>>(), "the same lines");
|
||||
let mut far: f64 = 0.0;
|
||||
for ((text, ga), (_, gb)) in a.iter().zip(b) {
|
||||
assert_eq!(ga.len(), gb.len(), "{text}");
|
||||
for ((pa, ia), (pb, ib)) in ga.iter().zip(gb) {
|
||||
far = far.max((*pa - *pb).hypot());
|
||||
match (ia, ib) {
|
||||
(Some(ia), Some(ib)) => {
|
||||
far = far.max((ia.x0 - ib.x0).abs().max((ia.x1 - ib.x1).abs()).max((ia.y0 - ib.y0).abs()).max((ia.y1 - ib.y1).abs()))
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => panic!("{text}: ink on one side only"),
|
||||
}
|
||||
}
|
||||
}
|
||||
far
|
||||
}
|
||||
|
||||
fn text_of<'a>(d: &'a [TextObject], text: &str) -> &'a TextObject {
|
||||
d.iter()
|
||||
.find(|t| t.plain_text() == text)
|
||||
.unwrap_or_else(|| panic!("no `{text}` among {:?}", d.iter().map(TextObject::plain_text).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_in_a_font_the_file_carries_keeps_its_glyphs_and_places() {
|
||||
let db = FontDb::global();
|
||||
let installed = import(&page_pdf(SOURCE_SERIF.to_vec()));
|
||||
let carried = import(&page_pdf(uninstalled_serif()));
|
||||
let t = texts(&carried.document);
|
||||
assert_eq!(t.len(), LINES.len() + 1, "a line stays a line: {:?}", t.iter().map(TextObject::plain_text).collect::<Vec<_>>());
|
||||
// Named by the file's font, which stays missing (Find Font and the Missing Fonts dialog list it).
|
||||
let st = text_of(&t, "AVATAR Toyota").first_style();
|
||||
assert_eq!(st.font_family, "Source Serif 9");
|
||||
assert_eq!(db.resolve(&st.font_family, &st.font_style).map(|(_, m)| m), Some(FontMatch::Missing));
|
||||
// Drawn as the same file whose font is installed: the file's glyphs, where the file put them.
|
||||
let far = farthest(&drawn(db, &carried.document), &drawn(db, &installed.document));
|
||||
assert!(far < 0.02, "glyphs {far} pt off the installed font's");
|
||||
// Every glyph from the font the file carries, which the document keeps.
|
||||
for t in &t {
|
||||
let lay = vectorcraft_text::layout(db, t);
|
||||
assert!(lay.glyphs.iter().all(|g| db.is_file_font(g.font_id)), "{}", t.plain_text());
|
||||
let key = &t.file_fonts.as_ref().unwrap().fonts[0].key;
|
||||
assert_eq!(carried.document.images[key].mime, FILE_FONT_MIME);
|
||||
}
|
||||
assert_eq!(carried.document.images.values().filter(|b| b.mime == FILE_FONT_MIME).count(), 1, "one font for the family and style");
|
||||
// Where the file put them: the ink is the file's own glyphs' (read as outlines).
|
||||
let as_outlines = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap();
|
||||
let ink = drawn(db, &carried.document).iter().flat_map(|(_, g)| g.iter().filter_map(|(_, i)| *i)).reduce(|a, b| a.union(b)).unwrap();
|
||||
let file = outlines(&as_outlines.document).bounding_box();
|
||||
let off = (ink.x0 - file.x0).abs().max((ink.x1 - file.x1).abs()).max((ink.y0 - file.y0).abs()).max((ink.y1 - file.y1).abs());
|
||||
assert!(off < 0.05, "{ink:?} vs the file's {file:?}");
|
||||
// Spacing measured from the file's widths, as with the font installed (not a stand-in's, #3756).
|
||||
let tracking = |d: &Document| text_of(&texts(d), "Spaced out").first_style().tracking;
|
||||
assert!(
|
||||
(tracking(&carried.document) - tracking(&installed.document)).abs() < 1.0,
|
||||
"{} vs {}",
|
||||
tracking(&carried.document),
|
||||
tracking(&installed.document)
|
||||
);
|
||||
assert!(carried.warnings.iter().any(|w| w.contains("Source Serif 9") && w.contains("until their text is edited")), "{:?}", carried.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_type_takes_the_substitute_and_unedited_type_keeps_the_files_font() {
|
||||
let db = FontDb::global();
|
||||
let carried = import(&page_pdf(uninstalled_serif()));
|
||||
let t = text_of(&texts(&carried.document), "AVATAR Toyota").clone();
|
||||
let from_file = |t: &TextObject| vectorcraft_text::layout(db, t).glyphs.iter().filter(|g| db.is_file_font(g.font_id)).count();
|
||||
assert_eq!(from_file(&t), vectorcraft_text::layout(db, &t).glyphs.len(), "every glyph");
|
||||
// Moved or resized, the text is the file's: still its font.
|
||||
let mut moved = t.clone();
|
||||
moved.xf = kurbo::Affine::translate((40.0, 10.0)) * moved.xf;
|
||||
for r in &mut moved.runs {
|
||||
r.style.size *= 2.0;
|
||||
}
|
||||
assert!(from_file(&moved) > 0);
|
||||
// Edited: the substitute (the run still names the missing font).
|
||||
let mut edited = t.clone();
|
||||
edited.runs[0].text.insert(0, 'Z');
|
||||
assert!(edited.file_fonts_in_use().is_empty());
|
||||
assert_eq!(from_file(&edited), 0);
|
||||
assert_eq!(edited.first_style().font_family, "Source Serif 9");
|
||||
// Undone, the file's again.
|
||||
edited.runs[0].text.remove(0);
|
||||
assert_eq!(from_file(&edited), from_file(&t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_font_that_is_installed_keeps_drawing_its_type() {
|
||||
// With the family installed nothing is kept: the type is set in the installed font as before.
|
||||
let installed = import(&page_pdf(SOURCE_SERIF.to_vec()));
|
||||
assert!(!installed.document.images.values().any(|b| b.mime == FILE_FONT_MIME));
|
||||
assert!(texts(&installed.document).iter().all(|t| t.file_fonts.is_none()));
|
||||
}
|
||||
|
||||
/// `ImportOptions::embedded_fonts` on (the default): type in an embedded font the machine lacks
|
||||
/// carries the file's glyphs (a font blob kept with the document) and the text keeps naming the
|
||||
/// file's font.
|
||||
#[test]
|
||||
fn embedded_fonts_on_keeps_the_files_glyphs() {
|
||||
let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: true, ..Default::default() }).unwrap();
|
||||
assert!(r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "a font kept with the document");
|
||||
assert!(texts(&r.document).iter().any(|t| t.file_fonts.is_some()), "its type draws in the file's font");
|
||||
}
|
||||
|
||||
/// Off (Preferences › File Handling › Use fonts embedded in imported PDFs): import behaves as it
|
||||
/// did without the feature: no font is kept, the type is set in the fallback font and the missing
|
||||
/// font is warned about.
|
||||
#[test]
|
||||
fn embedded_fonts_off_sets_type_in_the_fallback_font_with_the_warning() {
|
||||
let r = import_with_report(&page_pdf(uninstalled_serif()), &ImportOptions { embedded_fonts: false, ..Default::default() }).unwrap();
|
||||
assert!(!r.document.images.values().any(|b| b.mime == FILE_FONT_MIME), "no font kept");
|
||||
assert!(texts(&r.document).iter().all(|t| t.file_fonts.is_none()), "no type draws in a file font");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("Source Serif 9")), "the missing font is named: {:?}", r.warnings);
|
||||
let st = texts(&r.document)[0].first_style().clone();
|
||||
assert_eq!(st.font_family, "Source Serif 9", "the text still names the file's font");
|
||||
}
|
||||
|
||||
/// A page with the glyph of `a`, then of `b`, then of `a` again, each on its own line and each
|
||||
/// named `a` by the ToUnicode map: two different glyphs of the embedded font for one character.
|
||||
fn two_glyphs_pdf() -> Vec<u8> {
|
||||
let face = FontDb::global().face("Source Serif 4", "Regular").unwrap();
|
||||
let mut pdf = krilla::Document::new();
|
||||
let mut page = pdf.start_page_with(PageSettings::from_wh(400.0, 200.0).unwrap());
|
||||
let mut s = page.surface();
|
||||
let font = Font::new(uninstalled_serif().into(), 0).unwrap();
|
||||
// Glyph `from` standing for the character "a", on its own line at y.
|
||||
let mut draw = |y: f32, from: char| {
|
||||
let g = KrillaGlyph::new(GlyphId::new(face.glyph_for(from)), 0.5, 0.0, 0.0, 0.0, 0..1, None);
|
||||
s.draw_glyphs(KPoint::from_xy(20.0, y), &[g], font.clone(), "a", 30.0, false);
|
||||
};
|
||||
draw(40.0, 'a');
|
||||
draw(100.0, 'b');
|
||||
draw(160.0, 'a');
|
||||
s.finish();
|
||||
page.finish();
|
||||
pdf.finish().unwrap()
|
||||
}
|
||||
|
||||
/// The ink box of the glyph on each of the page's three lines (set at 40, 100 and 160 pt from the
|
||||
/// top) as `d` draws it: type laid out by `db` and outline paths, which an import may merge into
|
||||
/// one path for the page, so their subpaths are told apart by the line they lie on.
|
||||
fn glyph_ink(db: &FontDb, d: &Document) -> Vec<Rect> {
|
||||
let mut lines: [Option<Rect>; 3] = [None; 3];
|
||||
let mut add = |path: &kurbo::BezPath| {
|
||||
let mut start = 0;
|
||||
let els = path.elements();
|
||||
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 = 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;
|
||||
}
|
||||
};
|
||||
for t in texts(d) {
|
||||
for g in vectorcraft_text::layout(db, &t).glyphs {
|
||||
add(&(t.xf * g.outline.clone()));
|
||||
}
|
||||
}
|
||||
d.walk(|n| {
|
||||
if let vectorcraft_doc::NodeKind::Path { path, .. } = &n.kind {
|
||||
add(&path.to_bezpath());
|
||||
}
|
||||
});
|
||||
lines.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// Two different glyphs of the embedded font that map to one character (a normal and an alternate
|
||||
/// `a`, here the glyphs of `a` and `b` both named `a` by the ToUnicode map) can't both go into the
|
||||
/// font kept with the document, which has one glyph per character: the line with the other glyph is
|
||||
/// kept as outlines. Each glyph is the one the file draws, where it draws it: the outlines of the same page
|
||||
/// imported as outlines are the reference (the save and reopen half is `two_glyphs_for_one_character_survive_a_native_save_and_reopen` in the engine).
|
||||
#[test]
|
||||
fn two_glyphs_for_one_character_both_survive_import() {
|
||||
let db = FontDb::global();
|
||||
let bytes = two_glyphs_pdf();
|
||||
let reference = glyph_ink(db, &import_with_report(&bytes, &ImportOptions { text_as: TextAs::Outlines, ..Default::default() }).unwrap().document);
|
||||
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, "and the first and third are the same glyph: {reference:?}");
|
||||
|
||||
let imported = import(&bytes).document;
|
||||
let text: Vec<String> = texts(&imported).iter().map(|t| t.plain_text()).collect();
|
||||
assert!(text.iter().any(|t| t == "a"), "the glyphs the font keeps stay live type: {text:?}");
|
||||
assert!(text.len() < 3, "the line with the other glyph is not live type: {text:?}");
|
||||
|
||||
let close = |got: &[Rect], what: &str| {
|
||||
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(&glyph_ink(db, &imported), "imported");
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use vectorcraft_doc::{Document, NodeKind, TextObject};
|
||||
use crate::*;
|
||||
|
||||
const SOURCE_SANS: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf");
|
||||
pub(crate) const SOURCE_SERIF: &[u8] = include_bytes!("../../../../assets/fonts/SourceSerif4-Regular.ttf");
|
||||
|
||||
/// A 300 × 200 pt page with `lines` of (x, y from the top, size, text) in Source Sans 3, and the
|
||||
/// same rotated 90° when `rotated`.
|
||||
@@ -33,7 +33,7 @@ pub(crate) fn text_pdf(lines: &[(f32, f32, f32, &str)], rotated: bool) -> Vec<u8
|
||||
pdf.finish().unwrap()
|
||||
}
|
||||
|
||||
fn texts(d: &Document) -> Vec<TextObject> {
|
||||
pub(crate) fn texts(d: &Document) -> Vec<TextObject> {
|
||||
let mut v = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
@@ -294,7 +294,7 @@ fn uninstalled_font() -> Vec<u8> {
|
||||
|
||||
/// Source Serif 4 renamed `SourceSerif9-Regular`, family Source Serif 9: a serif font that isn't
|
||||
/// installed (the fallback font, Source Sans 3, is a sans).
|
||||
fn uninstalled_serif() -> Vec<u8> {
|
||||
pub(crate) fn uninstalled_serif() -> Vec<u8> {
|
||||
renamed(SOURCE_SERIF, &[("SourceSerif4", "SourceSerif9"), ("Source Serif 4", "Source Serif 9")])
|
||||
}
|
||||
|
||||
@@ -310,7 +310,7 @@ fn one_line_pdf(font: Vec<u8>, text: &str) -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// The outlines text imported as (`textAs: outlines`), as one path.
|
||||
fn outlines(d: &Document) -> kurbo::BezPath {
|
||||
pub(crate) fn outlines(d: &Document) -> kurbo::BezPath {
|
||||
let mut all = kurbo::BezPath::new();
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Path { path, .. } = &n.kind {
|
||||
|
||||
@@ -284,7 +284,7 @@ fn colorize_dims_with_the_grays() {
|
||||
fn a_colorized_missing_link_placeholder_draws_in_its_own_colors() {
|
||||
let proxy = |bytes: Vec<u8>| {
|
||||
let bytes = std::sync::Arc::new(bytes);
|
||||
ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes) }
|
||||
ImageBlob { mime: "image/png".into(), bytes: bytes.clone(), proxy: Some(bytes), file_font: Default::default() }
|
||||
};
|
||||
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
|
||||
let sharp = RenderOptions { smooth_images: false, ..Default::default() };
|
||||
|
||||
@@ -75,6 +75,55 @@ fn type_redraws_when_its_font_becomes_available() {
|
||||
assert_eq!(after, Renderer::new().render(&d, 300, 150, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it");
|
||||
}
|
||||
|
||||
/// Same serialized text and node ids are not the same glyph geometry when each document owns
|
||||
/// different file-font bytes. Both fonts are bound before either render, so generation is steady.
|
||||
#[test]
|
||||
fn file_font_geometry_is_scoped_to_owned_resources_not_serialized_keys() {
|
||||
use vectorcraft_doc::{FILE_FONT_MIME, FileFont, FileFonts, ImageBlob};
|
||||
use vectorcraft_text::{FileFontInfo, FileGlyph, FontDb, build_file_font};
|
||||
|
||||
let _adding = adding_fonts();
|
||||
let make = |width| {
|
||||
const FAMILY: &str = "Rendered Owned File Font Regression";
|
||||
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 mut doc = Document::new(100.0, 100.0);
|
||||
doc.images.insert("chosen".into(), ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[g]).unwrap()));
|
||||
let style = CharStyle { size: 60.0, font_family: FAMILY.into(), ..Default::default() };
|
||||
let mut t = TextObject::point(Point::new(10.0, 70.0), "x", style);
|
||||
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();
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
assert!(FontDb::global().bind_document_file_fonts(&mut doc).is_empty());
|
||||
doc
|
||||
};
|
||||
let (a, b) = (make(200.0), make(800.0));
|
||||
let renderer = with_fonts_unchanged(|| {
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let mut reused = Renderer::new();
|
||||
let first = reused.render(&a, 100, 100, Affine::IDENTITY, &opts).pixels;
|
||||
let second = reused.render(&b, 100, 100, Affine::IDENTITY, &opts).pixels;
|
||||
let fresh = Renderer::new().render(&b, 100, 100, Affine::IDENTITY, &opts).pixels;
|
||||
assert_ne!(first, second, "B must draw its own wider glyph");
|
||||
assert_eq!(second, fresh, "a renderer must not reuse A's glyph geometry for B");
|
||||
reused
|
||||
});
|
||||
let mut faces = vec![];
|
||||
for doc in [&a, &b] {
|
||||
doc.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
faces.extend(FontDb::global().file_faces(t).into_iter().flatten().map(|face| Arc::downgrade(&face)));
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(faces.len(), 2);
|
||||
drop(a);
|
||||
drop(b);
|
||||
assert!(!renderer.texts.is_empty(), "the idle renderer still holds its old text nodes");
|
||||
assert!(faces.iter().all(|face| face.upgrade().is_none()), "geometry-cache nodes must not pin document font allowance");
|
||||
}
|
||||
|
||||
/// Type with raster effects redraws in a font that becomes available: its drop shadow and its
|
||||
/// blurred content are made again.
|
||||
#[test]
|
||||
|
||||
@@ -166,18 +166,22 @@ pub(crate) fn text_geom_snapped(t: &TextObject, snap: Option<Affine>) -> TextGeo
|
||||
_ => spans.push((run, start, end)),
|
||||
}
|
||||
};
|
||||
// Per run: is its family missing, and the face its glyphs should come from.
|
||||
// Per run: is its family missing, and the face its glyphs should come from. A run drawn in a
|
||||
// font its file carried isn't substituted: its glyphs come from that font.
|
||||
let file = db.file_faces(t);
|
||||
let faces: Vec<(bool, Option<u32>)> = t
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| match db.resolve(&r.style.font_family, &r.style.font_style) {
|
||||
.enumerate()
|
||||
.map(|(i, r)| match (file.get(i).and_then(Option::as_ref), db.resolve(&r.style.font_family, &r.style.font_style)) {
|
||||
(Some(f), _) => (false, Some(f.id())),
|
||||
// The version the type names, when it's installed (see `FontDb::face_version`), at its
|
||||
// Variable Font settings (see `FontDb::style_face`).
|
||||
Some((f, m)) => {
|
||||
(None, Some((f, m))) => {
|
||||
let face = db.style_face(&r.style).unwrap_or(f);
|
||||
(m == vectorcraft_text::FontMatch::Missing, Some(face.id()))
|
||||
}
|
||||
None => (true, None),
|
||||
(None, None) => (true, None),
|
||||
})
|
||||
.collect();
|
||||
let (mut substituted_fonts, mut substituted_glyphs, mut alternate_candidates) = (BezPath::new(), BezPath::new(), vec![]);
|
||||
|
||||
@@ -795,7 +795,7 @@ impl Importer {
|
||||
let link = linked.map(|l| l.link.clone());
|
||||
let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str()));
|
||||
self.doc.images.entry(key.clone()).or_insert_with(|| {
|
||||
let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) };
|
||||
let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()), file_font: Default::default() };
|
||||
if link.is_some() && !missing { blob.with_proxy() } else { blob }
|
||||
});
|
||||
let xf = acc * Affine::scale_non_uniform(size.width() as f64 / pw as f64, size.height() as f64 / ph as f64);
|
||||
|
||||
@@ -39,9 +39,13 @@ unicode-normalization = "0.1.26"
|
||||
# Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing
|
||||
# modes) into images: the canvas's renderer, already in the build.
|
||||
vello_cpu = { workspace = true }
|
||||
# Builds a small variable font for tests (`test_fonts`; no font file is committed). MIT OR
|
||||
# Apache-2.0, already in the build through subsetter.
|
||||
write-fonts = { version = "0.48", optional = true }
|
||||
# Builds the fonts files carried for their type (`file_font`: a PDF's embedded fonts, from the
|
||||
# glyphs it drew) and a small variable font for tests (`test_fonts`; no font file is committed).
|
||||
# MIT OR Apache-2.0, already in the build through subsetter.
|
||||
write-fonts = "0.48"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[features]
|
||||
default = ["bundled-fonts"]
|
||||
@@ -52,10 +56,7 @@ default = ["bundled-fonts"]
|
||||
# vectorcraft-ui-egui and vectorcraft-mcp by default through the engine.
|
||||
bundled-fonts = []
|
||||
# `vectorcraft_text::test_fonts` for other crates' tests (dev-dependencies only).
|
||||
test-fonts = ["dep:write-fonts"]
|
||||
|
||||
[dev-dependencies]
|
||||
write-fonts = "0.48"
|
||||
test-fonts = []
|
||||
|
||||
# Fonts registered with Windows outside its font folders ("install as shortcut", installers);
|
||||
# MIT OR Apache-2.0, a safe wrapper of the registry API from the windows-rs project.
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
//! Fonts files carried for type whose fonts aren't available here ([`vectorcraft_doc::FileFonts`]):
|
||||
//! a TrueType font built from the glyphs a file drew, each with the outline and advance the file
|
||||
//! gave it, for the character it shows. Built from outlines, it is the same whatever the file's
|
||||
//! font program was (Type 1, CFF or TrueType, simple or CID-keyed): CFF's cubic curves become
|
||||
//! quadratic ones within a quarter of a thousandth of an em.
|
||||
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
use write_fonts::FontBuilder;
|
||||
use write_fonts::tables::cmap::Cmap;
|
||||
use write_fonts::tables::glyf::{Bbox, GlyfLocaBuilder, Glyph, SimpleGlyph};
|
||||
use write_fonts::tables::head::{Flags, Head, MacStyle};
|
||||
use write_fonts::tables::hhea::Hhea;
|
||||
use write_fonts::tables::hmtx::{Hmtx, LongMetric};
|
||||
use write_fonts::tables::maxp::Maxp;
|
||||
use write_fonts::tables::os2::{Os2, SelectionFlags};
|
||||
use write_fonts::tables::post::Post;
|
||||
use write_fonts::types::{FWord, Fixed, GlyphId, Tag, UfWord, Version16Dot16};
|
||||
|
||||
/// Units per em of the fonts built: two per thousandth of an em, the unit of PDF glyph space, so
|
||||
/// the widths a file gives in whole and half thousandths stay exact.
|
||||
pub const FILE_FONT_UPEM: u16 = 2000;
|
||||
/// Font units per thousandth of an em.
|
||||
const SCALE: f64 = FILE_FONT_UPEM as f64 / 1000.0;
|
||||
/// How far a quadratic curve may stray from the cubic it stands for (font units).
|
||||
const ACCURACY: f64 = 0.5;
|
||||
/// The most glyphs a font is built with: TrueType counts them in 16 bits, `.notdef` included.
|
||||
pub const MAX_FILE_GLYPHS: usize = 65_534;
|
||||
/// The furthest a point may lie from the glyph's origin (font units): further, the glyph is left
|
||||
/// out (its character takes the substitute).
|
||||
const MAX_COORD: f64 = 30_000.0;
|
||||
|
||||
/// A glyph a file drew: the character it shows, its outline (thousandths of an em, y up, as PDF
|
||||
/// glyph space measures) and its advance (thousandths of an em).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FileGlyph {
|
||||
pub ch: char,
|
||||
pub outline: BezPath,
|
||||
pub advance: f64,
|
||||
}
|
||||
|
||||
/// What a font built from a file's glyphs is called and how it is set.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FileFontInfo {
|
||||
pub family: String,
|
||||
pub style: String,
|
||||
/// The PostScript name of the file's font (without a subset's tag).
|
||||
pub postscript: String,
|
||||
/// Ascent and descent (thousandths of an em, the descent below the baseline negative).
|
||||
pub ascent: f64,
|
||||
pub descent: f64,
|
||||
/// The file's font's licence flags (OS/2 `fsType`) when it says; else 4, print and preview,
|
||||
/// which lets an export embed it as the file did.
|
||||
pub fs_type: Option<u16>,
|
||||
}
|
||||
|
||||
/// A TrueType font of `glyphs` (the first glyph of each character; at most [`MAX_FILE_GLYPHS`])
|
||||
/// named and set as `info` says. A glyph whose outline can't be written is left out: its character
|
||||
/// takes the substitute. `None` when no glyph can be written.
|
||||
pub fn build_file_font(info: &FileFontInfo, glyphs: &[FileGlyph]) -> Option<Vec<u8>> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut made: Vec<(char, Glyph, u16)> = vec![];
|
||||
for g in glyphs {
|
||||
if made.len() >= MAX_FILE_GLYPHS {
|
||||
break;
|
||||
}
|
||||
if seen.contains(&g.ch) {
|
||||
continue;
|
||||
}
|
||||
let Some(glyph) = glyph(&g.outline) else { continue };
|
||||
let advance = (g.advance * SCALE).round();
|
||||
let advance = if advance.is_finite() { advance.clamp(0.0, f64::from(u16::MAX)) as u16 } else { 0 };
|
||||
seen.insert(g.ch);
|
||||
made.push((g.ch, glyph, advance));
|
||||
}
|
||||
if made.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let notdef = (Glyph::Empty, FILE_FONT_UPEM / 2);
|
||||
let all = std::iter::once((¬def.0, notdef.1)).chain(made.iter().map(|(_, g, a)| (g, *a)));
|
||||
let mut glyf = GlyfLocaBuilder::new();
|
||||
let mut metrics = vec![];
|
||||
let mut bounds: Option<Bbox> = None;
|
||||
let (mut max_points, mut max_contours) = (0usize, 0usize);
|
||||
let (mut min_lsb, mut min_rsb, mut max_extent, mut max_advance) = (i16::MAX, i16::MAX, i16::MIN, 0u16);
|
||||
for (g, advance) in all {
|
||||
glyf.add_glyph(g).ok()?;
|
||||
let b = match g {
|
||||
Glyph::Simple(s) => {
|
||||
max_points = max_points.max(s.contours.iter().map(|c| c.len()).sum());
|
||||
max_contours = max_contours.max(s.contours.len());
|
||||
Some(s.bbox)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let lsb = b.map_or(0, |b| b.x_min);
|
||||
if let Some(b) = b {
|
||||
bounds = Some(bounds.map_or(b, |u| u.union(b)));
|
||||
min_lsb = min_lsb.min(b.x_min);
|
||||
min_rsb = min_rsb.min((i32::from(advance) - i32::from(b.x_max)).clamp(i16::MIN.into(), i16::MAX.into()) as i16);
|
||||
max_extent = max_extent.max(b.x_max);
|
||||
}
|
||||
max_advance = max_advance.max(advance);
|
||||
metrics.push(LongMetric::new(advance, lsb));
|
||||
}
|
||||
let (glyf, loca, loca_format) = glyf.build();
|
||||
let count = u16::try_from(metrics.len()).ok()?;
|
||||
let bounds = bounds.unwrap_or_default();
|
||||
let units = |v: f64| {
|
||||
let v = (v * SCALE).round();
|
||||
if v.is_finite() { v.clamp(f64::from(i16::MIN), f64::from(i16::MAX)) as i16 } else { 0 }
|
||||
};
|
||||
// A font without them stands on an em from 0.88 up to 0.12 down, as PDF's vertical metrics do.
|
||||
let ascent = if info.ascent > 0.0 { units(info.ascent) } else { units(880.0) };
|
||||
let descent = if info.descent < 0.0 { units(info.descent) } else { units(-120.0) };
|
||||
let bold = info.style.to_ascii_lowercase().contains("bold");
|
||||
let italic = ["italic", "oblique"].iter().any(|s| info.style.to_ascii_lowercase().contains(s));
|
||||
let head = Head {
|
||||
font_revision: Fixed::from_f64(1.0),
|
||||
flags: Flags::from_bits_truncate(0b1011),
|
||||
units_per_em: FILE_FONT_UPEM,
|
||||
x_min: bounds.x_min,
|
||||
y_min: bounds.y_min,
|
||||
x_max: bounds.x_max,
|
||||
y_max: bounds.y_max,
|
||||
mac_style: MacStyle::from_bits_truncate(u16::from(bold) | (u16::from(italic) << 1)),
|
||||
lowest_rec_ppem: 6,
|
||||
index_to_loc_format: loca_format as i16,
|
||||
..Head::default()
|
||||
};
|
||||
let hhea = Hhea {
|
||||
ascender: FWord::new(ascent),
|
||||
descender: FWord::new(descent),
|
||||
line_gap: FWord::new(0),
|
||||
advance_width_max: UfWord::new(max_advance),
|
||||
min_left_side_bearing: FWord::new(if min_lsb == i16::MAX { 0 } else { min_lsb }),
|
||||
min_right_side_bearing: FWord::new(if min_rsb == i16::MAX { 0 } else { min_rsb }),
|
||||
x_max_extent: FWord::new(if max_extent == i16::MIN { 0 } else { max_extent }),
|
||||
caret_slope_rise: 1,
|
||||
caret_slope_run: 0,
|
||||
caret_offset: 0,
|
||||
number_of_h_metrics: count,
|
||||
};
|
||||
let maxp = Maxp {
|
||||
num_glyphs: count,
|
||||
max_points: Some(u16::try_from(max_points).unwrap_or(u16::MAX)),
|
||||
max_contours: Some(u16::try_from(max_contours).unwrap_or(u16::MAX)),
|
||||
max_composite_points: Some(0),
|
||||
max_composite_contours: Some(0),
|
||||
max_zones: Some(1),
|
||||
max_twilight_points: Some(0),
|
||||
max_storage: Some(0),
|
||||
max_function_defs: Some(0),
|
||||
max_instruction_defs: Some(0),
|
||||
max_stack_elements: Some(0),
|
||||
max_size_of_instructions: Some(0),
|
||||
max_component_elements: Some(0),
|
||||
max_component_depth: Some(0),
|
||||
};
|
||||
let chars: Vec<u32> = made.iter().map(|(c, ..)| u32::from(*c)).collect();
|
||||
let first = chars.iter().copied().min().unwrap_or(0).min(0xffff) as u16;
|
||||
let last = chars.iter().copied().max().unwrap_or(0).min(0xffff) as u16;
|
||||
let advances: Vec<u32> = metrics.iter().skip(1).map(|m| u32::from(m.advance)).filter(|a| *a > 0).collect();
|
||||
let avg = advances.iter().sum::<u32>().checked_div(advances.len() as u32).unwrap_or(0);
|
||||
let selection = if bold || italic {
|
||||
u16::from(italic) | (u16::from(bold) << 5)
|
||||
} else {
|
||||
// Regular, and the typographic ascent and descent are the line's.
|
||||
0x40 | 0x80
|
||||
};
|
||||
let os2 = Os2 {
|
||||
x_avg_char_width: i16::try_from(avg).unwrap_or(i16::MAX),
|
||||
us_weight_class: if bold { 700 } else { 400 },
|
||||
us_width_class: 5,
|
||||
fs_type: info.fs_type.unwrap_or(4),
|
||||
y_strikeout_size: units(50.0),
|
||||
y_strikeout_position: units(250.0),
|
||||
ach_vend_id: Tag::new(b"NONE"),
|
||||
fs_selection: SelectionFlags::from_bits_truncate(selection),
|
||||
us_first_char_index: first,
|
||||
us_last_char_index: last,
|
||||
s_typo_ascender: ascent,
|
||||
s_typo_descender: descent,
|
||||
s_typo_line_gap: 0,
|
||||
us_win_ascent: u16::try_from(ascent.max(bounds.y_max)).unwrap_or(0),
|
||||
us_win_descent: u16::try_from(-i32::from(descent.min(bounds.y_min))).unwrap_or(0),
|
||||
ul_code_page_range_1: Some(0),
|
||||
ul_code_page_range_2: Some(0),
|
||||
sx_height: Some(0),
|
||||
s_cap_height: Some(0),
|
||||
us_default_char: Some(0),
|
||||
us_break_char: Some(32),
|
||||
us_max_context: Some(1),
|
||||
..Os2::default()
|
||||
};
|
||||
let post = Post {
|
||||
version: Version16Dot16::VERSION_3_0,
|
||||
underline_position: FWord::new(units(-75.0)),
|
||||
underline_thickness: FWord::new(units(50.0)),
|
||||
..Post::default()
|
||||
};
|
||||
let cmap = Cmap::from_mappings(made.iter().enumerate().map(|(i, (c, ..))| (*c, GlyphId::new(i as u32 + 1)))).ok()?;
|
||||
let hmtx = Hmtx::new(metrics, vec![]);
|
||||
let full = if info.style.is_empty() { info.family.clone() } else { format!("{} {}", info.family, info.style) };
|
||||
let name = name_table(&[(1, &info.family), (2, &info.style), (4, &full), (5, "Version 1.0"), (6, &postscript_name(&info.postscript))])?;
|
||||
let mut b = FontBuilder::new();
|
||||
b.add_table(&head).ok()?;
|
||||
b.add_table(&hhea).ok()?;
|
||||
b.add_table(&maxp).ok()?;
|
||||
b.add_table(&os2).ok()?;
|
||||
b.add_table(&hmtx).ok()?;
|
||||
b.add_table(&cmap).ok()?;
|
||||
b.add_table(&post).ok()?;
|
||||
b.add_table(&glyf).ok()?;
|
||||
b.add_table(&loca).ok()?;
|
||||
b.add_raw(Tag::new(b"name"), name);
|
||||
Some(b.build())
|
||||
}
|
||||
|
||||
/// The largest coordinate of a glyph outline read from a file, in the file's units (thousandths of
|
||||
/// an em). Far past any glyph; a curve control point beyond it leaves the glyph out.
|
||||
const MAX_INPUT: f64 = 1e6;
|
||||
|
||||
/// `outline` (thousandths of an em, y up) as a TrueType glyph in font units: its cubic curves as
|
||||
/// quadratic ones, its contours that draw nothing (a lone point) left out. `Glyph::Empty` for a
|
||||
/// glyph without ink (a space); `None` when it can't be written (points that aren't numbers or lie
|
||||
/// too far out, a malformed path).
|
||||
fn glyph(outline: &BezPath) -> Option<Glyph> {
|
||||
let at = |p: kurbo::Point| kurbo::Point::new(p.x * SCALE, p.y * SCALE);
|
||||
let mut out = BezPath::new();
|
||||
// The contour being read: its start, and its drawing commands (font units).
|
||||
let mut contour: Option<(kurbo::Point, Vec<PathEl>)> = None;
|
||||
let mut last = kurbo::Point::ZERO;
|
||||
let flush = |c: Option<(kurbo::Point, Vec<PathEl>)>, out: &mut BezPath| {
|
||||
if let Some((start, els)) = c.filter(|(_, els)| !els.is_empty()) {
|
||||
out.move_to(start);
|
||||
for e in els {
|
||||
out.push(e);
|
||||
}
|
||||
out.close_path();
|
||||
}
|
||||
};
|
||||
// A point that isn't a number can't be written (nor bounded: `min`/`max` skip NaN), and one
|
||||
// far outside any glyph would make the curve subdivision below enormous.
|
||||
let sane = |p: kurbo::Point| p.is_finite() && p.x.abs() <= MAX_INPUT && p.y.abs() <= MAX_INPUT;
|
||||
let finite = |el: &PathEl| match *el {
|
||||
PathEl::MoveTo(p) | PathEl::LineTo(p) => sane(p),
|
||||
PathEl::QuadTo(a, p) => sane(a) && sane(p),
|
||||
PathEl::CurveTo(a, b, p) => sane(a) && sane(b) && sane(p),
|
||||
PathEl::ClosePath => true,
|
||||
};
|
||||
if !outline.elements().iter().all(finite) {
|
||||
return None;
|
||||
}
|
||||
for el in outline.elements() {
|
||||
let p = match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(contour.take(), &mut out);
|
||||
last = at(p);
|
||||
contour = Some((last, vec![]));
|
||||
continue;
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let Some((start, _)) = &contour {
|
||||
last = *start;
|
||||
}
|
||||
flush(contour.take(), &mut out);
|
||||
continue;
|
||||
}
|
||||
PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => at(p),
|
||||
};
|
||||
// A drawing command without a move goes on from where the pen is.
|
||||
let (_, els) = contour.get_or_insert((last, vec![]));
|
||||
match *el {
|
||||
PathEl::QuadTo(c, _) => els.push(PathEl::QuadTo(at(c), p)),
|
||||
PathEl::CurveTo(c1, c2, _) => {
|
||||
let cubic = kurbo::CubicBez::new(last, at(c1), at(c2), p);
|
||||
els.extend(cubic.to_quads(ACCURACY).map(|(.., q)| PathEl::QuadTo(q.p1, q.p2)));
|
||||
}
|
||||
_ => els.push(PathEl::LineTo(p)),
|
||||
}
|
||||
last = p;
|
||||
}
|
||||
flush(contour.take(), &mut out);
|
||||
if out.elements().is_empty() {
|
||||
return Some(Glyph::Empty);
|
||||
}
|
||||
let b = out.bounding_box();
|
||||
if !(b.is_finite() && b.x0 > -MAX_COORD && b.y0 > -MAX_COORD && b.x1 < MAX_COORD && b.y1 < MAX_COORD) {
|
||||
return None;
|
||||
}
|
||||
SimpleGlyph::from_bezpath(&out).ok().map(Glyph::Simple)
|
||||
}
|
||||
|
||||
/// `name` as a PostScript name: printable ASCII other than the characters PostScript reserves, at
|
||||
/// most 63 of them ("Font" when none is left).
|
||||
fn postscript_name(name: &str) -> String {
|
||||
let s: String = name.chars().filter(|c| c.is_ascii_graphic() && !"[](){}<>/%".contains(*c)).take(63).collect();
|
||||
if s.is_empty() { "Font".to_string() } else { s }
|
||||
}
|
||||
|
||||
/// A `name` table of Windows English (US) records (name id, string).
|
||||
pub(crate) fn name_table(records: &[(u16, &str)]) -> Option<Vec<u8>> {
|
||||
let mut records = records.to_vec();
|
||||
records.sort_by_key(|r| r.0);
|
||||
let n = u16::try_from(records.len()).ok()?;
|
||||
let (mut head, mut strings) = (Vec::new(), Vec::new());
|
||||
for v in [0, n, 6 + 12 * n] {
|
||||
head.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
for (id, s) in records {
|
||||
let bytes: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
for v in [3, 1, 0x0409, id, u16::try_from(bytes.len()).ok()?, u16::try_from(strings.len()).ok()?] {
|
||||
head.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
strings.extend(bytes);
|
||||
}
|
||||
head.extend(strings);
|
||||
Some(head)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use kurbo::{Affine, Rect};
|
||||
use skrifa::MetadataProvider;
|
||||
|
||||
use super::*;
|
||||
use crate::FontDb;
|
||||
|
||||
/// Source Serif 4's glyphs of `text` as a PDF draws them (thousandths of an em, y up).
|
||||
fn glyphs(text: &str) -> Vec<FileGlyph> {
|
||||
let db = FontDb::global();
|
||||
let face = db.face("Source Serif 4", "Regular").unwrap();
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
text.chars()
|
||||
.map(|ch| {
|
||||
let gid = face.glyph_for(ch);
|
||||
// The database's outlines run y down.
|
||||
let outline = Affine::scale_non_uniform(k, -k) * db.outline(&face, gid).as_ref().clone();
|
||||
FileGlyph { ch, outline, advance: face.advance(gid) * k }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn info() -> FileFontInfo {
|
||||
FileFontInfo { family: "Kept Serif".into(), style: "Regular".into(), postscript: "KeptSerif-Regular".into(), ..Default::default() }
|
||||
}
|
||||
|
||||
fn near(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
(a.x0 - b.x0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.y1 - b.y1).abs() < tol
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_font_built_from_a_files_glyphs_draws_them_with_their_widths() {
|
||||
let from = glyphs("Hamburg é&Q ");
|
||||
let bytes = build_file_font(&info(), &from).unwrap();
|
||||
let font = skrifa::FontRef::new(&bytes).unwrap();
|
||||
assert_eq!(font.metrics(skrifa::instance::Size::unscaled(), skrifa::instance::LocationRef::default()).units_per_em, FILE_FONT_UPEM);
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap();
|
||||
assert_eq!((face.family.as_str(), face.style.as_str()), ("Kept Serif", "Regular"));
|
||||
assert_eq!(face.postscript_name(), "KeptSerif-Regular");
|
||||
// Kept apart: no family name finds it.
|
||||
assert!(!db.has_family("Kept Serif"));
|
||||
let k = 1000.0 / face.units_per_em();
|
||||
for g in &from {
|
||||
let gid = face.glyph_for(g.ch);
|
||||
assert_ne!(gid, 0, "{}", g.ch);
|
||||
assert!((face.advance(gid) * k - g.advance).abs() < 0.5, "{}: the file's width", g.ch);
|
||||
let drawn = Affine::scale_non_uniform(k, -k) * db.outline(&face, gid).as_ref().clone();
|
||||
if g.outline.elements().is_empty() {
|
||||
assert!(drawn.elements().is_empty());
|
||||
} else {
|
||||
assert!(
|
||||
near(drawn.bounding_box(), g.outline.bounding_box(), 0.6),
|
||||
"{}: {:?} vs {:?}",
|
||||
g.ch,
|
||||
drawn.bounding_box(),
|
||||
g.outline.bounding_box()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's font's licence flags travel with the font built from its glyphs, so an export
|
||||
/// treats it as the file's font was treated (#4568): a restricted licence keeps its outlines
|
||||
/// out of an SVG's `@font-face`, a missing one reads as print and preview, which may embed.
|
||||
#[test]
|
||||
fn a_file_fonts_licence_flags_carry_over_to_the_font_built_from_it() {
|
||||
use crate::embed::Embedding;
|
||||
let from = glyphs("Hamburg");
|
||||
for (fs_type, want) in [
|
||||
(Some(2), Embedding::Forbidden),
|
||||
(Some(0x0200), Embedding::Forbidden),
|
||||
(Some(4), Embedding::Subset),
|
||||
(Some(0x0108), Embedding::Whole),
|
||||
(None, Embedding::Subset),
|
||||
] {
|
||||
let bytes = build_file_font(&FileFontInfo { fs_type, ..info() }, &from).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap();
|
||||
assert_eq!(face.embedding(), want, "fsType {fs_type:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve whose control point is absurdly far out is left out before it is subdivided
|
||||
/// (CodeRabbit, #4569); a glyph of ordinary size still builds.
|
||||
#[test]
|
||||
fn a_curve_with_an_absurd_control_point_is_left_out() {
|
||||
let mut from = glyphs("a");
|
||||
let mut wild = BezPath::new();
|
||||
wild.move_to((0.0, 0.0));
|
||||
wild.curve_to((1e12, 0.0), (0.0, 1e12), (10.0, 10.0));
|
||||
wild.line_to((10.0, 0.0));
|
||||
wild.close_path();
|
||||
from.push(FileGlyph { ch: 'w', outline: wild, advance: 500.0 });
|
||||
let bytes = build_file_font(&info(), &from).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let face = db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, bytes)).unwrap();
|
||||
assert_ne!(face.glyph_for('a'), 0);
|
||||
assert_eq!(face.glyph_for('w'), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glyphs_that_cannot_be_written_are_left_out() {
|
||||
let mut from = glyphs("ab");
|
||||
// A second glyph for `a`: the first is kept.
|
||||
from.push(FileGlyph { ch: 'a', outline: glyphs("x").remove(0).outline, advance: 999.0 });
|
||||
let mut nan = BezPath::new();
|
||||
nan.move_to((0.0, 0.0));
|
||||
nan.line_to((f64::NAN, 10.0));
|
||||
nan.line_to((10.0, 10.0));
|
||||
from.push(FileGlyph { ch: 'c', outline: nan, advance: 500.0 });
|
||||
let mut far = BezPath::new();
|
||||
far.move_to((0.0, 0.0));
|
||||
far.line_to((1e9, 0.0));
|
||||
far.line_to((0.0, 10.0));
|
||||
from.push(FileGlyph { ch: 'd', outline: far, advance: 500.0 });
|
||||
// A lone point draws nothing; an advance that isn't a number is none.
|
||||
let mut dot = BezPath::new();
|
||||
dot.move_to((5.0, 5.0));
|
||||
from.push(FileGlyph { ch: 'e', outline: dot, advance: f64::NAN });
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let blob = vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, build_file_font(&info(), &from).unwrap());
|
||||
let face = db.keep_file_font(&blob).unwrap();
|
||||
assert!(face.covers('a') && face.covers('b') && face.covers('e'));
|
||||
assert!(!face.covers('c') && !face.covers('d'));
|
||||
assert!((face.advance(face.glyph_for('a')) - from[0].advance * 2.0).abs() < 1.0, "the first glyph of a character");
|
||||
assert_eq!(face.advance(face.glyph_for('e')), 0.0);
|
||||
assert!(db.outline(&face, face.glyph_for('e')).elements().is_empty());
|
||||
assert!(build_file_font(&info(), &[]).is_none());
|
||||
// Bytes that aren't a font are kept by no one.
|
||||
assert!(db.keep_file_font(&vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, b"not a font".to_vec())).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_negative_descent_does_not_overflow() {
|
||||
let mut i = info();
|
||||
i.descent = -100_000.0;
|
||||
let bytes = build_file_font(&i, &glyphs("a"));
|
||||
assert!(bytes.is_some());
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,18 @@ pub use traits::{FontClass, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIE
|
||||
pub(crate) use traits::{alias_lists, face_styles, on_faces_published};
|
||||
pub use wanted::{WantedFont, WantedFonts};
|
||||
|
||||
/// Weak indexes of live file-font resources, by content hash (collisions checked by bytes) and id.
|
||||
#[derive(Default)]
|
||||
pub(super) struct FileFaces {
|
||||
pub(super) by_key: HashMap<String, Vec<std::sync::Weak<FontFace>>>,
|
||||
pub(super) by_id: HashMap<u32, std::sync::Weak<FontFace>>,
|
||||
/// Only each admitted face's own byte allocation, never an unbounded list of alias owners.
|
||||
pub(super) by_blob: HashMap<usize, std::sync::Weak<FontFace>>,
|
||||
}
|
||||
|
||||
/// How many live fonts files carried the database admits at most (each shares its document's bytes).
|
||||
pub const MAX_FILE_FACES: usize = 4096;
|
||||
|
||||
/// Process-wide font database.
|
||||
pub struct FontDb {
|
||||
faces: RwLock<Vec<Arc<FontFace>>>,
|
||||
@@ -87,6 +99,9 @@ pub struct FontDb {
|
||||
images: Mutex<GlyphImages>,
|
||||
colours: Mutex<GlyphColours>,
|
||||
catalog: RwLock<Catalog>,
|
||||
/// Fonts files carried for their type ([`vectorcraft_doc::FileFonts`]): apart from the faces,
|
||||
/// so no family name, font menu, fallback or PostScript name lookup finds them.
|
||||
pub(super) file_faces: RwLock<FileFaces>,
|
||||
/// The installed faces by PostScript name (documents name fonts so: PDF, EPS, .ai).
|
||||
postscript: RwLock<PostScriptNames>,
|
||||
/// Where the system font scan looks.
|
||||
|
||||
@@ -395,8 +395,11 @@ impl FontDb {
|
||||
if !self.lends() && self.composites.read().unwrap_or_else(|e| e.into_inner()).is_empty() {
|
||||
return None;
|
||||
}
|
||||
let fonts: Vec<Option<Arc<CompositeFont>>> =
|
||||
t.runs.iter().map(|r| if r.inline.is_some() { None } else { self.composite_font(&r.style.font_family) }).collect();
|
||||
let fonts: Vec<Option<Arc<CompositeFont>>> = t
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| if r.inline.is_some() || r.style.file_font_id.is_some() { None } else { self.composite_font(&r.style.font_family) })
|
||||
.collect();
|
||||
if fonts.iter().all(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -56,6 +56,7 @@ impl FontDb {
|
||||
images: Mutex::new(GlyphCache::default()),
|
||||
colours: Mutex::new(GlyphCache::default()),
|
||||
catalog: RwLock::new(Catalog::new()),
|
||||
file_faces: RwLock::new(super::FileFaces::default()),
|
||||
postscript: RwLock::new(PostScriptNames::new()),
|
||||
font_paths,
|
||||
aliases: RwLock::new(HashMap::new()),
|
||||
|
||||
@@ -212,6 +212,16 @@ pub struct FontFace {
|
||||
pub(super) named_chars: std::sync::OnceLock<std::collections::HashMap<String, char>>,
|
||||
}
|
||||
|
||||
impl vectorcraft_doc::FileFontFace for FontFace {
|
||||
fn id(&self) -> u32 {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn bytes(&self) -> &[u8] {
|
||||
self.data()
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the ideographic character face (ICF) lies inside the ideographic em box: its distance
|
||||
/// from each edge of the em box, in ems. `top` and `bottom` along a horizontal line, `right` and
|
||||
/// `left` across a vertical one.
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
use super::*;
|
||||
use crate::{FileFontInfo, FileGlyph, build_file_font, layout};
|
||||
use kurbo::{Point, Rect, Shape};
|
||||
use vectorcraft_doc::{CharStyle, Document, FILE_FONT_MIME, FileFont, FileFonts, ImageBlob, Node, NodeId, NodeKind, TextObject};
|
||||
|
||||
const FAMILY: &str = "Owned File Font Regression";
|
||||
|
||||
fn blob(width: f64) -> ImageBlob {
|
||||
let glyph = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, width, 700.0).to_path(0.1), advance: width + 100.0 };
|
||||
let info = FileFontInfo { family: FAMILY.into(), style: "Regular".into(), ..Default::default() };
|
||||
ImageBlob::new(FILE_FONT_MIME, build_file_font(&info, &[glyph]).unwrap())
|
||||
}
|
||||
|
||||
fn text(key: &str) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, "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: key.into() }], "x")));
|
||||
t
|
||||
}
|
||||
|
||||
fn document(key: &str, blob: ImageBlob) -> Document {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
doc.images.insert(key.into(), blob);
|
||||
doc.layers.push(Arc::new(Node::new(NodeId(100), NodeKind::Text(Box::new(text(key))))));
|
||||
doc
|
||||
}
|
||||
|
||||
fn first_text(doc: &Document) -> &TextObject {
|
||||
let NodeKind::Text(t) = &doc.layers.last().unwrap().kind else { panic!("text") };
|
||||
t
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chosen_keys_cannot_replace_another_documents_owned_font() {
|
||||
for reverse in [false, true] {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let (a, b) = (blob(200.0), blob(800.0));
|
||||
// A chooses the exact key an honest B derives from its different bytes.
|
||||
let key = b.content_key();
|
||||
let (mut da, mut dbb) = (document(&key, a.clone()), document(&key, b.clone()));
|
||||
let (first, second) = if reverse { (&mut dbb, &mut da) } else { (&mut da, &mut dbb) };
|
||||
assert!(db.bind_document_file_fonts(first).is_empty());
|
||||
assert!(db.bind_document_file_fonts(second).is_empty());
|
||||
for (doc, owned) in [(&da, &a), (&dbb, &b)] {
|
||||
let laid = layout(&db, first_text(doc));
|
||||
assert_eq!(laid.glyphs.len(), 1);
|
||||
let face = db.face_by_id(laid.glyphs[0].font_id).unwrap();
|
||||
assert_eq!(face.file_data(), owned.bytes.as_slice());
|
||||
}
|
||||
assert!(layout(&db, first_text(&dbb)).bounds.width() > layout(&db, first_text(&da)).bounds.width() * 2.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_and_forged_internal_family_do_not_authorize_global_faces() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let owned = blob(500.0);
|
||||
let face = db.keep_file_font(&owned).unwrap();
|
||||
let id = face.id();
|
||||
let mut missing = text(&owned.content_key());
|
||||
assert!(!db.bind_file_fonts(&mut missing, |_| None));
|
||||
assert!(db.file_faces(&missing).is_empty());
|
||||
assert!(layout(&db, &missing).glyphs.iter().all(|g| g.font_id != id));
|
||||
|
||||
let mut json = serde_json::to_value(CharStyle::default()).unwrap();
|
||||
json["font_family"] = format!("\u{1}file font {id}").into();
|
||||
json["file_font_id"] = id.into();
|
||||
let forged: CharStyle = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(forged.file_font_id, None);
|
||||
assert!(db.style_face(&forged).is_none_or(|face| face.id() != id));
|
||||
let forged = TextObject::point(Point::ZERO, "x", forged);
|
||||
assert!(layout(&db, &forged).glyphs.iter().all(|g| g.font_id != id));
|
||||
|
||||
let mut owned_text = text("chosen");
|
||||
assert!(db.bind_file_fonts(&mut owned_text, |_| Some(&owned)));
|
||||
let serialized = serde_json::to_string(&owned_text).unwrap();
|
||||
let unowned: TextObject = serde_json::from_str(&serialized).unwrap();
|
||||
assert!(db.file_faces(&unowned).is_empty(), "runtime authorization never travels as metadata");
|
||||
let mut invalid = document("chosen", ImageBlob::new(FILE_FONT_MIME, b"not a font".to_vec()));
|
||||
let warnings = db.bind_document_file_fonts(&mut invalid);
|
||||
assert!(warnings.iter().any(|w| w.contains(FAMILY) && w.contains("substitute")));
|
||||
assert!(db.file_faces(first_text(&invalid)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_fonts_referenced_by_active_runs_consume_allowance() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
for i in 0..32 {
|
||||
doc.images.insert(format!("unused-{i}"), blob(100.0 + f64::from(i)));
|
||||
}
|
||||
let mut unused_reference = text("unused-0");
|
||||
unused_reference.runs[0].style.font_family = "Another Missing Family".into();
|
||||
doc.layers.push(Arc::new(Node::new(NodeId(100), NodeKind::Text(Box::new(unused_reference)))));
|
||||
assert!(db.bind_document_file_fonts(&mut doc).is_empty());
|
||||
assert!(db.read_file_faces().by_id.is_empty());
|
||||
let wanted = blob(900.0);
|
||||
let face = db.keep_file_font_up_to(&wanted, 1).unwrap();
|
||||
assert_eq!(face.file_data(), wanted.bytes.as_slice());
|
||||
assert_eq!(db.read_file_faces().by_id.len(), 1);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn removing_an_installed_exact_face_uses_the_owned_snapshot_fallback() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-file-font-{}-installed-fallback", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let installed_path = dir.join("Installed.ttf");
|
||||
std::fs::write(&installed_path, blob(800.0).bytes.as_slice()).unwrap();
|
||||
let db = FontDb::with_font_dirs(vec![dir.clone()]);
|
||||
db.set_system_fallback(false);
|
||||
let installed_id = {
|
||||
let (face, matched) = db.resolve(FAMILY, "Regular").unwrap();
|
||||
assert_eq!(matched, super::super::traits::FontMatch::Exact);
|
||||
face.id()
|
||||
};
|
||||
let mut doc = document("carried", blob(200.0));
|
||||
assert!(db.bind_document_file_fonts(&mut doc).is_empty());
|
||||
assert!(db.file_faces(first_text(&doc)).is_empty(), "the installed exact face still wins");
|
||||
assert_eq!(layout(&db, first_text(&doc)).glyphs[0].font_id, installed_id);
|
||||
assert_eq!(db.read_file_faces().by_id.len(), 1, "the referenced carried resource is admitted while dormant");
|
||||
let (carried_id, weak) = {
|
||||
let face = first_text(&doc).file_fonts.as_ref().unwrap().face("carried").unwrap();
|
||||
assert_ne!(face.id(), installed_id);
|
||||
assert_eq!(face.bytes(), doc.images["carried"].bytes.as_slice());
|
||||
(face.id(), Arc::downgrade(&face))
|
||||
};
|
||||
let undo = doc.clone();
|
||||
let resource = doc.images["carried"].clone();
|
||||
let cached_text = first_text(&doc).clone();
|
||||
let replacement = blob(900.0);
|
||||
assert!(db.keep_file_font_up_to(&replacement, 1).is_none(), "dormant owned resources count toward the live allowance");
|
||||
|
||||
std::fs::remove_file(&installed_path).unwrap();
|
||||
std::fs::remove_dir(&dir).unwrap();
|
||||
assert_eq!(db.load_system_fonts(), 0);
|
||||
assert!(db.face_by_id(installed_id).is_none());
|
||||
for retained in [&doc, &undo] {
|
||||
assert_eq!(layout(&db, first_text(retained)).glyphs[0].font_id, carried_id, "removal needs no reopen or rebind");
|
||||
}
|
||||
|
||||
doc.images.clear();
|
||||
assert!(!db.bind_document_file_fonts(&mut doc).is_empty());
|
||||
assert!(db.file_faces(first_text(&doc)).is_empty());
|
||||
drop(doc);
|
||||
assert_eq!(layout(&db, first_text(&undo)).glyphs[0].font_id, carried_id, "current-document rebinding cannot revoke Undo ownership");
|
||||
drop(undo);
|
||||
assert_eq!(layout(&db, &cached_text).glyphs[0].font_id, carried_id, "a resource snapshot still owns the carried face");
|
||||
assert!(db.keep_file_font_up_to(&replacement, 1).is_none());
|
||||
drop(resource);
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(db.face_by_id(carried_id).is_none());
|
||||
assert!(db.file_faces(&cached_text).is_empty(), "text bindings alone do not own admission");
|
||||
assert!(db.keep_file_font_up_to(&replacement, 1).is_some(), "closing the last resource owner releases allowance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_snapshots_and_inflight_faces_keep_only_live_allowance() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let (a, b) = (blob(200.0), blob(800.0));
|
||||
let mut doc = document("k", a.clone());
|
||||
assert!(db.bind_document_file_fonts(&mut doc).is_empty());
|
||||
let original = layout(&db, first_text(&doc));
|
||||
let id = original.glyphs[0].font_id;
|
||||
let inflight = db.face_by_id(id).unwrap();
|
||||
let weak = Arc::downgrade(&inflight);
|
||||
let open_document = Arc::new(doc);
|
||||
let undo_or_copy = open_document.clone();
|
||||
let resource_copy = (*open_document).clone();
|
||||
let cached_node = open_document.layers.last().unwrap().clone();
|
||||
let cached_text = first_text(&open_document).clone();
|
||||
let before_expiry = cached_text.clone();
|
||||
assert!(db.keep_file_font_up_to(&b, 1).is_none());
|
||||
// Identical content may share a live face even while the allowance is full.
|
||||
assert_eq!(db.keep_file_font_up_to(&a, 1).unwrap().id(), id);
|
||||
drop(open_document);
|
||||
assert_eq!(layout(&db, first_text(&undo_or_copy)).glyphs[0].font_id, id);
|
||||
assert!(db.keep_file_font_up_to(&b, 1).is_none());
|
||||
drop(undo_or_copy);
|
||||
assert!(db.keep_file_font_up_to(&b, 1).is_none(), "a copied document owns its image resources too");
|
||||
drop(resource_copy);
|
||||
drop(a);
|
||||
assert!(db.keep_file_font_up_to(&b, 1).is_none(), "an in-flight font Arc still owns its slot");
|
||||
drop(inflight);
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(db.face_by_id(id).is_none());
|
||||
assert_eq!(cached_text, before_expiry, "weak expiry must not change cache identity");
|
||||
assert!(db.file_faces(&cached_text).is_empty());
|
||||
let NodeKind::Text(cached) = &cached_node.kind else { panic!("text") };
|
||||
assert!(db.file_faces(cached).is_empty(), "a cached node is not a resource owner");
|
||||
let recovered = db.keep_file_font_up_to(&b, 1).unwrap();
|
||||
assert_eq!(recovered.file_data(), b.bytes.as_slice());
|
||||
assert_eq!(db.read_file_faces().by_id.len(), 1, "dead slots were reaped, not accumulated");
|
||||
assert_eq!(db.read_file_faces().by_key.len(), 1);
|
||||
assert_eq!(db.read_file_faces().by_blob.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloned_and_mutated_blobs_cannot_reuse_an_old_runtime_face() {
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let (a, b) = (blob(200.0), blob(800.0));
|
||||
let first = db.keep_file_font(&a).unwrap();
|
||||
let mut changed = a.clone();
|
||||
assert_eq!(changed, a, "runtime ownership does not change blob equality");
|
||||
changed.bytes = b.bytes.clone();
|
||||
// Cloning must not propagate a stale lease after public bytes were replaced.
|
||||
let copied = changed.clone();
|
||||
assert!(copied.file_font.lock().unwrap().is_none());
|
||||
assert!(changed.file_font.lock().unwrap().is_none());
|
||||
let second = db.keep_file_font(&copied).unwrap();
|
||||
assert_ne!(first.id(), second.id());
|
||||
assert_eq!(second.file_data(), b.bytes.as_slice());
|
||||
assert_eq!(first.file_data(), a.bytes.as_slice());
|
||||
let mut invalid = copied.clone();
|
||||
invalid.bytes = Arc::new(b"invalid replacement".to_vec());
|
||||
assert!(db.keep_file_font(&invalid).is_none());
|
||||
assert!(invalid.file_font.lock().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_font_height_references_measure_the_owned_face() {
|
||||
use vectorcraft_doc::FontHeightReference;
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
let owned = ImageBlob::new(FILE_FONT_MIME, crate::test_fonts::height_font(true).expect("the fixture has explicit OS/2 heights"));
|
||||
let mut t = text("k");
|
||||
assert!(db.bind_file_fonts(&mut t, |_| Some(&owned)));
|
||||
let face = db.file_faces(&t)[0].clone().unwrap();
|
||||
let height = face.font_height(FontHeightReference::CapHeight, false).unwrap();
|
||||
t.runs[0].style.font_height_reference = FontHeightReference::CapHeight;
|
||||
let mut em = t.clone();
|
||||
em.runs[0].style.font_height_reference = FontHeightReference::EmBox;
|
||||
em.runs[0].style.size /= height;
|
||||
assert!((layout(&db, &t).bounds.width() - layout(&db, &em).bounds.width()).abs() < 1e-6);
|
||||
assert_eq!(t.runs[0].style.file_font_id, None, "internal layout ids never enter source runs");
|
||||
}
|
||||
@@ -12,6 +12,12 @@ use super::scan::{enumerate_faces, font_files};
|
||||
use super::traits::{Alias, FontMatch, FontTraits, regular_rank};
|
||||
use super::{Arc, BezPath, CANONICAL_CACHE_MAX, Color, ColourContent, FontDb, GlyphImage, MetadataProvider, NEXT_ID, OUTLINE_CACHE_MAX, Ordering};
|
||||
|
||||
fn has_file_fonts(n: &vectorcraft_doc::Node) -> bool {
|
||||
matches!(&n.kind, vectorcraft_doc::NodeKind::Text(t) if t.file_fonts.is_some())
|
||||
|| n.extras().mask.as_ref().is_some_and(|mask| has_file_fonts(&mask.art))
|
||||
|| n.children().is_some_and(|children| children.iter().any(|child| has_file_fonts(child)))
|
||||
}
|
||||
|
||||
/// The most faces [`FontDb::postscript_faces`] gives, and the most families it loads.
|
||||
const MAX_POSTSCRIPT_FACES: usize = 16;
|
||||
|
||||
@@ -362,7 +368,7 @@ impl FontDb {
|
||||
/// instanced face ([`Self::instance`]) included.
|
||||
pub fn face_by_id(&self, id: u32) -> Option<Arc<FontFace>> {
|
||||
let loaded = self.read_faces().iter().find(|f| f.id == id).cloned();
|
||||
loaded.or_else(|| self.instance_by_id(id))
|
||||
loaded.or_else(|| self.instance_by_id(id)).or_else(|| self.read_file_faces().by_id.get(&id).and_then(std::sync::Weak::upgrade))
|
||||
}
|
||||
|
||||
/// The faces loaded so far (the bundled fonts and the installed ones type has used), in load
|
||||
@@ -374,6 +380,11 @@ impl FontDb {
|
||||
/// The face of character style `st`: [`Self::face_version`] of its font, instanced at its
|
||||
/// Variable Font settings ([`Self::instance`]).
|
||||
pub fn style_face(&self, st: &vectorcraft_doc::CharStyle) -> Option<Arc<FontFace>> {
|
||||
if let Some(id) = st.file_font_id
|
||||
&& let Some(face) = self.read_file_faces().by_id.get(&id).and_then(std::sync::Weak::upgrade)
|
||||
{
|
||||
return Some(face);
|
||||
}
|
||||
let face = self.face_version(&st.font_family, &st.font_style, st.font_version.as_deref())?;
|
||||
Some(self.instance(&face, &st.font_axes))
|
||||
}
|
||||
@@ -729,8 +740,210 @@ impl FontDb {
|
||||
self.colours.lock().unwrap_or_else(std::sync::PoisonError::into_inner).keep(key, content.clone());
|
||||
content
|
||||
}
|
||||
|
||||
/// Admit a font resource, sharing its bytes. Its blob and returned face own the admission.
|
||||
/// Invalid fonts and the live-face cap return `None`; document keys are never identities.
|
||||
pub fn keep_file_font(&self, blob: &vectorcraft_doc::ImageBlob) -> Option<Arc<FontFace>> {
|
||||
self.keep_file_font_up_to(blob, super::MAX_FILE_FACES)
|
||||
}
|
||||
|
||||
fn keep_file_font_up_to(&self, blob: &vectorcraft_doc::ImageBlob, limit: usize) -> Option<Arc<FontFace>> {
|
||||
// Drop this short-lived resource lock before touching registry locks.
|
||||
let cached = {
|
||||
let mut owner = blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if blob.mime != vectorcraft_doc::FILE_FONT_MIME {
|
||||
*owner = None;
|
||||
return None;
|
||||
}
|
||||
if owner.as_ref().is_some_and(|face| !std::ptr::eq(face.bytes(), blob.bytes.as_slice()) && face.bytes() != blob.bytes.as_slice()) {
|
||||
*owner = None;
|
||||
}
|
||||
owner.clone()
|
||||
};
|
||||
if let Some(cached) = cached
|
||||
&& let Some(face) = self.read_file_faces().by_id.get(&cached.id()).and_then(std::sync::Weak::upgrade)
|
||||
&& std::ptr::eq::<dyn vectorcraft_doc::FileFontFace>(face.as_ref(), cached.as_ref())
|
||||
{
|
||||
return Some(face);
|
||||
}
|
||||
let face = self.admit_file_font(blob, limit)?;
|
||||
// No registry lock is held here; only resource owners, never weak bindings, keep slots.
|
||||
*blob.file_font.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(face.clone());
|
||||
Some(face)
|
||||
}
|
||||
|
||||
fn admit_file_font(&self, blob: &vectorcraft_doc::ImageBlob, limit: usize) -> Option<Arc<FontFace>> {
|
||||
let allocation = Arc::as_ptr(&blob.bytes) as usize;
|
||||
if let Some(face) = self.read_file_faces().by_blob.get(&allocation).and_then(std::sync::Weak::upgrade) {
|
||||
return Some(face);
|
||||
}
|
||||
let key = blob.content_key();
|
||||
let mut faces = self.file_faces.write().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(face) = faces
|
||||
.by_key
|
||||
.get(&key)
|
||||
.and_then(|bucket| bucket.iter().filter_map(std::sync::Weak::upgrade).find(|face| face.data() == blob.bytes.as_slice()))
|
||||
{
|
||||
return Some(face);
|
||||
}
|
||||
// Reap on admission, including dead hash buckets, so closed documents recover allowance.
|
||||
faces.by_id.retain(|_, face| face.strong_count() != 0);
|
||||
faces.by_blob.retain(|_, face| face.strong_count() != 0);
|
||||
faces.by_key.retain(|_, bucket| {
|
||||
bucket.retain(|face| face.strong_count() != 0);
|
||||
!bucket.is_empty()
|
||||
});
|
||||
if faces.by_id.len() >= limit {
|
||||
return None;
|
||||
}
|
||||
let (i, spec) = super::scan::enumerate_faces(&blob.bytes).into_iter().next()?;
|
||||
let face = Arc::new(super::build::make_face(super::face::FontBytes::Owned(blob.bytes.clone()), i, spec, None)?);
|
||||
faces.by_id.insert(face.id, Arc::downgrade(&face));
|
||||
faces.by_blob.insert(allocation, Arc::downgrade(&face));
|
||||
faces.by_key.entry(key).or_default().push(Arc::downgrade(&face));
|
||||
self.generation.fetch_add(1, super::Ordering::Relaxed);
|
||||
Some(face)
|
||||
}
|
||||
|
||||
/// Bind only references whose owning document actually carries the bytes. A serialized
|
||||
/// reference without its blob cannot borrow a font another document loaded.
|
||||
/// Keep owned fallbacks bound even while an installed exact face wins, in case it is removed.
|
||||
/// The return value says whether every active reference was admitted.
|
||||
pub fn bind_file_fonts<'a>(&self, t: &mut vectorcraft_doc::TextObject, image: impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>) -> bool {
|
||||
let mut resources: Vec<(String, Arc<dyn vectorcraft_doc::FileFontFace>)> = vec![];
|
||||
let mut complete = true;
|
||||
for font in t.file_fonts_in_use() {
|
||||
if !t.runs.iter().any(|r| r.style.font_family == font.family && r.style.font_style == font.style)
|
||||
|| resources.iter().any(|(key, _)| *key == font.key)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let face = image(&font.key).and_then(|blob| self.keep_file_font(blob));
|
||||
if let Some(face) = face {
|
||||
resources.push((font.key.clone(), face));
|
||||
} else {
|
||||
complete = false;
|
||||
}
|
||||
}
|
||||
if let Some(fonts) = t.file_fonts.as_mut()
|
||||
&& fonts.bind(resources)
|
||||
{
|
||||
t.cached_bounds = None;
|
||||
t.cached_baselines.clear();
|
||||
self.generation.fetch_add(1, super::Ordering::Relaxed);
|
||||
}
|
||||
complete
|
||||
}
|
||||
|
||||
/// Bind text throughout a resource tree, including opacity masks, reporting rejected fonts.
|
||||
pub fn bind_node_file_fonts<'a>(
|
||||
&self,
|
||||
n: &mut vectorcraft_doc::Node,
|
||||
image: &impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>,
|
||||
) -> Vec<String> {
|
||||
fn visit<'a>(
|
||||
db: &FontDb,
|
||||
n: &mut vectorcraft_doc::Node,
|
||||
image: &impl Fn(&str) -> Option<&'a vectorcraft_doc::ImageBlob>,
|
||||
warnings: &mut Vec<String>,
|
||||
) {
|
||||
if let vectorcraft_doc::NodeKind::Text(t) = &mut n.kind
|
||||
&& !db.bind_file_fonts(t, image)
|
||||
{
|
||||
for font in t.file_fonts_in_use() {
|
||||
if t.runs.iter().any(|r| r.style.font_family == font.family && r.style.font_style == font.style)
|
||||
&& t.file_fonts.as_ref().is_none_or(|fonts| fonts.face(&font.key).is_none())
|
||||
&& db.resolve(&font.family, &font.style).is_none_or(|(_, m)| m != super::traits::FontMatch::Exact)
|
||||
{
|
||||
let note = format!(
|
||||
"the file font {} {} could not be used (missing, invalid or live-font limit reached); its text uses a substitute",
|
||||
font.family, font.style
|
||||
);
|
||||
if !warnings.contains(¬e) {
|
||||
warnings.push(note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& has_file_fonts(&mask.art)
|
||||
{
|
||||
visit(db, Arc::make_mut(&mut mask.art), image, warnings);
|
||||
}
|
||||
for child in n.children_mut().into_iter().flatten().filter(|n| has_file_fonts(n)) {
|
||||
visit(db, Arc::make_mut(child), image, warnings);
|
||||
}
|
||||
}
|
||||
let mut warnings = vec![];
|
||||
visit(self, n, image, &mut warnings);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Establish document ownership before layout; unrelated blobs never enter the font cache.
|
||||
pub fn bind_document_file_fonts(&self, doc: &mut vectorcraft_doc::Document) -> Vec<String> {
|
||||
let vectorcraft_doc::Document { layers, symbols, graph_designs, patterns, pattern_edit, images, .. } = doc;
|
||||
let trees = layers.iter_mut().chain(symbols.iter_mut().map(|s| &mut s.art)).chain(graph_designs.iter_mut().map(|g| &mut g.art));
|
||||
let patterns = patterns.iter_mut().chain(pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
|
||||
let mut warnings = vec![];
|
||||
for root in trees.chain(patterns.flat_map(|p| &mut p.art)).filter(|n| has_file_fonts(n)) {
|
||||
for note in self.bind_node_file_fonts(Arc::make_mut(root), &|key| images.get(key)) {
|
||||
if !warnings.contains(¬e) {
|
||||
warnings.push(note);
|
||||
}
|
||||
}
|
||||
}
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Is `id` a live file-font resource?
|
||||
pub fn is_file_font(&self, id: u32) -> bool {
|
||||
self.read_file_faces().by_id.get(&id).is_some_and(|face| face.strong_count() != 0)
|
||||
}
|
||||
|
||||
pub(super) fn read_file_faces(&self) -> std::sync::RwLockReadGuard<'_, super::FileFaces> {
|
||||
self.file_faces.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// For each run of `t`, the font a file carried that draws it ([`vectorcraft_doc::FileFonts`]):
|
||||
/// while its text is the file's, the font the run names isn't available as named (missing, or
|
||||
/// another style of its family stands in) and the font kept for that family and style is
|
||||
/// bound to its owning blob. `None` for runs drawn in their named font or substitute;
|
||||
/// empty when none is drawn in such a font.
|
||||
pub fn file_faces(&self, t: &vectorcraft_doc::TextObject) -> Vec<Option<Arc<FontFace>>> {
|
||||
if t.file_fonts.is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let fonts = t.file_fonts_in_use();
|
||||
if fonts.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
// Each family and style's answer once: a line has a run per character it spaces apart.
|
||||
let mut known: Vec<(&str, &str, Option<Arc<FontFace>>)> = vec![];
|
||||
let mut out = Vec::with_capacity(t.runs.len());
|
||||
for r in &t.runs {
|
||||
let (family, style) = (r.style.font_family.as_str(), r.style.font_style.as_str());
|
||||
let face = match known.iter().find(|(f, s, _)| *f == family && *s == style) {
|
||||
Some((.., face)) => face.clone(),
|
||||
None => {
|
||||
let face = fonts
|
||||
.iter()
|
||||
.find(|f| f.family == family && f.style == style)
|
||||
.filter(|_| self.resolve(family, style).is_none_or(|(_, m)| m != super::traits::FontMatch::Exact))
|
||||
.and_then(|f| t.file_fonts.as_ref()?.face(&f.key))
|
||||
.and_then(|face| self.read_file_faces().by_id.get(&face.id()).and_then(std::sync::Weak::upgrade));
|
||||
known.push((family, style, face.clone()));
|
||||
face
|
||||
}
|
||||
};
|
||||
out.push(face);
|
||||
}
|
||||
if out.iter().all(Option::is_none) { vec![] } else { out }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "file_fonts_tests.rs"]
|
||||
mod file_fonts_tests;
|
||||
#[cfg(test)]
|
||||
mod shared_outline_tests {
|
||||
use super::super::glyph_pen::FlipPen;
|
||||
|
||||
@@ -66,6 +66,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
let CharStyle {
|
||||
font_family,
|
||||
font_style,
|
||||
file_font_id,
|
||||
font_version,
|
||||
font_axes,
|
||||
size,
|
||||
@@ -127,6 +128,7 @@ pub(crate) fn paint_only(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
original_paint == normalized_paint
|
||||
&& font_family == &b.font_family
|
||||
&& font_style == &b.font_style
|
||||
&& file_font_id == &b.file_font_id
|
||||
&& font_version == &b.font_version
|
||||
&& font_axes == &b.font_axes
|
||||
&& size == &b.size
|
||||
|
||||
@@ -160,10 +160,11 @@ fn text_hash(t: &TextObject) -> u64 {
|
||||
}
|
||||
|
||||
/// Does [`text_bytes`] and [`layout_bytes`] count everything `t` and `layout` hold? They do not count
|
||||
/// a gradient's stops, or a glyph's bitmap or color art.
|
||||
/// owned file-font resources, a gradient's stops, or a glyph's bitmap or color art.
|
||||
fn counts_its_memory(t: &TextObject, layout: &TextLayout) -> bool {
|
||||
let gradient = |p: &Paint| matches!(p, Paint::Gradient(_));
|
||||
!t.runs.iter().any(|r| gradient(&r.style.fill) || gradient(&r.style.stroke))
|
||||
t.file_fonts.is_none()
|
||||
&& !t.runs.iter().any(|r| gradient(&r.style.fill) || gradient(&r.style.stroke))
|
||||
&& !layout.glyphs.iter().chain(&layout.ruby).any(|g| g.image.is_some() || g.colour.is_some())
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,9 @@ pub fn layout_with(db: &FontDb, t: &TextObject, opts: &LayoutOptions) -> TextLay
|
||||
// The sizes the fits step and limit are the ones the Character panel shows (`shown`), whatever
|
||||
// em size a font height reference sets them at.
|
||||
let shown = t;
|
||||
// Keep the verified faces alive throughout fitting and resolve their height references too.
|
||||
let file = in_file_fonts(db, t);
|
||||
let t = file.as_ref().map_or(t, |(text, _)| text);
|
||||
let resolved = db.font_heights_resolved(t);
|
||||
let t = &*resolved;
|
||||
let first = layout_once(db, t, opts);
|
||||
@@ -375,6 +378,24 @@ pub fn scaled(t: &TextObject, f: f64) -> TextObject {
|
||||
s
|
||||
}
|
||||
|
||||
/// `t` with the runs a font its file carried draws ([`FontDb::file_faces`]) set in that font;
|
||||
/// `None` when none is.
|
||||
fn in_file_fonts(db: &FontDb, t: &TextObject) -> Option<(TextObject, Vec<Option<std::sync::Arc<crate::FontFace>>>)> {
|
||||
let faces = db.file_faces(t);
|
||||
if faces.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut out = t.clone();
|
||||
for (r, face) in out.runs.iter_mut().zip(&faces) {
|
||||
let Some(face) = face else { continue };
|
||||
r.style.file_font_id = Some(face.id());
|
||||
r.style.font_style = face.style.clone();
|
||||
r.style.font_version = None;
|
||||
r.style.font_axes.clear();
|
||||
}
|
||||
Some((out, faces))
|
||||
}
|
||||
|
||||
/// `t` in the styles its layout draws it in: [`scaled`] by the layout's
|
||||
/// [`TextLayout::fit_scale`] when Shrink Text to Fit (area type) or Dynamic Text (type on a path)
|
||||
/// scales it, `t` itself otherwise. Text with neither setting is not laid out.
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod craft_fonts;
|
||||
pub mod edit;
|
||||
pub mod embed;
|
||||
mod features;
|
||||
mod file_font;
|
||||
mod fontconfig;
|
||||
mod fontdb;
|
||||
mod harakat;
|
||||
@@ -41,9 +42,10 @@ pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont};
|
||||
pub use features::{
|
||||
EXTRA_FEATURES, LIGATURE_TRACKING_LIMITS, MAX_FEATURE_VALUE, MAX_STYLE_FEATURES, OtFeatures, explicit_ligatures, ligatures_suppressed_by,
|
||||
};
|
||||
pub use file_font::{FILE_FONT_UPEM, FileFontInfo, FileGlyph, MAX_FILE_GLYPHS, build_file_font};
|
||||
pub use fontdb::{
|
||||
CompositeCoverage, FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontLikeness, FontMatch, FontTraits, GENERIC_FAMILIES, GlyphAlternate,
|
||||
GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, OutlineFormat, PlatformFontFiles,
|
||||
GlyphCategory, GlyphCategoryKind, GlyphOrigin, IcfMargins, JoiningPosition, LentCompositeFonts, MAX_FILE_FACES, OutlineFormat, PlatformFontFiles,
|
||||
RECENTLY_ADDED_WITHIN, RecentlyAdded, StylisticSet, Substitution, SubstitutionKind, WantedFont, WantedFonts, app_font_dir, is_font_file,
|
||||
is_generic_family, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, set_user_font_dirs_confined, style_weight,
|
||||
system_font_dirs, user_font_dirs,
|
||||
|
||||
@@ -1158,6 +1158,7 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
|
||||
let CharStyle {
|
||||
font_family,
|
||||
font_style,
|
||||
file_font_id,
|
||||
font_version,
|
||||
font_axes,
|
||||
size,
|
||||
@@ -1226,6 +1227,7 @@ fn drawn_alike(a: &CharStyle, b: &CharStyle, vertical: bool) -> bool {
|
||||
&& offsets == other_offsets
|
||||
&& font_family == &b.font_family
|
||||
&& font_style == &b.font_style
|
||||
&& file_font_id == &b.file_font_id
|
||||
&& font_version == &b.font_version
|
||||
&& font_axes == &b.font_axes
|
||||
&& size == &b.size
|
||||
@@ -1292,6 +1294,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
let CharStyle {
|
||||
font_family,
|
||||
font_style,
|
||||
file_font_id,
|
||||
font_version,
|
||||
font_axes,
|
||||
size,
|
||||
@@ -1355,6 +1358,7 @@ fn shapes_alike(a: &CharStyle, b: &CharStyle) -> bool {
|
||||
*font_family == b.font_family
|
||||
&& warichu_alike(a, b)
|
||||
&& *font_style == b.font_style
|
||||
&& *file_font_id == b.file_font_id
|
||||
&& *font_version == b.font_version
|
||||
&& *font_axes == b.font_axes
|
||||
&& *size == b.size
|
||||
|
||||
@@ -398,22 +398,7 @@ pub fn two_axis_font() -> Option<Vec<u8>> {
|
||||
|
||||
/// A `name` table of Windows English (US) records (name id, string).
|
||||
pub fn name_table(records: &[(u16, &str)]) -> Option<Vec<u8>> {
|
||||
let mut records = records.to_vec();
|
||||
records.sort_by_key(|r| r.0);
|
||||
let n = u16::try_from(records.len()).ok()?;
|
||||
let (mut head, mut strings) = (Vec::new(), Vec::new());
|
||||
for v in [0, n, 6 + 12 * n] {
|
||||
head.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
for (id, s) in records {
|
||||
let bytes: Vec<u8> = s.encode_utf16().flat_map(u16::to_be_bytes).collect();
|
||||
for v in [3, 1, 0x0409, id, u16::try_from(bytes.len()).ok()?, u16::try_from(strings.len()).ok()?] {
|
||||
head.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
strings.extend(bytes);
|
||||
}
|
||||
head.extend(strings);
|
||||
Some(head)
|
||||
crate::file_font::name_table(records)
|
||||
}
|
||||
|
||||
/// The family of [`vertical_font`].
|
||||
|
||||
@@ -116,6 +116,38 @@ fn composite_type_draws_each_class_in_its_font() {
|
||||
assert!((l.glyphs[1].advance - alone.glyphs[0].advance).abs() < 1e-9);
|
||||
}
|
||||
|
||||
/// A file font and a composite font can share one text object without losing either face or the
|
||||
/// original run indices when the composite run splits.
|
||||
#[test]
|
||||
fn file_fonts_and_composite_fonts_draw_together() {
|
||||
use vectorcraft_doc::{FileFont, FileFonts};
|
||||
|
||||
let db = FontDb::with_font_dirs(vec![]);
|
||||
db.set_composite_font(&mixed("Mixed"));
|
||||
let info = FileFontInfo { family: "Carried Test".into(), style: "Regular".into(), ..Default::default() };
|
||||
let glyph = FileGlyph { ch: 'x', outline: Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 };
|
||||
let blob = vectorcraft_doc::ImageBlob::new(vectorcraft_doc::FILE_FONT_MIME, build_file_font(&info, &[glyph]).unwrap());
|
||||
let mut t = TextObject::point(Point::ZERO, "x", style("Carried Test", 12.0));
|
||||
t.runs.push(TextRun::new("A1", style("Mixed", 20.0)));
|
||||
t.runs.push(TextRun::new("x", style("Carried Test", 12.0)));
|
||||
t.file_fonts = Some(Box::new(FileFonts::new(
|
||||
vec![FileFont { family: "Carried Test".into(), style: "Regular".into(), key: "carried-test".into() }],
|
||||
&t.plain_text(),
|
||||
)));
|
||||
assert!(db.bind_file_fonts(&mut t, |key| (key == "carried-test").then_some(&blob)));
|
||||
let carried = db.file_faces(&t)[0].as_ref().unwrap().id();
|
||||
let l = layout(&db, &t);
|
||||
let fonts: Vec<(usize, u32)> = l.glyphs.iter().map(|g| (g.run, g.font_id)).collect();
|
||||
assert_eq!(fonts, [(0, carried), (1, face_id(&db, "JetBrains Mono")), (1, face_id(&db, "Inter")), (2, carried)]);
|
||||
assert_eq!(t.runs[0].style.font_family, "Carried Test", "layout does not rename the source runs");
|
||||
// Editing the text drops the file faces, but not the composite font's class-specific faces.
|
||||
t.runs[0].text.push('x');
|
||||
let edited = layout(&db, &t);
|
||||
assert!(edited.glyphs.iter().all(|g| !db.is_file_font(g.font_id)));
|
||||
let composite: Vec<u32> = edited.glyphs.iter().filter(|g| g.run == 1).map(|g| g.font_id).collect();
|
||||
assert_eq!(composite, [face_id(&db, "JetBrains Mono"), face_id(&db, "Inter")]);
|
||||
}
|
||||
|
||||
/// A ruby reading over type in a composite font is set in the parts its own characters fall in.
|
||||
#[test]
|
||||
fn ruby_over_composite_type_is_set_in_its_own_parts() {
|
||||
|
||||
@@ -749,7 +749,13 @@ fn duplicate_authored_glyphs_keep_occurrence_order() {
|
||||
|
||||
let mut wrong = before.clone();
|
||||
wrong.glyphs[0].run = 1;
|
||||
assert!(std::panic::catch_unwind(|| assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)).is_err());
|
||||
// This panic probe only reads snapshots; opaque carried-font handles need no unwind-safety bound.
|
||||
assert!(
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
assert_kashida_ownership(&text, &before, &wrong, &red(), "changed owner", false)
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// Compare authored glyph run indices before/after Insert Kashidas (matched by byte and gid;
|
||||
|
||||
@@ -4647,7 +4647,7 @@ fn a_documents_placed_key_moves_only_for_bitmaps_of_its_own_files() {
|
||||
assert_eq!(key(&mut keys, &session, plain, 10, &|_, _| files(&[file.as_str()])), 8, "no images: a file another document holds");
|
||||
// The same document holding an image and showing no placed document.
|
||||
let mut raster = session.documents().iter().find(|d| d.uid == plain).unwrap().clone();
|
||||
let blob = vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Default::default(), proxy: None };
|
||||
let blob = vectorcraft_doc::ImageBlob { mime: "image/png".into(), bytes: Default::default(), proxy: None, file_font: Default::default() };
|
||||
std::sync::Arc::make_mut(&mut raster.doc).images.insert("an image".into(), blob);
|
||||
assert_eq!(placed_key_at(&mut keys, &session, &raster, 11, |_, _| None), 8, "an image and no placed document: files no longer known");
|
||||
assert_eq!(keys.len(), 2);
|
||||
|
||||
@@ -79,6 +79,7 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>, params:
|
||||
// Update Links (Preferences › File Handling) applies there as it is set now.
|
||||
let update_links = app.session.prefs.update_links == "automatically";
|
||||
let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps;
|
||||
let open_params = app.session.prefs.with_pdf_font_choice(¶ms);
|
||||
// The automation roots in force here are in force there.
|
||||
let scope = ScopeHandle::capture();
|
||||
let opener = scope.clone();
|
||||
@@ -90,7 +91,7 @@ pub fn start_with(app: &mut VectorcraftApp, path: &str, bytes: Vec<u8>, params:
|
||||
vectorcraft_engine::guard::catch_panic(|| {
|
||||
cancel::scope(&raised, None, || {
|
||||
// A profile question Edit › Color Settings asks waits for the UI thread.
|
||||
fileio::read_for_open_asking(&name, &file, Some(name.clone()), ¶ms, update_links, low_res_proxy_eps, true)
|
||||
fileio::read_for_open_asking(&name, &file, Some(name.clone()), &open_params, update_links, low_res_proxy_eps, true)
|
||||
.map_err(|e| e.to_string())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -332,6 +332,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[
|
||||
"lowResProxyEps",
|
||||
"When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links.",
|
||||
),
|
||||
("pdfImportEmbeddedFonts", "Uses a PDF's embedded glyphs for imported text when its font is missing; off, it uses the fallback font."),
|
||||
(
|
||||
"antiAliasedBitmaps",
|
||||
"In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed.",
|
||||
|
||||
@@ -2972,8 +2972,8 @@ fn the_description_line_keeps_the_fields_column_height() {
|
||||
}
|
||||
|
||||
/// Each sentence describes a setting the dialog shows on this platform or, like System Title Bar,
|
||||
/// on another one, and every complete catalog translates it into at most the three lines the
|
||||
/// description line holds.
|
||||
/// on another one. The actual translation, or English fallback for a new sentence, fits the three
|
||||
/// lines the description line holds.
|
||||
#[test]
|
||||
fn every_description_names_a_setting_and_fits_in_every_language() {
|
||||
let ctx = egui::Context::default();
|
||||
@@ -2986,13 +2986,14 @@ fn every_description_names_a_setting_and_fits_in_every_language() {
|
||||
}
|
||||
for lang in crate::i18n::Lang::all() {
|
||||
let text = crate::i18n::tr(lang, sentence);
|
||||
if lang != crate::i18n::Lang::EN && text == *sentence {
|
||||
bad.push(format!("{}: no row for {sentence:?}", lang.code()));
|
||||
let translated = crate::i18n::has(lang, sentence);
|
||||
if lang != crate::i18n::Lang::EN && translated && text == *sentence {
|
||||
bad.push(format!("{}: the available translation for {sentence:?} was not used", lang.code()));
|
||||
}
|
||||
let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0);
|
||||
job.wrap.max_rows = 3;
|
||||
let galley = ui.painter().layout_job(job);
|
||||
if galley.elided || galley.size().y > DESCRIPTION_HEIGHT {
|
||||
if !translated && text != *sentence {
|
||||
bad.push(format!("{}: missing {sentence:?} did not fall back to English", lang.code()));
|
||||
}
|
||||
if !description_fits(ui, text) {
|
||||
bad.push(format!("{}: {text:?} takes more than three lines", lang.code()));
|
||||
}
|
||||
}
|
||||
@@ -3001,3 +3002,29 @@ fn every_description_names_a_setting_and_fits_in_every_language() {
|
||||
out.textures_delta.clear();
|
||||
assert!(bad.is_empty(), "{}", bad.join("\n"));
|
||||
}
|
||||
|
||||
fn description_fits(ui: &egui::Ui, text: &str) -> bool {
|
||||
let mut job = egui::text::LayoutJob::simple(text.to_string(), egui::FontId::proportional(11.5), egui::Color32::WHITE, 530.0);
|
||||
job.wrap.max_rows = 3;
|
||||
let galley = ui.painter().layout_job(job);
|
||||
!galley.elided && galley.size().y <= DESCRIPTION_HEIGHT
|
||||
}
|
||||
|
||||
/// English fallback still has to fit: accepting a missing catalog row must not hide overflow.
|
||||
#[test]
|
||||
fn description_layout_rejects_overflow_even_for_english_fallback() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let short = "A new setting without a catalog row.";
|
||||
let long = format!("{short} ").repeat(100);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
for lang in crate::i18n::Lang::all() {
|
||||
assert!(!crate::i18n::has(lang, short) && !crate::i18n::has(lang, &long));
|
||||
assert_eq!(crate::i18n::tr(lang, short), short);
|
||||
assert_eq!(crate::i18n::tr(lang, &long), long);
|
||||
assert!(description_fits(ui, crate::i18n::tr(lang, short)));
|
||||
assert!(!description_fits(ui, crate::i18n::tr(lang, &long)), "{}: overflowing fallback was accepted", lang.code());
|
||||
}
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live enLine truncated
|
||||
>
|
||||
> **File-font integration status (2026-11-19, #4569):** 56 focused PDF/native-reopen, file-font, stroked-text and font-binding tests passed on the current-main integration candidate. Full workspace CI and hardening paths outside those suites remain pending. Scores and estimates unchanged.
|
||||
>
|
||||
> Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865).
|
||||
|
||||
Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`,
|
||||
@@ -9,6 +11,42 @@ Every format Illustrator opens, places, saves or exports, against VectorCraft's
|
||||
documentation (helpx "file formats" and Save/Export pages), not from its installed bundle: the clean-room rule
|
||||
forbids reading the install. Part of [target-app-parity.md](target-app-parity.md).
|
||||
|
||||
### File-font ownership hardening (#4569)
|
||||
|
||||
The implementation binds editable PDF and native text to font bytes the owning document carries.
|
||||
Serialized blob keys and forged internal font-family names cannot authorize another document's
|
||||
face. Content keys index candidate faces; a byte comparison resolves collisions. Referenced fonts
|
||||
enter a bounded live-face registry with weak indexes, so admission can reap released slots.
|
||||
Runtime image-blob leases retain faces across document, Undo and clipboard resource copies;
|
||||
weak text bindings keep cached geometry from retaining admission after those owners disappear.
|
||||
Explicit in-flight face handles retain their admission until their final owner drops.
|
||||
Unreferenced `font/ttf` blobs do not enter that registry. Referenced carried fonts retain an owned,
|
||||
dormant binding while an installed exact face draws, so removing that face needs no reopen.
|
||||
Place and Break Link transfer font resources and their runtime leases, including equal-byte reuse
|
||||
and conflicting keys. Older-version placed-art saves prefix serialized and runtime font keys
|
||||
together. Recovery restores the blobs before binding and reporting actual refusals. Invalid,
|
||||
missing and cap-refused resources produce substitution warnings during native open, PDF import,
|
||||
paste and recovery.
|
||||
|
||||
Synthetic regressions cover chosen-key collisions in both opening orders, metadata-only references,
|
||||
forged internal names, unused blobs, last-owner quota recovery, cross-document renderer reuse, and
|
||||
native open/save, source-tab close, clipboard relinking, Undo/Redo and export. Placement, Break Link,
|
||||
older-version save, recovery and installed-font-removal regressions cover resource-lifetime paths.
|
||||
The serde round-trip regressions use a test-only `serde_json` dependency; the read-only harakat
|
||||
panic probe asserts unwind safety locally without restricting production font interfaces.
|
||||
The height-reference regression uses a fixture with explicit OS/2 cap-height metadata.
|
||||
Native and recovery regression fixtures put artwork inside a layer, preserving the document
|
||||
structure that placement, clipboard insertion and native reopening require.
|
||||
SVG regression checks read the text response and require both owned faces to be embedded; the
|
||||
existing warning for overlapping CSS font descriptions is distinct from font substitution.
|
||||
Paragraph reconstruction binds the source lines' validated carried faces before measuring or
|
||||
checking wrapping. The native-reopen regressions compare conflicting-glyph positions and wrapped
|
||||
paragraph ink bounds with outline imports, including filled-and-stroked `TJ` text. The focused
|
||||
engine PDF-fidelity, PDF file-font/stroked-text and text binding/shared-outline suites passed
|
||||
56 tests on the canonical-main integration candidate. Full workspace CI and hardening paths
|
||||
outside those suites remain pending. Existing PDF respacing and composite-font regressions
|
||||
remain; no parity score or estimate changes.
|
||||
|
||||
**Fidelity** is estimated unless a test is named. Test sources: unit and property tests per crate
|
||||
(`crates/svg/tests`, `crates/pdf/tests`, `crates/format/tests/prop_format.rs`), import fuzzing
|
||||
(`crates/engine/tests/import_fuzz.rs`), the Affinity corpus (`cargo xtask corpus --affinity`, 51 pinned public
|
||||
@@ -386,6 +424,8 @@ Stop opacity on translated artboards remains outside this regression coverage.
|
||||
|---|---|---|
|
||||
| 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged |
|
||||
| 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. |
|
||||
| 2026-11-12 | minor | #4569: document-owned file-font bindings, exact-byte identity checks and reclaimable live-face allowance; preserve referenced fallback bindings through installed-font removal, transfer placement leases/resources, relink older-save font keys, and restore recovery blobs before binding/diagnostics. Regression sources cover native/clipboard/export, Place/Break Link/older saves/recovery and isolated text/renderer ownership. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. |
|
||||
| 2026-11-09 | minor | PDF embedded-font import and composite-font layout work together: retained file fonts keep their glyphs while composite runs split by character class, with glyphs still naming their original runs; editing switches only the file-font text to its substitute. Background opens keep explicit importer parameters and PDF options while applying the embedded-font preference only when no choice was supplied. Regression `tests::composite::file_fonts_and_composite_fonts_draw_together` and existing PDF fidelity and Open With tests; scores unchanged (#4568) |
|
||||
| 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. |
|
||||
| 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. |
|
||||
@@ -460,6 +500,7 @@ Stop opacity on translated artboards remains outside this regression coverage.
|
||||
| 2026-11-04 | minor | Raster/PSD export uses document resolution unless ppi or scale is supplied; CLI run/convert accept --ppi. Synthetic engine, CLI and MCP regressions cover dimensions and override precedence; scores and hours unchanged. |
|
||||
| 2026-11-01 | minor | Native format: a symbol's Symbol Type (`dynamic`) and a dynamic symbol instance's appearance changes to objects of its art (`symbol_overrides`) round-trip; both are left out when unset, so other documents save unchanged (#4938). `.ai` reading and writing of dynamic symbols remains. |
|
||||
| 2026-11-01 | minor | Exports draw each artboard's background color behind its art (#4937): PNG, JPEG, GIF, TIFF, WebP, BMP, Targa and PSD (a layer of its own; on a transparent background too), PDF, SVG and EPS pages, a `.ai` file's PDF pages and PostScript and PDF print; `includeArtboardFill: false` leaves it out. Files with editing data (Preserve Editing, `.ai`, EPS, native) keep it as the artboard's color and reopen without extra art. Not read from the reference app's own `.ai` data, nor written to it. DXF, EMF and WMF leave it out |
|
||||
| 2026-11-01 | minor | PDF import: type in a font the file embeds and this machine lacks is drawn in a small TrueType font built from the glyphs the file draws, kept with the document (MIME `font/ttf`, one per family and style, at most 64 are used to draw one type object, however many the file lists; 200,000 glyphs per import, a per-font glyph cap and a cap on fonts kept in memory), not the file's own font program: that program draws nothing and builds nothing, and is read only for its licence flags and metrics. The file's licence flags (OS/2 `fsType`) are copied to it (4, print and preview, when the file's program has none), so an export honours them as for any font: a restricted one (`fsType` 2, or bitmaps only) keeps its outlines out of an SVG's embedded fonts, and Document Info lists the permission. The text keeps naming the file's fonts, so they stay listed as missing; editing it, or installing the font, returns it to the font it names or its substitute. A saved file carries these glyphs, which is third-party font software in a file that may be shared: whether that is allowed is for the user to check against the font's licence. Import itself does not leave out a font whose flags forbid editing or embedding: it keeps the glyphs the file drew and carries the flags, and a policy that goes further (refusing such fonts, or a licence note when saving) is for the project owner. Sources: [Acrobat Help, PDF fonts](https://helpx.adobe.com/acrobat/using/pdf-fonts.html) and [Edit text in PDFs](https://helpx.adobe.com/acrobat/using/edit-text-pdfs1.html) for embedded fonts and what editing text in a font that is not installed does; the OpenType [OS/2 `fsType`](https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fstype) field for the licence flags. Two programs of one family and style share one built font, which takes the stricter of their flags. It is on by default and has an opt-out: Preferences › File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`) and the `embeddedFonts` param of `document.open` and `file.place`; off, import sets the type in the fallback font and warns, as before (owner decision 2026-11-03). Tests `embedded_fonts_on_keeps_the_files_glyphs`, `embedded_fonts_off_sets_type_in_the_fallback_font_with_the_warning` and `the_embedded_fonts_preference_reaches_the_import_options`. Scores unchanged. |
|
||||
| 2026-10-31 | minor | PDF import finds an installed font whose PDF name holds hyphens (`Noto-Sans-Bold` is Noto Sans, Bold: the longest part before a hyphen that names an installed family) and a composite font by its CIDFont's name rather than its base name, which ends in the CMap's (`Name-Identity-H`, [ISO 32000-1 §9.7.6.1](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf)); a missing font is split only before a style part (`Helvetica-BoldOblique`), so it is reported as `MS PGothic`, not `MS`; scores unchanged (estimated) |
|
||||
| 2026-10-31 | minor | DXF export (2000–2018): the LAYOUT objects wrote the paper image origin as a point at group codes 148 and 158, but PLOTSETTINGS defines 148 and 149 and no 158, so strict readers could reject the file (Autodesk Fusion reported "DXF File failed to insert", #3085). They now write 148/149, the shade plot mode, resolution and DPI (76–78, 2004 and later) and flag 1024 on the Model layout; the plot style ACDBPLACEHOLDER no longer carries a subclass marker. Test `r2000_and_later_files_have_the_structure_cad_apps_require` (required sections and table entries, handles and references, LAYOUT group codes); exports pass ezdxf's recover and audit; not tested in Fusion itself; scores unchanged |
|
||||
| 2026-10-31 | minor | `.ai`/EPS editing data: an envelope whose contents are being edited is written the other way round from one that isn't: its contents, a group on `%_` lines, then its dictionary, which holds the mesh that shapes them. Those contents were read as art, so the undistorted art drew over the distorted art the page draws. The group on `%_` lines before an envelope's dictionary is now left out whatever it holds (text in it stays as hidden text, as the dictionary's own does), as the envelope's mesh already was (#2405). Test `import::ai::tests::an_envelope_s_contents_being_edited_are_not_read_as_art`; checked locally against a user's file: it opens from its layers, 0.0% from its page (it was 9.7%, over the 5% limit); scores unchanged |
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
> Blend redraw update (#5179; previously: Keyboard Shortcuts: user-bindable Switch Selection Tools (#7645), with no default key; scores and estimates unchanged): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
|
||||
|
||||
> **File-font hardening status (2026-11-12, #4569):** G8 implementation and synthetic regressions added; compilation and runtime proof pending. Scores and estimates unchanged.
|
||||
|
||||
## Feature submission evidence
|
||||
|
||||
Actions panel item context menus (2026-11-20): Right-clicking an Action Set row selects it and presents a context menu with New Action…, New Set…, Duplicate Set, Delete Set, and Set Options…. Right-clicking an Action row selects it and presents a context menu with Play, Record, Duplicate, Delete, Action Options…, and Batch…. Duplicate on an action duplicates that action and selects the duplicate; Delete removes it. Headless tests in `crates/ui-egui/src/panels/actions.rs`: `right_clicking_an_action_set_selects_it_and_presents_set_context_options`, `right_clicking_an_action_selects_it_and_presents_action_options`, and `clicking_duplicate_on_an_action_duplicates_that_action_in_the_set`. Scores and estimates unchanged.
|
||||
@@ -315,6 +317,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G8 Hardening at scale
|
||||
|
||||
- **Implementation awaiting runtime proof (#4569):** bind file-font references to owned document blobs, compare candidate face bytes, and reclaim dead live-face slots. Unused blobs do not consume admission; native/PDF/paste report refused resources. Synthetic text, renderer and native/clipboard regressions added; no gap closed before compilation and runtime checks.
|
||||
|
||||
- **Done:** PngSuite fetching verifies 175 original PNGs and redistribution notices against a pinned SHA-256/size manifest before publishing; file and total-size budgets, cache verification and no archive extraction (#1729). The real-world corpus and manual QA gaps below remain.
|
||||
|
||||
- **Done:** bounded synthetic control-input expansion (#1709): click/drag counts and pending-event capacity are checked before mutation, and control-channel bursts yield between frames. The corpus and platform QA below remain pending.
|
||||
@@ -990,6 +994,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv
|
||||
| 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-12 | minor | G8 / #4569: file-font ownership and reclaimable admission implementation; regression sources added, compilation and runtime proof pending. Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged |
|
||||
| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. |
|
||||
| 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. |
|
||||
|
||||
@@ -1563,6 +1563,7 @@ are compared with the first page only. An artboard, or the page of an EPS's edit
|
||||
a point of its page's is compared on an area of the page's size. A file whose editing data is for a page of another
|
||||
size opens the same way, and its warning gives both sizes in points, with the scale of the editing data's page to the
|
||||
file's page (1:10 for a tenth of its size) when their sides are in proportion.
|
||||
Type in a font a PDF embeds and this machine lacks is drawn in glyphs built from the file's own, kept with the document (#4568); `embeddedFonts: false` (default `true`) sets it in the fallback font with the missing-font warning instead, as before. Preferences › File Handling › Use fonts embedded in imported PDFs (`pdfImportEmbeddedFonts`, on by default) is the choice `document.open` and `file.place` take when they give none; a call's own `embeddedFonts` wins. With `textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. A PDF
|
||||
With `textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines. A PDF
|
||||
saved with Illustrator's editing data holds it in `AIPDFPrivateData` streams and opens from it as a `.ai` file does.
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
>
|
||||
> Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865).
|
||||
>
|
||||
> **M4/M7 file-font hardening status (2026-11-12, #4569):** implementation and synthetic regressions added; compilation and runtime proof pending. Scores and estimates unchanged.
|
||||
>
|
||||
> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged.
|
||||
>
|
||||
> Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369).
|
||||
@@ -246,6 +248,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours
|
||||
| 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | M14/G12: Character Styles and Paragraph Styles panels item context menus (Options…, Duplicate, Delete, Redefine, Clear Overrides); regression tests in crates/ui-egui/src/panels/text_styles/tests.rs; scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged |
|
||||
| 2026-11-12 | minor | M4/M7 / #4569: document-owned file-font identity and reclaimable live-face allowance implementation, with text/renderer/native/clipboard/export regression sources. Format-only verification; compilation and runtime proof pending. Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged |
|
||||
| 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. |
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
>
|
||||
> Glyphs update (#5514): Alternates for Current Selection applies a variant's OpenType feature to that letter alone (`salt=2`) so an Arabic word stays joined; Entire Font lists unencoded glyphs. A positional variant no supported feature draws can be applied as a glyph choice (#6084). Entire Font uses the selection's font version and variable axes, and the default cell remains available after an unlisted choice even without GSUB alternates. Only Arabic presentation-form characters insert their joining base letter. Scores and estimates unchanged.
|
||||
>
|
||||
> **File-font integration status (2026-11-19, #4569):** 56 focused integration tests passed, including wrapped carried-font paragraphs and conflicting glyphs through native reopen. Full workspace CI and other hardening paths remain pending. Type core and file-format scores and estimates unchanged. See [file-font ownership evidence](file-format-parity.md#file-font-ownership-hardening-4569).
|
||||
>
|
||||
> Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373).
|
||||
>
|
||||
> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged.
|
||||
@@ -3183,6 +3185,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
|
||||
| 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. |
|
||||
| 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. |
|
||||
| 2026-11-12 | minor | #4569: file-font identity, ownership and quota hardening implementation with isolated text/renderer and native/clipboard/export regression sources; integration coverage includes Place, Break Link, older saves, recovery and installed-font removal. Format-only verification; runtime proof pending. Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged |
|
||||
| 2026-11-18 | minor | Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. |
|
||||
|
||||
+5
-1
@@ -2,7 +2,9 @@
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged.
|
||||
> **File-font hardening status (2026-11-12, #4569):** implementation and synthetic regressions added; compilation and runtime checks pending. Scores and estimates unchanged.
|
||||
>
|
||||
> Glyphs review (#6084): a positional variant no supported feature draws is accepted as a glyph choice. Entire Font respects the selection's variable axes and font version; the default cell can reset an unlisted choice without GSUB alternates. Contextual choices use the supplying face, including fallback. Feature-only boundaries preserve ligature clusters and Arabic mark attachment. Encoded characters insert unchanged except Arabic presentation forms with a joining base letter; normalization reports success only after insertion succeeds. Latest follow-up regressions await runtime verification. Scores and estimates unchanged.
|
||||
|
||||
Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in
|
||||
[target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the
|
||||
@@ -20,6 +22,7 @@ against Illustrator's public documentation; **estimated** unless noted.
|
||||
|
||||
| Feature | Status | Notes |
|
||||
|---|---|---|
|
||||
| File-carried font ownership and admission | unverified implementation | #4569 binds referenced fonts to document-owned bytes, compares content-hash collisions by bytes, and reaps dead global face entries. Synthetic text, renderer and native/clipboard regressions added; runtime proof pending. |
|
||||
| Mouse wheel over the closed font-family field | done | #5253: Character, Properties and Control step selected text through the family list using saved font filters (excluding search text), one undo step per notch; the style is matched and the list stops at either end. Escape and leaving the field keep the change. The field takes the wheel only when the pointer was moved onto it after the field last moved or was covered by a window or overlay, and the wheel stream began there; a stream that began elsewhere stays there until 0.5 s pass with no wheel input. Order, bounds, Undo grouping, this rule and its 0.5 s are VectorCraft's choices; scores unchanged. |
|
||||
| Soft return (forced line break, Shift+Enter) | done | Shift+Enter inserts a soft return (U+2028), breaking the line without starting a new paragraph; paragraph spacing (space before/after) and first-line indents apply only at paragraph ends; continuation lines in lists do not repeat the marker; in justified text a line a soft return ends is justified as a wrapped line is, only the paragraph's last line keeping its alignment, as Illustrator's own layout in a user's `.ai` sets it (evidence: `tests::typo::soft_return_in_justified_text_spreads_like_a_wrapped_line`; first done the other way in #2754) |
|
||||
| Native font-family labels | partial | With Show Font Names in English off, localized legacy names are used when typographic names contain no native label (#2208); loaded-font and catalog-only regressions. Choosing among multiple native languages is unchanged. |
|
||||
@@ -89,6 +92,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-12 | minor | #4569: file-font identity, ownership and live-face allowance hardening; forged internal family names no longer select global file fonts. Preserve owned fallback bindings through installed-font removal, placement, older saves and recovery. Added synthetic regressions; format-only verification, runtime proof pending. Scores and estimates unchanged. |
|
||||
| 2026-11-18 | minor | Retype phase 1 (#4934): `type.retype` turns outlined glyphs that exactly match an available font back into point text (font, size, baseline, turn, paint), reporting the shapes it cannot match; the Retype row is now partial. Scores and estimates unchanged |
|
||||
| 2026-11-15 | minor | Check Spelling dialog (#4936): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) modal dialog with sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete. Scores and estimates unchanged. |
|
||||
| 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. |
|
||||
|
||||
Reference in new issue
Block a user