Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

Merge main into #209; leave other apps' private font folders alone

Brandon Thomas51a9b899c17f
diff --cc ROADMAP.md
index 8baf91c61,44ab4471e..b0115f5a3
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -126,7 -126,6 +126,7 @@@ grade by behaviour against `plan/illust
- **Graphic styles:** styles keep opacity and blend mode, capture groups and type, apply on top with Alt, and link to the objects using them; Redefine, Break Link, Graphic Style Options, Select All Unused, Sort by Name, and Select > Same Graphic Style / Appearance Attribute. The panel has list and thumbnail views with rendered previews, merge, reorder and drag and drop, plus a Control bar Style picker; six generated style libraries save and load as `.vcstyles`.
- **Neutral wording:** labels, MCP tool text, docs and packaging use neutral names, and `cargo xtask brands` (part of `cargo xtask ci`) fails on vendor names.
- **Colour, type and file workflows:** Recolor Artwork (dialog with harmonies), Edit Colors, Find & Replace, Change Case, Smart Punctuation, Guides, Lock/Hide Above, Transform Each, Rasterize.
- - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. On macOS, fonts activated by other design apps (their subscription fonts and own font folders) are found too (Preferences › Type › Include Fonts of Other Design Apps' Folders).
++- **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing.
- **Files (M4):**
- `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash, background save and export.
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units; PDF and PDF-compatible `.ai` in and out (layers, masks, editable text, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3).
diff --cc crates/text/src/fontdb.rs
index fa1ccd52c,d797e07fe..8e32e3917
--- a/crates/text/src/fontdb.rs
+++ b/crates/text/src/fontdb.rs
@@@ -159,6 -153,9 +155,9 @@@ struct CatalogFamily
/// [`FontDb::face`] does). Always empty on wasm, which has no system fonts.
type Catalog = HashMap<String, CatalogFamily>;
-/// The installed faces' (family, style) by ASCII-lowercased PostScript name.
++/// The installed faces' (family, style) by normalized PostScript name ([`norm`]).
+ type PostScriptNames = HashMap<String, (String, String)>;
+
/// Process-wide font database.
pub struct FontDb {
faces: RwLock<Vec<Arc<FontFace>>>,
@@@ -167,13 -166,6 +168,8 @@@
/// The folders the system font scan reads (the platform's font folders for [`FontDb::global`]).
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
font_dirs: Vec<PathBuf>,
- /// Adobe applications' font folders, scanned with `font_dirs` while `adobe` is on.
- #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
- adobe_dirs: Vec<PathBuf>,
- #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
- adobe: std::sync::atomic::AtomicBool,
+ /// The installed fonts' other names (localized, legacy, PostScript) by normalized name.
+ aliases: RwLock<HashMap<String, Vec<Alias>>>,
/// Set once the font folders have been scanned. Lookups by family name wait for the first
/// scan, so what they find never depends on what ran before them.
#[cfg(not(target_arch = "wasm32"))]
@@@ -362,10 -251,11 +358,11 @@@ fn enumerate_faces(data: &[u8]) -> Vec<
.collect()
}
- /// (family, style) of every face in the font file at `path`, reading only its table directories
- /// and `name` tables: a scan opens hundreds of font files, many of them megabytes long.
+ /// (family, style, PostScript name) of every face in the font file at `path`, reading only its
+ /// table directories and `name` tables: a scan opens hundreds of font files, many of them
+ /// megabytes long.
#[cfg(not(target_arch = "wasm32"))]
-fn file_face_names(path: &Path) -> Vec<(String, String, Option<String>)> {
+fn file_face_names(path: &Path) -> Vec<(String, String, FaceKeys)> {
use std::io::{Read, Seek, SeekFrom};
/// Caps on what a (possibly damaged) file can make the scan read.
const MAX_FACES: u32 = 256;
@@@ -542,10 -410,8 +529,9 @@@ impl FontDb
faces: RwLock::new(faces),
outlines: Mutex::new(HashMap::new()),
catalog: RwLock::new(Catalog::new()),
+ postscript: RwLock::new(PostScriptNames::new()),
font_dirs,
- adobe_dirs: vec![],
- adobe: std::sync::atomic::AtomicBool::new(true),
+ aliases: RwLock::new(HashMap::new()),
#[cfg(not(target_arch = "wasm32"))]
cataloged: std::sync::OnceLock::new(),
family_cache: Mutex::new(None),
@@@ -693,12 -557,9 +679,10 @@@
#[cfg(not(target_arch = "wasm32"))]
fn scan_font_dirs(&self) -> usize {
let mut catalog = Catalog::new();
+ let mut aliases: HashMap<String, Vec<Alias>> = HashMap::new();
+ let mut postscript = PostScriptNames::new();
let mut n = 0;
let mut stack = self.font_dirs.clone();
- if self.adobe.load(Ordering::Relaxed) {
- stack.extend(self.adobe_dirs.iter().cloned());
- }
// Each folder once, however links lead back to it.
let mut visited = std::collections::HashSet::new();
while let Some(d) = stack.pop() {
@@@ -716,10 -577,10 +700,14 @@@
if !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) {
continue;
}
- for (family, style, ps) in file_face_names(&p) {
- if let Some(ps) = ps {
- postscript.insert(ps.to_ascii_lowercase(), (family.clone(), style.clone()));
+ for (family, style, keys) in file_face_names(&p) {
+ for (k, a) in Alias::of(&family, &style, &keys) {
+ aliases.entry(k).or_default().push(a);
+ }
++ // `keys.postscript` is normalized ([`norm`]), as `by_postscript_name` looks it up.
++ for ps in &keys.postscript {
++ postscript.insert(ps.clone(), (family.clone(), style.clone()));
+ }
let entry = catalog.entry(family.to_ascii_lowercase()).or_default();
if entry.name.is_empty() {
entry.name = family;
@@@ -731,87 -592,19 +719,85 @@@
}
log::debug!("cataloged {n} system font faces");
*self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog;
+ *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases;
+ *self.postscript.write().unwrap_or_else(|e| e.into_inner()) = postscript;
self.changed();
n
}
- /// Also catalog the font folders of Adobe applications ([`adobe_font_dirs`]; on by default).
- /// A change rescans the catalog if it was made.
- pub fn set_adobe_fonts(&self, on: bool) {
- #[cfg(not(target_arch = "wasm32"))]
- if self.adobe.swap(on, Ordering::Relaxed) != on && !self.adobe_dirs.is_empty() && self.cataloged.get().is_some() {
- self.load_system_fonts();
- }
- #[cfg(target_arch = "wasm32")]
- let _ = on;
- }
-
+ /// The family's own name and the style for a name given in a document: any of a family's
+ /// names (`ヒラギノ角ゴシック` is Hiragino Sans), a legacy family name (`Hiragino Sans W6` with its
+ /// legacy style names the W6 face) or a PostScript name (`HiraginoSans-W6`, as PDF and `.ai`
+ /// files name fonts). Case and anything but letters and digits are ignored. A name nothing
+ /// answers to comes back as it is.
+ pub fn canonical(&self, family: &str, style: &str) -> (String, String) {
+ if self.is_loaded(family) || self.read_catalog().contains_key(&family.to_ascii_lowercase()) {
+ return (family.to_string(), style.to_string());
+ }
+ let key = norm(family);
+ let mut found: Vec<Alias> =
+ self.read_faces().iter().flat_map(|f| Alias::of(&f.family, &f.style, &f.keys)).filter(|(k, _)| *k == key).map(|(_, a)| a).collect();
+ if let Some(v) = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key) {
+ found.extend(v.iter().cloned());
+ }
+ let ns = norm(style);
+ // A family name keeps the style asked for; a legacy pair names its face; a PostScript name
+ // its face whatever style is asked for.
+ if let Some(a) = found.iter().find(|a| a.style.is_none()) {
+ return (a.family.clone(), style.to_string());
+ }
+ if let Some(a) = found.iter().find(|a| a.paired.as_ref().is_some_and(|p| *p == ns) || a.paired.is_none()) {
+ return (a.family.clone(), a.style.clone().unwrap_or_else(|| style.to_string()));
+ }
+ match found.first() {
+ Some(a) => (a.family.clone(), style.to_string()),
+ None => (family.to_string(), style.to_string()),
+ }
+ }
+
+ /// [`face`](Self::face) by any of the family's names ([`canonical`](Self::canonical)), and how
+ /// it matched.
+ pub fn resolve(&self, family: &str, style: &str) -> Option<(Arc<FontFace>, FontMatch)> {
+ let (family, style) = self.canonical(family, style);
+ let f = self.face(&family, &style)?;
+ let m = if !f.family.eq_ignore_ascii_case(&family) {
+ FontMatch::Missing
+ } else if norm(&f.style) == norm(&style) || f.keys.styles.contains(&norm(&style)) {
+ FontMatch::Exact
+ } else {
+ FontMatch::Style
+ };
+ Some((f, m))
+ }
+
+ /// The installed face whose PostScript name is `name` (`HiraginoSans-W3`; any case), loaded
+ /// from the system fonts if need be. `None` when no installed font has the name.
+ pub fn find_postscript(&self, name: &str) -> Option<Arc<FontFace>> {
+ let key = norm(name);
+ if key.is_empty() {
+ return None;
+ }
+ let loaded = |db: &FontDb| db.read_faces().iter().find(|f| f.keys.postscript.contains(&key)).cloned();
+ if let Some(f) = loaded(self) {
+ return Some(f);
+ }
+ self.ensure_catalog();
+ let face = self.aliases.read().unwrap_or_else(|e| e.into_inner()).get(&key).and_then(|v| {
+ v.iter().find(|a| a.paired.is_none() && a.style.is_some()).map(|a| (a.family.clone(), a.style.clone().unwrap_or_default()))
+ });
+ let (family, style) = face?;
+ self.face(&family, &style)?;
+ loaded(self)
+ }
+
+ /// The (family, style) of the installed face whose PostScript name is `name` (ignoring ASCII
+ /// case). Documents name fonts this way, and a family can hold hyphens
+ /// ("Rounded-X-Mplus-1c-black" is Rounded-X M+ 1c, black), so the name can't be split.
+ pub fn by_postscript_name(&self, name: &str) -> Option<(String, String)> {
+ self.ensure_catalog();
- self.postscript.read().unwrap_or_else(|e| e.into_inner()).get(&name.to_ascii_lowercase()).cloned()
++ self.postscript.read().unwrap_or_else(|e| e.into_inner()).get(&norm(name)).cloned()
+ }
+
/// Load the files of the installed `family`. Returns whether any face was added.
#[cfg(not(target_arch = "wasm32"))]
fn load_cataloged(&self, family: &str) -> bool {
@@@ -950,12 -738,7 +936,11 @@@
return true;
}
}
- let mut paths: Vec<PathBuf> = self.read_catalog().values().flat_map(|c| c.faces.iter().map(|(_, p)| p.clone())).collect();
+ let mut paths: Vec<PathBuf> = self
+ .read_catalog()
+ .values()
+ .flat_map(|c| c.faces.iter().map(|(_, p)| p.clone()))
- .filter(|p| !self.adobe_dirs.iter().any(|d| p.starts_with(d)))
+ .collect();
paths.sort();
paths.dedup();
for p in paths {
diff --cc crates/text/src/lib.rs
index 7c06c7c74,bf251e695..7749d60da
--- a/crates/text/src/lib.rs
+++ b/crates/text/src/lib.rs
@@@ -19,8 -20,9 +20,9 @@@ mod layout
mod shape;
pub mod thread;
+ pub use craft_fonts::{CRAFT_FONTS, CraftFont};
pub use features::OtFeatures;
- pub use fontdb::{FALLBACK_FAMILY, FontDb, FontFace, FontMatch, SHIPPORI_MINCHO_REGULAR, style_weight, system_font_dirs};
-pub use fontdb::{FALLBACK_FAMILY, FontDb, FontFace, style_weight, system_font_dirs};
++pub use fontdb::{FALLBACK_FAMILY, FontDb, FontFace, FontMatch, style_weight, system_font_dirs};
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
pub use layout::{layout, layout_with};
pub use vectorcraft_doc::TextObject;