diff --git a/.config/cargo-ci.toml b/.config/cargo-ci.toml index 956491323b..93a48332ff 100644 --- a/.config/cargo-ci.toml +++ b/.config/cargo-ci.toml @@ -29,3 +29,9 @@ opt-level = 1 [profile.dev.package.craft-cms] opt-level = 1 + +# The runtime under every screen test: each frame of a fixture runs its pass, layout, focus and access tree. At +# opt-level 2 a suite trial runs about 40 percent fewer instructions than at 0 (Table activation 19.8 G to 11.9 G); +# opt-level 1 gives about 30 percent. Every UI crate waits for its compile, which grows by about a minute. +[profile.dev.package.craft-ui-contract] +opt-level = 2 diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 63170f1214..33106085a5 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -167,8 +167,8 @@ jobs: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings # A selection that reaches a replay-audit crate builds once in a `build` job, which writes # three nextest archives and then runs the doctests; three shard legs run them in parallel: - # every selected test outside the replay audit's crates, those crates (run plainly, then with the - # audit), and craft-image-codecs with default features. Any other selection + # every selected test outside the replay audit's crates and craft-draw, those crates (run plainly, + # then the audit crates with the audit), and craft-image-codecs with default features. Any other selection # (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh # holds every step. test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }} diff --git a/AGENTS.md b/AGENTS.md index ff4606fd5f..2fd1513b85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119 Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/`. See `README.md` for layout and released versions. -- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`. +- **New crates** go in `crates/`, named `craft-`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below). - **No app code.** A crate here is useful to more than one app and does not depend on any app. -- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`. +- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls. - **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p --all-targets -- -D warnings`, `cargo test -p `. diff --git a/Cargo.lock b/Cargo.lock index 62dfc38e65..59f96c7eee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1804,6 +1804,7 @@ dependencies = [ "craft-flow", "craft-font-catalog", "craft-font-manager", + "craft-font-os-windows", "craft-font-store", "craft-font-subset", "craft-format", @@ -2772,6 +2773,14 @@ dependencies = [ "skrifa 0.47.0", ] +[[package]] +name = "craft-font-os-windows" +version = "0.1.0" +dependencies = [ + "windows-registry", + "windows-sys 0.61.2", +] + [[package]] name = "craft-font-store" version = "0.1.0" @@ -2779,6 +2788,7 @@ dependencies = [ "cap-primitives", "craft-atomic", "craft-font-catalog", + "craft-font-os-windows", "flate2", "log", "ruzstd", diff --git a/Cargo.toml b/Cargo.toml index cc40daf56d..7166c5a781 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -123,6 +123,7 @@ craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } craft-font-catalog = { path = "crates/font-catalog" } craft-font-manager = { path = "crates/font-manager" } +craft-font-os-windows = { path = "crates/font-os-windows" } craft-font-store = { path = "crates/font-store" } craft-gainmap = { path = "crates/gainmap" } craft-flow = { path = "crates/flow" } diff --git a/README.md b/README.md index f1ded80ca2..5cbfd01ab4 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit and filters over the Google Fonts index, installed fonts by family, the font store interface, and (`ui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab and the standalone app. +- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store` + needs on Windows to make a font available to every app of the user (the per-user font + registry, `AddFontResourceW`, `WM_FONTCHANGE`), behind a safe API. - [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub) @@ -476,7 +479,7 @@ architecture: [docs/craft-framework.md](docs/craft-framework.md). - [`craft-theme`](crates/theme/README.md) and [`craft-theme-store`](crates/theme-store/README.md): the token model, the built-in themes and the suite's theme selection ([docs/suite-themes.md](docs/suite-themes.md)). - [`craft-host`](crates/host/README.md): the services an app installs once and every feature reads. -- `craft-win32`: the Win32 calls that need `unsafe`, behind a safe API; the one crate that allows `unsafe`. +- `craft-win32`: the window-procedure and window-handle Win32 calls that need `unsafe`, behind a safe API. - Tools, not shipped in apps: `craft-ui-gallery` (the story viewer), `story-render` (one component's stories to PNG files), [`craft-design-lint`](crates/design-lint/README.md), `craft-ui-bench`, `craft-ui-test-kit`. diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 3cae59522b..19faa7c6be 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -34,6 +34,7 @@ craft-draw = { workspace = true, optional = true } craft-ecproj-format = { workspace = true, optional = true } craft-font-catalog = { workspace = true, optional = true } craft-font-manager = { workspace = true, optional = true } +craft-font-os-windows = { workspace = true, optional = true } craft-font-store = { workspace = true, optional = true } craft-font-subset = { workspace = true, optional = true } craft-imaging = { workspace = true, optional = true } @@ -500,6 +501,8 @@ font-catalog-system = ["font-catalog", "craft-font-catalog/system"] font-manager = ["dep:craft-font-manager"] +font-os-windows = ["dep:craft-font-os-windows"] + font-store = ["dep:craft-font-store"] font-store-bundled-index = ["font-store", "craft-font-store/bundled-index"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index caeb7d5267..b465304399 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -139,6 +139,8 @@ pub use craft_flow as flow; pub use craft_font_catalog as font_catalog; #[cfg(feature = "font-manager")] pub use craft_font_manager as font_manager; +#[cfg(feature = "font-os-windows")] +pub use craft_font_os_windows as font_os_windows; #[cfg(feature = "font-store")] pub use craft_font_store as font_store; #[cfg(feature = "font-subset")] diff --git a/crates/font-catalog/README.md b/crates/font-catalog/README.md index 4ed1b0cecb..bbc13c3af7 100644 --- a/crates/font-catalog/README.md +++ b/crates/font-catalog/README.md @@ -54,7 +54,8 @@ Each face (`FaceInfo`) has its family and style, legacy family and style, family - `family(name)` and `resolve(name, style)` accept any name of a family: its own name ignoring ASCII case, its names in other languages and its legacy names ignoring case and anything but letters and digits. `resolve` also accepts a legacy family with its legacy style (`Roboto Light` / `Regular`), a full name, and a PostScript name. - Within a family, `resolve` matches the style by name (any of its names). Otherwise it picks the nearest weight, with italic differing counting as 1000, then the nearest width. It returns `Match::Exact` or `Match::NearestStyle`, so the app decides about substitutes. - `by_postscript_name(name)`. -- These list each face once, from the first file that has it: added faces first, then installed files by path. `versions(face)` gives the face from every file that has it (the same family, style, PostScript name and variations), for an app that offers another version of a font. +- `faces()`, `families()` and the lookups list each face once: of faces with the same family, style, PostScript name and variations they keep the first (added faces, then installed files by path), except that the font store's face wins over a scanned copy elsewhere, such as one in the OS font folder. `versions(face)` gives the face from every file that has it, for an app that offers another version of a font. `scanned_faces()` lists every face the scan found, the same font in two places included, for telling copies apart (craft-font-store's conflict check). +- `read_faces(path, source)` reads one file's faces, named instances included, as a scan does, without a catalog. ## Loading and threads diff --git a/crates/font-catalog/src/catalog.rs b/crates/font-catalog/src/catalog.rs index 21d9840953..bee23bf041 100644 --- a/crates/font-catalog/src/catalog.rs +++ b/crates/font-catalog/src/catalog.rs @@ -139,22 +139,44 @@ struct Index { impl Index { /// Added faces first: a document's or the app's own face wins over an installed face of the - /// same family and style. + /// same family and style. Among scanned duplicates the font store's face wins, so a store + /// font copied into the OS font folder stays the store's wherever the folders sort. fn build(added: &[Face], scanned: &[Face]) -> Self { - let mut faces: Vec = Vec::new(); - let mut listed = HashMap::new(); - let mut versions: HashMap> = HashMap::new(); - for f in added.iter().chain(scanned) { + let all: Vec<&Face> = added.iter().chain(scanned).collect(); + // The positions in `all` of each face's versions, the listed one first. + let mut groups: HashMap<_, Vec> = HashMap::new(); + for (i, f) in all.iter().enumerate() { let variations: Vec<(u32, u32)> = f.info.variations.iter().map(|(t, v)| (u32::from_be_bytes(*t), v.to_bits())).collect(); let key = (f.info.family.to_ascii_lowercase(), norm(&f.info.style), f.keys.postscript.first().cloned(), variations); - match listed.entry(key) { - Entry::Occupied(e) => versions.entry(*e.get()).or_default().push(f.info.clone()), + match groups.entry(key) { Entry::Vacant(e) => { - e.insert(faces.len()); - faces.push(f.clone()); + e.insert(vec![i]); + } + Entry::Occupied(mut e) => { + let group = e.get_mut(); + let store_first = + group.first().is_some_and(|held| *held >= added.len() && all.get(*held).is_some_and(|h| h.info.source != Source::Store)); + if store_first && f.info.source == Source::Store { + group.insert(0, i); + } else { + group.push(i); + } } } } + let mut groups: Vec> = groups.into_values().collect(); + groups.sort_unstable(); + let mut faces: Vec = Vec::new(); + let mut versions: HashMap> = HashMap::new(); + for group in &groups { + let mut group = group.iter().filter_map(|i| all.get(*i)); + let Some(listed) = group.next() else { continue }; + let others: Vec = group.map(|f| f.info.clone()).collect(); + if !others.is_empty() { + versions.insert(faces.len(), others); + } + faces.push((*listed).clone()); + } let mut by_family: HashMap> = HashMap::new(); let mut aliases: HashMap> = HashMap::new(); let mut postscript: HashMap = HashMap::new(); @@ -469,6 +491,12 @@ fn modified(path: &Path) -> Option { std::fs::metadata(path).and_then(|m| m.modified()).ok() } +/// The faces of the font file at `path` as a scan reads them, named instances included, with +/// `source` as their source. Empty when it isn't a font. +pub fn read_faces(path: &Path, source: Source) -> Vec { + scan::file_faces(path, MAX_SCAN_READ, source).into_iter().map(|f| f.info).collect() +} + impl Catalog { /// A catalog of the fonts installed on the system `env` describes, the font store, and the /// files the platform's font service lists (with the `system` feature). @@ -728,6 +756,14 @@ impl Catalog { history.record(generation, &old, &new); } + /// Every face the last scan found, in path order, with the faces [`Catalog::faces`] drops as + /// duplicates of another of the same family, style and PostScript name. Faces added from + /// files or bytes aren't in it. For telling apart copies of one font in different places. + pub fn scanned_faces(&self) -> Vec { + self.ensure(); + self.scanned().iter().map(|f| f.info.clone()).collect() + } + /// The family names, sorted ignoring case. Private system families are among them ([`is_private_family`]): a /// document may name one, while font lists leave them out. pub fn families(&self) -> Arc<[String]> { diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index bc16df00d5..b9feb95776 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -41,7 +41,7 @@ mod suitcase; pub mod system; mod visual_order; -pub use catalog::{Catalog, Changes, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family}; +pub use catalog::{Catalog, Changes, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch, is_private_family, read_faces}; pub use embedding::{SubsetEmbedding, subset_embedding}; pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs}; pub use face_data::FaceData; diff --git a/crates/font-catalog/src/tests.rs b/crates/font-catalog/src/tests.rs index 4a5be33c49..1c7397578c 100644 --- a/crates/font-catalog/src/tests.rs +++ b/crates/font-catalog/src/tests.rs @@ -259,6 +259,23 @@ fn lookup_by_every_name_kind() { assert_eq!(cat.by_postscript_name("Missing-Regular"), None); } +#[test] +fn the_stores_face_wins_over_its_copy_in_the_os_folder() { + // A Flatpak's store sits under ~/.var/app, which sorts after the host's ~/.local/share/fonts + // the store copies its fonts into. + let root = temp("store-copy"); + let bytes = font(&spec("Copied Sans", "Regular", 400)); + write(&root.join("home/.local/share/fonts/Craft/Copied Sans/CopiedSans-Regular.ttf"), &bytes); + let store = root.join("home/.var/app/org.example.Fonts/data/craft-fonts"); + write(&store.join("Copied Sans/CopiedSans-Regular.ttf"), &bytes); + let cat = Catalog::new(FontEnv { font_store: Some(store), ..linux_env(&root) }).with_font_service(false); + cat.rescan(); + let styles = cat.styles("Copied Sans"); + assert_eq!(styles.len(), 1); + assert_eq!(styles[0].source, Source::Store); + assert_eq!(cat.scanned_faces().iter().filter(|f| f.family == "Copied Sans").count(), 2); +} + #[test] fn installed_and_removed_fonts_are_seen_without_a_restart() { let root = temp("rescan"); diff --git a/crates/font-manager/README.md b/crates/font-manager/README.md index 5c4fd076fe..e5a30b4507 100644 --- a/crates/font-manager/README.md +++ b/crates/font-manager/README.md @@ -10,7 +10,7 @@ Fonts tab; the standalone app | `filter` | always | Search over the index: family names ignoring case and accents, category, language (English name, autonym or id) and script | | `index` | always | The pinned built-in indexes (Google Fonts and Noto) compiled into [`craft-font-store`](../font-store/README.md) (`bundled`), each family's source (`source_label`: its name and whether it is curated), and the categories | | `installed` | always | The installed fonts [`craft-font-catalog`](../font-catalog/README.md) sees, grouped by family and source | -| `store` | always | `Installer`, what the interface needs from the font store: the download consent, install, remove, downloads for a preview, the indexes (`indexes`, `fetch_indexes`) and the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`). `SuiteStore` is craft-font-store's store (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown. What the preview pool (craft-font-store's `preview`) reads is the `PreviewStore` part | +| `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`), the sources the user added (`user_sources`, `add_user_source`, `remove_user_source`), 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 (native only), `FakeStore` a stand-in for tests, `NoStore` one for when the store folder is unknown. What the preview pool (craft-font-store's `preview`) reads is the `PreviewStore` part | | `FontsPanel` | `ui` | The whole interface as one egui panel | | `glyphs` | `ui` | `GlyphsPanel`: the character grid of a face with categories, zoom and Recently Used; the app supplies the glyphs through `GlyphSource`, which also reports when it is ready and when its faces change. Sizes are the `glyphs.*` tokens | | `missing` | `ui` | `document_fonts`, `missing_font_warnings` and `MissingFontsDialog`: which fonts a document names are not installed, and a replacement for each | @@ -28,14 +28,16 @@ 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. The arrow keys step through the cards and Enter opens one. - **Sample toolbar**: a preset (a sentence in the language filtered by, or in the family's own script when it has no Latin; 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, designer, licence, scripts and languages, and what a + 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, designer, licence, scripts and languages, and what a preview downloads. - **Installed**: system and font store fonts as the same cards, filtered by source. Only font store families can be removed; system fonts are removed with the system's own tools. diff --git a/crates/font-manager/src/panel/app.rs b/crates/font-manager/src/panel/app.rs index 3074a0a147..a07707f9bc 100644 --- a/crates/font-manager/src/panel/app.rs +++ b/crates/font-manager/src/panel/app.rs @@ -5,13 +5,14 @@ pub(crate) mod stories; use std::collections::HashMap; +use std::path::PathBuf; use std::sync::Arc; use crate::craft_font_catalog::{FontEnv, Limits, Os}; use crate::filter::{Query, Search}; use crate::index::{Category, Family, Index, categories, source_label}; use crate::installed::{InstalledFamily, group}; -use crate::store::{Installer, RemoveRequest, StoreError}; +use crate::store::{Conflict, Installer, MadeAvailable, RemoveRequest, StoreError}; use crate::{Catalog, FaceInfo, Source}; use craft_behavior::ColumnWidth; use craft_host::{Host, Section, Wake}; @@ -63,6 +64,8 @@ craft_ui::words! { styles: count "fontsPanel.styles" = "{n} style" | "{n} styles"; families: count "fontsPanel.families" = "{n} family" | "{n} families"; setting_failed: template "fontsPanel.settingFailed" = "The download setting couldn't be saved: {error}"; + craft_apps_only_failed: template "fontsPanel.craftAppsOnlyFailed" = "The Craft apps only setting couldn't be applied: {error}"; + system_fonts_failed: template "fontsPanel.systemFontsFailed" = "Your system's fonts folder couldn't be updated: {error}"; consent_title: template "fontsPanel.consentTitle" = "Download from {source}?"; consent_text: template "fontsPanel.consentText" = "Craft Font Manager downloads {family} ({size}) from {source}, and checks every file before using it."; consent_text_host: template "fontsPanel.consentTextHost" = "Craft Font Manager downloads {family} ({size}) from {host}, the server of {source}, a source you added, and checks every file before using it."; @@ -175,7 +178,8 @@ impl 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), /// One file of a family, by its path in the index. InstallFile(usize, String), Preview(usize), @@ -184,7 +188,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, } } } @@ -198,6 +202,37 @@ 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), +} + +/// A problem that belongs to no family, with the error reported. +#[derive(Clone, Debug)] +pub(crate) enum Problem { + /// The download setting couldn't be saved. + DownloadSetting(String), + /// "Keep fonts in Craft apps only" couldn't be saved. + CraftAppsOnly(String), + /// A family couldn't be copied to or withdrawn from the OS user font folder. + SystemFonts(String), +} + +impl Problem { + /// What the panel says about it. + pub(crate) fn text(&self, words: &FontsPanelWords) -> String { + let (template, error) = match self { + Problem::DownloadSetting(error) => (&words.setting_failed, error), + Problem::CraftAppsOnly(error) => (&words.craft_apps_only_failed, error), + Problem::SystemFonts(error) => (&words.system_fonts_failed, error), + }; + template.fill(&[("error", error.as_str())]) + } +} + /// Why the last job for a family failed, and what Retry runs. #[derive(Clone, Debug)] pub(crate) struct Failure { @@ -258,8 +293,14 @@ pub struct FontsPanel { pub(crate) asking: Option, /// By lower-case family name. pub(crate) failed: HashMap, - /// A problem that belongs to no family: why the download setting couldn't be saved. - pub(crate) notice: Option, + /// The last problem that belongs to no family. + 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, + /// Whether the start-up copy of families whose choice is the OS user font folder was queued. + shared_at_start: bool, /// The window had OS focus on the last pass. window_active: bool, /// The download consent as last read. @@ -323,7 +364,9 @@ impl FontsPanel { tab: Tab::Catalogue, downloads_switch: true, 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, @@ -350,6 +393,7 @@ impl FontsPanel { asking: None, failed: HashMap::new(), notice: None, + not_copied: HashMap::new(), window_active: true, consent: None, } @@ -468,7 +512,7 @@ impl FontsPanel { pub fn set_downloads_allowed(&mut self, allowed: bool) -> Result<(), StoreError> { let result = self.installer.allow_downloads(allowed); self.consent = None; - self.notice = result.as_ref().err().map(|e| e.0.clone()); + self.notice = result.as_ref().err().map(|e| Problem::DownloadSetting(e.0.clone())); result } @@ -482,6 +526,7 @@ impl FontsPanel { /// (read again when the window regains focus) and the results of the search. fn prepare(&mut self, host: Option<&Arc>, window_active: bool) { self.load_settings(host); + self.share_installed_at_start(host); self.poll_jobs(); if window_active && !self.window_active { if self.catalog.is_ready() { @@ -519,9 +564,19 @@ 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::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::SystemFonts => self.notice = Some(Problem::SystemFonts(e.0)), Ok(Finished::Previewed(files)) => { self.failed.remove(&key); let mut faces = Vec::new(); @@ -539,9 +594,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 => 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 }); @@ -551,6 +606,44 @@ 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": 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| Problem::CraftAppsOnly(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, as a job, and records that as its + /// choice. + pub(crate) fn set_available_to_all(&mut self, host: Option<&Arc>, family: &str, files: Vec, on: bool) { + self.notice = None; + let request = Request::AvailableToAll(family.to_owned(), files, on); + self.jobs.start(host, 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), as a job. + fn share_installed_at_start(&mut self, host: Option<&Arc>) { + if std::mem::replace(&mut self.shared_at_start, true) { + return; + } + if self.installer.available_to_all_supported() { + self.jobs.start(host, Arc::clone(&self.installer), Arc::clone(&self.catalog), Request::ShareAtStart); + } + } + fn refresh_installed(&mut self) { if !self.catalog.is_ready() { return; @@ -672,7 +765,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), }; diff --git a/crates/font-manager/src/panel/app/stories.rs b/crates/font-manager/src/panel/app/stories.rs index 057fa65fb1..b2f8dcf7ff 100644 --- a/crates/font-manager/src/panel/app/stories.rs +++ b/crates/font-manager/src/panel/app/stories.rs @@ -60,6 +60,6 @@ fn fonts_panel_no_results(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn fonts_panel_consent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { show(ui, data, Tab::Catalogue, |panel| { let _ = panel.set_downloads_allowed(false); - panel.asking = Some(Pending::Install(0)); + panel.asking = Some(Pending::Install(0, None)); }) } diff --git a/crates/font-manager/src/panel/browse.rs b/crates/font-manager/src/panel/browse.rs index 84e6de3002..875b351187 100644 --- a/crates/font-manager/src/panel/browse.rs +++ b/crates/font-manager/src/panel/browse.rs @@ -17,7 +17,7 @@ use craft_ui::choice::{Checkbox, Radio, RadioGroup}; use craft_ui::contract::{ Access, ActivateOn, Bind, Collection, CollectionEvent, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, Entry, ItemOutput, MeasureCx, Name, NoValue, Outcome, PartsCx, Props as _, Role, Scroll, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, - Sizing, clicked, + Sizing, WrapWidth, clicked, }; use craft_ui::display::{Badge, Progress, Shade, Spinner, Text}; use craft_ui::form::{SliderField, SliderFieldLayout}; @@ -64,6 +64,9 @@ craft_ui::words! { downloads: "fontsBrowse.downloads" = "Downloads"; allow_downloads: "fontsBrowse.allowDownloads" = "Allow downloads"; downloads_hint: "fontsBrowse.downloadsHint" = "From each font's source, only when you install or preview a font."; + system_fonts: "fontsBrowse.systemFonts" = "System fonts"; + craft_apps_only: "fontsBrowse.craftAppsOnly" = "Keep fonts in Craft apps only"; + craft_apps_only_hint: "fontsBrowse.craftAppsOnlyHint" = "Off: Install also copies fonts to your system's fonts folder, for all apps. Fonts already installed keep their own setting."; category: "fontsBrowse.category" = "Category"; all_categories: "fontsBrowse.allCategories" = "All categories"; language: "fontsBrowse.language" = "Language"; @@ -103,14 +106,19 @@ craft_ui::words! { installing: "fontsBrowse.installing" = "Installing"; removing: "fontsBrowse.removing" = "Removing"; downloading: "fontsBrowse.downloading" = "Downloading"; + updating_system_fonts: "fontsBrowse.updatingSystemFonts" = "Updating system fonts"; progress: template "fontsBrowse.progress" = "{what} {percent} %"; working: template "fontsBrowse.working" = "{what}…"; retry: "fontsBrowse.retry" = "Retry"; failed_install: "fontsBrowse.failedInstall" = "Couldn't install"; failed_remove: "fontsBrowse.failedRemove" = "Couldn't remove"; failed_download: "fontsBrowse.failedDownload" = "Couldn't download"; + failed_system_fonts: "fontsBrowse.failedSystemFonts" = "Couldn't update system fonts"; install: "fontsBrowse.install" = "Install"; install_family: template "fontsBrowse.installFamily" = "Install {family}"; + install_options: "fontsBrowse.installOptions" = "More install options"; + install_all_apps: "fontsBrowse.installAllApps" = "Install for all apps"; + install_craft_apps: "fontsBrowse.installCraftApps" = "Install for Craft apps only"; preview: "fontsBrowse.preview" = "Preview"; preview_family: template "fontsBrowse.previewFamily" = "Preview {family}"; remove: "fontsBrowse.remove" = "Remove"; @@ -189,7 +197,7 @@ impl FontsPanel { pub(crate) fn filters(&mut self, ui: &mut Ui, texts: &Texts<'_>) { let browse = texts.browse; - Stack::new().scroll(Scroll::vertical()).label(browse.filters.clone()).show(ui, |ui, _| { + Stack::new().scroll(Scroll::vertical()).wrap_width(WrapWidth::Column).label(browse.filters.clone()).show(ui, |ui, _| { match self.tab { Tab::Catalogue => self.catalogue_filters(ui, texts), Tab::Installed => self.installed_filters(ui, texts), @@ -205,6 +213,16 @@ impl FontsPanel { Text::new(browse.downloads_hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); }); } + if self.installer.available_to_all_supported() { + Section::fixed(browse.system_fonts.clone()).id_salt("system-fonts").show(ui, |ui, _| { + let mut on = self.craft_apps_only; + Checkbox::new(Bind::bound(&mut on)).label(browse.craft_apps_only.clone()).show(ui); + if on != self.craft_apps_only { + self.set_craft_apps_only(on); + } + Text::new(browse.craft_apps_only_hint.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui); + }); + } }); } @@ -320,8 +338,8 @@ impl FontsPanel { pub(crate) fn main(&mut self, ui: &mut Ui, texts: &Texts<'_>, folder: &Folder, host: Option<&Arc>) { Stack::new().fill().show(ui, |ui, _| { self.toolbar(ui, texts.browse); - if let Some(error) = self.notice.clone() { - Notice::new(Tone::Bad, Label::from(texts.panel.setting_failed.fill(&[("error", error.as_str())]))).show(ui); + if let Some(problem) = &self.notice { + Notice::new(Tone::Bad, Label::from(problem.text(texts.panel))).show(ui); } match self.tab { Tab::Catalogue => { @@ -397,7 +415,7 @@ impl FontsPanel { for event in events { match event { CollectionEvent::Activate(i) => self.detail = Some(Detail::Family(i)), - CollectionEvent::Item(i, CardEvent::Install) => self.ask(host, Pending::Install(i)), + CollectionEvent::Item(i, CardEvent::Install(share)) => self.ask(host, Pending::Install(i, share)), CollectionEvent::Item(i, CardEvent::Preview) => self.ask(host, Pending::Preview(i)), CollectionEvent::Item(i, CardEvent::Retry) => { let retry = index @@ -508,7 +526,7 @@ impl FontsPanel { } else if installed.is_some() { CardState::Installed } else { - CardState::Offer { preview: !self.previewed.contains_key(&key) } + CardState::Offer { preview: !self.previewed.contains_key(&key), destinations: self.installer.available_to_all_supported() } }; let (source, curated) = source_label(index, family); let meta = [texts.styles(style_count(family)), category_label(texts.panel, family), source.to_owned()].join(" · "); diff --git a/crates/font-manager/src/panel/browse/cards.rs b/crates/font-manager/src/panel/browse/cards.rs index 733a5634cc..b60b5b83e9 100644 --- a/crates/font-manager/src/panel/browse/cards.rs +++ b/crates/font-manager/src/panel/browse/cards.rs @@ -1,6 +1,7 @@ //! The family card and the collection of cards the panel lists. -use craft_ui::contract::{Props as _, Styled as _, clicked}; +use craft_ui::buttons::{SplitButton, SplitOutput}; +use craft_ui::contract::{Entry, Props as _, Styled as _, clicked}; use super::{ Access, Arc, Badge, Button, Catalog, Collection, CollectionProps, CollectionResponse, Common, Component, ComponentStyle, ContainerProps, Cow, Cx, @@ -14,8 +15,9 @@ use craft_ui::primitives::RectSide; #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum CardEvent { - /// Install the family. - Install, + /// Install the family, for all apps (`true`), for Craft apps only (`false`), or as its recorded choice, else the + /// setting, says (`None`). + Install(Option), /// Download the family for a preview. Preview, /// Remove the family from the font store. @@ -43,6 +45,8 @@ pub enum CardState { Offer { /// Whether Preview is offered. preview: bool, + /// Whether Install's menu offers installing for all apps or for Craft apps only. + destinations: bool, }, } @@ -75,6 +79,7 @@ enum End { Installed, Preview, Install, + InstallMenu, Remove, RunningText, RunningBar, @@ -83,7 +88,7 @@ enum End { impl End { fn event(self) -> Option { match self { - End::Install => Some(CardEvent::Install), + End::Install | End::InstallMenu => Some(CardEvent::Install(None)), End::Preview => Some(CardEvent::Preview), End::Remove => Some(CardEvent::Remove), End::Retry => Some(CardEvent::Retry), @@ -92,6 +97,24 @@ impl End { } } +/// What the control of a piece reports. +trait EndOutput { + /// What the pressed control of `end` asks for. + fn event(&self, end: End) -> Option; +} + +impl EndOutput for Response { + fn event(&self, end: End) -> Option { + clicked(self).then(|| end.event()).flatten() + } +} + +impl EndOutput for SplitOutput { + fn event(&self, end: End) -> Option { + self.chosen.map(|share| CardEvent::Install(Some(share))).or_else(|| self.activated.then(|| end.event()).flatten()) + } +} + /// Builds the control for one piece of a card's end and runs `$body` on it as `$c`. A control is built where it is /// measured and again where it is shown, so both come from this one list. macro_rules! with_end { @@ -123,6 +146,13 @@ macro_rules! with_end { let $c = Button::new($words.install.clone()).description($words.install_family.fill(&[("family", $card.data.name.as_str())])); $body } + End::InstallMenu => { + let entries = [Entry::new(true, $words.install_all_apps.clone()), Entry::new(false, $words.install_craft_apps.clone())]; + let $c = SplitButton::new($words.install.clone(), &entries) + .arrow_label($words.install_options.clone()) + .description($words.install_family.fill(&[("family", $card.data.name.as_str())])); + $body + } End::Remove => { let $c = Button::new($words.remove.clone()) .variant(Variant::DANGER) @@ -236,6 +266,7 @@ impl FamilyCard { Kind::Install => words.installing.as_str(), Kind::Remove => words.removing.as_str(), Kind::Preview => words.downloading.as_str(), + Kind::SystemFonts => words.updating_system_fonts.as_str(), }; match fraction { Some(fraction) => words.progress.fill(&[("what", what), ("percent", &((fraction * 100.0).round() as u64).to_string())]), @@ -251,6 +282,7 @@ impl FamilyCard { Kind::Install => &words.failed_install, Kind::Remove => &words.failed_remove, Kind::Preview => &words.failed_download, + Kind::SystemFonts => &words.failed_system_fonts, }; (what.clone(), error.clone()) } @@ -276,11 +308,11 @@ impl FamilyCard { CardState::Installed => ends.push(End::Installed), CardState::Removable => ends.push(End::Remove), CardState::System => {} - CardState::Offer { preview } => { + CardState::Offer { preview, destinations } => { if *preview { ends.push(End::Preview); } - ends.push(End::Install); + ends.push(if *destinations { End::InstallMenu } else { End::Install }); } } ends @@ -394,9 +426,9 @@ impl Component for FamilyCard { draw.edge_rule(RuleKind::Divider, cx.rect, RectSide::Bottom); } for (piece, rect) in &placed.end { - let pressed = with_end!(self, words, *piece, |child| clicked(&ui.child(("end", *piece as u8), *rect, child))); - if pressed { - self.event = piece.event(); + let event = with_end!(self, words, *piece, |child| ui.child(("end", *piece as u8), *rect, child).event(*piece)); + if event.is_some() { + self.event = event; } } let sample = self.sample(&words); diff --git a/crates/font-manager/src/panel/browse/stories.rs b/crates/font-manager/src/panel/browse/stories.rs index fcc6a4ee49..86eba711f7 100644 --- a/crates/font-manager/src/panel/browse/stories.rs +++ b/crates/font-manager/src/panel/browse/stories.rs @@ -23,7 +23,12 @@ fn data(name: &str, state: CardState) -> CardData { #[story(FamilyCard, covers = [Default], drive = Drive::Never)] fn family_card_not_installed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true }))).into() + show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true, destinations: true }))).into() +} + +#[story(FamilyCard, covers = [], drive = Drive::Never)] +fn family_card_craft_apps_only(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + show_as_only_item(ui, FamilyCard::new(data("Hack", CardState::Offer { preview: true, destinations: false }))).into() } #[story(FamilyCard, covers = [], drive = Drive::Never)] @@ -43,7 +48,7 @@ fn family_card_installed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(FamilyCard, covers = [], drive = Drive::Never)] fn family_card_not_curated(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - let mut card = data("Hack", CardState::Offer { preview: false }); + let mut card = data("Hack", CardState::Offer { preview: false, destinations: true }); card.curated = false; show_as_only_item(ui, FamilyCard::new(card)).into() } @@ -51,7 +56,7 @@ fn family_card_not_curated(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { fn cards(ui: &mut Ui, keys: &[usize]) -> StoryOutput { FamilyCards::new("Families") .show_items(ui, &CardKeys::new(keys, |_| None), &mut |key, _| { - let state = if key % 2 == 0 { CardState::Installed } else { CardState::Offer { preview: true } }; + let state = if key % 2 == 0 { CardState::Installed } else { CardState::Offer { preview: true, destinations: true } }; FamilyCard::new(data(&format!("Family {key}"), state)) }) .into() diff --git a/crates/font-manager/src/panel/details.rs b/crates/font-manager/src/panel/details.rs index 5a04697add..5778d8cbc2 100644 --- a/crates/font-manager/src/panel/details.rs +++ b/crates/font-manager/src/panel/details.rs @@ -5,14 +5,15 @@ pub(crate) mod rows; #[cfg(feature = "suite")] pub(crate) mod stories; +use std::path::PathBuf; use std::sync::Arc; use craft_behavior::ColumnWidth; use craft_host::Host; use craft_theme::variant::{Emphasis, Tone}; -use craft_ui::buttons::Button; +use craft_ui::buttons::{Button, Link, SplitButton}; use craft_ui::contract::overlay::Outside; -use craft_ui::contract::{Bind, CollectionEvent, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft_ui::contract::{Bind, CollectionEvent, Entry, NoValue, Outcome, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; use craft_ui::dialog::Dialog; use craft_ui::display::{Badge, Progress, Shade, Text}; use craft_ui::layout_components::{Grid, Row, Stack}; @@ -23,7 +24,9 @@ use egui::{Response, Ui}; use self::rows::{Action, Lines, StyleLine, StyleList, StyleRow}; use crate::index::{Family, FontFile, Index, script_name, source_label}; -use crate::panel::app::{Detail, FontsPanel, FontsPanelWords, Pending, category_label, family_key, regular, source_name, style_count, style_name}; +use crate::panel::app::{ + Detail, FontsPanel, FontsPanelWords, NotCopied, Pending, category_label, family_key, regular, source_name, style_count, style_name, +}; use crate::panel::faces::Owner; use crate::panel::jobs::Kind; use crate::panel::specimen::{FontSample, SampleFace}; @@ -51,9 +54,25 @@ craft_ui::words! { installing: "fontDetails.installing" = "Installing"; removing: "fontDetails.removing" = "Removing"; downloading: "fontDetails.downloading" = "Downloading"; + updating_system_fonts: "fontDetails.updatingSystemFonts" = "Updating system fonts"; installed: "fontDetails.installed" = "Installed"; installed_on_system: "fontDetails.installedOnSystem" = "Installed on this system"; install_all: "fontDetails.installAll" = "Install all"; + install_all_options: "fontDetails.installAllOptions" = "More install all options"; + install_all_apps: "fontDetails.installAllApps" = "Install for all apps"; + install_craft_apps: "fontDetails.installCraftApps" = "Install for Craft apps only"; + /// `{reason}`. + only_craft_apps: template "fontDetails.onlyCraftApps" = "Only in Craft apps: {reason}"; + available_to_all: "fontDetails.availableToAll" = "Available to all apps"; + kept_in_craft_apps: "fontDetails.keptInCraftApps" = "Kept in Craft apps only"; + make_available: "fontDetails.makeAvailable" = "Make available to all apps"; + keep_in_craft_apps: "fontDetails.keepInCraftApps" = "Keep in Craft apps only"; + /// `{error}`. + copy_failed: template "fontDetails.copyFailed" = "Couldn't copy to your system's fonts folder: {error}"; + /// `{file}` and `{name}`. + copy_name_taken: template "fontDetails.copyNameTaken" = "Not copied to your system's fonts folder: {file} already has the font name {name}"; + /// `{file}`. + copy_in_the_way: template "fontDetails.copyInTheWay" = "Not copied to your system's fonts folder: {file} is in the way"; remove_all: "fontDetails.removeAll" = "Remove all"; preview: "fontDetails.preview" = "Preview"; install: "fontDetails.install" = "Install"; @@ -72,6 +91,7 @@ craft_ui::words! { couldnt_install: "fontDetails.couldntInstall" = "Couldn't install"; couldnt_remove: "fontDetails.couldntRemove" = "Couldn't remove"; couldnt_download: "fontDetails.couldntDownload" = "Couldn't download"; + couldnt_update_system_fonts: "fontDetails.couldntUpdateSystemFonts" = "Couldn't update system fonts"; retry: "fontDetails.retry" = "Retry"; system_fonts_note: "fontDetails.systemFontsNote" = "System fonts are removed with your system's own font tools."; system_fonts_removal: "fontDetails.systemFontsRemoval" = "Removed with your system's font tools"; @@ -151,6 +171,7 @@ fn file_of<'a>(family: &'a Family, face: &FaceInfo) -> Option<&'a FontFile> { enum Do { Ask(Pending), Remove { faces: Vec, whole: bool }, + AvailableToAll { files: Vec, on: bool }, } /// The job running for the whole family, as the header shows it. @@ -176,6 +197,69 @@ struct Failed { retry: Option, } +/// Whether the family's store fonts are in the OS user font folder for all apps, or why not. +struct SystemFonts { + text: Label, + tone: Option, + /// The store files. + files: Vec, + /// What the line's action sets; none while it can't change. + switch: Option, +} + +impl SystemFonts { + /// The line of the family named `family`; none when `faces` has no store font. + fn read(panel: &FontsPanel, words: &DetailsWords, family: &str, faces: &[FaceInfo]) -> Option { + let files: Vec = faces.iter().filter(|f| f.source == Source::Store).filter_map(|f| f.path.clone()).collect(); + if files.is_empty() { + return None; + } + let not_here = panel.installer.available_to_all_unsupported(); + let available = not_here.is_none() && panel.installer.is_available_to_all(family, &files); + let (text, tone) = if let Some(reason) = not_here { + (Label::from(words.only_craft_apps.fill(&[("reason", &reason)])), None) + } else if available { + (words.available_to_all.clone(), Some(Tone::Good)) + } else if let Some(not_copied) = panel.not_copied.get(&family.to_lowercase()) { + (Label::from(not_copied_text(words, not_copied)), Some(Tone::Warn)) + } else { + (words.kept_in_craft_apps.clone(), None) + }; + let switch = (panel.installer.available_to_all_supported() && panel.jobs.of("", family).is_none()).then_some(!available); + Some(SystemFonts { text, tone, files, switch }) + } + + fn show(&self, ui: &mut Ui, words: &DetailsWords, todo: &mut Vec) { + Row::new().wrap(true).show(ui, |ui, _| { + let text = Text::new(self.text.clone()); + match self.tone { + Some(tone) => text.tone(tone), + None => text.shade(Shade::Muted), + } + .show(ui); + if let Some(on) = self.switch { + let action = if on { &words.make_available } else { &words.keep_in_craft_apps }; + if clicked(&Link::new(action.clone()).show(ui)) { + todo.push(Do::AvailableToAll { files: self.files.clone(), on }); + } + } + }); + } +} + +/// What the sheet says about a family an install couldn't copy into the OS user font folder. +fn not_copied_text(words: &DetailsWords, not_copied: &NotCopied) -> String { + let conflict = match not_copied { + NotCopied::Failed(error) => return words.copy_failed.fill(&[("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) => words.copy_name_taken.fill(&[("file", &file), ("name", name)]), + None => words.copy_in_the_way.fill(&[("file", &file)]), + } +} + /// Everything the sheet shows, read from the panel before the pass draws it. struct Sheet { eyebrow: String, @@ -184,11 +268,15 @@ struct Sheet { hero: Option<(Owner, FaceInfo)>, run: Option, badge: Option