Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(fonts): rescan installed fonts and preserve accepted results

FredApps6e4d9a683869
diff --git a/crates/engine/src/text_fonts.rs b/crates/engine/src/text_fonts.rs
index c231dad09..e2b413d88 100644
--- a/crates/engine/src/text_fonts.rs
+++ b/crates/engine/src/text_fonts.rs
@@ -32,18 +32,22 @@ pub fn installed_directories() -> Vec<PathBuf> {
}
}
-/// Bounded, symlink-free scan. Only standalone, openly licensed, embeddable faces are listed.
+/// Bounded scan with resolved roots and no descendant symlinks.
+/// Only standalone, openly licensed, embeddable faces are listed.
/// The caller controls roots (automation resolves confinement before calling this).
pub fn discover(roots: &[PathBuf]) -> Vec<FontFile> {
discover_budgeted(roots, 64u64 << 20)
}
-/// Bounded, symlink-free scan. `budget` caps the total size of the fonts listed: a file that
-/// is rejected (unreadable, not openly licensed, a duplicate) does not spend it. Every file read
+/// Bounded scan with resolved roots and no descendant symlinks. `budget` caps the total
+/// size of the fonts listed: a rejected file (unreadable, not openly licensed, a duplicate)
+/// does not spend it. Every file read
/// counts against four times the budget, so a folder of unusable fonts cannot stall the scan.
pub fn discover_budgeted(roots: &[PathBuf], mut budget: u64) -> Vec<FontFile> {
use std::io::Read;
- let mut pending: Vec<_> = roots.iter().take(16).map(|r| (r.clone(), 0usize)).collect();
+ // User font directories themselves are often links. Resolve only the explicitly
+ // supplied roots; links found below them must not escape an automation read root.
+ let mut pending: Vec<_> = roots.iter().take(16).filter_map(|r| r.canonicalize().ok()).map(|r| (r, 0usize)).collect();
let mut files = Vec::new();
let mut entries = 0usize;
let mut read_allowance = budget.saturating_mul(4);
@@ -89,7 +93,6 @@ pub fn discover_budgeted(roots: &[PathBuf], mut budget: u64) -> Vec<FontFile> {
}
}
files.sort_by(|a, b| a.face.cmp(&b.face).then(a.path.cmp(&b.path)));
- files.truncate(500);
files
}
@@ -107,6 +110,44 @@ fn font_extension(path: &Path) -> bool {
mod tests {
use super::*;
+ #[cfg(unix)]
+ #[test]
+ fn a_linked_font_root_is_scanned_but_descendant_links_are_not() {
+ let root = std::env::temp_dir().join(format!("pdfcraft-font-links-{}", std::process::id()));
+ let real = root.join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let source = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/Inter-Regular.ttf");
+ std::fs::copy(&source, real.join("regular.ttf")).unwrap();
+ let link = root.join("linked");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+ std::os::unix::fs::symlink(&real, real.join("cycle")).unwrap();
+ std::os::unix::fs::symlink(source.with_file_name("Inter-Medium.ttf"), real.join("escape.ttf")).unwrap();
+ let found = discover(&[link]);
+ let expected = real.canonicalize().unwrap().join("regular.ttf");
+ std::fs::remove_dir_all(&root).unwrap();
+ assert_eq!(found.len(), 1);
+ assert_eq!(found.first().unwrap().face, "Inter-Regular");
+ assert_eq!(found.first().unwrap().path, expected);
+ }
+
+ #[test]
+ fn discovery_keeps_all_valid_faces_within_its_scan_budget() {
+ let root = std::env::temp_dir().join(format!("pdfcraft-font-count-{}", std::process::id()));
+ std::fs::create_dir_all(&root).unwrap();
+ let source = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/Inter-Regular.ttf");
+ let bytes = std::fs::read(source).unwrap();
+ for id in 0..501u32 {
+ let mut font = bytes.clone();
+ // Valid standalone fonts with distinct bytes: an unreferenced trailer
+ // does not change their tables or embedding licence.
+ font.extend_from_slice(&id.to_le_bytes());
+ std::fs::write(root.join(format!("font-{id:03}.ttf")), font).unwrap();
+ }
+ let found = discover_budgeted(std::slice::from_ref(&root), (bytes.len() as u64 + 4) * 501);
+ std::fs::remove_dir_all(&root).unwrap();
+ assert_eq!(found.len(), 501, "do not silently discard accepted fonts after sorting");
+ }
+
#[test]
fn test_installed_directories() {
let dirs = installed_directories();
diff --git a/crates/ui-egui/src/panels/format_text_ui.rs b/crates/ui-egui/src/panels/format_text_ui.rs
index ea3bfaa3c..eb2979bff 100644
--- a/crates/ui-egui/src/panels/format_text_ui.rs
+++ b/crates/ui-egui/src/panels/format_text_ui.rs
@@ -159,7 +159,8 @@ pub(crate) fn panel(
#[cfg(not(target_arch = "wasm32"))]
ui.menu_button(tl!("Installed fonts…"), |ui| {
ui.set_min_width(260.0);
- match crate::files::installed_font_files(ui.ctx()) {
+ let reload = ui.button(tl!("Reload")).clicked();
+ match crate::files::installed_font_files(ui.ctx(), reload) {
Some(list) if list.is_empty() => {
ui.label(tl!("No openly licensed document fonts found. Load a font file."));
}
diff --git a/crates/ui-egui/src/workflows/files.rs b/crates/ui-egui/src/workflows/files.rs
index 17870e5b1..adb5e2f0d 100644
--- a/crates/ui-egui/src/workflows/files.rs
+++ b/crates/ui-egui/src/workflows/files.rs
@@ -35,14 +35,40 @@ fn discover_fonts_safely(
std::panic::catch_unwind(discover).unwrap_or_default()
}
-/// Discover installed document fonts off the GUI thread, only when the picker is opened.
#[cfg(not(target_arch = "wasm32"))]
-pub(crate) fn installed_font_files(ctx: &egui::Context) -> Option<Vec<pdfcraft_engine::text_fonts::FontFile>> {
+#[derive(Default)]
+struct FontScanCache {
+ files: Option<Vec<pdfcraft_engine::text_fonts::FontFile>>,
+ loading: bool,
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl FontScanCache {
+ fn begin(&mut self, reload: bool) -> bool {
+ if self.loading || (!reload && self.files.is_some()) {
+ return false;
+ }
+ self.loading = true;
+ self.files = None;
+ true
+ }
+
+ fn finish(&mut self, files: Vec<pdfcraft_engine::text_fonts::FontFile>) {
+ self.files = Some(files);
+ self.loading = false;
+ }
+}
+
+/// Discover installed document fonts off the GUI thread. Reload permits retrying a
+/// failed scan or discovering newly installed fonts without restarting the app.
+#[cfg(not(target_arch = "wasm32"))]
+pub(crate) fn installed_font_files(ctx: &egui::Context, reload: bool) -> Option<Vec<pdfcraft_engine::text_fonts::FontFile>> {
use std::sync::{Mutex, OnceLock};
- type Files = Arc<Mutex<Option<Vec<pdfcraft_engine::text_fonts::FontFile>>>>;
+ type Files = Arc<Mutex<FontScanCache>>;
static CACHE: OnceLock<Files> = OnceLock::new();
- let files = CACHE.get_or_init(|| {
- let files: Files = Arc::new(Mutex::new(None));
+ let files = CACHE.get_or_init(|| Arc::new(Mutex::new(FontScanCache::default())));
+ let start = files.lock().is_ok_and(|mut state| state.begin(reload));
+ if start {
let result = files.clone();
let ctx = ctx.clone();
if std::thread::Builder::new()
@@ -50,18 +76,17 @@ pub(crate) fn installed_font_files(ctx: &egui::Context) -> Option<Vec<pdfcraft_e
.spawn(move || {
let fonts = discover_fonts_safely(|| pdfcraft_engine::text_fonts::discover(&pdfcraft_engine::text_fonts::installed_directories()));
if let Ok(mut result) = result.lock() {
- *result = Some(fonts);
+ result.finish(fonts);
}
ctx.request_repaint();
})
.is_err()
&& let Ok(mut result) = files.lock()
{
- *result = Some(Vec::new());
+ result.finish(Vec::new());
}
- files
- });
- files.lock().ok().and_then(|f| f.clone())
+ }
+ files.lock().ok().and_then(|f| f.files.clone())
}
/// The picker for `purpose`: PDFs, and for Create and Insert also what they convert.
@@ -1187,6 +1212,23 @@ mod stem_tests {
#[cfg(all(test, not(target_arch = "wasm32")))]
mod font_scan_tests {
+ #[test]
+ fn completed_and_failed_font_scans_can_be_reloaded_without_duplicate_workers() {
+ let mut cache = super::FontScanCache::default();
+ assert!(cache.begin(false));
+ assert!(!cache.begin(true), "a reload during discovery must not start another worker");
+ cache.finish(Vec::new());
+ assert!(!cache.begin(false), "reuse a finished scan until explicitly reloaded");
+ assert!(cache.begin(true), "an empty or failed scan can be retried");
+ cache.finish(vec![pdfcraft_engine::text_fonts::FontFile {
+ path: "installed.ttf".into(),
+ family: "Installed".into(),
+ face: "Installed".into(),
+ }]);
+ assert!(cache.begin(true), "a populated scan can discover newly installed fonts");
+ assert!(cache.files.is_none());
+ }
+
#[test]
fn a_panicking_font_scan_finishes_with_an_empty_list() {
assert!(super::discover_fonts_safely(|| panic!("synthetic font scan failure")).is_empty());