diff --git a/AGENTS.md b/AGENTS.md index ff4606fd5..2fd1513b8 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 a7e2b6277..bc2c0ff33 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 607c0a49d..bc76a21ab 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 951298091..29615b42a 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-os-windows/Cargo.toml b/crates/font-os-windows/Cargo.toml new file mode 100644 index 000000000..9266a0151 --- /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 000000000..cacddf5f1 --- /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 d840ff48e..406212347 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 a89d03e4f..d0fa39e81 100644 --- a/crates/font-store/README.md +++ b/crates/font-store/README.md @@ -203,7 +203,8 @@ The user's `remove_family` and `remove_files` withdraw the copies first, so the | 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. | -| Snap, a sandboxed macOS build (Mac App Store), Windows, Haiku, the web | none | `Error::Unsupported`. | +| 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. diff --git a/crates/font-store/src/store/os_fonts.rs b/crates/font-store/src/store/os_fonts.rs index 82d7e430c..544eb424a 100644 --- a/crates/font-store/src/store/os_fonts.rs +++ b/crates/font-store/src/store/os_fonts.rs @@ -11,6 +11,13 @@ //! 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}; @@ -20,7 +27,7 @@ use std::path::{Component, Path, PathBuf}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::SystemTime; -use craft_font_catalog::{Catalog, FontEnv, Os, Source, read_faces}; +use craft_font_catalog::{Catalog, FaceInfo, FontEnv, Os, Source, read_faces}; use serde::{Deserialize, Serialize}; use super::{Caller, Error, FontStore, InstalledFamily, io}; @@ -47,6 +54,8 @@ 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 { @@ -60,9 +69,16 @@ impl OsFontFolder { /// 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, Haiku and the web: not offered. + /// - 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 { - Self::for_env_with(env, &|k| std::env::var_os(k).filter(|v| !v.is_empty())) + 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`. @@ -74,7 +90,7 @@ impl OsFontFolder { 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 }) + Ok(Self { dir: home.join("Library/Fonts"), layout: OsFontLayout::Flat, fc_cache: false, registry: false }) } Os::Unix => { if var("SNAP").is_some() { @@ -91,9 +107,18 @@ impl OsFontFolder { } 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 }) + 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::Windows => Err("copying fonts into the Windows Fonts folder isn't supported".into()), Os::Haiku | Os::None => Err("this system has no user font folder the store can add to".into()), } } @@ -101,7 +126,7 @@ impl OsFontFolder { /// 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 } + Self { dir: dir.into(), layout, fc_cache: false, registry: false } } /// The folder. @@ -147,9 +172,62 @@ impl OsFontFolder { && self.no_links(&file.path) } - /// Tells fontconfig, off the calling thread. It isn't needed for correctness: fontconfig - /// notices changed folders by their mtime. + /// 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; } @@ -243,6 +321,9 @@ struct LedgerFile { /// 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)] @@ -361,6 +442,8 @@ struct Planned { path: PathBuf, sha256: String, postscript: Vec, + /// Windows: the registry value name for the copy. + registry: Option, } impl FontStore { @@ -509,7 +592,7 @@ impl FontStore { 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 = { + let (copies, registered) = { let _lock = self.lock()?; let mut ledger = self.read_ledger()?; ledger.settle(folder); @@ -529,6 +612,7 @@ impl FontStore { .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))) { @@ -553,6 +637,7 @@ impl FontStore { mechanism: Mechanism::Present, state: State::Active, replacing: None, + registry: None, }); continue; } @@ -582,6 +667,7 @@ impl FontStore { mechanism: Mechanism::Copy, state, replacing: earlier_copy.filter(|_| state == State::Adding).map(|e| e.sha256.clone()), + registry: p.registry.clone(), }); } if !conflicts.is_empty() { @@ -604,6 +690,7 @@ impl FontStore { 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; @@ -616,11 +703,12 @@ impl FontStore { ledger.families.retain(|f| !f.files.is_empty()); self.write_ledger(&ledger)?; prune_dirs(folder, stale.iter().map(|s| s.path.as_path())); - ledger.family(source, name).map(|f| f.copies().map(|x| x.path.clone()).collect()).unwrap_or_default() + 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(); - Ok(copies) + registered.map(|()| copies) } /// The family's files, checked against the manifest, with their PostScript names: the @@ -633,7 +721,9 @@ impl FontStore { if file_sha256(&from).as_ref() != Some(&f.sha256) { return Err(Error::Verify { file: f.name.clone(), error: VerifyError::Sha256 }); } - let mut postscript: Vec = read_faces(&from, Source::Store).into_iter().filter_map(|x| x.postscript_name).collect(); + 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(); @@ -643,6 +733,7 @@ impl FontStore { path: folder.path_for(&family.dir, &f.name), sha256: f.sha256.clone(), postscript, + registry, }); } Ok(planned) @@ -777,6 +868,7 @@ fn copy_in(folder: &OsFontFolder, p: &Planned) -> Result<(), Error> { 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(()) @@ -798,6 +890,7 @@ fn remove_if_unchanged(folder: &OsFontFolder, dir: &str, f: &LedgerFile) -> Resu 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() { @@ -815,6 +908,13 @@ fn remove_if_unchanged(folder: &OsFontFolder, dir: &str, f: &LedgerFile) -> Resu } } +/// 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 { diff --git a/crates/font-store/src/tests.rs b/crates/font-store/src/tests.rs index 61bd2e6fe..37bd0f56d 100644 --- a/crates/font-store/src/tests.rs +++ b/crates/font-store/src/tests.rs @@ -1677,7 +1677,9 @@ mod store { 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()); - assert!(with(&[], &FontEnv { os: Os::Windows, ..unix.clone() }).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")));