mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:47:49 +00:00
Merge pull request #3424 from aiongg/os-share-existing
font-manager: choose per font whether installs go to the system fonts folder
This commit is contained in:
@@ -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`), 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 |
|
||||
| `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`) with its recorded choice (`available_to_all_choice`, `set_available_to_all_choice`, the default `craft_apps_only`, and `shares` for the two together). `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 |
|
||||
|
||||
@@ -23,7 +23,8 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages.
|
||||
English name or its own, "Japanese · 日本語"), script, source, and installed or not; each option
|
||||
with its count.
|
||||
- **Family cards**, one per row: the name, style count, category and source on one line with the
|
||||
card's state at its end (Install and Preview, Installed, a progress bar while downloading,
|
||||
card's state at its end (Install, whose menu installs for all apps or for Craft apps only, and
|
||||
Preview, Installed, a progress bar while downloading,
|
||||
Couldn't install with Retry, "Not curated" for a source the user added), and a large sample in
|
||||
the face below. The list is virtual: only the cards on screen are laid out, and their faces load
|
||||
as they come into view. With a preview service set, families that aren't installed draw from
|
||||
@@ -36,7 +37,8 @@ The layout follows Adobe Fonts' and Google Fonts' browse pages.
|
||||
sample from the index, by its `sample_script`; the alphabet; numerals), the sample text, and the
|
||||
size.
|
||||
- **Details sheet** over the list: every style in its own face with Install or Remove for each,
|
||||
Install all and Remove all, the source, scripts and languages, and what a preview downloads.
|
||||
Install all (with the same menu) and Remove all, whether the family is available to all apps
|
||||
with the switch that changes it, the source, scripts and languages, and what a preview downloads.
|
||||
With a preview service, styles not installed draw with its subsets: a static file's sample, and
|
||||
one subset of each variable file with every axis kept, drawn at each named instance and at the
|
||||
values of its axis sliders. The licence block shows the licence, copyright, designer and
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! the filters at the reading start, the family cards, and the details sheet over them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::craft_font_catalog::{FontEnv, Limits, Os};
|
||||
@@ -110,7 +111,8 @@ pub struct Options {
|
||||
/// A download, waiting for the user's consent or to be tried again.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Pending {
|
||||
Install(usize),
|
||||
/// A family, and whether to copy it into the OS user font folder ([`Request::Install`]).
|
||||
Install(usize, Option<bool>),
|
||||
/// One file of a family, by its path in the index.
|
||||
InstallFile(usize, String),
|
||||
Preview(usize),
|
||||
@@ -119,7 +121,7 @@ pub(crate) enum Pending {
|
||||
impl Pending {
|
||||
pub(crate) fn family(&self) -> usize {
|
||||
match self {
|
||||
Pending::Install(i) | Pending::InstallFile(i, _) | Pending::Preview(i) => *i,
|
||||
Pending::Install(i, _) | Pending::InstallFile(i, _) | Pending::Preview(i) => *i,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,6 +212,8 @@ pub struct FontsPanel {
|
||||
pub(crate) not_copied: HashMap<String, NotCopied>,
|
||||
/// "Keep fonts in Craft apps only" as last read or set.
|
||||
pub(crate) craft_apps_only: bool,
|
||||
/// Whether the start-up copy of families whose choice is the OS user font folder was queued.
|
||||
shared_at_start: bool,
|
||||
focused: bool,
|
||||
pub(crate) folder: Folder,
|
||||
/// The download consent as last read, and when.
|
||||
@@ -299,6 +303,7 @@ impl FontsPanel {
|
||||
catalog: options.catalog,
|
||||
craft_apps_only: options.installer.craft_apps_only(),
|
||||
installer: options.installer,
|
||||
shared_at_start: false,
|
||||
catalogue,
|
||||
query: Query::default(),
|
||||
show: Show::All,
|
||||
@@ -527,6 +532,7 @@ impl FontsPanel {
|
||||
self.skin = Skin { p: self.look.palette(&ctx), look: self.look.clone() };
|
||||
self.faces.begin_frame(&ctx);
|
||||
self.subsets.begin_frame(&ctx);
|
||||
self.share_installed_at_start(&ctx);
|
||||
self.poll_jobs();
|
||||
let focused = ctx.input(|i| i.focused);
|
||||
if focused && !self.focused {
|
||||
@@ -579,12 +585,12 @@ impl FontsPanel {
|
||||
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();
|
||||
Ok(Finished::Switched(copied)) => self.record_copy(&job.family, copied.map(Ok)),
|
||||
Ok(Finished::SharedAtStart(refused)) => {
|
||||
self.not_copied.extend(refused.into_iter().map(|(f, c)| (f.to_lowercase(), NotCopied::Refused(c))));
|
||||
}
|
||||
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)]));
|
||||
Err(e) if job.kind == Kind::SystemFonts => {
|
||||
self.notice = Some(fmt("Your system's fonts folder couldn't be updated: {error}", &[("error", &e.0)]));
|
||||
}
|
||||
Ok(Finished::Previewed(files)) => {
|
||||
self.failed.remove(&key);
|
||||
@@ -603,9 +609,9 @@ impl FontsPanel {
|
||||
c.index.families().iter().position(|f| f.source == job.source && f.family.eq_ignore_ascii_case(&job.family))
|
||||
});
|
||||
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::Install => Some(job.file.clone().map_or(Pending::Install(i, job.share), |path| Pending::InstallFile(i, path))),
|
||||
Kind::Preview => Some(Pending::Preview(i)),
|
||||
Kind::Remove | Kind::CraftAppsOnly => None,
|
||||
Kind::Remove | Kind::SystemFonts => None,
|
||||
});
|
||||
log::warn!("{} ({:?}): {e}", job.family, job.kind);
|
||||
self.failed.insert(key, Failure { kind: job.kind, error: e.0, retry });
|
||||
@@ -627,12 +633,31 @@ impl FontsPanel {
|
||||
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;
|
||||
/// Sets "Keep fonts in Craft apps only": what a plain Install does from now on. Installed
|
||||
/// families keep their choice.
|
||||
pub(crate) fn set_craft_apps_only(&mut self, on: bool) {
|
||||
self.notice =
|
||||
self.installer.set_craft_apps_only(on).err().map(|e| fmt("The Craft apps only setting couldn't be applied: {error}", &[("error", &e.0)]));
|
||||
self.craft_apps_only = self.installer.craft_apps_only();
|
||||
}
|
||||
|
||||
/// Makes a store family available to all apps or keeps it in Craft apps only, on the worker,
|
||||
/// and records that as its choice.
|
||||
pub(crate) fn set_available_to_all(&mut self, ctx: &Context, family: &str, files: Vec<PathBuf>, on: bool) {
|
||||
self.notice = None;
|
||||
self.jobs.start(ctx, Arc::clone(&self.installer), Arc::clone(&self.catalog), Request::CraftAppsOnly(on));
|
||||
let request = Request::AvailableToAll(family.to_owned(), files, on);
|
||||
self.jobs.start(ctx, Arc::clone(&self.installer), Arc::clone(&self.catalog), request);
|
||||
}
|
||||
|
||||
/// Once per start, copies the store families whose choice is the OS user font folder and
|
||||
/// that aren't all there yet (installed before installs copied, say), on the worker.
|
||||
fn share_installed_at_start(&mut self, ctx: &Context) {
|
||||
if std::mem::replace(&mut self.shared_at_start, true) {
|
||||
return;
|
||||
}
|
||||
if self.installer.available_to_all_supported() {
|
||||
self.jobs.start(ctx, Arc::clone(&self.installer), Arc::clone(&self.catalog), Request::ShareAtStart);
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_installed(&mut self) {
|
||||
@@ -758,7 +783,7 @@ impl FontsPanel {
|
||||
self.failed.remove(&family_key(&f.source, &f.family));
|
||||
}
|
||||
let request = match pending {
|
||||
Pending::Install(i) => Request::Install(index, i),
|
||||
Pending::Install(i, share) => Request::Install(index, i, share),
|
||||
Pending::InstallFile(i, path) => Request::InstallFile(index, i, path),
|
||||
Pending::Preview(i) => Request::Preview(index, i),
|
||||
};
|
||||
|
||||
@@ -112,11 +112,10 @@ impl FontsPanel {
|
||||
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);
|
||||
if ui.checkbox(&mut on, tl!("Keep fonts in Craft apps only")).changed() {
|
||||
self.set_craft_apps_only(on);
|
||||
}
|
||||
let note = tl!("Off: fonts you install here are also copied to your system's fonts folder, for all apps.");
|
||||
let note = tl!("Off: Install also copies fonts to your system's fonts folder, for all apps. Fonts already installed keep their own setting.");
|
||||
ui.add(egui::Label::new(egui::RichText::new(note).size(12.0).color(s.p.muted)).wrap());
|
||||
}
|
||||
|
||||
@@ -678,7 +677,7 @@ impl FontsPanel {
|
||||
Kind::Install => tl!("Installing"),
|
||||
Kind::Remove => tl!("Removing"),
|
||||
Kind::Preview => tl!("Downloading"),
|
||||
Kind::CraftAppsOnly => tl!("Updating system fonts"),
|
||||
Kind::SystemFonts => tl!("Updating system fonts"),
|
||||
};
|
||||
let text = match fraction {
|
||||
Some(f) => format!("{what} {}", fmt("{percent} %", &[("percent", &i18n::number((f * 100.0).round() as u64))])),
|
||||
@@ -701,7 +700,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"),
|
||||
Kind::SystemFonts => tl!("Couldn't update system fonts"),
|
||||
};
|
||||
widgets::label(ui, s, what, p.bad).on_hover_text(error);
|
||||
}
|
||||
@@ -718,10 +717,10 @@ impl FontsPanel {
|
||||
}
|
||||
CardState::Offer { preview } => {
|
||||
let Some(i) = index_position else { return };
|
||||
let install = widgets::button(ui, s, tl!("Install"), widgets::Kind::Secondary, h, 0.0);
|
||||
widgets::name(ui, &install, &fmt("Install {family}", &[("family", name)]));
|
||||
if install.clicked() {
|
||||
self.ask(&ctx, Pending::Install(i));
|
||||
let label = fmt("Install {family}", &[("family", name)]);
|
||||
let menu = self.installer.available_to_all_supported();
|
||||
if let Some(share) = widgets::install_button(ui, s, tl!("Install"), &label, widgets::Kind::Secondary, h, menu) {
|
||||
self.ask(&ctx, Pending::Install(i, share));
|
||||
}
|
||||
if preview {
|
||||
let button = widgets::link(ui, s, tl!("Preview"));
|
||||
|
||||
@@ -313,15 +313,23 @@ impl FontsPanel {
|
||||
Kind::Install => tl!("Installing"),
|
||||
Kind::Remove => tl!("Removing"),
|
||||
Kind::Preview => tl!("Downloading"),
|
||||
Kind::CraftAppsOnly => tl!("Updating system fonts"),
|
||||
Kind::SystemFonts => tl!("Updating system fonts"),
|
||||
};
|
||||
self.progress(ui, s, what, *fraction, 220.0);
|
||||
}
|
||||
_ => {
|
||||
if all_installed {
|
||||
widgets::badge(ui, s, if on_system { tl!("Installed on this system") } else { tl!("Installed") }, s.p.good, true);
|
||||
} else if widgets::button(ui, s, tl!("Install all"), widgets::Kind::Primary, s.h(), 0.0).clicked() {
|
||||
self.ask(&ctx, Pending::Install(i));
|
||||
} else if let Some(share) = widgets::install_button(
|
||||
ui,
|
||||
s,
|
||||
tl!("Install all"),
|
||||
tl!("Install all"),
|
||||
widgets::Kind::Primary,
|
||||
s.h(),
|
||||
self.installer.available_to_all_supported(),
|
||||
) {
|
||||
self.ask(&ctx, Pending::Install(i, share));
|
||||
}
|
||||
if !store.is_empty() && widgets::button(ui, s, tl!("Remove all"), widgets::Kind::Danger, s.h(), 0.0).clicked() {
|
||||
self.remove(&ctx, &family.family, &store, true);
|
||||
@@ -359,7 +367,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"),
|
||||
Kind::SystemFonts => tl!("Couldn't update system fonts"),
|
||||
};
|
||||
let buttons: &[&str] = if failure.retry.is_some() { &[tl!("Retry")] } else { &[] };
|
||||
let mut retry = false;
|
||||
@@ -503,23 +511,35 @@ 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]) {
|
||||
/// Whether the family's store fonts are in the OS user font folder for all apps, or why not,
|
||||
/// and the action that changes it.
|
||||
fn system_fonts_line(&mut 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 available = not_here.is_none() && self.installer.is_available_to_all(family, &files);
|
||||
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) {
|
||||
} else if available {
|
||||
(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());
|
||||
let switch = self.installer.available_to_all_supported() && self.jobs.of("", family).is_none();
|
||||
let size = vec2(ui.available_width(), ui.spacing().interact_size.y);
|
||||
ui.allocate_ui_with_layout(size, direction::row(ui).with_main_wrap(true), |ui| {
|
||||
ui.add(egui::Label::new(RichText::new(text).size(12.5).color(colour)).wrap());
|
||||
if switch {
|
||||
let action = if available { tl!("Keep in Craft apps only") } else { tl!("Make available to all apps") };
|
||||
if widgets::link(ui, s, action).clicked() {
|
||||
self.set_available_to_all(ui.ctx(), family, files.clone(), !available);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn progress(&self, ui: &mut Ui, s: &Skin, what: &str, fraction: Option<f32>, width: f32) {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Installs, removals, preview downloads and the "Keep fonts in Craft apps only" setting, one at
|
||||
//! a time on a worker thread.
|
||||
//! Installs, removals, preview downloads and copies to the OS user font folder, one at a time on
|
||||
//! a worker thread.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
|
||||
@@ -25,8 +26,9 @@ pub enum Kind {
|
||||
Install,
|
||||
Remove,
|
||||
Preview,
|
||||
/// Changing "Keep fonts in Craft apps only"; it has no family.
|
||||
CraftAppsOnly,
|
||||
/// Copying to or withdrawing from the OS user font folder: a family's switch, or the start-up
|
||||
/// copy, which has no family.
|
||||
SystemFonts,
|
||||
}
|
||||
|
||||
pub struct Running {
|
||||
@@ -36,6 +38,8 @@ pub struct Running {
|
||||
pub kind: Kind,
|
||||
/// One file's index path or store path, when the job is for one style.
|
||||
pub file: Option<String>,
|
||||
/// An install's choice of the OS user font folder (see [`Request::Install`]).
|
||||
pub share: Option<bool>,
|
||||
pub progress: Progress,
|
||||
}
|
||||
|
||||
@@ -51,8 +55,10 @@ pub enum Finished {
|
||||
Installed(Option<Result<MadeAvailable, StoreError>>),
|
||||
Removed,
|
||||
Previewed(Vec<Downloaded>),
|
||||
/// The families a conflict kept out of the OS user font folder.
|
||||
CraftAppsOnly(Vec<(String, Vec<Conflict>)>),
|
||||
/// What a family's switch did: copied it, with the outcome, or withdrew it (`None`).
|
||||
Switched(Option<MadeAvailable>),
|
||||
/// The families a conflict kept out of the OS user font folder at start.
|
||||
SharedAtStart(Vec<(String, Vec<Conflict>)>),
|
||||
}
|
||||
|
||||
enum Msg {
|
||||
@@ -61,15 +67,20 @@ enum Msg {
|
||||
}
|
||||
|
||||
pub enum Request {
|
||||
/// A family of the index, by position.
|
||||
Install(Arc<Index>, usize),
|
||||
/// A family of the index, by position, and whether to copy it into the OS user font folder
|
||||
/// (and record that as its choice); `None` keeps its recorded choice, else takes the default.
|
||||
Install(Arc<Index>, usize, Option<bool>),
|
||||
/// One file of a family of the index, by its path in the index.
|
||||
InstallFile(Arc<Index>, usize, String),
|
||||
Remove(RemoveRequest),
|
||||
/// A family of the index, by position.
|
||||
Preview(Arc<Index>, usize),
|
||||
/// Sets "Keep fonts in Craft apps only".
|
||||
CraftAppsOnly(bool),
|
||||
/// Records a store family's choice, by name and store files, then copies it into the OS user
|
||||
/// font folder (`true`) or withdraws it.
|
||||
AvailableToAll(String, Vec<PathBuf>, bool),
|
||||
/// Copies the store families whose choice is the OS user font folder and that aren't all
|
||||
/// there yet: those installed before installs copied, or whose copy failed.
|
||||
ShareAtStart,
|
||||
}
|
||||
|
||||
pub struct Jobs {
|
||||
@@ -101,24 +112,20 @@ 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. An
|
||||
/// install also copies the family into the OS user font folder, unless the user keeps fonts in
|
||||
/// Craft apps only.
|
||||
/// install also records the family's choice and copies it into the OS user font folder when
|
||||
/// that is the choice.
|
||||
pub fn start(&mut self, ctx: &egui::Context, installer: Arc<dyn Installer>, catalog: Arc<Catalog>, request: Request) {
|
||||
let id = self.next;
|
||||
self.next += 1;
|
||||
let share = if let Request::Install(_, _, share) = &request { *share } else { None };
|
||||
let (source, family, kind, file, total) = match &request {
|
||||
Request::Install(index, i) | Request::Preview(index, i) => {
|
||||
Request::Install(index, i, _) | Request::Preview(index, i) => {
|
||||
let Some(f) = index.families().get(*i) else { return };
|
||||
let kind = if matches!(request, Request::Install(..)) { Kind::Install } else { Kind::Preview };
|
||||
(f.source.clone(), f.family.clone(), kind, None, f.size())
|
||||
@@ -132,9 +139,10 @@ 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),
|
||||
Request::AvailableToAll(family, ..) => (String::new(), family.clone(), Kind::SystemFonts, None, 0),
|
||||
Request::ShareAtStart => (String::new(), String::new(), Kind::SystemFonts, None, 0),
|
||||
};
|
||||
self.running.insert(id, Running { source, family, kind, file, progress: Progress { done: 0, total } });
|
||||
self.running.insert(id, Running { source, family, kind, file, share, progress: Progress { done: 0, total } });
|
||||
let tx = self.tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
let task: Task = Box::new(move || {
|
||||
@@ -143,18 +151,28 @@ 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 copy = |name: &str, share: Option<bool>| {
|
||||
if !installer.available_to_all_supported() {
|
||||
return Ok(Finished::Installed(None));
|
||||
}
|
||||
let share = share.unwrap_or_else(|| installer.shares(name, &[]));
|
||||
installer.set_available_to_all_choice(name, &[], share)?;
|
||||
Ok(Finished::Installed(share.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(|()| copy(&f.family))),
|
||||
Request::Install(index, i, share) => {
|
||||
family(&index, i).and_then(|f| installer.install(&index, &f, &mut progress).and_then(|()| copy(&f.family, share)))
|
||||
}
|
||||
Request::InstallFile(index, i, path) => {
|
||||
family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress).map(|()| copy(&f.family)))
|
||||
family(&index, i).and_then(|f| installer.install_file(&index, &f, &path, &mut progress).and_then(|()| copy(&f.family, None)))
|
||||
}
|
||||
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),
|
||||
Request::AvailableToAll(name, files, on) => installer.set_available_to_all_choice(&name, &files, on).and_then(|()| {
|
||||
if on { installer.make_available(&name, &files).map(Some) } else { installer.withdraw(&name, &files).map(|_| None) }
|
||||
.map(Finished::Switched)
|
||||
}),
|
||||
Request::ShareAtStart => share_at_start(installer.as_ref()).map(Finished::SharedAtStart),
|
||||
};
|
||||
if matches!(result, Ok(Finished::Installed(_) | Finished::Removed)) {
|
||||
catalog.rescan();
|
||||
@@ -192,3 +210,18 @@ impl Jobs {
|
||||
done
|
||||
}
|
||||
}
|
||||
|
||||
/// The work of [`Request::ShareAtStart`]: returns the families a conflict refused.
|
||||
fn share_at_start(installer: &dyn Installer) -> Result<Vec<(String, Vec<Conflict>)>, StoreError> {
|
||||
let mut refused = Vec::new();
|
||||
for (family, files) in installer.store_families() {
|
||||
let there = installer.is_available_to_all(&family, &files) && installer.not_yet_available(&family, &files).is_empty();
|
||||
if there || !installer.shares(&family, &files) {
|
||||
continue;
|
||||
}
|
||||
if let MadeAvailable::Refused(conflicts) = installer.make_available(&family, &files)? {
|
||||
refused.push((family, conflicts));
|
||||
}
|
||||
}
|
||||
Ok(refused)
|
||||
}
|
||||
|
||||
@@ -124,6 +124,51 @@ pub fn button(ui: &mut Ui, s: &Skin, text: &str, kind: Kind, height: f32, min_wi
|
||||
if enabled { resp.on_hover_cursor(CursorIcon::PointingHand) } else { resp }
|
||||
}
|
||||
|
||||
/// An Install button, `name` for screen readers. With `menu`, a split button whose menu chooses
|
||||
/// where the fonts go. `None` when not clicked; `Some(None)` for the button itself (the family's
|
||||
/// choice, else the default), `Some(Some(true))` for all apps, `Some(Some(false))` for Craft apps
|
||||
/// only.
|
||||
pub fn install_button(ui: &mut Ui, s: &Skin, text: &str, name: &str, kind: Kind, height: f32, menu: bool) -> Option<Option<bool>> {
|
||||
use crate::panel::i18n::tl;
|
||||
use craft_ui::menu::{MenuItem, MenuLabels, SplitHit};
|
||||
if !menu {
|
||||
let resp = button(ui, s, text, kind, height, 0.0);
|
||||
self::name(ui, &resp, name);
|
||||
return resp.clicked().then_some(None);
|
||||
}
|
||||
let items = [MenuItem::new("all", tl!("Install for all apps")), MenuItem::new("craft", tl!("Install for Craft apps only"))];
|
||||
let labels = MenuLabels { more: tl!("More options").to_owned(), more_for: tl!("More {action} options").to_owned() };
|
||||
let text = if s.look.caps { text.to_uppercase() } else { text.to_owned() };
|
||||
let p = s.p;
|
||||
let (fill, hover, stroke, ink) = match kind {
|
||||
// The background's colour around each half parts them.
|
||||
Kind::Primary => (p.invert_bg, p.invert_bg.gamma_multiply(0.82), Stroke::new(1.0, p.bg), p.invert_fg),
|
||||
Kind::Secondary | Kind::Danger => (Color32::TRANSPARENT, p.sunken, Stroke::new(1.0, p.line_strong), p.ink),
|
||||
};
|
||||
let hit = ui.scope(|ui| {
|
||||
let style = ui.style_mut();
|
||||
style.override_font_id = Some(FontId::new(if s.look.caps { 11.0 } else { 13.0 }, s.look.button.clone()));
|
||||
style.spacing.interact_size.y = height;
|
||||
style.spacing.button_padding.x = 14.0;
|
||||
let w = &mut style.visuals.widgets;
|
||||
for (v, fill) in [(&mut w.inactive, fill), (&mut w.hovered, hover), (&mut w.active, hover)] {
|
||||
v.weak_bg_fill = fill;
|
||||
v.bg_stroke = stroke;
|
||||
v.fg_stroke = Stroke::new(1.0, ink);
|
||||
v.corner_radius = s.look.corner;
|
||||
v.expansion = 0.0;
|
||||
}
|
||||
// The chevron's colour.
|
||||
w.noninteractive.fg_stroke.color = ink;
|
||||
style.visuals.override_text_color = None;
|
||||
craft_ui::menu::split_named(ui, &text, name, &items, &labels)
|
||||
});
|
||||
match hit.inner? {
|
||||
SplitHit::Primary => Some(None),
|
||||
SplitHit::Item(id) => Some(Some(id == "all")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A text-only action in the accent colour: "Clear filters", "Retry".
|
||||
pub fn link(ui: &mut Ui, s: &Skin, text: &str) -> Response {
|
||||
let galley = s.label_galley(ui, text, s.p.accent_ink);
|
||||
|
||||
@@ -175,21 +175,44 @@ pub trait Installer: Send + Sync {
|
||||
(!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.
|
||||
/// Whether the user keeps store fonts in Craft apps only by default (a setting of the font
|
||||
/// store, off by default): what a plain Install does with a family that has no choice of its
|
||||
/// own ([`Installer::available_to_all_choice`]).
|
||||
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<Vec<(String, Vec<Conflict>)>, StoreError> {
|
||||
/// Sets [`Installer::craft_apps_only`], as the user's own action. Installed families keep
|
||||
/// their choice and their copies.
|
||||
fn set_craft_apps_only(&self, _on: bool) -> Result<(), StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
|
||||
/// The installed store families, by name, each with its folder in the store (which tells
|
||||
/// families of the same name from different sources apart, as `files` below).
|
||||
fn store_families(&self) -> Vec<(String, Vec<PathBuf>)> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// The user's choice for the store family `family`: available to all apps (`true`) or kept
|
||||
/// in Craft apps only (`false`). `None` when none is recorded (installed before the choice
|
||||
/// existed, or by an agent): [`Installer::craft_apps_only`] decides.
|
||||
fn available_to_all_choice(&self, _family: &str, _files: &[PathBuf]) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Records [`Installer::available_to_all_choice`], as the user's own action. It neither copies
|
||||
/// nor withdraws the family.
|
||||
fn set_available_to_all_choice(&self, _family: &str, _files: &[PathBuf], _on: bool) -> Result<(), StoreError> {
|
||||
Err(StoreError(NOT_HERE.into()))
|
||||
}
|
||||
|
||||
/// Whether the store family `family` belongs in the OS user font folder: its own choice, else
|
||||
/// the default; never where families can't be copied there.
|
||||
fn shares(&self, family: &str, files: &[PathBuf]) -> bool {
|
||||
self.available_to_all_supported() && self.available_to_all_choice(family, files).unwrap_or(!self.craft_apps_only())
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -254,14 +277,18 @@ impl SuiteStore {
|
||||
/// 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)> {
|
||||
self.installed_entry(family, files).map(|f| (f.source, f.family))
|
||||
}
|
||||
|
||||
fn installed_entry(&self, family: &str, files: &[PathBuf]) -> Option<craft_font_store::InstalledFamily> {
|
||||
let dir = self.store.dir();
|
||||
let installed = self.store.installed();
|
||||
let mut installed = self.store.installed();
|
||||
let lower = family.to_lowercase();
|
||||
installed
|
||||
let pos = installed
|
||||
.iter()
|
||||
.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()))
|
||||
.position(|f| files.iter().any(|path| path.starts_with(dir.join(&f.dir))))
|
||||
.or_else(|| installed.iter().position(|f| f.family.to_lowercase() == lower))?;
|
||||
Some(installed.swap_remove(pos))
|
||||
}
|
||||
|
||||
fn found(&self, family: &str, files: &[PathBuf]) -> Result<(String, String), StoreError> {
|
||||
@@ -394,21 +421,22 @@ impl Installer for SuiteStore {
|
||||
self.store.craft_apps_only()
|
||||
}
|
||||
|
||||
fn set_craft_apps_only(&self, on: bool) -> Result<Vec<(String, Vec<Conflict>)>, 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 set_craft_apps_only(&self, on: bool) -> Result<(), StoreError> {
|
||||
self.store.set_craft_apps_only(on).map_err(err)
|
||||
}
|
||||
|
||||
fn store_families(&self) -> Vec<(String, Vec<PathBuf>)> {
|
||||
let dir = self.store.dir();
|
||||
self.store.installed().into_iter().map(|f| (f.family, vec![dir.join(&f.dir)])).collect()
|
||||
}
|
||||
|
||||
fn available_to_all_choice(&self, family: &str, files: &[PathBuf]) -> Option<bool> {
|
||||
self.installed_entry(family, files)?.available_to_all
|
||||
}
|
||||
|
||||
fn set_available_to_all_choice(&self, family: &str, files: &[PathBuf], on: bool) -> Result<(), StoreError> {
|
||||
let (source, name) = self.found(family, files)?;
|
||||
self.store.set_available_to_all_choice(&source, &name, on).map_err(err)
|
||||
}
|
||||
|
||||
fn is_available_to_all(&self, family: &str, files: &[PathBuf]) -> bool {
|
||||
@@ -502,6 +530,8 @@ pub struct FakeStore {
|
||||
/// Families made available to all apps, by name.
|
||||
available: Mutex<Vec<String>>,
|
||||
craft_apps_only: AtomicBool,
|
||||
/// Families' recorded choices, by lower-case name.
|
||||
choices: Mutex<HashMap<String, bool>>,
|
||||
/// What the next [`Installer::make_available`] refuses with.
|
||||
refusal: Mutex<Option<Vec<Conflict>>>,
|
||||
}
|
||||
@@ -525,6 +555,7 @@ impl FakeStore {
|
||||
held: (Mutex::new(false), Condvar::new()),
|
||||
available: Mutex::new(Vec::new()),
|
||||
craft_apps_only: AtomicBool::new(false),
|
||||
choices: Mutex::new(HashMap::new()),
|
||||
refusal: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
@@ -672,6 +703,7 @@ impl Installer for FakeStore {
|
||||
}
|
||||
if request.whole {
|
||||
self.available.lock().map_err(err)?.retain(|f| !f.eq_ignore_ascii_case(&request.family));
|
||||
self.choices.lock().map_err(err)?.remove(&request.family.to_lowercase());
|
||||
}
|
||||
for file in &request.files {
|
||||
std::fs::remove_file(file).map_err(err)?;
|
||||
@@ -796,20 +828,25 @@ impl Installer for FakeStore {
|
||||
self.craft_apps_only.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn set_craft_apps_only(&self, on: bool) -> Result<Vec<(String, Vec<Conflict>)>, StoreError> {
|
||||
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)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The folders in its folder but the preview cache, as families.
|
||||
fn store_families(&self) -> Vec<(String, Vec<PathBuf>)> {
|
||||
let previews = self.preview_cache();
|
||||
let dirs = std::fs::read_dir(&self.dir).into_iter().flatten().flatten().filter(|e| e.path().is_dir() && Some(e.path()) != previews);
|
||||
dirs.map(|e| (e.file_name().to_string_lossy().into_owned(), vec![e.path()])).collect()
|
||||
}
|
||||
|
||||
fn available_to_all_choice(&self, family: &str, _files: &[PathBuf]) -> Option<bool> {
|
||||
self.choices.lock().ok()?.get(&family.to_lowercase()).copied()
|
||||
}
|
||||
|
||||
fn set_available_to_all_choice(&self, family: &str, _files: &[PathBuf], on: bool) -> Result<(), StoreError> {
|
||||
self.choices.lock().map_err(err)?.insert(family.to_lowercase(), on);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_available(&self, family: &str, _files: &[PathBuf]) -> Result<MadeAvailable, StoreError> {
|
||||
|
||||
@@ -60,6 +60,17 @@ fn setup_with(
|
||||
settings: Settings,
|
||||
runner: Runner,
|
||||
fonts: impl Fn(&egui::Context) + 'static,
|
||||
) -> (Harness<'static, FontsPanel>, Arc<FakeStore>) {
|
||||
setup_seeded(name, settings, runner, fonts, |_| {})
|
||||
}
|
||||
|
||||
/// [`setup_with`] after `seed` filled the store folder, as families installed by an earlier run.
|
||||
fn setup_seeded(
|
||||
name: &str,
|
||||
settings: Settings,
|
||||
runner: Runner,
|
||||
fonts: impl Fn(&egui::Context) + 'static,
|
||||
seed: impl Fn(&std::path::Path),
|
||||
) -> (Harness<'static, FontsPanel>, Arc<FakeStore>) {
|
||||
let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("flows").join(name);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
@@ -68,9 +79,7 @@ fn setup_with(
|
||||
std::fs::write(system.join("Ubuntu-Light.ttf"), epaint_default_fonts::UBUNTU_LIGHT).unwrap();
|
||||
let store_dir = root.join("store");
|
||||
std::fs::create_dir_all(&store_dir).unwrap();
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), font_store: Some(store_dir.clone()), ..FontEnv::default() };
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.rescan();
|
||||
seed(&store_dir);
|
||||
let files = HashMap::from([
|
||||
(HACK.to_owned(), epaint_default_fonts::HACK_REGULAR.to_vec()),
|
||||
(UBUNTU.to_owned(), epaint_default_fonts::UBUNTU_LIGHT.to_vec()),
|
||||
@@ -80,7 +89,21 @@ fn setup_with(
|
||||
Some(checkout) => store.serving(checkout),
|
||||
None => store,
|
||||
});
|
||||
let options = Options { catalog, installer: store.clone(), index: Ok(index()), runner };
|
||||
(open(&root, store.clone(), settings, runner, fonts), store)
|
||||
}
|
||||
|
||||
/// The panel over the system under `root` and `store`, as at a start of the app.
|
||||
fn open(
|
||||
root: &std::path::Path,
|
||||
store: Arc<FakeStore>,
|
||||
settings: Settings,
|
||||
runner: Runner,
|
||||
fonts: impl Fn(&egui::Context) + 'static,
|
||||
) -> Harness<'static, FontsPanel> {
|
||||
let env = FontEnv { os: Os::Unix, root: root.to_owned(), font_store: Some(root.join("store")), ..FontEnv::default() };
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.rescan();
|
||||
let options = Options { catalog, installer: store, index: Ok(index()), runner };
|
||||
let app = FontsPanel::new(options, settings);
|
||||
let mut harness = Harness::builder()
|
||||
.with_size([1120.0, 678.0])
|
||||
@@ -92,7 +115,7 @@ fn setup_with(
|
||||
})
|
||||
.build_ui_state(|ui, app: &mut FontsPanel| app.ui(ui), app);
|
||||
harness.run_steps(4);
|
||||
(harness, store)
|
||||
harness
|
||||
}
|
||||
|
||||
fn settle(h: &mut Harness<'_, FontsPanel>) {
|
||||
@@ -234,20 +257,47 @@ fn installs_are_copied_to_the_system_fonts_folder_unless_kept_in_craft_apps() {
|
||||
assert!(has_installed(&h, "Hack"));
|
||||
assert!(h.query_by_label_contains("/fonts/Hack-Regular.ttf already has the font name Hack-Regular").is_some());
|
||||
|
||||
// The setting decides what Install does from now on; Hack stays as it is.
|
||||
h.key_press(egui::Key::Escape);
|
||||
settle(&mut h);
|
||||
craft_apps_only_switch(&mut h);
|
||||
assert!(store.craft_apps_only());
|
||||
assert_eq!(store.calls().len(), 2);
|
||||
click(&mut h, "Hack");
|
||||
click(&mut h, "Remove all");
|
||||
click(&mut h, "Install all");
|
||||
assert_eq!(store.calls()[2..], [Call::Remove("Hack".into()), Call::Install("Hack".into())]);
|
||||
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");
|
||||
// The details switch copies it after all.
|
||||
click(&mut h, "Make available to all apps");
|
||||
assert_eq!(store.calls().last(), Some(&Call::MakeAvailable("Hack".into())));
|
||||
assert!(h.query_by_label("Available to all apps").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_family_keeps_its_system_fonts_choice_across_starts() {
|
||||
// Ubuntu, installed by an earlier run with no choice recorded, follows the default.
|
||||
let seed = |dir: &std::path::Path| {
|
||||
std::fs::create_dir_all(dir.join("Ubuntu")).unwrap();
|
||||
std::fs::write(dir.join("Ubuntu/Ubuntu-Light.ttf"), epaint_default_fonts::UBUNTU_LIGHT).unwrap();
|
||||
};
|
||||
let (mut h, store) = setup_seeded("os-choice", Settings::default(), Runner::Inline, |_| {}, seed);
|
||||
assert_eq!(store.calls(), [Call::MakeAvailable("Ubuntu".into())]);
|
||||
|
||||
allow(&mut h);
|
||||
click(&mut h, "Hack");
|
||||
click(&mut h, "More install all options");
|
||||
click(&mut h, "Install for Craft apps only");
|
||||
assert_eq!(store.calls()[1..], [Call::Install("Hack".into())]);
|
||||
assert!(h.query_by_label("Kept in Craft apps only").is_some());
|
||||
|
||||
// The next start copies neither: Hack is kept in Craft apps, Ubuntu is there already.
|
||||
let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("flows").join("os-choice");
|
||||
let _h = open(&root, store.clone(), Settings::default(), Runner::Inline, |_| {});
|
||||
assert_eq!(store.calls().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_fonts_cannot_be_removed() {
|
||||
let (mut h, store) = setup("system", Settings::default());
|
||||
|
||||
@@ -30,7 +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. |
|
||||
| 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). It is the default for families with no choice of their own (`available_to_all` below): while it is off, craft-font-manager copies each family it installs into the OS user font folder. The setting only records the choice; installed families keep theirs. |
|
||||
| Mirror first | With a service set, an install requests `<service>/v1/files/<sha256>` for each font file and `<service>/v1/licences/<sha256>` 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/<version>`. Timeouts: 15 s to connect, 30 s to the response headers, 10 minutes per file. |
|
||||
|
||||
@@ -112,7 +112,7 @@ language-packs.json which Language packs are installed
|
||||
|
||||
A Google Fonts family's folder is google/fonts' own folder name (`lato/`); another source's is `<source>/<family>` (`notofonts/noto-sans-cjk-jp/`, `user-fonts-example-org-myfonts-bfeb06e2/some-family/`).
|
||||
|
||||
`manifest.json` lists each installed family: its name, source, folder, licence and licence file, and per file its name, path in its repository, size, sha256, the index commit it came from, and its PostScript names. An entry is one family of one source, so the same name from two sources is two entries. A manifest that can't be read is moved aside to `manifest.json.bad` and counts as empty.
|
||||
`manifest.json` lists each installed family: its name, source, folder, licence and licence file, per file its name, path in its repository, size, sha256, the index commit it came from, and its PostScript names, and `available_to_all`: the user's choice to copy the family into the OS user font folder (`true`) or keep it in Craft apps only (`false`), absent when none is recorded. `set_available_to_all_choice(source, name, on)` records it (user only); it doesn't copy or withdraw. An entry is one family of one source, so the same name from two sources is two entries. A manifest that can't be read is moved aside to `manifest.json.bad` and counts as empty.
|
||||
|
||||
| Call | What it does |
|
||||
|---|---|
|
||||
|
||||
@@ -193,6 +193,11 @@ pub struct InstalledFamily {
|
||||
pub license_file: Option<String>,
|
||||
/// The installed files: all of the family's, or some faces.
|
||||
pub files: Vec<InstalledFile>,
|
||||
/// The user's choice for this family: copied into the OS user font folder for all apps
|
||||
/// (`true`) or kept in Craft apps only (`false`). `None` when none is recorded (installed
|
||||
/// before the choice existed, or by an agent): [`FontStore::craft_apps_only`] decides.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub available_to_all: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
@@ -506,15 +511,16 @@ 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.
|
||||
/// Whether the user keeps store fonts in Craft apps only by default. 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, unless the user chose otherwise
|
||||
/// for that family ([`InstalledFamily::available_to_all`]).
|
||||
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.
|
||||
/// Sets [`FontStore::craft_apps_only`], from the user's own action. It only records the choice;
|
||||
/// installed families keep theirs. [`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);
|
||||
@@ -522,6 +528,20 @@ impl FontStore {
|
||||
self.change_settings(|s| s.craft_apps_only = on)
|
||||
}
|
||||
|
||||
/// Records the user's choice for the installed family ([`InstalledFamily::available_to_all`]).
|
||||
/// It only records it: the caller copies or withdraws the family. [`Error::NotAllowed`] for an
|
||||
/// agent, [`Error::NotInstalled`] for a family that isn't installed.
|
||||
pub fn set_available_to_all_choice(&self, source: &str, name: &str, on: bool) -> Result<(), Error> {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
let _lock = self.lock()?;
|
||||
let mut manifest = self.read_manifest();
|
||||
let entry = manifest.families.iter_mut().find(|f| f.is(source, name)).ok_or_else(|| Error::NotInstalled(name.to_string()))?;
|
||||
entry.available_to_all = Some(on);
|
||||
self.write_manifest(&manifest)
|
||||
}
|
||||
|
||||
fn change_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), Error> {
|
||||
let _lock = self.lock()?;
|
||||
let mut settings = self.settings();
|
||||
@@ -1061,6 +1081,7 @@ fn merge_entry(manifest: &mut Manifest, index: &Index, family: &Family, files: &
|
||||
license: family.license.clone(),
|
||||
license_file: None,
|
||||
files: Vec::new(),
|
||||
available_to_all: None,
|
||||
});
|
||||
manifest.families.len() - 1
|
||||
}
|
||||
@@ -1090,7 +1111,15 @@ fn merge_entry(manifest: &mut Manifest, index: &Index, family: &Family, files: &
|
||||
|
||||
impl InstalledFamily {
|
||||
fn empty() -> Self {
|
||||
Self { family: String::new(), source: String::new(), dir: String::new(), license: String::new(), license_file: None, files: Vec::new() }
|
||||
Self {
|
||||
family: String::new(),
|
||||
source: String::new(),
|
||||
dir: String::new(),
|
||||
license: String::new(),
|
||||
license_file: None,
|
||||
files: Vec::new(),
|
||||
available_to_all: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is the family `name` (ignoring case) from `source`.
|
||||
|
||||
@@ -517,8 +517,8 @@ impl FontStore {
|
||||
|
||||
/// 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.
|
||||
/// files whose copy is older than the store's, or whose copy or identical system file is gone
|
||||
/// (the user deleted it, say). Empty for a family that isn't available.
|
||||
pub fn pending_files(&self, source: &str, name: &str) -> Vec<String> {
|
||||
let Some(ledger) = self.cached_ledger() else { return Vec::new() };
|
||||
let Some(listed) = ledger.family(source, name) else { return Vec::new() };
|
||||
@@ -526,12 +526,7 @@ impl FontStore {
|
||||
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()))
|
||||
})
|
||||
.filter(|f| !listed.files.iter().any(|x| x.store_file == f.name && x.sha256 == f.sha256 && std::fs::metadata(&x.path).is_ok()))
|
||||
.map(|f| f.name.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1625,6 +1625,21 @@ mod store {
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_copy_is_pending_and_copied_again() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, _shared) = shared_store(&server, "os-fonts-deleted");
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
std::fs::remove_file(&copies[0]).unwrap();
|
||||
assert_eq!(store.pending_files(GOOGLE_FONTS, "Test Sans").len(), 1);
|
||||
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());
|
||||
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();
|
||||
|
||||
+29
-4
@@ -109,12 +109,23 @@ pub fn overflow(ui: &mut Ui, items: &[MenuItem], labels: &MenuLabels) -> Option<
|
||||
items_of(&hit, items)
|
||||
}
|
||||
|
||||
/// Width of a split button's chevron half, as a share of the control height, so it follows
|
||||
/// density.
|
||||
const CHEVRON_WIDTH_PER_HEIGHT: f32 = 0.8;
|
||||
|
||||
/// A primary action with a chevron beside it.
|
||||
///
|
||||
/// The two halves are two controls. Pressing the label does the thing. Pressing
|
||||
/// the chevron offers the variations. One control that did both would leave a
|
||||
/// person guessing which half they had hit.
|
||||
pub fn split(ui: &mut Ui, primary: &str, items: &[MenuItem], labels: &MenuLabels) -> Option<SplitHit> {
|
||||
split_named(ui, primary, primary, items, labels)
|
||||
}
|
||||
|
||||
/// [`split`] for a primary action whose label leaves out what it acts on, as on each card of a
|
||||
/// list. `name` is the button's accessible name ("Install Hack" for "Install"), and starts with
|
||||
/// the label.
|
||||
pub fn split_named(ui: &mut Ui, primary: &str, name: &str, items: &[MenuItem], labels: &MenuLabels) -> Option<SplitHit> {
|
||||
let mut hit = None;
|
||||
ui.horizontal(|ui| {
|
||||
// The halves touch, so they read as one control with two parts. Square
|
||||
@@ -133,14 +144,28 @@ pub fn split(ui: &mut Ui, primary: &str, items: &[MenuItem], labels: &MenuLabels
|
||||
(egui::CornerRadius { ne: 0, se: 0, ..radius }, egui::CornerRadius { nw: 0, sw: 0, ..radius })
|
||||
};
|
||||
let label = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
|
||||
if ui.add(egui::Button::new(primary).corner_radius(if backwards { inner } else { outer })).clicked() {
|
||||
let button = ui.add(egui::Button::new(primary).corner_radius(if backwards { inner } else { outer }));
|
||||
if name != primary {
|
||||
button.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, button.enabled(), name));
|
||||
}
|
||||
if button.clicked() {
|
||||
*hit = Some(SplitHit::Primary);
|
||||
}
|
||||
};
|
||||
let chevron = |ui: &mut Ui, hit: &mut Option<SplitHit>| {
|
||||
// Room for the triangle, which is painted rather than typed.
|
||||
let more = ui.add(egui::Button::new(" ").corner_radius(if backwards { outer } else { inner }));
|
||||
crate::buttons::chevron(ui, more.rect, ui.visuals().text_color());
|
||||
// Just room for the painted triangle, whatever padding and font the
|
||||
// caller's style gives the label half.
|
||||
let more = ui
|
||||
.scope(|ui| {
|
||||
ui.spacing_mut().button_padding.x = 0.0;
|
||||
let corner = if backwards { outer } else { inner };
|
||||
let width = ui.spacing().interact_size.y * CHEVRON_WIDTH_PER_HEIGHT;
|
||||
ui.add(egui::Button::new("").min_size(egui::vec2(width, 0.0)).corner_radius(corner))
|
||||
})
|
||||
.inner;
|
||||
// `chevron` paints 9 points in from the rect's right edge; centre it.
|
||||
let at = more.rect.translate(egui::vec2(9.0 - more.rect.width() / 2.0, 0.0));
|
||||
crate::buttons::chevron(ui, at, ui.visuals().text_color());
|
||||
let name = labels.more_for.replace("{action}", &primary.to_lowercase());
|
||||
more.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.as_str()));
|
||||
let more = more.on_hover_text(name.as_str());
|
||||
|
||||
Reference in New Issue
Block a user