Merge pull request #792 from dotCooCoo/feat/missing-fonts

Fonts: missing fonts are listed when a document opens, with Find Fonts and a folder search
This commit is contained in:
BFlat authored and GitHub committed 2026-10-10 09:18:20 +07:00
commit 6fed61b4db
41 files changed
+4735 -51

No files matched your search

+1 -1
View File
@@ -163,7 +163,7 @@ grade by behaviour against `plan/illustrator/`, not by whether a menu item exist
- **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. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite, and those apps and font managers register with CoreText on macOS (#579).
- **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. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite, and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`).
- **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 (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465).
- SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, 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). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask.
+4
View File
@@ -41,6 +41,9 @@ macro_rules! out {
#[path = "../../vectorcraft/src/mac_fonts.rs"]
mod mac_fonts;
mod perf;
/// The desktop app's settings folder, shared: exports and MCP read the same Fonts folder.
#[path = "../../vectorcraft/src/prefs_dir.rs"]
mod prefs_dir;
/// The desktop app's DirectWrite font lister, shared: exports and MCP find the same fonts.
#[cfg(all(windows, not(target_vendor = "win7")))]
#[path = "../../vectorcraft/src/system_fonts.rs"]
@@ -110,6 +113,7 @@ fn main() -> ExitCode {
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
prefs_dir::install_fonts();
let args: Vec<String> = std::env::args().skip(1).collect();
let r = match args.first().map(String::as_str) {
Some("mcp") => mcp(&args[1..]),
+5 -16
View File
@@ -28,6 +28,7 @@ mod mac_fonts;
mod mac_menu;
#[cfg(target_os = "macos")]
mod open_documents;
mod prefs_dir;
mod printing;
#[cfg(all(windows, not(target_vendor = "win7")))]
mod system_fonts;
@@ -141,27 +142,13 @@ fn discard_marked_text() {
/// Where UI preferences live: ~/Library/Application Support/VectorCraft (macOS),
/// %APPDATA%\VectorCraft (Windows), $XDG_CONFIG_HOME or ~/.config/vectorcraft (Linux).
fn prefs_path() -> Option<std::path::PathBuf> {
prefs_path_for("VectorCraft", "vectorcraft")
prefs_dir::prefs_path_for("VectorCraft", "vectorcraft")
}
/// The same place under the project's former name (DrawCraft): read once if there are no
/// VectorCraft preferences yet, so settings survive the rename.
fn legacy_prefs_path() -> Option<std::path::PathBuf> {
prefs_path_for("DrawCraft", "drawcraft")
}
fn prefs_path_for(name: &str, lower: &str) -> Option<std::path::PathBuf> {
let base = if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support").join(name))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join(name))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join(lower))
};
base.map(|b| b.join("ui.json"))
prefs_dir::prefs_path_for("DrawCraft", "drawcraft")
}
/// Where the log files live: `logs` in the preferences folder (see `logging`).
@@ -397,6 +384,8 @@ fn main() -> std::process::ExitCode {
system_fonts::install();
#[cfg(target_os = "macos")]
mac_fonts::install();
// VectorCraft's own Fonts folder, which text.addFontFiles copies fonts into.
prefs_dir::install_fonts();
let mut control_port: Option<u16> = std::env::var("VECTORCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut in_window_menus = std::env::var_os("VECTORCRAFT_IN_WINDOW_MENUS").is_some_and(|v| !v.is_empty() && v != "0");
+45
View File
@@ -0,0 +1,45 @@
//! Where VectorCraft keeps its settings, `ui.json`, and next to it folders of the user's own
//! (Swatches, Graphic Styles, Fonts, Data Recovery, logs). The desktop app and `vectorcraft-cli`
//! (which shares this file) read the same Fonts folder.
use std::path::PathBuf;
/// The settings file `ui.json` of the app `name`: in a folder named `name` in ~/Library/Application
/// Support (macOS) or %APPDATA% (Windows), or `lower` in $XDG_CONFIG_HOME or ~/.config (Linux and
/// BSD).
pub fn prefs_path_for(name: &str, lower: &str) -> Option<PathBuf> {
let base = if cfg!(target_os = "macos") {
std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join("Library/Application Support").join(name))
} else if cfg!(windows) {
std::env::var_os("APPDATA").map(|a| std::path::PathBuf::from(a).join(name))
} else {
std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".config")))
.map(|c| c.join(lower))
};
base.map(|b| b.join("ui.json"))
}
/// Have the font scans read VectorCraft's own Fonts folder, next to the settings, which
/// `text.addFontFiles` copies font files into. The folder is set whether or not
/// `VECTORCRAFT_NO_PREFS` is set, as the Swatches and Graphic Styles folders are.
pub fn install_fonts() {
if let Some(dir) = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts"))) {
vectorcraft_text::set_app_font_dir(dir);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_font_scans_read_the_fonts_folder_next_to_the_settings() {
install_fonts();
let fonts = prefs_path_for("VectorCraft", "vectorcraft").and_then(|p| Some(p.parent()?.join("Fonts")));
assert!(fonts.is_some(), "a home folder to keep the settings in");
assert_eq!(vectorcraft_text::app_font_dir().map(std::path::Path::to_path_buf), fonts);
assert!(vectorcraft_text::system_font_dirs().contains(&fonts.unwrap_or_default()));
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Looking through a folder the user picks, and its subfolders, for files of some kind, on separate
//! threads: up to 8 walker threads share one stack of folders and list each folder once. They
//! follow no links and don't enter other apps' or the system's folders, hidden folders or folders
//! whose contents aren't on the disk ([`Rules`]); the time, the entries listed, the folders queued,
//! the depth and the files read are capped ([`Limits`]). [`start`] returns at once,
//! [`Search::progress`] reports where a search stands and [`Search::stop`] ends it. A search reads
//! the files [`Visitor::wants`] accepts by their names and [`Visitor::worth_reading`] by the files
//! themselves, and keeps those [`Visitor::items`] gives wanted items for.
//! The web has no file system: [`start`] fails there.
mod rules;
#[cfg(test)]
mod tests;
mod walk;
pub use rules::{Rules, plain};
pub use walk::{End, Limits, Progress, Search, Visitor, start, threads};
+409
View File
@@ -0,0 +1,409 @@
//! Where a folder search goes: not into other apps' or the system's folders. They are told by
//! their names and places (an app package, a home folder's `Library` or `AppData`, the system
//! folders at the root of a volume), never by the name of an app. Names and paths compare in
//! lowercase.
use std::path::{Component, Path, PathBuf};
/// Extensions of the packages apps and media libraries keep their files in.
const PACKAGE_EXTENSIONS: &[&str] = &[
"app",
"appex",
"bundle",
"component",
"fcpbundle",
"framework",
"imovielibrary",
"kext",
"musiclibrary",
"photolibrary",
"photoslibrary",
"plugin",
"tvlibrary",
"xpc",
];
/// The folders Windows installs programs and keeps their data and the system's in, wherever they
/// are.
const INSTALL_FOLDERS: &[&str] =
&["program files", "program files (x86)", "program files (arm)", "programdata", "$recycle.bin", "system volume information"];
/// The folders a home folder keeps apps and their data in (besides its hidden ones).
const HOME_APP_FOLDERS: &[&str] = &["library", "appdata", "applications", "snap"];
/// The folders a `Library` folder keeps apps' data in (macOS).
const LIBRARY_APP_FOLDERS: &[&str] = &["application support", "containers", "group containers", "caches", "preferences"];
/// The folders beside the home folders that apps share (macOS `Shared`, Windows `Public`).
const SHARED_FOLDERS: &[&str] = &["shared", "public"];
/// The system's folders at the root of a macOS volume (or a copy of one).
const MAC_SYSTEM: &[&str] =
&["applications", "bin", "cores", "dev", "etc", "home", "library", "net", "network", "opt", "private", "sbin", "system", "tmp", "usr", "var"];
/// The system's folders at the root of a Linux or BSD system (or a copy of one).
const UNIX_SYSTEM: &[&str] = &[
"bin",
"boot",
"dev",
"efi",
"etc",
"gnu",
"lib",
"lib32",
"lib64",
"libx32",
"lost+found",
"nix",
"opt",
"proc",
"root",
"run",
"sbin",
"snap",
"sys",
"usr",
"var",
];
/// The system's folders at the root of a Windows drive (or a copy of one), besides the install
/// folders.
const WINDOWS_SYSTEM: &[&str] =
&["windows", "windows.old", "recovery", "perflogs", "boot", "config.msi", "msocache", "$windows.~bt", "$windows.~ws", "$winreagent", "$sysreset"];
/// The most entries of a folder read to tell what kind of folder it is.
const MAX_SIBLINGS: usize = 100_000;
/// The names of the folders that show a folder is the root of a system ([`system_folders`]).
const SYSTEM_SIGNS: &[&str] = &["users", "system", "library", "applications", "windows", "program files", "etc", "usr", "bin", "sbin"];
/// Which of [`SYSTEM_SIGNS`] are among the names of a folder's folders and links.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Siblings(u16);
impl Siblings {
/// The folders and links named `names` (in any case).
#[cfg(test)]
pub(crate) fn of(names: &[&str]) -> Self {
let mut s = Self::default();
names.iter().for_each(|n| s.note(n));
s
}
/// Note a folder or link named `name` (in any case).
pub(crate) fn note(&mut self, name: &str) {
if let Some(i) = SYSTEM_SIGNS.iter().position(|s| s.eq_ignore_ascii_case(name)) {
self.0 |= 1 << i;
}
}
/// Whether a folder or link named `name`, one of [`SYSTEM_SIGNS`], was noted.
fn has(self, name: &str) -> bool {
SYSTEM_SIGNS.iter().position(|s| *s == name).is_some_and(|i| self.0 & (1 << i) != 0)
}
}
/// Why a search may not start in a folder ([`Rules::refusal`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Refusal {
/// The folder is in other apps' or the system's folders, or in an app package.
Apps,
/// The folder is in the Shared or Public folder of a `Users` folder.
Shared,
}
/// A folder a walk lists, as the rules see it ([`Rules::listed`]).
pub(crate) struct Listed {
/// The folder, in lowercase.
dir: PathBuf,
/// Its name, in lowercase.
name: String,
/// The system folders in it, when it is the root of a system.
system: Option<&'static [&'static str]>,
/// It is a home folder.
home: bool,
}
/// Where a search may go.
#[derive(Clone, Debug, Default)]
pub struct Rules {
/// The home folder (canonical).
pub home: Option<PathBuf>,
/// Folders searched when picked, whatever holds them (canonical): the temporary folders, and
/// tests' folders.
pub user_content: Vec<PathBuf>,
/// Other apps' and the system's folders the environment names (canonical): never entered, and a
/// search of a folder inside one fails.
pub refused: Vec<PathBuf>,
}
/// `path` in lowercase and, on Windows, without its `\\?\` prefix ([`unprefixed`]), for comparing
/// paths.
fn lower(path: &Path) -> PathBuf {
let text = path.to_string_lossy();
let plain = if cfg!(windows) { unprefixed(&text) } else { None };
PathBuf::from(plain.as_deref().unwrap_or(&text).to_lowercase())
}
/// The system's folders a volume's root holds, when its folders (`siblings`) show it is the root of
/// an operating system.
fn system_folders(siblings: Siblings) -> Option<&'static [&'static str]> {
let has = |name: &str| siblings.has(name);
if has("users") && (has("system") || has("library") || has("applications")) {
Some(MAC_SYSTEM)
} else if has("windows") && (has("users") || has("program files")) {
Some(WINDOWS_SYSTEM)
} else if has("etc") && has("usr") && (has("bin") || has("sbin")) {
Some(UNIX_SYSTEM)
} else {
None
}
}
/// What the names of the folders and links in `dir` show ([`Siblings`]).
fn folder_siblings(dir: &Path) -> Siblings {
let mut siblings = Siblings::default();
for e in std::fs::read_dir(dir).into_iter().flatten().take(MAX_SIBLINGS).flatten() {
let name = e.file_name();
if let Some(name) = name.to_str()
&& e.file_type().is_ok_and(|t| t.is_dir() || t.is_symlink())
{
siblings.note(name);
}
}
siblings
}
/// The first `n` components of `path`.
fn prefix(path: &Path, n: usize) -> PathBuf {
path.components().take(n).collect()
}
/// `path` without the `\\?\` prefix that `std::fs::canonicalize` gives paths on Windows: `C:\…`
/// for `\\?\C:\…` and `\\server\share\…` for `\\?\UNC\server\share\…`, when every name in it can
/// be written without the prefix ([`without_verbatim`]). Other paths, and paths on other systems,
/// are returned as they are.
pub fn plain(path: PathBuf) -> PathBuf {
if !cfg!(windows) {
return path;
}
match path.to_str().and_then(without_verbatim) {
Some(p) => PathBuf::from(p),
None => path,
}
}
/// The Windows path `p` without its `\\?\` prefix, when it has one for a drive or a share: `C:\…`
/// for `\\?\C:\…` and `\\server\…` for `\\?\UNC\server\…`.
pub(crate) fn unprefixed(p: &str) -> Option<String> {
if let Some(unc) = p.strip_prefix(r"\\?\UNC\") {
return Some(format!(r"\\{unc}"));
}
let disk = p.strip_prefix(r"\\?\")?;
matches!(disk.as_bytes(), [d, b':', b'\\', ..] if d.is_ascii_alphabetic()).then(|| disk.to_string())
}
/// [`unprefixed`], when each name in the path can be written without the prefix ([`portable`]):
/// a share's server and share names, and the names below a drive's root or a share.
pub(crate) fn without_verbatim(p: &str) -> Option<String> {
let plain = unprefixed(p)?;
let (names, at_least) = match plain.strip_prefix(r"\\") {
Some(unc) => (unc, 2),
None => (plain.get(3..)?, 0),
};
let mut names: Vec<&str> = if names.is_empty() { vec![] } else { names.split('\\').collect() };
// A trailing separator.
if names.len() > at_least && names.last() == Some(&"") {
names.pop();
}
let ok = names.len() >= at_least && names.iter().all(|n| portable(n));
ok.then_some(plain)
}
/// Whether `name` can be a name in a Windows path without the `\\?\` prefix: not `.` or `..`, not
/// ending in a dot or a space, without `<>:"/\|?*` or control characters, and not a device name
/// (`CON`, `PRN`, `AUX`, `NUL`, `COM0` to `COM9`, `LPT0` to `LPT9`, these with a superscript digit,
/// `CONIN$`, `CONOUT$`), with an extension or not.
fn portable(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name).trim_end().to_ascii_lowercase();
let numbered = |device: &str| {
stem.strip_prefix(device).is_some_and(|n| {
let mut n = n.chars();
n.next().is_some_and(|c| c.is_ascii_digit() || "¹²³".contains(c)) && n.next().is_none()
})
};
let device = ["con", "prn", "aux", "nul", "conin$", "conout$"].contains(&stem.as_str()) || numbered("com") || numbered("lpt");
!name.is_empty()
&& name != "."
&& name != ".."
&& !name.ends_with(['.', ' '])
&& !name.chars().any(|c| c < ' ' || "<>:\"/\\|?*".contains(c))
&& !device
}
impl Rules {
/// This computer's: the home folder, the temporary folders, and the app and system folders the
/// environment names.
pub fn system() -> Self {
let canonical = |p: PathBuf| p.is_absolute().then(|| std::fs::canonicalize(&p).ok()).flatten();
let var = |name: &str| std::env::var_os(name).map(PathBuf::from).and_then(canonical);
let home = var(if cfg!(windows) { "USERPROFILE" } else { "HOME" });
let user_content = [std::env::temp_dir(), PathBuf::from("/tmp")].into_iter().filter_map(canonical).collect();
let names: &[&str] = if cfg!(windows) {
&["APPDATA", "LOCALAPPDATA", "ProgramData", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "SystemRoot"]
} else {
&[
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_CACHE_HOME",
"XDG_STATE_HOME",
"HOST_XDG_CONFIG_HOME",
"HOST_XDG_DATA_HOME",
"HOST_XDG_CACHE_HOME",
"HOST_XDG_STATE_HOME",
]
};
let refused = names.iter().filter_map(|n| var(n)).collect();
Rules { home, user_content, refused }
}
/// Whether `dir` is a home folder: the home folder, a folder in a `Users` or `home` folder, or
/// a folder the Flatpak document portal exports (`/run/user/<uid>/doc/<id>/<name>`).
fn is_home(&self, dir: &Path) -> bool {
if self.home.as_ref().is_some_and(|h| lower(h) == lower(dir)) {
return true;
}
let above = dir.parent().and_then(Path::file_name).map(|n| n.to_string_lossy().to_lowercase());
if matches!(above.as_deref(), Some("users" | "home")) {
return true;
}
let parts: Vec<String> = dir.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
matches!(parts.as_slice(), [_, run, user, uid, doc, _, _] if run == "run" && user == "user" && is_number(uid) && doc == "doc")
}
/// The folder `dir`, whose folders show `siblings`, as the rules see it when a walk lists it:
/// told once for all the folders in it.
pub(crate) fn listed(&self, dir: &Path, siblings: Siblings) -> Listed {
Listed {
dir: lower(dir),
name: dir.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default(),
system: system_folders(siblings),
home: self.is_home(dir),
}
}
/// Whether a search never enters the folder `name` in the listed folder `parent`: an app's
/// package, a Windows install folder, a system folder at the root of a volume, the folders apps
/// share beside the home folders, a `Library` folder's app data, or a home folder's hidden
/// folders and app folders.
pub(crate) fn never_in(&self, parent: &Listed, name: &str) -> bool {
let name = name.to_lowercase();
let name = name.as_str();
if Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| PACKAGE_EXTENSIONS.contains(&e)) || INSTALL_FOLDERS.contains(&name) {
return true;
}
if parent.system.is_some_and(|system| system.contains(&name)) {
return true;
}
match parent.name.as_str() {
"users" if SHARED_FOLDERS.contains(&name) => return true,
"library" if LIBRARY_APP_FOLDERS.contains(&name) => return true,
_ => {}
}
parent.home && (name.starts_with('.') || HOME_APP_FOLDERS.contains(&name))
}
/// [`Self::never_in`] the folder `parent`, whose folders show `siblings`.
#[cfg(test)]
pub(crate) fn never(&self, parent: &Path, siblings: Siblings, name: &str) -> bool {
self.never_in(&self.listed(parent, siblings), name)
}
/// The home folder, when the listed folder `parent` is the root of a system whose rules skip
/// the folder the home folder is in (`/usr/home/me` on FreeBSD, `/var/home/me`): a walk of the
/// root reaches it this way.
pub(crate) fn home_below(&self, parent: &Listed) -> Option<PathBuf> {
let home = self.home.as_ref()?;
let system = parent.system?;
let below = lower(home).strip_prefix(&parent.dir).ok()?.components().next()?.as_os_str().to_string_lossy().into_owned();
system.contains(&below.as_str()).then(|| home.clone())
}
/// Whether `path` is one of the refused folders.
pub(crate) fn is_refused(&self, path: &Path) -> bool {
let path = lower(path);
self.refused.iter().any(|r| lower(r) == path)
}
/// The folders that hold user content whatever holds them, as far as they hold `folder`: the
/// home folder, [`Self::user_content`], the cloud storage folders in the home folder's
/// `Library` (an app's own iCloud `Documents` folder too), removable media and a user's runtime
/// folder on Linux (network shares, the document portal).
fn bases(&self, folder: &Path) -> Vec<PathBuf> {
let mut v = self.user_content.clone();
let lowered = lower(folder);
if let Some(home) = &self.home {
v.push(home.clone());
let library = home.join("Library");
v.push(library.join("CloudStorage"));
let mobile = library.join("Mobile Documents");
v.push(mobile.join("com~apple~CloudDocs"));
let depth = mobile.components().count();
if lowered.starts_with(lower(&mobile)) && lowered.components().nth(depth + 1).is_some_and(|c| c.as_os_str() == "documents") {
v.push(prefix(folder, depth + 2));
}
}
v.push(PathBuf::from("/run/media"));
let parts: Vec<String> = folder.components().take(4).map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
if matches!(parts.as_slice(), [_, run, user, uid] if run == "run" && user == "user" && is_number(uid)) {
v.push(prefix(folder, 4));
}
v
}
/// Why a search may not start in `folder` (canonical), or `None` when it may: the deepest base
/// ([`Self::bases`]) or refused folder that holds it is a refused one, or a folder below that
/// base (or below the root, without one) is one a walk doesn't enter.
pub(crate) fn refusal(&self, folder: &Path) -> Option<Refusal> {
self.refusal_with(folder, folder_siblings)
}
/// [`Self::refusal`] without listing a folder: the root of a system, told by the folders it
/// holds, isn't recognized.
pub(crate) fn refusal_unlisted(&self, folder: &Path) -> Option<Refusal> {
self.refusal_with(folder, |_| Siblings::default())
}
/// [`Self::refusal`], with `siblings` telling what a folder's folders show.
fn refusal_with(&self, folder: &Path, siblings: impl Fn(&Path) -> Siblings) -> Option<Refusal> {
let lowered = lower(folder);
let held = |p: &PathBuf| lowered.starts_with(lower(p)).then(|| p.components().count());
let base = self.bases(folder).iter().filter_map(held).max();
let refused = self.refused.iter().filter_map(held).max();
let start = match (base, refused) {
(_, Some(r)) if base.is_none_or(|b| r >= b) => return Some(Refusal::Apps),
(Some(b), _) => b,
// From the root of the folder's volume.
(None, _) => folder.components().take_while(|c| matches!(c, Component::Prefix(_) | Component::RootDir)).count(),
};
let mut parent = prefix(folder, start);
for c in folder.components().skip(start) {
let child = parent.join(c);
let listed = self.listed(&parent, siblings(&parent));
let name = c.as_os_str().to_string_lossy().to_lowercase();
if listed.name == "users" && SHARED_FOLDERS.contains(&name.as_str()) {
return Some(Refusal::Shared);
}
if self.never_in(&listed, &name) || self.is_refused(&child) {
return Some(Refusal::Apps);
}
parent = child;
}
None
}
}
/// Whether `s` is a number (a user id).
fn is_number(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
+545
View File
@@ -0,0 +1,545 @@
//! The folder search: where it goes and where it doesn't, its limits, its threads.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use super::rules::{Siblings, unprefixed, without_verbatim};
use super::walk::{Pool, start_in};
use super::*;
/// The walker threads of these tests' searches, apart from the searches of other tests.
static TESTS: Pool = Pool::new(32);
/// [`start`] on the threads of [`TESTS`].
fn begin(folder: PathBuf, rules: Rules, limits: Limits, threads: usize, items: usize, visitor: Arc<dyn Visitor>) -> Search {
start_in(&TESTS, folder, Some(rules), limits, threads, items, visitor).unwrap()
}
/// Reads `.ttf` files; each is the item its name is in the list.
struct Names(&'static [&'static str]);
impl Visitor for Names {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn items(&self, path: &Path) -> Vec<usize> {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
self.0.iter().position(|n| *n == name).into_iter().collect()
}
}
/// Reads every file, and waits on reading one until its channel sends or closes.
struct Blocked(Mutex<mpsc::Receiver<()>>);
impl Visitor for Blocked {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let _ = self.0.lock().unwrap().recv();
vec![]
}
}
/// A fresh folder (canonical, as a search reports it) holding `paths`: files, and folders where
/// they end in `/`.
fn tree(tag: &str, paths: &[&str]) -> PathBuf {
let root = vectorcraft_testkit::temp_dir(&format!("findfiles-{tag}"));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
for p in paths {
let path = root.join(p);
if p.ends_with('/') {
std::fs::create_dir_all(&path).unwrap();
} else {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, b"font").unwrap();
}
}
plain(std::fs::canonicalize(&root).unwrap())
}
/// The rules of a search of `root`: its `Users/me` is the home folder, `refused` an app's folder.
fn rules(root: &Path) -> Rules {
Rules { home: Some(root.join("Users/me")), user_content: vec![root.to_path_buf()], refused: vec![root.join("refused")] }
}
/// The search's progress once it ended (or after 10 seconds).
fn wait(s: &Search) -> Progress {
let until = Instant::now() + Duration::from_secs(10);
loop {
let p = s.progress();
if p.end.is_some() || Instant::now() > until {
return p;
}
std::thread::sleep(Duration::from_millis(2));
}
}
/// Search `from` in `root` for the files named `names`, to the end.
fn search(root: &Path, from: &str, limits: Limits, threads: usize, names: &'static [&'static str]) -> Progress {
let s = begin(root.join(from), rules(root), limits, threads, names.len(), Arc::new(Names(names)));
wait(&s)
}
/// The files a search found, relative to `root`, sorted.
fn found(root: &Path, p: &Progress) -> Vec<String> {
let mut v: Vec<String> = p.hits.iter().map(|(f, _)| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/")).collect();
v.sort();
v
}
#[test]
fn the_walk_stays_out_of_other_apps_and_the_systems_folders() {
let root = tree(
"roles",
&[
"a/b/c/one.ttf",
"Users/me/Documents/two.ttf",
"Disk/Fonts/four.ttf",
"Disk/Users/you/Documents/four.ttf",
// Never entered: each of these folders counts as skipped once.
"Program Files/x/three.ttf",
"Program Files (Arm)/x/three.ttf",
"Users/me/Library/Fonts/three.ttf",
"Users/me/.cache/three.ttf",
"Users/me/AppData/Roaming/three.ttf",
"Users/you/snap/three.ttf",
"Users/Shared/x/three.ttf",
"Pictures/P.photoslibrary/three.ttf",
"Tools/Foo.app/Contents/three.ttf",
"Copy/Library/Application Support/x/three.ttf",
".hidden/three.ttf",
"refused/three.ttf",
"Disk/System/Library/Fonts/three.ttf",
"Disk/Library/Fonts/three.ttf",
"Disk/Applications/three.ttf",
"Disk/Users/you/Library/three.ttf",
],
);
let p = search(&root, "", Limits::default(), 3, &["one.ttf", "two.ttf", "three.ttf", "four.ttf"]);
assert_eq!(p.end, Some(End::Done));
assert_eq!(found(&root, &p), ["Disk/Fonts/four.ttf", "Disk/Users/you/Documents/four.ttf", "Users/me/Documents/two.ttf", "a/b/c/one.ttf"]);
assert_eq!(p.skipped, 16);
assert_eq!((p.read, p.unreadable), (4, 0));
}
#[test]
fn a_picked_folder_inside_other_apps_folders_is_refused() {
let root = tree(
"picks",
&[
"Users/me/Library/Fonts/",
"Users/me/Library/CloudStorage/Box/F/",
"Users/me/Library/Mobile Documents/x~y/Documents/",
"Users/me/Library/Mobile Documents/x~y/Other/",
"Users/me/.config/fonts/",
"Users/Shared/x/",
"Disk/Users/",
"Disk/System/",
"Disk/Library/Fonts/",
"Tools/Foo.app/Contents/",
"refused/sub/",
"Program Files/x/",
"Program Files (Arm)/x/",
"Users/Public/x/",
"a/.b/",
"file.ttf",
],
);
for picked in [
"Users/me/Library/Fonts",
"Users/me/Library/Mobile Documents/x~y/Other",
"Users/me/.config/fonts",
"Disk/Library/Fonts",
"Tools/Foo.app/Contents",
"refused",
"refused/sub",
"Program Files/x",
"Program Files (Arm)/x",
] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert_eq!(p.state(), "failed", "{picked}");
assert!(p.error().is_some_and(|e| e.contains("doesn't search other apps' or the system's folders")), "{picked}: {p:?}");
}
for picked in ["Users/Shared/x", "Users/Public/x"] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.contains("doesn't search the Shared or Public folder in Users")), "{picked}: {p:?}");
}
// Cloud folders, a hidden folder of the user's and another system's root are searched when
// picked.
for picked in ["Users/me/Library/CloudStorage/Box/F", "Users/me/Library/Mobile Documents/x~y/Documents", "a/.b", "Disk", "Disk/Users", ""] {
let p = search(&root, picked, Limits::default(), 1, &[]);
assert_eq!((p.state(), p.error()), ("done", None), "{picked}");
}
let p = search(&root, "file.ttf", Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.ends_with("is not a folder")), "{p:?}");
let p = search(&root, "missing", Limits::default(), 1, &[]);
assert!(p.error().is_some_and(|e| e.starts_with(&root.join("missing").display().to_string())), "{p:?}");
}
#[test]
fn the_search_ends_at_its_limits_and_when_stopped() {
let root = tree("limits", &["one.ttf", "two.ttf", "a/b/c/three.ttf", "x/y.txt"]);
let names = &["one.ttf", "two.ttf", "three.ttf", "nowhere.ttf"];
// The picked folder and the folders in it are listed, not the ones below them.
let p = search(&root, "", Limits { depth: 1, ..Limits::default() }, 2, names);
assert_eq!(p.end, Some(End::Done));
assert_eq!(found(&root, &p), ["one.ttf", "two.ttf"]);
assert_eq!((p.folders, p.skipped), (3, 1));
let p = search(&root, "", Limits { entries: 3, ..Limits::default() }, 1, names);
assert_eq!((p.state(), p.stopped()), ("stopped", Some("limit")));
let p = search(&root, "", Limits { files: 1, ..Limits::default() }, 1, names);
assert_eq!((p.stopped(), p.read), (Some("limit"), 1));
let p = search(&root, "", Limits { hits: 1, ..Limits::default() }, 1, names);
assert_eq!((p.stopped(), p.hits.len()), (Some("limit"), 1));
// Each item keeps at most `per_item` files.
let root = tree("per-item", &["a/one.ttf", "b/one.ttf", "c/one.ttf"]);
let p = search(&root, "", Limits { per_item: 2, ..Limits::default() }, 1, &["one.ttf", "nowhere.ttf"]);
assert_eq!((p.end, p.hits.len(), p.read), (Some(End::Done), 2, 3));
}
#[test]
fn the_search_answers_at_its_deadline_while_a_walker_is_blocked() {
let root = tree("blocked", &["f.ttf"]);
let (tx, rx) = mpsc::channel();
let s = begin(root.clone(), rules(&root), Limits { seconds: 0.2, ..Limits::default() }, 1, 1, Arc::new(Blocked(Mutex::new(rx))));
std::thread::sleep(Duration::from_millis(300));
let p = s.progress();
assert_eq!((p.state(), p.stopped()), ("stopped", Some("time")), "{p:?}");
assert!(p.seconds >= 0.2 && p.seconds < 5.0, "{p:?}");
let (tx2, rx2) = mpsc::channel();
let s2 = begin(root.clone(), rules(&root), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx2))));
let until = Instant::now() + Duration::from_secs(10);
while s2.progress().read == 0 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(s2.progress().state(), "searching");
s2.stop();
assert_eq!(s2.progress().stopped(), Some("stop"));
drop((tx, tx2));
}
/// Every file is item 0; reading the second file waits until the channel closes.
struct SecondBlocks(Mutex<(usize, mpsc::Receiver<()>)>);
impl Visitor for SecondBlocks {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let mut read = self.0.lock().unwrap();
read.0 += 1;
if read.0 == 2 {
let _ = read.1.recv();
}
vec![0]
}
}
/// A file is kept as soon as it is read: progress shows it while the rest of its folder is read,
/// and a search that stops or reaches a limit keeps it.
#[test]
fn files_found_are_kept_as_they_are_read() {
let root = tree("kept", &["a.ttf", "b.ttf", "c.ttf"]);
let (tx, rx) = mpsc::channel();
let s = begin(root.clone(), rules(&root), Limits::default(), 1, 2, Arc::new(SecondBlocks(Mutex::new((0, rx)))));
let until = Instant::now() + Duration::from_secs(10);
while s.progress().read < 2 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
let p = s.progress();
assert_eq!((p.state(), p.hits.len()), ("searching", 1), "{p:?}");
s.stop();
drop(tx);
let p = wait(&s);
assert_eq!(p.stopped(), Some("stop"));
assert!(!p.hits.is_empty(), "{p:?}");
let p = search(&root, "", Limits { files: 2, ..Limits::default() }, 1, &["a.ttf", "b.ttf", "c.ttf", "nowhere.ttf"]);
assert_eq!((p.stopped(), p.hits.len()), (Some("limit"), 2), "{p:?}");
}
#[test]
fn the_search_ends_once_every_item_has_a_file() {
let root = tree("found", &["a/one.ttf", "b/two.ttf", "c/d/e/f/g/other.ttf"]);
let p = search(&root, "", Limits::default(), 2, &["one.ttf", "two.ttf"]);
assert_eq!((p.end.clone(), found(&root, &p)), (Some(End::Found), vec!["a/one.ttf".to_string(), "b/two.ttf".into()]));
}
#[test]
fn one_walker_and_eight_find_the_same_files_and_every_search_ends() {
let mut paths = vec![];
for a in 0..6 {
for b in 0..4 {
paths.push(format!("d{a}/e{b}/one.ttf"));
paths.push(format!("d{a}/e{b}/f/two.ttf"));
paths.push(format!("d{a}/e{b}/f/g/skip.txt"));
}
}
let paths: Vec<&str> = paths.iter().map(String::as_str).collect();
let root = tree("threads", &paths);
let limits = Limits { per_item: 100, ..Limits::default() };
let one = search(&root, "", limits, 1, &["one.ttf", "two.ttf", "nowhere.ttf"]);
assert_eq!((one.end.clone(), one.hits.len(), one.folders), (Some(End::Done), 48, 1 + 6 + 24 + 24 + 24));
for round in 0..25 {
for threads in 1..=8 {
let p = search(&root, "", limits, threads, &["one.ttf", "two.ttf", "nowhere.ttf"]);
assert_eq!(p.end, Some(End::Done), "round {round}, {threads} threads");
assert_eq!(found(&root, &p), found(&root, &one), "round {round}, {threads} threads");
}
}
}
/// Fails on `boom.ttf` with a panic: a bug in reading one file.
struct Boom;
impl Visitor for Boom {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn items(&self, path: &Path) -> Vec<usize> {
match path.file_name().and_then(|n| n.to_str()) {
Some("boom.ttf") => panic!("a bug"),
Some("ok.ttf") => vec![0],
_ => vec![1],
}
}
}
#[test]
fn a_visitor_that_panics_on_one_file_does_not_end_the_search() {
// The file beside the one that trips the bug is found too.
let root = tree("boom", &["a/boom.ttf", "a/ok.ttf", "b/c/fine.ttf"]);
let s = begin(root.clone(), rules(&root), Limits::default(), 2, 3, Arc::new(Boom));
let p = wait(&s);
assert_eq!((p.end.clone(), found(&root, &p), p.unreadable), (Some(End::Done), vec!["a/ok.ttf".to_string(), "b/c/fine.ttf".into()], 1));
}
#[cfg(unix)]
#[test]
fn links_are_not_followed_and_unreadable_folders_count() {
use std::os::unix::fs::{PermissionsExt, symlink};
let root = tree("links", &["outside/x.ttf", "inner/locked/y.ttf"]);
let inner = root.join("inner");
symlink(root.join("outside"), inner.join("folder")).unwrap();
symlink(&inner, inner.join("loop")).unwrap();
symlink(root.join("outside/x.ttf"), inner.join("x.ttf")).unwrap();
let locked = inner.join("locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// Where permissions don't hold (root), the folder reads as any other.
let enforced = std::fs::read_dir(&locked).is_err();
let p = search(&root, "inner", Limits::default(), 2, &["x.ttf", "y.ttf"]);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
assert_eq!(p.end, Some(End::Done));
if enforced {
assert!(p.hits.is_empty() && p.unreadable == 1, "{p:?}");
} else {
assert_eq!(found(&root, &p), ["inner/locked/y.ttf"]);
}
// The linked file isn't a file of the folder; y.ttf is one where the locked folder reads.
assert_eq!(p.files, u64::from(!enforced), "{p:?}");
}
#[cfg(unix)]
#[test]
fn a_picked_folder_that_cant_be_listed_fails_the_search() {
use std::os::unix::fs::PermissionsExt;
let root = tree("unlistable", &["locked/y.ttf"]);
let locked = root.join("locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// Where permissions don't hold (root), the folder reads as any other.
let enforced = std::fs::read_dir(&locked).is_err();
let p = search(&root, "locked", Limits::default(), 2, &["y.ttf"]);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
if enforced {
assert!(matches!(&p.end, Some(End::Failed(e)) if e.contains("locked")), "{p:?}");
} else {
assert_eq!(found(&root, &p), ["locked/y.ttf"]);
}
}
#[test]
fn system_roots_and_homes_are_told_by_what_they_hold() {
let r = Rules { home: Some(PathBuf::from("/home/me")), ..Rules::default() };
let never = |parent: &str, siblings: Siblings, name: &str| r.never(Path::new(parent), siblings, name);
let none = Siblings::default();
let mac = Siblings::of(&["Users", "Library", "System", "Applications", "Volumes", "opt"]);
for name in ["Library", "System", "Applications", "opt", "private"] {
assert!(never("/", mac, name), "{name}");
}
for name in ["Users", "Volumes", "Fonts"] {
assert!(!never("/", mac, name), "{name}");
}
let unix = Siblings::of(&["usr", "etc", "bin", "home", "nix", "srv", "data", "mnt"]);
for name in ["usr", "etc", "bin", "nix", "var", "proc"] {
assert!(never("/", unix, name), "{name}");
}
for name in ["home", "srv", "data", "mnt", "media"] {
assert!(!never("/", unix, name), "{name}");
}
let windows = Siblings::of(&["Windows", "Users", "Program Files", "Data"]);
for name in ["Windows", "Program Files", "Recovery"] {
assert!(never("C:\\", windows, name), "{name}");
}
for name in ["Data", "Users"] {
assert!(!never("C:\\", windows, name), "{name}");
}
// A project that holds a bin and an etc folder isn't the root of a system.
let project = Siblings::of(&["bin", "etc", "src"]);
assert!(!never("/work/p", project, "bin") && !never("/work/p", project, "etc"));
// Home folders: the home folder, and every folder in a Users or home folder.
for name in ["Library", ".config", "snap", "AppData", "Applications"] {
assert!(never("/home/me", none, name), "{name}");
assert!(never("/Users/you", none, name), "{name}");
}
assert!(!never("/home/me", none, "Documents") && !never("/home/me/Documents", none, "Library"));
assert!(never("/run/user/1000/doc/a1b2/me", none, "snap"), "a folder the document portal exports");
assert!(never("/Users", none, "Shared") && never("/Users", none, "Public"));
assert!(never("/Volumes/Copy/Library", none, "Application Support") && !never("/Volumes/Copy/Library", none, "Fonts"));
assert!(never("/x", none, "Foo.app") && never("/x", none, "Program Files (x86)") && !never("/x", none, "Fonts.d"));
assert!(never("/x", none, "Program Files (Arm)"));
// A system root's walk reaches a home folder below a folder it skips (FreeBSD's /usr/home).
let bsd = Rules { home: Some(PathBuf::from("/usr/home/me")), ..Rules::default() };
let root = Path::new("/");
assert_eq!(bsd.home_below(&bsd.listed(root, unix)), Some(PathBuf::from("/usr/home/me")));
assert_eq!(r.home_below(&r.listed(root, unix)), None);
assert_eq!(bsd.home_below(&bsd.listed(root, project)), None);
}
#[test]
fn a_search_starts_with_the_threads_left_and_fails_when_none_is() {
static POOL: Pool = Pool::new(3);
let root = tree("pool", &["f.ttf"]);
let blocked = || {
let (tx, rx) = mpsc::channel();
(tx, Arc::new(Blocked(Mutex::new(rx))) as Arc<dyn Visitor>)
};
let (tx_a, a) = blocked();
let (tx_b, b) = blocked();
let a = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 2, 1, a).unwrap();
let b = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 4, 1, b).unwrap();
assert_eq!(POOL.live(), 3);
let (_, c) = blocked();
let c = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 1, 1, c);
assert_eq!(c.err().as_deref(), Some("the search couldn't start: try again in a moment"));
drop((tx_a, tx_b));
assert_eq!((wait(&a).end, wait(&b).end), (Some(End::Done), Some(End::Done)));
let until = Instant::now() + Duration::from_secs(10);
while POOL.live() > 0 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(POOL.live(), 0, "every walker thread ended");
let s = start_in(&POOL, root.clone(), Some(rules(&root)), Limits::default(), 8, 1, Arc::new(Names(&[]))).unwrap();
assert_eq!(wait(&s).end, Some(End::Done));
}
#[test]
fn a_search_takes_the_cpus_the_renderer_leaves_from_two_to_eight() {
use super::walk::threads_for;
assert_eq!([threads_for(64, 4), threads_for(12, 4), threads_for(4, 4), threads_for(1, 0)], [8, 7, 2, 2]);
assert!((2..=8).contains(&threads()));
}
/// A folder holding more folders than a search queues ends the search while it is being listed.
#[test]
fn a_folder_with_more_folders_than_the_search_queues_ends_it_as_it_is_listed() {
// Folders and files made in turns: whatever order a file system lists them in, about half of a
// folder's first entries are folders.
let names: Vec<String> = (0..2048).flat_map(|i| [format!("d{i}/"), format!("f{i}.txt")]).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
let root = tree("many-folders", &names);
let p = search(&root, "", Limits { folders: 10, ..Limits::default() }, 1, &[]);
assert_eq!(p.end, Some(End::Limit));
assert!(p.files < 2048, "the folder was listed to its end: {p:?}");
}
/// Wants every file, counting the files it is asked about.
struct Counted(AtomicUsize);
impl Visitor for Counted {
fn wants(&self, _: &str) -> bool {
self.0.fetch_add(1, Ordering::Relaxed);
true
}
fn items(&self, _: &Path) -> Vec<usize> {
vec![]
}
}
/// A folder's files past those the search reads aren't kept to be read.
#[test]
fn files_past_those_the_search_reads_are_not_kept() {
let names: Vec<String> = (0..50).map(|i| format!("f{i}.ttf")).collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
let root = tree("many-files", &names);
let counted = Arc::new(Counted(AtomicUsize::new(0)));
let p = wait(&begin(root.clone(), rules(&root), Limits { files: 3, ..Limits::default() }, 1, 1, counted.clone()));
assert_eq!((p.stopped(), p.read, p.files), (Some("limit"), 3, 50), "{p:?}");
assert_eq!(counted.0.load(Ordering::Relaxed), 4, "one more than the files read");
}
/// Wants `.ttf` files by their names, turns down those whose names start with `skip` by the file,
/// and finds `font.ttf`.
struct Picky;
impl Visitor for Picky {
fn wants(&self, name: &str) -> bool {
name.ends_with(".ttf")
}
fn worth_reading(&self, path: &Path) -> bool {
!path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("skip"))
}
fn items(&self, path: &Path) -> Vec<usize> {
if path.ends_with("font.ttf") { vec![0] } else { vec![] }
}
}
/// Files a visitor turns down by the file itself aren't read and don't count among the files
/// read: with room to read one file, the search gets past them to the font in the folder below.
#[test]
fn files_turned_down_by_the_file_are_not_read() {
let root = tree("turned-down", &["skip1.ttf", "skip2.ttf", "skip3.ttf", "sub/font.ttf"]);
let p = wait(&begin(root.clone(), rules(&root), Limits { files: 1, ..Limits::default() }, 1, 1, Arc::new(Picky)));
assert_eq!((p.end.clone(), p.read, found(&root, &p)), (Some(End::Found), 1, vec!["sub/font.ttf".to_string()]), "{p:?}");
}
/// Windows paths lose the `\\?\` prefix `canonicalize` gives them where they read the same
/// without it. Paths compare the same with the prefix and without it.
#[test]
fn windows_paths_lose_the_verbatim_prefix_where_they_read_the_same() {
for (verbatim, without) in [
(r"\\?\C:\Users\me\Fonts", r"C:\Users\me\Fonts"),
(r"\\?\d:\", r"d:\"),
(r"\\?\UNC\server\share\a b\c.otf", r"\\server\share\a b\c.otf"),
(r"\\?\UNC\server\share", r"\\server\share"),
(r"\\?\UNC\server\share\", r"\\server\share\"),
] {
assert_eq!(without_verbatim(verbatim).as_deref(), Some(without), "{verbatim}");
}
// For comparing, any name goes.
assert_eq!(unprefixed(r"\\?\C:\a.\b").as_deref(), Some(r"C:\a.\b"));
assert_eq!(unprefixed(r"\\?\UNC\server").as_deref(), Some(r"\\server"));
assert_eq!((unprefixed(r"\\?\C:"), unprefixed(r"C:\a"), unprefixed("/home/me")), (None, None, None));
for kept in [
r"\\?\C:",
r"\\?\C:\a.\b",
r"\\?\C:\a \b",
r"\\?\C:\CON\b",
r"\\?\C:\a\nul.txt",
r"\\?\C:\a\COM¹",
r"\\?\C:\a/b",
r"\\?\C:\a\..\b",
r"\\?\C:\a\\b",
r"\\?\Volume{00000000-0000-0000-0000-000000000000}\a",
r"\\?\UNC\server",
r"C:\a",
"/home/me",
] {
assert_eq!(without_verbatim(kept), None, "{kept}");
}
if !cfg!(windows) {
assert_eq!(plain(PathBuf::from(r"\\?\C:\a")), PathBuf::from(r"\\?\C:\a"), "other systems' paths stay as they are");
}
}
+666
View File
@@ -0,0 +1,666 @@
//! The walker threads of a folder search and what they share.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
use super::rules::{Refusal, Rules, Siblings, plain};
/// The most walker threads one search starts.
const MAX_THREADS: usize = 8;
/// The most walker threads all searches together have running.
const MAX_LIVE: usize = 32;
/// How often a walker with nothing to do looks again (the deadline, the end).
const IDLE: Duration = Duration::from_millis(50);
/// How many entries of a folder a walker lists between looks at the end, the deadline and the
/// folders waiting to be listed.
const CHECK_EVERY: u64 = 1024;
/// How a search ends when every walker thread stopped on a bug.
const INTERNAL: &str = "every search thread stopped on an internal error (please report this bug)";
/// What a search looks for.
pub trait Visitor: Send + Sync {
/// Whether the regular file named `name` is to be read: asked of the files a folder lists until
/// it has one more of them to read than [`Limits::files`].
fn wants(&self, name: &str) -> bool;
/// Whether the file at `path`, which [`Self::wants`] took by its name, is to be read after all,
/// by what the file itself is. A file turned down here doesn't count among the files read.
fn worth_reading(&self, _path: &Path) -> bool {
true
}
/// The wanted items (indexes below the search's item count) the file at `path` is.
fn items(&self, path: &Path) -> Vec<usize>;
}
/// The caps on a search.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Limits {
/// Seconds before it ends (0 to 3600; 60 when not finite).
pub seconds: f64,
/// Entries listed, in every folder.
pub entries: u64,
/// Folders waiting to be listed.
pub folders: usize,
/// Folders below the picked one.
pub depth: u32,
/// Files read.
pub files: u64,
/// Files kept for each item.
pub per_item: usize,
/// Files kept in all.
pub hits: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { seconds: 60.0, entries: 10_000_000, folders: 1_000_000, depth: 64, files: 10_000, per_item: 10, hits: 1_000 }
}
}
/// How a search ended.
#[derive(Clone, Debug, PartialEq)]
pub enum End {
/// Every folder it could enter was searched.
Done,
/// Every item has a file.
Found,
/// [`Search::stop`].
Stopped,
/// [`Limits::seconds`] passed.
Time,
/// The entries listed, the folders waiting to be listed, the files read or the files kept
/// reached their [`Limits`]. Folders deeper than [`Limits::depth`] are skipped and an item
/// keeps at most [`Limits::per_item`] files, without ending the search.
Limit,
/// It couldn't start: the folder can't be read, isn't a folder or isn't one to search.
Failed(String),
}
/// Where a search stands ([`Search::progress`]).
#[derive(Clone, Debug, Default)]
pub struct Progress {
/// `None` while it runs.
pub end: Option<End>,
/// The folder searched (canonical, through [`plain`]), once it was checked. The walk reads the
/// folder and the files below it by the paths with the `\\?\` prefix that Windows gives them.
pub folder: PathBuf,
/// The files found, each with the items it is, in the order found (through [`plain`]).
pub hits: Vec<(PathBuf, Vec<usize>)>,
/// Folders listed.
pub folders: u64,
/// Files listed.
pub files: u64,
/// Files read.
pub read: u64,
/// Folders not entered (other apps', the system's, hidden ones, ones too deep, ones whose
/// contents aren't on the disk, ones whose names can't be read).
pub skipped: u64,
/// Folders and files that couldn't be read.
pub unreadable: u64,
/// How long it ran, or has been running.
pub seconds: f64,
}
impl Progress {
/// `searching`, `done` ([`End::Done`], [`End::Found`]), `stopped` ([`End::Stopped`],
/// [`End::Time`], [`End::Limit`]) or `failed`.
pub fn state(&self) -> &'static str {
match &self.end {
None => "searching",
Some(End::Done | End::Found) => "done",
Some(End::Stopped | End::Time | End::Limit) => "stopped",
Some(End::Failed(_)) => "failed",
}
}
/// Why a stopped search stopped: `stop`, `time` or `limit`.
pub fn stopped(&self) -> Option<&'static str> {
match &self.end {
Some(End::Stopped) => Some("stop"),
Some(End::Time) => Some("time"),
Some(End::Limit) => Some("limit"),
_ => None,
}
}
/// Why a failed search failed.
pub fn error(&self) -> Option<&str> {
match &self.end {
Some(End::Failed(e)) => Some(e),
_ => None,
}
}
}
/// Walker threads shared out among searches: all of them together run at most `cap` threads.
pub(crate) struct Pool {
live: AtomicUsize,
cap: usize,
}
impl Pool {
pub(crate) const fn new(cap: usize) -> Self {
Self { live: AtomicUsize::new(0), cap }
}
/// Reserve up to `want` threads: as many as are free, none when none is.
fn reserve(&self, want: usize) -> usize {
let mut live = self.live.load(Ordering::SeqCst);
loop {
let n = want.min(self.cap.saturating_sub(live));
if n == 0 {
return 0;
}
match self.live.compare_exchange(live, live + n, Ordering::SeqCst, Ordering::SeqCst) {
Ok(_) => return n,
Err(now) => live = now,
}
}
}
fn release(&self, n: usize) {
self.live.fetch_sub(n, Ordering::SeqCst);
}
/// The threads running now.
#[cfg(test)]
pub(crate) fn live(&self) -> usize {
self.live.load(Ordering::SeqCst)
}
}
/// The threads of every search.
static POOL: Pool = Pool::new(MAX_LIVE);
/// The walker threads for a search: the logical CPUs less one and less the renderer's threads,
/// from 2 to 8.
pub fn threads() -> usize {
let cpus = std::thread::available_parallelism().map_or(2, std::num::NonZero::get);
threads_for(cpus, usize::from(vectorcraft_render::default_threads()))
}
/// [`threads`] on `cpus` logical CPUs with `render` renderer threads.
pub(crate) fn threads_for(cpus: usize, render: usize) -> usize {
cpus.saturating_sub(1 + render).clamp(2, MAX_THREADS)
}
/// A running (or ended) search. Dropping it stops it.
pub struct Search {
shared: Arc<Shared>,
}
impl Search {
/// End the search ([`End::Stopped`]) unless it has ended. Walkers busy reading a folder or a
/// file stop after it.
pub fn stop(&self) {
let mut w = self.shared.lock();
self.shared.finish(&mut w, End::Stopped);
}
/// Where the search stands. Past its deadline it has ended ([`End::Time`]), even while a walker
/// is still waiting for a slow folder or file.
pub fn progress(&self) -> Progress {
let s = &self.shared;
let mut w = s.lock();
if w.end.is_none() && Instant::now() >= s.deadline {
s.finish(&mut w, End::Time);
}
Progress {
end: w.end.clone(),
folder: plain(w.folder.clone()),
hits: w.hits.iter().map(|(path, items)| (plain(path.clone()), items.clone())).collect(),
folders: w.folders,
files: w.files,
read: s.read.load(Ordering::Relaxed).min(s.limits.files),
skipped: w.skipped,
unreadable: w.unreadable,
seconds: if w.end.is_some() { w.seconds } else { s.started.elapsed().as_secs_f64() },
}
}
}
impl Drop for Search {
fn drop(&mut self) {
self.stop();
}
}
/// Search `folder` and its subfolders on up to `threads` walker threads (at most 8, as many as the
/// process-wide cap leaves) for the `items` a `visitor` looks for, where `rules` allow (this
/// computer's when `None`). Returns at once; the folder is checked on a walker thread.
pub fn start(
folder: PathBuf,
rules: Option<Rules>,
limits: Limits,
threads: usize,
items: usize,
visitor: Arc<dyn Visitor>,
) -> Result<Search, String> {
start_in(&POOL, folder, rules, limits, threads, items, visitor)
}
/// [`start`] with the threads of `pool`.
pub(crate) fn start_in(
pool: &'static Pool,
folder: PathBuf,
rules: Option<Rules>,
limits: Limits,
threads: usize,
items: usize,
visitor: Arc<dyn Visitor>,
) -> Result<Search, String> {
if cfg!(target_arch = "wasm32") {
return Err("searching a folder isn't available on the web".into());
}
let seconds = if limits.seconds.is_finite() { limits.seconds.clamp(0.0, 3600.0) } else { 60.0 };
let n = pool.reserve(threads.clamp(1, MAX_THREADS));
if n == 0 {
return Err("the search couldn't start: try again in a moment".into());
}
let started = Instant::now();
let shared = Arc::new(Shared {
stop: AtomicBool::new(false),
entries: AtomicU64::new(0),
read: AtomicU64::new(0),
started,
deadline: started + Duration::from_secs_f64(seconds),
limits,
items,
given: rules,
rules: OnceLock::new(),
visitor,
walk: Mutex::new(Walk { root: Some(folder), alive: n, found: vec![0; items], ..Walk::default() }),
wake: Condvar::new(),
pool,
});
let mut spawned = 0;
for _ in 0..n {
let s = shared.clone();
let thread = std::thread::Builder::new().name("vectorcraft-find".into()).spawn(move || {
let _alive = Alive(s.clone());
// A bug in the walk ends this walker and the others go on; when every walker ends this
// way, the search fails ([`Alive`]).
let _ = crate::guard::catch_panic(|| walker(&s));
});
if thread.is_ok() {
spawned += 1;
}
}
if spawned < n {
pool.release(n - spawned);
let mut w = shared.lock();
w.alive = w.alive.saturating_sub(n - spawned);
if spawned == 0 {
return Err("the search couldn't start: try again in a moment".into());
}
if w.alive == 0 && w.end.is_none() {
shared.finish(&mut w, End::Failed(INTERNAL.into()));
}
}
Ok(Search { shared })
}
/// What a search's walkers share.
struct Shared {
/// Set once the search ended: walkers stop listing and reading.
stop: AtomicBool,
entries: AtomicU64,
read: AtomicU64,
started: Instant,
deadline: Instant,
limits: Limits,
items: usize,
/// The rules given to [`start`], else this computer's, read by the first walker.
given: Option<Rules>,
rules: OnceLock<Rules>,
visitor: Arc<dyn Visitor>,
walk: Mutex<Walk>,
/// Woken when folders are queued, a walker finishes a folder, or the search ends.
wake: Condvar,
pool: &'static Pool,
}
/// The state walkers change under the lock.
#[derive(Default)]
struct Walk {
/// The picked folder, until a walker takes it to check it.
root: Option<PathBuf>,
/// A walker is checking the picked folder.
preparing: bool,
folder: PathBuf,
/// Folders waiting to be listed, with their depth below the picked one.
stack: Vec<(PathBuf, u32)>,
/// Folders being listed (and their candidates read) now.
listing: usize,
/// Walker threads still running.
alive: usize,
end: Option<End>,
seconds: f64,
hits: Vec<(PathBuf, Vec<usize>)>,
/// Files kept for each item.
found: Vec<usize>,
folders: u64,
files: u64,
skipped: u64,
unreadable: u64,
/// The home folder was queued from a system's root ([`Rules::home_below`]).
home_queued: bool,
}
impl Shared {
fn lock(&self) -> MutexGuard<'_, Walk> {
self.walk.lock().unwrap_or_else(|e| e.into_inner())
}
/// End the search as `end` unless it has ended, and wake every walker to see it.
fn finish(&self, w: &mut Walk, end: End) {
if w.end.is_none() {
w.end = Some(end);
w.seconds = self.started.elapsed().as_secs_f64();
}
self.stop.store(true, Ordering::Relaxed);
self.wake.notify_all();
}
fn end_with(&self, end: End) {
let mut w = self.lock();
self.finish(&mut w, end);
}
/// Whether to stop listing and reading: the search ended or its time is up.
fn should_stop(&self) -> bool {
self.stop.load(Ordering::Relaxed) || Instant::now() >= self.deadline
}
/// Whether the folders waiting to be listed and `more` folders found in the folder being listed
/// come to more than [`Limits::folders`], which ends the search ([`End::Limit`]).
fn too_many_folders(&self, more: usize) -> bool {
let mut w = self.lock();
let over = w.stack.len().saturating_add(more) > self.limits.folders;
if over {
self.finish(&mut w, End::Limit);
}
over
}
/// Check the picked folder, then queue it.
fn prepare(&self, root: &Path) {
let rules = self.rules.get_or_init(|| self.given.clone().unwrap_or_else(Rules::system));
let path = root.display();
let checked = match std::fs::canonicalize(root) {
Err(e) => Err(format!("{path}: {e}")),
Ok(folder) if !folder.is_dir() => Err(format!("{path} is not a folder")),
Ok(folder) => match rules.refusal(&folder) {
None => Ok(folder),
Some(Refusal::Shared) => Err(format!("VectorCraft doesn't search the Shared or Public folder in Users: {path}")),
Some(Refusal::Apps) => Err(format!("VectorCraft doesn't search other apps' or the system's folders: {path}")),
},
};
let mut w = self.lock();
match checked {
Ok(folder) => {
w.folder = folder.clone();
w.stack.push((folder, 0));
}
Err(e) => self.finish(&mut w, End::Failed(e)),
}
}
/// List one folder: queue its subfolders, then read the files [`Visitor::wants`] accepts.
fn list(&self, dir: &Path, depth: u32) {
let Some(rules) = self.rules.get() else { return };
let (mut skipped, mut unreadable, mut files) = (0, 0, 0);
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) => {
let mut w = self.lock();
// The picked folder itself: the search can't run, and says why.
if depth == 0 {
self.finish(&mut w, End::Failed(format!("{}: {e}", plain(dir.to_path_buf()).display())));
} else {
w.unreadable += 1;
w.folders += 1;
}
return;
}
};
let (mut folders, mut siblings, mut candidates) = (vec![], Siblings::default(), vec![]);
for (n, entry) in entries.enumerate() {
if n as u64 % CHECK_EVERY == CHECK_EVERY - 1 && (self.should_stop() || self.too_many_folders(folders.len())) {
break;
}
if self.entries.fetch_add(1, Ordering::Relaxed) >= self.limits.entries {
self.end_with(End::Limit);
break;
}
let Ok(entry) = entry else {
unreadable += 1;
break;
};
let Ok(kind) = entry.file_type() else {
unreadable += 1;
continue;
};
let name = entry.file_name();
let Some(name) = name.to_str() else {
// A name that isn't Unicode: its folder is left out, its file can't be wanted.
if kind.is_dir() {
skipped += 1;
}
continue;
};
if kind.is_dir() || kind.is_symlink() {
siblings.note(name);
}
// Links are neither followed nor read.
if kind.is_dir() {
folders.push((entry, name.to_string()));
} else if kind.is_file() {
files += 1;
// At most one file more than the search reads is kept to be read.
if (candidates.len() as u64) <= self.limits.files && self.visitor.wants(name) && self.visitor.worth_reading(&entry.path()) {
if hidden_and_offline(&entry).1 {
// Its contents are in the cloud: counted as unreadable, never read.
unreadable += 1;
} else {
candidates.push(entry);
}
}
}
}
// The folder is told once for all its folders.
let listed = rules.listed(dir, siblings);
let mut queue = vec![];
for (n, (entry, name)) in folders.into_iter().enumerate() {
if n as u64 % CHECK_EVERY == CHECK_EVERY - 1 && self.should_stop() {
break;
}
let path = entry.path();
let (hidden, offline) = hidden_and_offline(&entry);
if depth >= self.limits.depth || name.starts_with('.') || hidden || offline || rules.never_in(&listed, &name) || rules.is_refused(&path) {
skipped += 1;
continue;
}
queue.push((path, depth + 1));
}
let home = rules.home_below(&listed);
{
let mut w = self.lock();
w.files += files;
w.skipped += skipped;
w.unreadable += unreadable;
if w.end.is_none() {
if w.stack.len() + queue.len() > self.limits.folders {
self.finish(&mut w, End::Limit);
} else {
w.stack.extend(queue);
if let Some(home) = home.filter(|_| !w.home_queued) {
w.home_queued = true;
w.stack.push((home, 1));
}
self.wake.notify_all();
}
}
}
let mut unreadable = 0;
for entry in candidates {
if self.should_stop() {
break;
}
if self.read.fetch_add(1, Ordering::Relaxed) >= self.limits.files {
self.end_with(End::Limit);
break;
}
let path = entry.path();
match crate::guard::catch_panic(|| self.visitor.items(&path)) {
Ok(items) if !items.is_empty() => self.keep(path, items),
Ok(_) => {}
// A file that trips a bug: as one that can't be read, and the search goes on.
Err(_) => unreadable += 1,
}
}
let mut w = self.lock();
w.folders += 1;
w.unreadable += unreadable;
}
/// Keep a file the visitor gave `items` for, for those of its items that take more files, as
/// soon as it is read: a file read as the search ends is kept too. The search ends at the most
/// files it keeps, and once every item has a file.
fn keep(&self, path: PathBuf, mut items: Vec<usize>) {
let mut w = self.lock();
items.sort_unstable();
items.dedup();
items.retain(|i| w.found.get(*i).is_some_and(|n| *n < self.limits.per_item));
if items.is_empty() || w.hits.len() >= self.limits.hits {
return;
}
for i in &items {
if let Some(n) = w.found.get_mut(*i) {
*n += 1;
}
}
w.hits.push((path, items));
if w.hits.len() >= self.limits.hits {
self.finish(&mut w, End::Limit);
}
if self.items > 0 && w.found.iter().all(|n| *n > 0) {
self.finish(&mut w, End::Found);
}
}
}
/// What a walker does next.
enum Job {
Prepare(PathBuf),
List(PathBuf, u32),
}
/// A walker thread: check the picked folder, or list the next folder, until the search ends.
fn walker(s: &Shared) {
loop {
let job = {
let mut w = s.lock();
loop {
if w.end.is_some() {
return;
}
if Instant::now() >= s.deadline {
s.finish(&mut w, End::Time);
return;
}
if let Some(root) = w.root.take() {
w.preparing = true;
break Job::Prepare(root);
}
if let Some((dir, depth)) = w.stack.pop() {
w.listing += 1;
break Job::List(dir, depth);
}
if !w.preparing && w.listing == 0 {
s.finish(&mut w, End::Done);
return;
}
w = s.wake.wait_timeout(w, IDLE).map_or_else(|e| e.into_inner().0, |(w, _)| w);
}
};
// The guard lowers `preparing` or `listing` when the job ends, on a bug too.
let _busy = Busy(s, matches!(job, Job::Prepare(_)));
let done = crate::guard::catch_panic(|| match &job {
Job::Prepare(root) => s.prepare(root),
Job::List(dir, depth) => s.list(dir, *depth),
});
if done.is_err() {
let mut w = s.lock();
match job {
Job::Prepare(_) => s.finish(&mut w, End::Failed(INTERNAL.into())),
Job::List(..) => w.unreadable += 1,
}
}
}
}
/// A walker's job in progress: preparing (`true`) or listing a folder.
struct Busy<'a>(&'a Shared, bool);
impl Drop for Busy<'_> {
fn drop(&mut self) {
let mut w = self.0.lock();
if self.1 {
w.preparing = false;
} else {
w.listing = w.listing.saturating_sub(1);
}
self.0.wake.notify_all();
}
}
/// A running walker thread, counted out of the search and the pool when it ends.
struct Alive(Arc<Shared>);
impl Drop for Alive {
fn drop(&mut self) {
let mut w = self.0.lock();
w.alive = w.alive.saturating_sub(1);
if w.alive == 0 && w.end.is_none() {
self.0.finish(&mut w, End::Failed(INTERNAL.into()));
}
drop(w);
self.0.pool.release(1);
}
}
/// Whether a folder or file is hidden by its flags (macOS `UF_HIDDEN`; Windows hidden or system),
/// and whether its contents are in the cloud rather than on the disk (macOS `SF_DATALESS`; Windows
/// offline or recalled on access).
#[cfg(target_os = "macos")]
fn hidden_and_offline(entry: &std::fs::DirEntry) -> (bool, bool) {
use std::os::macos::fs::MetadataExt;
const UF_HIDDEN: u32 = 0x8000;
const SF_DATALESS: u32 = 0x4000_0000;
entry.metadata().map_or((false, false), |m| (m.st_flags() & UF_HIDDEN != 0, m.st_flags() & SF_DATALESS != 0))
}
#[cfg(windows)]
fn hidden_and_offline(entry: &std::fs::DirEntry) -> (bool, bool) {
use std::os::windows::fs::MetadataExt;
const HIDDEN: u32 = 0x2;
const SYSTEM: u32 = 0x4;
const OFFLINE: u32 = 0x1000;
const RECALL_ON_OPEN: u32 = 0x4_0000;
const RECALL_ON_DATA_ACCESS: u32 = 0x40_0000;
entry.metadata().map_or((false, false), |m| {
let a = m.file_attributes();
(a & (HIDDEN | SYSTEM) != 0, a & (OFFLINE | RECALL_ON_OPEN | RECALL_ON_DATA_ACCESS) != 0)
})
}
#[cfg(not(any(target_os = "macos", windows)))]
fn hidden_and_offline(_: &std::fs::DirEntry) -> (bool, bool) {
(false, false)
}
+517
View File
@@ -0,0 +1,517 @@
//! The fonts a document uses that aren't available (`text.missingFonts`), the files that provide
//! them in a folder the user picks (`text.findFontFiles`, searched on separate threads:
//! [`super::findfiles`]), and copying the files the user chooses into VectorCraft's own Fonts
//! folder, which the font scan reads (`text.addFontFiles`).
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_text::{FontDb, FontMatch, WantedFont, WantedFonts};
use super::findfiles::{self, Limits, Visitor};
use super::*;
use crate::DocState;
/// The most fonts listed, or looked for at once.
const MAX_FONTS: usize = 1_000;
/// The longest family or style name listed or given (bytes).
const MAX_NAME: usize = 256;
/// The CSS generic font families (CSS Fonts Module Level 4), which SVG and HTML files name in place
/// of a font and no font file provides; compared in any ASCII case. The list leaves out
/// `fangsong`, which is also the family name of a Chinese font (FangSong).
const GENERIC_FAMILIES: &[&str] = &[
"serif",
"sans-serif",
"monospace",
"cursive",
"fantasy",
"system-ui",
"ui-serif",
"ui-sans-serif",
"ui-monospace",
"ui-rounded",
"math",
"emoji",
];
/// The longest folder path given (bytes).
const MAX_PATH: usize = 4096;
/// The most files one `text.addFontFiles` copies: as many as a search keeps.
const MAX_ADD_FILES: usize = 1_000;
/// The largest font file a search reads and `text.addFontFiles` copies, and the most bytes one
/// `text.addFontFiles` copies.
pub(crate) const MAX_FONT_FILE: u64 = 256 << 20;
#[cfg(not(target_arch = "wasm32"))]
const MAX_ADD_BYTES: u64 = 1 << 30;
/// The highest number a copy's name gets (`Name 99.otf`).
#[cfg(not(target_arch = "wasm32"))]
const MAX_NUMBER: u32 = 99;
/// The extensions of the font files `text.addFontFiles` copies (in any case), besides suitcase
/// fonts.
#[cfg(not(target_arch = "wasm32"))]
const FONT_EXTENSIONS: &[&str] = &["ttf", "otf", "ttc", "otc", "woff", "woff2"];
/// Why a file wasn't copied.
const NOT_A_FILE: &str = "not a file";
#[cfg(not(target_arch = "wasm32"))]
const NOT_A_FONT: &str = "not a font file";
#[cfg(not(target_arch = "wasm32"))]
const TOO_LARGE: &str = "larger than 256 MB";
#[cfg(not(target_arch = "wasm32"))]
const TOO_MUCH: &str = "the files come to more than 1 GB: add fewer at a time";
#[cfg(not(target_arch = "wasm32"))]
const NO_NAME: &str = "every numbered name for it is taken in the Fonts folder";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "text.missingFonts",
"Missing Fonts",
[],
None,
"{} → {fonts: [{family, style, status: missing|substitute, resolved: {family, style}}] (sorted by name; at most 1000), count, fontsNextToDocument?} the fonts the active document's type uses, in its layers and its symbols, that aren't available as named: missing (the family is unknown and the fallback family stands in) or substitute (the family is there but not the style; resolved names the stand-in), as text.fonts says. CSS generic families such as sans-serif and names longer than 256 bytes are left out. fontsNextToDocument: the Fonts folder next to the saved document (File › Package writes it), when there is one and a search may start there (not in another app's folders, such as a mail app's attachments)",
has_doc,
missing
),
cmd!(
query "text.findFontFiles",
"Find Font Files",
[],
None,
"{folder?: an absolute path, fonts?: [{family, style?}] (1 to 1000; default: the active document's missing fonts, as text.missingFonts lists them), maxSeconds?: 60 (1 to 600), stop?: false (true: stop the last search)} with folder: look in it and its subfolders for font files that make the fonts available, on separate threads, and answer at once (state: searching); without folder: the last search's state, with the files found so far. A search reads the table directories and the name, fvar and OS/2 tables of .ttf, .otf, .ttc and .otc files of at most 256 MB and, on macOS, of suitcase fonts (files without an extension or with .suit, whose fonts are in a resource fork of at most 8 MB), and lists a file for a font when the file, added with text.addFontFiles, makes the font resolve exactly as text.fonts resolves it; fonts that resolve exactly already are left out. It doesn't enter app packages, folders named Program Files (also x86 and Arm), ProgramData, $Recycle.Bin or System Volume Information, the system's folders at the root of a volume, the Shared and Public folders in Users, a home folder's Library, AppData, Applications, snap and dot folders, a Library folder's app data folders or the folders the environment names for apps' data, and a search of a folder inside one of them fails; the walk also skips other hidden folders, folders whose contents are in the cloud and folders more than 64 levels deep, and follows no links (a picked path is resolved through its links); none on the web → {id (absent while idle), state: idle|searching|done|stopped|failed, folder?, fonts: [{family, style, status, files: [paths]}], searched?: {folders, files, fontFiles}, skipped?, unreadable?, stopped?: stop|time|limit, error?, seconds?}",
always,
find
),
cmd!(
query "text.addFontFiles",
"Add Font Files",
[],
None,
"{files: [paths the last text.findFontFiles search found] (1 to 1000)} copy the font files into VectorCraft's own Fonts folder (next to the preferences; the desktop app and vectorcraft-cli read it), never replacing a file there: a file with the same contents is kept, and when another file has that name, the copy gets a number (Name 2.otf); then scan the fonts again, as text.rescanFonts does, and type set in them redraws. Only regular .ttf, .otf, .ttc, .otc, .woff and .woff2 files and suitcase fonts (with their resource fork) are copied, at most 256 MB a file and 1 GB in all; any other file is skipped. Add only fonts you own or are licensed to install; none on the web → {folder, copied: [{from, to}], kept: [{from, to}], skipped: [{file, reason}], families?, faces?}",
always,
add
),
]
}
/// A font a document names that isn't available as named.
#[derive(Clone, Debug, PartialEq)]
pub struct MissingFont {
pub family: String,
pub style: String,
/// [`FontMatch::Missing`] or [`FontMatch::Style`].
pub status: FontMatch,
/// The family and style of the face shown instead.
pub resolved: Option<(String, String)>,
}
/// The fonts the type of `d` uses, in its layers and its symbols, that aren't available as named
/// (sorted by family and style, each once whatever version its type names; at most 1000). CSS generic families such as `sans-serif`
/// ([`GENERIC_FAMILIES`]) and names longer than 256 bytes are left out.
pub fn missing_fonts(d: &Document) -> Vec<MissingFont> {
let db = FontDb::global();
let generic = |family: &str| GENERIC_FAMILIES.iter().any(|g| g.eq_ignore_ascii_case(family.trim()));
let mut used: Vec<(String, String)> = super::fonts::used_fonts(d).into_iter().map(|(family, style, _)| (family, style)).collect();
// Sorted by family and style: the versions type names of one face are neighbors.
used.dedup();
used.into_iter()
.filter(|(family, style)| !family.trim().is_empty() && !generic(family) && family.len() <= MAX_NAME && style.len() <= MAX_NAME)
.filter_map(|(family, style)| {
let resolved = db.resolve(&family, &style);
let status = resolved.as_ref().map_or(FontMatch::Missing, |(_, m)| *m);
(status != FontMatch::Exact).then(|| MissingFont {
family,
style,
status,
resolved: resolved.map(|(f, _)| (f.family.clone(), f.style.clone())),
})
})
.take(MAX_FONTS)
.collect()
}
/// `text.missingFonts`'s answer for the open document `st`, where searches go by `rules` (this
/// computer's when `None`).
pub fn missing_fonts_of(st: &DocState, rules: Option<&findfiles::Rules>) -> Value {
let fonts: Vec<Value> = missing_fonts(&st.doc)
.into_iter()
.map(|m| {
json!({
"family": m.family, "style": m.style, "status": m.status.as_str(),
"resolved": m.resolved.map(|(family, style)| json!({ "family": family, "style": style })),
})
})
.collect();
let mut out = json!({ "count": fonts.len(), "fonts": fonts });
// File › Package puts the fonts in a `Fonts` folder next to the packaged document. The folder
// is made absolute against the working folder when the document's path is relative. It is
// offered when a search may start there, as far as the rules tell without listing a folder.
if let Some(dir) = st.path.as_deref().and_then(|p| Path::new(p).parent()).map(|d| d.join("Fonts")).filter(|d| d.is_dir()) {
let dir = super::fileio::absolute_path(&dir.to_string_lossy());
let system;
let rules = match rules {
Some(rules) => rules,
None => {
system = findfiles::Rules::system();
&system
}
};
if std::fs::canonicalize(&dir).is_ok_and(|c| rules.refusal_unlisted(&c).is_none()) {
out["fontsNextToDocument"] = json!(dir);
}
}
out
}
fn missing(s: &mut Session, _: &Value) -> Result<Value> {
Ok(missing_fonts_of(s.doc()?, s.search_rules.as_ref()))
}
/// A font a search looks for.
#[derive(Clone, Debug)]
pub(crate) struct Sought {
pub(crate) family: String,
pub(crate) style: String,
pub(crate) status: FontMatch,
}
/// The session's last search for font files (`text.findFontFiles`).
pub(crate) struct FontSearch {
/// The search's number in the session; [`stop`] takes it.
pub(crate) id: u64,
/// The folder as given.
pub(crate) folder: String,
pub(crate) fonts: Vec<Sought>,
pub(crate) search: findfiles::Search,
}
/// The files a search for fonts reads: font files, by their names ([`WantedFonts`]).
struct FontFiles(WantedFonts);
impl Visitor for FontFiles {
fn wants(&self, name: &str) -> bool {
let path = Path::new(name);
// A suitcase font (macOS) has no extension, or `.suit`.
vectorcraft_text::is_font_file(path) || cfg!(target_os = "macos") && path.extension().is_none_or(|e| e.eq_ignore_ascii_case("suit"))
}
fn worth_reading(&self, path: &Path) -> bool {
// A search reads font files and suitcase fonts of at most [`MAX_FONT_FILE`] bytes, the files
// `text.addFontFiles` copies.
(vectorcraft_text::is_font_file(path) || vectorcraft_text::is_suitcase(path))
&& std::fs::metadata(path).is_ok_and(|m| m.len() <= MAX_FONT_FILE)
}
fn items(&self, path: &Path) -> Vec<usize> {
self.0.provided_by(path)
}
}
/// `[{family, style?}]`: 1 to 1000 fonts with a family of 1 to 256 bytes and a style of at most 256
/// (Regular when left out).
fn font_list(v: &Value) -> Option<Vec<(String, String)>> {
let list = v.as_array().filter(|a| (1..=MAX_FONTS).contains(&a.len()))?;
list.iter()
.map(|f| {
let family = f.get("family")?.as_str().filter(|s| !s.trim().is_empty() && s.len() <= MAX_NAME)?;
let style = match f.get("style") {
None | Some(Value::Null) => "Regular",
Some(s) => s.as_str().filter(|s| s.len() <= MAX_NAME)?,
};
Some((family.to_string(), style.to_string()))
})
.collect()
}
fn find(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.findFontFiles";
static NEXT: AtomicU64 = AtomicU64::new(1);
if bool_or(p, "stop", false) {
if let Some(f) = &s.font_search {
f.search.stop();
}
return Ok(state(s));
}
let Some(folder) = p.get("folder").filter(|f| !f.is_null()) else { return Ok(state(s)) };
let given = match p.get("fonts") {
None | Some(Value::Null) => None,
Some(v) => Some(font_list(v).ok_or_else(|| bad(C, "each of `fonts` is {family, style?}; 1 to 1000 of them"))?),
};
let seconds = p.get("maxSeconds").and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(60.0).clamp(1.0, 600.0);
// Only checked here: the folder is read on a walker thread.
let folder = folder
.as_str()
.filter(|f| !f.is_empty() && f.len() <= MAX_PATH && !f.contains(['\0', '\u{FFFD}']) && Path::new(f).is_absolute())
.ok_or_else(|| bad(C, "`folder` must be an absolute folder path"))?
.to_string();
let fonts = match given {
Some(fonts) => fonts,
None => missing_fonts(&s.active().ok_or_else(|| bad(C, "give `fonts`, or open a document"))?.doc)
.into_iter()
.map(|m| (m.family, m.style))
.collect(),
};
let db = FontDb::global();
let (mut sought, mut wanted) = (vec![], vec![]);
for (family, style) in fonts {
let (status, installed) = match db.resolve(&family, &style) {
Some((_, FontMatch::Exact)) => continue,
Some((f, FontMatch::Style)) => (FontMatch::Style, Some(f.family.clone())),
_ => (FontMatch::Missing, None),
};
wanted.push(WantedFont { family: family.clone(), style: style.clone(), installed });
sought.push(Sought { family, style, status });
}
if sought.is_empty() {
return Err(bad(C, "no fonts to look for: they are all available"));
}
// A new search stops the last one.
s.font_search = None;
let threads = s.search_threads.unwrap_or_else(findfiles::threads);
let limits = Limits { seconds, ..Limits::default() };
let visitor = Arc::new(FontFiles(WantedFonts::new(&wanted)));
let search =
findfiles::start(PathBuf::from(&folder), s.search_rules.clone(), limits, threads, sought.len(), visitor).map_err(EngineError::Other)?;
s.font_search = Some(FontSearch { id: NEXT.fetch_add(1, Ordering::Relaxed), folder, fonts: sought, search });
Ok(state(s))
}
/// Where the session's last search stands (`text.findFontFiles` without `folder`).
fn state(s: &Session) -> Value {
let Some(f) = &s.font_search else { return json!({ "state": "idle", "fonts": [] }) };
let p = f.search.progress();
let mut files: Vec<Vec<String>> = vec![vec![]; f.fonts.len()];
for (path, items) in &p.hits {
for i in items {
if let Some(v) = files.get_mut(*i) {
v.push(path.to_string_lossy().into_owned());
}
}
}
let fonts: Vec<Value> = f
.fonts
.iter()
.zip(files)
.map(|(font, mut files)| {
files.sort();
json!({ "family": font.family, "style": font.style, "status": font.status.as_str(), "files": files })
})
.collect();
let folder = if p.folder.as_os_str().is_empty() { f.folder.clone() } else { p.folder.to_string_lossy().into_owned() };
let mut out = json!({
"id": f.id, "state": p.state(), "folder": folder, "fonts": fonts,
"searched": { "folders": p.folders, "files": p.files, "fontFiles": p.read },
"skipped": p.skipped, "unreadable": p.unreadable, "seconds": (p.seconds * 10.0).round() / 10.0,
});
if let Some(why) = p.stopped() {
out["stopped"] = json!(why);
}
if let Some(e) = p.error() {
out["error"] = json!(e);
}
out
}
/// Stop the session's search when it is the one numbered `id` (`text.findFontFiles`'s `id`): a
/// newer search, started by someone else, goes on.
pub fn stop(s: &mut Session, id: u64) {
if let Some(f) = s.font_search.as_ref().filter(|f| f.id == id) {
f.search.stop();
}
}
/// What copying font files into a folder did: each file copied (from, to), kept because the same
/// file is there already (from, the file there), or skipped (file, why).
#[derive(Debug, Default)]
pub(crate) struct CopyReport {
pub(crate) copied: Vec<(PathBuf, PathBuf)>,
pub(crate) kept: Vec<(PathBuf, PathBuf)>,
pub(crate) skipped: Vec<(PathBuf, String)>,
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.addFontFiles";
let mut files: Vec<PathBuf> = p
.get("files")
.and_then(Value::as_array)
.filter(|a| (1..=MAX_ADD_FILES).contains(&a.len()))
.and_then(|a| a.iter().map(|f| f.as_str().map(PathBuf::from)).collect::<Option<Vec<_>>>())
.ok_or_else(|| bad(C, "`files` must be 1 to 1000 paths of font files the last text.findFontFiles search found"))?;
files.sort();
files.dedup();
let dir = vectorcraft_text::app_font_dir()
.ok_or_else(|| EngineError::Other("VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it".into()))?;
let found: Vec<PathBuf> =
s.font_search.as_ref().map(|f| f.search.progress().hits.into_iter().map(|(path, _)| path).collect()).unwrap_or_default();
if let Some(f) = files.iter().find(|f| !found.contains(f)) {
return Err(bad(C, format!("`{}` is not a font file the last text.findFontFiles search found", f.display())));
}
super::fileio::create_dir(&dir.to_string_lossy())?;
let report = copy_into(&files, dir);
let pairs = |v: &[(PathBuf, PathBuf)]| {
v.iter().map(|(from, to)| json!({ "from": from.to_string_lossy(), "to": to.to_string_lossy() })).collect::<Vec<_>>()
};
let mut out = json!({
"folder": dir.to_string_lossy(), "copied": pairs(&report.copied), "kept": pairs(&report.kept),
"skipped": report.skipped.iter().map(|(file, why)| json!({ "file": file.to_string_lossy(), "reason": why })).collect::<Vec<_>>(),
});
if !report.copied.is_empty() || !report.kept.is_empty() {
// The fonts are cataloged and type set in them redraws, as Refresh Font List does it.
let r = super::fonts::rescan(s, &Value::Null)?;
out["families"] = r["families"].clone();
out["faces"] = r["faces"].clone();
}
Ok(out)
}
/// Where [`copy_one`] put a file: copied to, or kept as, the file in the folder.
#[cfg(not(target_arch = "wasm32"))]
enum Placed {
Copied(PathBuf),
Kept(PathBuf),
}
/// Copy `files` into `dir`, never replacing a file there: a file with the same contents is kept,
/// and when another file has the name, the copy gets the first free name from `Name 2.otf` to
/// `Name 99.otf`. At most [`MAX_FONT_FILE`] bytes a file and 1 GB in all.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn copy_into(files: &[PathBuf], dir: &Path) -> CopyReport {
let mut report = CopyReport::default();
let mut total = 0;
for from in files {
match copy_one(from, dir, &mut total) {
Ok(Placed::Copied(to)) => report.copied.push((from.clone(), to)),
Ok(Placed::Kept(to)) => report.kept.push((from.clone(), to)),
Err(why) => report.skipped.push((from.clone(), why)),
}
}
report
}
/// The web has no file system: nothing is copied.
#[cfg(target_arch = "wasm32")]
pub(crate) fn copy_into(files: &[PathBuf], _: &Path) -> CopyReport {
CopyReport { skipped: files.iter().map(|f| (f.clone(), NOT_A_FILE.to_string())).collect(), ..CopyReport::default() }
}
#[cfg(not(target_arch = "wasm32"))]
fn copy_one(from: &Path, dir: &Path, total: &mut u64) -> std::result::Result<Placed, String> {
use std::io::ErrorKind;
let meta = std::fs::symlink_metadata(from).map_err(|e| e.to_string())?;
if !meta.is_file() {
return Err(NOT_A_FILE.into());
}
let font = from.extension().and_then(|e| e.to_str()).is_some_and(|e| FONT_EXTENSIONS.iter().any(|x| e.eq_ignore_ascii_case(x)));
// A suitcase font's fonts are in its resource fork, which is copied with it, whatever its name.
let fork = match (vectorcraft_text::is_suitcase(from), font) {
(true, _) => Some(read_fork(from)?),
(false, true) => None,
(false, false) => return Err(NOT_A_FONT.into()),
};
let len = fork.as_ref().map_or(meta.len(), |f| f.len() as u64);
if len > MAX_FONT_FILE {
return Err(TOO_LARGE.into());
}
if total.saturating_add(len) > MAX_ADD_BYTES {
return Err(TOO_MUCH.into());
}
let (Some(name), Some(stem)) = (from.file_name(), from.file_stem()) else { return Err(NOT_A_FILE.into()) };
let ext = from.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
for n in 1..=MAX_NUMBER {
let to = if n == 1 { dir.join(name) } else { dir.join(format!("{} {n}{ext}", stem.to_string_lossy())) };
match std::fs::symlink_metadata(&to) {
Err(e) if e.kind() == ErrorKind::NotFound => match create_copy(from, &to, fork.as_deref()) {
Ok(()) => {
*total += len;
return Ok(Placed::Copied(to));
}
// Taken meanwhile: the next name.
Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
Err(e) => return Err(e.to_string()),
},
Ok(m) if m.is_file() && same_file(from, &to, m.len(), len, fork.as_deref()) => return Ok(Placed::Kept(to)),
_ => {}
}
}
Err(NO_NAME.into())
}
/// Create `to` as a copy of the font file `from`, or for a suitcase font, as an empty file whose
/// resource fork is `fork`; never in place of a file.
#[cfg(not(target_arch = "wasm32"))]
fn create_copy(from: &Path, to: &Path, fork: Option<&[u8]>) -> std::io::Result<()> {
let Some(fork) = fork else { return vectorcraft_format::write_new_with(to, |f| copy_capped(from, f)) };
vectorcraft_format::write_new_with(to, |_| Ok(()))?;
std::fs::write(fork_path(to), fork).inspect_err(|_| {
// Best effort: the empty file just made is all there is to clean up.
let _ = std::fs::remove_file(to);
})
}
/// Whether the file `to` (`to_len` bytes) holds what the copy of `from` (`len` bytes, or the
/// resource fork `fork` of a suitcase font) would.
#[cfg(not(target_arch = "wasm32"))]
fn same_file(from: &Path, to: &Path, to_len: u64, len: u64, fork: Option<&[u8]>) -> bool {
match fork {
None => to_len == len && same_contents(from, to),
Some(fork) => to_len == 0 && read_fork(to).is_ok_and(|f| f == fork),
}
}
/// The resource fork of the file at `path` (where macOS keeps a suitcase font's fonts), at most
/// [`MAX_FONT_FILE`] bytes.
#[cfg(not(target_arch = "wasm32"))]
fn read_fork(path: &Path) -> std::result::Result<Vec<u8>, String> {
use std::io::Read;
let mut fork = vec![];
std::fs::File::open(fork_path(path)).and_then(|f| f.take(MAX_FONT_FILE + 1).read_to_end(&mut fork)).map_err(|e| e.to_string())?;
if fork.len() as u64 > MAX_FONT_FILE {
return Err(TOO_LARGE.into());
}
Ok(fork)
}
/// Where macOS shows the resource fork of the file at `path`.
#[cfg(not(target_arch = "wasm32"))]
fn fork_path(path: &Path) -> PathBuf {
path.join("..namedfork/rsrc")
}
/// Copy the file `from` into `to`, failing past [`MAX_FONT_FILE`] bytes (a file that grew since
/// it was measured).
#[cfg(not(target_arch = "wasm32"))]
fn copy_capped(from: &Path, to: &mut std::fs::File) -> std::io::Result<()> {
use std::io::Read;
let copied = std::io::copy(&mut std::fs::File::open(from)?.take(MAX_FONT_FILE + 1), to)?;
if copied > MAX_FONT_FILE {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, TOO_LARGE));
}
Ok(())
}
/// Whether the files `a` and `b` hold the same bytes (read 64 KB at a time).
#[cfg(not(target_arch = "wasm32"))]
fn same_contents(a: &Path, b: &Path) -> bool {
let (Ok(mut a), Ok(mut b)) = (std::fs::File::open(a), std::fs::File::open(b)) else { return false };
let (mut x, mut y) = (vec![0; 1 << 16], vec![0; 1 << 16]);
loop {
match (fill(&mut a, &mut x), fill(&mut b, &mut y)) {
(Ok(0), Ok(0)) => return true,
(Ok(n), Ok(m)) if n == m && x.get(..n) == y.get(..m) => {}
_ => return false,
}
}
}
/// Read from `f` until `buf` is full or the file ends: the bytes read.
#[cfg(not(target_arch = "wasm32"))]
fn fill(f: &mut std::fs::File, buf: &mut [u8]) -> std::io::Result<usize> {
use std::io::Read;
let mut n = 0;
while let Some(rest) = buf.get_mut(n..).filter(|r| !r.is_empty()) {
match f.read(rest)? {
0 => break,
k => n += k,
}
}
Ok(n)
}
+3
View File
@@ -22,7 +22,9 @@ mod effectcmd;
pub mod expand;
pub(crate) mod fileinfo;
pub mod fileio;
pub mod findfiles;
pub mod flatten;
pub mod fontfiles;
mod fonts;
pub(crate) mod freeform;
pub(crate) mod gradient;
@@ -223,6 +225,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(inline::specs());
v.extend(textstyles::specs());
v.extend(fonts::specs());
v.extend(fontfiles::specs());
v.extend(help::specs());
v.extend(threads::specs());
v.extend(textwrap::specs());
+30 -4
View File
@@ -50,6 +50,17 @@ fn font_ext(bytes: &[u8]) -> &'static str {
}
}
/// The name a font's file gets in the package's `Fonts` folder: the name of the file at `path`,
/// with the extension the font's `data` calls for ([`font_ext`]) when that name has no font
/// extension; without a file, `family-style` with that extension.
fn packaged_name(path: Option<&Path>, family: &str, style: &str, data: &[u8]) -> String {
match path.and_then(Path::file_name).map(|n| n.to_string_lossy().into_owned()) {
Some(name) if vectorcraft_text::is_font_file(Path::new(&name)) => name,
Some(name) => format!("{name}.{}", font_ext(data)),
None => format!("{family}-{style}.{}", font_ext(data)).replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), ""),
}
}
/// The options of a package.
struct Options {
copy_links: bool,
@@ -123,10 +134,7 @@ fn package(s: &mut Session, p: &Value) -> Result<Value> {
let reason = match resolved {
Some((f, _)) if f.embeddable() => {
let data = f.file_data();
let file = f.path().and_then(Path::file_name).map_or_else(
|| format!("{}-{}.{}", f.family, f.style, font_ext(data)).replace(|c: char| !(c.is_alphanumeric() || "-_.".contains(c)), ""),
|n| n.to_string_lossy().into_owned(),
);
let file = packaged_name(f.path(), &f.family, &f.style, data);
// A collection, or a style shown in another face's file, is copied once.
if files.insert(file.to_lowercase()) {
entries.push((format!("Fonts/{file}"), data.to_vec()));
@@ -258,3 +266,21 @@ pub(crate) fn zip(files: &[(String, &[u8])]) -> Result<Vec<u8>> {
out.extend_from_slice(&0u16.to_le_bytes());
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
/// A font read from a file without a font extension (one a font manager keeps, for example) is
/// packaged with the extension its data calls for.
#[test]
fn packaged_fonts_have_a_font_extension() {
let (otf, ttc, ttf) = (b"OTTO....".as_slice(), b"ttcf....".as_slice(), b"\0\x01\0\0....".as_slice());
let name = |path: Option<&str>, data: &[u8]| packaged_name(path.map(Path::new), "Some Family", "Bold", data);
assert_eq!(name(Some("/fonts/A8F3C2"), otf), "A8F3C2.otf");
assert_eq!(name(Some("/fonts/Shared Fonts.dat"), ttc), "Shared Fonts.dat.ttc");
assert_eq!(name(Some("/fonts/Kept.TTF"), otf), "Kept.TTF");
assert_eq!(name(Some("/fonts/Kept.otc"), ttc), "Kept.otc");
assert_eq!(name(None, ttf), "SomeFamily-Bold.ttf");
}
}
+14
View File
@@ -861,6 +861,15 @@ pub struct Session {
pub(crate) plane_widget_press: bool,
/// A guide being dragged out of a ruler ([`Session::ruler_guide`]).
pub(crate) ruler_guide: Option<vectorcraft_tools::rulerguide::NewGuide>,
/// The last search for the files of missing fonts (`text.findFontFiles`), until another
/// starts; dropping it stops it.
pub(crate) font_search: Option<cmd::fontfiles::FontSearch>,
/// Where folder searches may go; `None`: this computer's rules ([`cmd::findfiles::Rules`]).
/// Tests set it.
pub search_rules: Option<cmd::findfiles::Rules>,
/// The walker threads a folder search starts; `None`: [`cmd::findfiles::threads`]. Tests set
/// it.
pub search_threads: Option<usize>,
}
impl Default for Session {
@@ -913,6 +922,9 @@ impl Session {
liquify_stroke: None,
plane_widget_press: false,
ruler_guide: None,
font_search: None,
search_rules: None,
search_threads: None,
}
}
@@ -1459,6 +1471,8 @@ mod tests_flatten;
#[cfg(test)]
mod tests_focal;
#[cfg(test)]
mod tests_fontfiles;
#[cfg(test)]
mod tests_fontlist;
#[cfg(test)]
mod tests_freeform;
+429
View File
@@ -0,0 +1,429 @@
//! Missing fonts: listed (`text.missingFonts`), their files found in a folder on threads of their
//! own (`text.findFontFiles`), and copied into a folder without replacing a file there. These tests
//! never set VectorCraft's Fonts folder and never add a font to the process's font database:
//! `tests/font_folder.rs` does both, in a process of its own.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_text::FontMatch;
use crate::cmd::findfiles::{self, Limits, Rules, Visitor};
use crate::cmd::fontfiles::{self, FontSearch, MAX_FONT_FILE, Sought, copy_into};
use crate::{EngineError, Session};
/// A fresh temporary folder (canonical, as a search reports it).
fn folder(tag: &str) -> PathBuf {
let dir = vectorcraft_testkit::temp_dir(&format!("fontfiles-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
findfiles::plain(std::fs::canonicalize(&dir).unwrap())
}
/// A session whose folder searches may go anywhere in `root`, on two threads.
fn session_for(root: &Path) -> Session {
let mut s = Session::new();
s.search_rules = Some(Rules { user_content: vec![root.to_path_buf()], ..Rules::default() });
s.search_threads = Some(2);
s
}
/// `text.findFontFiles {}` once the search ended (10 seconds at most).
fn finished(s: &mut Session) -> Value {
let until = Instant::now() + Duration::from_secs(10);
loop {
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
if r["state"] != "searching" || Instant::now() > until {
return r;
}
std::thread::sleep(Duration::from_millis(5));
}
}
/// New point type in `font` and `style` → its id.
fn text(s: &mut Session, y: f64, font: &str, style: &str) -> u64 {
s.execute("text.create", &json!({"x": 10, "y": y, "text": "Ab", "font": font, "style": style})).unwrap()["id"].as_u64().unwrap()
}
fn bundled(file: &str) -> Vec<u8> {
std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts").join(file)).unwrap()
}
#[test]
fn missing_fonts_are_listed_symbols_included() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "No Such Font Family", "Regular");
// Type naming another version of a missing font is listed with it.
let other = vectorcraft_doc::NodeId(text(&mut s, 40.0, "No Such Font Family", "Regular"));
s.edit("version", |d, _| {
if let vectorcraft_doc::NodeKind::Text(t) = &mut d.node_mut(other).unwrap().kind {
t.runs.iter_mut().for_each(|r| r.style.font_version = Some("Version 2.000".into()));
}
Ok(())
})
.unwrap();
// A style no Source Sans 3 has, bundled or installed.
text(&mut s, 60.0, "Source Sans 3", "Black Wide");
text(&mut s, 100.0, "Source Sans 3", "Semibold");
let id = text(&mut s, 140.0, "Symbol Only Family", "Bold");
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("symbol.new", &json!({})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
// CSS generic families, which no font file provides, are left out.
text(&mut s, 180.0, "sans-serif", "Regular");
text(&mut s, 220.0, "SERIF", "Bold");
let r = s.execute("text.missingFonts", &json!({})).unwrap();
let rows: Vec<(&str, &str, &str)> = r["fonts"]
.as_array()
.unwrap()
.iter()
.map(|f| (f["family"].as_str().unwrap(), f["style"].as_str().unwrap(), f["status"].as_str().unwrap()))
.collect();
assert_eq!(
rows,
[("No Such Font Family", "Regular", "missing"), ("Source Sans 3", "Black Wide", "substitute"), ("Symbol Only Family", "Bold", "missing")]
);
assert_eq!((r["count"].as_u64(), r["fonts"][1]["resolved"]["family"].as_str()), (Some(3), Some("Source Sans 3")));
assert!(r.get("fontsNextToDocument").is_none(), "an unsaved document has no folder");
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert!(!listed.as_array().unwrap().iter().any(|f| f["family"] == "Symbol Only Family"), "Find Font lists the layers' type only");
assert!(listed.as_array().unwrap().iter().any(|f| f["family"] == "sans-serif" && f["status"] == "missing"), "{listed}");
assert!(matches!(Session::new().execute("text.missingFonts", &json!({})), Err(EngineError::Disabled(..))));
}
/// A font whose name is longer than 256 bytes is left out of the list, and a search for the fonts
/// listed finds the other fonts' files.
#[test]
fn an_overlong_font_name_leaves_the_other_fonts_searchable() {
let root = folder("long-name");
std::fs::write(root.join("Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, &"L".repeat(300), "Regular");
text(&mut s, 60.0, "Findme Sans 3", "Regular");
let listed = s.execute("text.missingFonts", &json!({})).unwrap();
let fonts: Vec<Value> = listed["fonts"].as_array().unwrap().iter().map(|f| json!({"family": f["family"], "style": f["style"]})).collect();
assert_eq!(fonts, [json!({"family": "Findme Sans 3", "style": "Regular"})]);
s.execute("text.findFontFiles", &json!({"folder": root, "fonts": fonts})).unwrap();
assert_eq!(finished(&mut s)["fonts"][0]["files"], json!([root.join("Findme.otf")]));
}
/// The Fonts folder next to a document is offered only where a search may start: not inside other
/// apps' folders, such as the attachments a mail app keeps in the home folder's Library.
#[test]
fn the_fonts_folder_next_to_a_document_in_another_apps_folder_isnt_offered() {
let root = folder("next-to");
let home = root.join("Users/me");
let mut s = Session::new();
s.search_rules = Some(Rules { home: Some(home.clone()), ..Rules::default() });
for (dir, offered) in [("Library/Mail Downloads/pkg", false), ("Documents/pkg", true)] {
std::fs::create_dir_all(home.join(dir).join("Fonts")).unwrap();
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
doc.title = "doc".into();
s.add_document(doc, Some(home.join(dir).join("doc.vectorcraft").to_string_lossy().into_owned()));
text(&mut s, 20.0, "No Such Font Family", "Regular");
let r = s.execute("text.missingFonts", &json!({})).unwrap();
assert_eq!(r.get("fontsNextToDocument").is_some(), offered, "{dir}: {r}");
}
}
/// A document opened by a relative path gives the Fonts folder next to it as an absolute path,
/// which `text.findFontFiles` takes.
#[cfg(unix)]
#[test]
fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
let root = folder("relative");
std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap();
let cwd = std::env::current_dir().unwrap();
let up = "../".repeat(cwd.components().count().saturating_sub(1));
let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display());
assert!(Path::new(&relative).is_relative());
let mut s = session_for(&root);
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
doc.title = "doc".into();
s.add_document(doc, Some(relative));
text(&mut s, 20.0, "No Such Font Family", "Regular");
let next = s.execute("text.missingFonts", &json!({})).unwrap()["fontsNextToDocument"].as_str().unwrap().to_string();
assert!(Path::new(&next).is_absolute(), "{next}");
assert_eq!(std::fs::canonicalize(&next).unwrap(), root.join("pkg/Fonts"));
assert!(s.execute("text.findFontFiles", &json!({"folder": next})).is_ok());
assert_ne!(finished(&mut s)["state"], "failed");
}
#[test]
fn a_search_finds_a_missing_fonts_file_by_its_names() {
let root = folder("find");
std::fs::create_dir_all(root.join("x/y")).unwrap();
std::fs::write(root.join("x/y/Findme.otf"), vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
std::fs::write(root.join("other.ttf"), bundled("SourceSerif4-Regular.ttf")).unwrap();
std::fs::write(root.join("readme.txt"), "Findme Sans 3").unwrap();
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "Findme Sans 3", "Regular");
// Never found: the search reads the whole folder.
text(&mut s, 60.0, "No Such Font Family", "Regular");
let r = s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}");
let id = r["id"].clone();
let r = finished(&mut s);
assert_eq!((&r["state"], &r["id"], r.get("stopped")), (&json!("done"), &id, None), "{r}");
let found = root.join("x").join("y").join("Findme.otf").to_string_lossy().into_owned();
let findme = r["fonts"].as_array().unwrap().iter().find(|f| f["family"] == "Findme Sans 3").cloned().unwrap();
assert_eq!((findme["status"].as_str(), findme["files"].clone()), (Some("missing"), json!([found])));
assert_eq!(r["searched"]["fontFiles"], 2, "the font files are read, not the text file: {r}");
assert_eq!(r["folder"], json!(root));
// Fonts given by name: the search ends once each has a file.
let r = s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Findme Sans 3"}]})).unwrap();
assert_ne!(r["id"], id, "a new search");
let r = finished(&mut s);
assert_eq!((&r["state"], &r["fonts"][0]["files"]), (&json!("done"), &json!([found])), "{r}");
// Fonts that are available aren't looked for.
let r = s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Source Sans 3"}]}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}");
// Stopped by a new search, or by `stop`.
s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
let r = s.execute("text.findFontFiles", &json!({"stop": true})).unwrap();
assert!(matches!(r["state"].as_str(), Some("stopped" | "done")), "{r}");
}
#[test]
fn junk_search_params_never_fail_internally() {
let root = folder("junk");
let mut s = session_for(&root);
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
text(&mut s, 20.0, "No Such Font Family", "Regular");
let internal = |r: &crate::Result<Value>| matches!(r, Err(EngineError::Internal { .. }));
let mut cases = vec![];
for v in vectorcraft_testkit::strategies::junk_values() {
cases.extend([
json!({"folder": root, "maxSeconds": v}),
json!({"folder": root, "fonts": v}),
json!({"folder": root, "stop": v}),
json!({"folder": v}),
json!({"folder": root, "fonts": [v]}),
json!({"folder": root, "fonts": [{"family": v}]}),
json!({"folder": root, "fonts": [{"family": "No Such Font Family", "style": v}]}),
]);
assert!(s.execute("text.addFontFiles", &json!({"files": v})).is_err());
assert!(s.execute("text.addFontFiles", &json!({"files": [v]})).is_err());
}
let long = "x".repeat(257);
let many: Vec<Value> = (0..1001).map(|i| json!({"family": format!("No Such Family {i}")})).collect();
cases.extend([
json!({"folder": root, "fonts": [{"family": long}]}),
json!({"folder": root, "fonts": [{"family": "x", "style": long}]}),
json!({"folder": root, "fonts": [{"family": "a\u{0}b"}]}),
json!({"folder": root, "fonts": many}),
json!({"folder": root, "fonts": many[..1000]}),
json!({"folder": "/a\u{0}b"}),
json!({"folder": "relative/folder"}),
json!({"folder": "/\u{FFFD}"}),
json!({"folder": format!("/{}", "x".repeat(4096))}),
json!({"folder": root.join("No Such Folder")}),
]);
let mut started = 0;
for p in &cases {
let r = s.execute("text.findFontFiles", p);
assert!(!internal(&r), "{p}: {r:?}");
if r.is_ok() && p.get("folder").is_some_and(|f| f.is_string()) {
started += 1;
assert_ne!(finished(&mut s)["state"], "searching", "{p}");
}
}
assert!(started > 40, "only {started} searches started");
// After a finished search, files it didn't find aren't copied.
for v in [json!(["/no/such.ttf"]), json!([root.join("readme.ttf")])] {
assert!(s.execute("text.addFontFiles", &json!({"files": v})).is_err());
}
}
/// Reads every file, and waits on reading one until its channel sends or closes.
struct Blocked(Mutex<mpsc::Receiver<()>>);
impl Visitor for Blocked {
fn wants(&self, _: &str) -> bool {
true
}
fn items(&self, _: &Path) -> Vec<usize> {
let _ = self.0.lock().unwrap().recv();
vec![]
}
}
#[test]
fn stop_ends_only_the_search_it_names() {
let root = folder("stop");
std::fs::write(root.join("a.ttf"), b"font").unwrap();
let mut s = session_for(&root);
let (tx, rx) = mpsc::channel();
let search = findfiles::start(root.clone(), s.search_rules.clone(), Limits::default(), 1, 1, Arc::new(Blocked(Mutex::new(rx)))).unwrap();
let fonts = vec![Sought { family: "A".into(), style: "Regular".into(), status: FontMatch::Missing }];
s.font_search = Some(FontSearch { id: 7, folder: root.to_string_lossy().into_owned(), fonts, search });
let until = Instant::now() + Duration::from_secs(10);
while s.execute("text.findFontFiles", &json!({})).unwrap()["searched"]["fontFiles"] != 1 && Instant::now() < until {
std::thread::sleep(Duration::from_millis(2));
}
fontfiles::stop(&mut s, 8);
assert_eq!(s.execute("text.findFontFiles", &json!({})).unwrap()["state"], "searching");
fontfiles::stop(&mut s, 7);
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
assert_eq!((r["state"].as_str(), r["stopped"].as_str(), r["id"].as_u64()), (Some("stopped"), Some("stop"), Some(7)));
drop(tx);
}
#[test]
fn adding_fonts_needs_vectorcraft_s_fonts_folder() {
let mut s = Session::new();
let r = s.execute("text.addFontFiles", &json!({"files": ["/fonts/a.ttf"]}));
assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("isn't set here")), "{r:?}");
// As many files as a search keeps (one for each of 1000 fonts) can be added at once.
let files = |n: usize| json!({"files": (0..n).map(|i| format!("/fonts/{i}.ttf")).collect::<Vec<_>>()});
let r = s.execute("text.addFontFiles", &files(1000));
assert!(matches!(&r, Err(EngineError::Other(m)) if m.contains("isn't set here")), "{r:?}");
assert!(matches!(s.execute("text.addFontFiles", &files(1001)), Err(EngineError::BadParams { .. })));
}
#[test]
fn copying_never_replaces_a_file() {
let root = folder("copy");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dest).unwrap();
std::fs::write(src.join("a.otf"), b"new font").unwrap();
std::fs::write(dest.join("a.otf"), b"keep").unwrap();
let r = copy_into(&[src.join("a.otf")], &dest);
assert_eq!(r.copied, [(src.join("a.otf"), dest.join("a 2.otf"))]);
assert_eq!((std::fs::read(dest.join("a.otf")).unwrap(), std::fs::read(dest.join("a 2.otf")).unwrap()), (b"keep".to_vec(), b"new font".to_vec()));
// The same file again: kept, not copied a third time.
let r = copy_into(&[src.join("a.otf")], &dest);
assert_eq!((r.copied.len(), r.kept.clone()), (0, vec![(src.join("a.otf"), dest.join("a 2.otf"))]));
assert!(!dest.join("a 3.otf").exists());
// A link of that name, even one to nothing, is neither replaced nor written through.
#[cfg(unix)]
{
std::fs::write(src.join("b.otf"), b"b").unwrap();
std::os::unix::fs::symlink(root.join("nothing.otf"), dest.join("b.otf")).unwrap();
let r = copy_into(&[src.join("b.otf")], &dest);
assert_eq!(r.copied, [(src.join("b.otf"), dest.join("b 2.otf"))]);
assert!(!root.join("nothing.otf").exists());
}
// A name taken in another case: on a file system that ignores case, the copy gets a number.
std::fs::write(dest.join("C.OTF"), b"other").unwrap();
std::fs::write(src.join("c.otf"), b"c").unwrap();
let ignores_case = dest.join("c.otf").exists();
let r = copy_into(&[src.join("c.otf")], &dest);
let to = dest.join(if ignores_case { "c 2.otf" } else { "c.otf" });
assert_eq!((r.copied, std::fs::read(dest.join("C.OTF")).unwrap()), (vec![(src.join("c.otf"), to)], b"other".to_vec()));
// Every numbered name taken.
std::fs::write(src.join("d.otf"), b"d").unwrap();
std::fs::write(dest.join("d.otf"), b"other").unwrap();
for n in 2..=99 {
std::fs::write(dest.join(format!("d {n}.otf")), b"other").unwrap();
}
let r = copy_into(&[src.join("d.otf")], &dest);
assert_eq!(r.skipped, [(src.join("d.otf"), "every numbered name for it is taken in the Fonts folder".to_string())]);
// Too large (a sparse file), a folder, and a file that isn't there.
let huge = std::fs::File::create(src.join("huge.otf")).unwrap();
huge.set_len(MAX_FONT_FILE + 1).unwrap();
std::fs::create_dir_all(src.join("folder.otf")).unwrap();
let r = copy_into(&[src.join("huge.otf"), src.join("folder.otf"), src.join("none.otf")], &dest);
let reasons: Vec<&str> = r.skipped.iter().map(|(_, why)| why.as_str()).collect();
assert_eq!(reasons[..2], ["larger than 256 MB", "not a file"]);
assert!(r.copied.is_empty() && reasons.len() == 3, "{r:?}");
assert!(!dest.join("huge.otf").exists() && !dest.join("folder.otf").exists());
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn only_font_files_are_copied() {
let root = folder("allowed");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(&src).unwrap();
std::fs::create_dir_all(&dest).unwrap();
let names = ["notes.txt", "Script", "web.WOFF2", "font.woff"];
for name in names {
std::fs::write(src.join(name), name).unwrap();
}
let r = copy_into(&names.map(|n| src.join(n)), &dest);
let copied: Vec<PathBuf> = r.copied.iter().map(|(from, _)| from.clone()).collect();
assert_eq!(copied, [src.join("web.WOFF2"), src.join("font.woff")]);
let not_a_font = |n: &str| (src.join(n), "not a font file".to_string());
assert_eq!(r.skipped, [not_a_font("notes.txt"), not_a_font("Script")]);
assert!(!dest.join("notes.txt").exists() && !dest.join("Script").exists());
let _ = std::fs::remove_dir_all(&root);
}
/// A search reads no font file larger than Add Fonts copies, and finds a smaller copy of the font.
#[test]
fn a_search_skips_font_files_too_large_to_add() {
let root = folder("too-large");
let (big, small) = (root.join("big").join("Sizeme.otf"), root.join("small").join("Sizeme.otf"));
let font = vectorcraft_testkit::fonts::renamed("Sizeme Sans 3");
for path in [&big, &small] {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, &font).unwrap();
}
// One byte past the limit, without writing it: the file system leaves the rest unallocated.
std::fs::File::options().write(true).open(&big).unwrap().set_len(MAX_FONT_FILE + 1).unwrap();
let mut s = session_for(&root);
// A font no file has keeps the search going through every folder.
s.execute("text.findFontFiles", &json!({"folder": root, "fonts": [{"family": "Sizeme Sans 3"}, {"family": "No Such Sans"}]})).unwrap();
let r = finished(&mut s);
assert_eq!(r["fonts"][0]["files"], json!([small]), "{r}");
let _ = std::fs::remove_dir_all(&root);
}
/// A suitcase font: a file without an extension or with `.suit`, empty but for the fonts in its
/// resource fork, which only macOS keeps. A search finds it, and Add Fonts copies it with its fork.
#[cfg(target_os = "macos")]
#[test]
fn suitcase_fonts_are_found_and_copied_with_their_fork() {
use vectorcraft_testkit::fonts::{renamed, suitcase_fork};
let root = folder("suitcase");
let (src, dest) = (root.join("src"), root.join("dest"));
std::fs::create_dir_all(src.join("sub")).unwrap();
std::fs::create_dir_all(&dest).unwrap();
let suitcase = |path: &Path, family: &str| {
let fork = suitcase_fork(&[renamed(family)]);
std::fs::write(path, b"").unwrap();
std::fs::write(path.join("..namedfork/rsrc"), &fork).unwrap();
fork
};
let found = src.join("sub/Suitme");
let fork = suitcase(&found, "Suitme Sans 3");
// A file without an extension that isn't a suitcase is checked and left out.
std::fs::write(src.join("README"), b"text").unwrap();
let mut s = session_for(&root);
s.execute("text.findFontFiles", &json!({"folder": src, "fonts": [{"family": "Suitme Sans 3"}]})).unwrap();
let r = finished(&mut s);
assert_eq!(r["fonts"][0]["files"], json!([found]), "{r}");
// A suitcase with the `.suit` extension is found too, and a `.suit` file that isn't one is left out.
let suit = src.join("Suited.SUIT");
suitcase(&suit, "Suited Sans 3");
std::fs::write(src.join("Plain.suit"), b"text").unwrap();
// A font no file has keeps the search going through every folder.
s.execute("text.findFontFiles", &json!({"folder": src, "fonts": [{"family": "Suited Sans 3"}, {"family": "No Such Sans"}]})).unwrap();
let r = finished(&mut s);
assert_eq!((r["fonts"][0]["files"].clone(), r["searched"]["fontFiles"].as_u64()), (json!([suit]), Some(2)), "{r}");
let r = copy_into(std::slice::from_ref(&found), &dest);
assert_eq!(r.copied, [(found.clone(), dest.join("Suitme"))]);
assert!(vectorcraft_text::is_suitcase(&dest.join("Suitme")));
assert_eq!(std::fs::read(dest.join("Suitme/..namedfork/rsrc")).unwrap(), fork);
// The same suitcase again is kept; another of that name gets a number.
assert_eq!(copy_into(std::slice::from_ref(&found), &dest).kept, [(found.clone(), dest.join("Suitme"))]);
let other = src.join("Suitme");
suitcase(&other, "Other Sans 33");
assert_eq!(copy_into(std::slice::from_ref(&other), &dest).copied, [(other.clone(), dest.join("Suitme 2"))]);
// A suitcase named like a font file keeps its fork too.
let named = src.join("Suitext.ttf");
let named_fork = suitcase(&named, "Suitext Sans3");
assert_eq!(copy_into(std::slice::from_ref(&named), &dest).copied, [(named.clone(), dest.join("Suitext.ttf"))]);
assert_eq!(std::fs::read(dest.join("Suitext.ttf/..namedfork/rsrc")).unwrap(), named_fork);
// The font scan reads the copies.
let db = vectorcraft_text::FontDb::with_font_dirs(vec![dest.clone()]);
assert_eq!((db.styles("Suitme Sans 3"), db.styles("Other Sans 33")), (vec!["Regular".to_string()], vec!["Regular".to_string()]));
let _ = std::fs::remove_dir_all(&root);
}
+77
View File
@@ -0,0 +1,77 @@
//! VectorCraft's own Fonts folder: a missing font's file, found in a folder, is copied into it
//! without replacing a file there, and type set in the font redraws in it. One test in its own
//! process, so the process-wide font database and Fonts folder start fresh, as when the app starts.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::findfiles::{Rules, plain};
/// `text.findFontFiles {}` once the search ended (10 seconds at most).
fn finished(s: &mut Session) -> Value {
let until = Instant::now() + Duration::from_secs(10);
loop {
let r = s.execute("text.findFontFiles", &json!({})).unwrap();
if r["state"] != "searching" || Instant::now() > until {
return r;
}
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn a_found_font_is_copied_without_replacing_a_file_and_its_type_redraws() {
let root = vectorcraft_testkit::temp_dir("font-folder");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("Downloads/Deep")).unwrap();
let root = plain(std::fs::canonicalize(&root).unwrap());
let fonts = root.join("App Fonts");
vectorcraft_text::set_app_font_dir(fonts.clone());
assert!(vectorcraft_text::system_font_dirs().contains(&fonts));
let file = root.join("Downloads").join("Deep").join("Findme.otf");
std::fs::write(&file, vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let serif = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSerif4-Regular.ttf");
std::fs::copy(serif, root.join("other.ttf")).unwrap();
let mut s = Session::new();
s.search_rules = Some(Rules { user_content: vec![root.clone()], ..Rules::default() });
s.search_threads = Some(2);
s.execute("file.new", &json!({"width": 300, "height": 200})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Findme", "font": "Findme Sans 3"})).unwrap();
let r = s.execute("text.missingFonts", &json!({})).unwrap();
assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["status"].as_str()), (Some("Findme Sans 3"), Some("missing")), "{r}");
s.doc_mut().unwrap().mark_saved();
let revision = s.doc().unwrap().revision;
s.execute("text.findFontFiles", &json!({"folder": root})).unwrap();
let r = finished(&mut s);
assert_eq!((&r["state"], &r["fonts"][0]["files"]), (&json!("done"), &json!([file])), "{r}");
// A file of that name is in the Fonts folder already: it stays, and the copy takes a number.
std::fs::create_dir_all(&fonts).unwrap();
std::fs::write(fonts.join("Findme.otf"), b"keep").unwrap();
let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap();
assert_eq!(r["copied"], json!([{"from": file, "to": fonts.join("Findme 2.otf")}]), "{r}");
assert!(r["faces"].as_u64().is_some_and(|n| n > 0) && r["families"].as_u64().is_some(), "{r}");
assert_eq!(std::fs::read(fonts.join("Findme.otf")).unwrap(), b"keep");
// The type is set in the font now, without editing the document.
let listed = s.execute("text.fonts", &json!({})).unwrap();
let findme = listed.as_array().unwrap().iter().find(|f| f["family"] == "Findme Sans 3").cloned().unwrap();
assert_eq!((findme["status"].as_str(), findme["resolved"]["family"].as_str()), (Some("exact"), Some("Findme Sans 3")), "{findme}");
let st = s.doc().unwrap();
assert!(st.revision > revision && !st.is_dirty());
assert_eq!(s.execute("text.missingFonts", &json!({})).unwrap()["count"], 0);
// The same file again is kept, not copied a third time.
let r = s.execute("text.addFontFiles", &json!({"files": [file]})).unwrap();
assert_eq!((r["copied"].clone(), r["kept"].clone()), (json!([]), json!([{"from": file, "to": fonts.join("Findme 2.otf")}])), "{r}");
assert!(!fonts.join("Findme 3.otf").exists());
// Only files the last search found are copied.
let r = s.execute("text.addFontFiles", &json!({"files": [root.join("other.ttf")]}));
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the last text.findFontFiles search")), "{r:?}");
let _ = std::fs::remove_dir_all(&root);
}
+127 -1
View File
@@ -6,7 +6,9 @@
//! of every kind with random contents) opened, placed or pasted, nor EPS and PostScript files
//! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of
//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions).
//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the
//! font files a folder search reads (damaged fonts, collections whose headers give any count of
//! faces).
//!
//! `PROPTEST_CASES=20000 cargo test -p vectorcraft-engine --test import_fuzz` runs a deeper search.
// Integration tests: unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
@@ -1915,3 +1917,127 @@ proptest! {
}
}
}
// ---------- font files a folder search reads ----------
/// A small font file holding what a folder search reads: an outline table's tag, the `name` and
/// `OS/2` tables of the bundled Source Sans 3 renamed "Findme Sans 3", and an `fvar` table with a
/// weight axis and three named instances (named by name ids 2, 1 and 4).
fn search_font() -> Vec<u8> {
let font = vectorcraft_testkit::fonts::renamed("Findme Sans 3");
let be32 = |at: usize| u32::from_be_bytes(font[at..at + 4].try_into().unwrap()) as usize;
let table = |tag: &[u8; 4]| {
let n = u16::from_be_bytes([font[4], font[5]]) as usize;
let r = (0..n).map(|i| 12 + 16 * i).find(|&r| &font[r..r + 4] == tag).unwrap();
font[be32(r + 8)..be32(r + 8) + be32(r + 12)].to_vec()
};
// fvar 1.0: the axis array at 16, one axis of 20 bytes, three instances of 8.
let mut fvar = vec![];
for v in [1u16, 0, 16, 2, 1, 20, 3, 8] {
fvar.extend(v.to_be_bytes());
}
fvar.extend(b"wght");
for v in [100i32, 400, 900] {
fvar.extend((v << 16).to_be_bytes());
}
fvar.extend([0, 0, 1, 0]);
for (name, weight) in [(2u16, 300i32), (1, 600), (4, 900)] {
fvar.extend(name.to_be_bytes());
fvar.extend(0u16.to_be_bytes());
fvar.extend((weight << 16).to_be_bytes());
}
let tables: [(&[u8; 4], Vec<u8>); 4] = [(b"OS/2", table(b"OS/2")), (b"fvar", fvar), (b"glyf", vec![0; 4]), (b"name", table(b"name"))];
let mut out = 0x0001_0000_u32.to_be_bytes().to_vec();
for v in [tables.len() as u16, 0, 0, 0] {
out.extend(v.to_be_bytes());
}
let mut offset = 12 + 16 * tables.len();
for (tag, data) in &tables {
out.extend(*tag);
for v in [0, offset as u32, data.len() as u32] {
out.extend(v.to_be_bytes());
}
offset += data.len().next_multiple_of(4);
}
for (_, data) in &tables {
out.extend(data);
out.resize(out.len().next_multiple_of(4), 0);
}
out
}
/// `font` as a collection of `faces % 5` faces that all read it, whose header gives `faces` as the
/// count.
fn search_collection(font: &[u8], faces: u32) -> Vec<u8> {
let k = (faces % 5) as usize;
let base = 12 + 4 * k;
let mut out = b"ttcf".to_vec();
out.extend(0x0001_0000_u32.to_be_bytes());
out.extend(faces.to_be_bytes());
for _ in 0..k {
out.extend((base as u32).to_be_bytes());
}
// The tables' offsets count from the start of the collection.
let mut f = font.to_vec();
let n = u16::from_be_bytes([f[4], f[5]]) as usize;
for i in 0..n {
let at = 12 + 16 * i + 8;
let offset = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) + base as u32;
f[at..at + 4].copy_from_slice(&offset.to_be_bytes());
}
out.extend(f);
out
}
/// The fonts a search for "Findme Sans 3" looks for: the face, and a style of the family as if the
/// family were installed.
fn findme_wanted() -> vectorcraft_text::WantedFonts {
use vectorcraft_text::WantedFont;
vectorcraft_text::WantedFonts::new(&[
WantedFont { family: "Findme Sans 3".into(), style: "Regular".into(), installed: None },
WantedFont { family: "FINDME SANS 3".into(), style: "Black".into(), installed: Some("Findme Sans 3".into()) },
WantedFont { family: "SourceSans3-Regular".into(), style: "Bold".into(), installed: None },
])
}
/// Whether reading `bytes` as a font file a search reads panics.
fn search_reads(what: &str, bytes: &[u8]) -> Result<Vec<usize>, TestCaseError> {
let path = vectorcraft_testkit::temp_dir("font-search-fuzz").join(format!("{:?}.ttc", std::thread::current().id()));
std::fs::write(&path, bytes).unwrap();
catch_quiet(|| findme_wanted().provided_by(&path)).map_err(|e| TestCaseError::fail(format!("{what}: a search reading the file panicked: {e}")))
}
/// The samples the fuzz properties mutate reach the matching: each provides the face it names.
#[test]
fn the_search_font_samples_are_read_whole() {
let font = search_font();
assert_eq!(search_reads("font", &font).unwrap(), [0, 2]);
assert_eq!(search_reads("collection", &search_collection(&font, 3)).unwrap(), [0, 2]);
// Two faces, and a header that gives seven.
assert_eq!(search_reads("collection claiming more faces", &search_collection(&font, 7)).unwrap(), [0, 2]);
}
proptest! {
#![proptest_config(config())]
#[test]
fn font_files_a_search_reads_never_panic(
faces in prop::option::of(any::<u32>()),
cut in prop::option::of(0usize..12_000),
edits in prop::collection::vec((0usize..12_000, any::<u8>()), 0..12),
) {
let font = search_font();
let mut bytes = match faces {
Some(n) => search_collection(&font, n),
None => font,
};
for (at, b) in edits {
let n = bytes.len();
bytes[at % n] = b;
}
if let Some(cut) = cut {
bytes.truncate(cut);
}
search_reads("mutated font file", &bytes)?;
}
}
+103
View File
@@ -1,5 +1,6 @@
//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed
//! or interrupted write never leaves a damaged file behind (the old one stays as it was).
//! [`write_new_with`] creates a file the same way without ever replacing one.
use std::fs::{File, OpenOptions};
use std::io::{self, Write as _};
@@ -26,6 +27,48 @@ pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result
})
}
/// Create `path` with the content `fill` writes, never replacing a file or a link of that name. The
/// content goes to a temporary file beside it, which is then linked in under `path`
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
/// it. The temporary file is always removed.
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
}
/// [`write_new_with`], with `link` linking the temporary file in under `path`.
fn write_new_linking(
path: &Path,
fill: impl FnOnce(&mut File) -> io::Result<()>,
link: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let tmp = temp_path(path)?;
let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?;
let filled = fill(&mut f).and_then(|()| f.sync_all());
drop(f);
let placed = filled.and_then(|()| match link(&tmp, path) {
Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path),
linked => linked,
});
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&tmp);
placed
}
/// Create `path` (never replacing anything) with the content of the file `from`; a failed copy
/// removes it again.
fn copy_new(from: &Path, path: &Path) -> io::Result<()> {
let mut to = OpenOptions::new().write(true).create_new(true).open(path)?;
let copied = File::open(from).and_then(|mut f| io::copy(&mut f, &mut to)).and_then(|_| to.sync_all());
drop(to);
if copied.is_err() {
// Best effort: the part copied is all there is to clean up.
let _ = std::fs::remove_file(path);
}
copied
}
/// A symbolic link keeps pointing at its file: write the file it names.
fn resolve_link(path: &Path) -> io::Result<PathBuf> {
match std::fs::symlink_metadata(path) {
@@ -93,4 +136,64 @@ mod tests {
assert!(write_atomic(&d.join("missing").join("x.vectorcraft"), b"x").is_err());
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn write_new_never_replaces_what_is_there() {
let d = dir("new");
let path = d.join("a.otf");
write_new_with(&path, |f| f.write_all(b"first")).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty(), "the temporary file is removed");
let r = write_new_with(&path, |f| f.write_all(b"second"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"first");
assert!(leftovers(&d, "a.otf").is_empty());
// A failed write leaves nothing.
let failed = d.join("b.otf");
assert!(write_new_with(&failed, |f| f.write_all(b"half").and(Err(io::Error::other("disk full")))).is_err());
assert!(!failed.exists() && leftovers(&d, "a.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// Where hard links fail (a file system without them), the content is copied in, and a taken
/// name stays as it was. A link that fails because the name is taken copies nothing.
#[test]
fn write_new_copies_where_hard_links_fail() {
let d = dir("new-copy");
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
let path = d.join("c.otf");
write_new_linking(&path, |f| f.write_all(b"copied"), unsupported).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
assert!(leftovers(&d, "c.otf").is_empty(), "the temporary file is removed");
let r = write_new_linking(&path, |f| f.write_all(b"second"), unsupported);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert_eq!(std::fs::read(&path).unwrap(), b"copied");
let taken = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists));
let other = d.join("d.otf");
let r = write_new_linking(&other, |f| f.write_all(b"other"), taken);
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists));
assert!(!other.exists() && leftovers(&d, "c.otf").is_empty());
let _ = std::fs::remove_dir_all(&d);
}
/// A link of that name, even one to nothing, is never replaced or written through.
#[cfg(unix)]
#[test]
fn write_new_leaves_links_alone() {
let d = dir("new-links");
let target = d.join("target.otf");
std::fs::write(&target, b"target").unwrap();
std::os::unix::fs::symlink(&target, d.join("link.otf")).unwrap();
std::os::unix::fs::symlink(d.join("nothing.otf"), d.join("dangling.otf")).unwrap();
for name in ["link.otf", "dangling.otf"] {
let r = write_new_with(&d.join(name), |f| f.write_all(b"new"));
assert_eq!(r.map_err(|e| e.kind()), Err(io::ErrorKind::AlreadyExists), "{name}");
}
assert_eq!(std::fs::read(&target).unwrap(), b"target");
assert!(!d.join("nothing.otf").exists());
let mut names: Vec<String> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
names.sort();
assert_eq!(names, ["dangling.otf", "link.otf", "target.otf"], "no temporary file is left");
let _ = std::fs::remove_dir_all(&d);
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ use serde::{Deserialize, Serialize};
use vectorcraft_doc::{Document, ImageBlob};
#[cfg(not(target_arch = "wasm32"))]
pub use atomic::{write_atomic, write_atomic_with};
pub use atomic::{write_atomic, write_atomic_with, write_new_with};
/// v4: large data after the JSON (v1 to v3 files still load).
pub const VERSION: u32 = 4;
+69
View File
@@ -0,0 +1,69 @@
//! Font files for tests, made from the bundled fonts when a test runs: no font file is committed.
/// The bundled Source Sans 3 Regular with its family renamed `family` in every record of its name
/// table, UTF-16 and ASCII alike. `family` must be as long as "Source Sans 3" (13 bytes). The
/// PostScript name stays `SourceSans3-Regular`.
pub fn renamed(family: &str) -> Vec<u8> {
const ORIGINAL: &str = "Source Sans 3";
assert_eq!(family.len(), ORIGINAL.len(), "`{family}` must be 13 bytes long");
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
let mut data = std::fs::read(path).unwrap();
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
for (from, to) in [(utf16(ORIGINAL), utf16(family)), (ORIGINAL.as_bytes().to_vec(), family.as_bytes().to_vec())] {
let mut i = 0;
while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) {
data[i + at..i + at + to.len()].copy_from_slice(&to);
i += at + to.len();
}
}
data
}
/// A resource fork holding `fonts` as `sfnt` resources and one other resource (a `vers`), as a font
/// utility writes a suitcase font's fork, and as vectorcraft-text's suitcase tests build one. macOS
/// keeps a file's resource fork at `<file>/..namedfork/rsrc`.
pub fn suitcase_fork(fonts: &[Vec<u8>]) -> Vec<u8> {
let mut data = Vec::new();
let mut offsets = Vec::new();
for body in fonts.iter().map(Vec::as_slice).chain([&b"1.0"[..]]) {
offsets.push(data.len() as u32);
data.extend_from_slice(&(body.len() as u32).to_be_bytes());
data.extend_from_slice(body);
}
let n = fonts.len();
// The type list: `vers` (1 resource) then `sfnt`, each entry pointing at its references.
let list = 2 + 2 * 8;
let mut types = Vec::new();
types.extend_from_slice(&1u16.to_be_bytes());
types.extend_from_slice(b"vers");
types.extend_from_slice(&0u16.to_be_bytes());
types.extend_from_slice(&(list as u16).to_be_bytes());
types.extend_from_slice(b"sfnt");
types.extend_from_slice(&((n - 1) as u16).to_be_bytes());
types.extend_from_slice(&((list + 12) as u16).to_be_bytes());
let reference = |id: i16, offset: u32| {
let mut r = Vec::new();
r.extend_from_slice(&id.to_be_bytes());
r.extend_from_slice(&0xFFFFu16.to_be_bytes());
r.extend_from_slice(&offset.to_be_bytes());
r.extend_from_slice(&[0; 4]);
r
};
types.extend(reference(1, offsets[n]));
for (i, o) in offsets[..n].iter().enumerate() {
types.extend(reference(5000 + i as i16, *o));
}
// The map: a copy of the header, a handle, attributes, then the offsets of the lists.
let mut map = vec![0; 24];
map.extend_from_slice(&28u16.to_be_bytes());
map.extend_from_slice(&((28 + types.len()) as u16).to_be_bytes());
map.extend(types);
let mut fork = Vec::new();
for v in [256u32, 256 + data.len() as u32, data.len() as u32, map.len() as u32] {
fork.extend_from_slice(&v.to_be_bytes());
}
fork.resize(256, 0);
fork.extend(data);
fork.extend(map);
fork
}
+2
View File
@@ -12,6 +12,7 @@
//! - [`pdf`]: hand-written PDF files (page boxes, colour spaces, encryption) for import tests.
//! - [`ai`]: hand-written Illustrator editing data, and the EPS and `.ai` files that carry it.
//! - [`ase`]: hand-written swatch exchange (`.ase`) files for swatch library tests.
//! - [`fonts`]: font files made from the bundled fonts (a renamed family) for font tests.
//!
//! This crate may only be used as a dev-dependency (enforced by `cargo xtask layers`).
// Test support only (a dev-dependency of every crate that uses it): a failed setup or assertion
@@ -23,6 +24,7 @@
pub mod ai;
pub mod ase;
pub mod fixtures;
pub mod fonts;
pub mod geom;
pub mod invariants;
pub mod pdf;
+208 -15
View File
@@ -801,28 +801,45 @@ fn font_files(path: &Path) -> Vec<Vec<u8>> {
const OUTLINE_TABLES: [&[u8; 4]; 4] = [b"glyf", b"CFF ", b"CFF2", b"VARC"];
/// The styles of every face in the font file at `path` ([`face_styles`]), reading only its table
/// directories and `name` and `fvar` tables: a scan opens hundreds of font files, many of them
/// megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table) are
/// left out.
/// directories and `name`, `fvar` and `OS/2` tables: a scan opens hundreds of font files, many of
/// them megabytes long. Faces without outlines the font engine draws (no [`OUTLINE_TABLES`] table)
/// are left out.
#[cfg(not(target_arch = "wasm32"))]
fn file_face_names(path: &Path) -> Vec<FaceStyle> {
/// The most faces read from a (possibly damaged) collection.
const MAX_FACES: u32 = 256;
file_face_names_within(path, MAX_FACES, u64::MAX)
}
/// [`file_face_names`], reading at most `max_faces` faces and `max_read` bytes of the file in all.
/// A suitcase font's resource fork is read whole when it is at most `max_read` bytes long, and the
/// limits then apply to each of its fonts; a longer fork gives none.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn file_face_names_within(path: &Path, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
if crate::suitcase::is_suitcase(path) {
return crate::suitcase::read_fonts(path).into_iter().flat_map(|font| reader_face_names(std::io::Cursor::new(font))).collect();
if crate::suitcase::fork_len(path) > max_read {
return vec![];
}
return crate::suitcase::read_fonts(path)
.into_iter()
.flat_map(|font| reader_face_names_within(std::io::Cursor::new(font), max_faces, max_read))
.collect();
}
match std::fs::File::open(path) {
Ok(file) => reader_face_names(file),
Ok(file) => reader_face_names_within(file, max_faces, max_read),
Err(_) => vec![],
}
}
/// [`file_face_names`] for the font file `file` reads.
/// [`file_face_names_within`] for the font file `file` reads.
#[cfg(not(target_arch = "wasm32"))]
fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceStyle> {
fn reader_face_names_within(mut file: impl std::io::Read + std::io::Seek, max_faces: u32, max_read: u64) -> Vec<FaceStyle> {
use std::io::SeekFrom;
/// Caps on what a (possibly damaged) file can make the scan read.
const MAX_FACES: u32 = 256;
/// The largest table read from a (possibly damaged) file.
const MAX_NAME_TABLE: u32 = 1 << 20;
let mut read = 0u64;
let mut read_at = |offset: u64, len: usize| -> Option<Vec<u8>> {
read = read.checked_add(u64::try_from(len).ok()?).filter(|r| *r <= max_read)?;
let mut buf = vec![0; len];
file.seek(SeekFrom::Start(offset)).ok()?;
file.read_exact(&mut buf).ok()?;
@@ -832,7 +849,7 @@ fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceSt
let Some(head) = read_at(0, 12) else { return vec![] };
// A collection lists where each face's table directory starts.
let starts: Vec<u32> = if head.starts_with(b"ttcf") {
let n = be32(&head, 8).unwrap_or(0).min(MAX_FACES) as usize;
let n = be32(&head, 8).unwrap_or(0).min(max_faces) as usize;
read_at(12, n * 4).map(|b| b.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes(*c)).collect()).unwrap_or_default()
} else {
vec![0]
@@ -874,6 +891,157 @@ fn reader_face_names(mut file: impl std::io::Read + std::io::Seek) -> Vec<FaceSt
.collect()
}
/// Whether the file at `path` is a font file by its extension (`.ttf`, `.otf`, `.ttc` or `.otc`,
/// in any case), as the font scan reads the files in a folder.
pub fn is_font_file(path: &Path) -> bool {
path.extension().and_then(|e| e.to_str()).is_some_and(|e| ["ttf", "otf", "ttc", "otc"].iter().any(|x| e.eq_ignore_ascii_case(x)))
}
/// Whether the file at `path` is a suitcase font ([`crate::suitcase`]): on macOS, a file with
/// nothing in its data and its fonts in its resource fork. Never on the web.
pub fn is_suitcase(path: &Path) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
crate::suitcase::is_suitcase(path)
}
#[cfg(target_arch = "wasm32")]
{
let _ = path;
false
}
}
/// A font a document names that isn't available, to look for in font files ([`WantedFonts`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WantedFont {
pub family: String,
pub style: String,
/// When the family is installed but not the style ([`FontMatch::Style`]): the family of the
/// face [`FontDb::resolve`] gives instead. `None` when the family is missing.
pub installed: Option<String>,
}
/// Fonts to look for in font files: [`WantedFonts::provided_by`] tells which of them a file
/// provides.
#[derive(Debug, Default)]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub struct WantedFonts {
fonts: Vec<WantedFont>,
/// The indexes of the fonts by every name a face could answer to them by: the family as given
/// and the installed family (ASCII-lowercased), and the family normalized ([`norm`]).
by_name: HashMap<String, Vec<usize>>,
}
impl WantedFonts {
/// The most faces and bytes of one file a search reads.
#[cfg(not(target_arch = "wasm32"))]
const SEARCH_FACES: u32 = 64;
#[cfg(not(target_arch = "wasm32"))]
const SEARCH_READ: u64 = 8 << 20;
pub fn new(fonts: &[WantedFont]) -> Self {
let mut by_name: HashMap<String, Vec<usize>> = HashMap::new();
for (i, w) in fonts.iter().enumerate() {
let mut names = vec![w.family.to_ascii_lowercase(), norm(&w.family)];
names.extend(w.installed.as_ref().map(|c| c.to_ascii_lowercase()));
names.sort();
names.dedup();
for n in names.into_iter().filter(|n| !n.is_empty()) {
by_name.entry(n).or_default().push(i);
}
}
Self { fonts: fonts.to_vec(), by_name }
}
pub fn len(&self) -> usize {
self.fonts.len()
}
pub fn is_empty(&self) -> bool {
self.fonts.is_empty()
}
/// The indexes of the fonts that the font file at `path` provides: copied into a folder the
/// font scan reads, the file makes [`FontDb::resolve`] find each of them exactly, in one of its
/// faces or a variable font's named instances. The file is read as the scan reads it (its
/// table directories and its `name`, `fvar` and `OS/2` tables), at most 64 faces and 8 MB of
/// it, when it is a font file by its extension ([`is_font_file`]) or a suitcase font whose
/// resource fork is at most 8 MB long. Sorted; none on the web.
pub fn provided_by(&self, path: &Path) -> Vec<usize> {
#[cfg(not(target_arch = "wasm32"))]
{
if !is_font_file(path) && !crate::suitcase::is_suitcase(path) {
return Vec::new();
}
let faces = file_face_names_within(path, Self::SEARCH_FACES, Self::SEARCH_READ);
self.provided_by_faces(&faces)
}
#[cfg(target_arch = "wasm32")]
{
let _ = path;
Vec::new()
}
}
/// [`Self::provided_by`] for the faces of a file.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn provided_by_faces(&self, faces: &[FaceStyle]) -> Vec<usize> {
let mut candidates: Vec<usize> = Vec::new();
for f in faces {
let names = std::iter::once(f.family.to_ascii_lowercase())
.chain(f.keys.families.iter().cloned())
.chain(f.keys.legacy.iter().map(|(family, _)| family.clone()))
.chain(f.keys.postscript.iter().cloned());
for n in names {
candidates.extend(self.by_name.get(&n).into_iter().flatten());
}
}
candidates.sort_unstable();
candidates.dedup();
candidates.retain(|i| self.fonts.get(*i).is_some_and(|w| provides(w, faces)));
candidates
}
}
/// Whether the faces of a font file, cataloged by a rescan, make [`FontDb::resolve`] find `w`
/// exactly in one of them: [`FontDb::canonical`] and [`FontDb::find`] over these faces, as they
/// would run once the file is cataloged.
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
fn provides(w: &WantedFont, faces: &[FaceStyle]) -> bool {
let sk = norm(&w.style);
// A face of `family` with the style among its style names, as `find` looks for it once the
// family's files are loaded.
let styled = |family: &str| faces.iter().any(|f| f.family.eq_ignore_ascii_case(family) && f.keys.styles.contains(&sk));
let named_as_given = faces.iter().any(|f| f.family.eq_ignore_ascii_case(&w.family));
if let Some(installed) = &w.installed {
// A family cataloged by the name as given is found by it.
if named_as_given && !w.family.eq_ignore_ascii_case(installed) {
return styled(&w.family);
}
// The installed family is loaded: a face of it is loaded from the file only when its own
// style is the one asked for (`is_cataloged`).
return faces.iter().any(|f| f.family.eq_ignore_ascii_case(installed) && norm(&f.style) == sk);
}
if named_as_given {
return styled(&w.family);
}
let key = norm(&w.family);
if key.is_empty() {
return false;
}
// Another of a family's names keeps the style asked for.
if let Some(f) = faces.iter().find(|f| f.keys.families.contains(&key)) {
return styled(&f.family);
}
// A legacy family with its legacy style, or a PostScript name, names its face whatever style
// is asked for.
if faces.iter().any(|f| f.keys.legacy.iter().any(|(family, style)| *family == key && *style == sk) || f.keys.postscript.contains(&key)) {
return true;
}
// A legacy family with another style: that style of the family.
faces.iter().find(|f| f.keys.legacy.iter().any(|(family, _)| *family == key)).is_some_and(|f| styled(&f.family))
}
/// A font file holding `tables` (tag, data), sorted by tag as table directories are.
#[cfg(any(test, not(target_arch = "wasm32")))]
pub(crate) fn sfnt_of(tables: &[(&[u8; 4], &[u8])]) -> Option<Vec<u8>> {
@@ -947,9 +1115,34 @@ pub fn user_font_dirs() -> Vec<PathBuf> {
Vec::new()
}
/// The platform's font folders (the system's and the user's) and the font files known to it
/// outside them (on Windows those registered with it, and those [`set_platform_font_files`]
/// lists), scanned by [`FontDb::global`].
/// VectorCraft's own Fonts folder, set by the app ([`set_app_font_dir`]).
#[cfg(not(target_arch = "wasm32"))]
static APP_FONT_DIR: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
/// Have [`system_font_dirs`] read `dir` with its subfolders: VectorCraft's own Fonts folder, which
/// `text.addFontFiles` copies font files into. The desktop app and `vectorcraft-cli` set it before
/// the first scan, as they install [`set_platform_font_files`]. A folder that doesn't exist yet is
/// read once it does. Only the first call counts. Ignored on wasm.
pub fn set_app_font_dir(dir: PathBuf) {
#[cfg(not(target_arch = "wasm32"))]
// A second call keeps the first folder, as documented.
let _ = APP_FONT_DIR.set(dir);
#[cfg(target_arch = "wasm32")]
let _ = dir;
}
/// The folder [`set_app_font_dir`] set: none before that, and none on wasm.
pub fn app_font_dir() -> Option<&'static Path> {
#[cfg(not(target_arch = "wasm32"))]
return APP_FONT_DIR.get().map(PathBuf::as_path);
#[cfg(target_arch = "wasm32")]
None
}
/// The platform's font folders (the system's and the user's), VectorCraft's own Fonts folder
/// ([`set_app_font_dir`]), the font files known to the platform outside them (on Windows those
/// registered with it, and those [`set_platform_font_files`] lists) and the folders the user added
/// ([`set_user_font_dirs`]), scanned by [`FontDb::global`].
pub fn system_font_dirs() -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
if cfg!(target_arch = "wasm32") {
@@ -990,6 +1183,7 @@ pub fn system_font_dirs() -> Vec<PathBuf> {
// In a Flatpak sandbox, the host's fonts (system, local and the user's).
dirs.extend(["/run/host/fonts", "/run/host/local-fonts", "/run/host/user-fonts"].map(Into::into));
}
dirs.extend(app_font_dir().map(Path::to_path_buf));
#[cfg(not(target_arch = "wasm32"))]
if let Some(list) = PLATFORM_FONT_FILES.get() {
let files = fonts_outside(list(), &dirs);
@@ -1402,8 +1596,7 @@ impl FontDb {
// A file named by itself is a font whatever its name (font services keep fonts in
// files without an extension); one of a folder's only with a font's extension, or
// a suitcase font (whose fonts are in its resource fork, whatever its name).
let ext = p.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
if !named && !matches!(ext.as_deref(), Some("ttf" | "otf" | "ttc" | "otc")) && !crate::suitcase::is_suitcase(&p) {
if !named && !is_font_file(&p) && !crate::suitcase::is_suitcase(&p) {
continue;
}
for FaceStyle { family, style, keys, weight, italic, traits, .. } in file_face_names(&p) {
+2 -2
View File
@@ -27,8 +27,8 @@ pub mod thread;
pub use craft_fonts::{CRAFT_FONTS, CraftFont, WEB_FONTS, WebFont};
pub use features::{LIGATURE_TRACKING_LIMITS, OtFeatures, explicit_ligatures, ligatures_suppressed_by};
pub use fontdb::{
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, set_platform_font_files, set_user_font_dirs,
style_weight, system_font_dirs, user_font_dirs,
FALLBACK_FAMILY, FontClass, FontDb, FontFace, FontMatch, FontTraits, IcfMargins, PlatformFontFiles, WantedFont, WantedFonts, app_font_dir,
is_font_file, is_suitcase, set_app_font_dir, set_platform_font_files, set_user_font_dirs, style_weight, system_font_dirs, user_font_dirs,
};
pub use hyphen::{hyphenation_exceptions, set_hyphenation_exceptions};
use kurbo::{Affine, BezPath, Point, Rect, Vec2};
+2 -2
View File
@@ -78,7 +78,7 @@ fn fork_path(path: &Path) -> std::path::PathBuf {
}
#[cfg(target_os = "macos")]
fn fork_len(path: &Path) -> u64 {
pub(crate) fn fork_len(path: &Path) -> u64 {
std::fs::metadata(fork_path(path)).map_or(0, |m| m.len())
}
@@ -91,7 +91,7 @@ fn read_fork(path: &Path) -> Option<Vec<u8>> {
}
#[cfg(not(target_os = "macos"))]
fn fork_len(_: &Path) -> u64 {
pub(crate) fn fork_len(_: &Path) -> u64 {
0
}
+229
View File
@@ -318,3 +318,232 @@ fn the_scan_reads_suitcase_fonts() {
assert_eq!(bold.path(), Some(suitcase.as_path()));
assert_eq!(db.find_family("SysfontSans3").as_deref(), Some(FAMILY), "by a PostScript-style name, as an EPS names it");
}
/// The bundled Source Sans 3 Regular with a `name` table of `records` (platform, language, name id,
/// text): Windows Unicode (UTF-16) or Mac Roman (ASCII here).
fn named(records: &[(u16, u16, u16, &str)]) -> Vec<u8> {
let mut records = records.to_vec();
records.sort_by_key(|r| (r.0, r.1, r.2));
let (mut name, mut strings) = (vec![], vec![]);
let n = records.len() as u16;
for v in [0, n, 6 + 12 * n] {
name.extend_from_slice(&v.to_be_bytes());
}
for &(platform, lang, id, s) in &records {
let bytes: Vec<u8> = if platform == 3 { s.encode_utf16().flat_map(u16::to_be_bytes).collect() } else { s.as_bytes().to_vec() };
let encoding = if platform == 3 { 1 } else { 0 };
for v in [platform, encoding, lang, id, bytes.len() as u16, strings.len() as u16] {
name.extend_from_slice(&v.to_be_bytes());
}
strings.extend(bytes);
}
name.extend(strings);
let base = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf")).unwrap();
let font = skrifa::FontRef::new(&base).unwrap();
let mut builder = write_fonts::FontBuilder::new();
builder.add_raw(write_fonts::types::Tag::new(b"name"), name);
for r in font.table_directory.table_records() {
let tag = write_fonts::types::Tag::new(&r.tag().to_be_bytes());
if !builder.contains(tag) {
builder.add_raw(tag, font.table_data(r.tag()).unwrap().as_bytes());
}
}
builder.build()
}
const EN: u16 = 0x0409;
const JA: u16 = 0x0411;
/// Copying a file a search offers into a folder the scan reads makes the font resolve exactly from
/// that file, and a file it doesn't offer doesn't: the search matches fonts as `resolve` finds
/// them. Each case resolves the font, copies the file into a scanned folder, rescans and resolves
/// again, as the app does.
#[test]
fn wanted_fonts_match_as_resolve_finds_them() {
let one = named(&[(3, EN, 1, "Parity One"), (3, EN, 2, "Regular"), (3, EN, 6, "ParityOne-Regular")]);
let two = named(&[
(3, EN, 1, "Parity Two"),
(3, EN, 2, "Regular"),
(3, EN, 6, "ParityTwo-Regular"),
(3, EN, 16, "Parity Two"),
(3, JA, 16, "パリティ二"),
(3, EN, 17, "Regular"),
]);
// Laid out like Hiragino Sans W3: a legacy family per weight, paired with its legacy style, and
// a PostScript name that reads as the legacy family.
let three = |postscript: &str| {
named(&[
(1, 0, 1, "Parity Three"),
(1, 0, 2, "W3"),
(3, EN, 1, "Parity Three W3"),
(3, EN, 2, "Regular"),
(3, EN, 6, postscript),
(3, EN, 16, "Parity Three"),
(3, EN, 17, "W3"),
(3, JA, 1, "パリティ三 W3"),
(3, JA, 2, "Regular"),
(3, JA, 16, "パリティ三"),
(3, JA, 17, "W3"),
])
};
let (three, three_ps) = (three("ParityThree-W3"), three("PThree-W3"));
// A PostScript name that is the family's name.
let findme = named(&[(3, EN, 1, "Findme"), (3, EN, 2, "Regular"), (3, EN, 6, "Findme")]);
let psdiff = named(&[(3, EN, 1, "Psdiff Sans"), (3, EN, 2, "Regular"), (3, EN, 6, "PsdiffSans-Regular")]);
let variable = crate::test_fonts::variable_font().unwrap();
let four = |style: &str, ja_style: &str| {
named(&[
(3, EN, 1, "Parity Four"),
(3, EN, 2, style),
(3, EN, 6, &format!("ParityFour-{style}")),
(3, EN, 16, "Parity Four"),
(3, EN, 17, style),
(3, JA, 16, "パリティ四"),
(3, JA, 17, ja_style),
])
};
let (four_regular, four_bold) = (four("Regular", "標準"), four("Bold", "太字"));
let five = named(&[(3, EN, 1, "Parity Five"), (3, EN, 2, "Bold"), (3, EN, 6, "ParityFive-Bold"), (3, EN, 17, "Bold"), (3, JA, 17, "太字")]);
// (family, style, Parity Four Regular installed, candidate file, provides it)
let cases: Vec<(&str, &str, bool, &[u8], bool)> = vec![
("Parity One", "Regular", false, &one, true),
("parity one", "REGULAR", false, &one, true),
("Parity One", "Bold", false, &one, false),
("Parity One", "Regular", false, &four_bold, false),
("パリティ二", "Regular", false, &two, true),
("パリティ二", "Bold", false, &two, false),
("Parity Three W3", "Regular", false, &three_ps, true),
("Parity Three W3", "Bold", false, &three_ps, false),
("PThree-W3", "Bold", false, &three_ps, true),
// The legacy family reads as the PostScript name, which names the W3 face.
("Parity Three W3", "Bold", false, &three, true),
("パリティ三", "W3", false, &three, true),
("パリティ三", "Bold", false, &three, false),
("Findme", "Bold", false, &findme, false),
("Find-me", "Regular", false, &findme, true),
// A family's name goes before a PostScript name that reads the same.
("Find-me", "Bold", false, &findme, false),
("PsdiffSans-Regular", "Bold", false, &psdiff, true),
("Varitest Sans", "SemiBold", false, &variable, true),
("Varitest Sans", "Normal", false, &variable, true),
("VaritestSans-Bold", "Regular", false, &variable, true),
("Varitest Sans", "Black", false, &variable, false),
("Parity Five", "太字", false, &five, true),
("Parity Four", "Bold", true, &four_bold, true),
("パリティ四", "Bold", true, &four_bold, true),
("Parity Four", "太字", true, &four_bold, false),
("Parity Four", "Bold", true, &one, false),
];
for (i, (family, style, installed, candidate, provides)) in cases.into_iter().enumerate() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-wanted-{i}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let (base, new) = (dir.join("base"), dir.join("new"));
std::fs::create_dir_all(&base).unwrap();
std::fs::create_dir_all(&new).unwrap();
if installed {
std::fs::write(base.join("ParityFour-Regular.ttf"), &four_regular).unwrap();
}
let db = FontDb::with_font_dirs(vec![base, new.clone()]);
let (face, m) = db.resolve(family, style).unwrap();
assert_eq!(m, if installed { FontMatch::Style } else { FontMatch::Missing }, "case {i}: {family} {style}");
let wanted = WantedFont { family: family.into(), style: style.into(), installed: (m == FontMatch::Style).then(|| face.family.clone()) };
let file = new.join("Candidate.ttf");
std::fs::write(&file, candidate).unwrap();
db.load_system_fonts();
let (face, m) = db.resolve(family, style).unwrap();
let exact = m == FontMatch::Exact && face.path().map(|p| std::fs::canonicalize(p).unwrap()) == Some(std::fs::canonicalize(&file).unwrap());
assert_eq!(exact, provides, "case {i}: resolve gave {face:?} {m:?} for {family} {style}");
assert_eq!(WantedFonts::new(&[wanted]).provided_by(&file) == [0], provides, "case {i}: the search, for {family} {style}");
let _ = std::fs::remove_dir_all(&dir);
}
}
/// A search reads only so much of a file: of a collection whose header gives 300 faces it reads
/// the first 64, and a cap on the bytes read ends it early.
#[test]
fn a_search_reads_at_most_its_share_of_a_font_file() {
use crate::fontdb::file_face_names_within;
let face = renamed("SourceSans3-Regular.ttf");
let tables = u16::from_be_bytes([face[4], face[5]]) as usize;
let len = |tag: &[u8]| {
let r = (0..tables).map(|i| 12 + 16 * i).find(|&r| &face[r..r + 4] == tag).unwrap();
u64::from(u32::from_be_bytes(face[r + 12..r + 16].try_into().unwrap()))
};
// What one face costs: its table directory and its name and OS/2 tables.
let per_face = 12 + 16 * tables as u64 + len(b"name") + len(b"OS/2");
let n = 300;
let base = 12 + 4 * n;
let mut ttc = b"ttcf".to_vec();
ttc.extend_from_slice(&0x0001_0000_u32.to_be_bytes());
ttc.extend_from_slice(&(n as u32).to_be_bytes());
for _ in 0..n {
ttc.extend_from_slice(&(base as u32).to_be_bytes());
}
// Every face is the one font, whose table offsets count from the start of the collection.
let mut f = face.clone();
for r in 0..tables {
let at = 12 + r * 16 + 8;
let off = u32::from_be_bytes(f[at..at + 4].try_into().unwrap()) + base as u32;
f[at..at + 4].copy_from_slice(&off.to_be_bytes());
}
ttc.extend(f);
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-many", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Many.ttc");
std::fs::write(&file, ttc).unwrap();
assert_eq!(file_face_names_within(&file, 256, u64::MAX).len(), 256);
assert_eq!(file_face_names_within(&file, 64, u64::MAX).len(), 64);
// The header, 64 offsets and three faces.
assert_eq!(file_face_names_within(&file, 64, 12 + 4 * 64 + 3 * per_face).len(), 3);
let wanted = WantedFonts::new(&[WantedFont { family: FAMILY.into(), style: "Regular".into(), installed: None }]);
assert_eq!(wanted.provided_by(&file), [0]);
assert!(wanted.provided_by(&dir.join("No Such.ttf")).is_empty());
}
/// A search reads a suitcase font only when its whole resource fork fits in the 8 MB a search reads
/// of one file.
#[cfg(target_os = "macos")]
#[test]
fn a_search_reads_a_suitcase_font_only_within_its_share() {
use crate::fontdb::file_face_names_within;
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-big-suitcase", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let suitcase = dir.join("Sysfont Sans3");
std::fs::write(&suitcase, b"").unwrap();
let fork = crate::suitcase::fork_of(&[renamed("SourceSans3-Regular.ttf")]);
let len = fork.len() as u64;
std::fs::write(suitcase.join("..namedfork/rsrc"), &fork).unwrap();
assert_eq!(file_face_names_within(&suitcase, 64, len).len(), 1);
assert!(file_face_names_within(&suitcase, 64, len - 1).is_empty());
let wanted = WantedFonts::new(&[WantedFont { family: FAMILY.into(), style: "Regular".into(), installed: None }]);
assert_eq!(wanted.provided_by(&suitcase), [0]);
// Past the 8 MB a search reads of one file.
let mut big = fork;
big.resize((8 << 20) + 1, 0);
std::fs::write(suitcase.join("..namedfork/rsrc"), big).unwrap();
assert!(wanted.provided_by(&suitcase).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn font_files_are_told_by_their_extension() {
for name in ["a/B.TTF", "c.otf", "d.Ttc", "e.otc"] {
assert!(is_font_file(Path::new(name)), "{name}");
}
for name in ["f.ttf.txt", "ttf", ".29457", "g.woff2", "h.fon"] {
assert!(!is_font_file(Path::new(name)), "{name}");
}
}
/// VectorCraft's own Fonts folder joins the scan once set, even before it exists; only the first
/// folder set counts.
#[test]
fn the_app_font_folder_is_read_by_the_scan() {
let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-app-fonts", std::process::id()));
set_app_font_dir(dir.clone());
set_app_font_dir(dir.join("Other"));
assert_eq!(app_font_dir(), Some(dir.as_path()));
let dirs = system_font_dirs();
assert_eq!(dirs.iter().filter(|d| **d == dir).count(), 1, "{dirs:?}");
assert!(!dirs.contains(&dir.join("Other")));
}
+763
View File
@@ -0,0 +1,763 @@
//! The fonts a document opened without (`text.missingFonts`), listed once the missing linked file
//! questions (dialog `missingLinks`) are answered, one document at a time ([`super::settle`]), with
//! Find Fonts (Type › Find Font on the first of them, to replace it) and Close. Neither brings the
//! dialog back for that open. Search Fonts Folder (the `Fonts` folder next to the document, as
//! File › Package writes it) and Find in Folder… look for their files (`text.findFontFiles`, on
//! separate threads), and Add Fonts copies the files the user chooses into VectorCraft's own Fonts
//! folder (`text.addFontFiles`). Type › Find Font's Find in Folder… opens it too
//! (`ui.findFontsInFolder`), and so does `ui.missingFontsDialog`.
//!
//! Fields: `document` (the document's uid), `fonts` (`text.missingFonts`'s rows),
//! `fontsNextToDocument` (or empty), `state` (empty, `searching`, `done`, `stopped` or `failed`),
//! `search` (the search's `id`), `folder`, `found` (`text.findFontFiles`'s `fonts`, with the files
//! found), `searched`, `skipped`, `unreadable`, `stopped`, `error`, `chosen` (the files to add; a
//! font's first file is chosen when it is found), `searchFolder` (set it and confirm to search that
//! folder) and `discard` (set it and confirm for Find Fonts; confirming without either adds the
//! chosen files).
use std::time::Duration;
use serde_json::{Value, json};
use super::DialogSpec;
use crate::picks::PickRequest;
use crate::state::Dialog;
use crate::theme::{self, Tokens};
use crate::{VectorcraftApp, widgets};
/// The dialog kind of the fonts a document opened without.
pub const KIND: &str = "missingFonts";
pub(super) const SPEC: DialogSpec = DialogSpec {
heading: |_| tl!("Missing Fonts").into(),
body,
confirm,
// Close, with Find Fonts beside it; Add Fonts is a button of the body.
ok: None,
discard: Some("Find Fonts"),
min_width: 440.0,
max_width: Some(540.0),
..DialogSpec::FORM
};
/// After a document opened (`document.open`'s result `r`): its Missing Fonts dialog waits for the
/// dialog slot. On the web the status line shows how many fonts are missing instead, unless it
/// shows the open's notes.
pub fn after_open(app: &mut VectorcraftApp, r: &Value) {
after_open_for(app, r, cfg!(target_arch = "wasm32"));
}
fn after_open_for(app: &mut VectorcraftApp, r: &Value, web: bool) {
let Some(st) = app.session.active() else { return };
let uid = st.uid;
if web {
let n = vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).len();
if n > 0 && r["warnings"].as_array().is_none_or(Vec::is_empty) {
app.status(format!("{n} font(s) aren't available here: their text shows in another font"));
}
return;
}
if !app.ui.pending_fonts.contains(&uid) {
app.ui.pending_fonts.push(uid);
}
}
/// The Missing Fonts dialog of the open document `uid`, when fonts it uses aren't available.
fn dialog_for(app: &VectorcraftApp, uid: u64) -> Option<Dialog> {
let st = app.session.documents().iter().find(|d| d.uid == uid)?;
let r = vectorcraft_engine::cmd::fontfiles::missing_fonts_of(st, app.session.search_rules.as_ref());
let fonts = r["fonts"].as_array().filter(|f| !f.is_empty())?;
let next = r["fontsNextToDocument"].as_str().unwrap_or_default();
Some(Dialog::new(KIND, json!({ "document": uid, "fonts": fonts, "fontsNextToDocument": next, "state": "", "chosen": [] })))
}
/// With no dialog open: the dialog of the first queued document that is still open and still
/// misses fonts.
pub(super) fn open_next(app: &mut VectorcraftApp) {
while app.ui.dialog.is_none() && !app.ui.pending_fonts.is_empty() {
let uid = app.ui.pending_fonts.remove(0);
app.ui.dialog = dialog_for(app, uid);
if app.ui.dialog.is_some() {
app.ui.fonts_dialog = Some(uid);
}
}
}
/// Put the document `uid` at the front of the queue.
fn queue_first(app: &mut VectorcraftApp, uid: u64) {
app.ui.pending_fonts.retain(|u| *u != uid);
app.ui.pending_fonts.insert(0, uid);
}
/// Once the Missing Fonts dialog on show is gone: when another dialog took its place (Import PDF
/// for a file opened after the document, for example), its document goes back to the front of the
/// queue, and the dialog opens again once no dialog is open. A dialog closed by Cancel, Add Fonts
/// or Escape stays closed.
pub(super) fn requeue_replaced(app: &mut VectorcraftApp) {
let Some(uid) = app.ui.fonts_dialog else { return };
let Some(d) = &app.ui.dialog else {
app.ui.fonts_dialog = None;
return;
};
if d.kind != KIND || d.fields.get("document").and_then(Value::as_u64) != Some(uid) {
app.ui.fonts_dialog = None;
queue_first(app, uid);
}
}
/// Stop the search the dialog started once the dialog is gone (closed, or another in its place).
pub(super) fn stop_when_closed(app: &mut VectorcraftApp) {
let Some(id) = app.ui.dialog_search else { return };
let open = app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND && d.fields.get("search").and_then(Value::as_u64) == Some(id));
if !open {
app.ui.dialog_search = None;
vectorcraft_engine::cmd::fontfiles::stop(&mut app.session, id);
}
}
/// `ui.missingFontsDialog`: the dialog for the active document; with `folder`, searching it.
pub(crate) fn open_command(app: &mut VectorcraftApp, folder: Option<String>) -> Result<Value, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
let mut d = dialog_for(app, uid).ok_or("No fonts are missing in this document")?;
if let Some(folder) = folder {
start_search(app, &mut d, &folder)?;
}
show_for(app, uid, d);
Ok(Value::Null)
}
/// Show `d`, the dialog of the document `uid`, in place of the open dialog (another document's
/// Missing Fonts dialog asks again later).
fn show_for(app: &mut VectorcraftApp, uid: u64, d: Dialog) {
requeue_replaced(app);
if let Some(shown) = app.ui.fonts_dialog.filter(|shown| *shown != uid) {
queue_first(app, shown);
}
app.ui.pending_fonts.retain(|u| *u != uid);
app.ui.fonts_dialog = Some(uid);
app.ui.dialog = Some(d);
}
/// `ui.findFontsInFolder` (Type › Find Font's Find in Folder…): ask for a folder (or take
/// `folder`), then open the dialog for the active document, searching it.
pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option<String>) -> Result<Value, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
// Nothing to look for: no folder is asked for.
let mut d = dialog_for(app, uid).ok_or("No fonts are missing in this document")?;
let folder = match folder {
Some(f) => f,
None => crate::picks::folder(app).ok_or("cancelled")?,
};
start_search(app, &mut d, &folder)?;
show_for(app, uid, d);
Ok(Value::Null)
}
/// Start looking in `folder` for the files of the dialog's fonts; what an earlier search found is
/// dropped.
fn start_search(app: &mut VectorcraftApp, d: &mut Dialog, folder: &str) -> Result<(), String> {
let fonts: Vec<Value> = d
.fields
.get("fonts")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|f| json!({ "family": f["family"], "style": f["style"] }))
.collect();
let r = app.run("text.findFontFiles", json!({ "folder": folder, "fonts": fonts }))?;
for k in ["found", "searched", "skipped", "unreadable", "stopped", "error"] {
d.fields.remove(k);
}
d.fields.insert("chosen".into(), json!([]));
d.fields.insert("search".into(), r["id"].clone());
d.fields.insert("folder".into(), json!(folder));
update(d, &r);
app.ui.dialog_search = r["id"].as_u64();
Ok(())
}
/// The files a search found for the font `f` (`{family, style}`): the answer's `fonts` row with
/// the same family and style.
fn files_for<'a>(found: &'a [Value], f: &Value) -> &'a [Value] {
found.iter().find(|r| r["family"] == f["family"] && r["style"] == f["style"]).and_then(|r| r["files"].as_array()).map_or(&[], Vec::as_slice)
}
/// A search's answer `r` into the dialog. A font that gets its first file has that file chosen; a
/// file the user unchecked stays unchecked.
fn update(d: &mut Dialog, r: &Value) {
let before = d.fields.get("found").and_then(Value::as_array).cloned().unwrap_or_default();
let mut chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
for font in r["fonts"].as_array().into_iter().flatten() {
let had = !files_for(&before, font).is_empty();
if let Some(first) = font["files"].as_array().and_then(|f| f.first()).filter(|f| !had && !chosen.contains(f)) {
chosen.push(first.clone());
}
}
d.fields.insert("chosen".into(), json!(chosen));
d.fields.insert("found".into(), r["fonts"].clone());
for k in ["state", "searched", "skipped", "unreadable", "stopped", "error"] {
match r.get(k) {
Some(v) => d.fields.insert(k.into(), v.clone()),
None => d.fields.remove(k),
};
}
}
/// While searching: the search's progress into the dialog. A search started elsewhere since
/// stopped this one.
fn follow(app: &mut VectorcraftApp, d: &mut Dialog) {
// Polled through `session.execute`.
let Ok(r) = app.session.execute("text.findFontFiles", &json!({})) else { return };
if d.fields.get("search") != Some(&r["id"]) {
d.fields.insert("state".into(), json!("stopped"));
return;
}
update(d, &r);
if let Some(e) = r["error"].as_str() {
app.status(e);
}
}
/// A button of the dialog's.
enum Act {
Search(String),
Pick,
Stop,
Add,
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let t = Tokens::get(ui.ctx());
if d.str("state") == "searching" {
follow(app, d);
ui.ctx().request_repaint_after(Duration::from_millis(100));
}
let state = d.str("state");
let searching = state == "searching";
widgets::dim_label(ui, tl!("These fonts aren't available. Their text shows in another font."));
ui.add_space(8.0);
let fonts = d.fields.get("fonts").and_then(Value::as_array).cloned().unwrap_or_default();
let found = d.fields.get("found").and_then(Value::as_array).cloned().unwrap_or_default();
let mut chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
widgets::list_box(ui, |ui| {
egui::ScrollArea::vertical().max_height(220.0).show(ui, |ui| {
ui.set_width(ui.available_width());
for f in &fonts {
ui.horizontal(|ui| {
ui.add_space(6.0);
ui.vertical(|ui| {
ui.add_space(3.0);
let (note, color) = crate::find_font::font_note(f);
let name = format!("{} {}{note}", f["family"].as_str().unwrap_or_default(), f["style"].as_str().unwrap_or_default());
ui.label(egui::RichText::new(name).font(theme::semibold(12.0)).color(color.unwrap_or(t.text_strong)));
let files = files_for(&found, f);
for file in files {
let path = file.as_str().unwrap_or_default();
let name = std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().into_owned());
let on = chosen.contains(file);
if widgets::check(ui, &name, on, true) {
if on {
chosen.retain(|c| c != file);
} else {
chosen.push(file.clone());
}
}
ui.add(egui::Label::new(egui::RichText::new(path).size(11.0).color(t.text_dim)).truncate()).on_hover_text(path);
}
if files.is_empty() && !state.is_empty() {
widgets::dim_label(ui, if searching { tl!("Searching…") } else { tl!("Not found") });
}
ui.add_space(3.0);
});
});
}
});
});
d.fields.insert("chosen".into(), json!(chosen));
ui.add_space(10.0);
let mut act = None;
let can_pick = crate::picks::can(app, &PickRequest::Folder);
ui.horizontal(|ui| {
let next = d.str("fontsNextToDocument");
if !next.is_empty() && ui.add_enabled(!searching, egui::Button::new(tl!("Search Fonts Folder"))).on_hover_text(&next).clicked() {
act = Some(Act::Search(next));
}
if can_pick && ui.add_enabled(!searching, egui::Button::new(tl!("Find in Folder…"))).clicked() {
act = Some(Act::Pick);
}
if searching {
if ui.button(tl!("Stop")).clicked() {
act = Some(Act::Stop);
}
ui.add(egui::Spinner::new().size(12.0).color(t.accent));
}
});
if searching {
widgets::dim_name(ui, &d.str("folder"));
}
if let Some(s) = d.fields.get("searched") {
let (folders, files) = (s["folders"].to_string(), s["files"].to_string());
widgets::dim_name(
ui,
&crate::i18n::fmt(tl!("{folders} folder(s) and {files} file(s) searched"), &[("folders", &folders), ("files", &files)]),
);
}
let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).filter(|n| *n > 0).map(|n| n.to_string());
if let Some(n) = count("skipped") {
let text = tl!("{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones");
widgets::dim_name(ui, &crate::i18n::fmt(text, &[("count", &n)]));
}
if let Some(n) = count("unreadable") {
widgets::dim_name(ui, &crate::i18n::fmt(tl!("{count} folder(s) or file(s) couldn't be read"), &[("count", &n)]));
}
if matches!(d.fields.get("stopped").and_then(Value::as_str), Some("time" | "limit")) {
widgets::dim_label(ui, tl!("The search stopped at its limit: search a smaller folder."));
}
// Once files are found: what copying them means, and Add Fonts.
if found.iter().any(|f| f["files"].as_array().is_some_and(|files| !files.is_empty())) {
ui.add_space(8.0);
widgets::dim_label(ui, tl!("Copy only fonts you own or are licensed to install."));
if let Some(dir) = vectorcraft_text::app_font_dir() {
widgets::dim_name(ui, &crate::i18n::fmt(tl!("VectorCraft copies the fonts to {folder}."), &[("folder", &dir.to_string_lossy())]));
}
ui.add_space(6.0);
if ui.add_enabled(!searching && !chosen.is_empty(), egui::Button::new(tl!("Add Fonts"))).clicked() {
act = Some(Act::Add);
}
}
let r = match act {
Some(Act::Search(folder)) => start_search(app, d, &folder),
Some(Act::Pick) => crate::picks::in_dialog(app, d, |app, d| match crate::picks::folder(app) {
Some(folder) => start_search(app, d, &folder),
None => Ok(()),
}),
Some(Act::Stop) => app.run("text.findFontFiles", json!({ "stop": true })).map(|_| follow(app, d)),
// Added: the dialog closes.
Some(Act::Add) => match add_fonts(app, d) {
Ok(_) => return true,
Err(e) => Err(e),
},
None => Ok(()),
};
if let Err(e) = r {
app.status(e);
}
false
}
/// Find Fonts (`discard`): Type › Find Font on the first font the document misses, to replace it;
/// this Missing Fonts dialog doesn't come back. Otherwise (agents), with `searchFolder`: search that
/// folder, and stay open; else Add Fonts.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
if d.bool("discard") {
app.ui.fonts_dialog = None;
// Find Font works on the active document; the dialog's may be another tab.
let uid = d.fields.get("document").and_then(Value::as_u64);
let index = app.session.documents().iter().position(|doc| Some(doc.uid) == uid).ok_or("that document is no longer open")?;
app.run("document.activate", json!({ "index": index }))?;
crate::find_font::open_on_missing(app);
return Ok(Value::Null);
}
let folder = d.str("searchFolder");
if !folder.is_empty() {
let mut d = d.clone();
d.fields.remove("searchFolder");
// The folder is searched once: a search that doesn't start leaves the dialog without it.
if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) {
open.fields.remove("searchFolder");
}
start_search(app, &mut d, &folder)?;
let state = d.fields.get("state").cloned().unwrap_or(Value::Null);
app.ui.dialog = Some(d);
return Ok(json!({ "state": state }));
}
add_fonts(app, d)
}
/// Add Fonts: copy the chosen files into VectorCraft's Fonts folder and close.
fn add_fonts(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let chosen = d.fields.get("chosen").and_then(Value::as_array).cloned().unwrap_or_default();
if chosen.is_empty() {
return Err("choose the font files to add".into());
}
let r = app.run("text.addFontFiles", json!({ "files": chosen }))?;
app.ui.dialog = None;
let len = |k: &str| r[k].as_array().map_or(0, Vec::len);
let n = len("copied") + len("kept");
let folder = r["folder"].as_str().unwrap_or_default();
match r["skipped"].as_array().and_then(|s| s.first()) {
None => app.status(format!("{n} font file(s) are now in {folder}")),
Some(first) => {
let failed = len("skipped");
let file =
first["file"].as_str().map(std::path::Path::new).and_then(std::path::Path::file_name).map(|f| f.to_string_lossy().into_owned());
let reason = format!("{}: {}", file.unwrap_or_default(), first["reason"].as_str().unwrap_or_default());
app.status(format!("{n} font file(s) are now in {folder}; {failed} couldn't be added: {reason}"));
}
}
Ok(r)
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::time::Instant;
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::findfiles::Rules;
use super::*;
fn frame(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
/// A fresh temporary folder (canonical, as a search reports it).
fn folder(tag: &str) -> PathBuf {
let dir = vectorcraft_testkit::temp_dir(&format!("missing-fonts-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
vectorcraft_engine::cmd::findfiles::plain(std::fs::canonicalize(&dir).unwrap())
}
/// An app that reads files and whose searches may go anywhere in `root`, on two threads.
fn app_for(root: &Path) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.session.search_rules = Some(Rules { user_content: vec![root.to_path_buf()], ..Rules::default() });
app.session.search_threads = Some(2);
app
}
fn png() -> Vec<u8> {
let mut out = vec![];
image::RgbaImage::from_pixel(40, 30, image::Rgba([200, 0, 0, 255]))
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
.unwrap();
out
}
/// Save a new document with type in `font` at `path`, with a linked image that is then deleted
/// when `link`.
fn save_doc(app: &mut VectorcraftApp, path: &Path, font: &str, link: bool) {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let pic = path.with_extension("png");
if link {
std::fs::write(&pic, png()).unwrap();
app.run("file.place", json!({"path": pic.to_string_lossy()})).unwrap();
}
app.run("text.create", json!({"x": 10, "y": 40, "text": "Type", "font": font})).unwrap();
app.run("document.save", json!({"path": path.to_string_lossy()})).unwrap();
if link {
std::fs::remove_file(&pic).unwrap();
}
}
fn open(app: &mut VectorcraftApp, path: &Path) {
crate::io::open_path(app, &path.to_string_lossy()).unwrap();
}
fn kind(app: &VectorcraftApp) -> Option<&str> {
app.ui.dialog.as_ref().map(|d| d.kind.as_str())
}
#[test]
fn missing_fonts_are_asked_about_after_the_missing_links() {
let root = folder("after-links");
let mut app = app_for(&root);
let doc = root.join("doc.vectorcraft");
save_doc(&mut app, &doc, "No Such Font Family", true);
open(&mut app, &doc);
assert_eq!(kind(&app), Some(super::super::missing_links::KIND));
super::super::cancel(&mut app);
let d = app.ui.dialog.as_ref().expect("Missing Fonts after the linked files");
assert_eq!((d.kind.as_str(), d.fields["fonts"][0]["family"].as_str()), (KIND, Some("No Such Font Family")));
let text = frame(&mut app);
for label in
["Missing Fonts", "No Such Font Family Regular", "These fonts aren't available. Their text shows in another font.", "Find Fonts", "Close"]
{
assert!(text.contains(label), "{label} in {text}");
}
assert!(!text.contains("Search Fonts Folder"), "no Fonts folder next to the document");
assert!(!text.contains("Add Fonts") && !text.contains("Copy only fonts"), "no file found yet: {text}");
assert_eq!(super::super::confirm(&mut app).err().as_deref(), Some("choose the font files to add"));
assert_eq!(kind(&app), Some(KIND), "nothing to add: the dialog stays open");
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none());
}
#[test]
fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() {
let root = folder("package");
let font = root.join("pkg").join("Fonts").join("sub").join("Findme.otf");
std::fs::create_dir_all(font.parent().unwrap()).unwrap();
std::fs::write(&font, vectorcraft_testkit::fonts::renamed("Findme Sans 3")).unwrap();
let mut app = app_for(&root);
let doc = root.join("pkg/doc.vectorcraft");
save_doc(&mut app, &doc, "Findme Sans 3", false);
open(&mut app, &doc);
let next = app.ui.dialog.as_ref().filter(|d| d.kind == KIND).expect("Missing Fonts at once: no links missing").str("fontsNextToDocument");
assert_eq!(next, root.join("pkg").join("Fonts").to_string_lossy());
assert!(frame(&mut app).contains("Search Fonts Folder"));
app.ui.dialog.as_mut().unwrap().fields.insert("searchFolder".into(), json!(next));
let r = super::super::confirm(&mut app).unwrap();
assert!(matches!(r["state"].as_str(), Some("searching" | "done")), "{r}");
assert_eq!(kind(&app), Some(KIND), "the dialog stays open while it searches");
let until = Instant::now() + Duration::from_secs(10);
while app.ui.dialog.as_ref().is_some_and(|d| d.str("state") == "searching") && Instant::now() < until {
frame(&mut app);
std::thread::sleep(Duration::from_millis(5));
}
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.str("state"), &d.fields["found"][0]["files"]), ("done".to_string(), &json!([font])));
assert_eq!(d.fields["chosen"], json!([font]), "the font's file is chosen");
let text = frame(&mut app);
for label in ["Findme.otf", "Copy only fonts you own or are licensed to install.", "Add Fonts"] {
assert!(text.contains(label), "{label} in {text}");
}
// Adding needs VectorCraft's Fonts folder, which only the apps set.
let e = super::super::confirm(&mut app).unwrap_err();
assert!(e.contains("isn't set here"), "{e}");
assert_eq!(kind(&app), Some(KIND));
}
/// Find Fonts opens Type › Find Font on the first missing font, to replace it, and the Missing
/// Fonts dialog doesn't come back for that open.
#[test]
fn find_fonts_opens_find_font_on_the_missing_font() {
let root = folder("find-fonts");
let mut app = app_for(&root);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Here", "font": "Source Sans 3"})).unwrap();
app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "Zz Missing Family"})).unwrap();
let doc = root.join("doc.vectorcraft");
app.run("document.save", json!({"path": doc.to_string_lossy()})).unwrap();
open(&mut app, &doc);
assert_eq!(kind(&app), Some(KIND));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
super::super::confirm(&mut app).unwrap();
let d = app.ui.dialog.as_ref().expect("Find Font");
assert_eq!(d.kind, "findFont");
let fonts = app.session.execute("text.fonts", &json!({})).unwrap();
let selected = d.fields["selected"].as_u64().unwrap() as usize;
assert!(selected > 0 && fonts[selected]["family"] == "Zz Missing Family", "{selected} in {fonts}");
// Find Font closed: no Missing Fonts dialog follows.
app.ui.dialog = None;
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// The dialog of a document in another tab: Find Fonts makes that document the active one, so
/// Find Font lists and replaces its fonts.
#[test]
fn find_fonts_works_on_the_dialog_s_own_document() {
let root = folder("find-fonts-tab");
let mut app = app_for(&root);
let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft"));
save_doc(&mut app, &a, "Alpha Missing Family", false);
save_doc(&mut app, &b, "Beta Missing Family", true);
open(&mut app, &a);
open(&mut app, &b);
// B's linked files are asked about first; then A's fonts, with B the active tab.
super::super::cancel(&mut app);
let d = app.ui.dialog.as_mut().unwrap();
assert_eq!(d.fields["fonts"][0]["family"], "Alpha Missing Family");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*b.to_string_lossy()));
app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));
super::super::confirm(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().path.as_deref(), Some(&*a.to_string_lossy()));
let fonts = app.session.execute("text.fonts", &json!({})).unwrap();
let selected = app.ui.dialog.as_ref().unwrap().fields["selected"].as_u64().unwrap() as usize;
assert_eq!(fonts[selected]["family"], "Alpha Missing Family", "{fonts}");
}
#[test]
fn closing_the_dialog_stops_its_search() {
let root = folder("stop");
// Enough folders that the search usually still runs when the dialog closes.
for a in 0..40 {
for b in 0..40 {
std::fs::create_dir_all(root.join(format!("f{a}/g{b}"))).unwrap();
}
}
let mut app = app_for(&root);
app.session.search_threads = Some(1);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
app.run("ui.missingFontsDialog", json!({"folder": root})).unwrap();
let id = app.ui.dialog_search.expect("the dialog's search");
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.dialog_search.is_none());
// Stopped by the close, unless the walker finished the folders first.
let r = app.session.execute("text.findFontFiles", &json!({})).unwrap();
assert_eq!(r["id"].as_u64(), Some(id), "{r}");
match r["state"].as_str() {
Some("stopped") => assert_eq!(r["stopped"], "stop", "{r}"),
state => assert_eq!(state, Some("done"), "{r}"),
}
// Without missing fonts there is nothing to open.
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
assert_eq!(app.run("ui.missingFontsDialog", json!({})).err().as_deref(), Some("No fonts are missing in this document"));
}
#[test]
fn one_dialog_at_a_time_document_by_document() {
let root = folder("queue");
let mut app = app_for(&root);
let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft"));
save_doc(&mut app, &a, "Alpha Missing Family", false);
save_doc(&mut app, &b, "Beta Missing Family", true);
open(&mut app, &a);
let family = |app: &VectorcraftApp| app.ui.dialog.as_ref().and_then(|d| d.fields["fonts"][0]["family"].as_str().map(str::to_string));
assert_eq!(family(&app).as_deref(), Some("Alpha Missing Family"));
// The second document's linked files are asked about first; then each document's fonts.
open(&mut app, &b);
assert_eq!(kind(&app), Some(super::super::missing_links::KIND));
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Alpha Missing Family"));
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Beta Missing Family"));
super::super::cancel(&mut app);
assert!(app.ui.dialog.is_none());
// A document closed before its turn is passed over.
open(&mut app, &a);
open(&mut app, &b);
let index = app.session.documents().iter().rposition(|d| d.path.as_deref() == Some(&*a.to_string_lossy())).unwrap();
app.session.execute("file.close", &json!({"index": index})).unwrap();
super::super::cancel(&mut app);
assert_eq!(family(&app).as_deref(), Some("Beta Missing Family"));
}
/// Another dialog that takes the Missing Fonts dialog's place (Import PDF for a PDF dropped
/// with the document) hands the question back once it closes.
#[test]
fn the_question_comes_back_after_a_dialog_that_took_its_place() {
let root = folder("replaced");
let mut app = app_for(&root);
let doc = root.join("a.vectorcraft");
save_doc(&mut app, &doc, "Alpha Missing Family", false);
let pdf = || {
let page = || vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "0 g 0 0 10 10 re f");
vectorcraft_testkit::pdf::pdf(&[page(), page()], None)
};
let opened = |name: &str, path: Option<String>, bytes: Vec<u8>| (crate::place::DropTarget::Open, (name.to_string(), path, bytes));
let files =
vec![opened("a.vectorcraft", Some(doc.to_string_lossy().into_owned()), std::fs::read(&doc).unwrap()), opened("b.pdf", None, pdf())];
crate::place::drop_files(&mut app, files);
assert_eq!(kind(&app), Some(super::super::import_pdf::KIND));
super::super::cancel(&mut app);
let family = |app: &VectorcraftApp| app.ui.dialog.as_ref().filter(|d| d.kind == KIND).map(|d| d.fields["fonts"][0]["family"].clone());
assert_eq!(family(&app), Some(json!("Alpha Missing Family")));
// The same when a frame drew the other dialog before it closed.
crate::io::open_bytes(&mut app, "c.pdf", &pdf(), None).unwrap();
assert_eq!(kind(&app), Some(super::super::import_pdf::KIND));
frame(&mut app);
super::super::cancel(&mut app);
assert_eq!(family(&app), Some(json!("Alpha Missing Family")));
// Closed by Cancel, or by Escape (which empties the dialog slot), it stays closed.
super::super::cancel(&mut app);
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
app.run("ui.missingFontsDialog", json!({})).unwrap();
app.ui.dialog = None;
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// Type in a CSS generic family (`sans-serif`, the default font of SVG files from some editors)
/// opens without the question.
#[test]
fn generic_families_are_not_asked_about() {
let mut app = app_for(&folder("generic"));
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="10" y="40" font-family="sans-serif">A</text></svg>"#;
crate::io::open_bytes(&mut app, "generic.svg", svg.as_bytes(), None).unwrap();
let listed = app.session.execute("text.fonts", &json!({})).unwrap();
assert!(listed.as_array().unwrap().iter().any(|f| f["family"] == "sans-serif"), "{listed}");
frame(&mut app);
assert!(app.ui.dialog.is_none() && app.ui.pending_fonts.is_empty());
}
/// A `searchFolder` whose search doesn't start is dropped from the dialog: OK doesn't try it
/// again.
#[test]
fn a_search_folder_that_fails_is_not_tried_again() {
let root = folder("retry");
let mut app = app_for(&root);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
app.run("ui.missingFontsDialog", json!({})).unwrap();
app.ui.dialog.as_mut().unwrap().fields.insert("searchFolder".into(), json!("relative/folder"));
let e = super::super::confirm(&mut app).unwrap_err();
assert!(e.contains("absolute"), "{e}");
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("searchFolder"));
assert_eq!(super::super::confirm(&mut app).err().as_deref(), Some("choose the font files to add"));
}
/// A placed document that Links › Edit Original opens asks about its fonts, as File › Open does.
#[test]
fn edit_original_asks_about_the_placed_documents_fonts() {
let root = folder("edit-original");
let mut app = app_for(&root);
let badge = root.join("badge.vectorcraft");
save_doc(&mut app, &badge, "Badge Missing Family", false);
app.session.execute("file.close", &json!({})).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": badge.to_string_lossy(), "link": true})).unwrap();
let tabs = app.session.documents().len();
app.run("links.editOriginal", json!({})).unwrap();
assert_eq!(app.session.documents().len(), tabs + 1);
let d = app.ui.dialog.as_ref().expect("Missing Fonts for the document opened");
assert_eq!((d.kind.as_str(), d.fields["fonts"][0]["family"].as_str()), (KIND, Some("Badge Missing Family")));
}
/// A search leaves out the fonts that became available: the files it found go with their fonts
/// by name, and a file the user unchecked stays unchecked as the search goes on.
#[test]
fn files_go_with_their_fonts_by_name() {
let (a, b) = (json!({"family": "A Sans", "style": "Regular"}), json!({"family": "B Sans", "style": "Bold"}));
let mut d = Dialog::new(KIND, json!({"fonts": [a, b], "chosen": []}));
update(&mut d, &json!({"state": "searching", "fonts": [{"family": "B Sans", "style": "Bold", "files": ["/f/b.otf"]}]}));
let found = d.fields["found"].as_array().unwrap().clone();
assert!(files_for(&found, &a).is_empty());
assert_eq!(files_for(&found, &b), [json!("/f/b.otf")]);
assert_eq!(d.fields["chosen"], json!(["/f/b.otf"]));
d.fields.insert("chosen".into(), json!([]));
update(&mut d, &json!({"state": "done", "fonts": [{"family": "B Sans", "style": "Bold", "files": ["/f/b.otf", "/g/b.otf"]}]}));
assert_eq!((d.str("state"), &d.fields["chosen"]), ("done".to_string(), &json!([])));
}
/// The status lines are translated with the reasons in them, and so are the reasons a search
/// failed and a file wasn't copied, which the code holds as constants.
#[test]
fn the_status_lines_read_in_the_interface_language() {
let fr = crate::i18n::Lang::from_code("fr").unwrap();
let shown = crate::i18n::message(fr, "2 font file(s) are now in /Fonts; 1 couldn't be added: a.otf: larger than 256 MB");
assert!(shown.contains("se trouvent maintenant dans /Fonts") && shown.contains("a.otf") && shown.contains("plus de 256 Mo"), "{shown}");
for code in ["es", "fr", "it", "ru"] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for s in [
"every search thread stopped on an internal error (please report this bug)",
"not a file",
"not a font file",
"the files come to more than 1 GB: add fewer at a time",
"every numbered name for it is taken in the Fonts folder",
] {
assert_ne!(crate::i18n::message(lang, s), s, "{code}");
}
}
}
#[test]
fn the_web_says_how_many_fonts_are_missing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("text.create", json!({"x": 10, "y": 40, "text": "Gone", "font": "No Such Font Family"})).unwrap();
after_open_for(&mut app, &json!({}), true);
assert_eq!(app.ui.status, "1 font(s) aren't available here: their text shows in another font");
assert!(app.ui.pending_fonts.is_empty());
// The open's notes stay on show.
app.ui.status = "Opened with 1 note(s): fonts".into();
after_open_for(&mut app, &json!({"warnings": ["fonts"]}), true);
assert_eq!(app.ui.status, "Opened with 1 note(s): fonts");
}
}
+8 -3
View File
@@ -35,18 +35,23 @@ fn ids(rows: &[Value]) -> Vec<Value> {
}
/// After a document opened (`document.open`'s result `r`): ask about its missing linked files,
/// then about its modified ones. The web reads no linked files, so missing ones just show their
/// then about its modified ones, then about the fonts it opened without
/// ([`super::missing_fonts`]). The web reads no linked files, so missing ones just show their
/// previews there.
pub fn after_open(app: &mut VectorcraftApp, r: &Value) {
// The fonts' dialog waits for these questions (one dialog at a time).
super::missing_fonts::after_open(app, r);
let rows = |k: &str| r[k].as_array().cloned().unwrap_or_default();
let (missing, modified) = (rows("missingLinks"), ids(&rows("modifiedLinks")));
if missing.is_empty() || cfg!(target_arch = "wasm32") {
if !missing.is_empty() {
app.status(format!("{} linked file(s) can't be read here: their previews show", missing.len()));
}
return ask_update(app, modified);
ask_update(app, modified);
} else {
open(app, missing, modified);
}
open(app, missing, modified);
super::settle(app);
}
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>) {
+18 -1
View File
@@ -39,6 +39,7 @@ pub mod import_pdf;
pub mod layer_options;
pub mod layers_panel_options;
pub mod liquify;
pub mod missing_fonts;
pub mod missing_links;
pub(crate) mod modal;
pub mod new_color_group;
@@ -246,6 +247,7 @@ registry! {
FileInfo: [file_info::KIND] => file_info::SPEC,
RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC,
MissingLinks: [missing_links::KIND] => missing_links::SPEC,
MissingFonts: [missing_fonts::KIND] => missing_fonts::SPEC,
TextImport: [text_import::KIND] => text_import::SPEC,
PdfPresets: [pdf_presets::KIND] => pdf_presets::SPEC,
PdfPreset: [save_pdf::PRESET_KIND] => save_pdf::PRESET_SPEC,
@@ -310,20 +312,35 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes
/// Close the open dialog as Cancel does, rolling back a live preview (`ui.dialog.cancel`).
pub fn cancel(app: &mut VectorcraftApp) {
missing_fonts::requeue_replaced(app);
if app.ui.dialog.take().is_some_and(|d| spec(&d.kind).preview) {
let _ = app.session.cancel_interaction();
}
settle(app);
}
/// Apply the open dialog (OK).
pub fn confirm(app: &mut VectorcraftApp) -> DialogResult {
missing_fonts::requeue_replaced(app);
let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) };
// A file dialog it shows off the UI thread confirms the dialog as it is again.
crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d))
let r = crate::picks::as_entry(app, || crate::picks::Entry::Confirm(Box::new(d.clone())), |app| (spec(&d.kind).confirm)(app, &d));
settle(app);
r
}
/// After a dialog closes, and each frame: a Missing Fonts dialog that another dialog replaced waits
/// for its turn again, the search a Missing Fonts dialog started stops once that dialog is gone,
/// and with no dialog open the next document's Missing Fonts dialog opens (one dialog at a time).
pub(crate) fn settle(app: &mut VectorcraftApp) {
missing_fonts::requeue_replaced(app);
missing_fonts::stop_when_closed(app);
missing_fonts::open_next(app);
}
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
about::show(app, ctx);
settle(app);
// The kind of dialog shown last frame: a different one (or none) means this one just opened, and
// its first field is to take the keyboard focus (`focus_id`, until a field takes it).
let (shown_id, focus_id) = (egui::Id::new("dialog-shown"), egui::Id::new("dialog-focus-pending"));
+56 -3
View File
@@ -1,5 +1,6 @@
//! Type → Find Font…: the fonts the document uses (missing ones marked), Find (select the text
//! using a font), and Change / Change All to another installed font.
//! using a font), Change / Change All to another installed font, and Find in Folder… (the missing
//! fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`).
use egui::Ui;
use serde_json::{Value, json};
@@ -11,7 +12,19 @@ use crate::{VectorcraftApp, font_menu};
/// Open the dialog.
pub fn open(app: &mut VectorcraftApp) {
app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": 0, "family": "Source Sans 3", "style": "", "selectionOnly": false })));
open_at(app, 0);
}
/// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find
/// Fonts).
pub fn open_on_missing(app: &mut VectorcraftApp) {
let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute")));
open_at(app, first.unwrap_or(0));
}
/// Open the dialog with the document's font `selected` (an index into `text.fonts`) chosen.
fn open_at(app: &mut VectorcraftApp, selected: usize) {
app.ui.dialog = Some(Dialog::new("findFont", json!({ "selected": selected, "family": "Source Sans 3", "style": "", "selectionOnly": false })));
}
fn fonts(app: &mut VectorcraftApp) -> Vec<Value> {
@@ -35,7 +48,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
let t = Tokens::get(ctx);
let list = fonts(app);
let sample = font_menu::sample_text(app);
// Find in Folder… shows when the document misses fonts, fonts used only in its symbols included.
let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder)
&& app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty());
let mut close = false;
let mut find_in_folder = false;
let mut act: Option<&str> = None;
crate::dialogs::modal::show(ctx, tl!("Find Font"), egui::Id::new("dialog-find-font"), -40.0, 22, |ui: &mut Ui| {
ui.set_width(380.0);
@@ -57,6 +74,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
});
});
// The missing fonts' files, looked for in a folder (the Missing Fonts dialog).
if offer_folder {
ui.add_space(6.0);
find_in_folder = ui.button(tl!("Find in Folder…")).clicked();
}
ui.add_space(10.0);
widgets::subheader(ui, tl!("Replace With Font"));
let fam = d.str("family");
@@ -113,11 +135,15 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
} else if app.ui.dialog.is_some() {
app.ui.dialog = Some(d);
}
// Missing Fonts takes the dialog's place, searching the folder picked.
if find_in_folder && let Err(e) = app.run("ui.findFontsInFolder", json!({})) {
app.ui.status = e;
}
}
/// What a Find Font row says after the font's name (`text.fonts` row): a missing family, a style
/// standing in for another, characters the font lacks; and the colour to flag it with.
fn font_note(f: &Value) -> (String, Option<egui::Color32>) {
pub(crate) fn font_note(f: &Value) -> (String, Option<egui::Color32>) {
let lacking = f["missingGlyphs"].as_u64().unwrap_or(0);
let glyphs =
if lacking > 0 { crate::i18n::fmt(tl!(" — {n} characters from another font"), &[("n", &lacking.to_string())]) } else { String::new() };
@@ -156,6 +182,33 @@ mod tests {
assert_eq!(fonts(&mut app)[0]["family"], "Source Sans 3");
}
#[test]
fn find_in_folder_puts_the_missing_fonts_dialog_in_find_fonts_place() {
let dir = std::fs::canonicalize(vectorcraft_testkit::temp_dir("find-font-folder")).unwrap();
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.search_rules = Some(vectorcraft_engine::cmd::findfiles::Rules { user_content: vec![dir.clone()], ..Default::default() });
app.session.search_threads = Some(1);
app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
assert!(!crate::menus::enabled(&app, "ui.findFontsInFolder"), "no folder picker (the web)");
let picked = dir.to_string_lossy().into_owned();
app.services.pick_folder = Some(Box::new(move || Some(picked.clone())));
assert!(crate::menus::enabled(&app, "ui.findFontsInFolder"));
// Nothing missing: no button, and no folder is asked for.
open(&mut app);
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.contains("Fonts in Document") && !text.contains("Find in Folder…"), "{text}");
assert_eq!(app.run("ui.findFontsInFolder", json!({})).err().as_deref(), Some("No fonts are missing in this document"));
app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Missing Family"})).unwrap();
let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx()));
assert!(text.contains("Find in Folder…"), "{text}");
app.run("ui.findFontsInFolder", json!({})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert_eq!((d.kind.as_str(), d.str("folder")), (crate::dialogs::missing_fonts::KIND, dir.to_string_lossy().into_owned()));
assert_eq!(d.fields["fonts"][0]["family"], "Missing Family");
assert!(app.ui.dialog_search.is_some());
crate::dialogs::cancel(&mut app);
}
#[test]
fn rows_flag_missing_fonts_substituted_styles_and_lacking_characters() {
let row = |status: &str, glyphs: u64| json!({"status": status, "resolved": {"style": "W4"}, "missingGlyphs": glyphs});
+37
View File
@@ -2062,6 +2062,25 @@
Reflect… Reflejar…
Refresh Actualizar
Refresh Font List Actualizar lista de fuentes
Missing Fonts Fuentes que faltan
Missing Fonts Dialog Cuadro de diálogo Fuentes que faltan
These fonts aren't available. Their text shows in another font. Estas fuentes no están disponibles. Su texto se muestra con otra fuente.
Search Fonts Folder Buscar en la carpeta Fonts
Find in Folder… Buscar en una carpeta…
Find Fonts in Folder… Buscar fuentes en una carpeta…
Find Font Files Buscar archivos de fuentes
Add Font Files Agregar archivos de fuentes
Add Fonts Agregar fuentes
Find Fonts Buscar fuentes
Stop Detener
Searching… Buscando…
Not found No se encontró
{folders} folder(s) and {files} file(s) searched Se buscó en {folders} carpeta(s) y {files} archivo(s)
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Se omitieron {count} carpeta(s), como las de otras aplicaciones y del sistema y las ocultas
{count} folder(s) or file(s) couldn't be read No se pudieron leer {count} carpeta(s) o archivo(s)
The search stopped at its limit: search a smaller folder. La búsqueda se detuvo en su límite: busca en una carpeta más pequeña.
Copy only fonts you own or are licensed to install. Copia solo fuentes que te pertenezcan o cuya licencia te permita instalarlas.
VectorCraft copies the fonts to {folder}. VectorCraft copia las fuentes en {folder}.
Registered Trademark Symbol Símbolo de marca registrada
Registration marks Marcas de registro
Registry name: Nombre del registro:
@@ -3714,6 +3733,24 @@ axis Both Ambos
@msg an image whose data is cut short was left out se omitió una imagen con datos incompletos
@msg its editing data doesn't say where its art is sus datos de edición no dicen dónde está su ilustración
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) este archivo se guardó sin compatibilidad con PDF y sus datos de edición no se pueden leer ({why})
@msg No fonts are missing in this document No faltan fuentes en este documento
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft no busca en carpetas de otras aplicaciones ni del sistema: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft no busca en las carpetas Shared ni Public de Users: {path}
@msg {path} is not a folder {path} no es una carpeta
@msg the search couldn't start: try again in a moment no se pudo iniciar la búsqueda: inténtalo de nuevo en un momento
@msg searching a folder isn't available on the web en la web no se puede buscar en una carpeta
@msg every search thread stopped on an internal error (please report this bug) todos los hilos de búsqueda se detuvieron por un error interno (informa de este error)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La carpeta Fonts de VectorCraft no está configurada aquí: la configuran la aplicación de escritorio y vectorcraft-cli
@msg choose the font files to add elige los archivos de fuentes que quieres agregar
@msg {n} font file(s) are now in {folder} {n} archivo(s) de fuentes ahora están en {folder}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} archivo(s) de fuentes ahora están en {folder}; no se pudieron agregar {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font aquí no están disponibles {n} fuente(s): su texto se muestra con otra fuente
@msg not a file no es un archivo
@msg not a font file no es un archivo de fuente
@msg that document is no longer open ese documento ya no está abierto
@msg larger than 256 MB mayor de 256 MB
@msg the files come to more than 1 GB: add fewer at a time los archivos suman más de 1 GB: agrega menos a la vez
@msg every numbered name for it is taken in the Fonts folder todos los nombres numerados para él ya existen en la carpeta Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Servicios
Can't render this file because it contains an unexpected character in line 2 and column 73.
+37
View File
@@ -2059,6 +2059,25 @@
Reflect… Miroir…
Refresh Actualiser
Refresh Font List Actualiser la liste des polices
Missing Fonts Polices manquantes
Missing Fonts Dialog Boîte de dialogue Polices manquantes
These fonts aren't available. Their text shows in another font. Ces polices ne sont pas disponibles. Leur texte s’affiche dans une autre police.
Search Fonts Folder Rechercher dans le dossier Fonts
Find in Folder… Rechercher dans un dossier…
Find Fonts in Folder… Rechercher des polices dans un dossier…
Find Font Files Rechercher des fichiers de polices
Add Font Files Ajouter des fichiers de polices
Add Fonts Ajouter les polices
Find Fonts Rechercher les polices
Stop Arrêter
Searching… Recherche…
Not found Introuvable
{folders} folder(s) and {files} file(s) searched {folders} dossier(s) et {files} fichier(s) parcourus
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} dossier(s) ignoré(s), comme ceux d’autres apps et du système et les dossiers masqués
{count} folder(s) or file(s) couldn't be read {count} dossier(s) ou fichier(s) illisible(s)
The search stopped at its limit: search a smaller folder. La recherche s’est arrêtée à sa limite : recherchez dans un dossier plus petit.
Copy only fonts you own or are licensed to install. Ne copiez que des polices qui vous appartiennent ou dont la licence vous autorise l’installation.
VectorCraft copies the fonts to {folder}. VectorCraft copie les polices dans {folder}.
Registered Trademark Symbol Symbole de marque déposée
Registration marks Repères de montage
Registry name: Nom du registre :
@@ -3711,6 +3730,24 @@ axis Both Les deux
@msg an image whose data is cut short was left out une image aux données tronquées a été ignorée
@msg its editing data doesn't say where its art is ses données d’édition ne disent pas où se trouve son illustration
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) ce fichier a été enregistré sans compatibilité PDF et ses données d’édition sont illisibles ({why})
@msg No fonts are missing in this document Aucune police ne manque dans ce document
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft ne recherche pas dans les dossiers d’autres apps ni du système : {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft ne recherche pas dans les dossiers Shared et Public de Users : {path}
@msg {path} is not a folder {path} n’est pas un dossier
@msg the search couldn't start: try again in a moment la recherche n’a pas pu démarrer : réessayez dans un instant
@msg searching a folder isn't available on the web la recherche dans un dossier n’est pas disponible sur le web
@msg every search thread stopped on an internal error (please report this bug) tous les fils de recherche se sont arrêtés sur une erreur interne (veuillez signaler ce bogue)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Le dossier Fonts de VectorCraft n’est pas défini ici : l’application de bureau et vectorcraft-cli le définissent
@msg choose the font files to add choisissez les fichiers de polices à ajouter
@msg {n} font file(s) are now in {folder} {n} fichier(s) de polices se trouvent maintenant dans {folder}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} fichier(s) de polices se trouvent maintenant dans {folder} ; {failed} n’ont pas pu être ajoutés : {reason}
@msg {n} font(s) aren't available here: their text shows in another font {n} police(s) indisponible(s) ici : leur texte s’affiche dans une autre police
@msg not a file n’est pas un fichier
@msg not a font file n’est pas un fichier de police
@msg that document is no longer open ce document n’est plus ouvert
@msg larger than 256 MB plus de 256 Mo
@msg the files come to more than 1 GB: add fewer at a time les fichiers dépassent 1 Go : ajoutez-en moins à la fois
@msg every numbered name for it is taken in the Fonts folder tous les noms numérotés pour ce fichier sont déjà pris dans le dossier Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Services
Can't render this file because it contains an unexpected character in line 2 and column 73.
+37
View File
@@ -2062,6 +2062,25 @@
Reflect… Rifletti…
Refresh Aggiorna
Refresh Font List Aggiorna elenco font
Missing Fonts Font mancanti
Missing Fonts Dialog Finestra di dialogo Font mancanti
These fonts aren't available. Their text shows in another font. Questi font non sono disponibili. Il loro testo viene mostrato con un altro font.
Search Fonts Folder Cerca nella cartella Fonts
Find in Folder… Trova in una cartella…
Find Fonts in Folder… Trova font in una cartella…
Find Font Files Trova file dei font
Add Font Files Aggiungi file dei font
Add Fonts Aggiungi font
Find Fonts Trova font
Stop Interrompi
Searching… Ricerca in corso…
Not found Non trovato
{folders} folder(s) and {files} file(s) searched Cartelle cercate: {folders}, file: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Cartelle saltate: {count}, ad esempio quelle di altre app e di sistema e quelle nascoste
{count} folder(s) or file(s) couldn't be read Cartelle o file non leggibili: {count}
The search stopped at its limit: search a smaller folder. La ricerca si è fermata al suo limite: cerca in una cartella più piccola.
Copy only fonts you own or are licensed to install. Copia solo font di tua proprietà o con una licenza che ti consente di installarli.
VectorCraft copies the fonts to {folder}. VectorCraft copia i font in {folder}.
Registered Trademark Symbol Simbolo di marchio registrato
Registration marks Segni di registro
Registry name: Nome registro:
@@ -3714,6 +3733,24 @@ axis Both Entrambi
@msg an image whose data is cut short was left out un'immagine con dati incompleti è stata omessa
@msg its editing data doesn't say where its art is i suoi dati di modifica non dicono dove si trova la grafica
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) questo file è stato salvato senza compatibilità PDF e i suoi dati di modifica non si possono leggere ({why})
@msg No fonts are missing in this document In questo documento non mancano font
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft non cerca nelle cartelle di altre app né di sistema: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft non cerca nelle cartelle Shared e Public di Users: {path}
@msg {path} is not a folder {path} non è una cartella
@msg the search couldn't start: try again in a moment impossibile avviare la ricerca: riprova tra un momento
@msg searching a folder isn't available on the web la ricerca in una cartella non è disponibile sul web
@msg every search thread stopped on an internal error (please report this bug) tutti i thread di ricerca si sono fermati per un errore interno (segnala questo bug)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it La cartella Fonts di VectorCraft non è impostata qui: la impostano l'app desktop e vectorcraft-cli
@msg choose the font files to add scegli i file dei font da aggiungere
@msg {n} font file(s) are now in {folder} File di font ora in {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} File di font ora in {folder}: {n}; impossibile aggiungerne {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font font non disponibili qui: {n}; il loro testo viene mostrato con un altro font
@msg not a file non è un file
@msg not a font file non è un file di font
@msg that document is no longer open quel documento non è più aperto
@msg larger than 256 MB più grande di 256 MB
@msg the files come to more than 1 GB: add fewer at a time i file superano 1 GB: aggiungine meno alla volta
@msg every numbered name for it is taken in the Fonts folder tutti i nomi numerati per il file sono già usati nella cartella Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Servizi
Can't render this file because it contains an unexpected character in line 2 and column 73.
+37
View File
@@ -2064,6 +2064,25 @@
Reflect Y Y 軸でリフレクト
Refresh 更新
Refresh Font List フォントリストを更新
Missing Fonts 見つからないフォント
Missing Fonts Dialog 見つからないフォントダイアログ
These fonts aren't available. Their text shows in another font. これらのフォントは使用できません。テキストは別のフォントで表示されます。
Search Fonts Folder 「Fonts」フォルダーを検索
Find in Folder… フォルダー内を検索…
Find Fonts in Folder… フォルダー内のフォントを検索…
Find Font Files フォントファイルを検索
Add Font Files フォントファイルを追加
Add Fonts フォントを追加
Find Fonts フォントを検索
Stop 停止
Searching… 検索中…
Not found 見つかりません
{folders} folder(s) and {files} file(s) searched {folders} 個のフォルダーと {files} 個のファイルを検索しました
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} 個のフォルダーをスキップしました(他のアプリやシステムのフォルダー、隠しフォルダーなど)
{count} folder(s) or file(s) couldn't be read {count} 個のフォルダーまたはファイルを読み込めませんでした
The search stopped at its limit: search a smaller folder. 検索は上限で停止しました。より小さなフォルダーを検索してください。
Copy only fonts you own or are licensed to install. 所有しているフォント、またはインストールするライセンスがあるフォントだけをコピーしてください。
VectorCraft copies the fonts to {folder}. VectorCraft はフォントを {folder} にコピーします。
Registry name: レジストリ名:
Release Compound Shape 複合シェイプを解除
Release Opacity Mask 不透明マスクを解除
@@ -3726,3 +3745,21 @@ theme Appearance 外観
@msg no user workspace `{from}` ユーザーワークスペース `{from}` が見つかりません
@msg unknown workspace (one of {_1}) 不明なワークスペースです ({_1} のいずれかを指定してください)
@msg workspace name can't be empty ワークスペース名を入力してください
@msg No fonts are missing in this document このドキュメントには見つからないフォントはありません
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft は他のアプリやシステムのフォルダーを検索しません: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft は Users 内の Shared フォルダーと Public フォルダーを検索しません: {path}
@msg {path} is not a folder {path} はフォルダーではありません
@msg the search couldn't start: try again in a moment 検索を開始できませんでした: しばらくしてからもう一度お試しください
@msg searching a folder isn't available on the web Web 版ではフォルダーを検索できません
@msg every search thread stopped on an internal error (please report this bug) すべての検索スレッドが内部エラーで停止しました (このバグを報告してください)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it この環境では VectorCraft の Fonts フォルダーが設定されていません: デスクトップアプリと vectorcraft-cli が設定します
@msg choose the font files to add 追加するフォントファイルを選択してください
@msg {n} font file(s) are now in {folder} {n} 個のフォントファイルが {folder} に入りました
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} {n} 個のフォントファイルが {folder} に入りましたが、{failed} 個は追加できませんでした: {reason}
@msg {n} font(s) aren't available here: their text shows in another font {n} 個のフォントはこの環境では使用できません: テキストは別のフォントで表示されます
@msg not a file ファイルではありません
@msg not a font file フォントファイルではありません
@msg that document is no longer open そのドキュメントはもう開かれていません
@msg larger than 256 MB 256 MB を超えています
@msg the files come to more than 1 GB: add fewer at a time ファイルの合計が 1 GB を超えています: 一度に追加するファイルを減らしてください
@msg every numbered name for it is taken in the Fonts folder Fonts フォルダーでは、このファイルの番号付きの名前がすべて使われています
Can't render this file because it contains an unexpected character in line 2 and column 73.
+19
View File
@@ -1819,6 +1819,25 @@
Reflect… Espelhar…
Refresh Atualizar
Refresh Font List Atualizar Lista de Fontes
Missing Fonts Fontes Ausentes
Missing Fonts Dialog Diálogo de Fontes Ausentes
These fonts aren't available. Their text shows in another font. Estas fontes não estão disponíveis. O texto delas aparece em outra fonte.
Search Fonts Folder Pesquisar na Pasta Fonts
Find in Folder… Localizar em uma Pasta…
Find Fonts in Folder… Localizar Fontes em uma Pasta…
Find Font Files Localizar Arquivos de Fontes
Add Font Files Adicionar Arquivos de Fontes
Add Fonts Adicionar Fontes
Find Fonts Localizar Fontes
Stop Parar
Searching… Pesquisando…
Not found Não encontrado
{folders} folder(s) and {files} file(s) searched {folders} pasta(s) e {files} arquivo(s) pesquisados
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones {count} pasta(s) ignorada(s), como as de outros aplicativos e do sistema e as ocultas
{count} folder(s) or file(s) couldn't be read {count} pasta(s) ou arquivo(s) não puderam ser lidos
The search stopped at its limit: search a smaller folder. A pesquisa parou no limite: pesquise uma pasta menor.
Copy only fonts you own or are licensed to install. Copie apenas fontes que sejam suas ou que você tenha licença para instalar.
VectorCraft copies the fonts to {folder}. O VectorCraft copia as fontes para {folder}.
Registered Trademark Symbol Símbolo de Marca Registrada
Registry name: Nome do registro:
Release Liberar
Can't render this file because it contains an unexpected character in line 6 and column 47.
+37
View File
@@ -2058,6 +2058,25 @@
Reflect… Отразить…
Refresh Обновить
Refresh Font List Обновить список шрифтов
Missing Fonts Отсутствующие шрифты
Missing Fonts Dialog Диалоговое окно «Отсутствующие шрифты»
These fonts aren't available. Their text shows in another font. Эти шрифты недоступны. Их текст отображается другим шрифтом.
Search Fonts Folder Искать в папке Fonts
Find in Folder… Найти в папке…
Find Fonts in Folder… Найти шрифты в папке…
Find Font Files Найти файлы шрифтов
Add Font Files Добавить файлы шрифтов
Add Fonts Добавить шрифты
Find Fonts Найти шрифты
Stop Остановить
Searching… Поиск…
Not found Не найдено
{folders} folder(s) and {files} file(s) searched Просмотрено папок: {folders}, файлов: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, например папки других приложений и системы и скрытые папки
{count} folder(s) or file(s) couldn't be read Не удалось прочитать папок или файлов: {count}
The search stopped at its limit: search a smaller folder. Поиск остановился на пределе: выберите папку поменьше.
Copy only fonts you own or are licensed to install. Копируйте только шрифты, которые принадлежат вам или которые вы вправе устанавливать по лицензии.
VectorCraft copies the fonts to {folder}. VectorCraft копирует шрифты в {folder}.
Registered Trademark Symbol Символ зарегистрированного товарного знака
Registration marks Метки совмещения
Registry name: Имя в реестре:
@@ -3710,6 +3729,24 @@ axis Both Оба
@msg an image whose data is cut short was left out изображение с обрезанными данными пропущено
@msg its editing data doesn't say where its art is в его данных редактирования не указано, где находится графика
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) этот файл сохранён без совместимости с PDF, и его данные редактирования не удаётся прочитать ({why})
@msg No fonts are missing in this document В этом документе нет отсутствующих шрифтов
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft не ищет в папках других приложений и системы: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft не ищет в папках Shared и Public внутри Users: {path}
@msg {path} is not a folder {path} не является папкой
@msg the search couldn't start: try again in a moment не удалось начать поиск: повторите попытку чуть позже
@msg searching a folder isn't available on the web поиск в папке недоступен в веб-версии
@msg every search thread stopped on an internal error (please report this bug) все потоки поиска остановились из-за внутренней ошибки (сообщите об этой ошибке)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папка Fonts VectorCraft здесь не задана: её задают настольное приложение и vectorcraft-cli
@msg choose the font files to add выберите файлы шрифтов для добавления
@msg {n} font file(s) are now in {folder} Файлов шрифтов теперь в {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлов шрифтов теперь в {folder}: {n}; не удалось добавить {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font здесь недоступно шрифтов: {n}; их текст отображается другим шрифтом
@msg not a file не файл
@msg not a font file не файл шрифта
@msg that document is no longer open этот документ больше не открыт
@msg larger than 256 MB больше 256 МБ
@msg the files come to more than 1 GB: add fewer at a time файлы занимают больше 1 ГБ: добавляйте меньше за раз
@msg every numbered name for it is taken in the Fonts folder все нумерованные имена для него уже заняты в папке Fonts
# The macOS menu bar (native_menu): the app and Window menus' system items, Settings pages.
Services Службы
Can't render this file because it contains an unexpected character in line 2 and column 73.
+37
View File
@@ -2054,6 +2054,25 @@
Reflect… Відобразити…
Refresh Оновити
Refresh Font List Оновити список шрифтів
Missing Fonts Відсутні шрифти
Missing Fonts Dialog Діалогове вікно «Відсутні шрифти»
These fonts aren't available. Their text shows in another font. Ці шрифти недоступні. Їхній текст показано іншим шрифтом.
Search Fonts Folder Шукати в папці Fonts
Find in Folder… Знайти в папці…
Find Fonts in Folder… Знайти шрифти в папці…
Find Font Files Знайти файли шрифтів
Add Font Files Додати файли шрифтів
Add Fonts Додати шрифти
Find Fonts Знайти шрифти
Stop Зупинити
Searching… Пошук…
Not found Не знайдено
{folders} folder(s) and {files} file(s) searched Переглянуто папок: {folders}, файлів: {files}
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones Пропущено папок: {count}, зокрема папки інших програм і системи та приховані папки
{count} folder(s) or file(s) couldn't be read Не вдалося прочитати папок або файлів: {count}
The search stopped at its limit: search a smaller folder. Пошук зупинився на межі: виберіть меншу папку.
Copy only fonts you own or are licensed to install. Копіюйте лише шрифти, які належать вам або які ви маєте право встановлювати за ліцензією.
VectorCraft copies the fonts to {folder}. VectorCraft копіює шрифти в {folder}.
Registered Trademark Symbol Символ зареєстрованого товарного знаку
Registration marks Мітки поєднання
Registry name: Ім’я у реєстрі:
@@ -3697,6 +3716,24 @@ axis Both Обидві
@msg an image whose data is cut short was left out зображення з обрізаними даними пропущено
@msg its editing data doesn't say where its art is у даних редагування не зазначено, де знаходиться графіка
@msg this file was saved without PDF compatibility, and its editing data can't be read ({why}) цей файл збережений без сумісності з PDF, і його дані редагування не вдається прочитати ({why})
@msg No fonts are missing in this document У цьому документі немає відсутніх шрифтів
@msg VectorCraft doesn't search other apps' or the system's folders: {path} VectorCraft не шукає в папках інших програм і системи: {path}
@msg VectorCraft doesn't search the Shared or Public folder in Users: {path} VectorCraft не шукає в папках Shared і Public у Users: {path}
@msg {path} is not a folder {path} не є папкою
@msg the search couldn't start: try again in a moment не вдалося почати пошук: спробуйте ще раз за мить
@msg searching a folder isn't available on the web пошук у папці недоступний у веб-версії
@msg every search thread stopped on an internal error (please report this bug) усі потоки пошуку зупинилися через внутрішню помилку (повідомте про цю помилку)
@msg VectorCraft's Fonts folder isn't set here: the desktop app and vectorcraft-cli set it Папку Fonts VectorCraft тут не задано: її задають настільна програма та vectorcraft-cli
@msg choose the font files to add виберіть файли шрифтів для додавання
@msg {n} font file(s) are now in {folder} Файлів шрифтів тепер у {folder}: {n}
@msg {n} font file(s) are now in {folder}; {failed} couldn't be added: {reason} Файлів шрифтів тепер у {folder}: {n}; не вдалося додати {failed}: {reason}
@msg {n} font(s) aren't available here: their text shows in another font тут недоступно шрифтів: {n}; їхній текст показано іншим шрифтом
@msg not a file не файл
@msg not a font file не файл шрифту
@msg that document is no longer open цей документ більше не відкрито
@msg larger than 256 MB більше 256 МБ
@msg the files come to more than 1 GB: add fewer at a time файли займають понад 1 ГБ: додавайте менше за раз
@msg every numbered name for it is taken in the Fonts folder усі нумеровані імена для нього вже зайняті в папці Fonts
Services Служби
Hide VectorCraft Приховати VectorCraft
Zoom Масштаб
Can't render this file because it contains an unexpected character in line 627 and column 40.
+19
View File
@@ -2016,6 +2016,25 @@
Reflect… 镜像…
Refresh 刷新
Refresh Font List 刷新字体列表
Missing Fonts 缺失的字体
Missing Fonts Dialog 缺失的字体对话框
These fonts aren't available. Their text shows in another font. 这些字体不可用。其文字以其他字体显示。
Search Fonts Folder 搜索 Fonts 文件夹
Find in Folder… 在文件夹中查找…
Find Fonts in Folder… 在文件夹中查找字体…
Find Font Files 查找字体文件
Add Font Files 添加字体文件
Add Fonts 添加字体
Find Fonts 查找字体
Stop 停止
Searching… 正在搜索…
Not found 未找到
{folders} folder(s) and {files} file(s) searched 已搜索 {folders} 个文件夹、{files} 个文件
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已跳过 {count} 个文件夹,例如其他应用程序和系统的文件夹,以及隐藏的文件夹
{count} folder(s) or file(s) couldn't be read 有 {count} 个文件夹或文件无法读取
The search stopped at its limit: search a smaller folder. 搜索已达上限而停止:请搜索较小的文件夹。
Copy only fonts you own or are licensed to install. 只复制您拥有或已获得安装许可的字体。
VectorCraft copies the fonts to {folder}. VectorCraft 会将字体复制到 {folder}。
Registered Trademark Symbol 注册商标符号
Registration marks 对位标记
Registry name: 登录名称:
Can't render this file because it contains an unexpected character in line 2 and column 73.
+19
View File
@@ -2065,6 +2065,25 @@
Reflect… 鏡射…
Refresh 重新整理
Refresh Font List 重新整理字體清單
Missing Fonts 遺失的字體
Missing Fonts Dialog 遺失的字體對話框
These fonts aren't available. Their text shows in another font. 這些字體無法使用。其文字以其他字體顯示。
Search Fonts Folder 搜尋 Fonts 資料夾
Find in Folder… 在資料夾中尋找…
Find Fonts in Folder… 在資料夾中尋找字體…
Find Font Files 尋找字體檔案
Add Font Files 新增字體檔案
Add Fonts 新增字體
Find Fonts 尋找字體
Stop 停止
Searching… 搜尋中…
Not found 找不到
{folders} folder(s) and {files} file(s) searched 已搜尋 {folders} 個資料夾、{files} 個檔案
{count} folder(s) skipped, such as other apps' and the system's folders and hidden ones 已略過 {count} 個資料夾,例如其他應用程式和系統的資料夾,以及隱藏的資料夾
{count} folder(s) or file(s) couldn't be read 有 {count} 個資料夾或檔案無法讀取
The search stopped at its limit: search a smaller folder. 搜尋已達上限而停止:請搜尋較小的資料夾。
Copy only fonts you own or are licensed to install. 只複製您擁有或已取得安裝授權的字體。
VectorCraft copies the fonts to {folder}. VectorCraft 會將字體複製到 {folder}。
Registered Trademark Symbol 註冊商標符號
Registration marks 對位標記
Registry name: 登錄名稱:
Can't render this file because it contains an unexpected character in line 6 and column 47.
+16
View File
@@ -137,6 +137,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
("type.recentFont15", "Recent Font 15", "", "{} apply the 15. most recently used font"),
("file.clearRecent", "Clear Recent Files", "", "{}"),
("type.findFont", "Find Font…", "", "{} open the Find Font dialog (engine: text.fonts / text.replaceFont / select.font)"),
(
"ui.missingFontsDialog",
"Missing Fonts Dialog",
"",
"{folder?} open Missing Fonts (dialog `missingFonts`) for the fonts the active document uses that aren't available (text.missingFonts); with folder, it looks for their files there at once (text.findFontFiles). An error when no font is missing. Opening a document whose fonts are missing shows it after the missing linked file questions (dialog `missingLinks`). Disabled on the web",
),
(
"ui.findFontsInFolder",
"Find Fonts in Folder…",
"",
"{folder?} Type › Find Font's Find in Folder…: asks for a folder (or takes folder), then opens Missing Fonts looking there for the files of the fonts the active document misses (text.findFontFiles). Disabled where there is no folder picker (the web)",
),
("file.recentFiles", "Recent Files", "", "{} → [path…] most recent first"),
(
"file.export.svg",
@@ -879,6 +891,8 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
crate::find_font::open(app);
Ok(Value::Null)
}
"ui.missingFontsDialog" => crate::dialogs::missing_fonts::open_command(app, s("folder")),
"ui.findFontsInFolder" => crate::dialogs::missing_fonts::find_in_folder_command(app, s("folder")),
"file.clearRecent" => {
app.ui.recent_files.clear();
Ok(Value::Null)
@@ -1853,6 +1867,8 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool {
"ui.cropImage" => selected_image(app, |_| true),
"effect.applyLast" | "effect.last" => app.last_effect.is_some() && app.session.active().is_some_and(|d| !d.selection.is_empty()),
"file.export.pdf" | "ui.savePdfDialog" | "ui.fileInfoDialog" | "ui.rasterEffectsSettingsDialog" => app.session.active().is_some(),
"ui.missingFontsDialog" => !cfg!(target_arch = "wasm32") && app.session.active().is_some(),
"ui.findFontsInFolder" => crate::picks::can(app, &crate::picks::PickRequest::Folder) && app.session.active().is_some(),
"ui.swatchOptions" | "ui.newSwatch" | "ui.newColorGroup" => app.session.active().is_some(),
"ui.graphicStyleOptions" => app.session.active().is_some(),
"ui.colorBalanceDialog" | "ui.saturateDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()),
+4 -1
View File
@@ -185,7 +185,10 @@ pub(crate) fn open_file(app: &mut VectorcraftApp, p: &Value, reveal: bool) -> Re
}
// A placed document's file opens here, in a new tab: saving it updates this document.
if !reveal && info["document"] == true {
app.run("document.open", json!({ "path": path }))?;
let opened = app.run("document.open", json!({ "path": path }))?;
// Its missing fonts are asked about as for a document opened with File › Open.
crate::dialogs::missing_fonts::after_open(app, &opened);
crate::dialogs::settle(app);
return Ok(json!({ "path": path }));
}
if reveal { crate::io::reveal_path(app, &path) } else { crate::io::open_in_app(app, &path) }?;
+15
View File
@@ -347,6 +347,18 @@ pub struct UiState {
/// dialog is open.
#[serde(skip)]
pub dialog_file: Option<std::sync::Arc<crate::dialogs::import_pdf::DialogFile>>,
/// The documents (uids) whose Missing Fonts dialog waits until no dialog is open, the next one to
/// show first ([`crate::dialogs::settle`]).
#[serde(skip)]
pub pending_fonts: Vec<u64>,
/// The document (uid) whose Missing Fonts dialog is on show. When another dialog takes its
/// place, [`crate::dialogs::settle`] puts the document back at the front of `pending_fonts`.
#[serde(skip)]
pub fonts_dialog: Option<u64>,
/// The search the Missing Fonts dialog started (`text.findFontFiles`'s `id`), stopped once the
/// dialog is gone.
#[serde(skip)]
pub dialog_search: Option<u64>,
/// The DXF Options chosen last (`document.exportDxf` options; null: never used).
#[serde(default)]
pub dxf_options: Value,
@@ -519,6 +531,9 @@ impl Default for UiState {
svg_options: Value::Null,
place_link: true,
dialog_file: None,
pending_fonts: vec![],
fonts_dialog: None,
dialog_search: None,
dxf_options: Value::Null,
eps_options: Value::Null,
dxf_import: Value::Null,
+21
View File
@@ -375,6 +375,27 @@ folder; `ui.dialog.set {field: "discard", value: true}` then confirm ignores it
Then, with the preference `updateLinks: "askWhenModified"`, modified linked files are offered for update in a
`confirm` dialog whose `ui.dialog.confirm` runs `links.update`.
Missing fonts: once the missing linked file questions are answered, or at once when there are none, `app.open` of a
document whose type uses fonts that aren't available (`text.missingFonts`) opens the `missingFonts` dialog, one document
at a time, and so does `links.editOriginal` of a placed document. When another dialog takes its place (Import PDF for a
file opened next, for example), the dialog opens again once that one closes. Fields: `document` (the document's uid),
`fonts` (`[{family, style, status, resolved}]`), `fontsNextToDocument` (the `Fonts` folder next to the document, or
empty), `state` (empty, `searching`, `done`, `stopped` or `failed`), `search` (the search's `id`), `folder`, `found`
(`text.findFontFiles`'s `fonts`, with the files found), `searched`, `skipped`, `unreadable`, `stopped`, `error` and
`chosen` (the files to add; a font's first file is chosen when the search finds it). Its buttons are Find Fonts and
Close, with Search Fonts Folder, Find in Folder… and, once files are found, Add Fonts in the dialog.
`ui.dialog.set {field: "discard", value: true}` then `ui.dialog.confirm` is Find Fonts: the dialog closes and Type ›
Find Font opens (dialog `findFont`) with the first missing font selected. `ui.dialog.set {field: "searchFolder",
value}` then `ui.dialog.confirm` searches that folder (`text.findFontFiles`), keeps the dialog open and clears
`searchFolder`, also when the search doesn't start. The fields change as frames draw the dialog; `text.findFontFiles
{}` reports the search directly. `ui.dialog.confirm` without `discard` or `searchFolder` is Add Fonts: it copies the
files in `chosen` (`text.addFontFiles`) and closes the dialog. `ui.dialog.cancel` (Close) closes it and stops its
search. After Find Fonts or Close, the dialog doesn't open again for that open.
`ui.missingFontsDialog {folder?}` opens the dialog for the active document, searching `folder` when given.
`ui.findFontsInFolder {folder?}` (Find in Folder… in Type › Find Font…, shown when the document misses fonts) asks for a
folder, then opens the dialog searching it. The web shows a status line instead of the dialog, and both commands are
disabled there.
Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place
dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`,
`removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area
+50 -1
View File
@@ -2562,7 +2562,11 @@ the fonts CoreText's font manager lists outside them, such as those apps and fon
folders; Linux and BSD: `/usr/share/fonts`,
`/usr/local/share/fonts`, `~/.fonts` and the XDG data folders' `fonts`, `~/.local/share/fonts` among them, and in a
Flatpak sandbox the host's fonts). Faces without outlines VectorCraft draws (no `glyf`, `CFF`, `CFF2` or `VARC` table, such
as bitmap-only fonts) are left out. The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
as bitmap-only fonts) are left out. The scan also reads the folder the `fontsFolder` preference names (Preferences › Type ›
Additional Fonts Folder) with its subfolders and, in the desktop app and `vectorcraft-cli`, VectorCraft's own `Fonts` folder
next to the preferences: `~/Library/Application Support/VectorCraft/Fonts` on macOS, `%APPDATA%\VectorCraft\Fonts` on
Windows, and `$XDG_CONFIG_HOME/vectorcraft/Fonts` or `~/.config/vectorcraft/Fonts` on Linux and BSD. `text.addFontFiles`
copies fonts into that folder. The installed fonts are cataloged once per session (in the background when the app starts, else on the first lookup
by family name), so opening, placing, pasting and importing files find them whatever ran before. `text.fontList`
lists every family available, the installed ones included, as the font menus do: without the system's hidden
families, whose names start with "." (macOS's ".SF NS", ".LastResort"), which still resolve when a document names
@@ -2578,6 +2582,51 @@ comes to the front and a font folder changed meanwhile.
{"name":"run_command","arguments":{"command":"text.rescanFonts","params":{}}}
```
`text.missingFonts` lists the fonts that the active document's type uses, in its layers and its symbols, and that aren't
available as named: `{fonts: [{family, style, status, resolved}], count, fontsNextToDocument?}`. `status` is `missing` or
`substitute`, as in `text.fonts`. CSS generic families such as `sans-serif`, which no font file provides, and names
longer than 256 bytes are left out. `fontsNextToDocument` is the `Fonts` folder next to the saved document
(File › Package writes it), when there is one and a search may start there. `text.findFontFiles {folder}` looks for
the fonts' files in an absolute folder and its subfolders on separate threads and returns at once with
`state: "searching"` and an `id`; `fonts: [{family, style?}]` names other fonts to look for. `text.findFontFiles {}`
returns the last search's state with the files found so far for each font: `searching`, `done`, `stopped` (with
`stopped`: `stop`, `time` or `limit`) or `failed` (with `error`); before the first search it returns
`{state: "idle", fonts: []}`, without an `id`. `{stop: true}` stops the search. A search reads the table directories
and the `name`, `fvar` and `OS/2` tables of `.ttf`, `.otf`, `.ttc` and `.otc` files and, on macOS, of suitcase fonts
(extensionless or `.suit` files whose fonts are in their resource fork), and it lists a file for a font only when adding
the file makes the font resolve exactly as `text.fonts` resolves it. It ends after `maxSeconds` (60 by default, 1 to
600), at its limits on the entries listed (10,000,000), the folders waiting to be listed (1,000,000), the font files
read (10,000) and the files kept (1,000), or once every font has a file. Folders more than 64 levels below the picked
one are skipped and counted in `skipped`. A search does not read a font file larger than 256 MB, which
`text.addFontFiles` does not copy, or a suitcase font whose resource fork is larger than 8 MB.
A search does not enter app and media library packages (`.app`, `.bundle`, `.framework`, `.photoslibrary` and the like),
folders named `Program Files` (also `Program Files (x86)` and `Program Files (Arm)`), `ProgramData`, `$Recycle.Bin` or
`System Volume Information`, the system's folders at the root of a volume (a macOS, Linux, BSD or Windows root, told by
the folders it holds), the `Shared` and `Public` folders in `Users`, a home folder's `Library`, `AppData`,
`Applications` and `snap` folders and the folders in it whose names start with a dot, the app data folders in a
`Library` folder (`Application Support`, `Containers`, `Group Containers`, `Caches`, `Preferences`), or the folders the
environment names for apps and the system (such as `APPDATA`, `LOCALAPPDATA`, `ProgramFiles`, `SystemRoot` and
`XDG_CONFIG_HOME`), and a search of a folder inside one of them fails. The walk also skips other hidden folders and
folders whose contents are in the cloud, and it follows no links; a picked folder may be one of those, and a picked path
that goes through a link is searched at its target. Programs installed in other folders, such as a folder on another
drive, are searched as any other folder is.
`text.addFontFiles {files}` copies files that the session's last search found into VectorCraft's `Fonts` folder, then
scans the fonts again, and type set in them redraws. It copies only regular `.ttf`, `.otf`, `.ttc`, `.otc`, `.woff`
and `.woff2` files and suitcase fonts (with their resource fork), at most 256 MB a file and 1 GB in all, and lists any
other file in `skipped`. It never replaces a file: a file with the same contents is kept (`kept`), and when another
file has the name, the copy gets a number (`Name 2.otf`). Copy only fonts you own or are licensed to install. `command.batch` returns before a search ends; later requests over MCP or the control channel poll
`text.findFontFiles {}`. `vectorcraft-cli run` stops the search when its last step ends. The web build has no Fonts
folder and no folder search.
```json
{"name":"run_command","arguments":{"command":"text.missingFonts","params":{}}}
{"name":"run_command","arguments":{"command":"text.findFontFiles","params":{"folder":"/Users/me/Downloads"}}}
{"name":"run_command","arguments":{"command":"text.findFontFiles","params":{}}}
{"name":"run_command","arguments":{"command":"text.addFontFiles","params":{"files":["/Users/me/Downloads/Example/Example-Regular.otf"]}}}
```
## Tool options
`tool.setOption` reads and sets a tool's options, headless too: `{key, value}` or `{values: {…}}` sets them on the