diff --git a/AGENTS.md b/AGENTS.md index ff4606fd5f..2fd1513b85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/`. See `README.md` for layout and released versions. -- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`. +- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below). - **No app code.** A crate here is useful to more than one app and does not depend on any app. -- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`. +- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls. - **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p --all-targets -- -D warnings`, `cargo test -p `. diff --git a/Cargo.lock b/Cargo.lock index a7e2b62777..bc2c0ff33b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2181,6 +2181,14 @@ dependencies = [ "wuff", ] +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "craft-font-store" version = "0.1.0" @@ -2188,6 +2196,7 @@ dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", diff --git a/Cargo.toml b/Cargo.toml index 607c0a49dd..bc76a21ab0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -112,6 +112,7 @@ craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } +craft-font-os-windows = { path = "crates/font-os-windows" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } craft-flow = { path = "crates/flow" } diff --git a/README.md b/README.md index 9512980917..29615b42a3 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit and filters over the Google Fonts index, installed fonts by family, the font store interface, and (`egui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab and the standalone app. +- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store` + needs on Windows to make a font available to every app of the user (the per-user font + registry, `AddFontResourceW`, `WM_FONTCHANGE`); the one crate here allowed `unsafe`. - [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub) diff --git a/crates/font-catalog/README.md b/crates/font-catalog/README.md index c0576767b8..08eed3c73f 100644 --- a/crates/font-catalog/README.md +++ b/crates/font-catalog/README.md @@ -54,6 +54,8 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family - `family(name)` and `resolve(name, style)` accept any name of a family: its own name ignoring ASCII case, its names in other languages and its legacy names ignoring case and anything but letters and digits. `resolve` also accepts a legacy family with its legacy style (`Roboto Light` / `Regular`), a full name, and a PostScript name. - Within a family, `resolve` matches the style by name (any of its names). Otherwise it picks the nearest weight, with italic differing counting as 1000, then the nearest width. It returns `Match::Exact` or `Match::NearestStyle`, so the app decides about substitutes. - `by_postscript_name(name)`. +- `faces()` lists each face once: of faces with the same family, style and PostScript name it keeps the first (added faces, then by path), except that the font store's face wins over a scanned copy elsewhere, such as one in the OS font folder. `scanned_faces()` lists every face the scan found, the same font in two places included, for telling copies apart (craft-font-store's conflict check). +- `read_faces(path, source)` reads one file's faces, named instances included, as a scan does, without a catalog. ## Loading and threads diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 10663e6afc..65a27b8d5c 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -132,17 +132,29 @@ struct Index { impl Index { /// Added faces first: a document's or the app's own face wins over an installed face of the - /// same family and style. + /// same family and style. Among scanned duplicates the font store's face wins, so a store + /// font copied into the OS font folder stays the store's wherever the folders sort. fn build(added: &[Face], scanned: &[Face]) -> Self { - let mut faces: Vec = Vec::new(); - let mut seen = HashSet::new(); - for f in added.iter().chain(scanned) { + let all: Vec<&Face> = added.iter().chain(scanned).collect(); + let mut winner: HashMap<_, usize> = HashMap::new(); + for (i, f) in all.iter().enumerate() { let variations: Vec<(u32, u32)> = f.info.variations.iter().map(|(t, v)| (u32::from_be_bytes(*t), v.to_bits())).collect(); let key = (f.info.family.to_ascii_lowercase(), norm(&f.info.style), f.keys.postscript.first().cloned(), variations); - if seen.insert(key) { - faces.push(f.clone()); + match winner.entry(key) { + std::collections::hash_map::Entry::Vacant(e) => { + e.insert(i); + } + std::collections::hash_map::Entry::Occupied(mut e) => { + let held = *e.get(); + if held >= added.len() && all[held].info.source != Source::Store && f.info.source == Source::Store { + e.insert(i); + } + } } } + let mut kept: Vec = winner.into_values().collect(); + kept.sort_unstable(); + let faces: Vec = kept.into_iter().map(|i| all[i].clone()).collect(); let mut by_family: HashMap> = HashMap::new(); let mut aliases: HashMap> = HashMap::new(); let mut postscript: HashMap = HashMap::new(); @@ -327,6 +339,12 @@ fn modified(path: &Path) -> Option { std::fs::metadata(path).and_then(|m| m.modified()).ok() } +/// The faces of the font file at `path` as a scan reads them, named instances included, with +/// `source` as their source. Empty when it isn't a font. +pub fn read_faces(path: &Path, source: Source) -> Vec { + scan::file_faces(path, MAX_SCAN_READ, source).into_iter().map(|f| f.info).collect() +} + impl Catalog { /// A catalog of the fonts installed on the system `env` describes, the font store, and the /// files the platform's font service lists (with the `system` feature). @@ -491,6 +509,14 @@ impl Catalog { self.generation.fetch_add(1, Ordering::AcqRel); } + /// Every face the last scan found, in path order, with the faces [`Catalog::faces`] drops as + /// duplicates of another of the same family, style and PostScript name. Faces added from + /// files or bytes aren't in it. For telling apart copies of one font in different places. + pub fn scanned_faces(&self) -> Vec { + self.ensure(); + self.scanned().into_iter().map(|f| f.info).collect() + } + /// The family names, sorted ignoring case. pub fn families(&self) -> Arc<[String]> { Arc::clone(&self.snapshot().families) diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index 70aaa19b1f..81788757ef 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -40,7 +40,7 @@ mod suitcase; pub mod system; mod visual_order; -pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch}; +pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, read_faces}; pub use embedding::{SubsetEmbedding, subset_embedding}; pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs}; pub use face_data::FaceData; diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 83628ac34f..7e0a0c4506 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -360,6 +360,23 @@ fn lookup_by_every_name_kind() { assert_eq!(cat.by_postscript_name("Missing-Regular"), None); } +#[test] +fn the_stores_face_wins_over_its_copy_in_the_os_folder() { + // A Flatpak's store sits under ~/.var/app, which sorts after the host's ~/.local/share/fonts + // the store copies its fonts into. + let root = temp("store-copy"); + let bytes = font(&spec("Copied Sans", "Regular", 400)); + write(&root.join("home/.local/share/fonts/Craft/Copied Sans/CopiedSans-Regular.ttf"), &bytes); + let store = root.join("home/.var/app/org.example.Fonts/data/craft-fonts"); + write(&store.join("Copied Sans/CopiedSans-Regular.ttf"), &bytes); + let cat = Catalog::new(FontEnv { font_store: Some(store), ..linux_env(&root) }).with_font_service(false); + cat.rescan(); + let styles = cat.styles("Copied Sans"); + assert_eq!(styles.len(), 1); + assert_eq!(styles[0].source, Source::Store); + assert_eq!(cat.scanned_faces().iter().filter(|f| f.family == "Copied Sans").count(), 2); +} + #[test] fn installed_and_removed_fonts_are_seen_without_a_restart() { let root = temp("rescan"); diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index 279fafb6ac..f769ef4514 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -10,7 +10,7 @@ Fonts tab; the standalone app | `filter` | always | Search over the index: family names ignoring case and accents, category, language (English name, autonym or id) and script | | `index` | always | The pinned built-in indexes (Google Fonts and Noto) compiled into [`craft-font-store`](../font-store/README.md) (`bundled`), each family's source (`source_label`: its name and whether it is curated), and the categories | | `installed` | always | The installed fonts [`craft-font-catalog`](../font-catalog/README.md) sees, grouped by family and source | -| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`) and the optional preview service address (`preview_service`, `set_preview_service`) and the previews setting (`previews_enabled`, `set_previews_enabled`). `SuiteStore` is craft-font-store's store (`with_default_preview_service(url)` gives it the host's default preview service, used while neither the environment nor the user's setting names one), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown | +| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`) and the optional preview service address (`preview_service`, `set_preview_service`) and the previews setting (`previews_enabled`, `set_previews_enabled`), and a family's copies in the OS user font folder (`available_to_all_supported`, `is_available_to_all`, `not_yet_available`, `make_available`, `withdraw`). `SuiteStore` is craft-font-store's store (`with_default_preview_service(url)` gives it the host's default preview service, used while neither the environment nor the user's setting names one), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown | | `remote` | always | The preview service client: subset URLs (`PreviewKey`, `Codepoints`), a fetch pool (`Previews`: 8 at a time, highest priority first, cancel by key, results by `poll`) that decodes WOFF2, and the disk cache in the store's `previews/` folder (`DiskCache`, least recently used out past 50 MB). It requests nothing unless a preview service is set and previews are enabled (`Installer::previews_enabled`, a user setting, on by default). There is no prompt, and the install consent (`downloads_allowed`) is not consulted. With previews off nothing goes to the network, and cached previews are still used | | `FontsPanel` | `egui` | The whole interface as one egui panel | diff --git a/crates/font-manager/src/panel/app.rs b/crates/font-manager/src/panel/app.rs index 1d4be3c145..fa2676556b 100644 --- a/crates/font-manager/src/panel/app.rs +++ b/crates/font-manager/src/panel/app.rs @@ -9,7 +9,7 @@ use crate::filter::{Query, Search}; use crate::index::{Category, Family, FontFile, Index, categories, source_label}; use crate::installed::{InstalledFamily, group}; use crate::remote::Previews; -use crate::store::{Installer, RemoveRequest, StoreError}; +use crate::store::{Conflict, Installer, MadeAvailable, RemoveRequest, StoreError}; use crate::{Catalog, FaceInfo, Source}; use craft_i18n::Folder; use craft_ui::direction; @@ -133,6 +133,14 @@ pub(crate) enum Detail { Installed(String, Source), } +/// Why a family installed here isn't in the OS user font folder. +#[derive(Clone, Debug)] +pub(crate) enum NotCopied { + /// Fonts already there have its PostScript names, or sit where its copies would go. + Refused(Vec), + Failed(String), +} + /// Why the last job for a family failed, and what Retry runs. #[derive(Clone, Debug)] pub(crate) struct Failure { @@ -198,6 +206,10 @@ pub struct FontsPanel { pub(crate) failed: HashMap, /// A problem that belongs to no family (the download setting couldn't be saved). pub(crate) notice: Option, + /// Families an install couldn't copy into the OS user font folder, by lower-case name. + pub(crate) not_copied: HashMap, + /// "Keep fonts in Craft apps only" as last read or set. + pub(crate) craft_apps_only: bool, focused: bool, pub(crate) folder: Folder, /// The download consent as last read, and when. @@ -285,6 +297,7 @@ impl FontsPanel { look, downloads_switch: true, catalog: options.catalog, + craft_apps_only: options.installer.craft_apps_only(), installer: options.installer, catalogue, query: Query::default(), @@ -316,6 +329,7 @@ impl FontsPanel { asking: None, failed: HashMap::new(), notice: None, + not_copied: HashMap::new(), focused: true, folder: Folder::new("en"), consent: None, @@ -557,8 +571,20 @@ impl FontsPanel { for (job, result) in self.jobs.poll() { let key = family_key(&job.source, &job.family); match result { - Ok(Finished::Installed | Finished::Removed) => { + Ok(Finished::Installed(copied)) => { self.failed.remove(&key); + self.record_copy(&job.family, copied); + } + Ok(Finished::Removed) => { + self.failed.remove(&key); + self.not_copied.remove(&job.family.to_lowercase()); + } + Ok(Finished::CraftAppsOnly(refused)) => { + self.not_copied = refused.into_iter().map(|(f, c)| (f.to_lowercase(), NotCopied::Refused(c))).collect(); + } + Err(e) if job.kind == Kind::CraftAppsOnly => { + self.craft_apps_only = self.installer.craft_apps_only(); + self.notice = Some(fmt("The Craft apps only setting couldn't be applied: {error}", &[("error", &e.0)])); } Ok(Finished::Previewed(files)) => { self.failed.remove(&key); @@ -579,7 +605,7 @@ impl FontsPanel { let retry = position.and_then(|i| match job.kind { Kind::Install => Some(job.file.clone().map_or(Pending::Install(i), |path| Pending::InstallFile(i, path))), Kind::Preview => Some(Pending::Preview(i)), - Kind::Remove => None, + Kind::Remove | Kind::CraftAppsOnly => None, }); log::warn!("{} ({:?}): {e}", job.family, job.kind); self.failed.insert(key, Failure { kind: job.kind, error: e.0, retry }); @@ -589,6 +615,26 @@ impl FontsPanel { self.poll_sources(); } + fn record_copy(&mut self, family: &str, copied: Option>) { + let not_copied = match copied { + Some(Ok(MadeAvailable::Refused(conflicts))) => NotCopied::Refused(conflicts), + Some(Err(e)) => NotCopied::Failed(e.0), + Some(Ok(MadeAvailable::Done)) | None => { + self.not_copied.remove(&family.to_lowercase()); + return; + } + }; + self.not_copied.insert(family.to_lowercase(), not_copied); + } + + /// Sets "Keep fonts in Craft apps only" on the worker, which then withdraws or copies every + /// store family. + pub(crate) fn set_craft_apps_only(&mut self, ctx: &Context, on: bool) { + self.craft_apps_only = on; + self.notice = None; + self.jobs.start(ctx, Arc::clone(&self.installer), Arc::clone(&self.catalog), Request::CraftAppsOnly(on)); + } + fn refresh_installed(&mut self) { if !self.catalog.is_ready() { return; diff --git a/crates/font-manager/src/panel/browse.rs b/crates/font-manager/src/panel/browse.rs index db59755d60..ab92fdafa2 100644 --- a/crates/font-manager/src/panel/browse.rs +++ b/crates/font-manager/src/panel/browse.rs @@ -99,10 +99,27 @@ impl FontsPanel { let note = tl!("From each font's source, only when you install or preview a font."); ui.add(egui::Label::new(egui::RichText::new(note).size(12.0).color(s.p.muted)).wrap()); } + if self.installer.available_to_all_supported() { + self.craft_apps_only_switch(ui, &s); + } }); }); } + fn craft_apps_only_switch(&mut self, ui: &mut Ui, s: &Skin) { + ui.add_space(14.0); + ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), s.hairline()); + ui.add_space(14.0); + widgets::label(ui, s, tl!("System fonts"), s.p.faint); + let mut on = self.craft_apps_only; + let idle = !self.jobs.runs(Kind::CraftAppsOnly); + if ui.add_enabled(idle, egui::Checkbox::new(&mut on, tl!("Keep fonts in Craft apps only"))).changed() { + self.set_craft_apps_only(ui.ctx(), on); + } + let note = tl!("Off: fonts you install here are also copied to your system's fonts folder, for all apps."); + ui.add(egui::Label::new(egui::RichText::new(note).size(12.0).color(s.p.muted)).wrap()); + } + fn catalogue_filters(&mut self, ui: &mut Ui, s: &Skin) { let Ok(c) = &self.catalogue else { return }; let index = Arc::clone(&c.index); @@ -661,6 +678,7 @@ impl FontsPanel { Kind::Install => tl!("Installing"), Kind::Remove => tl!("Removing"), Kind::Preview => tl!("Downloading"), + Kind::CraftAppsOnly => tl!("Updating system fonts"), }; let text = match fraction { Some(f) => format!("{what} {}", fmt("{percent} %", &[("percent", &i18n::number((f * 100.0).round() as u64))])), @@ -683,6 +701,7 @@ impl FontsPanel { Kind::Install => tl!("Couldn't install"), Kind::Remove => tl!("Couldn't remove"), Kind::Preview => tl!("Couldn't download"), + Kind::CraftAppsOnly => tl!("Couldn't update system fonts"), }; widgets::label(ui, s, what, p.bad).on_hover_text(error); } diff --git a/crates/font-manager/src/panel/details.rs b/crates/font-manager/src/panel/details.rs index b4859ae333..14ca96996a 100644 --- a/crates/font-manager/src/panel/details.rs +++ b/crates/font-manager/src/panel/details.rs @@ -16,7 +16,7 @@ use egui::{ }; use crate::index::{Family, FontFile, Index, script_name, source_label}; -use crate::panel::app::{Detail, FontsPanel, Pending, category_label, family_key, regular, source_name, style_count, style_name}; +use crate::panel::app::{Detail, FontsPanel, NotCopied, Pending, category_label, family_key, regular, source_name, style_count, style_name}; use crate::panel::faces::{Owner, Shown}; use crate::panel::i18n::{self, fmt, tl, tn}; use crate::panel::jobs::Kind; @@ -313,6 +313,7 @@ impl FontsPanel { Kind::Install => tl!("Installing"), Kind::Remove => tl!("Removing"), Kind::Preview => tl!("Downloading"), + Kind::CraftAppsOnly => tl!("Updating system fonts"), }; self.progress(ui, s, what, *fraction, 220.0); } @@ -332,6 +333,7 @@ impl FontsPanel { } } }); + self.system_fonts_line(ui, s, &family.family, &store); if session_preview { let note = fmt("Preview downloads this font ({size}) for this session without installing it.", &[("size", &size)]); ui.label(RichText::new(note).size(12.5).color(s.p.muted)); @@ -357,6 +359,7 @@ impl FontsPanel { Kind::Install => tl!("Couldn't install"), Kind::Remove => tl!("Couldn't remove"), Kind::Preview => tl!("Couldn't download"), + Kind::CraftAppsOnly => tl!("Couldn't update system fonts"), }; let buttons: &[&str] = if failure.retry.is_some() { &[tl!("Retry")] } else { &[] }; let mut retry = false; @@ -476,6 +479,7 @@ impl FontsPanel { self.remove(&ctx, &family.name, &family.faces, true); } }); + self.system_fonts_line(ui, s, &family.name, &family.faces); ui.add_space(14.0); let rows = family .faces @@ -499,6 +503,25 @@ impl FontsPanel { close } + /// Whether the family's store fonts are in the OS user font folder for all apps, or why not. + fn system_fonts_line(&self, ui: &mut Ui, s: &Skin, family: &str, faces: &[FaceInfo]) { + let files: Vec<_> = faces.iter().filter(|f| f.source == Source::Store).filter_map(|f| f.path.clone()).collect(); + if files.is_empty() { + return; + } + let not_here = self.installer.available_to_all_unsupported(); + let (text, colour) = if let Some(reason) = not_here { + (fmt("Only in Craft apps: {reason}", &[("reason", &reason)]), s.p.muted) + } else if self.installer.is_available_to_all(family, &files) { + (tl!("Available to all apps").to_owned(), s.p.good) + } else if let Some(not_copied) = self.not_copied.get(&family.to_lowercase()) { + (not_copied_text(not_copied), s.p.warn) + } else { + (tl!("Kept in Craft apps only").to_owned(), s.p.muted) + }; + ui.add(egui::Label::new(RichText::new(text).size(12.5).color(colour)).wrap()); + } + fn progress(&self, ui: &mut Ui, s: &Skin, what: &str, fraction: Option, width: f32) { let text = match fraction { Some(f) => format!("{what} {}", fmt("{percent} %", &[("percent", &i18n::number((f * 100.0).round() as u64))])), @@ -801,6 +824,18 @@ impl FontsPanel { } } +fn not_copied_text(not_copied: &NotCopied) -> String { + let conflict = match not_copied { + NotCopied::Failed(error) => return fmt("Couldn't copy to your system's fonts folder: {error}", &[("error", error)]), + NotCopied::Refused(conflicts) => conflicts.first(), + }; + let file = conflict.map(|c| c.path.display().to_string()).unwrap_or_default(); + match conflict.and_then(|c| c.postscript.as_deref()) { + Some(name) => fmt("Not copied to your system's fonts folder: {file} already has the font name {name}", &[("file", &file), ("name", name)]), + None => fmt("Not copied to your system's fonts folder: {file} is in the way", &[("file", &file)]), + } +} + fn action_clone(action: &RowAction) -> RowAction { match action { RowAction::None => RowAction::None, diff --git a/crates/font-manager/src/panel/jobs.rs b/crates/font-manager/src/panel/jobs.rs index 2a688c02e3..d93e3526e8 100644 --- a/crates/font-manager/src/panel/jobs.rs +++ b/crates/font-manager/src/panel/jobs.rs @@ -1,4 +1,5 @@ -//! Installs, removals and preview downloads, one at a time on a worker thread. +//! Installs, removals, preview downloads and the "Keep fonts in Craft apps only" setting, one at +//! a time on a worker thread. use std::collections::BTreeMap; use std::sync::Arc; @@ -6,7 +7,7 @@ use std::sync::mpsc::{Receiver, Sender, channel}; use crate::Catalog; use crate::index::Index; -use crate::store::{Downloaded, Installer, Progress, RemoveRequest, StoreError}; +use crate::store::{Conflict, Downloaded, Installer, MadeAvailable, Progress, RemoveRequest, StoreError}; type Task = Box; @@ -24,6 +25,8 @@ pub enum Kind { Install, Remove, Preview, + /// Changing "Keep fonts in Craft apps only"; it has no family. + CraftAppsOnly, } pub struct Running { @@ -44,9 +47,12 @@ impl Running { } pub enum Finished { - Installed, + /// With what copying the family into the OS user font folder did, when it was copied. + Installed(Option>), Removed, Previewed(Vec), + /// The families a conflict kept out of the OS user font folder. + CraftAppsOnly(Vec<(String, Vec)>), } enum Msg { @@ -62,6 +68,8 @@ pub enum Request { Remove(RemoveRequest), /// A family of the index, by position. Preview(Arc, usize), + /// Sets "Keep fonts in Craft apps only". + CraftAppsOnly(bool), } pub struct Jobs { @@ -93,12 +101,19 @@ impl Jobs { Jobs { worker, tx, rx, next: 0, running: BTreeMap::new() } } + /// Whether a job of `kind` runs or waits. + pub fn runs(&self, kind: Kind) -> bool { + self.running.values().any(|r| r.kind == kind) + } + /// The job running for `family` of `source` (any source when empty), if any. pub fn of(&self, source: &str, family: &str) -> Option<&Running> { self.running.values().find(|r| r.family.eq_ignore_ascii_case(family) && (source.is_empty() || r.source.is_empty() || r.source == source)) } - /// Runs `request` through `installer`, then rescans `catalog` after an install or removal. + /// Runs `request` through `installer`, then rescans `catalog` after an install or removal. An + /// install also copies the family into the OS user font folder, unless the user keeps fonts in + /// Craft apps only. pub fn start(&mut self, ctx: &egui::Context, installer: Arc, catalog: Arc, request: Request) { let id = self.next; self.next += 1; @@ -117,6 +132,7 @@ impl Jobs { let file = if r.whole { None } else { r.files.first().map(|p| p.display().to_string()) }; (String::new(), r.family.clone(), Kind::Remove, file, 0) } + Request::CraftAppsOnly(_) => (String::new(), String::new(), Kind::CraftAppsOnly, None, 0), }; self.running.insert(id, Running { source, family, kind, file, progress: Progress { done: 0, total } }); let tx = self.tx.clone(); @@ -127,17 +143,20 @@ impl Jobs { ctx.request_repaint(); }; let family = |index: &Index, i: usize| index.families().get(i).cloned().ok_or_else(|| StoreError("no such family".into())); + let copy = |name: &str| { + let copy = installer.available_to_all_supported() && !installer.craft_apps_only(); + Finished::Installed(copy.then(|| installer.make_available(name, &[]))) + }; let result = match request { - Request::Install(index, i) => { - family(&index, i).and_then(|f| installer.install(&index, &f, &mut progress)).map(|()| Finished::Installed) - } + Request::Install(index, i) => family(&index, i).and_then(|f| installer.install(&index, &f, &mut progress).map(|()| copy(&f.family))), Request::InstallFile(index, i, path) => { - family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress)).map(|()| Finished::Installed) + family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress).map(|()| copy(&f.family))) } Request::Remove(r) => installer.remove(&r).map(|()| Finished::Removed), Request::Preview(index, i) => family(&index, i).and_then(|f| installer.download(&index, &f, &mut progress)).map(Finished::Previewed), + Request::CraftAppsOnly(on) => installer.set_craft_apps_only(on).map(Finished::CraftAppsOnly), }; - if matches!(result, Ok(Finished::Installed | Finished::Removed)) { + if matches!(result, Ok(Finished::Installed(_) | Finished::Removed)) { catalog.rescan(); } let _ = tx.send(Msg::Done(id, result)); diff --git a/crates/font-manager/src/store.rs b/crates/font-manager/src/store.rs index a3d8d800ef..fc08f8a508 100644 --- a/crates/font-manager/src/store.rs +++ b/crates/font-manager/src/store.rs @@ -12,7 +12,7 @@ use std::sync::{Condvar, Mutex}; use craft_font_catalog::Catalog; use craft_font_store::{Cancel, Client, Face, FontStore, Network, PINNED_INDEX, verify_font}; -pub use craft_font_store::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource}; +pub use craft_font_store::{Conflict, LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource}; use crate::index::{Family, Index}; @@ -52,6 +52,15 @@ impl std::fmt::Display for StoreError { impl std::error::Error for StoreError {} +/// What [`Installer::make_available`] did. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MadeAvailable { + Done, + /// Refused, changing nothing: fonts on the system already have the family's PostScript + /// names, or sit where its copies would go. + Refused(Vec), +} + fn err(e: impl std::fmt::Display) -> StoreError { StoreError(e.to_string()) } @@ -153,9 +162,64 @@ pub trait Installer: Send + Sync { fn legal_text(&self, _index: &Index, _family: &Family, _which: LegalText) -> Result, StoreError> { Err(StoreError(NO_FOLDER.into())) } + + /// Whether store families can be made available to all apps (copied into the OS user font + /// folder). The interface offers the action only when this is true. + fn available_to_all_supported(&self) -> bool { + false + } + + /// Why store families can't be made available to all apps here, in English; `None` when they + /// can. + fn available_to_all_unsupported(&self) -> Option { + (!self.available_to_all_supported()).then(|| NOT_HERE.to_owned()) + } + + /// Whether the user keeps store fonts in Craft apps only (a setting of the font store, off by + /// default). While it is off, the interface makes every family it installs available to all + /// apps. + fn craft_apps_only(&self) -> bool { + false + } + + /// Sets [`Installer::craft_apps_only`], as the user's own action, then withdraws every store + /// family's copies from the OS user font folder (on) or copies every installed family there + /// (off). Returns the families a conflict refused, with the conflicts. It blocks: call it on + /// a worker thread. + fn set_craft_apps_only(&self, _on: bool) -> Result)>, StoreError> { + Err(StoreError(NO_FOLDER.into())) + } + + /// Whether the store family `family` (its name, and the files the catalog found for it in + /// the font store) is available to all apps. Cheap enough to call for every row. + fn is_available_to_all(&self, _family: &str, _files: &[PathBuf]) -> bool { + false + } + + /// The files of an available store family not available to all apps yet (styles an agent + /// installed, say), by their names in the store, for the interface to offer copying them. + fn not_yet_available(&self, _family: &str, _files: &[PathBuf]) -> Vec { + Vec::new() + } + + /// Makes a store family available to all apps, as the user's own action; calling it again + /// copies the styles [`Installer::not_yet_available`] lists. A font on the system with one of + /// its PostScript names refuses it ([`MadeAvailable::Refused`]). It blocks (hashing, copying, + /// a catalog rescan): call it on a worker thread. + fn make_available(&self, _family: &str, _files: &[PathBuf]) -> Result { + Err(StoreError(NOT_HERE.into())) + } + + /// Takes a store family's copies out of the OS user font folder, as the user's own action. + /// Returns the copies left in place because they changed since. It blocks: call it on a + /// worker thread. + fn withdraw(&self, _family: &str, _files: &[PathBuf]) -> Result, StoreError> { + Err(StoreError(NOT_HERE.into())) + } } const NO_FOLDER: &str = "there is no folder for the font store"; +const NOT_HERE: &str = "fonts can't be made available to all apps here"; /// craft-font-store's store, in the user's font store folder. pub struct SuiteStore { @@ -187,18 +251,22 @@ impl SuiteStore { self.store.client() } - /// The store's source and name for the family holding `files`, which can differ from the - /// name in the fonts themselves. - fn installed_name(&self, request: &RemoveRequest) -> Option<(String, String)> { + /// The store's source and name for the family `family` holding `files`, which can differ + /// from the name in the fonts themselves. + fn installed_name(&self, family: &str, files: &[PathBuf]) -> Option<(String, String)> { let dir = self.store.dir(); let installed = self.store.installed(); - let lower = request.family.to_lowercase(); + let lower = family.to_lowercase(); installed .iter() - .find(|f| request.files.iter().any(|path| path.starts_with(dir.join(&f.dir)))) + .find(|f| files.iter().any(|path| path.starts_with(dir.join(&f.dir)))) .or_else(|| installed.iter().find(|f| f.family.to_lowercase() == lower)) .map(|f| (f.source.clone(), f.family.clone())) } + + fn found(&self, family: &str, files: &[PathBuf]) -> Result<(String, String), StoreError> { + self.installed_name(family, files).ok_or_else(|| err(craft_font_store::Error::NotInstalled(family.to_owned()))) + } } impl Installer for SuiteStore { @@ -222,7 +290,7 @@ impl Installer for SuiteStore { } fn remove(&self, request: &RemoveRequest) -> Result<(), StoreError> { - let (source, name) = self.installed_name(request).ok_or_else(|| err(craft_font_store::Error::NotInstalled(request.family.clone())))?; + let (source, name) = self.found(&request.family, &request.files)?; if request.whole { return self.store.remove_family(&source, &name).map_err(err); } @@ -313,6 +381,58 @@ impl Installer for SuiteStore { fn legal_text(&self, index: &Index, family: &Family, which: LegalText) -> Result, StoreError> { self.store.legal_text(index, family, which, &Cancel::new()).map_err(err) } + + fn available_to_all_supported(&self) -> bool { + self.store.available_to_all_supported() + } + + fn available_to_all_unsupported(&self) -> Option { + self.store.available_to_all_unsupported().map(str::to_owned) + } + + fn craft_apps_only(&self) -> bool { + self.store.craft_apps_only() + } + + fn set_craft_apps_only(&self, on: bool) -> Result)>, StoreError> { + self.store.set_craft_apps_only(on).map_err(err)?; + let mut refused = Vec::new(); + for f in self.store.installed() { + if on { + self.store.withdraw(&f.source, &f.family).map_err(err)?; + continue; + } + match self.store.make_available(&f.source, &f.family) { + Ok(_) => {} + Err(craft_font_store::Error::Conflict(conflicts)) => refused.push((f.family, conflicts)), + Err(e) => return Err(err(e)), + } + } + Ok(refused) + } + + fn is_available_to_all(&self, family: &str, files: &[PathBuf]) -> bool { + self.store.available_family_holding(family, files).is_some() + } + + fn not_yet_available(&self, family: &str, files: &[PathBuf]) -> Vec { + self.installed_name(family, files).map(|(source, name)| self.store.pending_files(&source, &name)).unwrap_or_default() + } + + fn make_available(&self, family: &str, files: &[PathBuf]) -> Result { + let (source, name) = self.found(family, files)?; + match self.store.make_available(&source, &name) { + Ok(_) => Ok(MadeAvailable::Done), + Err(craft_font_store::Error::Conflict(conflicts)) => Ok(MadeAvailable::Refused(conflicts)), + Err(e) => Err(err(e)), + } + } + + fn withdraw(&self, family: &str, files: &[PathBuf]) -> Result, StoreError> { + // A family an unsupported build removed keeps its ledger entry and copies. + let (source, name) = self.found(family, files).or_else(|e| self.store.available_family_holding(family, files).ok_or(e))?; + self.store.withdraw(&source, &name).map_err(err) + } } /// The store when the system names no folder for it (no home folder): nothing installs. @@ -352,6 +472,8 @@ pub enum Call { InstallFile(String, String), Remove(String), Download(String), + MakeAvailable(String), + Withdraw(String), } /// A font store without a network: "downloads" come from a table of file bytes by index path, @@ -377,6 +499,11 @@ pub struct FakeStore { changed: Mutex>, /// Downloads stop halfway while this is true. held: (Mutex, Condvar), + /// Families made available to all apps, by name. + available: Mutex>, + craft_apps_only: AtomicBool, + /// What the next [`Installer::make_available`] refuses with. + refusal: Mutex>>, } impl FakeStore { @@ -396,6 +523,9 @@ impl FakeStore { fetched: Mutex::new(Vec::new()), changed: Mutex::new(Vec::new()), held: (Mutex::new(false), Condvar::new()), + available: Mutex::new(Vec::new()), + craft_apps_only: AtomicBool::new(false), + refusal: Mutex::new(None), } } @@ -431,6 +561,13 @@ impl FakeStore { } } + /// The next [`Installer::make_available`] is refused for `conflicts`. + pub fn refuse_next(&self, conflicts: Vec) { + if let Ok(mut refusal) = self.refusal.lock() { + *refusal = Some(conflicts); + } + } + /// Downloads report half their bytes, then wait until [`FakeStore::release`] (with /// `Runner::Thread`). pub fn hold(&self) { @@ -533,6 +670,9 @@ impl Installer for FakeStore { if let Some(outside) = request.files.iter().find(|f| !self.in_store(f)) { return Err(StoreError(format!("{} isn't in the font store", outside.display()))); } + if request.whole { + self.available.lock().map_err(err)?.retain(|f| !f.eq_ignore_ascii_case(&request.family)); + } for file in &request.files { std::fs::remove_file(file).map_err(err)?; } @@ -643,4 +783,50 @@ impl Installer for FakeStore { let bytes = self.files.get(path).ok_or_else(|| StoreError(format!("{path} isn't available")))?; Ok(Some(String::from_utf8_lossy(bytes).into_owned())) } + + fn available_to_all_supported(&self) -> bool { + true + } + + fn is_available_to_all(&self, family: &str, _files: &[PathBuf]) -> bool { + self.available.lock().is_ok_and(|a| a.iter().any(|f| f.eq_ignore_ascii_case(family))) + } + + fn craft_apps_only(&self) -> bool { + self.craft_apps_only.load(Ordering::SeqCst) + } + + fn set_craft_apps_only(&self, on: bool) -> Result)>, StoreError> { + self.craft_apps_only.store(on, Ordering::SeqCst); + if on { + self.available.lock().map_err(err)?.clear(); + return Ok(Vec::new()); + } + let mut refused = Vec::new(); + for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() { + let family = entry.file_name().to_string_lossy().into_owned(); + if let MadeAvailable::Refused(conflicts) = self.make_available(&family, &[])? { + refused.push((family, conflicts)); + } + } + Ok(refused) + } + + fn make_available(&self, family: &str, _files: &[PathBuf]) -> Result { + self.record(Call::MakeAvailable(family.to_owned())); + if let Some(conflicts) = self.refusal.lock().map_err(err)?.take() { + return Ok(MadeAvailable::Refused(conflicts)); + } + let mut available = self.available.lock().map_err(err)?; + if !available.iter().any(|f| f.eq_ignore_ascii_case(family)) { + available.push(family.to_owned()); + } + Ok(MadeAvailable::Done) + } + + fn withdraw(&self, family: &str, _files: &[PathBuf]) -> Result, StoreError> { + self.record(Call::Withdraw(family.to_owned())); + self.available.lock().map_err(err)?.retain(|f| !f.eq_ignore_ascii_case(family)); + Ok(Vec::new()) + } } diff --git a/crates/font-manager/tests/flows.rs b/crates/font-manager/tests/flows.rs index 36e2b84f96..4ec21d4396 100644 --- a/crates/font-manager/tests/flows.rs +++ b/crates/font-manager/tests/flows.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use craft_font_manager::craft_font_catalog::Os; use craft_font_manager::index::Index; use craft_font_manager::remote::{Fetch, Previews}; -use craft_font_manager::store::{Call, FakeStore, Installer}; +use craft_font_manager::store::{Call, Conflict, FakeStore, Installer}; use craft_font_manager::{Catalog, FontEnv, Source}; use craft_font_manager::{FontsPanel, Look, Options, Palette, Runner, Settings, Tab, install_interface_fonts}; use craft_font_store::{Cancel, FetchError}; @@ -186,7 +186,7 @@ fn install_a_family_then_remove_it_from_its_card() { assert_eq!(h.state().details_family().as_deref(), Some("Hack")); click(&mut h, "Install all"); click(&mut h, "Download"); - assert_eq!(store.calls(), [Call::Install("Hack".into())]); + assert_eq!(store.calls(), [Call::Install("Hack".into()), Call::MakeAvailable("Hack".into())]); assert!(h.state().downloads_allowed()); let hack = h.state().installed().iter().find(|f| f.name == "Hack").cloned().expect("Hack is listed"); assert_eq!(hack.source, Source::Store); @@ -207,7 +207,7 @@ fn install_and_remove_one_style() { allow(&mut h); click(&mut h, "Hack"); click(&mut h, "Install Regular"); - assert_eq!(store.calls(), [Call::InstallFile("Hack".into(), HACK.into())]); + assert_eq!(store.calls(), [Call::InstallFile("Hack".into(), HACK.into()), Call::MakeAvailable("Hack".into())]); assert!(has_installed(&h, "Hack")); click(&mut h, "Remove Regular"); @@ -215,6 +215,39 @@ fn install_and_remove_one_style() { assert!(!has_installed(&h, "Hack")); } +/// Clicks "Keep fonts in Craft apps only", at the end of the sidebar. +fn craft_apps_only_switch(h: &mut Harness<'_, FontsPanel>) { + h.get_by_role_and_label(Role::CheckBox, "Keep fonts in Craft apps only").scroll_to_me(); + settle(h); + click_role(h, Role::CheckBox, "Keep fonts in Craft apps only"); +} + +#[test] +fn installs_are_copied_to_the_system_fonts_folder_unless_kept_in_craft_apps() { + let (mut h, store) = setup("os-copy", Settings::default()); + allow(&mut h); + let conflict = Conflict { postscript: Some("Hack-Regular".into()), path: PathBuf::from("/fonts/Hack-Regular.ttf") }; + store.refuse_next(vec![conflict]); + click(&mut h, "Hack"); + click(&mut h, "Install all"); + assert_eq!(store.calls(), [Call::Install("Hack".into()), Call::MakeAvailable("Hack".into())]); + assert!(has_installed(&h, "Hack")); + assert!(h.query_by_label_contains("/fonts/Hack-Regular.ttf already has the font name Hack-Regular").is_some()); + + h.key_press(egui::Key::Escape); + settle(&mut h); + craft_apps_only_switch(&mut h); + assert!(store.craft_apps_only()); + click(&mut h, "Hack"); + assert!(h.query_by_label("Kept in Craft apps only").is_some()); + + h.key_press(egui::Key::Escape); + settle(&mut h); + craft_apps_only_switch(&mut h); + click(&mut h, "Hack"); + assert!(h.query_by_label("Available to all apps").is_some()); +} + #[test] fn system_fonts_cannot_be_removed() { let (mut h, store) = setup("system", Settings::default()); diff --git a/crates/font-os-windows/Cargo.toml b/crates/font-os-windows/Cargo.toml new file mode 100644 index 0000000000..9266a0151b --- /dev/null +++ b/crates/font-os-windows/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "craft-font-os-windows" +description = "The Win32 calls craft-font-store needs to make its fonts available to every app of the user on Windows: the HKCU font registry, AddFontResourceW and RemoveFontResourceW, and the WM_FONTCHANGE broadcast. Empty on other systems." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-registry = "0.6.1" +windows-sys = { version = "0.61.2", features = [ + "Win32_Foundation", + "Win32_Graphics_Gdi", + "Win32_Storage_Packaging_Appx", + "Win32_UI_WindowsAndMessaging", +] } + +# Not `workspace = true`: the workspace forbids `unsafe`, and `forbid` can't be lifted for one +# crate. Loading a font into the running session needs `AddFontResourceW`, which the Windows +# crates offer only as an unsafe call, so this crate copies the workspace lints with +# `unsafe_code = "deny"`, and allows it only on the functions that make those calls (AGENTS.md). +# Keep these tables in step with `[workspace.lints]` in the root Cargo.toml. +[lints.rust] +unsafe_code = "deny" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } + +[lints.cargo] + +[lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" +dbg_macro = "warn" +todo = "warn" diff --git a/crates/font-os-windows/src/lib.rs b/crates/font-os-windows/src/lib.rs new file mode 100644 index 0000000000..cacddf5f16 --- /dev/null +++ b/crates/font-os-windows/src/lib.rs @@ -0,0 +1,178 @@ +//! The Win32 calls craft-font-store makes to put its fonts within reach of every app of the user +//! on Windows 10 1809 and later: the per-user font registry (`HKCU\Software\Microsoft\Windows +//! NT\CurrentVersion\Fonts`), `AddFontResourceW` and `RemoveFontResourceW` for the running +//! session, and the `WM_FONTCHANGE` broadcast. +//! +//! This is the one crate in `crates/` that may use `unsafe` (AGENTS.md): the session calls exist +//! only as unsafe functions. Each one is a small function of its own with `allow(unsafe_code)`. +//! On other systems the calls report that they are unsupported, or do nothing. + +use std::io; +use std::path::{Path, PathBuf}; + +/// The per-user font key under `HKEY_CURRENT_USER`. Its values name a font (` +/// (TrueType)`) and hold the font file's full path. +pub const FONTS_KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Fonts"; + +/// Whether this process can add fonts for every app of the user: Windows 10 1809 (build 17763, +/// the first with per-user fonts) or later, and not a packaged (MSIX) app, whose registry and +/// `AppData` writes other apps don't see. +pub fn check_supported() -> Result<(), String> { + imp::check_supported() +} + +/// The path the per-user font value `name` holds, when there is one. +pub fn registered(name: &str) -> Option { + imp::registered(name) +} + +/// Lists the font at `path` as the per-user font value `name`, so Windows loads it at each +/// logon, and loads it into the running session. +pub fn register(name: &str, path: &Path) -> io::Result<()> { + imp::register(name, path) +} + +/// Unloads the font at `path` from the running session, so the file can be replaced or deleted. +/// It calls `RemoveFontResourceW` until it fails, at most 1000 times: every `AddFontResourceW` +/// counts. A program that holds the file open itself still keeps it. +pub fn unload(path: &Path) { + imp::unload(path); +} + +/// Unloads the font at `path` and deletes the per-user font value `name` while it still points +/// to `path` (in any letter case). +pub fn unregister(name: &str, path: &Path) -> io::Result<()> { + imp::unregister(name, path) +} + +/// Tells every top-level window that the fonts changed (`WM_FONTCHANGE`). It waits up to a +/// second for each window that doesn't answer, so call it off the UI thread. +pub fn broadcast_font_change() { + imp::broadcast_font_change(); +} + +#[cfg(windows)] +mod imp { + use std::io; + use std::os::windows::ffi::OsStrExt; + use std::path::{Path, PathBuf}; + + use windows_registry::{CURRENT_USER, LOCAL_MACHINE}; + use windows_sys::Win32::Foundation::APPMODEL_ERROR_NO_PACKAGE; + use windows_sys::Win32::Graphics::Gdi::{AddFontResourceW, RemoveFontResourceW}; + use windows_sys::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName; + use windows_sys::Win32::UI::WindowsAndMessaging::{HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_FONTCHANGE}; + + use super::FONTS_KEY; + + const FIRST_BUILD: u32 = 17763; + + pub fn check_supported() -> Result<(), String> { + let build = LOCAL_MACHINE + .open(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion") + .and_then(|k| k.get_string("CurrentBuildNumber")) + .ok() + .and_then(|b| b.trim().parse::().ok()); + if build.is_none_or(|b| b < FIRST_BUILD) { + return Err("adding fonts for every app needs Windows 10 version 1809 or later".into()); + } + if packaged() { + return Err("a packaged (MSIX) app can't add fonts for other apps".into()); + } + Ok(()) + } + + #[allow(unsafe_code)] + fn packaged() -> bool { + let mut len = 0u32; + // SAFETY: with a length of 0 and a null buffer the call writes only the length it would + // need to `len`, which outlives the call. + let status = unsafe { GetCurrentPackageFullName(&mut len, std::ptr::null_mut()) }; + status != APPMODEL_ERROR_NO_PACKAGE + } + + pub fn registered(name: &str) -> Option { + CURRENT_USER.open(FONTS_KEY).ok()?.get_string(name).ok().map(PathBuf::from) + } + + pub fn register(name: &str, path: &Path) -> io::Result<()> { + let data = path.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the font's path isn't valid Unicode"))?; + CURRENT_USER.create(FONTS_KEY).and_then(|k| k.set_string(name, data)).map_err(io::Error::other)?; + if add_font_resource(path) == 0 { + return Err(io::Error::other(format!("Windows didn't load {}", path.display()))); + } + Ok(()) + } + + pub fn unregister(name: &str, path: &Path) -> io::Result<()> { + unload(path); + if registered(name).is_some_and(|p| same_path(&p, path)) { + CURRENT_USER.create(FONTS_KEY).and_then(|k| k.remove_value(name)).map_err(io::Error::other)?; + } + Ok(()) + } + + /// Whether two Windows paths name the same file, ignoring letter case. + fn same_path(a: &Path, b: &Path) -> bool { + a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase() + } + + /// `path` as a NUL-terminated UTF-16 string. + fn wide(path: &Path) -> Vec { + path.as_os_str().encode_wide().chain(std::iter::once(0)).collect() + } + + #[allow(unsafe_code)] + fn add_font_resource(path: &Path) -> i32 { + let wide = wide(path); + // SAFETY: `wide` is a NUL-terminated UTF-16 string that outlives the call, which only + // reads it. + unsafe { AddFontResourceW(wide.as_ptr()) } + } + + #[allow(unsafe_code)] + pub fn unload(path: &Path) { + let wide = wide(path); + for _ in 0..1000 { + // SAFETY: `wide` is a NUL-terminated UTF-16 string that outlives the call, which only + // reads it. + if unsafe { RemoveFontResourceW(wide.as_ptr()) } == 0 { + break; + } + } + } + + #[allow(unsafe_code)] + pub fn broadcast_font_change() { + let mut result = 0usize; + // SAFETY: `WM_FONTCHANGE` carries no pointers (both parameters are 0), and `result` + // outlives the call, which only writes it. + unsafe { SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0, SMTO_ABORTIFHUNG, 1000, &mut result) }; + } +} + +#[cfg(not(windows))] +mod imp { + use std::io; + use std::path::{Path, PathBuf}; + + pub fn check_supported() -> Result<(), String> { + Err("the Windows font registry exists only on Windows".into()) + } + + pub fn registered(_name: &str) -> Option { + None + } + + pub fn register(_name: &str, _path: &Path) -> io::Result<()> { + Err(io::ErrorKind::Unsupported.into()) + } + + pub fn unload(_path: &Path) {} + + pub fn unregister(_name: &str, _path: &Path) -> io::Result<()> { + Err(io::ErrorKind::Unsupported.into()) + } + + pub fn broadcast_font_change() {} +} diff --git a/crates/font-store/Cargo.toml b/crates/font-store/Cargo.toml index d840ff48e3..406212347e 100644 --- a/crates/font-store/Cargo.toml +++ b/crates/font-store/Cargo.toml @@ -26,6 +26,8 @@ thiserror = { workspace = true } cap-primitives = "4.0.3" craft-atomic = { workspace = true } craft-font-catalog = { workspace = true } +# The Windows font registry and session calls; empty elsewhere. +craft-font-os-windows = { workspace = true } log = "0.4" # Language packs (`language_packs`): `.tar.zst` archives, unpacked in pure Rust. ruzstd = { version = "0.9", default-features = false, features = ["std"] } diff --git a/crates/font-store/README.md b/crates/font-store/README.md index c0e4aed347..84bfb349af 100644 --- a/crates/font-store/README.md +++ b/crates/font-store/README.md @@ -1,6 +1,6 @@ # craft-font-store -The suite's font store: the font indexes of every source, exact lookup of a missing font, and verified installs into the one folder every app's font catalog reads ([`craft-font-catalog`](../font-catalog/README.md)'s `font_store_dir`). +The suite's font store: the font indexes of every source, exact lookup of a missing font, verified installs into the one folder every app's font catalog reads ([`craft-font-catalog`](../font-catalog/README.md)'s `font_store_dir`), and, per family at the user's request, copies in the OS user font folder so that every other program can use it. The indexes are [aiongg/craft-font-index](https://github.com/aiongg/craft-font-index) (format 1.x), designed by @kntrttm for photocraft#1135 and #2453. Every font file and licence in an index has a size and a sha256, and only families under a licence that allows redistribution (OFL, Apache 2.0, Ubuntu Font Licence) are listed. @@ -30,6 +30,7 @@ A source the user adds is an index file at an https URL (`.json` or `.json.gz`). | No requests at startup | Nothing in the crate makes a request on its own. Only `fetch_indexes` and the installs do, and they return `Error::NetworkOff` without one while the network is off. | | Optional preview service | Off unless set: craft-libs has no default address. `CRAFT_FONT_PREVIEW_URL`, else the `preview_service` field of `settings.json` (`FontStore::set_preview_service`, user only, `Error::NotAllowed` for an agent), else the host's default (`FontStore::with_default_preview_service`), which is never saved, so clearing the setting brings it back and other apps sharing the store don't see it. `FontStore::preview_service()` returns the one in effect and `preview_service_source()` says whether it is `Env`, `Saved`, `Default` or `None`; the variable's name is `PREVIEW_SERVICE_ENV`. A `settings.json` that exists but can't be read or parsed means no saved service and no host default. Installs and `legal_text` try the service's mirror only for curated families (the built-in sources, `Family::is_curated`), so the hashes of files from sources the user added are never sent to it. https only; http is accepted only for the addresses `127.0.0.1` and `::1`, never for a host name, which a resolver can point off the machine. A trailing slash is dropped. Example: `CRAFT_FONT_PREVIEW_URL=https://fonts.example.com`. | | Previews setting | `previews` in `settings.json`, on by default: `FontStore::previews_enabled()`, `set_previews_enabled(bool)` (user only, `Error::NotAllowed` for an agent). The app fetches previews from a set service only while it is on; installs ignore it. | +| Craft apps only setting | `craft_apps_only` in `settings.json`, off by default: `FontStore::craft_apps_only()`, `set_craft_apps_only(bool)` (user only, `Error::NotAllowed` for an agent). While it is off, craft-font-manager copies each family it installs into the OS user font folder; the setting only records the choice, and the caller copies or withdraws the families. | | Mirror first | With a service set, an install requests `/v1/files/` for each font file and `/v1/licences/` for a licence (when the index gives its sha256) before the index's URLs. The size and sha256 checks are the same, and a response that fails them moves on to the next URL. | | One HTTP client | `Client`: ureq with rustls and the webpki roots, HTTPS only (plain http only to `127.0.0.1` or `::1`, following no redirects, for a preview service run locally), no cookies, `User-Agent: craft-font-store/`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. | @@ -99,6 +100,7 @@ When every file has passed, the store takes `.lock`, moves the files into the fa ```text settings.json the network setting and the sources the user added manifest.json what is installed +os-fonts.json the ledger of copies in the OS user font folder indexes/ the last indexes fetched: sources.json, .json.gz, user- previews/ preview subsets (WOFF2) craft-font-manager caches, at most 50 MB / the font files and the licence @@ -115,7 +117,7 @@ A Google Fonts family's folder is google/fonts' own folder name (`lato/`); anoth | Call | What it does | |---|---| | `installed()`, `installed_family(source, name)`, `is_installed(family, file)` | Read the manifest. | -| `remove_family(source, name)` | Moves the family folder out at once, updates the manifest, then deletes the files and the licence. | +| `remove_family(source, name)` | Withdraws the family's copies from the OS user font folder (user only when it has some), moves the family folder out at once, updates the manifest, then deletes the files and the licence. `remove_files` withdraws the copies of the files it removes. | | `verify()` | Reads every installed file and reports the missing, damaged and unparseable ones. | | `user_sources()`, `add_user_source(url)`, `remove_user_source(url)` | The sources the user added. Removing one leaves its installed families installed. | @@ -169,6 +171,76 @@ Windows retains ancestor handles that prevent their replacement during cleanup. **Developer override (testing only — bypasses the pin):** `CRAFT_LANGUAGE_PACK_INDEX=` replaces the pinned index URL with an `http://` URL on a loopback host (`127.0.0.1`, `localhost`, `[::1]`), an `https://` URL or a local file path (`file://` URLs are not taken), and **skips the index's sha256 pin**. Archives are still checked against the sha256 and size in that index, and may then also be loopback `http://` URLs or local paths. Off unless the variable is set; it works in release builds too (for end-to-end tests of a real build), a warning is logged whenever it is used, and `language_pack_index_overridden() -> Option` returns the value so apps can show that the pin is bypassed. Never set it for users. +## Copies in the OS font folder + +Fonts in the store are for the Craft apps only. A family can also be copied into the OS user font folder, for every other program of the current user (the API calls this making it available to all apps). The calls below work per family; whether an app copies every family the user installs or lets the user choose per family is the app's decision. Only the user's store (`for_user`) changes the OS folder. + +| Call | What it does | +|---|---| +| `available_to_all_supported()`, `available_to_all_unsupported()` | Whether the action works here, and why not. The interface hides it when it doesn't. | +| `make_available(source, name)` | Checks for conflicts, copies the family's font files into the OS user font folder and records them in the ledger. Calling it again copies styles installed since and brings the copies up to date. Returns the copies. | +| `withdraw(source, name)` | Deletes the copies the ledger lists, each only if its sha256 is unchanged. Returns the copies left in place because they changed. | +| `is_available(source, name)`, `available_family_holding(name, files)`, `available_files(source, name)` | Read the ledger. They read the file again only when it changed, so a list can ask for every row. `available_family_holding` goes by the store files when it has them, so a family of the same name from another source doesn't count. | +| `copies_out_of_reach(source, name)` | The family's listed copies when this build can't change the OS folder (a Flatpak whose access to it was revoked). Removing the family leaves them. | +| `pending_files(source, name)` | Files of an available family not available yet: styles installed since by an agent, or whose copy is older than the store's file. | + +`make_available`, `withdraw`, the installs and removals block (hashing, copying, a catalog rescan): call them off the UI thread. + +### Who may change the OS folder + +Only the user. An agent (`for_agent`) never changes what is in the OS font folder: + +- `make_available` and `withdraw` give it `Error::NotAllowed`. +- Its install into an available family stays in the store; the new files show in `pending_files`, and the interface offers to copy them. The user's install copies them at once. +- Its `remove_family` of a family with copies, and its `remove_files` of files with copies, give `Error::NotAllowed` before anything changes. + +The user's `remove_family` and `remove_files` withdraw the copies first, so the ledger never lists copies of fonts the store no longer has. Where this build can't change the OS folder (a Flatpak whose `xdg-data/fonts` access was revoked, a Snap build) but the ledger lists copies, removing the family removes its store files and leaves the copies, still listed in the ledger: a build that has the folder withdraws them, and a reinstall finds them the store's. `copies_out_of_reach` names them beforehand. + +### Folders + +| System | Folder (`OsFontFolder::for_env`) | Copies | +|---|---|---| +| macOS | `~/Library/Fonts` | `Craft--`, side by side. macOS activates them for every app of the user. | +| Linux and the BSDs | `$XDG_DATA_HOME/fonts/Craft` (`~/.local/share/fonts/Craft`) | `/`. fontconfig reads the folder with its subfolders; `fc-cache` refreshes the cache afterwards when it is on `PATH`, off the calling thread. | +| Flatpak | the host's `$HOST_XDG_DATA_HOME/fonts/Craft`, else `~/.local/share/fonts/Craft` | Only when `/.flatpak-info` grants write access to that folder (`--filesystem=xdg-data/fonts:create`; its entries apply in order, `!name` revokes and `:ro` grants no write). No `fc-cache`: it would refresh the sandbox's cache. | +| Windows 10 1809 and later | `%LOCALAPPDATA%\Microsoft\Windows\Fonts\Craft` | `/`, each listed as ` (TrueType)` (or `(OpenType)` for CFF outlines) under `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Fonts`, loaded into the running session with `AddFontResourceW`, then `WM_FONTCHANGE` is broadcast off the calling thread. A registry value that already names another file is a conflict. Withdrawing unloads the font, deletes the value, then deletes the file; a file another program still holds can't be deleted, so the withdrawal fails and the ledger keeps the copy for the next try. The Win32 calls are in `craft-font-os-windows`. | +| Snap, a sandboxed macOS build (Mac App Store), a packaged (MSIX) Windows build, older Windows, Haiku, the web | none | `Error::Unsupported`. | + +`FontStore::new` has no folder; `with_os_fonts(OsFontFolder::at(dir, layout))` sets one, for tests and setups the rules above don't cover. + +Only font files are copied. Licences stay in the store, which remains the record: copying a font into the same user's font folder isn't redistribution under the OFL, the Apache 2.0 licence or the UFL, and macOS doesn't expect text files in `~/Library/Fonts`. + +Running apps see a new font at once or only after a restart, depending on the app (GTK under GNOME and Firefox at once, Chromium, Electron and Qt apps after a restart), so the interface tells the user that open apps may need a restart. + +### Conflicts + +`make_available` reads the catalog given to `with_catalog` (rescanned first if the font folders changed), else a fresh catalog of the process's environment, with the store locked. It refuses with `Error::Conflict`, changing nothing and naming each file with the PostScript name it has (`None` for a file in the way), when: + +- a system font has a PostScript name of one of the family's faces or named instances (ignoring ASCII case). Names come from a catalog scan of each store file and from the index. fontconfig would otherwise pick the newer version system-wide, and macOS can't activate two fonts of one PostScript name; +- another store family's copy has one of those names (Roboto from Google Fonts and from a user's source, say); +- a file the store didn't add, another family's copy or a symbolic link sits where a copy would go. + +The store's own copies are told apart by file identity (device and inode on Unix), so a copy the catalog reaches by another path (Flatpak shows the user's fonts again at `/run/host/user-fonts`) is still the store's. A system file identical to the store's (same sha256) is no conflict: the file isn't copied, and the ledger notes it as `present`, never to be deleted. A file at a copy's own place with the store's sha256 is taken into the ledger as a copy. Fonts of the same family name with other PostScript names (soft conflicts) are not checked yet. + +### The ledger + +`os-fonts.json` (version 1) lists, per family (name, source and store folder), every file: its store file name, its path, the store file's sha256, its PostScript names, how it is there (`copy`, or `present` for a system file) and its state (`adding` or `active`). + +The store deletes a file only when the ledger lists it as a copy, at the very path the store puts that file (`path_for` of the family's folder and file name), with no symbolic link on the way, and with the sha256 the ledger gives. Any other listed path is left alone and reported. A ledger that can't be read or understood (damaged, an unknown value, another version) is kept as it is: queries treat the family as not available, and everything that would change the ledger, removals of the family from the store included, gives `Error::Ledger`. + +A crash leaves nothing the store loses track of: + +- A copy is listed as `adding` before it is made, written to `.craft-.part` (a dot-file, which fontconfig and macOS skip), checked against its sha256, and renamed into place; then the ledger lists it as `active`. +- The next change settles every `adding` entry: the temporary file goes, a file with the new sha256 (or, while replacing a copy, the old one) stays listed as `active`, and any other is dropped from the ledger and left alone. +- A copy being deleted is renamed to `.craft-.removing`, checked there and then deleted, or renamed back if it changed. One a crash leaves aside goes back at the next change. +- A withdrawal deletes the files first and rewrites the ledger after, so a crash in between leaves entries whose files are gone, which the next withdrawal drops. + +### Limits + +- The copies stay when the suite is uninstalled, unless the user withdraws them first. +- The catalog lists a copy as a system face beside the store's face. Both have the same family, style and PostScript name, so `Catalog::faces` keeps one: the store's, wherever the folders sort. +- Copies take disk space beside the store's files; there are no hard links, so a font editor saving over a copy can't change the store's file. + ## Web The index, the lookups, `verify_font` and `IndexPin` build for `wasm32-unknown-unknown`. The store folder and the HTTP client are native only; the web keeps fonts elsewhere. diff --git a/crates/font-store/src/lib.rs b/crates/font-store/src/lib.rs index 7a2697d24f..2969553b2c 100644 --- a/crates/font-store/src/lib.rs +++ b/crates/font-store/src/lib.rs @@ -1,8 +1,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] //! The suite's font store: the font indexes of every source (Google Fonts, Noto, indexes the user -//! adds), exact lookup of a missing font, and verified installs into the one folder every app's -//! font catalog reads. +//! adds), exact lookup of a missing font, verified installs into the one folder every app's font +//! catalog reads, and, per family at the user's request, copies in the OS user font folder for +//! every other program ([`FontStore::make_available`]). //! //! ```no_run //! # #[cfg(not(target_arch = "wasm32"))] { @@ -52,8 +53,8 @@ pub use language_packs::{ }; #[cfg(not(target_arch = "wasm32"))] pub use store::{ - Caller, Error, FontStore, InstalledFamily, InstalledFile, LegalText, Network, PREVIEW_SERVICE_ENV, PreviewServiceSource, Problem, Progress, - UserSource, check_preview_service, + Caller, Conflict, Error, FontStore, InstalledFamily, InstalledFile, LegalText, Network, OsFontFolder, OsFontLayout, PREVIEW_SERVICE_ENV, + PreviewServiceSource, Problem, Progress, UserSource, check_preview_service, }; #[cfg(test)] diff --git a/crates/font-store/src/store.rs b/crates/font-store/src/store.rs index b421f16d4c..fb383a2fd0 100644 --- a/crates/font-store/src/store.rs +++ b/crates/font-store/src/store.rs @@ -3,8 +3,9 @@ //! Layout of the folder ([`craft_font_catalog::font_store_dir`]): //! //! ```text -//! settings.json the consent setting and the sources the user added +//! settings.json the consent setting, the sources the user added and the other settings //! manifest.json what is installed +//! os-fonts.json the ledger of copies in the OS user font folder //! indexes/ the last indexes fetched: sources.json, one file per source //! previews/ preview subsets from the preview service (WOFF2), a cache of at most 50 MB //! / google/fonts' folder name, or /: the fonts and the licence @@ -33,6 +34,10 @@ use crate::source::{is_source_url, safe_dir, safe_file_name, slug}; use crate::sources::{MAX_SOURCES_BYTES, SourceEntry, SourcesFile}; use crate::verify::{VerifyError, is_font, sha256_hex, verify_font}; +mod os_fonts; + +pub use os_fonts::{Conflict, OsFontFolder, OsFontLayout}; + const SETTINGS: &str = "settings.json"; const MANIFEST: &str = "manifest.json"; pub(crate) const INDEX_CACHE: &str = "indexes"; @@ -73,8 +78,9 @@ pub enum Error { /// Downloading is off; the user turns it on in the app. #[error("downloading fonts is turned off")] NetworkOff, - /// An agent tried to turn the network on. - #[error("only the user can turn on downloading fonts")] + /// An agent tried what only the user may do: turn the network on, change a setting, or add + /// or remove a family's copies in the OS user font folder. + #[error("only the user can do this, in the app")] NotAllowed, /// Not an https URL a source can be added from. #[error("{0} is not an https URL")] @@ -110,6 +116,21 @@ pub enum Error { /// The operation was cancelled. #[error("cancelled")] Cancelled, + /// Families can't be copied into the OS user font folder here; the reason says why. + #[error("{0}")] + Unsupported(String), + /// Fonts the store didn't add already have the family's PostScript names, or sit where its + /// copies would go. + #[error("the family can't be copied into your fonts folder: {}", .0.iter().map(|c| match &c.postscript { + Some(ps) => format!("{} already has the name {ps}", c.path.display()), + None => format!("{} is in the way", c.path.display()), + }).collect::>().join("; "))] + Conflict(Vec), + /// The ledger of copies in the OS user font folder (`os-fonts.json`) can't be read or + /// understood (damaged, or from a newer version). It is kept as it is, and nothing that would + /// change it runs. + #[error("the record of fonts copied into your fonts folder (os-fonts.json in the font store) can't be used: {0}")] + Ledger(String), /// Reading or writing the store failed. #[error("{what}: {source}")] Io { @@ -209,6 +230,10 @@ struct Settings { preview_service: Option, #[serde(default = "on")] previews: bool, + /// The user keeps store fonts in Craft apps only: the font manager doesn't copy families + /// into the OS user font folder. + #[serde(default)] + craft_apps_only: bool, /// The file exists but couldn't be read or parsed. #[serde(skip)] unreadable: bool, @@ -220,7 +245,7 @@ fn on() -> bool { impl Default for Settings { fn default() -> Self { - Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, unreadable: false } + Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, craft_apps_only: false, unreadable: false } } } @@ -278,6 +303,9 @@ pub struct FontStore { default_preview_service: Option, /// The host's network setting, used while the user hasn't chosen. Never saved. default_network: Option, + /// The OS user font folder, or why there is none. + os_fonts: Result, + ledger_cache: os_fonts::LedgerCache, /// Tests: stands in for the environment variable. #[cfg(test)] preview_env: Option>, @@ -293,15 +321,19 @@ impl FontStore { /// The store for the app's own interface, in the folder every app reads. /// `None` where there is no per-user folder. pub fn for_user(env: &FontEnv) -> Option { - Some(Self::new(font_store_dir(env)?, Caller::User)) + let mut store = Self::new(font_store_dir(env)?, Caller::User); + store.set_os_fonts(OsFontFolder::for_env(env)); + Some(store) } /// The store for an agent (MCP, CLI): it can never turn the network on. pub fn for_agent(env: &FontEnv) -> Option { - Some(Self::new(font_store_dir(env)?, Caller::Agent)) + let mut store = Self::new(font_store_dir(env)?, Caller::Agent); + store.set_os_fonts(OsFontFolder::for_env(env)); + Some(store) } - /// A store in `dir`. + /// A store in `dir`, with no OS user font folder ([`FontStore::with_os_fonts`] sets one). pub fn new(dir: PathBuf, caller: Caller) -> Self { Self { dir, @@ -312,6 +344,8 @@ impl FontStore { pack_removal_round_end: AtomicUsize::new(0), default_preview_service: None, default_network: None, + os_fonts: Err("no user font folder was given".into()), + ledger_cache: os_fonts::LedgerCache::default(), #[cfg(test)] preview_env: None, } @@ -472,6 +506,22 @@ impl FontStore { self.change_settings(|s| s.previews = enabled) } + /// Whether the user keeps store fonts in Craft apps only. Off by default: the font manager + /// then copies each family it installs into the OS user font folder + /// ([`FontStore::make_available`]), so other apps can use it. + pub fn craft_apps_only(&self) -> bool { + self.settings().craft_apps_only + } + + /// Sets [`FontStore::craft_apps_only`], from the user's own action. It only records the choice: + /// the caller copies or withdraws the families. [`Error::NotAllowed`] for an agent. + pub fn set_craft_apps_only(&self, on: bool) -> Result<(), Error> { + if self.caller != Caller::User { + return Err(Error::NotAllowed); + } + self.change_settings(|s| s.craft_apps_only = on) + } + fn change_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), Error> { let _lock = self.lock()?; let mut settings = self.settings(); @@ -641,7 +691,8 @@ impl FontStore { // ----- install /// Installs every file of `family`. Files already installed with the same sha256 aren't - /// downloaded again. + /// downloaded again. When the family has copies in the OS user font folder, the user's install + /// also copies the new files there; an agent's leaves them in [`FontStore::pending_files`]. pub fn install_family( &self, index: &Index, @@ -673,6 +724,7 @@ impl FontStore { let wanted: Vec<&FontFile> = files.iter().copied().filter(|f| !have(f) || !folder.join(f.file_name()).is_file()).collect(); let license_missing = family.license_file_name().is_some_and(|name| !folder.join(name).is_file()); if wanted.is_empty() && !license_missing { + self.reshare(&family.source, &family.family); return installed.ok_or_else(|| Error::NotInstalled(family.family.clone())); } self.require_network()?; @@ -727,6 +779,9 @@ impl FontStore { }; drop(stage); self.rescan(); + if result.is_ok() { + self.reshare(&family.source, &family.family); + } result } @@ -824,13 +879,17 @@ impl FontStore { .is_some_and(|i| i.files.iter().any(|x| x.name == file.file_name() && x.sha256 == file.sha256)) } - /// Removes the family of this name installed from `source`: its files, its licence and its - /// manifest entry. Its folder disappears at once and is deleted after. + /// Removes the family of this name installed from `source`: its copies in the OS user font + /// folder (as [`FontStore::withdraw`]), its files, its licence and its manifest entry. Its + /// folder disappears at once and is deleted after. A family with copies in the OS folder is + /// the user's to remove: an agent gets [`Error::NotAllowed`] and nothing changes. Copies this + /// build can't reach ([`FontStore::copies_out_of_reach`]) stay, listed in the ledger. pub fn remove_family(&self, source: &str, name: &str) -> Result<(), Error> { let result = { let _lock = self.lock()?; let mut manifest = self.read_manifest(); let pos = manifest.families.iter().position(|f| f.is(source, name)).ok_or_else(|| Error::NotInstalled(name.to_string()))?; + self.withdraw_for_removal(source, name, None)?; let entry = manifest.families.remove(pos); let folder = self.dir.join(&entry.dir); let stage = Stage::new(&self.dir)?; @@ -853,9 +912,11 @@ impl FontStore { result } - /// Removes some files of an installed family (one style, say), by their names in its folder. - /// Taking out the last one removes the family. Names the family's manifest entry doesn't list - /// are left alone. + /// Removes some files of an installed family (one style, say), by their names in its folder, + /// with their copies in the OS user font folder. Taking out the last one removes the family. + /// Names the family's manifest entry doesn't list are left alone. Files with copies in the OS + /// folder are the user's to remove: an agent gets [`Error::NotAllowed`] and nothing changes. + /// Copies this build can't reach stay, as for [`FontStore::remove_family`]. pub fn remove_files(&self, source: &str, name: &str, files: &[String]) -> Result<(), Error> { let result = { let _lock = self.lock()?; @@ -867,6 +928,7 @@ impl FontStore { if removing.is_empty() { return Ok(()); } + self.withdraw_for_removal(source, name, Some(removing.as_slice()))?; entry.files.retain(|f| !removing.contains(&f.name)); let folder = self.dir.join(&entry.dir); let stage = Stage::new(&self.dir)?; diff --git a/crates/font-store/src/store/os_fonts.rs b/crates/font-store/src/store/os_fonts.rs new file mode 100644 index 0000000000..304ada3a15 --- /dev/null +++ b/crates/font-store/src/store/os_fonts.rs @@ -0,0 +1,969 @@ +//! Copies of a store family in the OS user font folder, for every app of the user, recorded in a +//! ledger (`os-fonts.json`) so that withdrawing one removes exactly what the store added. +//! +//! Crash safety: the ledger lists a copy as `adding` before it is made, and as `active` once it +//! is in place. Copies go to a dot-file (`.craft-.part`, which neither fontconfig nor macOS +//! reads) and are renamed into place. The next call that changes the ledger settles every +//! `adding` entry: the temporary file goes; a file that has the new sha256 (or, for a +//! replacement, the old one) stays listed as `active`; any other is dropped from the ledger and +//! left alone. A copy being deleted is first renamed to `.craft-.removing` and checked +//! there, so a file changed at the last moment goes back; one a crash leaves there goes back at +//! the next change. A withdrawal deletes files first and rewrites the ledger after, so a crash in +//! between leaves entries whose files are gone, which the next withdrawal drops. +//! +//! On Windows each copy is also a per-user font value in the registry, which the ledger names +//! (listed before the copy is made, like the copy), loaded into the running session with +//! `AddFontResourceW`. Windows keeps a loaded font's file from being replaced or deleted, so a +//! copy is unloaded before either, and its value deleted before it is deleted. A copy that is +//! still in use elsewhere can't be deleted: the withdrawal fails with that error and the ledger +//! keeps the copy, so the next withdrawal tries again. +//! +//! Everything here blocks (hashing, copying, a catalog rescan): call it off the UI thread. + +use std::collections::{HashMap, HashSet}; +use std::ffi::OsString; +use std::fs::File; +use std::path::{Component, Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::SystemTime; + +use craft_font_catalog::{Catalog, FaceInfo, FontEnv, Os, Source, read_faces}; +use serde::{Deserialize, Serialize}; + +use super::{Caller, Error, FontStore, InstalledFamily, io}; +use crate::source::{safe_dir, safe_file_name}; +use crate::verify::VerifyError; + +const LEDGER: &str = "os-fonts.json"; +const LEDGER_VERSION: u32 = 1; +const MAX_LEDGER_BYTES: u64 = 16 << 20; + +/// How the OS user font folder is laid out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OsFontLayout { + /// One folder of files, each named `Craft--`: `~/Library/Fonts`. + Flat, + /// A folder per family, `//`: `~/.local/share/fonts/Craft`, + /// which fontconfig reads with its subfolders. + Folders, +} + +/// The OS user font folder the store copies families into, for every app of the user. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OsFontFolder { + dir: PathBuf, + layout: OsFontLayout, + fc_cache: bool, + /// Windows: each copy is a per-user font value in the registry and loaded into the session. + registry: bool, +} + +impl OsFontFolder { + /// The current user's font folder on the system `env` describes, or why the store can't add + /// fonts to it: + /// + /// - macOS: `~/Library/Fonts`. Not in a sandboxed build (`APP_SANDBOX_CONTAINER_ID` is set), + /// such as the Mac App Store's. + /// - Linux and the BSDs: `$XDG_DATA_HOME/fonts/Craft` (`~/.local/share/fonts/Craft`), and + /// `fc-cache` refreshes the user's font cache after each change when it is on `PATH`. In a + /// Flatpak, the host's folder (`$HOST_XDG_DATA_HOME`, else `~/.local/share`), only when + /// `/.flatpak-info` grants write access to it (`--filesystem=xdg-data/fonts:create`), and + /// without `fc-cache`. Not in a Snap (`SNAP` is set). + /// - Windows 10 1809 and later: `%LOCALAPPDATA%\Microsoft\Windows\Fonts\Craft`, each copy + /// listed under `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Fonts` and loaded into + /// the running session. Not in a packaged (MSIX) build. + /// - Haiku and the web: not offered. + pub fn for_env(env: &FontEnv) -> Result { + let folder = Self::for_env_with(env, &|k| std::env::var_os(k).filter(|v| !v.is_empty()))?; + if folder.registry { + craft_font_os_windows::check_supported()?; + } + Ok(folder) + } + + /// [`OsFontFolder::for_env`], reading the variables `FontEnv` doesn't hold through `var`. + pub(crate) fn for_env_with(env: &FontEnv, var: &dyn Fn(&str) -> Option) -> Result { + const NO_HOME: &str = "there is no home folder"; + match env.os { + Os::MacOs => { + if var("APP_SANDBOX_CONTAINER_ID").is_some() { + return Err("a sandboxed app (such as the Mac App Store build) can't add fonts to ~/Library/Fonts".into()); + } + let home = env.home.as_ref().ok_or(NO_HOME)?; + Ok(Self { dir: home.join("Library/Fonts"), layout: OsFontLayout::Flat, fc_cache: false, registry: false }) + } + Os::Unix => { + if var("SNAP").is_some() { + return Err("the Snap build can't write the user font folder".into()); + } + let absolute = |p: &PathBuf| p.is_absolute(); + let local_share = env.home.as_ref().map(|h| h.join(".local/share")); + let (data, fc_cache) = if env.flatpak { + let data = var("HOST_XDG_DATA_HOME").map(PathBuf::from).filter(absolute).or(local_share).ok_or(NO_HOME)?; + if !flatpak_can_write(&env.root.join(".flatpak-info"), env.home.as_deref(), &data) { + return Err("the Flatpak has no write access to the user font folder (--filesystem=xdg-data/fonts:create)".into()); + } + (data, false) + } else { + (env.xdg_data_home.clone().filter(absolute).or(local_share).ok_or(NO_HOME)?, true) + }; + Ok(Self { dir: data.join("fonts/Craft"), layout: OsFontLayout::Folders, fc_cache, registry: false }) + } + Os::Windows => { + let local = env + .local_app_data + .clone() + .or_else(|| env.home.as_ref().map(|h| h.join("AppData").join("Local"))) + .filter(|p| p.is_absolute()) + .ok_or("there is no local app data folder")?; + let dir = local.join("Microsoft").join("Windows").join("Fonts").join("Craft"); + Ok(Self { dir, layout: OsFontLayout::Folders, fc_cache: false, registry: true }) + } + Os::Haiku | Os::None => Err("this system has no user font folder the store can add to".into()), + } + } + + /// A folder of `layout` at `dir`, with no font cache refresh: tests, and setups the platform + /// rules don't cover. + pub fn at(dir: impl Into, layout: OsFontLayout) -> Self { + Self { dir: dir.into(), layout, fc_cache: false, registry: false } + } + + /// The folder. + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Where the copy of `file` of the store family in folder `family_dir` goes. + fn path_for(&self, family_dir: &str, file: &str) -> PathBuf { + match self.layout { + OsFontLayout::Flat => self.dir.join(format!("Craft-{family_dir}-{file}")), + OsFontLayout::Folders => self.dir.join(family_dir).join(file), + } + } + + /// Whether `path` is inside the folder and no folder on the way, nor `path` itself, is a + /// symbolic link (a dangling one included), so that writes and deletes stay inside. With the + /// `Folders` layout the store's own `Craft` folder counts too. + fn no_links(&self, path: &Path) -> bool { + let Ok(rest) = path.strip_prefix(&self.dir) else { return false }; + if rest.components().count() == 0 || !rest.components().all(|c| matches!(c, Component::Normal(_))) { + return false; + } + let mut at = self.dir.clone(); + let mut check = Vec::new(); + if self.layout == OsFontLayout::Folders { + check.push(at.clone()); + } + for c in rest.components() { + at.push(c); + check.push(at.clone()); + } + check.iter().all(|p| std::fs::symlink_metadata(p).map_or(true, |m| !m.file_type().is_symlink())) + } + + /// Whether the ledger's `file` of the family in store folder `dir` is a copy the store may + /// touch: where the store puts it, with no link on the way. + fn owns(&self, dir: &str, file: &LedgerFile) -> bool { + file.mechanism == Mechanism::Copy + && safe_dir(dir) + && safe_file_name(&file.store_file) + && file.path == self.path_for(dir, &file.store_file) + && self.no_links(&file.path) + } + + /// The registry value name of the store file `file` with these faces, on Windows: + /// ` (TrueType)`, or `(OpenType)` for CFF outlines. + fn registry_name(&self, path: &Path, file: &str, faces: &[FaceInfo]) -> Option { + if !self.registry { + return None; + } + let mut names: Vec<&str> = faces.iter().filter_map(|f| f.full_name.as_deref()).collect(); + names.dedup(); + let stem = Path::new(file).file_stem().map_or(file.into(), |s| s.to_string_lossy()); + let name = if names.is_empty() { stem.into_owned() } else { names.join(" & ") }; + let mut magic = [0u8; 4]; + let cff = File::open(path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut magic)).is_ok() && &magic == b"OTTO"; + Some(format!("{name} ({})", if cff { "OpenType" } else { "TrueType" })) + } + + /// Registry values of `planned` that already hold another font: conflicts. + fn registry_conflicts(&self, planned: &[Planned]) -> Vec { + planned + .iter() + .filter_map(|p| { + let held = craft_font_os_windows::registered(p.registry.as_deref()?)?; + let same = held.to_string_lossy().to_lowercase() == p.path.to_string_lossy().to_lowercase(); + (!same).then_some(Conflict { postscript: None, path: held }) + }) + .collect() + } + + /// Lists a copy in the registry and loads it into the session, where the OS needs that. + fn register(&self, f: &LedgerFile) -> Result<(), Error> { + match &f.registry { + Some(name) => craft_font_os_windows::register(name, &f.path).map_err(io(format!("registering {} with Windows", f.path.display()))), + None => Ok(()), + } + } + + /// Undoes [`OsFontFolder::register`] for a copy about to be deleted. + fn unregister(&self, f: &LedgerFile) -> Result<(), Error> { + match &f.registry { + Some(name) => craft_font_os_windows::unregister(name, &f.path).map_err(io(format!("unregistering {} from Windows", f.path.display()))), + None => Ok(()), + } + } + + /// Unloads the file at `path` from the session before it is replaced, where the OS locks it. + fn unload(&self, path: &Path) { + if self.registry && path.exists() { + craft_font_os_windows::unload(path); + } + } + + /// Tells fontconfig, or the windows of a Windows session, off the calling thread. It isn't + /// needed for correctness: fontconfig notices changed folders by their mtime. + fn refresh(&self) { + if self.registry { + let _ = std::thread::Builder::new().name("font-change".into()).spawn(craft_font_os_windows::broadcast_font_change); + } + if !self.fc_cache { + return; + } + let fonts = self.dir.parent().unwrap_or(&self.dir).to_path_buf(); + let _ = std::thread::Builder::new().name("fc-cache".into()).spawn(move || { + let _ = std::process::Command::new("fc-cache") + .arg(fonts) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); + }); + } +} + +/// Whether `/.flatpak-info` grants write access to `/fonts`. Its `filesystems=` entries +/// apply in order: `!name` revokes an earlier grant of `name`, and `:ro` grants no write. +fn flatpak_can_write(info: &Path, home: Option<&Path>, data: &Path) -> bool { + let Some(bytes) = std::fs::metadata(info).ok().filter(|m| m.len() <= 1 << 20).and_then(|_| std::fs::read(info).ok()) else { return false }; + let text = String::from_utf8_lossy(&bytes); + let fonts = data.join("fonts"); + let mut grants: Vec<(String, bool)> = Vec::new(); + for entry in text.lines().filter_map(|l| l.trim().strip_prefix("filesystems=")).flat_map(|l| l.split(';')) { + let entry = entry.trim(); + let (revoke, entry) = match entry.strip_prefix('!') { + Some(e) => (true, e), + None => (false, entry), + }; + let (name, mode) = entry.rsplit_once(':').unwrap_or((entry, "rw")); + let name = name.trim_end_matches('/').to_string(); + grants.retain(|(n, _)| *n != name); + if !revoke && !name.is_empty() { + grants.push((name, mode != "ro")); + } + } + let covers = |name: &str| -> bool { + let base = match name { + "host" => Some(PathBuf::from("/")), + "home" => home.map(Path::to_path_buf), + "xdg-data" => Some(data.to_path_buf()), + _ => match (name.strip_prefix("xdg-data/"), name.strip_prefix("~/")) { + (Some(sub), _) => Some(data.join(sub)), + (None, Some(sub)) => home.map(|h| h.join(sub)), + _ => Some(PathBuf::from(name)).filter(|p| p.is_absolute()), + }, + }; + base.is_some_and(|b| fonts.starts_with(b)) + }; + grants.iter().any(|(name, write)| *write && covers(name)) +} + +/// What stops a family being copied into the OS user font folder: a font that already has one +/// of its PostScript names, or a file in the way of a copy. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Conflict { + /// The PostScript name `path` has too; `None` for a file the store didn't add (another + /// family's copy, a link) sitting where a copy would go. + pub postscript: Option, + /// A system font or another store family's copy with the name, or the file in the way. + pub path: PathBuf, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum State { + /// Listed before the copy; settled by the next change. + Adding, + Active, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum Mechanism { + /// The store copied the file to `path`. + Copy, + /// The system already has the same file at `path`: nothing was copied, and nothing is ever + /// deleted for it. + Present, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct LedgerFile { + /// The file's name in the store family's folder. + store_file: String, + path: PathBuf, + /// The store file's sha256. + sha256: String, + postscript: Vec, + mechanism: Mechanism, + state: State, + /// While `adding` over an earlier copy: that copy's sha256. + #[serde(default, skip_serializing_if = "Option::is_none")] + replacing: Option, + /// Windows: the per-user font value in the registry that names the copy. + #[serde(default, skip_serializing_if = "Option::is_none")] + registry: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct LedgerFamily { + family: String, + source: String, + /// The family's folder in the store. + dir: String, + files: Vec, +} + +impl LedgerFamily { + fn is(&self, source: &str, name: &str) -> bool { + self.source == source && self.family.to_lowercase() == name.to_lowercase() + } + + fn copies(&self) -> impl Iterator { + self.files.iter().filter(|f| f.mechanism == Mechanism::Copy) + } +} + +#[derive(Default, Serialize, Deserialize)] +pub(super) struct Ledger { + version: u32, + families: Vec, +} + +impl Ledger { + fn family(&self, source: &str, name: &str) -> Option<&LedgerFamily> { + self.families.iter().find(|f| f.is(source, name)) + } + + /// Settles every `adding` entry and puts back files a crashed deletion left aside (see the + /// module comment). + fn settle(&mut self, folder: &OsFontFolder) { + for family in &mut self.families { + let dir = family.dir.clone(); + family.files.retain_mut(|f| { + let owned = folder.owns(&dir, f); + if owned { + restore_removing(&f.path); + } + if f.mechanism == Mechanism::Present { + // The system copy is gone: the next make-available copies the file. + return std::fs::metadata(&f.path).is_ok(); + } + if f.state == State::Active { + return true; + } + if !owned { + return false; + } + let _ = std::fs::remove_file(aside(&f.path, "part")); + match file_sha256(&f.path) { + Some(sha) if sha == f.sha256 => {} + Some(sha) if f.replacing.as_ref() == Some(&sha) => f.sha256 = sha, + _ => return false, + } + f.state = State::Active; + f.replacing = None; + true + }); + } + self.families.retain(|f| !f.files.is_empty()); + } +} + +/// The last ledger read, while the file's size and modification time are unchanged. +#[derive(Default)] +pub(super) struct LedgerCache(Mutex)>>); + +/// The ledger file's size and modification time. +type LedgerStamp = (u64, Option); + +/// `.craft-.` beside `path`: a copy being made (`part`) or deleted (`removing`). +fn aside(path: &Path, what: &str) -> PathBuf { + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + path.with_file_name(format!(".craft-{name}.{what}")) +} + +/// Puts back a file a crashed deletion left aside. +fn restore_removing(path: &Path) { + let removing = aside(path, "removing"); + if std::fs::symlink_metadata(path).is_err() && removing.is_file() { + let _ = std::fs::rename(&removing, path); + } +} + +/// The sha256 of the file at `path`, read in pieces; `None` when it can't be read. +fn file_sha256(path: &Path) -> Option { + use sha2::{Digest, Sha256}; + let mut hasher = Sha256::new(); + std::io::copy(&mut File::open(path).ok()?, &mut hasher).ok()?; + Some(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()) +} + +#[cfg(unix)] +type FileId = (u64, u64); +#[cfg(not(unix))] +type FileId = PathBuf; + +/// What makes two paths one file, through links and bind mounts (Flatpak shows the host's user +/// fonts again at `/run/host/user-fonts`). +fn file_id(path: &Path) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(path).ok().map(|m| (m.dev(), m.ino())) + } + #[cfg(not(unix))] + { + std::fs::canonicalize(path).ok() + } +} + +/// A store file to make available. +struct Planned { + store_file: String, + source: PathBuf, + path: PathBuf, + sha256: String, + postscript: Vec, + /// Windows: the registry value name for the copy. + registry: Option, +} + +impl FontStore { + /// Uses `folder` as the OS user font folder. [`FontStore::for_user`] and + /// [`FontStore::for_agent`] use [`OsFontFolder::for_env`]; [`FontStore::new`] has none. + pub fn with_os_fonts(mut self, folder: OsFontFolder) -> Self { + self.os_fonts = Ok(folder); + self + } + + pub(super) fn set_os_fonts(&mut self, folder: Result) { + self.os_fonts = folder; + } + + /// Whether families can be copied into the OS user font folder here. The interface hides the + /// action when it is false. + pub fn available_to_all_supported(&self) -> bool { + self.os_fonts.is_ok() + } + + /// Why families can't be copied into the OS user font folder here; `None` when they can. + pub fn available_to_all_unsupported(&self) -> Option<&str> { + self.os_fonts.as_ref().err().map(String::as_str) + } + + /// The OS user font folder, when there is one. + pub fn os_fonts(&self) -> Option<&OsFontFolder> { + self.os_fonts.as_ref().ok() + } + + /// Whether the family of this name installed from `source` has copies in the OS user font + /// folder (is available to all apps). Cheap enough for every row of a list: it reads the + /// ledger again only when the file changed. False when the ledger can't be read. + pub fn is_available(&self, source: &str, name: &str) -> bool { + self.cached_ledger().is_some_and(|l| l.family(source, name).is_some()) + } + + /// The source and name of the available family whose store folder holds one of `files`; with + /// no `files`, of the available family called `name` (ignoring case). A family of the same + /// name from another source doesn't count when `files` are given. Cheap like + /// [`FontStore::is_available`]: it reads only the ledger. + pub fn available_family_holding(&self, name: &str, files: &[PathBuf]) -> Option<(String, String)> { + let ledger = self.cached_ledger()?; + let found = if files.is_empty() { + let lower = name.to_lowercase(); + ledger.families.iter().find(|f| f.family.to_lowercase() == lower) + } else { + ledger.families.iter().find(|f| safe_dir(&f.dir) && files.iter().any(|p| p.starts_with(self.dir.join(&f.dir)))) + }; + found.map(|f| (f.source.clone(), f.family.clone())) + } + + /// The family's copies the ledger lists when this build can't change the OS user font folder + /// (a Flatpak whose access to it was taken away, say): removing the family leaves them in + /// place. Empty when the folder can be changed or the family has no copies. + pub fn copies_out_of_reach(&self, source: &str, name: &str) -> Vec { + if self.os_fonts.is_ok() { + return Vec::new(); + } + self.available_files(source, name) + } + + /// The copies of the family's files in the OS user font folder. + pub fn available_files(&self, source: &str, name: &str) -> Vec { + self.cached_ledger().and_then(|l| l.family(source, name).map(|f| f.copies().map(|x| x.path.clone()).collect())).unwrap_or_default() + } + + /// The store files of an available family that have no copy in the OS folder yet, by their + /// names in its folder: styles installed since (an agent's install doesn't copy them), or + /// files whose copy is older than the store's, or whose identical system file is gone. Empty + /// for a family that isn't available. + pub fn pending_files(&self, source: &str, name: &str) -> Vec { + let Some(ledger) = self.cached_ledger() else { return Vec::new() }; + let Some(listed) = ledger.family(source, name) else { return Vec::new() }; + let Some(family) = self.installed_family(source, name) else { return Vec::new() }; + family + .files + .iter() + .filter(|f| { + !listed + .files + .iter() + .any(|x| x.store_file == f.name && x.sha256 == f.sha256 && (x.mechanism == Mechanism::Copy || std::fs::metadata(&x.path).is_ok())) + }) + .map(|f| f.name.clone()) + .collect() + } + + /// Makes the installed family available to all apps, from the user's own action: copies its + /// font files into the OS user font folder and records them in the ledger. Calling it again + /// copies styles installed since and brings the copies up to date. Returns the copies. + /// + /// Refuses with [`Error::Conflict`], changing nothing, when a font the store didn't copy for + /// this family has one of its PostScript names (a system font, or another family's copy), or + /// a file the store didn't add sits where a copy would go. A system file identical to the + /// store's is no conflict: it isn't copied, and the ledger notes it. [`Error::NotAllowed`] + /// for an agent, [`Error::Unsupported`] where [`FontStore::available_to_all_supported`] is + /// false, [`Error::Ledger`] when the ledger can't be used. + /// + /// It blocks (hashing, copying, a catalog rescan): call it off the UI thread. Running apps see + /// the fonts at once or after a restart, depending on the app. + pub fn make_available(&self, source: &str, name: &str) -> Result, Error> { + if self.caller != Caller::User { + return Err(Error::NotAllowed); + } + self.share(source, name) + } + + /// Takes the family's copies out of the OS user font folder, from the user's own action. Only + /// files the ledger lists go, and only while unchanged: returns the ones left in place because + /// they changed since (or were moved or linked elsewhere). [`Error::NotAllowed`] for an agent. + /// It blocks: call it off the UI thread. + pub fn withdraw(&self, source: &str, name: &str) -> Result, Error> { + if self.caller != Caller::User { + return Err(Error::NotAllowed); + } + let folder = self.os_fonts.as_ref().map_err(|reason| Error::Unsupported(reason.clone()))?; + let kept = { + let _lock = self.lock()?; + self.unshare_locked(folder, source, name, None)? + }; + folder.refresh(); + self.rescan(); + Ok(kept) + } + + /// After the user's install: copies new styles of an available family and brings its copies + /// up to date. A failure leaves the earlier copies listed and the new files in + /// [`FontStore::pending_files`], as an agent's install does. + pub(super) fn reshare(&self, source: &str, name: &str) { + if self.caller == Caller::User && self.is_available(source, name) { + let _ = self.share(source, name); + } + } + + /// While the store is locked, before the family (`files` only, by their store names, when + /// given) leaves the store: withdraws their copies. Refuses, before anything changes, when + /// copies would have to go but an agent asks ([`Error::NotAllowed`]) or the ledger can't be + /// used ([`Error::Ledger`]). Where this build can't change the OS folder, the copies stay + /// there and in the ledger ([`FontStore::copies_out_of_reach`]), so a build that can still + /// removes them, and a reinstall finds them the store's. + pub(super) fn withdraw_for_removal(&self, source: &str, name: &str, files: Option<&[String]>) -> Result<(), Error> { + let ledger = self.read_ledger()?; + let Some(family) = ledger.family(source, name) else { return Ok(()) }; + let touched = |f: &LedgerFile| files.is_none_or(|o| o.contains(&f.store_file)); + if !family.files.iter().any(touched) { + return Ok(()); + } + if self.caller != Caller::User && family.copies().any(touched) { + return Err(Error::NotAllowed); + } + let Ok(folder) = self.os_fonts.as_ref() else { return Ok(()) }; + self.unshare_locked(folder, source, name, files)?; + folder.refresh(); + Ok(()) + } + + fn share(&self, source: &str, name: &str) -> Result, Error> { + let folder = self.os_fonts.as_ref().map_err(|reason| Error::Unsupported(reason.clone()))?; + let (copies, registered) = { + let _lock = self.lock()?; + let mut ledger = self.read_ledger()?; + ledger.settle(folder); + let family = self.installed_family(source, name).ok_or_else(|| Error::NotInstalled(name.to_string()))?; + let planned = self.plan(folder, &family)?; + let earlier: Vec = ledger.family(source, name).map(|f| f.files.clone()).unwrap_or_default(); + let others: Vec<&LedgerFile> = ledger.families.iter().filter(|f| !f.is(source, name)).flat_map(LedgerFamily::copies).collect(); + + // Faces at these files are the store's own, whatever path the catalog reached them + // by: every family's copies, and whatever sits where a copy goes, which the checks + // below look at. + let ours: HashSet = ledger + .families + .iter() + .flat_map(|f| f.copies().filter(|x| file_sha256(&x.path).as_ref() == Some(&x.sha256)).map(|x| &x.path)) + .chain(planned.iter().map(|p| &p.path)) + .filter_map(|p| file_id(p)) + .collect(); + let (mut conflicts, present) = self.system_conflicts(&planned, &ours); + conflicts.extend(folder.registry_conflicts(&planned)); + for p in &planned { + for other in &others { + for ps in p.postscript.iter().filter(|ps| other.postscript.iter().any(|o| o.eq_ignore_ascii_case(ps))) { + conflicts.push(Conflict { postscript: Some(ps.clone()), path: other.path.clone() }); + } + } + } + + let mut files = Vec::new(); + let mut to_copy = Vec::new(); + for p in &planned { + let earlier_copy = earlier.iter().find(|e| e.mechanism == Mechanism::Copy && e.path == p.path); + // Only a file not copied yet is left to an identical system file. + if earlier_copy.is_none() + && let Some(system) = present.get(&p.store_file) + { + files.push(LedgerFile { + store_file: p.store_file.clone(), + path: system.clone(), + sha256: p.sha256.clone(), + postscript: p.postscript.clone(), + mechanism: Mechanism::Present, + state: State::Active, + replacing: None, + registry: None, + }); + continue; + } + let disk = file_sha256(&p.path); + // A file where a copy goes is ours when the ledger lists it for this family + // unchanged, or when it is the store's file already (a copy the ledger lost). + let blocked = !folder.no_links(&p.path) + || others.iter().any(|x| x.path == p.path) + || match &disk { + Some(sha) => *sha != p.sha256 && earlier_copy.is_none_or(|e| e.sha256 != *sha), + None => std::fs::symlink_metadata(&p.path).is_ok(), + }; + if blocked { + conflicts.push(Conflict { postscript: None, path: p.path.clone() }); + } + let state = if disk.as_ref() == Some(&p.sha256) { + State::Active + } else { + to_copy.push((p, disk.clone())); + State::Adding + }; + files.push(LedgerFile { + store_file: p.store_file.clone(), + path: p.path.clone(), + sha256: p.sha256.clone(), + postscript: p.postscript.clone(), + mechanism: Mechanism::Copy, + state, + replacing: earlier_copy.filter(|_| state == State::Adding).map(|e| e.sha256.clone()), + registry: p.registry.clone(), + }); + } + if !conflicts.is_empty() { + conflicts.sort_by(|a, b| (&a.postscript, &a.path).cmp(&(&b.postscript, &b.path))); + conflicts.dedup(); + return Err(Error::Conflict(conflicts)); + } + // Copies of files the store no longer has stay listed until they are deleted below. + let stale: Vec = + earlier.into_iter().filter(|e| e.mechanism == Mechanism::Copy && !files.iter().any(|f| f.path == e.path)).collect(); + files.extend(stale.iter().cloned()); + ledger.families.retain(|f| !f.is(source, name)); + ledger.families.push(LedgerFamily { family: family.family.clone(), source: family.source.clone(), dir: family.dir.clone(), files }); + ledger.families.retain(|f| !f.files.is_empty()); + ledger.families.sort_by_key(|f| (f.family.to_lowercase(), f.source.clone())); + self.write_ledger(&ledger)?; + + if let Err(e) = to_copy.into_iter().try_for_each(|(p, found)| copy_in(folder, p, found.as_deref())) { + ledger.settle(folder); + let _ = self.write_ledger(&ledger); + return Err(e); + } + let registered = register_all(folder, &ledger, source, name, &stale); + if let Some(entry) = ledger.families.iter_mut().find(|f| f.is(source, name)) { + for f in &mut entry.files { + f.state = State::Active; + f.replacing = None; + } + let dir = entry.dir.clone(); + // A stale copy leaves the ledger once deleted, or once changed and so not ours. + entry.files.retain(|f| !stale.iter().any(|s| s.path == f.path) || remove_if_unchanged(folder, &dir, f).is_err()); + } + ledger.families.retain(|f| !f.files.is_empty()); + self.write_ledger(&ledger)?; + prune_dirs(folder, stale.iter().map(|s| s.path.as_path())); + let copies = ledger.family(source, name).map(|f| f.copies().map(|x| x.path.clone()).collect()).unwrap_or_default(); + (copies, registered) + }; + folder.refresh(); + self.rescan(); + registered.map(|()| copies) + } + + /// The family's files, checked against the manifest, with their PostScript names: the + /// faces' and named instances' as a catalog scan reads them, and the index's. + fn plan(&self, folder: &OsFontFolder, family: &InstalledFamily) -> Result, Error> { + let store_dir = self.dir.join(&family.dir); + let mut planned = Vec::new(); + for f in &family.files { + let from = store_dir.join(&f.name); + if file_sha256(&from).as_ref() != Some(&f.sha256) { + return Err(Error::Verify { file: f.name.clone(), error: VerifyError::Sha256 }); + } + let faces = read_faces(&from, Source::Store); + let registry = folder.registry_name(&from, &f.name, &faces); + let mut postscript: Vec = faces.into_iter().filter_map(|x| x.postscript_name).collect(); + postscript.extend(f.postscript.iter().cloned()); + postscript.sort(); + postscript.dedup(); + planned.push(Planned { + store_file: f.name.clone(), + source: from, + path: folder.path_for(&family.dir, &f.name), + sha256: f.sha256.clone(), + postscript, + registry, + }); + } + Ok(planned) + } + + /// System faces (except at the files in `ours`) with a PostScript name of `planned`: + /// conflicts, and the store files the system already has identical copies of, with where. + fn system_conflicts(&self, planned: &[Planned], ours: &HashSet) -> (Vec, HashMap) { + // Not `faces()`: it keeps one of two faces alike, which may be the store's. + let faces = match &self.catalog { + Some(catalog) => { + catalog.rescan_if_changed(); + catalog.scanned_faces() + } + None => Catalog::new(FontEnv::from_process()).scanned_faces(), + }; + let mut wanted: HashMap> = HashMap::new(); + for p in planned { + for ps in &p.postscript { + wanted.entry(ps.to_ascii_lowercase()).or_default().push(p); + } + } + let mut seen: HashMap, Option)> = HashMap::new(); + let mut conflicts = Vec::new(); + let mut present = HashMap::new(); + for face in faces.iter().filter(|f| f.source == Source::System) { + let (Some(ps), Some(path)) = (&face.postscript_name, &face.path) else { continue }; + let Some(hits) = wanted.get(&ps.to_ascii_lowercase()) else { continue }; + let (id, sha) = seen.entry(path.clone()).or_insert_with(|| (file_id(path), file_sha256(path))); + if id.as_ref().is_some_and(|id| ours.contains(id)) { + continue; + } + for p in hits { + if sha.as_ref() == Some(&p.sha256) { + present.insert(p.store_file.clone(), path.clone()); + } else { + conflicts.push(Conflict { postscript: Some(ps.clone()), path: path.clone() }); + } + } + } + (conflicts, present) + } + + fn unshare_locked(&self, folder: &OsFontFolder, source: &str, name: &str, only: Option<&[String]>) -> Result, Error> { + let mut ledger = self.read_ledger()?; + ledger.settle(folder); + let mut kept = Vec::new(); + let mut removed = Vec::new(); + let mut failed = None; + if let Some(entry) = ledger.families.iter_mut().find(|f| f.is(source, name)) { + let dir = entry.dir.clone(); + entry.files.retain(|f| { + if only.is_some_and(|o| !o.contains(&f.store_file)) { + return true; + } + if f.mechanism == Mechanism::Present { + return false; + } + match remove_if_unchanged(folder, &dir, f) { + Ok(true) => removed.push(f.path.clone()), + Ok(false) => kept.push(f.path.clone()), + Err(e) => { + failed.get_or_insert(e); + return true; + } + } + false + }); + } + ledger.families.retain(|f| !f.files.is_empty()); + self.write_ledger(&ledger)?; + prune_dirs(folder, removed.iter().map(PathBuf::as_path)); + match failed { + Some(e) => Err(e), + None => Ok(kept), + } + } + + /// The ledger; empty when there is none. One that can't be read, can't be parsed (an unknown + /// value, say) or has another version is an error and stays as it is, so nothing it lists is + /// lost. + fn read_ledger(&self) -> Result { + let path = self.dir.join(LEDGER); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Ledger::default()), + Err(e) => return Err(io(format!("reading {LEDGER}"))(e)), + }; + if meta.len() > MAX_LEDGER_BYTES { + return Err(Error::Ledger(format!("it is larger than {MAX_LEDGER_BYTES} bytes"))); + } + let bytes = std::fs::read(&path).map_err(io(format!("reading {LEDGER}")))?; + let ledger: Ledger = serde_json::from_slice(&bytes).map_err(|e| Error::Ledger(e.to_string()))?; + if ledger.version != LEDGER_VERSION { + return Err(Error::Ledger(format!("it is version {}, and this app reads version {LEDGER_VERSION}", ledger.version))); + } + Ok(ledger) + } + + /// [`FontStore::read_ledger`] for queries, read again only when the file changed; `None` + /// when it can't be used. + fn cached_ledger(&self) -> Option> { + let stamp = std::fs::metadata(self.dir.join(LEDGER)).map_or((0, None), |m| (m.len(), m.modified().ok())); + let mut cache = self.ledger_cache.0.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((s, ledger)) = cache.as_ref() + && *s == stamp + { + return Some(Arc::clone(ledger)); + } + let ledger = Arc::new(self.read_ledger().ok()?); + *cache = Some((stamp, Arc::clone(&ledger))); + Some(ledger) + } + + fn write_ledger(&self, ledger: &Ledger) -> Result<(), Error> { + let ledger = Ledger { version: LEDGER_VERSION, families: ledger.families.clone() }; + let bytes = serde_json::to_vec_pretty(&ledger).map_err(|e| io("saving the OS font ledger")(std::io::Error::other(e)))?; + *self.ledger_cache.0.lock().unwrap_or_else(PoisonError::into_inner) = None; + self.write_file(LEDGER, &bytes) + } +} + +/// Copies a store file to its place through a dot-file, checking the copy's sha256. `found` is +/// the sha256 of the file planning found at the place (the family's earlier copy), if any. +fn copy_in(folder: &OsFontFolder, p: &Planned, found: Option<&str>) -> Result<(), Error> { + let what = || format!("copying {} to {}", p.store_file, p.path.display()); + if let Some(parent) = p.path.parent() { + std::fs::create_dir_all(parent).map_err(io(what()))?; + } + if !folder.no_links(&p.path) { + return Err(io(what())(std::io::Error::other("a symbolic link is in the way"))); + } + let part = aside(&p.path, "part"); + let _ = std::fs::remove_file(&part); + std::fs::copy(&p.source, &part).map_err(io(what()))?; + folder.unload(&p.path); + let checked = File::open(&part).and_then(|f| f.sync_all()).map_err(io(what())).and_then(|()| { + if file_sha256(&part).as_ref() == Some(&p.sha256) { + Ok(()) + } else { + Err(Error::Verify { file: p.store_file.clone(), error: VerifyError::Sha256 }) + } + }); + if let Err(e) = checked.and_then(|()| publish(&part, p, found)) { + let _ = std::fs::remove_file(&part); + return Err(e); + } + Ok(()) +} + +/// Moves the checked copy `part` to `p.path`, only over what planning found there: nothing, or +/// the file with sha256 `found`. A file another app put there since is a conflict. +fn publish(part: &Path, p: &Planned, found: Option<&str>) -> Result<(), Error> { + let conflict = || Error::Conflict(vec![Conflict { postscript: None, path: p.path.clone() }]); + let absent = || std::fs::symlink_metadata(&p.path).is_err(); + if absent() { + // A hard link never replaces a file that appeared since the check. + match std::fs::hard_link(part, &p.path) { + Ok(()) => { + let _ = std::fs::remove_file(part); + return Ok(()); + } + // A file system without hard links falls through to the rename below. + Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists && absent() => {} + Err(_) => return Err(conflict()), + } + } else if found.is_none() || file_sha256(&p.path).as_deref() != found { + return Err(conflict()); + } + // Over the earlier copy, or without hard links, a file another app writes between the check + // above and this rename is replaced: std has no rename that refuses to replace. + std::fs::rename(part, &p.path).map_err(io(format!("copying {} to {}", p.store_file, p.path.display()))) +} + +/// Deletes a listed copy of the family in store folder `dir` when it is the store's and +/// unchanged: `Ok(true)` when it is gone (or already was), `Ok(false)` when it is left in place. +/// The file is moved aside first and checked there, so one changed in the meantime goes back. +fn remove_if_unchanged(folder: &OsFontFolder, dir: &str, f: &LedgerFile) -> Result { + if !folder.owns(dir, f) { + return Ok(false); + } + folder.unregister(f)?; + restore_removing(&f.path); + let _ = std::fs::remove_file(aside(&f.path, "part")); + if std::fs::symlink_metadata(&f.path).is_err() { + return Ok(true); + } + let what = || format!("removing {}", f.path.display()); + let removing = aside(&f.path, "removing"); + std::fs::rename(&f.path, &removing).map_err(io(what()))?; + if file_sha256(&removing).as_ref() == Some(&f.sha256) { + std::fs::remove_file(&removing).map_err(io(what()))?; + Ok(true) + } else { + std::fs::rename(&removing, &f.path).map_err(io(what()))?; + Ok(false) + } +} + +/// Registers the family's copies, except the `stale` ones about to go, where the OS needs that. +/// Registering again is harmless: it updates the value, and withdrawal unloads every load. +fn register_all(folder: &OsFontFolder, ledger: &Ledger, source: &str, name: &str, stale: &[LedgerFile]) -> Result<(), Error> { + let Some(family) = ledger.family(source, name) else { return Ok(()) }; + family.copies().filter(|f| !stale.iter().any(|s| s.path == f.path)).try_for_each(|f| folder.register(f)) +} + +/// Removes the folders `removed` files leave empty, up to the OS folder itself. +fn prune_dirs<'a>(folder: &OsFontFolder, removed: impl Iterator) { + for path in removed { + let mut dir = path.parent(); + while let Some(d) = dir.filter(|d| *d != folder.dir && d.starts_with(&folder.dir)) { + if std::fs::remove_dir(d).is_err() { + break; + } + dir = d.parent(); + } + } +} diff --git a/crates/font-store/src/tests.rs b/crates/font-store/src/tests.rs index 38174abf79..37bd0f56d5 100644 --- a/crates/font-store/src/tests.rs +++ b/crates/font-store/src/tests.rs @@ -1386,6 +1386,315 @@ mod store { let _ = std::fs::remove_dir_all(dir); } + /// A store with Test Sans installed, its catalog and an OS user font folder, all in temporary + /// folders: the store, the system root (`/usr/share/fonts`) and the home folder. + fn shared_store(server: &Server, name: &str) -> (FontStore, PathBuf, PathBuf, PathBuf) { + let index = index_of(&fixture().index).unwrap(); + let dir = temp(name); + let root = temp(&format!("{name}-root")); + let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(root.join("home")), font_store: Some(dir.clone()), ..Default::default() }; + let catalog = Arc::new(Catalog::new(env).with_font_service(false)); + let shared = root.join("home/.local/share/fonts/Craft"); + let store = user_store(server, &dir).with_catalog(catalog).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders)); + store.install_family(&index, index.family("Test Sans").unwrap(), &Cancel::new(), &mut none).unwrap(); + (store, dir, root, shared) + } + + fn ledger(dir: &Path) -> serde_json::Value { + serde_json::from_slice(&std::fs::read(dir.join("os-fonts.json")).unwrap()).unwrap() + } + + /// Each copy in `family` matches the store's file, and the ledger lists exactly these copies. + fn assert_copies_match_store_and_ledger(dir: &Path, family: &Path, names: &[&str]) { + for name in names { + assert_eq!(std::fs::read(family.join(name)).unwrap(), std::fs::read(dir.join("testsans").join(name)).unwrap()); + } + let l = ledger(dir); + assert_eq!((l["version"].as_u64(), l["families"][0]["family"].as_str()), (Some(1), Some("Test Sans"))); + let files = l["families"][0]["files"].as_array().unwrap(); + assert_eq!(files.len(), names.len()); + for f in files { + let path = PathBuf::from(f["path"].as_str().unwrap()); + assert_eq!(f["sha256"].as_str().unwrap(), sha256_hex(&std::fs::read(&path).unwrap())); + assert_eq!((f["state"].as_str(), f["mechanism"].as_str()), (Some("active"), Some("copy"))); + } + assert_eq!(files[0]["postscript"], json!(["TestSans-Bold"])); + } + + #[test] + fn a_family_made_available_to_all_apps_is_withdrawn_exactly() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let (store, dir, root, shared) = shared_store(&server, "os-fonts"); + let family = shared.join("testsans"); + assert!(store.available_to_all_supported()); + assert!(!store.is_available(GOOGLE_FONTS, "Test Sans")); + assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Var"), Err(Error::NotInstalled(_)))); + + let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + let names = ["TestSans-Bold.ttf", "TestSans-Italic.ttf", "TestSans-Regular.ttf"]; + assert_eq!(entries(&family), names, "fonts only: no licence, no temporary files"); + assert_eq!(copies, names.map(|n| family.join(n))); + assert_copies_match_store_and_ledger(&dir, &family, &names); + assert!(store.is_available(GOOGLE_FONTS, "test sans")); + // Again: the copies, which the catalog now lists as system fonts, aren't conflicts. + assert_eq!(store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(), copies); + + // A crash after a copy was renamed into place, before the ledger said so: the next change + // settles the entry and deletes the temporary file. + std::fs::write(family.join(".craft-TestSans-Regular.ttf.part"), b"half").unwrap(); + let mut l = ledger(&dir); + l["families"][0]["files"][2]["state"] = json!("adding"); + std::fs::write(dir.join("os-fonts.json"), l.to_string()).unwrap(); + store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + assert_eq!(entries(&family), names); + assert!(ledger(&dir)["families"][0]["files"].as_array().unwrap().iter().all(|f| f["state"] == "active")); + + // Withdrawing leaves a changed copy and files the store didn't add, and reports the copy. + let italic = family.join("TestSans-Italic.ttf"); + std::fs::write(&italic, b"the user's own").unwrap(); + std::fs::write(family.join("Unlisted.ttf"), b"x").unwrap(); + assert_eq!(store.withdraw(GOOGLE_FONTS, "Test Sans").unwrap(), std::slice::from_ref(&italic)); + assert_eq!(entries(&family), ["TestSans-Italic.ttf", "Unlisted.ttf"]); + assert!(!store.is_available(GOOGLE_FONTS, "Test Sans")); + assert_eq!(ledger(&dir)["families"], json!([])); + assert!(store.verify().is_empty(), "the store's own files are untouched"); + + // The changed file is no longer the store's: it sits where a copy would go. + match store.make_available(GOOGLE_FONTS, "Test Sans") { + Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: None, path: italic.clone() }]), + other => panic!("{other:?}"), + } + std::fs::remove_file(&italic).unwrap(); + std::fs::remove_file(family.join("Unlisted.ttf")).unwrap(); + + // Removing the family from the store withdraws it. + store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + assert!(store.copies_out_of_reach(GOOGLE_FONTS, "Test Sans").is_empty()); + store.remove_family(GOOGLE_FONTS, "Test Sans").unwrap(); + assert!(!family.exists()); + assert!(!store.is_available(GOOGLE_FONTS, "Test Sans")); + + // A build that can't change the OS folder removes the store's files and leaves the copies + // it can't reach, still listed, for a build that can. + let index = index_of(&fixture().index).unwrap(); + store.install_family(&index, index.family("Test Sans").unwrap(), &Cancel::new(), &mut none).unwrap(); + store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + let blind = FontStore::new(dir.clone(), Caller::User); + let out_of_reach = blind.copies_out_of_reach(GOOGLE_FONTS, "Test Sans"); + assert_eq!(out_of_reach, names.map(|n| family.join(n))); + blind.remove_family(GOOGLE_FONTS, "Test Sans").unwrap(); + assert!(blind.installed_family(GOOGLE_FONTS, "Test Sans").is_none()); + assert!(out_of_reach.iter().all(|c| c.is_file())); + assert!(blind.is_available(GOOGLE_FONTS, "Test Sans")); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn making_available_refuses_postscript_conflicts_and_agents() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let (store, dir, root, shared) = shared_store(&server, "os-fonts-conflict"); + let agent = FontStore::new(dir.clone(), Caller::Agent).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders)); + assert!(matches!(agent.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed))); + assert!(matches!(agent.withdraw(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed))); + assert!(!FontStore::new(dir.clone(), Caller::User).available_to_all_supported()); + + // A different font of the same PostScript name in a system folder. + let system = root.join("usr/share/fonts"); + std::fs::create_dir_all(&system).unwrap(); + let other = system.join("TestSans-Bold.ttf"); + std::fs::write(&other, font("Test Sans", "Bold", 600)).unwrap(); + match store.make_available(GOOGLE_FONTS, "Test Sans") { + Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: Some("TestSans-Bold".into()), path: other.clone() }]), + other => panic!("{other:?}"), + } + assert!(!shared.exists(), "nothing copied"); + assert!(!store.is_available(GOOGLE_FONTS, "Test Sans")); + + // The same file is no conflict: the system has it, so it isn't copied or recorded. + std::fs::write(&other, std::fs::read(dir.join("testsans/TestSans-Bold.ttf")).unwrap()).unwrap(); + let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + assert_eq!(copies, ["TestSans-Italic.ttf", "TestSans-Regular.ttf"].map(|n| shared.join("testsans").join(n))); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + } + + /// A catalog of the same system as [`shared_store`]'s, to look at what a scan sees. + fn catalog_of(dir: &Path, root: &Path) -> Catalog { + let env = FontEnv { + os: Os::Unix, + root: root.to_path_buf(), + home: Some(root.join("home")), + font_store: Some(dir.to_path_buf()), + ..Default::default() + }; + Catalog::new(env).with_font_service(false) + } + + #[test] + #[cfg(unix)] + fn copies_reached_by_another_path_are_still_the_stores_and_links_are_refused() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let (store, dir, root, shared) = shared_store(&server, "os-fonts-alias"); + // As Flatpak's /run/host/user-fonts: the user's font folder again, scanned first. + let fonts = root.join("home/.local/share/fonts"); + std::fs::create_dir_all(&fonts).unwrap(); + std::fs::create_dir_all(root.join("usr/share/fonts")).unwrap(); + std::os::unix::fs::symlink(&fonts, root.join("usr/share/fonts/user-fonts")).unwrap(); + + let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + assert_eq!(copies.len(), 3); + let seen = catalog_of(&dir, &root); + seen.rescan(); + assert!(seen.scanned_faces().iter().any(|f| f.path.as_ref().is_some_and(|p| p.starts_with(root.join("usr/share/fonts/user-fonts"))))); + assert_eq!(store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(), copies); + assert_eq!(store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(), copies); + assert!(copies.iter().all(|c| c.is_file())); + assert!(store.pending_files(GOOGLE_FONTS, "Test Sans").is_empty()); + + // A family folder that is a link leads outside: nothing is written or deleted through it. + let outside = temp("os-fonts-outside"); + let mut l = ledger(&dir); + l["families"][0]["files"][0]["path"] = json!(outside.join("TestSans-Bold.ttf")); + std::fs::write(dir.join("os-fonts.json"), l.to_string()).unwrap(); + std::fs::copy(&copies[0], outside.join("TestSans-Bold.ttf")).unwrap(); + let kept = store.withdraw(GOOGLE_FONTS, "Test Sans").unwrap(); + assert_eq!(kept, [outside.join("TestSans-Bold.ttf")], "a path the store doesn't put copies at is left alone"); + assert!(outside.join("TestSans-Bold.ttf").is_file()); + std::fs::remove_file(&copies[0]).unwrap(); + std::fs::remove_dir(shared.join("testsans")).unwrap(); + std::os::unix::fs::symlink(&outside, shared.join("testsans")).unwrap(); + assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::Conflict(_)))); + assert_eq!(entries(&outside), ["TestSans-Bold.ttf"]); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + let _ = std::fs::remove_dir_all(outside); + } + + #[test] + fn a_ledger_that_cant_be_understood_is_kept_and_blocks_changes() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let (store, dir, root, shared) = shared_store(&server, "os-fonts-bad-ledger"); + store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + let mut l = ledger(&dir); + l["families"][0]["files"][0]["mechanism"] = json!("hardlink"); + let bytes = l.to_string(); + std::fs::write(dir.join("os-fonts.json"), &bytes).unwrap(); + + assert!(!store.is_available(GOOGLE_FONTS, "Test Sans")); + assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_)))); + assert!(matches!(store.withdraw(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_)))); + assert!(matches!(store.remove_family(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_)))); + assert_eq!(std::fs::read_to_string(dir.join("os-fonts.json")).unwrap(), bytes); + assert_eq!(entries(&shared.join("testsans")).len(), 3); + assert!(store.installed_family(GOOGLE_FONTS, "Test Sans").is_some()); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn store_families_and_named_instances_conflict_by_postscript_name() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let index = index_of(&fixture().index).unwrap(); + let (store, dir, root, shared) = shared_store(&server, "os-fonts-families"); + for name in ["Shared One", "Shared Two", "Test Var"] { + store.install_family(&index, index.family(name).unwrap(), &Cancel::new(), &mut none).unwrap(); + } + // Both families' index entries name the face Shared-Regular. + store.make_available(GOOGLE_FONTS, "Shared One").unwrap(); + match store.make_available(GOOGLE_FONTS, "Shared Two") { + Err(Error::Conflict(c)) => { + assert_eq!(c, [Conflict { postscript: Some("Shared-Regular".into()), path: shared.join("sharedone/SharedOne-Regular.ttf") }]) + } + other => panic!("{other:?}"), + } + // A static system face named as one of a variable font's instances. + let system = root.join("usr/share/fonts"); + std::fs::create_dir_all(&system).unwrap(); + std::fs::write(system.join("TestVar-Bold.ttf"), font("Test Var", "Bold", 700)).unwrap(); + match store.make_available(GOOGLE_FONTS, "Test Var") { + Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: Some("TestVar-Bold".into()), path: system.join("TestVar-Bold.ttf") }]), + other => panic!("{other:?}"), + } + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn an_agent_never_changes_the_os_font_folder() { + let server = Server::start(); + server.serve_fixture(&fixture()); + let index = index_of(&fixture().index).unwrap(); + let (store, dir, root, shared) = shared_store(&server, "os-fonts-agent"); + store.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Italic.ttf".into()]).unwrap(); + store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(); + let family = shared.join("testsans"); + let before = entries(&family); + assert_eq!(before, ["TestSans-Bold.ttf", "TestSans-Regular.ttf"]); + + // An agent's install stays in the store, listed as not yet available. + let agent = + FontStore::new(dir.clone(), Caller::Agent).with_client(server.client()).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders)); + agent.install_face(&index, index.find_face("Test Sans", "Italic").unwrap(), &Cancel::new(), &mut none).unwrap(); + assert_eq!(entries(&family), before); + assert_eq!(store.pending_files(GOOGLE_FONTS, "Test Sans"), ["TestSans-Italic.ttf"]); + + // An agent can't remove what has copies; the user can. + assert!(matches!(agent.remove_family(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed))); + assert!(matches!(agent.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Bold.ttf".into()]), Err(Error::NotAllowed))); + assert_eq!(store.installed_family(GOOGLE_FONTS, "Test Sans").unwrap().files.len(), 3); + assert_eq!(entries(&family), before); + agent.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Italic.ttf".into()]).unwrap(); + + store.install_face(&index, index.find_face("Test Sans", "Italic").unwrap(), &Cancel::new(), &mut none).unwrap(); + assert_eq!(entries(&family), ["TestSans-Bold.ttf", "TestSans-Italic.ttf", "TestSans-Regular.ttf"], "the user's install copies it"); + assert!(store.pending_files(GOOGLE_FONTS, "Test Sans").is_empty()); + store.remove_family(GOOGLE_FONTS, "Test Sans").unwrap(); + assert!(!family.exists()); + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn the_os_folder_follows_the_platform_and_flatpak_grants() { + let root = temp("os-fonts-env"); + let home = root.join("home"); + let flatpak = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), flatpak: true, ..Default::default() }; + let with = |vars: &[(&str, &str)], env: &FontEnv| { + let vars: Vec<(String, String)> = vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + OsFontFolder::for_env_with(env, &move |k| vars.iter().find(|(n, _)| n == k).map(|(_, v)| v.into())).map(|f| f.dir().to_path_buf()) + }; + let info = |filesystems: &str| std::fs::write(root.join(".flatpak-info"), format!("[Context]\nfilesystems={filesystems}\n")).unwrap(); + + let unix = FontEnv { flatpak: false, xdg_data_home: Some(root.join("data")), ..flatpak.clone() }; + assert_eq!(with(&[], &unix), Ok(root.join("data/fonts/Craft"))); + assert!(with(&[("SNAP", "/snap/x")], &unix).is_err()); + let mac = FontEnv { os: Os::MacOs, ..unix.clone() }; + assert_eq!(with(&[], &mac), Ok(home.join("Library/Fonts"))); + assert!(with(&[("APP_SANDBOX_CONTAINER_ID", "x")], &mac).is_err()); + let windows = FontEnv { os: Os::Windows, local_app_data: Some(root.join("Local")), ..unix.clone() }; + assert_eq!(with(&[], &windows), Ok(root.join("Local/Microsoft/Windows/Fonts/Craft"))); + assert_eq!(with(&[], &FontEnv { local_app_data: None, ..windows.clone() }), Ok(home.join("AppData/Local/Microsoft/Windows/Fonts/Craft"))); + + info("xdg-data/fonts:create;"); + assert_eq!(with(&[], &flatpak), Ok(home.join(".local/share/fonts/Craft"))); + info("xdg-data/fonts:create;!xdg-data/fonts;"); + assert!(with(&[], &flatpak).is_err(), "revoked"); + info("home:ro;"); + assert!(with(&[], &flatpak).is_err(), "read only"); + info("~/.local/share/fonts;"); + assert!(with(&[], &flatpak).is_ok()); + assert!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak).is_err(), "the grant is for another folder"); + info("xdg-data/fonts;"); + assert_eq!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak), Ok(PathBuf::from("/elsewhere/fonts/Craft"))); + let _ = std::fs::remove_dir_all(root); + } + /// Fetches the pinned indexes from jsDelivr and GitHub and installs a Noto family whose /// licence is in another repository. `cargo test -p craft-font-store -- --ignored`. #[test]