From 097ff7c22d7e076e668778283c90b45253c48482 Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 25 Nov 2026 01:35:00 +0000 Subject: [PATCH] font-manager: copy installed families to the OS fonts folder, with a Craft-apps-only setting Each install through the font manager also makes the family available to all apps, unless the new "Keep fonts in Craft apps only" setting (in the font store's settings.json, off by default) is on. Toggling the setting runs as a worker job that withdraws every OS copy or copies every installed family. The family details show one status line: available to all apps, kept in Craft apps only, refused because of a conflict (naming the file), or not supported here. --- crates/font-manager/src/panel/app.rs | 52 ++++++++++- crates/font-manager/src/panel/browse.rs | 19 ++++ crates/font-manager/src/panel/details.rs | 37 +++++++- crates/font-manager/src/panel/jobs.rs | 37 ++++++-- crates/font-manager/src/store.rs | 110 +++++++++++++++++++++-- crates/font-manager/tests/flows.rs | 39 +++++++- crates/font-store/README.md | 1 + crates/font-store/src/store.rs | 24 ++++- 8 files changed, 293 insertions(+), 26 deletions(-) diff --git a/crates/font-manager/src/panel/app.rs b/crates/font-manager/src/panel/app.rs index 1d4be3c14..fa2676556 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 db59755d6..ab92fdafa 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 b4859ae33..14ca96996 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 2a688c02e..d93e3526e 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 9638a1f2c..dc1830ed8 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()) } @@ -160,6 +169,27 @@ pub trait Installer: Send + Sync { 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 { @@ -174,9 +204,9 @@ pub trait Installer: Send + Sync { /// 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, naming the fonts. It blocks (hashing, copying, a catalog - /// rescan): call it on a worker thread. - fn make_available(&self, _family: &str, _files: &[PathBuf]) -> Result<(), StoreError> { + /// 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())) } @@ -356,6 +386,31 @@ impl Installer for SuiteStore { 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() } @@ -364,9 +419,13 @@ impl Installer for SuiteStore { 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<(), StoreError> { + fn make_available(&self, family: &str, files: &[PathBuf]) -> Result { let (source, name) = self.found(family, files)?; - self.store.make_available(&source, &name).map(drop).map_err(err) + 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> { @@ -441,6 +500,9 @@ pub struct FakeStore { 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 { @@ -461,6 +523,8 @@ impl FakeStore { 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), } } @@ -496,6 +560,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) { @@ -720,13 +791,36 @@ impl Installer for FakeStore { self.available.lock().is_ok_and(|a| a.iter().any(|f| f.eq_ignore_ascii_case(family))) } - fn make_available(&self, family: &str, _files: &[PathBuf]) -> Result<(), StoreError> { + 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(()) + Ok(MadeAvailable::Done) } fn withdraw(&self, family: &str, _files: &[PathBuf]) -> Result, StoreError> { diff --git a/crates/font-manager/tests/flows.rs b/crates/font-manager/tests/flows.rs index 36e2b84f9..4ec21d439 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-store/README.md b/crates/font-store/README.md index 988a72a80..a89d03e4f 100644 --- a/crates/font-store/README.md +++ b/crates/font-store/README.md @@ -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. | diff --git a/crates/font-store/src/store.rs b/crates/font-store/src/store.rs index 648295095..9fe96f3e2 100644 --- a/crates/font-store/src/store.rs +++ b/crates/font-store/src/store.rs @@ -3,7 +3,7 @@ //! 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 @@ -230,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, @@ -241,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 } } } @@ -502,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();