mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 12:32:10 +01:00
Merge next into fix/dock-group-band-keeps-tab
This commit is contained in:
commit
ce87f5484d
134 files changed
+5535
-431
No files matched your search
@@ -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
|
||||
@@ -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 }}
|
||||
|
||||
@@ -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/<name>`. See `README.md` for layout and released versions.
|
||||
|
||||
- **New crates** go in `crates/<name>`, named `craft-<name>`, 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/<name>`, named `craft-<name>`, 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 <crate> --all-targets -- -D warnings`, `cargo test -p <crate>`.
|
||||
Generated
+10
@@ -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",
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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`.
|
||||
|
||||
|
||||
@@ -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"]
|
||||
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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<Face> = Vec::new();
|
||||
let mut listed = HashMap::new();
|
||||
let mut versions: HashMap<usize, Vec<FaceInfo>> = 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<usize>> = 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<Vec<usize>> = groups.into_values().collect();
|
||||
groups.sort_unstable();
|
||||
let mut faces: Vec<Face> = Vec::new();
|
||||
let mut versions: HashMap<usize, Vec<FaceInfo>> = 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<FaceInfo> = 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<String, Vec<usize>> = HashMap::new();
|
||||
let mut aliases: HashMap<String, Vec<Alias>> = HashMap::new();
|
||||
let mut postscript: HashMap<String, usize> = HashMap::new();
|
||||
@@ -469,6 +491,12 @@ fn modified(path: &Path) -> Option<SystemTime> {
|
||||
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<FaceInfo> {
|
||||
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<FaceInfo> {
|
||||
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]> {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<bool>),
|
||||
/// 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<Conflict>),
|
||||
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<Pending>,
|
||||
/// By lower-case family name.
|
||||
pub(crate) failed: HashMap<String, Failure>,
|
||||
/// A problem that belongs to no family: why the download setting couldn't be saved.
|
||||
pub(crate) notice: Option<String>,
|
||||
/// The last problem that belongs to no family.
|
||||
pub(crate) notice: Option<Problem>,
|
||||
/// Families an install couldn't copy into the OS user font folder, by lower-case name.
|
||||
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,
|
||||
/// 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<Host>>, 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<Result<MadeAvailable, StoreError>>) {
|
||||
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<Host>>, family: &str, files: Vec<PathBuf>, 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<Host>>) {
|
||||
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),
|
||||
};
|
||||
|
||||
@@ -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));
|
||||
})
|
||||
}
|
||||
@@ -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<Host>>) {
|
||||
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(" · ");
|
||||
|
||||
@@ -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<bool>),
|
||||
/// 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<CardEvent> {
|
||||
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<CardEvent>;
|
||||
}
|
||||
|
||||
impl EndOutput for Response {
|
||||
fn event(&self, end: End) -> Option<CardEvent> {
|
||||
clicked(self).then(|| end.event()).flatten()
|
||||
}
|
||||
}
|
||||
|
||||
impl EndOutput for SplitOutput<bool> {
|
||||
fn event(&self, end: End) -> Option<CardEvent> {
|
||||
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);
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<FaceInfo>, whole: bool },
|
||||
AvailableToAll { files: Vec<PathBuf>, on: bool },
|
||||
}
|
||||
|
||||
/// The job running for the whole family, as the header shows it.
|
||||
@@ -176,6 +197,69 @@ struct Failed {
|
||||
retry: Option<Pending>,
|
||||
}
|
||||
|
||||
/// 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<Tone>,
|
||||
/// The store files.
|
||||
files: Vec<PathBuf>,
|
||||
/// What the line's action sets; none while it can't change.
|
||||
switch: Option<bool>,
|
||||
}
|
||||
|
||||
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<SystemFonts> {
|
||||
let files: Vec<PathBuf> = 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<Do>) {
|
||||
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<Run>,
|
||||
badge: Option<Label>,
|
||||
install_all: Option<Pending>,
|
||||
/// The family's position in the index when it can be installed whole.
|
||||
install_all: Option<usize>,
|
||||
/// Whether Install all's menu offers installing for all apps or for Craft apps only.
|
||||
destinations: bool,
|
||||
removal: Removal,
|
||||
store: Vec<FaceInfo>,
|
||||
preview: Option<Pending>,
|
||||
size_line: Option<String>,
|
||||
system_fonts: Option<SystemFonts>,
|
||||
preview_note: Option<String>,
|
||||
uncurated: Option<String>,
|
||||
failure: Option<Failed>,
|
||||
@@ -266,6 +354,7 @@ impl<'a> DetailsSheet<'a> {
|
||||
match action {
|
||||
Do::Ask(pending) => panel.ask(host.as_ref(), pending),
|
||||
Do::Remove { faces, whole } => panel.remove(host.as_ref(), &sheet.title, &faces, whole),
|
||||
Do::AvailableToAll { files, on } => panel.set_available_to_all(host.as_ref(), &sheet.title, files, on),
|
||||
}
|
||||
}
|
||||
DetailsOutput { response: shown.output.response, closed }
|
||||
@@ -325,11 +414,13 @@ impl Sheet {
|
||||
hero,
|
||||
run,
|
||||
badge: all_installed.then(|| installed_word.clone()),
|
||||
install_all: (!all_installed).then_some(Pending::Install(i)),
|
||||
install_all: (!all_installed).then_some(i),
|
||||
destinations: panel.installer.available_to_all_supported(),
|
||||
removal: if store.is_empty() { Removal::None } else { Removal::Allowed },
|
||||
store,
|
||||
preview: unseen.then_some(Pending::Preview(i)),
|
||||
size_line: Some(words.download_size_line.fill(&[("size", &size)])),
|
||||
system_fonts: SystemFonts::read(panel, words, &family.family, &installed),
|
||||
preview_note: unseen.then(|| words.preview_note.fill(&[("size", &size)])),
|
||||
uncurated,
|
||||
failure,
|
||||
@@ -378,10 +469,12 @@ impl Sheet {
|
||||
run,
|
||||
badge: None,
|
||||
install_all: None,
|
||||
destinations: false,
|
||||
removal: if family.removable() { Removal::Allowed } else { Removal::System },
|
||||
store: family.faces.clone(),
|
||||
preview: None,
|
||||
size_line: None,
|
||||
system_fonts: SystemFonts::read(panel, words, &family.name, &family.faces),
|
||||
preview_note: None,
|
||||
uncurated: None,
|
||||
failure: None,
|
||||
@@ -414,6 +507,7 @@ impl Sheet {
|
||||
Kind::Install => &words.installing,
|
||||
Kind::Remove => &words.removing,
|
||||
Kind::Preview => &words.downloading,
|
||||
Kind::SystemFonts => &words.updating_system_fonts,
|
||||
};
|
||||
progress(ui, env, words, what, run.fraction);
|
||||
return;
|
||||
@@ -421,10 +515,10 @@ impl Sheet {
|
||||
if let Some(badge) = &self.badge {
|
||||
Badge::new(badge.clone()).variant(Variant::look(Emphasis::Soft, Tone::Good)).show(ui);
|
||||
}
|
||||
if let Some(pending) = &self.install_all
|
||||
&& clicked(&Button::new(words.install_all.clone()).variant(Variant::PRIMARY).show(ui))
|
||||
if let Some(i) = self.install_all
|
||||
&& let Some(share) = self.install_button(ui, words)
|
||||
{
|
||||
todo.push(Do::Ask(pending.clone()));
|
||||
todo.push(Do::Ask(Pending::Install(i, share)));
|
||||
}
|
||||
match self.removal {
|
||||
Removal::Allowed => {
|
||||
@@ -447,6 +541,9 @@ impl Sheet {
|
||||
Text::new(line.clone()).shade(Shade::Faint).show(ui);
|
||||
}
|
||||
});
|
||||
if let Some(system_fonts) = &self.system_fonts {
|
||||
system_fonts.show(ui, words, todo);
|
||||
}
|
||||
if let Some(note) = &self.preview_note {
|
||||
Text::new(note.clone()).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
@@ -458,6 +555,7 @@ impl Sheet {
|
||||
Kind::Install => &words.couldnt_install,
|
||||
Kind::Remove => &words.couldnt_remove,
|
||||
Kind::Preview => &words.couldnt_download,
|
||||
Kind::SystemFonts => &words.couldnt_update_system_fonts,
|
||||
};
|
||||
let mut notice = Notice::new(Tone::Bad, failure.error.clone()).title(what.clone());
|
||||
if failure.retry.is_some() {
|
||||
@@ -472,6 +570,19 @@ impl Sheet {
|
||||
}
|
||||
}
|
||||
|
||||
/// Install all, with a menu that chooses where the fonts go when they can be copied into the OS user font folder.
|
||||
/// `None` when not pressed; `Some(None)` for the button itself (the family's choice, else the setting), else the
|
||||
/// choice.
|
||||
fn install_button(&self, ui: &mut Ui, words: &DetailsWords) -> Option<Option<bool>> {
|
||||
if !self.destinations {
|
||||
return clicked(&Button::new(words.install_all.clone()).variant(Variant::PRIMARY).show(ui)).then_some(None);
|
||||
}
|
||||
let entries = [Entry::new(true, words.install_all_apps.clone()), Entry::new(false, words.install_craft_apps.clone())];
|
||||
let out =
|
||||
SplitButton::new(words.install_all.clone(), &entries).arrow_label(words.install_all_options.clone()).variant(Variant::PRIMARY).show(ui);
|
||||
out.chosen.map(Some).or_else(|| out.activated.then_some(None))
|
||||
}
|
||||
|
||||
/// The styles, and beside them (or below, when narrow) the facts and the languages.
|
||||
fn body(&self, ui: &mut Ui, env: &Env, words: &DetailsWords, catalogs: &Catalogs, points: f32, todo: &mut Vec<Do>) {
|
||||
Row::new().wrap(true).show(ui, |ui, _| {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Installs, removals and preview downloads, run through the Host's jobs, one at a time.
|
||||
//! Installs, removals, preview downloads and copies to the OS user font folder, run through the Host's jobs, one at a
|
||||
//! time.
|
||||
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
@@ -8,7 +10,7 @@ use craft_host::{Host, Wake};
|
||||
|
||||
use crate::Catalog;
|
||||
use crate::index::Index;
|
||||
use crate::store::{Downloaded, Installer, Progress, RemoveRequest, StoreError};
|
||||
use crate::store::{Conflict, Downloaded, Installer, MadeAvailable, Progress, RemoveRequest, StoreError};
|
||||
|
||||
type Task = Box<dyn FnOnce() + Send>;
|
||||
|
||||
@@ -37,6 +39,9 @@ pub enum Kind {
|
||||
Remove,
|
||||
/// Downloads a family for preview only.
|
||||
Preview,
|
||||
/// Copies to or withdraws from the OS user font folder: a family's switch, or the start-up copy, which has no
|
||||
/// family.
|
||||
SystemFonts,
|
||||
}
|
||||
|
||||
/// A job that has not ended.
|
||||
@@ -50,6 +55,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>,
|
||||
/// The latest report of the installer.
|
||||
pub progress: Progress,
|
||||
}
|
||||
@@ -64,12 +71,17 @@ impl Running {
|
||||
/// How a job ended well.
|
||||
#[non_exhaustive]
|
||||
pub enum Finished {
|
||||
/// The family or file is installed.
|
||||
Installed,
|
||||
/// The family or file is installed, with what copying the family into the OS user font folder did, when it was
|
||||
/// copied.
|
||||
Installed(Option<Result<MadeAvailable, StoreError>>),
|
||||
/// The files are removed.
|
||||
Removed,
|
||||
/// The preview faces were downloaded.
|
||||
Previewed(Vec<Downloaded>),
|
||||
/// 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 {
|
||||
@@ -80,14 +92,21 @@ enum Msg {
|
||||
/// What to start.
|
||||
#[non_exhaustive]
|
||||
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),
|
||||
/// Installed files to remove.
|
||||
Remove(RemoveRequest),
|
||||
/// A family of the index, by position.
|
||||
Preview(Arc<Index>, usize),
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// The panel's install, removal and preview jobs.
|
||||
@@ -128,12 +147,14 @@ impl Jobs {
|
||||
self.running.values().find(|r| r.family.eq_ignore_ascii_case(family) && (source.is_empty() || r.source.is_empty() || r.source == source))
|
||||
}
|
||||
|
||||
/// Runs `request` through `installer`, then rescans `catalog` after an install or removal.
|
||||
/// Runs `request` through `installer`, then rescans `catalog` after an install or removal. An install also records
|
||||
/// the family's choice and copies it into the OS user font folder when that is the choice.
|
||||
pub fn start(&mut self, host: Option<&Arc<Host>>, 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())
|
||||
@@ -147,8 +168,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::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 wake = self.waker();
|
||||
let task: Task = Box::new(move || {
|
||||
@@ -157,17 +180,30 @@ impl Jobs {
|
||||
wake.wake();
|
||||
};
|
||||
let family = |index: &Index, i: usize| index.families().get(i).cloned().ok_or_else(|| StoreError("no such family".into()));
|
||||
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(|()| Finished::Installed)
|
||||
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(|()| Finished::Installed)
|
||||
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::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)) {
|
||||
if matches!(result, Ok(Finished::Installed(_) | Finished::Removed)) {
|
||||
catalog.rescan();
|
||||
}
|
||||
let _ = tx.send(Msg::Done(id, result));
|
||||
@@ -221,3 +257,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)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ use craft_host::Section;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::buttons::{ControlPlace, IconButton};
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
|
||||
Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, InBar, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop,
|
||||
};
|
||||
use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow};
|
||||
@@ -621,6 +621,7 @@ struct Typing {
|
||||
hide_classes: bool,
|
||||
expanded: Vec<String>,
|
||||
rested: Vec<String>,
|
||||
focused: bool,
|
||||
}
|
||||
|
||||
/// The interface language code of the host, English without one.
|
||||
@@ -666,7 +667,10 @@ enum Stop {
|
||||
}
|
||||
|
||||
/// The font family field. Typing filters the list to the families whose name (in any language) matches, the best
|
||||
/// match first, and opens it; a click on the name while the list is closed, the chevron and Alt+Down open it on every family (the click selects the name), Alt+Up closes it. Rows: a star, the
|
||||
/// match first, and opens it; in the library picker a click on the name while the list is closed opens it on every
|
||||
/// family and selects the name, whereas in `Plain` only a click that focuses the field selects the name without opening
|
||||
/// the list (subsequent clicks place the caret). The chevron and Alt+Down open the list on every family, and Alt+Up
|
||||
/// closes it. Rows: a star, the
|
||||
/// family name in the interface face, the sample text (the preview text, else "Sample") in the family's own face at the
|
||||
/// preview size and the class mark.
|
||||
/// Recent families form a group at the top. Up, Down and Page keys move the keyboard row, which previews, Enter or a
|
||||
@@ -728,6 +732,9 @@ pub struct FontPicker<'a> {
|
||||
#[prop]
|
||||
current_host: Option<String>,
|
||||
host_picked: Option<String>,
|
||||
/// Whether the font picker uses compact bar sizing (`size.length.field.sm` / `size.length.short`).
|
||||
#[style_key]
|
||||
compact: bool,
|
||||
}
|
||||
|
||||
/// How many times a closed [`FontPicker`] built its stop list on `ctx`, for regression trials.
|
||||
@@ -774,11 +781,19 @@ impl<'a> FontPicker<'a> {
|
||||
host: &[],
|
||||
current_host: None,
|
||||
host_picked: None,
|
||||
compact: false,
|
||||
}
|
||||
.label(label)
|
||||
.enabled(catalog.is_ready())
|
||||
}
|
||||
|
||||
/// Sets whether the font picker uses compact bar sizing (`size.length.field.sm` / `size.length.short`).
|
||||
#[must_use]
|
||||
pub fn compact(mut self, compact: bool) -> Self {
|
||||
self.compact = compact;
|
||||
self
|
||||
}
|
||||
|
||||
/// The adornments at the end of the field: the missing mark when `missing`, then the chevron. The mark is a glyph
|
||||
/// whose part carries the note.
|
||||
fn trailing(name: Label, missing: bool, arrow: DropdownArrow) -> Vec<Adornment> {
|
||||
@@ -893,11 +908,14 @@ impl Component for FontPicker<'_> {
|
||||
type Style = FontPickerStyle;
|
||||
type Output = FontPickerOutput;
|
||||
|
||||
/// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a
|
||||
/// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows.
|
||||
fn style(cx: &StyleCx<'_>, _: FontPickerStyleKey) -> FontPickerStyle {
|
||||
/// A field; in a ribbon (`ControlPlace::Ribbon`) or toolbar (`InBar`), or when `compact` is set,
|
||||
/// held at the small field length (`size.length.field.sm`), as a ribbon's font box is:
|
||||
/// wide enough for a family name and its menu arrow, the same width whichever it shows.
|
||||
fn style(cx: &StyleCx<'_>, key: FontPickerStyleKey) -> FontPickerStyle {
|
||||
let field = FieldStyle::at(cx);
|
||||
let field = if cx.env::<ControlPlace>() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field };
|
||||
let in_bar = cx.env::<InBar>().0;
|
||||
let ribbon = cx.env::<ControlPlace>() == ControlPlace::Ribbon;
|
||||
let field = if key.compact || ribbon || in_bar { field.held_at(cx.tokens.size.length.field.sm) } else { field };
|
||||
let warn = cx.tone(Tone::Warn);
|
||||
let off = cx.color(cx.tokens.color.text.disabled);
|
||||
let thumb = &cx.tokens.size.thumb;
|
||||
@@ -919,7 +937,7 @@ impl Component for FontPicker<'_> {
|
||||
}
|
||||
|
||||
/// The width of the longest family names in common use, so the field keeps its size whichever family is picked.
|
||||
/// In a ribbon the name field is the short field length (`size.length.short`) wide whichever family it shows, a
|
||||
/// In a ribbon or toolbar the name field is the short field length (`size.length.short`) wide whichever family it shows, a
|
||||
/// longer name scrolling in it as in a word processor's font box: that is its least, about the old ribbon's font
|
||||
/// name, so a row short of room never narrows the box to its menu arrow; where the room allows the style holds
|
||||
/// the box at the small field length (`FieldStyle::held_at`).
|
||||
@@ -927,8 +945,8 @@ impl Component for FontPicker<'_> {
|
||||
let host = self.host_name();
|
||||
let current = host.as_deref().or(cx.value().map(String::as_str)).unwrap_or("");
|
||||
let widest = [NAME_SAMPLE, current].into_iter().map(|text| cx.field_text(&TextRun::new(text))).fold(Vec2::ZERO, Vec2::max);
|
||||
let ribbon = cx.env.get::<ControlPlace>() == ControlPlace::Ribbon;
|
||||
let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest };
|
||||
let compact = self.compact || cx.env.get::<ControlPlace>() == ControlPlace::Ribbon || cx.env.get::<InBar>().0;
|
||||
let widest = if compact { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest };
|
||||
let name = cx.words::<FontPickerWords>().list.clone();
|
||||
let note = self.missing_note(current, &cx.words::<MissingFontsWords>());
|
||||
Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some(), cx.env.get())), widest.y)
|
||||
@@ -977,6 +995,8 @@ impl Component for FontPicker<'_> {
|
||||
if !self.catalog.is_ready() {
|
||||
return;
|
||||
}
|
||||
let focused = cx.is_focused();
|
||||
let was_focused = std::mem::replace(&mut cx.memory::<Typing>().focused, focused);
|
||||
let list = cx.popup(POPUP);
|
||||
let draft = cx.text(&text_key()).and_then(|outcome| outcome.draft.clone());
|
||||
let before = std::mem::replace(&mut cx.memory::<Typing>().draft, draft.clone());
|
||||
@@ -992,10 +1012,18 @@ impl Component for FontPicker<'_> {
|
||||
}
|
||||
}
|
||||
// A click on the name while the list is closed opens it on every family and selects the name, so typing
|
||||
// replaces it (Photoshop's font field).
|
||||
// replaces it (Photoshop's font field). In Word's plain font picker, clicking selects the name without
|
||||
// auto-opening the popup list so the user can immediately type a replacement family. Subsequent clicks on
|
||||
// an already-focused plain field place the caret rather than re-selecting all text.
|
||||
if !list.is_open(cx) && cx.text(&text_key()).is_some_and(|outcome| outcome.clicked) {
|
||||
cx.select_all_text();
|
||||
list.open(cx);
|
||||
if self.kind == FontPickerKind::Plain {
|
||||
if !was_focused {
|
||||
cx.select_all_text();
|
||||
}
|
||||
} else {
|
||||
cx.select_all_text();
|
||||
list.open(cx);
|
||||
}
|
||||
}
|
||||
if list.is_open(cx) {
|
||||
return;
|
||||
|
||||
@@ -16,7 +16,7 @@ use craft_font_catalog::Catalog;
|
||||
pub use craft_font_store::PreviewStore;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use craft_font_store::{Cancel, Client, Face, FontStore, Network, PINNED_INDEX, verify_font};
|
||||
pub use craft_font_store::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource};
|
||||
pub use craft_font_store::{Conflict, LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, UserSource};
|
||||
|
||||
use crate::index::{Family, Index};
|
||||
|
||||
@@ -97,6 +97,17 @@ impl std::fmt::Display for StoreError {
|
||||
|
||||
impl std::error::Error for StoreError {}
|
||||
|
||||
/// What [`Installer::make_available`] did.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum MadeAvailable {
|
||||
/// The family's copies are in the OS user font folder.
|
||||
Done,
|
||||
/// Refused, changing nothing: fonts on the system already have the family's PostScript
|
||||
/// names, or sit where its copies would go.
|
||||
Refused(Vec<Conflict>),
|
||||
}
|
||||
|
||||
fn err(e: impl std::fmt::Display) -> StoreError {
|
||||
StoreError(e.to_string())
|
||||
}
|
||||
@@ -173,9 +184,87 @@ pub trait Installer: PreviewStore {
|
||||
fn legal_text(&self, _index: &Index, _family: &Family, _which: LegalText) -> Result<Option<String>, StoreError> {
|
||||
Err(StoreError(NO_FOLDER.into()))
|
||||
}
|
||||
|
||||
/// Whether store families can be made available to all apps (copied into the OS user font
|
||||
/// folder). The interface offers the action only when this is true.
|
||||
fn available_to_all_supported(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Why store families can't be made available to all apps here, in English; `None` when they
|
||||
/// can.
|
||||
fn available_to_all_unsupported(&self) -> Option<String> {
|
||||
(!self.available_to_all_supported()).then(|| NOT_HERE.to_owned())
|
||||
}
|
||||
|
||||
/// 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. 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 {
|
||||
false
|
||||
}
|
||||
|
||||
/// The files of an available store family not available to all apps yet (styles an agent
|
||||
/// installed, say), by their names in the store, for the interface to offer copying them.
|
||||
fn not_yet_available(&self, _family: &str, _files: &[PathBuf]) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Makes a store family available to all apps, as the user's own action; calling it again
|
||||
/// copies the styles [`Installer::not_yet_available`] lists. A font on the system with one of
|
||||
/// its PostScript names refuses it ([`MadeAvailable::Refused`]). It blocks (hashing, copying,
|
||||
/// a catalog rescan): call it on a worker thread.
|
||||
fn make_available(&self, _family: &str, _files: &[PathBuf]) -> Result<MadeAvailable, StoreError> {
|
||||
Err(StoreError(NOT_HERE.into()))
|
||||
}
|
||||
|
||||
/// Takes a store family's copies out of the OS user font folder, as the user's own action.
|
||||
/// Returns the copies left in place because they changed since. It blocks: call it on a
|
||||
/// worker thread.
|
||||
fn withdraw(&self, _family: &str, _files: &[PathBuf]) -> Result<Vec<PathBuf>, StoreError> {
|
||||
Err(StoreError(NOT_HERE.into()))
|
||||
}
|
||||
}
|
||||
|
||||
const NO_FOLDER: &str = "there is no folder for the font store";
|
||||
const NOT_HERE: &str = "fonts can't be made available to all apps here";
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
/// craft-font-store's store, in the user's font store folder.
|
||||
@@ -209,17 +298,25 @@ impl SuiteStore {
|
||||
self.store.client()
|
||||
}
|
||||
|
||||
/// The store's source and name for the family holding `files`, which can differ from the
|
||||
/// name in the fonts themselves.
|
||||
fn installed_name(&self, request: &RemoveRequest) -> Option<(String, String)> {
|
||||
/// 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 lower = request.family.to_lowercase();
|
||||
installed
|
||||
let mut installed = self.store.installed();
|
||||
let lower = family.to_lowercase();
|
||||
let pos = installed
|
||||
.iter()
|
||||
.find(|f| request.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> {
|
||||
self.installed_name(family, files).ok_or_else(|| err(craft_font_store::Error::NotInstalled(family.to_owned())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,7 +342,7 @@ impl Installer for SuiteStore {
|
||||
}
|
||||
|
||||
fn remove(&self, request: &RemoveRequest) -> Result<(), StoreError> {
|
||||
let (source, name) = self.installed_name(request).ok_or_else(|| err(craft_font_store::Error::NotInstalled(request.family.clone())))?;
|
||||
let (source, name) = self.found(&request.family, &request.files)?;
|
||||
if request.whole {
|
||||
return self.store.remove_family(&source, &name).map_err(err);
|
||||
}
|
||||
@@ -320,6 +417,59 @@ impl Installer for SuiteStore {
|
||||
fn legal_text(&self, index: &Index, family: &Family, which: LegalText) -> Result<Option<String>, StoreError> {
|
||||
self.store.legal_text(index, family, which, &Cancel::new()).map_err(err)
|
||||
}
|
||||
|
||||
fn available_to_all_supported(&self) -> bool {
|
||||
self.store.available_to_all_supported()
|
||||
}
|
||||
|
||||
fn available_to_all_unsupported(&self) -> Option<String> {
|
||||
self.store.available_to_all_unsupported().map(str::to_owned)
|
||||
}
|
||||
|
||||
fn craft_apps_only(&self) -> bool {
|
||||
self.store.craft_apps_only()
|
||||
}
|
||||
|
||||
fn set_craft_apps_only(&self, on: bool) -> Result<(), StoreError> {
|
||||
self.store.set_craft_apps_only(on).map_err(err)
|
||||
}
|
||||
|
||||
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 {
|
||||
self.store.available_family_holding(family, files).is_some()
|
||||
}
|
||||
|
||||
fn not_yet_available(&self, family: &str, files: &[PathBuf]) -> Vec<String> {
|
||||
self.installed_name(family, files).map(|(source, name)| self.store.pending_files(&source, &name)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn make_available(&self, family: &str, files: &[PathBuf]) -> Result<MadeAvailable, StoreError> {
|
||||
let (source, name) = self.found(family, files)?;
|
||||
match self.store.make_available(&source, &name) {
|
||||
Ok(_) => Ok(MadeAvailable::Done),
|
||||
Err(craft_font_store::Error::Conflict(conflicts)) => Ok(MadeAvailable::Refused(conflicts)),
|
||||
Err(e) => Err(err(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn withdraw(&self, family: &str, files: &[PathBuf]) -> Result<Vec<PathBuf>, StoreError> {
|
||||
// A family an unsupported build removed keeps its ledger entry and copies.
|
||||
let (source, name) = self.found(family, files).or_else(|e| self.store.available_family_holding(family, files).ok_or(e))?;
|
||||
self.store.withdraw(&source, &name).map_err(err)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! The in-memory font store used by tests.
|
||||
|
||||
use super::{
|
||||
AtomicBool, Condvar, Downloaded, Family, HashMap, Index, Installer, Mutex, Ordering, Path, PathBuf, Progress, RemoveRequest, StoreError,
|
||||
UserSource, err,
|
||||
AtomicBool, Condvar, Conflict, Downloaded, Family, HashMap, Index, Installer, MadeAvailable, Mutex, Ordering, Path, PathBuf, Progress,
|
||||
RemoveRequest, StoreError, UserSource, err,
|
||||
};
|
||||
use super::{LegalText, PreviewServiceSource, PreviewStore};
|
||||
|
||||
@@ -18,6 +18,10 @@ pub enum Call {
|
||||
Remove(String),
|
||||
/// Asked to download the family.
|
||||
Download(String),
|
||||
/// Asked to copy the family into the OS user font folder.
|
||||
MakeAvailable(String),
|
||||
/// Asked to take the family's copies out of the OS user font folder.
|
||||
Withdraw(String),
|
||||
}
|
||||
|
||||
/// A font store without a network: "downloads" come from a table of file bytes by index path,
|
||||
@@ -43,6 +47,13 @@ pub struct FakeStore {
|
||||
changed: Mutex<Vec<String>>,
|
||||
/// Downloads stop halfway while this is true.
|
||||
held: (Mutex<bool>, Condvar),
|
||||
/// 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>>>,
|
||||
}
|
||||
|
||||
impl FakeStore {
|
||||
@@ -63,6 +74,10 @@ impl FakeStore {
|
||||
fetched: Mutex::new(Vec::new()),
|
||||
changed: Mutex::new(Vec::new()),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,6 +113,13 @@ impl FakeStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// The next [`Installer::make_available`] is refused for `conflicts`.
|
||||
pub fn refuse_next(&self, conflicts: Vec<Conflict>) {
|
||||
if let Ok(mut refusal) = self.refusal.lock() {
|
||||
*refusal = Some(conflicts);
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads report half their bytes, then wait until [`FakeStore::release`] (with
|
||||
/// `Runner::Thread`).
|
||||
pub fn hold(&self) {
|
||||
@@ -201,6 +223,10 @@ impl Installer for FakeStore {
|
||||
if let Some(outside) = request.files.iter().find(|f| !self.in_store(f)) {
|
||||
return Err(StoreError(format!("{} isn't in the font store", outside.display())));
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
@@ -303,6 +329,57 @@ impl Installer for FakeStore {
|
||||
let bytes = self.files.get(path).ok_or_else(|| StoreError(format!("{path} isn't available")))?;
|
||||
Ok(Some(String::from_utf8_lossy(bytes).into_owned()))
|
||||
}
|
||||
|
||||
fn available_to_all_supported(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_available_to_all(&self, family: &str, _files: &[PathBuf]) -> bool {
|
||||
self.available.lock().is_ok_and(|a| a.iter().any(|f| f.eq_ignore_ascii_case(family)))
|
||||
}
|
||||
|
||||
fn craft_apps_only(&self) -> bool {
|
||||
self.craft_apps_only.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn set_craft_apps_only(&self, on: bool) -> Result<(), StoreError> {
|
||||
self.craft_apps_only.store(on, Ordering::SeqCst);
|
||||
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> {
|
||||
self.record(Call::MakeAvailable(family.to_owned()));
|
||||
if let Some(conflicts) = self.refusal.lock().map_err(err)?.take() {
|
||||
return Ok(MadeAvailable::Refused(conflicts));
|
||||
}
|
||||
let mut available = self.available.lock().map_err(err)?;
|
||||
if !available.iter().any(|f| f.eq_ignore_ascii_case(family)) {
|
||||
available.push(family.to_owned());
|
||||
}
|
||||
Ok(MadeAvailable::Done)
|
||||
}
|
||||
|
||||
fn withdraw(&self, family: &str, _files: &[PathBuf]) -> Result<Vec<PathBuf>, StoreError> {
|
||||
self.record(Call::Withdraw(family.to_owned()));
|
||||
self.available.lock().map_err(err)?.retain(|f| !f.eq_ignore_ascii_case(family));
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl PreviewStore for FakeStore {
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_font_manager::craft_font_catalog::Os;
|
||||
use craft_font_manager::index::Index;
|
||||
use craft_font_manager::store::{Call, FakeStore};
|
||||
use craft_font_manager::store::{Call, Conflict, FakeStore, Installer as _};
|
||||
use craft_font_manager::{Catalog, FontEnv, FontsPanel, FontsPanelView, Options};
|
||||
use craft_host::{AppInfo, Host, InlineJobs, Jobs, MemorySections};
|
||||
use craft_ui::contract::Role;
|
||||
@@ -86,20 +86,30 @@ fn setup_with(name: &str, sections: Arc<MemorySections>) -> Rig {
|
||||
}
|
||||
|
||||
fn setup_jobs(name: &str, sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>) -> Rig {
|
||||
setup_seeded(name, sections, jobs, |_| {})
|
||||
}
|
||||
|
||||
/// [`setup_jobs`] after `seed` filled the store folder, as families installed by an earlier run.
|
||||
fn setup_seeded(name: &str, sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>, seed: impl Fn(&Path)) -> Rig {
|
||||
let root = root(name);
|
||||
let system = root.join("usr/share/fonts");
|
||||
std::fs::create_dir_all(&system).unwrap();
|
||||
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()),
|
||||
]);
|
||||
let store = Arc::new(FakeStore::new(store_dir, files));
|
||||
start(&root, Arc::new(FakeStore::new(store_dir, files)), sections, jobs)
|
||||
}
|
||||
|
||||
/// The panel over the system under `root` and `store`, as at a start of the app.
|
||||
fn start(root: &Path, store: Arc<FakeStore>, sections: Arc<MemorySections>, jobs: Arc<dyn Jobs>) -> Rig {
|
||||
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 panel = Rc::new(RefCell::new(FontsPanel::new(Options::new(catalog, store.clone(), Ok(index())))));
|
||||
let shown = Rc::clone(&panel);
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
@@ -218,7 +228,7 @@ fn queued_installs_run_one_runner_in_request_order() {
|
||||
assert_eq!(spawned.len(), 1, "one runner drains the queue");
|
||||
assert!(rig.store.calls().is_empty(), "nothing runs before the runner does");
|
||||
spawned.remove(0)();
|
||||
assert_eq!(rig.store.calls(), [Call::Install("Amiri".into()), Call::Install("Hack".into())]);
|
||||
assert_eq!(rig.store.calls(), [Call::Install("Amiri".into()), Call::Install("Hack".into()), Call::MakeAvailable("Hack".into())]);
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
@@ -255,3 +265,67 @@ fn a_press_outside_the_details_sheet_closes_it() {
|
||||
rig.fx.settle();
|
||||
assert_eq!(rig.panel.borrow().details_family(), None, "the sheet closed and no other family opened");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn installs_are_copied_to_the_system_fonts_folder_unless_kept_in_craft_apps() {
|
||||
let mut rig = setup("os-copy");
|
||||
rig.allow();
|
||||
let conflict = Conflict { postscript: Some("Hack-Regular".into()), path: PathBuf::from("/fonts/Hack-Regular.ttf") };
|
||||
rig.store.refuse_next(vec![conflict]);
|
||||
rig.open("Hack");
|
||||
rig.click("Install all");
|
||||
assert_eq!(rig.store.calls(), [Call::Install("Hack".into()), Call::MakeAvailable("Hack".into())]);
|
||||
assert!(rig.has_installed("Hack"));
|
||||
assert!(rig.present("Not copied to your system's fonts folder: /fonts/Hack-Regular.ttf already has the font name Hack-Regular"));
|
||||
|
||||
// The setting decides what Install does from now on; Hack stays as it is.
|
||||
rig.key(Key::Escape);
|
||||
rig.click("Keep fonts in Craft apps only");
|
||||
assert!(rig.store.craft_apps_only());
|
||||
assert_eq!(rig.store.calls().len(), 2);
|
||||
rig.open("Hack");
|
||||
rig.click("Remove all");
|
||||
rig.click("Install all");
|
||||
assert_eq!(rig.store.calls()[2..], [Call::Remove("Hack".into()), Call::Install("Hack".into())]);
|
||||
assert!(rig.present("Kept in Craft apps only"));
|
||||
|
||||
// The details switch copies it after all.
|
||||
rig.click("Make available to all apps");
|
||||
assert_eq!(rig.store.calls().last(), Some(&Call::MakeAvailable("Hack".into())));
|
||||
assert!(rig.present("Available to all apps"));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
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: &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 rig = setup_seeded("os-choice", Arc::new(MemorySections::default()), Arc::new(InlineJobs), seed);
|
||||
assert_eq!(rig.store.calls(), [Call::MakeAvailable("Ubuntu".into())]);
|
||||
|
||||
rig.allow();
|
||||
rig.open("Hack");
|
||||
rig.click("More install all options");
|
||||
rig.click("Install for Craft apps only");
|
||||
assert_eq!(rig.store.calls()[1..], [Call::Install("Hack".into())]);
|
||||
assert!(rig.present("Kept in Craft apps only"));
|
||||
|
||||
// The next start copies neither: Hack is kept in Craft apps, Ubuntu is there already.
|
||||
let root = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("panel").join("os-choice");
|
||||
let again = start(&root, rig.store.clone(), Arc::new(MemorySections::default()), Arc::new(InlineJobs));
|
||||
assert_eq!(again.store.calls().len(), 2);
|
||||
}
|
||||
|
||||
/// A card's Install menu installs for the choice picked, and the press on it opens no details.
|
||||
#[trial]
|
||||
fn a_cards_install_menu_chooses_where_the_fonts_go() {
|
||||
let mut rig = setup("card-menu");
|
||||
rig.allow();
|
||||
rig.type_into("Search", "Hack");
|
||||
rig.click("More install options");
|
||||
rig.click("Install for Craft apps only");
|
||||
assert_eq!(rig.store.calls(), [Call::Install("Hack".into())]);
|
||||
assert_eq!(rig.panel.borrow().details_family(), None);
|
||||
}
|
||||
@@ -575,6 +575,9 @@ fn a_plain_box_commits_an_unknown_typed_name_lists_recents_first_and_again_after
|
||||
fx.settle();
|
||||
|
||||
let field = fx.by_label("Font family").expect("the family field");
|
||||
// Unfocus after Escape so the click below is a focusing click that selects all text in Plain mode.
|
||||
fx.click_at(field.rect.right_center() + egui::vec2(20.0, 0.0));
|
||||
fx.settle();
|
||||
fx.click(&field);
|
||||
fx.settle();
|
||||
fx.type_text("x");
|
||||
@@ -592,6 +595,76 @@ fn a_plain_box_commits_an_unknown_typed_name_lists_recents_first_and_again_after
|
||||
assert_eq!(seen.borrow().picks.last().map(|(picked, _)| picked.as_str()), Some("Zapfino"));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn clicking_the_font_field_selects_all_without_opening_dropdown_and_chevron_toggles() {
|
||||
let catalog = catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]);
|
||||
let (mut fx, _seen) = plain_rig(catalog, "Inter", &["Hack"], vec![], None);
|
||||
let words = FontPickerWords::default();
|
||||
let (recently, all) = (words.recently_used.as_str(), words.all_fonts.as_str());
|
||||
|
||||
// 1. Clicking the text field focuses and selects all text without opening the dropdown popup
|
||||
let field = fx.by_label("Font family").expect("the family field");
|
||||
fx.click(&field);
|
||||
fx.settle();
|
||||
assert!(!present(&fx, recently), "recently used fonts do not open on field click");
|
||||
assert!(!present(&fx, all), "all fonts do not open on field click");
|
||||
|
||||
// 2. Typing in the field opens the dropdown filtered on matches
|
||||
fx.type_text("Ha");
|
||||
fx.settle();
|
||||
assert!(present(&fx, "Hack"), "typing in the field opens the dropdown with matches");
|
||||
|
||||
// Pressing Enter commits the typed family and closes the dropdown
|
||||
fx.key(Key::Enter, Modifiers::NONE);
|
||||
fx.settle();
|
||||
fx.frame(vec![]);
|
||||
fx.settle();
|
||||
assert!(!present(&fx, all), "committing typed query closes the dropdown");
|
||||
|
||||
// 3. Clicking the dropdown arrow (chevron) toggles the dropdown list open
|
||||
let chevron = fx.by_label(words.list.as_str()).expect("the chevron button");
|
||||
fx.click(&chevron);
|
||||
fx.settle();
|
||||
assert!(present(&fx, recently), "recently used fonts show up on chevron click");
|
||||
assert!(present(&fx, all), "all fonts show up on chevron click");
|
||||
|
||||
// 4. Clicking inside the field while already open keeps dropdown open
|
||||
let field = fx.by_label("Font family").expect("the family field");
|
||||
fx.click(&field);
|
||||
fx.settle();
|
||||
assert!(present(&fx, all), "dropdown remains open on click inside field");
|
||||
|
||||
// 5. Clicking the chevron button again toggles the dropdown closed
|
||||
let chevron = fx.by_label(words.list.as_str()).expect("the chevron button");
|
||||
fx.click(&chevron);
|
||||
fx.settle();
|
||||
fx.frame(vec![]);
|
||||
fx.settle();
|
||||
assert!(!present(&fx, all), "dropdown closes on chevron click toggle");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn clicking_the_focused_plain_box_places_caret_instead_of_selecting_all() {
|
||||
let catalog = catalog_of(&[INTER_REGULAR, epaint_default_fonts::HACK_REGULAR]);
|
||||
let (mut fx, _seen) = plain_rig(catalog, "Inter", &["Hack"], vec![], None);
|
||||
let field = fx.by_label("Font family").expect("the family field");
|
||||
|
||||
// 1. The first click gives the field focus and selects all text
|
||||
fx.click(&field);
|
||||
fx.settle();
|
||||
|
||||
// 2. Clicking again after double-click interval places the caret before the "I" without re-selecting all
|
||||
fx.advance(1.0);
|
||||
fx.click_at(field.rect.left_center() + egui::vec2(6.0, 0.0));
|
||||
fx.settle();
|
||||
|
||||
// 3. Typing "Ha" inserts before "Inter" producing "HaInter" rather than replacing the text with "Ha"
|
||||
fx.type_text("Ha");
|
||||
fx.settle();
|
||||
assert!(present(&fx, "HaInter"), "typing inserts at placed caret before the existing family name");
|
||||
assert!(!present(&fx, "Hack"), "Hack is not suggested because draft is HaInter, not Ha");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_action_row_is_reported_not_committed_and_a_missing_family_shows_the_note_naming_the_face() {
|
||||
let words = MissingFontsWords::default();
|
||||
@@ -656,6 +729,48 @@ fn a_ribbons_font_box_is_short_and_keeps_its_width() {
|
||||
assert!((long - ribbon).abs() < 0.5, "a long family name leaves its width: {long} against {ribbon}");
|
||||
}
|
||||
|
||||
/// In a toolbar (`InBar`) or when `compact` is set, the font box is held at the small field length,
|
||||
/// narrower than in a form, and keeps its width whichever family it shows.
|
||||
#[trial]
|
||||
fn a_bars_font_box_is_short_and_keeps_its_width() {
|
||||
let bar_width = |family: &'static str, in_bar: bool, compact: bool| {
|
||||
let catalog = catalog_of(&[INTER_REGULAR]);
|
||||
let mut fx = Fixture::new(move |ui| {
|
||||
let mut family = family.to_owned();
|
||||
let mut show = |ui: &mut egui::Ui| {
|
||||
let mut picker = FontPicker::new("Font family", Bind::bound(&mut family), &catalog).kind(FontPickerKind::Plain);
|
||||
if compact {
|
||||
picker = picker.compact(true);
|
||||
}
|
||||
let _ = picker.show(ui);
|
||||
};
|
||||
if in_bar {
|
||||
with_env(
|
||||
ui,
|
||||
|overrides| {
|
||||
overrides.values.set(craft_ui::contract::InBar(true));
|
||||
},
|
||||
show,
|
||||
);
|
||||
} else {
|
||||
show(ui);
|
||||
}
|
||||
});
|
||||
fx.in_room(Room::Window);
|
||||
fx.settle();
|
||||
fx.by_label("Font family").expect("the picker").rect.width()
|
||||
};
|
||||
let standard = bar_width("Inter", false, false);
|
||||
let bar = bar_width("Inter", true, false);
|
||||
let opt_in = bar_width("Inter", false, true);
|
||||
assert!(bar < standard - 0.5, "the bar's font box is narrower: {bar} against {standard}");
|
||||
assert!((bar - opt_in).abs() < 0.5, "the opt-in compact picker matches the bar picker: {opt_in} against {bar}");
|
||||
let length = craft_ui::testing::style::tokens(craft_theme::Mode::Light, craft_theme::Contrast::Standard).size.length.field.sm;
|
||||
assert!((bar - length).abs() < 0.5, "the bar's font box is the small field length {length}: {bar}");
|
||||
let long = bar_width("Source Sans Pro Semibold Condensed Extra", true, false);
|
||||
assert!((long - bar).abs() < 0.5, "a long family name leaves its width in a bar: {long} against {bar}");
|
||||
}
|
||||
|
||||
/// The width of a plain picker over "Inter" in a ribbon group's place, in a row beside a block that leaves it 60 pt of
|
||||
/// the window, so the row shrinks it to its least.
|
||||
fn squeezed_ribbon_picker_width() -> f32 {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "craft-font-os-windows"
|
||||
description = "The Win32 calls craft-font-store needs to make its fonts available to every app of the user on Windows: the HKCU font registry, AddFontResourceW and RemoveFontResourceW, and the WM_FONTCHANGE broadcast. Empty on other systems."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-registry = "0.6.1"
|
||||
windows-sys = { version = "0.61.2", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_Storage_Packaging_Appx",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
# Not `workspace = true`: the workspace forbids `unsafe`, and `forbid` can't be lifted for one
|
||||
# crate. Loading a font into the running session needs `AddFontResourceW`, which the Windows
|
||||
# crates offer only as an unsafe call, so this crate copies the workspace lints with
|
||||
# `unsafe_code = "deny"`, and allows it only on the functions that make those calls (AGENTS.md).
|
||||
# Keep these tables in step with `[workspace.lints]` in the root Cargo.toml.
|
||||
[lints.rust]
|
||||
unsafe_code = "deny"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] }
|
||||
|
||||
[lints.cargo]
|
||||
|
||||
[lints.clippy]
|
||||
cognitive_complexity = "deny"
|
||||
too_many_arguments = "deny"
|
||||
wildcard_imports = "deny"
|
||||
dbg_macro = "warn"
|
||||
todo = "warn"
|
||||
@@ -0,0 +1,178 @@
|
||||
//! The Win32 calls craft-font-store makes to put its fonts within reach of every app of the user
|
||||
//! on Windows 10 1809 and later: the per-user font registry (`HKCU\Software\Microsoft\Windows
|
||||
//! NT\CurrentVersion\Fonts`), `AddFontResourceW` and `RemoveFontResourceW` for the running
|
||||
//! session, and the `WM_FONTCHANGE` broadcast.
|
||||
//!
|
||||
//! This is the one crate in `crates/` that may use `unsafe` (AGENTS.md): the session calls exist
|
||||
//! only as unsafe functions. Each one is a small function of its own with `allow(unsafe_code)`.
|
||||
//! On other systems the calls report that they are unsupported, or do nothing.
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The per-user font key under `HKEY_CURRENT_USER`. Its values name a font (`<full name>
|
||||
/// (TrueType)`) and hold the font file's full path.
|
||||
pub const FONTS_KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Fonts";
|
||||
|
||||
/// Whether this process can add fonts for every app of the user: Windows 10 1809 (build 17763,
|
||||
/// the first with per-user fonts) or later, and not a packaged (MSIX) app, whose registry and
|
||||
/// `AppData` writes other apps don't see.
|
||||
pub fn check_supported() -> Result<(), String> {
|
||||
imp::check_supported()
|
||||
}
|
||||
|
||||
/// The path the per-user font value `name` holds, when there is one.
|
||||
pub fn registered(name: &str) -> Option<PathBuf> {
|
||||
imp::registered(name)
|
||||
}
|
||||
|
||||
/// Lists the font at `path` as the per-user font value `name`, so Windows loads it at each
|
||||
/// logon, and loads it into the running session.
|
||||
pub fn register(name: &str, path: &Path) -> io::Result<()> {
|
||||
imp::register(name, path)
|
||||
}
|
||||
|
||||
/// Unloads the font at `path` from the running session, so the file can be replaced or deleted.
|
||||
/// It calls `RemoveFontResourceW` until it fails, at most 1000 times: every `AddFontResourceW`
|
||||
/// counts. A program that holds the file open itself still keeps it.
|
||||
pub fn unload(path: &Path) {
|
||||
imp::unload(path);
|
||||
}
|
||||
|
||||
/// Unloads the font at `path` and deletes the per-user font value `name` while it still points
|
||||
/// to `path` (in any letter case).
|
||||
pub fn unregister(name: &str, path: &Path) -> io::Result<()> {
|
||||
imp::unregister(name, path)
|
||||
}
|
||||
|
||||
/// Tells every top-level window that the fonts changed (`WM_FONTCHANGE`). It waits up to a
|
||||
/// second for each window that doesn't answer, so call it off the UI thread.
|
||||
pub fn broadcast_font_change() {
|
||||
imp::broadcast_font_change();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use windows_registry::{CURRENT_USER, LOCAL_MACHINE};
|
||||
use windows_sys::Win32::Foundation::APPMODEL_ERROR_NO_PACKAGE;
|
||||
use windows_sys::Win32::Graphics::Gdi::{AddFontResourceW, RemoveFontResourceW};
|
||||
use windows_sys::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_FONTCHANGE};
|
||||
|
||||
use super::FONTS_KEY;
|
||||
|
||||
const FIRST_BUILD: u32 = 17763;
|
||||
|
||||
pub fn check_supported() -> Result<(), String> {
|
||||
let build = LOCAL_MACHINE
|
||||
.open(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion")
|
||||
.and_then(|k| k.get_string("CurrentBuildNumber"))
|
||||
.ok()
|
||||
.and_then(|b| b.trim().parse::<u32>().ok());
|
||||
if build.is_none_or(|b| b < FIRST_BUILD) {
|
||||
return Err("adding fonts for every app needs Windows 10 version 1809 or later".into());
|
||||
}
|
||||
if packaged() {
|
||||
return Err("a packaged (MSIX) app can't add fonts for other apps".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
fn packaged() -> bool {
|
||||
let mut len = 0u32;
|
||||
// SAFETY: with a length of 0 and a null buffer the call writes only the length it would
|
||||
// need to `len`, which outlives the call.
|
||||
let status = unsafe { GetCurrentPackageFullName(&mut len, std::ptr::null_mut()) };
|
||||
status != APPMODEL_ERROR_NO_PACKAGE
|
||||
}
|
||||
|
||||
pub fn registered(name: &str) -> Option<PathBuf> {
|
||||
CURRENT_USER.open(FONTS_KEY).ok()?.get_string(name).ok().map(PathBuf::from)
|
||||
}
|
||||
|
||||
pub fn register(name: &str, path: &Path) -> io::Result<()> {
|
||||
let data = path.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the font's path isn't valid Unicode"))?;
|
||||
CURRENT_USER.create(FONTS_KEY).and_then(|k| k.set_string(name, data)).map_err(io::Error::other)?;
|
||||
if add_font_resource(path) == 0 {
|
||||
return Err(io::Error::other(format!("Windows didn't load {}", path.display())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unregister(name: &str, path: &Path) -> io::Result<()> {
|
||||
unload(path);
|
||||
if registered(name).is_some_and(|p| same_path(&p, path)) {
|
||||
CURRENT_USER.create(FONTS_KEY).and_then(|k| k.remove_value(name)).map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether two Windows paths name the same file, ignoring letter case.
|
||||
fn same_path(a: &Path, b: &Path) -> bool {
|
||||
a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase()
|
||||
}
|
||||
|
||||
/// `path` as a NUL-terminated UTF-16 string.
|
||||
fn wide(path: &Path) -> Vec<u16> {
|
||||
path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
fn add_font_resource(path: &Path) -> i32 {
|
||||
let wide = wide(path);
|
||||
// SAFETY: `wide` is a NUL-terminated UTF-16 string that outlives the call, which only
|
||||
// reads it.
|
||||
unsafe { AddFontResourceW(wide.as_ptr()) }
|
||||
}
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
pub fn unload(path: &Path) {
|
||||
let wide = wide(path);
|
||||
for _ in 0..1000 {
|
||||
// SAFETY: `wide` is a NUL-terminated UTF-16 string that outlives the call, which only
|
||||
// reads it.
|
||||
if unsafe { RemoveFontResourceW(wide.as_ptr()) } == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
pub fn broadcast_font_change() {
|
||||
let mut result = 0usize;
|
||||
// SAFETY: `WM_FONTCHANGE` carries no pointers (both parameters are 0), and `result`
|
||||
// outlives the call, which only writes it.
|
||||
unsafe { SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0, SMTO_ABORTIFHUNG, 1000, &mut result) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod imp {
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn check_supported() -> Result<(), String> {
|
||||
Err("the Windows font registry exists only on Windows".into())
|
||||
}
|
||||
|
||||
pub fn registered(_name: &str) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn register(_name: &str, _path: &Path) -> io::Result<()> {
|
||||
Err(io::ErrorKind::Unsupported.into())
|
||||
}
|
||||
|
||||
pub fn unload(_path: &Path) {}
|
||||
|
||||
pub fn unregister(_name: &str, _path: &Path) -> io::Result<()> {
|
||||
Err(io::ErrorKind::Unsupported.into())
|
||||
}
|
||||
|
||||
pub fn broadcast_font_change() {}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ thiserror = { workspace = true }
|
||||
cap-primitives = "4.0.3"
|
||||
craft-atomic = { workspace = true }
|
||||
craft-font-catalog = { workspace = true }
|
||||
# The Windows font registry and session calls; empty elsewhere.
|
||||
craft-font-os-windows = { workspace = true }
|
||||
log = "0.4"
|
||||
# Language packs (`language_packs`): `<locale>.tar.zst` archives, unpacked in pure Rust.
|
||||
ruzstd = { version = "0.9", default-features = false, features = ["std"] }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# craft-font-store
|
||||
|
||||
The suite's font store: the font indexes of every source, exact lookup of a missing font, and verified installs into the one folder every app's font catalog reads ([`craft-font-catalog`](../font-catalog/README.md)'s `font_store_dir`).
|
||||
The suite's font store: the font indexes of every source, exact lookup of a missing font, verified installs into the one folder every app's font catalog reads ([`craft-font-catalog`](../font-catalog/README.md)'s `font_store_dir`), and, per family at the user's request, copies in the OS user font folder so that every other program can use it.
|
||||
|
||||
The indexes are [aiongg/craft-font-index](https://github.com/aiongg/craft-font-index) (format 1.x), designed by @kntrttm for photocraft#1135 and #2453. Every font file and licence in an index has a size and a sha256, and only families under a licence that allows redistribution (OFL, Apache 2.0, Ubuntu Font Licence) are listed.
|
||||
|
||||
@@ -31,6 +31,7 @@ A source the user adds is an index file at an https URL (`.json` or `.json.gz`).
|
||||
| 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. |
|
||||
| Preview client | `preview`: subset keys and URLs (`PreviewKey`, `Codepoints`, `SampleHash`), the disk cache (`DiskCache`, least recently used out past 50 MB) and the pool that fetches and decodes WOFF2 subsets on threads of its own (`Previews`). The pool reads the service, the previews setting, the client and the cache folder through `PreviewStore`, which the font manager's `Installer` builds on. It requests nothing without a service or with previews off; cached subsets still load. |
|
||||
| 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. |
|
||||
|
||||
@@ -100,6 +101,7 @@ When every file has passed, the store takes `.lock`, moves the files into the fa
|
||||
```text
|
||||
settings.json the network setting and the sources the user added
|
||||
manifest.json what is installed
|
||||
os-fonts.json the ledger of copies in the OS user font folder
|
||||
indexes/ the last indexes fetched: sources.json, <source>.json.gz, user-<hash>
|
||||
previews/ preview subsets (WOFF2) the preview pool caches, at most 50 MB
|
||||
<family folder>/ the font files and the licence
|
||||
@@ -111,12 +113,12 @@ 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 |
|
||||
|---|---|
|
||||
| `installed()`, `installed_family(source, name)`, `is_installed(family, file)` | Read the manifest. |
|
||||
| `remove_family(source, name)` | Moves the family folder out at once, updates the manifest, then deletes the files and the licence. |
|
||||
| `remove_family(source, name)` | Withdraws the family's copies from the OS user font folder (user only when it has some), moves the family folder out at once, updates the manifest, then deletes the files and the licence. `remove_files` withdraws the copies of the files it removes. |
|
||||
| `verify()` | Reads every installed file and reports the missing, damaged and unparseable ones. |
|
||||
| `user_sources()`, `add_user_source(url)`, `remove_user_source(url)` | The sources the user added. Removing one leaves its installed families installed. |
|
||||
|
||||
@@ -170,6 +172,76 @@ Windows retains ancestor handles that prevent their replacement during cleanup.
|
||||
|
||||
**Developer override (testing only — bypasses the pin):** `CRAFT_LANGUAGE_PACK_INDEX=<url or path>` replaces the pinned index URL with an `http://` URL on a loopback host (`127.0.0.1`, `localhost`, `[::1]`), an `https://` URL or a local file path (`file://` URLs are not taken), and **skips the index's sha256 pin**. Archives are still checked against the sha256 and size in that index, and may then also be loopback `http://` URLs or local paths. Off unless the variable is set; it works in release builds too (for end-to-end tests of a real build), a warning is logged whenever it is used, and `language_pack_index_overridden() -> Option<String>` returns the value so apps can show that the pin is bypassed. Never set it for users.
|
||||
|
||||
## Copies in the OS font folder
|
||||
|
||||
Fonts in the store are for the Craft apps only. A family can also be copied into the OS user font folder, for every other program of the current user (the API calls this making it available to all apps). The calls below work per family; whether an app copies every family the user installs or lets the user choose per family is the app's decision. Only the user's store (`for_user`) changes the OS folder.
|
||||
|
||||
| Call | What it does |
|
||||
|---|---|
|
||||
| `available_to_all_supported()`, `available_to_all_unsupported()` | Whether the action works here, and why not. The interface hides it when it doesn't. |
|
||||
| `make_available(source, name)` | Checks for conflicts, copies the family's font files into the OS user font folder and records them in the ledger. Calling it again copies styles installed since and brings the copies up to date. Returns the copies. |
|
||||
| `withdraw(source, name)` | Deletes the copies the ledger lists, each only if its sha256 is unchanged. Returns the copies left in place because they changed. |
|
||||
| `is_available(source, name)`, `available_family_holding(name, files)`, `available_files(source, name)` | Read the ledger. They read the file again only when it changed, so a list can ask for every row. `available_family_holding` goes by the store files when it has them, so a family of the same name from another source doesn't count. |
|
||||
| `copies_out_of_reach(source, name)` | The family's listed copies when this build can't change the OS folder (a Flatpak whose access to it was revoked). Removing the family leaves them. |
|
||||
| `pending_files(source, name)` | Files of an available family not available yet: styles installed since by an agent, or whose copy is older than the store's file. |
|
||||
|
||||
`make_available`, `withdraw`, the installs and removals block (hashing, copying, a catalog rescan): call them off the UI thread.
|
||||
|
||||
### Who may change the OS folder
|
||||
|
||||
Only the user. An agent (`for_agent`) never changes what is in the OS font folder:
|
||||
|
||||
- `make_available` and `withdraw` give it `Error::NotAllowed`.
|
||||
- Its install into an available family stays in the store; the new files show in `pending_files`, and the interface offers to copy them. The user's install copies them at once.
|
||||
- Its `remove_family` of a family with copies, and its `remove_files` of files with copies, give `Error::NotAllowed` before anything changes.
|
||||
|
||||
The user's `remove_family` and `remove_files` withdraw the copies first, so the ledger never lists copies of fonts the store no longer has. Where this build can't change the OS folder (a Flatpak whose `xdg-data/fonts` access was revoked, a Snap build) but the ledger lists copies, removing the family removes its store files and leaves the copies, still listed in the ledger: a build that has the folder withdraws them, and a reinstall finds them the store's. `copies_out_of_reach` names them beforehand.
|
||||
|
||||
### Folders
|
||||
|
||||
| System | Folder (`OsFontFolder::for_env`) | Copies |
|
||||
|---|---|---|
|
||||
| macOS | `~/Library/Fonts` | `Craft-<family folder>-<file>`, side by side. macOS activates them for every app of the user. |
|
||||
| Linux and the BSDs | `$XDG_DATA_HOME/fonts/Craft` (`~/.local/share/fonts/Craft`) | `<store family folder>/<file>`. fontconfig reads the folder with its subfolders; `fc-cache` refreshes the cache afterwards when it is on `PATH`, off the calling thread. |
|
||||
| Flatpak | the host's `$HOST_XDG_DATA_HOME/fonts/Craft`, else `~/.local/share/fonts/Craft` | Only when `/.flatpak-info` grants write access to that folder (`--filesystem=xdg-data/fonts:create`; its entries apply in order, `!name` revokes and `:ro` grants no write). No `fc-cache`: it would refresh the sandbox's cache. |
|
||||
| Windows 10 1809 and later | `%LOCALAPPDATA%\Microsoft\Windows\Fonts\Craft` | `<store family folder>/<file>`, each listed as `<full name> (TrueType)` (or `(OpenType)` for CFF outlines) under `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Fonts`, loaded into the running session with `AddFontResourceW`, then `WM_FONTCHANGE` is broadcast off the calling thread. A registry value that already names another file is a conflict. Withdrawing unloads the font, deletes the value, then deletes the file; a file another program still holds can't be deleted, so the withdrawal fails and the ledger keeps the copy for the next try. The Win32 calls are in `craft-font-os-windows`. |
|
||||
| Snap, a sandboxed macOS build (Mac App Store), a packaged (MSIX) Windows build, older Windows, Haiku, the web | none | `Error::Unsupported`. |
|
||||
|
||||
`FontStore::new` has no folder; `with_os_fonts(OsFontFolder::at(dir, layout))` sets one, for tests and setups the rules above don't cover.
|
||||
|
||||
Only font files are copied. Licences stay in the store, which remains the record: copying a font into the same user's font folder isn't redistribution under the OFL, the Apache 2.0 licence or the UFL, and macOS doesn't expect text files in `~/Library/Fonts`.
|
||||
|
||||
Running apps see a new font at once or only after a restart, depending on the app (GTK under GNOME and Firefox at once, Chromium, Electron and Qt apps after a restart), so the interface tells the user that open apps may need a restart.
|
||||
|
||||
### Conflicts
|
||||
|
||||
`make_available` reads the catalog given to `with_catalog` (rescanned first if the font folders changed), else a fresh catalog of the process's environment, with the store locked. It refuses with `Error::Conflict`, changing nothing and naming each file with the PostScript name it has (`None` for a file in the way), when:
|
||||
|
||||
- a system font has a PostScript name of one of the family's faces or named instances (ignoring ASCII case). Names come from a catalog scan of each store file and from the index. fontconfig would otherwise pick the newer version system-wide, and macOS can't activate two fonts of one PostScript name;
|
||||
- another store family's copy has one of those names (Roboto from Google Fonts and from a user's source, say);
|
||||
- a file the store didn't add, another family's copy or a symbolic link sits where a copy would go.
|
||||
|
||||
The store's own copies are told apart by file identity (device and inode on Unix), so a copy the catalog reaches by another path (Flatpak shows the user's fonts again at `/run/host/user-fonts`) is still the store's. A system file identical to the store's (same sha256) is no conflict: the file isn't copied, and the ledger notes it as `present`, never to be deleted. A file at a copy's own place with the store's sha256 is taken into the ledger as a copy. Fonts of the same family name with other PostScript names (soft conflicts) are not checked yet.
|
||||
|
||||
### The ledger
|
||||
|
||||
`os-fonts.json` (version 1) lists, per family (name, source and store folder), every file: its store file name, its path, the store file's sha256, its PostScript names, how it is there (`copy`, or `present` for a system file) and its state (`adding` or `active`).
|
||||
|
||||
The store deletes a file only when the ledger lists it as a copy, at the very path the store puts that file (`path_for` of the family's folder and file name), with no symbolic link on the way, and with the sha256 the ledger gives. Any other listed path is left alone and reported. A ledger that can't be read or understood (damaged, an unknown value, another version) is kept as it is: queries treat the family as not available, and everything that would change the ledger, removals of the family from the store included, gives `Error::Ledger`.
|
||||
|
||||
A crash leaves nothing the store loses track of:
|
||||
|
||||
- A copy is listed as `adding` before it is made, written to `.craft-<name>.part` (a dot-file, which fontconfig and macOS skip), checked against its sha256, and renamed into place; then the ledger lists it as `active`.
|
||||
- The next change settles every `adding` entry: the temporary file goes, a file with the new sha256 (or, while replacing a copy, the old one) stays listed as `active`, and any other is dropped from the ledger and left alone.
|
||||
- A copy being deleted is renamed to `.craft-<name>.removing`, checked there and then deleted, or renamed back if it changed. One a crash leaves aside goes back at the next change.
|
||||
- A withdrawal deletes the files first and rewrites the ledger after, so a crash in between leaves entries whose files are gone, which the next withdrawal drops.
|
||||
|
||||
### Limits
|
||||
|
||||
- The copies stay when the suite is uninstalled, unless the user withdraws them first.
|
||||
- The catalog lists a copy as a system face beside the store's face. Both have the same family, style and PostScript name, so `Catalog::faces` keeps one: the store's, wherever the folders sort.
|
||||
- Copies take disk space beside the store's files; there are no hard links, so a font editor saving over a copy can't change the store's file.
|
||||
|
||||
## Web
|
||||
|
||||
The index, the lookups, `verify_font` and `IndexPin` build for `wasm32-unknown-unknown`. The store folder and the HTTP client are native only; the web keeps fonts elsewhere.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! The suite's font store: the font indexes of every source (Google Fonts, Noto, indexes the user
|
||||
//! adds), exact lookup of a missing font, and verified installs into the one folder every app's
|
||||
//! font catalog reads.
|
||||
//! adds), exact lookup of a missing font, verified installs into the one folder every app's font
|
||||
//! catalog reads, and, per family at the user's request, copies in the OS user font folder for
|
||||
//! every other program ([`FontStore::make_available`]).
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(not(target_arch = "wasm32"))] {
|
||||
@@ -43,7 +44,7 @@ pub use index::{
|
||||
MAX_FILE_BYTES, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, Sample, Script, SourceProblem, Unavailable, parse_style,
|
||||
};
|
||||
pub use pin::{IndexPin, PINNED_INDEX};
|
||||
pub use service::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, PreviewStore};
|
||||
pub use service::{Conflict, LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource, PreviewStore};
|
||||
pub use sources::{SourceEntry, SourcesFile};
|
||||
pub use verify::{VerifyError, is_font, sha256_hex, verify_font};
|
||||
|
||||
@@ -69,7 +70,9 @@ pub use language_packs::{
|
||||
MAX_PACK_INDEX_BYTES, MAX_PACK_UNPACKED_BYTES, PackEntry, PackIndex, PackIndexPin, language_pack_index_overridden,
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use store::{Caller, Error, FontStore, InstalledFamily, InstalledFile, Network, Problem, Progress, check_preview_service};
|
||||
pub use store::{
|
||||
Caller, Error, FontStore, InstalledFamily, InstalledFile, Network, OsFontFolder, OsFontLayout, Problem, Progress, check_preview_service,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,6 +1,6 @@
|
||||
//! What the font store and the preview service's client share with the font manager on every target: which legal
|
||||
//! text to read, where the preview service comes from, and what the preview pool reads from a store. The store and
|
||||
//! the client themselves are native only.
|
||||
//! text to read, where the preview service comes from, what keeps a family out of the OS user font folder, and what
|
||||
//! the preview pool reads from a store. The store and the client themselves are native only.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -29,6 +29,17 @@ pub enum PreviewServiceSource {
|
||||
None,
|
||||
}
|
||||
|
||||
/// What stops a family being copied into the OS user font folder: a font that already has one
|
||||
/// of its PostScript names, or a file in the way of a copy.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Conflict {
|
||||
/// The PostScript name `path` has too; `None` for a file the store didn't add (another
|
||||
/// family's copy, a link) sitting where a copy would go.
|
||||
pub postscript: Option<String>,
|
||||
/// A system font or another store family's copy with the name, or the file in the way.
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
/// What [`Previews`](crate::preview::Previews) reads from the font store: the service and the user's setting on each request, the client and
|
||||
/// the cache folder when the pool is made. The font manager's `Installer` builds on it.
|
||||
pub trait PreviewStore: Send + Sync {
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
//! Layout of the folder ([`craft_font_catalog::font_store_dir`]):
|
||||
//!
|
||||
//! ```text
|
||||
//! settings.json the consent setting and the sources the user added
|
||||
//! settings.json the consent setting, the sources the user added and the other settings
|
||||
//! manifest.json what is installed
|
||||
//! os-fonts.json the ledger of copies in the OS user font folder
|
||||
//! indexes/ the last indexes fetched: sources.json, one file per source
|
||||
//! previews/ preview subsets from the preview service (WOFF2), a cache of at most 50 MB
|
||||
//! <family dir>/ google/fonts' folder name, or <source>/<family>: the fonts and the licence
|
||||
@@ -24,7 +25,6 @@ use std::time::{Duration, SystemTime};
|
||||
use craft_font_catalog::{Catalog, FontEnv, font_store_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::UserSource;
|
||||
use crate::http::{Cancel, Client, FetchError};
|
||||
use crate::index::{
|
||||
Face, Family, FontFile, GOOGLE_FONTS, Index, IndexError, LicenseFile, MAX_INDEX_BYTES, MAX_LICENSE_BYTES, SourceProblem, Unavailable,
|
||||
@@ -34,10 +34,13 @@ use crate::service::{LegalText, PREVIEW_SERVICE_ENV, PreviewServiceSource};
|
||||
use crate::source::{is_source_url, safe_dir, safe_file_name, slug};
|
||||
use crate::sources::{MAX_SOURCES_BYTES, SourceEntry, SourcesFile};
|
||||
use crate::verify::{VerifyError, is_font, sha256_hex, verify_font};
|
||||
use crate::{Conflict, UserSource};
|
||||
|
||||
mod os_fonts;
|
||||
mod sources;
|
||||
mod transaction;
|
||||
|
||||
pub use os_fonts::{OsFontFolder, OsFontLayout};
|
||||
pub(crate) use transaction::Stage;
|
||||
use transaction::{Commit, merge_entry};
|
||||
|
||||
@@ -81,8 +84,9 @@ pub enum Error {
|
||||
/// Downloading is off; the user turns it on in the app.
|
||||
#[error("downloading fonts is turned off")]
|
||||
NetworkOff,
|
||||
/// An agent tried to turn the network on.
|
||||
#[error("only the user can turn on downloading fonts")]
|
||||
/// An agent tried what only the user may do: turn the network on, change a setting, or add
|
||||
/// or remove a family's copies in the OS user font folder.
|
||||
#[error("only the user can do this, in the app")]
|
||||
NotAllowed,
|
||||
/// Not an https URL a source can be added from.
|
||||
#[error("{0} is not an https URL")]
|
||||
@@ -118,6 +122,21 @@ pub enum Error {
|
||||
/// The operation was cancelled.
|
||||
#[error("cancelled")]
|
||||
Cancelled,
|
||||
/// Families can't be copied into the OS user font folder here; the reason says why.
|
||||
#[error("{0}")]
|
||||
Unsupported(String),
|
||||
/// Fonts the store didn't add already have the family's PostScript names, or sit where its
|
||||
/// copies would go.
|
||||
#[error("the family can't be copied into your fonts folder: {}", .0.iter().map(|c| match &c.postscript {
|
||||
Some(ps) => format!("{} already has the name {ps}", c.path.display()),
|
||||
None => format!("{} is in the way", c.path.display()),
|
||||
}).collect::<Vec<_>>().join("; "))]
|
||||
Conflict(Vec<Conflict>),
|
||||
/// The ledger of copies in the OS user font folder (`os-fonts.json`) can't be read or
|
||||
/// understood (damaged, or from a newer version). It is kept as it is, and nothing that would
|
||||
/// change it runs.
|
||||
#[error("the record of fonts copied into your fonts folder (os-fonts.json in the font store) can't be used: {0}")]
|
||||
Ledger(String),
|
||||
/// Reading or writing the store failed.
|
||||
#[error("{what}: {source}")]
|
||||
Io {
|
||||
@@ -180,6 +199,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)]
|
||||
@@ -204,6 +228,10 @@ struct Settings {
|
||||
preview_service: Option<String>,
|
||||
#[serde(default = "on")]
|
||||
previews: bool,
|
||||
/// The user keeps store fonts in Craft apps only: the font manager doesn't copy families
|
||||
/// into the OS user font folder.
|
||||
#[serde(default)]
|
||||
craft_apps_only: bool,
|
||||
/// The file exists but couldn't be read or parsed.
|
||||
#[serde(skip)]
|
||||
unreadable: bool,
|
||||
@@ -215,7 +243,7 @@ fn on() -> bool {
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, unreadable: false }
|
||||
Self { network: None, user_sources: Vec::new(), preview_service: None, previews: true, craft_apps_only: false, unreadable: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,6 +292,9 @@ pub struct FontStore {
|
||||
default_preview_service: Option<String>,
|
||||
/// The host's network setting, used while the user hasn't chosen. Never saved.
|
||||
default_network: Option<Network>,
|
||||
/// The OS user font folder, or why there is none.
|
||||
os_fonts: Result<OsFontFolder, String>,
|
||||
ledger_cache: os_fonts::LedgerCache,
|
||||
/// Tests: stands in for the environment variable.
|
||||
#[cfg(test)]
|
||||
preview_env: Option<Option<String>>,
|
||||
@@ -279,15 +310,19 @@ impl FontStore {
|
||||
/// The store for the app's own interface, in the folder every app reads.
|
||||
/// `None` where there is no per-user folder.
|
||||
pub fn for_user(env: &FontEnv) -> Option<Self> {
|
||||
Some(Self::new(font_store_dir(env)?, Caller::User))
|
||||
let mut store = Self::new(font_store_dir(env)?, Caller::User);
|
||||
store.set_os_fonts(OsFontFolder::for_env(env));
|
||||
Some(store)
|
||||
}
|
||||
|
||||
/// The store for an agent (MCP, CLI): it can never turn the network on.
|
||||
pub fn for_agent(env: &FontEnv) -> Option<Self> {
|
||||
Some(Self::new(font_store_dir(env)?, Caller::Agent))
|
||||
let mut store = Self::new(font_store_dir(env)?, Caller::Agent);
|
||||
store.set_os_fonts(OsFontFolder::for_env(env));
|
||||
Some(store)
|
||||
}
|
||||
|
||||
/// A store in `dir`.
|
||||
/// A store in `dir`, with no OS user font folder ([`FontStore::with_os_fonts`] sets one).
|
||||
pub fn new(dir: PathBuf, caller: Caller) -> Self {
|
||||
Self {
|
||||
dir,
|
||||
@@ -298,6 +333,8 @@ impl FontStore {
|
||||
pack_removal_round_end: AtomicUsize::new(0),
|
||||
default_preview_service: None,
|
||||
default_network: None,
|
||||
os_fonts: Err("no user font folder was given".into()),
|
||||
ledger_cache: os_fonts::LedgerCache::default(),
|
||||
#[cfg(test)]
|
||||
preview_env: None,
|
||||
}
|
||||
@@ -369,7 +406,8 @@ impl FontStore {
|
||||
// ----- install
|
||||
|
||||
/// Installs every file of `family`. Files already installed with the same sha256 aren't
|
||||
/// downloaded again.
|
||||
/// downloaded again. When the family has copies in the OS user font folder, the user's install
|
||||
/// also copies the new files there; an agent's leaves them in [`FontStore::pending_files`].
|
||||
pub fn install_family(
|
||||
&self,
|
||||
index: &Index,
|
||||
@@ -401,6 +439,7 @@ impl FontStore {
|
||||
let wanted: Vec<&FontFile> = files.iter().copied().filter(|f| !have(f) || !folder.join(f.file_name()).is_file()).collect();
|
||||
let license_missing = family.license_file_name().is_some_and(|name| !folder.join(name).is_file());
|
||||
if wanted.is_empty() && !license_missing {
|
||||
self.reshare(&family.source, &family.family);
|
||||
return installed.ok_or_else(|| Error::NotInstalled(family.family.clone()));
|
||||
}
|
||||
self.require_network()?;
|
||||
@@ -455,6 +494,9 @@ impl FontStore {
|
||||
};
|
||||
drop(stage);
|
||||
self.rescan();
|
||||
if result.is_ok() {
|
||||
self.reshare(&family.source, &family.family);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -552,13 +594,17 @@ impl FontStore {
|
||||
.is_some_and(|i| i.files.iter().any(|x| x.name == file.file_name() && x.sha256 == file.sha256))
|
||||
}
|
||||
|
||||
/// Removes the family of this name installed from `source`: its files, its licence and its
|
||||
/// manifest entry. Its folder disappears at once and is deleted after.
|
||||
/// Removes the family of this name installed from `source`: its copies in the OS user font
|
||||
/// folder (as [`FontStore::withdraw`]), its files, its licence and its manifest entry. Its
|
||||
/// folder disappears at once and is deleted after. A family with copies in the OS folder is
|
||||
/// the user's to remove: an agent gets [`Error::NotAllowed`] and nothing changes. Copies this
|
||||
/// build can't reach ([`FontStore::copies_out_of_reach`]) stay, listed in the ledger.
|
||||
pub fn remove_family(&self, source: &str, name: &str) -> Result<(), Error> {
|
||||
let result = {
|
||||
let _lock = self.lock()?;
|
||||
let mut manifest = self.read_manifest();
|
||||
let pos = manifest.families.iter().position(|f| f.is(source, name)).ok_or_else(|| Error::NotInstalled(name.to_string()))?;
|
||||
self.withdraw_for_removal(source, name, None)?;
|
||||
let entry = manifest.families.remove(pos);
|
||||
let folder = self.dir.join(&entry.dir);
|
||||
let stage = Stage::new(&self.dir)?;
|
||||
@@ -581,9 +627,11 @@ impl FontStore {
|
||||
result
|
||||
}
|
||||
|
||||
/// Removes some files of an installed family (one style, say), by their names in its folder.
|
||||
/// Taking out the last one removes the family. Names the family's manifest entry doesn't list
|
||||
/// are left alone.
|
||||
/// Removes some files of an installed family (one style, say), by their names in its folder,
|
||||
/// with their copies in the OS user font folder. Taking out the last one removes the family.
|
||||
/// Names the family's manifest entry doesn't list are left alone. Files with copies in the OS
|
||||
/// folder are the user's to remove: an agent gets [`Error::NotAllowed`] and nothing changes.
|
||||
/// Copies this build can't reach stay, as for [`FontStore::remove_family`].
|
||||
pub fn remove_files(&self, source: &str, name: &str, files: &[String]) -> Result<(), Error> {
|
||||
let result = {
|
||||
let _lock = self.lock()?;
|
||||
@@ -595,6 +643,7 @@ impl FontStore {
|
||||
if removing.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.withdraw_for_removal(source, name, Some(removing.as_slice()))?;
|
||||
entry.files.retain(|f| !removing.contains(&f.name));
|
||||
let folder = self.dir.join(&entry.dir);
|
||||
let stage = Stage::new(&self.dir)?;
|
||||
@@ -666,7 +715,15 @@ impl FontStore {
|
||||
|
||||
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`.
|
||||
|
||||
@@ -0,0 +1,954 @@
|
||||
//! Copies of a store family in the OS user font folder, for every app of the user, recorded in a
|
||||
//! ledger (`os-fonts.json`) so that withdrawing one removes exactly what the store added.
|
||||
//!
|
||||
//! Crash safety: the ledger lists a copy as `adding` before it is made, and as `active` once it
|
||||
//! is in place. Copies go to a dot-file (`.craft-<name>.part`, which neither fontconfig nor macOS
|
||||
//! reads) and are renamed into place. The next call that changes the ledger settles every
|
||||
//! `adding` entry: the temporary file goes; a file that has the new sha256 (or, for a
|
||||
//! replacement, the old one) stays listed as `active`; any other is dropped from the ledger and
|
||||
//! left alone. A copy being deleted is first renamed to `.craft-<name>.removing` and checked
|
||||
//! there, so a file changed at the last moment goes back; one a crash leaves there goes back at
|
||||
//! the next change. A withdrawal deletes files first and rewrites the ledger after, so a crash in
|
||||
//! between leaves entries whose files are gone, which the next withdrawal drops.
|
||||
//!
|
||||
//! On Windows each copy is also a per-user font value in the registry, which the ledger names
|
||||
//! (listed before the copy is made, like the copy), loaded into the running session with
|
||||
//! `AddFontResourceW`. Windows keeps a loaded font's file from being replaced or deleted, so a
|
||||
//! copy is unloaded before either, and its value deleted before it is deleted. A copy that is
|
||||
//! still in use elsewhere can't be deleted: the withdrawal fails with that error and the ledger
|
||||
//! keeps the copy, so the next withdrawal tries again.
|
||||
//!
|
||||
//! Everything here blocks (hashing, copying, a catalog rescan): call it off the UI thread.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::OsString;
|
||||
use std::fs::File;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use craft_font_catalog::{Catalog, FaceInfo, FontEnv, Os, Source, read_faces};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{Caller, Error, FontStore, InstalledFamily, io};
|
||||
use crate::Conflict;
|
||||
use crate::source::{safe_dir, safe_file_name};
|
||||
use crate::verify::VerifyError;
|
||||
|
||||
const LEDGER: &str = "os-fonts.json";
|
||||
const LEDGER_VERSION: u32 = 1;
|
||||
const MAX_LEDGER_BYTES: u64 = 16 << 20;
|
||||
|
||||
/// How the OS user font folder is laid out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OsFontLayout {
|
||||
/// One folder of files, each named `Craft-<family folder>-<file>`: `~/Library/Fonts`.
|
||||
Flat,
|
||||
/// A folder per family, `<folder>/<store family folder>/<file>`: `~/.local/share/fonts/Craft`,
|
||||
/// which fontconfig reads with its subfolders.
|
||||
Folders,
|
||||
}
|
||||
|
||||
/// The OS user font folder the store copies families into, for every app of the user.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OsFontFolder {
|
||||
dir: PathBuf,
|
||||
layout: OsFontLayout,
|
||||
fc_cache: bool,
|
||||
/// Windows: each copy is a per-user font value in the registry and loaded into the session.
|
||||
registry: bool,
|
||||
}
|
||||
|
||||
impl OsFontFolder {
|
||||
/// The current user's font folder on the system `env` describes, or why the store can't add
|
||||
/// fonts to it:
|
||||
///
|
||||
/// - macOS: `~/Library/Fonts`. Not in a sandboxed build (`APP_SANDBOX_CONTAINER_ID` is set),
|
||||
/// such as the Mac App Store's.
|
||||
/// - Linux and the BSDs: `$XDG_DATA_HOME/fonts/Craft` (`~/.local/share/fonts/Craft`), and
|
||||
/// `fc-cache` refreshes the user's font cache after each change when it is on `PATH`. In a
|
||||
/// Flatpak, the host's folder (`$HOST_XDG_DATA_HOME`, else `~/.local/share`), only when
|
||||
/// `/.flatpak-info` grants write access to it (`--filesystem=xdg-data/fonts:create`), and
|
||||
/// without `fc-cache`. Not in a Snap (`SNAP` is set).
|
||||
/// - Windows 10 1809 and later: `%LOCALAPPDATA%\Microsoft\Windows\Fonts\Craft`, each copy
|
||||
/// listed under `HKCU\Software\Microsoft\Windows NT\CurrentVersion\Fonts` and loaded into
|
||||
/// the running session. Not in a packaged (MSIX) build.
|
||||
/// - Haiku and the web: not offered.
|
||||
pub fn for_env(env: &FontEnv) -> Result<Self, String> {
|
||||
let folder = Self::for_env_with(env, &|k| std::env::var_os(k).filter(|v| !v.is_empty()))?;
|
||||
if folder.registry {
|
||||
craft_font_os_windows::check_supported()?;
|
||||
}
|
||||
Ok(folder)
|
||||
}
|
||||
|
||||
/// [`OsFontFolder::for_env`], reading the variables `FontEnv` doesn't hold through `var`.
|
||||
pub(crate) fn for_env_with(env: &FontEnv, var: &dyn Fn(&str) -> Option<OsString>) -> Result<Self, String> {
|
||||
const NO_HOME: &str = "there is no home folder";
|
||||
match env.os {
|
||||
Os::MacOs => {
|
||||
if var("APP_SANDBOX_CONTAINER_ID").is_some() {
|
||||
return Err("a sandboxed app (such as the Mac App Store build) can't add fonts to ~/Library/Fonts".into());
|
||||
}
|
||||
let home = env.home.as_ref().ok_or(NO_HOME)?;
|
||||
Ok(Self { dir: home.join("Library/Fonts"), layout: OsFontLayout::Flat, fc_cache: false, registry: false })
|
||||
}
|
||||
Os::Unix => {
|
||||
if var("SNAP").is_some() {
|
||||
return Err("the Snap build can't write the user font folder".into());
|
||||
}
|
||||
let absolute = |p: &PathBuf| p.is_absolute();
|
||||
let local_share = env.home.as_ref().map(|h| h.join(".local/share"));
|
||||
let (data, fc_cache) = if env.flatpak {
|
||||
let data = var("HOST_XDG_DATA_HOME").map(PathBuf::from).filter(absolute).or(local_share).ok_or(NO_HOME)?;
|
||||
if !flatpak_can_write(&env.root.join(".flatpak-info"), env.home.as_deref(), &data) {
|
||||
return Err("the Flatpak has no write access to the user font folder (--filesystem=xdg-data/fonts:create)".into());
|
||||
}
|
||||
(data, false)
|
||||
} else {
|
||||
(env.xdg_data_home.clone().filter(absolute).or(local_share).ok_or(NO_HOME)?, true)
|
||||
};
|
||||
Ok(Self { dir: data.join("fonts/Craft"), layout: OsFontLayout::Folders, fc_cache, registry: false })
|
||||
}
|
||||
Os::Windows => {
|
||||
let local = env
|
||||
.local_app_data
|
||||
.clone()
|
||||
.or_else(|| env.home.as_ref().map(|h| h.join("AppData").join("Local")))
|
||||
.filter(|p| p.is_absolute())
|
||||
.ok_or("there is no local app data folder")?;
|
||||
let dir = local.join("Microsoft").join("Windows").join("Fonts").join("Craft");
|
||||
Ok(Self { dir, layout: OsFontLayout::Folders, fc_cache: false, registry: true })
|
||||
}
|
||||
Os::Haiku | Os::None => Err("this system has no user font folder the store can add to".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder of `layout` at `dir`, with no font cache refresh: tests, and setups the platform
|
||||
/// rules don't cover.
|
||||
pub fn at(dir: impl Into<PathBuf>, layout: OsFontLayout) -> Self {
|
||||
Self { dir: dir.into(), layout, fc_cache: false, registry: false }
|
||||
}
|
||||
|
||||
/// The folder.
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
/// Where the copy of `file` of the store family in folder `family_dir` goes.
|
||||
fn path_for(&self, family_dir: &str, file: &str) -> PathBuf {
|
||||
match self.layout {
|
||||
OsFontLayout::Flat => self.dir.join(format!("Craft-{family_dir}-{file}")),
|
||||
OsFontLayout::Folders => self.dir.join(family_dir).join(file),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `path` is inside the folder and no folder on the way, nor `path` itself, is a
|
||||
/// symbolic link (a dangling one included), so that writes and deletes stay inside. With the
|
||||
/// `Folders` layout the store's own `Craft` folder counts too.
|
||||
fn no_links(&self, path: &Path) -> bool {
|
||||
let Ok(rest) = path.strip_prefix(&self.dir) else { return false };
|
||||
if rest.components().count() == 0 || !rest.components().all(|c| matches!(c, Component::Normal(_))) {
|
||||
return false;
|
||||
}
|
||||
let mut at = self.dir.clone();
|
||||
let mut check = Vec::new();
|
||||
if self.layout == OsFontLayout::Folders {
|
||||
check.push(at.clone());
|
||||
}
|
||||
for c in rest.components() {
|
||||
at.push(c);
|
||||
check.push(at.clone());
|
||||
}
|
||||
check.iter().all(|p| std::fs::symlink_metadata(p).map_or(true, |m| !m.file_type().is_symlink()))
|
||||
}
|
||||
|
||||
/// Whether the ledger's `file` of the family in store folder `dir` is a copy the store may
|
||||
/// touch: where the store puts it, with no link on the way.
|
||||
fn owns(&self, dir: &str, file: &LedgerFile) -> bool {
|
||||
file.mechanism == Mechanism::Copy
|
||||
&& safe_dir(dir)
|
||||
&& safe_file_name(&file.store_file)
|
||||
&& file.path == self.path_for(dir, &file.store_file)
|
||||
&& self.no_links(&file.path)
|
||||
}
|
||||
|
||||
/// The registry value name of the store file `file` with these faces, on Windows:
|
||||
/// `<full names joined by " & "> (TrueType)`, or `(OpenType)` for CFF outlines.
|
||||
fn registry_name(&self, path: &Path, file: &str, faces: &[FaceInfo]) -> Option<String> {
|
||||
if !self.registry {
|
||||
return None;
|
||||
}
|
||||
let mut names: Vec<&str> = faces.iter().filter_map(|f| f.full_name.as_deref()).collect();
|
||||
names.dedup();
|
||||
let stem = Path::new(file).file_stem().map_or(file.into(), |s| s.to_string_lossy());
|
||||
let name = if names.is_empty() { stem.into_owned() } else { names.join(" & ") };
|
||||
let mut magic = [0u8; 4];
|
||||
let cff = File::open(path).and_then(|mut f| std::io::Read::read_exact(&mut f, &mut magic)).is_ok() && &magic == b"OTTO";
|
||||
Some(format!("{name} ({})", if cff { "OpenType" } else { "TrueType" }))
|
||||
}
|
||||
|
||||
/// Registry values of `planned` that already hold another font: conflicts.
|
||||
fn registry_conflicts(&self, planned: &[Planned]) -> Vec<Conflict> {
|
||||
planned
|
||||
.iter()
|
||||
.filter_map(|p| {
|
||||
let held = craft_font_os_windows::registered(p.registry.as_deref()?)?;
|
||||
let same = held.to_string_lossy().to_lowercase() == p.path.to_string_lossy().to_lowercase();
|
||||
(!same).then_some(Conflict { postscript: None, path: held })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lists a copy in the registry and loads it into the session, where the OS needs that.
|
||||
fn register(&self, f: &LedgerFile) -> Result<(), Error> {
|
||||
match &f.registry {
|
||||
Some(name) => craft_font_os_windows::register(name, &f.path).map_err(io(format!("registering {} with Windows", f.path.display()))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Undoes [`OsFontFolder::register`] for a copy about to be deleted.
|
||||
fn unregister(&self, f: &LedgerFile) -> Result<(), Error> {
|
||||
match &f.registry {
|
||||
Some(name) => craft_font_os_windows::unregister(name, &f.path).map_err(io(format!("unregistering {} from Windows", f.path.display()))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Unloads the file at `path` from the session before it is replaced, where the OS locks it.
|
||||
fn unload(&self, path: &Path) {
|
||||
if self.registry && path.exists() {
|
||||
craft_font_os_windows::unload(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells fontconfig, or the windows of a Windows session, off the calling thread. It isn't
|
||||
/// needed for correctness: fontconfig notices changed folders by their mtime.
|
||||
fn refresh(&self) {
|
||||
if self.registry {
|
||||
let _ = std::thread::Builder::new().name("font-change".into()).spawn(craft_font_os_windows::broadcast_font_change);
|
||||
}
|
||||
if !self.fc_cache {
|
||||
return;
|
||||
}
|
||||
let fonts = self.dir.parent().unwrap_or(&self.dir).to_path_buf();
|
||||
let _ = std::thread::Builder::new().name("fc-cache".into()).spawn(move || {
|
||||
let _ = std::process::Command::new("fc-cache")
|
||||
.arg(fonts)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `/.flatpak-info` grants write access to `<data>/fonts`. Its `filesystems=` entries
|
||||
/// apply in order: `!name` revokes an earlier grant of `name`, and `:ro` grants no write.
|
||||
fn flatpak_can_write(info: &Path, home: Option<&Path>, data: &Path) -> bool {
|
||||
let Some(bytes) = std::fs::metadata(info).ok().filter(|m| m.len() <= 1 << 20).and_then(|_| std::fs::read(info).ok()) else { return false };
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let fonts = data.join("fonts");
|
||||
let mut grants: Vec<(String, bool)> = Vec::new();
|
||||
for entry in text.lines().filter_map(|l| l.trim().strip_prefix("filesystems=")).flat_map(|l| l.split(';')) {
|
||||
let entry = entry.trim();
|
||||
let (revoke, entry) = match entry.strip_prefix('!') {
|
||||
Some(e) => (true, e),
|
||||
None => (false, entry),
|
||||
};
|
||||
let (name, mode) = entry.rsplit_once(':').unwrap_or((entry, "rw"));
|
||||
let name = name.trim_end_matches('/').to_string();
|
||||
grants.retain(|(n, _)| *n != name);
|
||||
if !revoke && !name.is_empty() {
|
||||
grants.push((name, mode != "ro"));
|
||||
}
|
||||
}
|
||||
let covers = |name: &str| -> bool {
|
||||
let base = match name {
|
||||
"host" => Some(PathBuf::from("/")),
|
||||
"home" => home.map(Path::to_path_buf),
|
||||
"xdg-data" => Some(data.to_path_buf()),
|
||||
_ => match (name.strip_prefix("xdg-data/"), name.strip_prefix("~/")) {
|
||||
(Some(sub), _) => Some(data.join(sub)),
|
||||
(None, Some(sub)) => home.map(|h| h.join(sub)),
|
||||
_ => Some(PathBuf::from(name)).filter(|p| p.is_absolute()),
|
||||
},
|
||||
};
|
||||
base.is_some_and(|b| fonts.starts_with(b))
|
||||
};
|
||||
grants.iter().any(|(name, write)| *write && covers(name))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum State {
|
||||
/// Listed before the copy; settled by the next change.
|
||||
Adding,
|
||||
Active,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Mechanism {
|
||||
/// The store copied the file to `path`.
|
||||
Copy,
|
||||
/// The system already has the same file at `path`: nothing was copied, and nothing is ever
|
||||
/// deleted for it.
|
||||
Present,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct LedgerFile {
|
||||
/// The file's name in the store family's folder.
|
||||
store_file: String,
|
||||
path: PathBuf,
|
||||
/// The store file's sha256.
|
||||
sha256: String,
|
||||
postscript: Vec<String>,
|
||||
mechanism: Mechanism,
|
||||
state: State,
|
||||
/// While `adding` over an earlier copy: that copy's sha256.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
replacing: Option<String>,
|
||||
/// Windows: the per-user font value in the registry that names the copy.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
registry: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct LedgerFamily {
|
||||
family: String,
|
||||
source: String,
|
||||
/// The family's folder in the store.
|
||||
dir: String,
|
||||
files: Vec<LedgerFile>,
|
||||
}
|
||||
|
||||
impl LedgerFamily {
|
||||
fn is(&self, source: &str, name: &str) -> bool {
|
||||
self.source == source && self.family.to_lowercase() == name.to_lowercase()
|
||||
}
|
||||
|
||||
fn copies(&self) -> impl Iterator<Item = &LedgerFile> {
|
||||
self.files.iter().filter(|f| f.mechanism == Mechanism::Copy)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize, Deserialize)]
|
||||
pub(super) struct Ledger {
|
||||
version: u32,
|
||||
families: Vec<LedgerFamily>,
|
||||
}
|
||||
|
||||
impl Ledger {
|
||||
fn family(&self, source: &str, name: &str) -> Option<&LedgerFamily> {
|
||||
self.families.iter().find(|f| f.is(source, name))
|
||||
}
|
||||
|
||||
/// Settles every `adding` entry and puts back files a crashed deletion left aside (see the
|
||||
/// module comment).
|
||||
fn settle(&mut self, folder: &OsFontFolder) {
|
||||
for family in &mut self.families {
|
||||
let dir = family.dir.clone();
|
||||
family.files.retain_mut(|f| {
|
||||
let owned = folder.owns(&dir, f);
|
||||
if owned {
|
||||
restore_removing(&f.path);
|
||||
}
|
||||
if f.mechanism == Mechanism::Present {
|
||||
// The system copy is gone: the next make-available copies the file.
|
||||
return std::fs::metadata(&f.path).is_ok();
|
||||
}
|
||||
if f.state == State::Active {
|
||||
return true;
|
||||
}
|
||||
if !owned {
|
||||
return false;
|
||||
}
|
||||
let _ = std::fs::remove_file(aside(&f.path, "part"));
|
||||
match file_sha256(&f.path) {
|
||||
Some(sha) if sha == f.sha256 => {}
|
||||
Some(sha) if f.replacing.as_ref() == Some(&sha) => f.sha256 = sha,
|
||||
_ => return false,
|
||||
}
|
||||
f.state = State::Active;
|
||||
f.replacing = None;
|
||||
true
|
||||
});
|
||||
}
|
||||
self.families.retain(|f| !f.files.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// The last ledger read, while the file's size and modification time are unchanged.
|
||||
#[derive(Default)]
|
||||
pub(super) struct LedgerCache(Mutex<Option<(LedgerStamp, Arc<Ledger>)>>);
|
||||
|
||||
/// The ledger file's size and modification time.
|
||||
type LedgerStamp = (u64, Option<SystemTime>);
|
||||
|
||||
/// `.craft-<name>.<what>` beside `path`: a copy being made (`part`) or deleted (`removing`).
|
||||
fn aside(path: &Path, what: &str) -> PathBuf {
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
path.with_file_name(format!(".craft-{name}.{what}"))
|
||||
}
|
||||
|
||||
/// Puts back a file a crashed deletion left aside.
|
||||
fn restore_removing(path: &Path) {
|
||||
let removing = aside(path, "removing");
|
||||
if std::fs::symlink_metadata(path).is_err() && removing.is_file() {
|
||||
let _ = std::fs::rename(&removing, path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The sha256 of the file at `path`, read in pieces; `None` when it can't be read.
|
||||
fn file_sha256(path: &Path) -> Option<String> {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
std::io::copy(&mut File::open(path).ok()?, &mut hasher).ok()?;
|
||||
Some(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
type FileId = (u64, u64);
|
||||
#[cfg(not(unix))]
|
||||
type FileId = PathBuf;
|
||||
|
||||
/// What makes two paths one file, through links and bind mounts (Flatpak shows the host's user
|
||||
/// fonts again at `/run/host/user-fonts`).
|
||||
fn file_id(path: &Path) -> Option<FileId> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
std::fs::metadata(path).ok().map(|m| (m.dev(), m.ino()))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
std::fs::canonicalize(path).ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// A store file to make available.
|
||||
struct Planned {
|
||||
store_file: String,
|
||||
source: PathBuf,
|
||||
path: PathBuf,
|
||||
sha256: String,
|
||||
postscript: Vec<String>,
|
||||
/// Windows: the registry value name for the copy.
|
||||
registry: Option<String>,
|
||||
}
|
||||
|
||||
impl FontStore {
|
||||
/// Uses `folder` as the OS user font folder. [`FontStore::for_user`] and
|
||||
/// [`FontStore::for_agent`] use [`OsFontFolder::for_env`]; [`FontStore::new`] has none.
|
||||
pub fn with_os_fonts(mut self, folder: OsFontFolder) -> Self {
|
||||
self.os_fonts = Ok(folder);
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) fn set_os_fonts(&mut self, folder: Result<OsFontFolder, String>) {
|
||||
self.os_fonts = folder;
|
||||
}
|
||||
|
||||
/// Whether families can be copied into the OS user font folder here. The interface hides the
|
||||
/// action when it is false.
|
||||
pub fn available_to_all_supported(&self) -> bool {
|
||||
self.os_fonts.is_ok()
|
||||
}
|
||||
|
||||
/// Why families can't be copied into the OS user font folder here; `None` when they can.
|
||||
pub fn available_to_all_unsupported(&self) -> Option<&str> {
|
||||
self.os_fonts.as_ref().err().map(String::as_str)
|
||||
}
|
||||
|
||||
/// The OS user font folder, when there is one.
|
||||
pub fn os_fonts(&self) -> Option<&OsFontFolder> {
|
||||
self.os_fonts.as_ref().ok()
|
||||
}
|
||||
|
||||
/// Whether the family of this name installed from `source` has copies in the OS user font
|
||||
/// folder (is available to all apps). Cheap enough for every row of a list: it reads the
|
||||
/// ledger again only when the file changed. False when the ledger can't be read.
|
||||
pub fn is_available(&self, source: &str, name: &str) -> bool {
|
||||
self.cached_ledger().is_some_and(|l| l.family(source, name).is_some())
|
||||
}
|
||||
|
||||
/// The source and name of the available family whose store folder holds one of `files`; with
|
||||
/// no `files`, of the available family called `name` (ignoring case). A family of the same
|
||||
/// name from another source doesn't count when `files` are given. Cheap like
|
||||
/// [`FontStore::is_available`]: it reads only the ledger.
|
||||
pub fn available_family_holding(&self, name: &str, files: &[PathBuf]) -> Option<(String, String)> {
|
||||
let ledger = self.cached_ledger()?;
|
||||
let found = if files.is_empty() {
|
||||
let lower = name.to_lowercase();
|
||||
ledger.families.iter().find(|f| f.family.to_lowercase() == lower)
|
||||
} else {
|
||||
ledger.families.iter().find(|f| safe_dir(&f.dir) && files.iter().any(|p| p.starts_with(self.dir.join(&f.dir))))
|
||||
};
|
||||
found.map(|f| (f.source.clone(), f.family.clone()))
|
||||
}
|
||||
|
||||
/// The family's copies the ledger lists when this build can't change the OS user font folder
|
||||
/// (a Flatpak whose access to it was taken away, say): removing the family leaves them in
|
||||
/// place. Empty when the folder can be changed or the family has no copies.
|
||||
pub fn copies_out_of_reach(&self, source: &str, name: &str) -> Vec<PathBuf> {
|
||||
if self.os_fonts.is_ok() {
|
||||
return Vec::new();
|
||||
}
|
||||
self.available_files(source, name)
|
||||
}
|
||||
|
||||
/// The copies of the family's files in the OS user font folder.
|
||||
pub fn available_files(&self, source: &str, name: &str) -> Vec<PathBuf> {
|
||||
self.cached_ledger().and_then(|l| l.family(source, name).map(|f| f.copies().map(|x| x.path.clone()).collect())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 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 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() };
|
||||
let Some(family) = self.installed_family(source, name) else { return Vec::new() };
|
||||
family
|
||||
.files
|
||||
.iter()
|
||||
.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()
|
||||
}
|
||||
|
||||
/// Makes the installed family available to all apps, from the user's own action: copies its
|
||||
/// font files into the OS user font folder and records them in the ledger. Calling it again
|
||||
/// copies styles installed since and brings the copies up to date. Returns the copies.
|
||||
///
|
||||
/// Refuses with [`Error::Conflict`], changing nothing, when a font the store didn't copy for
|
||||
/// this family has one of its PostScript names (a system font, or another family's copy), or
|
||||
/// a file the store didn't add sits where a copy would go. A system file identical to the
|
||||
/// store's is no conflict: it isn't copied, and the ledger notes it. [`Error::NotAllowed`]
|
||||
/// for an agent, [`Error::Unsupported`] where [`FontStore::available_to_all_supported`] is
|
||||
/// false, [`Error::Ledger`] when the ledger can't be used.
|
||||
///
|
||||
/// It blocks (hashing, copying, a catalog rescan): call it off the UI thread. Running apps see
|
||||
/// the fonts at once or after a restart, depending on the app.
|
||||
pub fn make_available(&self, source: &str, name: &str) -> Result<Vec<PathBuf>, Error> {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
self.share(source, name)
|
||||
}
|
||||
|
||||
/// Takes the family's copies out of the OS user font folder, from the user's own action. Only
|
||||
/// files the ledger lists go, and only while unchanged: returns the ones left in place because
|
||||
/// they changed since (or were moved or linked elsewhere). [`Error::NotAllowed`] for an agent.
|
||||
/// It blocks: call it off the UI thread.
|
||||
pub fn withdraw(&self, source: &str, name: &str) -> Result<Vec<PathBuf>, Error> {
|
||||
if self.caller != Caller::User {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
let folder = self.os_fonts.as_ref().map_err(|reason| Error::Unsupported(reason.clone()))?;
|
||||
let kept = {
|
||||
let _lock = self.lock()?;
|
||||
self.unshare_locked(folder, source, name, None)?
|
||||
};
|
||||
folder.refresh();
|
||||
self.rescan();
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// After the user's install: copies new styles of an available family and brings its copies
|
||||
/// up to date. A failure leaves the earlier copies listed and the new files in
|
||||
/// [`FontStore::pending_files`], as an agent's install does.
|
||||
pub(super) fn reshare(&self, source: &str, name: &str) {
|
||||
if self.caller == Caller::User && self.is_available(source, name) {
|
||||
let _ = self.share(source, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// While the store is locked, before the family (`files` only, by their store names, when
|
||||
/// given) leaves the store: withdraws their copies. Refuses, before anything changes, when
|
||||
/// copies would have to go but an agent asks ([`Error::NotAllowed`]) or the ledger can't be
|
||||
/// used ([`Error::Ledger`]). Where this build can't change the OS folder, the copies stay
|
||||
/// there and in the ledger ([`FontStore::copies_out_of_reach`]), so a build that can still
|
||||
/// removes them, and a reinstall finds them the store's.
|
||||
pub(super) fn withdraw_for_removal(&self, source: &str, name: &str, files: Option<&[String]>) -> Result<(), Error> {
|
||||
let ledger = self.read_ledger()?;
|
||||
let Some(family) = ledger.family(source, name) else { return Ok(()) };
|
||||
let touched = |f: &LedgerFile| files.is_none_or(|o| o.contains(&f.store_file));
|
||||
if !family.files.iter().any(touched) {
|
||||
return Ok(());
|
||||
}
|
||||
if self.caller != Caller::User && family.copies().any(touched) {
|
||||
return Err(Error::NotAllowed);
|
||||
}
|
||||
let Ok(folder) = self.os_fonts.as_ref() else { return Ok(()) };
|
||||
self.unshare_locked(folder, source, name, files)?;
|
||||
folder.refresh();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn share(&self, source: &str, name: &str) -> Result<Vec<PathBuf>, Error> {
|
||||
let folder = self.os_fonts.as_ref().map_err(|reason| Error::Unsupported(reason.clone()))?;
|
||||
let (copies, registered) = {
|
||||
let _lock = self.lock()?;
|
||||
let mut ledger = self.read_ledger()?;
|
||||
ledger.settle(folder);
|
||||
let family = self.installed_family(source, name).ok_or_else(|| Error::NotInstalled(name.to_string()))?;
|
||||
let planned = self.plan(folder, &family)?;
|
||||
let earlier: Vec<LedgerFile> = ledger.family(source, name).map(|f| f.files.clone()).unwrap_or_default();
|
||||
let others: Vec<&LedgerFile> = ledger.families.iter().filter(|f| !f.is(source, name)).flat_map(LedgerFamily::copies).collect();
|
||||
|
||||
// Faces at these files are the store's own, whatever path the catalog reached them
|
||||
// by: every family's copies, and whatever sits where a copy goes, which the checks
|
||||
// below look at.
|
||||
let ours: HashSet<FileId> = ledger
|
||||
.families
|
||||
.iter()
|
||||
.flat_map(|f| f.copies().filter(|x| file_sha256(&x.path).as_ref() == Some(&x.sha256)).map(|x| &x.path))
|
||||
.chain(planned.iter().map(|p| &p.path))
|
||||
.filter_map(|p| file_id(p))
|
||||
.collect();
|
||||
let (mut conflicts, present) = self.system_conflicts(&planned, &ours);
|
||||
conflicts.extend(folder.registry_conflicts(&planned));
|
||||
for p in &planned {
|
||||
for other in &others {
|
||||
for ps in p.postscript.iter().filter(|ps| other.postscript.iter().any(|o| o.eq_ignore_ascii_case(ps))) {
|
||||
conflicts.push(Conflict { postscript: Some(ps.clone()), path: other.path.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut files = Vec::new();
|
||||
let mut to_copy = Vec::new();
|
||||
for p in &planned {
|
||||
let earlier_copy = earlier.iter().find(|e| e.mechanism == Mechanism::Copy && e.path == p.path);
|
||||
// Only a file not copied yet is left to an identical system file.
|
||||
if earlier_copy.is_none()
|
||||
&& let Some(system) = present.get(&p.store_file)
|
||||
{
|
||||
files.push(LedgerFile {
|
||||
store_file: p.store_file.clone(),
|
||||
path: system.clone(),
|
||||
sha256: p.sha256.clone(),
|
||||
postscript: p.postscript.clone(),
|
||||
mechanism: Mechanism::Present,
|
||||
state: State::Active,
|
||||
replacing: None,
|
||||
registry: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let disk = file_sha256(&p.path);
|
||||
// A file where a copy goes is ours when the ledger lists it for this family
|
||||
// unchanged, or when it is the store's file already (a copy the ledger lost).
|
||||
let blocked = !folder.no_links(&p.path)
|
||||
|| others.iter().any(|x| x.path == p.path)
|
||||
|| match &disk {
|
||||
Some(sha) => *sha != p.sha256 && earlier_copy.is_none_or(|e| e.sha256 != *sha),
|
||||
None => std::fs::symlink_metadata(&p.path).is_ok(),
|
||||
};
|
||||
if blocked {
|
||||
conflicts.push(Conflict { postscript: None, path: p.path.clone() });
|
||||
}
|
||||
let state = if disk.as_ref() == Some(&p.sha256) {
|
||||
State::Active
|
||||
} else {
|
||||
to_copy.push((p, disk.clone()));
|
||||
State::Adding
|
||||
};
|
||||
files.push(LedgerFile {
|
||||
store_file: p.store_file.clone(),
|
||||
path: p.path.clone(),
|
||||
sha256: p.sha256.clone(),
|
||||
postscript: p.postscript.clone(),
|
||||
mechanism: Mechanism::Copy,
|
||||
state,
|
||||
replacing: earlier_copy.filter(|_| state == State::Adding).map(|e| e.sha256.clone()),
|
||||
registry: p.registry.clone(),
|
||||
});
|
||||
}
|
||||
if !conflicts.is_empty() {
|
||||
conflicts.sort_by(|a, b| (&a.postscript, &a.path).cmp(&(&b.postscript, &b.path)));
|
||||
conflicts.dedup();
|
||||
return Err(Error::Conflict(conflicts));
|
||||
}
|
||||
// Copies of files the store no longer has stay listed until they are deleted below.
|
||||
let stale: Vec<LedgerFile> =
|
||||
earlier.into_iter().filter(|e| e.mechanism == Mechanism::Copy && !files.iter().any(|f| f.path == e.path)).collect();
|
||||
files.extend(stale.iter().cloned());
|
||||
ledger.families.retain(|f| !f.is(source, name));
|
||||
ledger.families.push(LedgerFamily { family: family.family.clone(), source: family.source.clone(), dir: family.dir.clone(), files });
|
||||
ledger.families.retain(|f| !f.files.is_empty());
|
||||
ledger.families.sort_by_key(|f| (f.family.to_lowercase(), f.source.clone()));
|
||||
self.write_ledger(&ledger)?;
|
||||
|
||||
if let Err(e) = to_copy.into_iter().try_for_each(|(p, found)| copy_in(folder, p, found.as_deref())) {
|
||||
ledger.settle(folder);
|
||||
let _ = self.write_ledger(&ledger);
|
||||
return Err(e);
|
||||
}
|
||||
let registered = register_all(folder, &ledger, source, name, &stale);
|
||||
if let Some(entry) = ledger.families.iter_mut().find(|f| f.is(source, name)) {
|
||||
for f in &mut entry.files {
|
||||
f.state = State::Active;
|
||||
f.replacing = None;
|
||||
}
|
||||
let dir = entry.dir.clone();
|
||||
// A stale copy leaves the ledger once deleted, or once changed and so not ours.
|
||||
entry.files.retain(|f| !stale.iter().any(|s| s.path == f.path) || remove_if_unchanged(folder, &dir, f).is_err());
|
||||
}
|
||||
ledger.families.retain(|f| !f.files.is_empty());
|
||||
self.write_ledger(&ledger)?;
|
||||
prune_dirs(folder, stale.iter().map(|s| s.path.as_path()));
|
||||
let copies = ledger.family(source, name).map(|f| f.copies().map(|x| x.path.clone()).collect()).unwrap_or_default();
|
||||
(copies, registered)
|
||||
};
|
||||
folder.refresh();
|
||||
self.rescan();
|
||||
registered.map(|()| copies)
|
||||
}
|
||||
|
||||
/// The family's files, checked against the manifest, with their PostScript names: the
|
||||
/// faces' and named instances' as a catalog scan reads them, and the index's.
|
||||
fn plan(&self, folder: &OsFontFolder, family: &InstalledFamily) -> Result<Vec<Planned>, Error> {
|
||||
let store_dir = self.dir.join(&family.dir);
|
||||
let mut planned = Vec::new();
|
||||
for f in &family.files {
|
||||
let from = store_dir.join(&f.name);
|
||||
if file_sha256(&from).as_ref() != Some(&f.sha256) {
|
||||
return Err(Error::Verify { file: f.name.clone(), error: VerifyError::Sha256 });
|
||||
}
|
||||
let faces = read_faces(&from, Source::Store);
|
||||
let registry = folder.registry_name(&from, &f.name, &faces);
|
||||
let mut postscript: Vec<String> = faces.into_iter().filter_map(|x| x.postscript_name).collect();
|
||||
postscript.extend(f.postscript.iter().cloned());
|
||||
postscript.sort();
|
||||
postscript.dedup();
|
||||
planned.push(Planned {
|
||||
store_file: f.name.clone(),
|
||||
source: from,
|
||||
path: folder.path_for(&family.dir, &f.name),
|
||||
sha256: f.sha256.clone(),
|
||||
postscript,
|
||||
registry,
|
||||
});
|
||||
}
|
||||
Ok(planned)
|
||||
}
|
||||
|
||||
/// System faces (except at the files in `ours`) with a PostScript name of `planned`:
|
||||
/// conflicts, and the store files the system already has identical copies of, with where.
|
||||
fn system_conflicts(&self, planned: &[Planned], ours: &HashSet<FileId>) -> (Vec<Conflict>, HashMap<String, PathBuf>) {
|
||||
// Not `faces()`: it keeps one of two faces alike, which may be the store's.
|
||||
let faces = match &self.catalog {
|
||||
Some(catalog) => {
|
||||
catalog.rescan_if_changed();
|
||||
catalog.scanned_faces()
|
||||
}
|
||||
None => Catalog::new(FontEnv::from_process()).scanned_faces(),
|
||||
};
|
||||
let mut wanted: HashMap<String, Vec<&Planned>> = HashMap::new();
|
||||
for p in planned {
|
||||
for ps in &p.postscript {
|
||||
wanted.entry(ps.to_ascii_lowercase()).or_default().push(p);
|
||||
}
|
||||
}
|
||||
let mut seen: HashMap<PathBuf, (Option<FileId>, Option<String>)> = HashMap::new();
|
||||
let mut conflicts = Vec::new();
|
||||
let mut present = HashMap::new();
|
||||
for face in faces.iter().filter(|f| f.source == Source::System) {
|
||||
let (Some(ps), Some(path)) = (&face.postscript_name, &face.path) else { continue };
|
||||
let Some(hits) = wanted.get(&ps.to_ascii_lowercase()) else { continue };
|
||||
let (id, sha) = seen.entry(path.clone()).or_insert_with(|| (file_id(path), file_sha256(path)));
|
||||
if id.as_ref().is_some_and(|id| ours.contains(id)) {
|
||||
continue;
|
||||
}
|
||||
for p in hits {
|
||||
if sha.as_ref() == Some(&p.sha256) {
|
||||
present.insert(p.store_file.clone(), path.clone());
|
||||
} else {
|
||||
conflicts.push(Conflict { postscript: Some(ps.clone()), path: path.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
(conflicts, present)
|
||||
}
|
||||
|
||||
fn unshare_locked(&self, folder: &OsFontFolder, source: &str, name: &str, only: Option<&[String]>) -> Result<Vec<PathBuf>, Error> {
|
||||
let mut ledger = self.read_ledger()?;
|
||||
ledger.settle(folder);
|
||||
let mut kept = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
let mut failed = None;
|
||||
if let Some(entry) = ledger.families.iter_mut().find(|f| f.is(source, name)) {
|
||||
let dir = entry.dir.clone();
|
||||
entry.files.retain(|f| {
|
||||
if only.is_some_and(|o| !o.contains(&f.store_file)) {
|
||||
return true;
|
||||
}
|
||||
if f.mechanism == Mechanism::Present {
|
||||
return false;
|
||||
}
|
||||
match remove_if_unchanged(folder, &dir, f) {
|
||||
Ok(true) => removed.push(f.path.clone()),
|
||||
Ok(false) => kept.push(f.path.clone()),
|
||||
Err(e) => {
|
||||
failed.get_or_insert(e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
});
|
||||
}
|
||||
ledger.families.retain(|f| !f.files.is_empty());
|
||||
self.write_ledger(&ledger)?;
|
||||
prune_dirs(folder, removed.iter().map(PathBuf::as_path));
|
||||
match failed {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(kept),
|
||||
}
|
||||
}
|
||||
|
||||
/// The ledger; empty when there is none. One that can't be read, can't be parsed (an unknown
|
||||
/// value, say) or has another version is an error and stays as it is, so nothing it lists is
|
||||
/// lost.
|
||||
fn read_ledger(&self) -> Result<Ledger, Error> {
|
||||
let path = self.dir.join(LEDGER);
|
||||
let meta = match std::fs::metadata(&path) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Ledger::default()),
|
||||
Err(e) => return Err(io(format!("reading {LEDGER}"))(e)),
|
||||
};
|
||||
if meta.len() > MAX_LEDGER_BYTES {
|
||||
return Err(Error::Ledger(format!("it is larger than {MAX_LEDGER_BYTES} bytes")));
|
||||
}
|
||||
let bytes = std::fs::read(&path).map_err(io(format!("reading {LEDGER}")))?;
|
||||
let ledger: Ledger = serde_json::from_slice(&bytes).map_err(|e| Error::Ledger(e.to_string()))?;
|
||||
if ledger.version != LEDGER_VERSION {
|
||||
return Err(Error::Ledger(format!("it is version {}, and this app reads version {LEDGER_VERSION}", ledger.version)));
|
||||
}
|
||||
Ok(ledger)
|
||||
}
|
||||
|
||||
/// [`FontStore::read_ledger`] for queries, read again only when the file changed; `None`
|
||||
/// when it can't be used.
|
||||
fn cached_ledger(&self) -> Option<Arc<Ledger>> {
|
||||
let stamp = std::fs::metadata(self.dir.join(LEDGER)).map_or((0, None), |m| (m.len(), m.modified().ok()));
|
||||
let mut cache = self.ledger_cache.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((s, ledger)) = cache.as_ref()
|
||||
&& *s == stamp
|
||||
{
|
||||
return Some(Arc::clone(ledger));
|
||||
}
|
||||
let ledger = Arc::new(self.read_ledger().ok()?);
|
||||
*cache = Some((stamp, Arc::clone(&ledger)));
|
||||
Some(ledger)
|
||||
}
|
||||
|
||||
fn write_ledger(&self, ledger: &Ledger) -> Result<(), Error> {
|
||||
let ledger = Ledger { version: LEDGER_VERSION, families: ledger.families.clone() };
|
||||
let bytes = serde_json::to_vec_pretty(&ledger).map_err(|e| io("saving the OS font ledger")(std::io::Error::other(e)))?;
|
||||
*self.ledger_cache.0.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
self.write_file(LEDGER, &bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies a store file to its place through a dot-file, checking the copy's sha256. `found` is
|
||||
/// the sha256 of the file planning found at the place (the family's earlier copy), if any.
|
||||
fn copy_in(folder: &OsFontFolder, p: &Planned, found: Option<&str>) -> Result<(), Error> {
|
||||
let what = || format!("copying {} to {}", p.store_file, p.path.display());
|
||||
if let Some(parent) = p.path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(io(what()))?;
|
||||
}
|
||||
if !folder.no_links(&p.path) {
|
||||
return Err(io(what())(std::io::Error::other("a symbolic link is in the way")));
|
||||
}
|
||||
let part = aside(&p.path, "part");
|
||||
let _ = std::fs::remove_file(&part);
|
||||
std::fs::copy(&p.source, &part).map_err(io(what()))?;
|
||||
folder.unload(&p.path);
|
||||
let checked = File::open(&part).and_then(|f| f.sync_all()).map_err(io(what())).and_then(|()| {
|
||||
if file_sha256(&part).as_ref() == Some(&p.sha256) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Verify { file: p.store_file.clone(), error: VerifyError::Sha256 })
|
||||
}
|
||||
});
|
||||
if let Err(e) = checked.and_then(|()| publish(&part, p, found)) {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the checked copy `part` to `p.path`, only over what planning found there: nothing, or
|
||||
/// the file with sha256 `found`. A file another app put there since is a conflict.
|
||||
fn publish(part: &Path, p: &Planned, found: Option<&str>) -> Result<(), Error> {
|
||||
let conflict = || Error::Conflict(vec![Conflict { postscript: None, path: p.path.clone() }]);
|
||||
let absent = || std::fs::symlink_metadata(&p.path).is_err();
|
||||
if absent() {
|
||||
// A hard link never replaces a file that appeared since the check.
|
||||
match std::fs::hard_link(part, &p.path) {
|
||||
Ok(()) => {
|
||||
let _ = std::fs::remove_file(part);
|
||||
return Ok(());
|
||||
}
|
||||
// A file system without hard links falls through to the rename below.
|
||||
Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists && absent() => {}
|
||||
Err(_) => return Err(conflict()),
|
||||
}
|
||||
} else if found.is_none() || file_sha256(&p.path).as_deref() != found {
|
||||
return Err(conflict());
|
||||
}
|
||||
// Over the earlier copy, or without hard links, a file another app writes between the check
|
||||
// above and this rename is replaced: std has no rename that refuses to replace.
|
||||
std::fs::rename(part, &p.path).map_err(io(format!("copying {} to {}", p.store_file, p.path.display())))
|
||||
}
|
||||
|
||||
/// Deletes a listed copy of the family in store folder `dir` when it is the store's and
|
||||
/// unchanged: `Ok(true)` when it is gone (or already was), `Ok(false)` when it is left in place.
|
||||
/// The file is moved aside first and checked there, so one changed in the meantime goes back.
|
||||
fn remove_if_unchanged(folder: &OsFontFolder, dir: &str, f: &LedgerFile) -> Result<bool, Error> {
|
||||
if !folder.owns(dir, f) {
|
||||
return Ok(false);
|
||||
}
|
||||
folder.unregister(f)?;
|
||||
restore_removing(&f.path);
|
||||
let _ = std::fs::remove_file(aside(&f.path, "part"));
|
||||
if std::fs::symlink_metadata(&f.path).is_err() {
|
||||
return Ok(true);
|
||||
}
|
||||
let what = || format!("removing {}", f.path.display());
|
||||
let removing = aside(&f.path, "removing");
|
||||
std::fs::rename(&f.path, &removing).map_err(io(what()))?;
|
||||
if file_sha256(&removing).as_ref() == Some(&f.sha256) {
|
||||
std::fs::remove_file(&removing).map_err(io(what()))?;
|
||||
Ok(true)
|
||||
} else {
|
||||
std::fs::rename(&removing, &f.path).map_err(io(what()))?;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the family's copies, except the `stale` ones about to go, where the OS needs that.
|
||||
/// Registering again is harmless: it updates the value, and withdrawal unloads every load.
|
||||
fn register_all(folder: &OsFontFolder, ledger: &Ledger, source: &str, name: &str, stale: &[LedgerFile]) -> Result<(), Error> {
|
||||
let Some(family) = ledger.family(source, name) else { return Ok(()) };
|
||||
family.copies().filter(|f| !stale.iter().any(|s| s.path == f.path)).try_for_each(|f| folder.register(f))
|
||||
}
|
||||
|
||||
/// Removes the folders `removed` files leave empty, up to the OS folder itself.
|
||||
fn prune_dirs<'a>(folder: &OsFontFolder, removed: impl Iterator<Item = &'a Path>) {
|
||||
for path in removed {
|
||||
let mut dir = path.parent();
|
||||
while let Some(d) = dir.filter(|d| *d != folder.dir && d.starts_with(&folder.dir)) {
|
||||
if std::fs::remove_dir(d).is_err() {
|
||||
break;
|
||||
}
|
||||
dir = d.parent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,37 @@ impl FontStore {
|
||||
self.change_settings(|s| s.previews = enabled)
|
||||
}
|
||||
|
||||
/// 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 ([`crate::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;
|
||||
/// 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);
|
||||
}
|
||||
self.change_settings(|s| s.craft_apps_only = on)
|
||||
}
|
||||
|
||||
/// Records the user's choice for the installed family ([`crate::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();
|
||||
|
||||
@@ -69,6 +69,7 @@ pub(super) fn merge_entry(manifest: &mut Manifest, index: &Index, family: &Famil
|
||||
license: family.license.clone(),
|
||||
license_file: None,
|
||||
files: Vec::new(),
|
||||
available_to_all: None,
|
||||
});
|
||||
manifest.families.len() - 1
|
||||
}
|
||||
|
||||
@@ -215,7 +215,6 @@ fn format_1_2_adds_tags_and_samples_and_1_1_still_loads() {
|
||||
reject(&mut check, &|v| &mut v["families"][3]["notice_file"]["path"], json!("apache/testvar/TestVar[wght].ttf"), "notice named like a font");
|
||||
}
|
||||
|
||||
#[cfg(feature = "bundled-index")]
|
||||
const NOTO_COMMIT: &str = "93fac8abebe6c7fed0c5b7d2456d8fa484fa146c";
|
||||
const VAR_PATH: &str = "fonts/NotoSerifTest/full/variable-ttf/NotoSerifTest[wdth,wght].ttf";
|
||||
const CJK_PATH: &str = "Sans/OTF/Japanese/NotoSansCJKtest-Regular.otf";
|
||||
@@ -869,4 +868,328 @@ mod store {
|
||||
assert!(store.cached_indexes(&pin).is_none());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A store with Test Sans installed, its catalog and an OS user font folder, all in temporary
|
||||
/// folders: the store, the system root (`<root>/usr/share/fonts`) and the home folder.
|
||||
fn shared_store(server: &Server, name: &str) -> (FontStore, PathBuf, PathBuf, PathBuf) {
|
||||
let index = index_of(&fixture().index).unwrap();
|
||||
let dir = temp(name);
|
||||
let root = temp(&format!("{name}-root"));
|
||||
let env = FontEnv { os: Os::Unix, root: root.clone(), home: Some(root.join("home")), font_store: Some(dir.clone()), ..Default::default() };
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
let shared = root.join("home/.local/share/fonts/Craft");
|
||||
let store = user_store(server, &dir).with_catalog(catalog).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders));
|
||||
store.install_family(&index, index.family("Test Sans").unwrap(), &Cancel::new(), &mut none).unwrap();
|
||||
(store, dir, root, shared)
|
||||
}
|
||||
|
||||
fn ledger(dir: &Path) -> serde_json::Value {
|
||||
serde_json::from_slice(&std::fs::read(dir.join("os-fonts.json")).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// Each copy in `family` matches the store's file, and the ledger lists exactly these copies.
|
||||
fn assert_copies_match_store_and_ledger(dir: &Path, family: &Path, names: &[&str]) {
|
||||
for name in names {
|
||||
assert_eq!(std::fs::read(family.join(name)).unwrap(), std::fs::read(dir.join("testsans").join(name)).unwrap());
|
||||
}
|
||||
let l = ledger(dir);
|
||||
assert_eq!((l["version"].as_u64(), l["families"][0]["family"].as_str()), (Some(1), Some("Test Sans")));
|
||||
let files = l["families"][0]["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), names.len());
|
||||
for f in files {
|
||||
let path = PathBuf::from(f["path"].as_str().unwrap());
|
||||
assert_eq!(f["sha256"].as_str().unwrap(), sha256_hex(&std::fs::read(&path).unwrap()));
|
||||
assert_eq!((f["state"].as_str(), f["mechanism"].as_str()), (Some("active"), Some("copy")));
|
||||
}
|
||||
assert_eq!(files[0]["postscript"], json!(["TestSans-Bold"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_made_available_to_all_apps_is_withdrawn_exactly() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts");
|
||||
let family = shared.join("testsans");
|
||||
assert!(store.available_to_all_supported());
|
||||
assert!(!store.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Var"), Err(Error::NotInstalled(_))));
|
||||
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
let names = ["TestSans-Bold.ttf", "TestSans-Italic.ttf", "TestSans-Regular.ttf"];
|
||||
assert_eq!(entries(&family), names, "fonts only: no licence, no temporary files");
|
||||
assert_eq!(copies, names.map(|n| family.join(n)));
|
||||
assert_copies_match_store_and_ledger(&dir, &family, &names);
|
||||
assert!(store.is_available(GOOGLE_FONTS, "test sans"));
|
||||
// Again: the copies, which the catalog now lists as system fonts, aren't conflicts.
|
||||
assert_eq!(store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(), copies);
|
||||
|
||||
// A crash after a copy was renamed into place, before the ledger said so: the next change
|
||||
// settles the entry and deletes the temporary file.
|
||||
std::fs::write(family.join(".craft-TestSans-Regular.ttf.part"), b"half").unwrap();
|
||||
let mut l = ledger(&dir);
|
||||
l["families"][0]["files"][2]["state"] = json!("adding");
|
||||
std::fs::write(dir.join("os-fonts.json"), l.to_string()).unwrap();
|
||||
store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert_eq!(entries(&family), names);
|
||||
assert!(ledger(&dir)["families"][0]["files"].as_array().unwrap().iter().all(|f| f["state"] == "active"));
|
||||
|
||||
// Withdrawing leaves a changed copy and files the store didn't add, and reports the copy.
|
||||
let italic = family.join("TestSans-Italic.ttf");
|
||||
std::fs::write(&italic, b"the user's own").unwrap();
|
||||
std::fs::write(family.join("Unlisted.ttf"), b"x").unwrap();
|
||||
assert_eq!(store.withdraw(GOOGLE_FONTS, "Test Sans").unwrap(), std::slice::from_ref(&italic));
|
||||
assert_eq!(entries(&family), ["TestSans-Italic.ttf", "Unlisted.ttf"]);
|
||||
assert!(!store.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
assert_eq!(ledger(&dir)["families"], json!([]));
|
||||
assert!(store.verify().is_empty(), "the store's own files are untouched");
|
||||
|
||||
// The changed file is no longer the store's: it sits where a copy would go.
|
||||
match store.make_available(GOOGLE_FONTS, "Test Sans") {
|
||||
Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: None, path: italic.clone() }]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
std::fs::remove_file(&italic).unwrap();
|
||||
std::fs::remove_file(family.join("Unlisted.ttf")).unwrap();
|
||||
|
||||
// Removing the family from the store withdraws it.
|
||||
store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert!(store.copies_out_of_reach(GOOGLE_FONTS, "Test Sans").is_empty());
|
||||
store.remove_family(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert!(!family.exists());
|
||||
assert!(!store.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
|
||||
// A build that can't change the OS folder removes the store's files and leaves the copies
|
||||
// it can't reach, still listed, for a build that can.
|
||||
let index = index_of(&fixture().index).unwrap();
|
||||
store.install_family(&index, index.family("Test Sans").unwrap(), &Cancel::new(), &mut none).unwrap();
|
||||
store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
let blind = FontStore::new(dir.clone(), Caller::User);
|
||||
let out_of_reach = blind.copies_out_of_reach(GOOGLE_FONTS, "Test Sans");
|
||||
assert_eq!(out_of_reach, names.map(|n| family.join(n)));
|
||||
blind.remove_family(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert!(blind.installed_family(GOOGLE_FONTS, "Test Sans").is_none());
|
||||
assert!(out_of_reach.iter().all(|c| c.is_file()));
|
||||
assert!(blind.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn making_available_refuses_postscript_conflicts_and_agents() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-conflict");
|
||||
let agent = FontStore::new(dir.clone(), Caller::Agent).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders));
|
||||
assert!(matches!(agent.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed)));
|
||||
assert!(matches!(agent.withdraw(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed)));
|
||||
assert!(!FontStore::new(dir.clone(), Caller::User).available_to_all_supported());
|
||||
|
||||
// A different font of the same PostScript name in a system folder.
|
||||
let system = root.join("usr/share/fonts");
|
||||
std::fs::create_dir_all(&system).unwrap();
|
||||
let other = system.join("TestSans-Bold.ttf");
|
||||
std::fs::write(&other, font("Test Sans", "Bold", 600)).unwrap();
|
||||
match store.make_available(GOOGLE_FONTS, "Test Sans") {
|
||||
Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: Some("TestSans-Bold".into()), path: other.clone() }]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(!shared.exists(), "nothing copied");
|
||||
assert!(!store.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
|
||||
// The same file is no conflict: the system has it, so it isn't copied or recorded.
|
||||
std::fs::write(&other, std::fs::read(dir.join("testsans/TestSans-Bold.ttf")).unwrap()).unwrap();
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert_eq!(copies, ["TestSans-Italic.ttf", "TestSans-Regular.ttf"].map(|n| shared.join("testsans").join(n)));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
/// A catalog of the same system as [`shared_store`]'s, to look at what a scan sees.
|
||||
fn catalog_of(dir: &Path, root: &Path) -> Catalog {
|
||||
let env = FontEnv {
|
||||
os: Os::Unix,
|
||||
root: root.to_path_buf(),
|
||||
home: Some(root.join("home")),
|
||||
font_store: Some(dir.to_path_buf()),
|
||||
..Default::default()
|
||||
};
|
||||
Catalog::new(env).with_font_service(false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn copies_reached_by_another_path_are_still_the_stores_and_links_are_refused() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-alias");
|
||||
// As Flatpak's /run/host/user-fonts: the user's font folder again, scanned first.
|
||||
let fonts = root.join("home/.local/share/fonts");
|
||||
std::fs::create_dir_all(&fonts).unwrap();
|
||||
std::fs::create_dir_all(root.join("usr/share/fonts")).unwrap();
|
||||
std::os::unix::fs::symlink(&fonts, root.join("usr/share/fonts/user-fonts")).unwrap();
|
||||
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert_eq!(copies.len(), 3);
|
||||
let seen = catalog_of(&dir, &root);
|
||||
seen.rescan();
|
||||
assert!(seen.scanned_faces().iter().any(|f| f.path.as_ref().is_some_and(|p| p.starts_with(root.join("usr/share/fonts/user-fonts")))));
|
||||
assert_eq!(store.make_available(GOOGLE_FONTS, "Test Sans").unwrap(), copies);
|
||||
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());
|
||||
|
||||
// A family folder that is a link leads outside: nothing is written or deleted through it.
|
||||
let outside = temp("os-fonts-outside");
|
||||
let mut l = ledger(&dir);
|
||||
l["families"][0]["files"][0]["path"] = json!(outside.join("TestSans-Bold.ttf"));
|
||||
std::fs::write(dir.join("os-fonts.json"), l.to_string()).unwrap();
|
||||
std::fs::copy(&copies[0], outside.join("TestSans-Bold.ttf")).unwrap();
|
||||
let kept = store.withdraw(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert_eq!(kept, [outside.join("TestSans-Bold.ttf")], "a path the store doesn't put copies at is left alone");
|
||||
assert!(outside.join("TestSans-Bold.ttf").is_file());
|
||||
std::fs::remove_file(&copies[0]).unwrap();
|
||||
std::fs::remove_dir(shared.join("testsans")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, shared.join("testsans")).unwrap();
|
||||
assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::Conflict(_))));
|
||||
assert_eq!(entries(&outside), ["TestSans-Bold.ttf"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
let _ = std::fs::remove_dir_all(outside);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ledger_that_cant_be_understood_is_kept_and_blocks_changes() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-bad-ledger");
|
||||
store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
let mut l = ledger(&dir);
|
||||
l["families"][0]["files"][0]["mechanism"] = json!("hardlink");
|
||||
let bytes = l.to_string();
|
||||
std::fs::write(dir.join("os-fonts.json"), &bytes).unwrap();
|
||||
|
||||
assert!(!store.is_available(GOOGLE_FONTS, "Test Sans"));
|
||||
assert!(matches!(store.make_available(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_))));
|
||||
assert!(matches!(store.withdraw(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_))));
|
||||
assert!(matches!(store.remove_family(GOOGLE_FONTS, "Test Sans"), Err(Error::Ledger(_))));
|
||||
assert_eq!(std::fs::read_to_string(dir.join("os-fonts.json")).unwrap(), bytes);
|
||||
assert_eq!(entries(&shared.join("testsans")).len(), 3);
|
||||
assert!(store.installed_family(GOOGLE_FONTS, "Test Sans").is_some());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_families_and_named_instances_conflict_by_postscript_name() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let index = index_of(&fixture().index).unwrap();
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-families");
|
||||
for name in ["Shared One", "Shared Two", "Test Var"] {
|
||||
store.install_family(&index, index.family(name).unwrap(), &Cancel::new(), &mut none).unwrap();
|
||||
}
|
||||
// Both families' index entries name the face Shared-Regular.
|
||||
store.make_available(GOOGLE_FONTS, "Shared One").unwrap();
|
||||
match store.make_available(GOOGLE_FONTS, "Shared Two") {
|
||||
Err(Error::Conflict(c)) => {
|
||||
assert_eq!(c, [Conflict { postscript: Some("Shared-Regular".into()), path: shared.join("sharedone/SharedOne-Regular.ttf") }])
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// A static system face named as one of a variable font's instances.
|
||||
let system = root.join("usr/share/fonts");
|
||||
std::fs::create_dir_all(&system).unwrap();
|
||||
std::fs::write(system.join("TestVar-Bold.ttf"), font("Test Var", "Bold", 700)).unwrap();
|
||||
match store.make_available(GOOGLE_FONTS, "Test Var") {
|
||||
Err(Error::Conflict(c)) => assert_eq!(c, [Conflict { postscript: Some("TestVar-Bold".into()), path: system.join("TestVar-Bold.ttf") }]),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
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();
|
||||
server.serve_fixture(&fixture());
|
||||
let index = index_of(&fixture().index).unwrap();
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-agent");
|
||||
store.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Italic.ttf".into()]).unwrap();
|
||||
store.make_available(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
let family = shared.join("testsans");
|
||||
let before = entries(&family);
|
||||
assert_eq!(before, ["TestSans-Bold.ttf", "TestSans-Regular.ttf"]);
|
||||
|
||||
// An agent's install stays in the store, listed as not yet available.
|
||||
let agent =
|
||||
FontStore::new(dir.clone(), Caller::Agent).with_client(server.client()).with_os_fonts(OsFontFolder::at(&shared, OsFontLayout::Folders));
|
||||
agent.install_face(&index, index.find_face("Test Sans", "Italic").unwrap(), &Cancel::new(), &mut none).unwrap();
|
||||
assert_eq!(entries(&family), before);
|
||||
assert_eq!(store.pending_files(GOOGLE_FONTS, "Test Sans"), ["TestSans-Italic.ttf"]);
|
||||
|
||||
// An agent can't remove what has copies; the user can.
|
||||
assert!(matches!(agent.remove_family(GOOGLE_FONTS, "Test Sans"), Err(Error::NotAllowed)));
|
||||
assert!(matches!(agent.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Bold.ttf".into()]), Err(Error::NotAllowed)));
|
||||
assert_eq!(store.installed_family(GOOGLE_FONTS, "Test Sans").unwrap().files.len(), 3);
|
||||
assert_eq!(entries(&family), before);
|
||||
agent.remove_files(GOOGLE_FONTS, "Test Sans", &["TestSans-Italic.ttf".into()]).unwrap();
|
||||
|
||||
store.install_face(&index, index.find_face("Test Sans", "Italic").unwrap(), &Cancel::new(), &mut none).unwrap();
|
||||
assert_eq!(entries(&family), ["TestSans-Bold.ttf", "TestSans-Italic.ttf", "TestSans-Regular.ttf"], "the user's install copies it");
|
||||
assert!(store.pending_files(GOOGLE_FONTS, "Test Sans").is_empty());
|
||||
store.remove_family(GOOGLE_FONTS, "Test Sans").unwrap();
|
||||
assert!(!family.exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_os_folder_follows_the_platform_and_flatpak_grants() {
|
||||
let root = temp("os-fonts-env");
|
||||
let home = root.join("home");
|
||||
let flatpak = FontEnv { os: Os::Unix, root: root.clone(), home: Some(home.clone()), flatpak: true, ..Default::default() };
|
||||
let with = |vars: &[(&str, &str)], env: &FontEnv| {
|
||||
let vars: Vec<(String, String)> = vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
|
||||
OsFontFolder::for_env_with(env, &move |k| vars.iter().find(|(n, _)| n == k).map(|(_, v)| v.into())).map(|f| f.dir().to_path_buf())
|
||||
};
|
||||
let info = |filesystems: &str| std::fs::write(root.join(".flatpak-info"), format!("[Context]\nfilesystems={filesystems}\n")).unwrap();
|
||||
|
||||
let unix = FontEnv { flatpak: false, xdg_data_home: Some(root.join("data")), ..flatpak.clone() };
|
||||
assert_eq!(with(&[], &unix), Ok(root.join("data/fonts/Craft")));
|
||||
assert!(with(&[("SNAP", "/snap/x")], &unix).is_err());
|
||||
let mac = FontEnv { os: Os::MacOs, ..unix.clone() };
|
||||
assert_eq!(with(&[], &mac), Ok(home.join("Library/Fonts")));
|
||||
assert!(with(&[("APP_SANDBOX_CONTAINER_ID", "x")], &mac).is_err());
|
||||
let windows = FontEnv { os: Os::Windows, local_app_data: Some(root.join("Local")), ..unix.clone() };
|
||||
assert_eq!(with(&[], &windows), Ok(root.join("Local/Microsoft/Windows/Fonts/Craft")));
|
||||
assert_eq!(with(&[], &FontEnv { local_app_data: None, ..windows.clone() }), Ok(home.join("AppData/Local/Microsoft/Windows/Fonts/Craft")));
|
||||
|
||||
info("xdg-data/fonts:create;");
|
||||
assert_eq!(with(&[], &flatpak), Ok(home.join(".local/share/fonts/Craft")));
|
||||
info("xdg-data/fonts:create;!xdg-data/fonts;");
|
||||
assert!(with(&[], &flatpak).is_err(), "revoked");
|
||||
info("home:ro;");
|
||||
assert!(with(&[], &flatpak).is_err(), "read only");
|
||||
info("~/.local/share/fonts;");
|
||||
assert!(with(&[], &flatpak).is_ok());
|
||||
assert!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak).is_err(), "the grant is for another folder");
|
||||
info("xdg-data/fonts;");
|
||||
assert_eq!(with(&[("HOST_XDG_DATA_HOME", "/elsewhere")], &flatpak), Ok(PathBuf::from("/elsewhere/fonts/Craft")));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
@@ -232,7 +232,7 @@ impl Component for ColumnBar<'_> {
|
||||
start = end;
|
||||
}
|
||||
for (at, divider) in dividers(&shares, rect, cx.style.grab) {
|
||||
divider::declare(cx, rect, DIVIDER, at, ÷r);
|
||||
divider::declare_focusing(cx, rect, DIVIDER, at, ÷r);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -458,7 +458,7 @@ impl Component for MarginHandles<'_> {
|
||||
let (grab, strip) = (cx.style.grab, cx.style.strip);
|
||||
let words = cx.words::<MarginHandlesWords>();
|
||||
for &visible in self.edges_shown() {
|
||||
divider::declare(cx, rect, EDGE, visible.index(), &self.divider(&rules, visible, rect, (grab, strip)))
|
||||
divider::declare_focusing(cx, rect, EDGE, visible.index(), &self.divider(&rules, visible, rect, (grab, strip)))
|
||||
.tooltip(visible.name(&words).clone());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,15 @@ pub fn text_contrast_min(contrast: Contrast) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The least contrast ratio non-text elements (controls, boundaries, icons) need against their background:
|
||||
/// WCAG non-text minimum, and the higher minimum under high contrast.
|
||||
pub fn non_text_contrast_min(contrast: Contrast) -> f64 {
|
||||
match contrast {
|
||||
Contrast::Standard => values::NON_TEXT_MIN.0,
|
||||
Contrast::High => values::NON_TEXT_MIN.1,
|
||||
}
|
||||
}
|
||||
|
||||
/// WCAG relative luminance, 0 (black) to 1 (white). Alpha is ignored.
|
||||
pub fn relative_luminance(c: Rgba) -> f64 {
|
||||
let [r, g, b] = c.to_linear();
|
||||
|
||||
@@ -73,7 +73,7 @@ pub use color::{Hsb, Lab, Oklab, Oklch, Rgba, Srgba};
|
||||
pub use color_model::{
|
||||
Channel, ColorModel, DefaultOn, HsbModel, LabModel, MAX_CHANNELS, ModelValues, OklchModel, RgbModel, builtin_models, kept_or_converted,
|
||||
};
|
||||
pub use contrast::{contrast_ratio, ensure_contrast, relative_luminance, text_contrast_min};
|
||||
pub use contrast::{contrast_ratio, ensure_contrast, non_text_contrast_min, relative_luminance, text_contrast_min};
|
||||
pub use derive::{Anchoring, ContrastCheck, PassMove, Ramps, over};
|
||||
pub use explain::{ColorOrigin, Explained, PairReport, SizeLayer, SizeOrigin, explain, explain_sized};
|
||||
pub use id::{APP_DEFAULT, AppId, IconPackId, IdError, RESERVED_PREFIX, SUITE_DEFAULT, ThemeId};
|
||||
|
||||
@@ -18,6 +18,12 @@ fn contrast_moves_keep_greys_neutral() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_text_contrast_min_matches_theme_values() {
|
||||
assert_eq!(non_text_contrast_min(Contrast::Standard), 3.0);
|
||||
assert_eq!(non_text_contrast_min(Contrast::High), 4.5);
|
||||
}
|
||||
|
||||
/// A user's accent over each built-in theme, in each mode and contrast and for each app the theme overrides, gives
|
||||
/// the accent fill its own colour even where the theme fixes the fill, and fails no contrast pair the theme alone
|
||||
/// passes.
|
||||
|
||||
@@ -362,6 +362,58 @@ pub(crate) mod own_window {
|
||||
assert!(!open.get(), "closing the dialog's window closes the dialog");
|
||||
assert_eq!(closed.get(), Some((CloseReason::Requested, true)), "the close is a cancel");
|
||||
}
|
||||
|
||||
/// photocraft#16905: in a window the app frames, a full-window dialog's own window moves by its title row. Its
|
||||
/// fallback covers the main window and does not move, and the window took that rule, so RAW Develop's window could
|
||||
/// not be moved.
|
||||
#[trial]
|
||||
fn a_full_window_dialogs_own_window_moves_by_its_title_row() {
|
||||
use craft_host::target::{Backend, Os, ShellInfo, WindowKind};
|
||||
use craft_ui::runtime::InstallSpec;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::windows::FakeSystem;
|
||||
use craft_window::policy::{Desktop, DesktopKind, Runtime, TitleBarPref};
|
||||
use egui::{Pos2, Rect, Vec2, ViewportCommand, pos2, vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None };
|
||||
let integrated =
|
||||
craft_window::policy::decide(Os::Linux, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None);
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(FakeSystem::new())).frame(integrated));
|
||||
let open = Cell::new(true);
|
||||
let frame = |events: Vec<egui::Event>| {
|
||||
windows.frame(vec![], events, |ui| {
|
||||
let mut is_open = open.get();
|
||||
FullWindowDialog::new("Workspace").own_window(WindowSpec::dialog()).opened(Bind::bound(&mut is_open)).show(ui, |_, _| {});
|
||||
open.set(is_open);
|
||||
})
|
||||
};
|
||||
let rect = Rect::from_min_size(Pos2::new(100.0, 100.0), Vec2::new(900.0, 640.0));
|
||||
windows.child_info(ViewportInfo {
|
||||
inner_rect: Some(rect),
|
||||
outer_rect: Some(rect),
|
||||
native_pixels_per_point: Some(1.0),
|
||||
..ViewportInfo::default()
|
||||
});
|
||||
for _ in 0..4 {
|
||||
frame(vec![]);
|
||||
}
|
||||
// Clear of the top edge's grip and of the title row's own parts (the title at the start, the close action at
|
||||
// the end).
|
||||
let at = pos2(450.0, 14.0);
|
||||
let mut sent = Vec::new();
|
||||
for events in [
|
||||
vec![moved(at)],
|
||||
vec![press(at)],
|
||||
vec![moved(at + vec2(20.0, 10.0))],
|
||||
vec![moved(at + vec2(40.0, 20.0))],
|
||||
vec![release(at + vec2(40.0, 20.0))],
|
||||
] {
|
||||
sent.extend(frame(events).commands.into_iter().map(|(_, command)| command));
|
||||
}
|
||||
assert!(open.get(), "the dialog stays open");
|
||||
assert!(sent.contains(&ViewportCommand::StartDrag), "a drag of the title row moves the window: {sent:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An overlay drawn through a frame.
|
||||
|
||||
@@ -795,11 +795,16 @@ impl BodyHooks<'_> {
|
||||
};
|
||||
let exclusive = |hit: WindowHit| os.is_some().then_some(hit);
|
||||
let moves_window = matches!(&props.mount, Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } if overlay.moves_window);
|
||||
// A full-window container in an OS window of its own: its fallback layer covers the main window, so neither
|
||||
// moves nor resizes, but the window is one the user moves by its title row and sizes by its edges, as any
|
||||
// window. Without them a window the app frames had no band and no grips (photocraft#16905).
|
||||
let own_full_window = os.is_some() && matches!(&props.mount, Mount::Viewport { fallback, .. } if fallback.is_full_window());
|
||||
// A layer moves when its overlay says so; other mounts follow the header's band.
|
||||
let movable = match &props.mount {
|
||||
// A band that moves the window below follows the rule of the window's own band (a title bar's); where the
|
||||
// platform answers the hit test, the sink reads it from the exclusive list.
|
||||
_ if moves_window => WindowParts::of(&ctx, pass::current_viewport(&ctx)).band,
|
||||
_ if own_full_window => stands.band,
|
||||
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => overlay.movable && stands.band,
|
||||
_ => props.header.is_some_and(|header| header.band == crate::contract::DragBand::Move) && stands.band,
|
||||
};
|
||||
@@ -810,8 +815,9 @@ impl BodyHooks<'_> {
|
||||
// areas cover its ends and top edge, and a cursor set over them fights the OS's.
|
||||
let moved = os.or(moves_window.then(|| pass::current_viewport(&ctx)));
|
||||
let os_bar = moved.is_some_and(|viewport| windows::shell_of(&ctx, viewport).window.chrome == WindowChrome::Inset);
|
||||
let hand = pcx.env.get::<crate::contract::MoveBandCursor>() == crate::contract::MoveBandCursor::Hand;
|
||||
let mut part = pcx.part(MOVE_BAND, band).sense(craft_behavior::Sense::DRAG).pointer_only(reason);
|
||||
if !os_bar {
|
||||
if !os_bar && hand {
|
||||
part = part.cursor(CursorIcon::Grab).drag_cursor(CursorIcon::Grabbing);
|
||||
}
|
||||
if let Some(hit) = exclusive(WindowHit::Move).or(moves_window.then_some(WindowHit::Move)) {
|
||||
@@ -825,6 +831,7 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
}
|
||||
let edges = match &props.mount {
|
||||
_ if own_full_window => ResizeEdges::ALL,
|
||||
Mount::Layer(overlay) | Mount::Viewport { fallback: overlay, .. } => overlay.resize.edges,
|
||||
Mount::Window { resize } => resize.edges,
|
||||
_ => ResizeEdges::NONE,
|
||||
|
||||
@@ -350,6 +350,20 @@ pub enum QuietHeader {
|
||||
Heads,
|
||||
}
|
||||
|
||||
/// The cursor over a header's move band ([`DragBand::Move`]). An app sets it once at its root (`RootEnv::values`); the
|
||||
/// default is `Hand`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::runtime::env::EnvValue, crate::contract::MemoProps)]
|
||||
#[env(style)]
|
||||
#[non_exhaustive]
|
||||
pub enum MoveBandCursor {
|
||||
/// The open hand, and the closed hand while the band is dragged.
|
||||
#[default]
|
||||
Hand,
|
||||
/// The arrow, as an OS title bar shows, also over the click-only controls on the band (menu titles, buttons):
|
||||
/// production VectorCraft's title bar and panel headers.
|
||||
Arrow,
|
||||
}
|
||||
|
||||
/// A header region, filled by `Container::header`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -87,7 +87,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> {
|
||||
// A kept measure serves only the outermost measuring run, which this opens when none is open.
|
||||
let inputs = self.items_inputs(comp, ui, room);
|
||||
if let Some(inputs) = &inputs
|
||||
&& crate::runtime::measure::run(&ctx, || layout_memory::kept_serves(&ctx, key, inputs))
|
||||
&& crate::runtime::measure::measuring(&ctx, || layout_memory::kept_serves(&ctx, key, inputs))
|
||||
&& let Some(found) = found(&ctx)
|
||||
{
|
||||
return found.took;
|
||||
|
||||
@@ -69,8 +69,8 @@ pub use container::InBar;
|
||||
pub use container::InMenu;
|
||||
pub use container::{
|
||||
BandFill, Bracket, Collapse, ContainerProps, DragBand, EndRegion, FooterPlace, FooterRegion, Gap, HeaderEdge, HeaderParts, HeaderRegion,
|
||||
LeastWidth, Mount, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator, SectionRhythm,
|
||||
ShellPane, Sizing, ThemeScope, WrapWidth,
|
||||
LeastWidth, Mount, MoveBandCursor, Notch, POPUP_PAD, Pad, PadEdges, PaneEdge, QuietHeader, Scroll, ScrollAnchor, ScrollAxes, ScrollIndicator,
|
||||
SectionRhythm, ShellPane, Sizing, ThemeScope, WrapWidth,
|
||||
};
|
||||
pub use craft_tracked::{PlainData, Revision, Tracked};
|
||||
pub use craft_ui_macros::{CommandSet, Component, Pattern, PlainData, Props, register_contract};
|
||||
|
||||
@@ -159,6 +159,11 @@ impl<'a> OverlayUi<'a> {
|
||||
};
|
||||
// An in-place editor is part of its owner: the owner's node reports no popup of it.
|
||||
let (kind, peers, reported) = (overlay.popup, overlay.opener.is_none(), overlay.role != LayerRole::InPlaceEditor);
|
||||
// A popup with no recorded opener hangs from this component: when the component goes disabled, its anchor is
|
||||
// gone, as for an explicit opener that goes disabled (`dismissal`).
|
||||
if open && peers && overlay.dismiss.anchor_gone && !self.resolved.enabled {
|
||||
crate::runtime::overlay::request_close(self.ctx, popup.id, CloseReason::AnchorGone);
|
||||
}
|
||||
let ctx = self.ctx.clone();
|
||||
with_popups(&ctx, |popups| {
|
||||
if reported {
|
||||
|
||||
@@ -56,7 +56,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> {
|
||||
});
|
||||
let size = kept.unwrap_or_else(|| {
|
||||
replay::open_in_pass(&ctx);
|
||||
let size = measure::run(&ctx, || {
|
||||
let size = measure::measuring(&ctx, || {
|
||||
// What the hidden page measures joins no transcript around it: the run that shows the pages does
|
||||
// not show it, so nothing there checks it.
|
||||
layout_memory::boundary(&ctx, true, || {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub(crate) struct IdPass {
|
||||
/// Runs `f` as a measuring run that leaves the `Auto` ordinals as it found them, so the run that follows in the same
|
||||
/// pass gives every component the id the measuring run gave it.
|
||||
pub(in crate::contract) fn measuring<R>(ctx: &Context, f: impl FnOnce() -> R) -> R {
|
||||
keeping_ids(ctx, || (crate::runtime::measure::run(ctx, f), true))
|
||||
keeping_ids(ctx, || (crate::runtime::measure::measuring(ctx, f), true))
|
||||
}
|
||||
|
||||
/// Runs the measuring run `run` as a draft (`layout_memory::draft`) whose `Auto` ordinals go with it: taken back, it leaves
|
||||
|
||||
@@ -658,6 +658,13 @@ pub fn moves(ctx: &Context, viewport: ViewportId) -> bool {
|
||||
board(ctx, |board| board.session.as_ref().is_some_and(|session| session.moving.viewport == Some(viewport)))
|
||||
}
|
||||
|
||||
/// Whether `source` started the running session, which after its release lives until a target in another window has
|
||||
/// taken the drop.
|
||||
#[doc(hidden)]
|
||||
pub fn sourced_by(ctx: &Context, source: Id) -> bool {
|
||||
board(ctx, |board| board.session.as_ref().is_some_and(|session| session.source == source))
|
||||
}
|
||||
|
||||
/// Starts a session whose source is the container `source`, as the title row of a dock window does, with no payload
|
||||
/// of its own. For trials.
|
||||
#[cfg(feature = "testing")]
|
||||
|
||||
@@ -551,6 +551,12 @@ pub(crate) fn host_popup(ui: &Ui, id: egui::Id, at: Pos2) {
|
||||
egui::Popup::new(id, ui.ctx().clone(), at, ui.layer_id()).open_memory(None).show(|ui| ui.allocate_space(ui.spacing().interact_size));
|
||||
}
|
||||
|
||||
/// A host's own egui window `id` around `body`: its first pass is a sizing pass, in an invisible `Ui`.
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) fn host_egui_window(ctx: &Context, id: Id, body: impl FnOnce(&mut Ui)) {
|
||||
egui::Window::new("host").id(id).show(ctx, body);
|
||||
}
|
||||
|
||||
/// The size of one entry of [`host_popup_list`], as an app's popup list entry.
|
||||
#[cfg(feature = "suite")]
|
||||
const HOST_LIST_ENTRY: Vec2 = Vec2::new(104.0, 22.0);
|
||||
|
||||
@@ -618,6 +618,18 @@ pub(crate) fn host_drag_area(ui: &Ui, id: egui::Id, rect: Rect) -> (bool, bool)
|
||||
(response.dragged(), response.drag_stopped())
|
||||
}
|
||||
|
||||
/// A host's own clickable egui widget `id` at `rect` in a disabled `Ui`.
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) fn host_disabled_button(ui: &mut Ui, id: egui::Id, rect: Rect) {
|
||||
ui.scope_builder(egui::UiBuilder::new().disabled(), |ui| host_button(ui, id, rect));
|
||||
}
|
||||
|
||||
/// A host's own egui widget `id` at `rect` that senses drags and takes no focus.
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) fn host_unfocusable_area(ui: &Ui, id: egui::Id, rect: Rect) {
|
||||
ui.interact(rect, id, egui::Sense::DRAG);
|
||||
}
|
||||
|
||||
/// A host's own selectable egui label of `text`; returns its rect.
|
||||
#[cfg(feature = "suite")]
|
||||
pub(crate) fn host_label(ui: &mut Ui, text: &str) -> Rect {
|
||||
|
||||
@@ -33,6 +33,13 @@ pub(crate) fn candidates_since(ctx: &Context, seen: usize) -> Vec<egui::FocusCan
|
||||
ctx.memory(|memory| memory.focus_candidates().get(seen..).map(<[_]>::to_vec).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The widget `id` as drawn so far in the running pass; `None` when no widget has the id. egui takes the focus from a
|
||||
/// widget that is not focusable or not enabled when it is drawn, and from an id no interactive widget has at the pass's
|
||||
/// end.
|
||||
pub(crate) fn drawn_widget(ctx: &Context, id: Id) -> Option<egui::WidgetRect> {
|
||||
ctx.viewport(|viewport| viewport.this_pass.widgets.get(id).copied())
|
||||
}
|
||||
|
||||
/// Whether the widget egui holds key focus on keeps Tab by its event filter (`Memory::focus_lock_filter`).
|
||||
pub(crate) fn focused_keeps_tab(ctx: &Context) -> bool {
|
||||
ctx.memory(|memory| memory.focus_lock_filter()).is_some_and(|filter| filter.tab)
|
||||
@@ -44,8 +51,8 @@ pub(crate) fn label_selection(ctx: &Context) -> bool {
|
||||
}
|
||||
|
||||
/// Gives `id` key focus with `filter`, applied from this pass: a filter set afterwards acts a pass late. egui never
|
||||
/// takes this focus away on a press or click elsewhere: the runtime moves it on press (8.3). egui's own rule, the
|
||||
/// app's `surrender_focus_on`, applies to the focus of the app's own widgets.
|
||||
/// takes this focus away on a press or click elsewhere: the runtime moves it on press (8.3). The end hook leaves
|
||||
/// the focus of an app's own widget to egui's rule (`leave_to_egui`).
|
||||
pub(crate) fn focus_with_filter(ctx: &Context, id: Id, filter: KeyFilter) {
|
||||
let filter =
|
||||
EventFilter { tab: filter.tab, horizontal_arrows: filter.horizontal_arrows, vertical_arrows: filter.vertical_arrows, escape: filter.escape };
|
||||
@@ -55,6 +62,23 @@ pub(crate) fn focus_with_filter(ctx: &Context, id: Id, filter: KeyFilter) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Keeps egui from taking the focus of `id`, if it holds it, on a press or click elsewhere, until the focus moves or a
|
||||
/// request gives it again.
|
||||
pub(crate) fn never_surrender(ctx: &Context, id: Id) {
|
||||
ctx.memory_mut(|memory| memory.set_focus_surrender(id, SurrenderFocusOn::Never));
|
||||
}
|
||||
|
||||
/// Leaves the focus of the app's own widget `id`, if it holds it, to egui's rule, the app's `surrender_focus_on`, with
|
||||
/// the key filter it has.
|
||||
pub(crate) fn leave_to_egui(ctx: &Context, id: Id) {
|
||||
ctx.memory_mut(|memory| {
|
||||
if memory.has_focus(id) {
|
||||
let filter = memory.focus_lock_filter().unwrap_or_default();
|
||||
memory.request_focus_with_filter(id, filter);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Gives a component's widget `id` back the focus egui dropped in this pass (egui drops the focus of a disabled
|
||||
/// widget), as the runtime's focus: egui never surrenders it on a press or click elsewhere.
|
||||
pub(crate) fn keep_focus(memory: &mut egui::Memory, id: Id) {
|
||||
|
||||
@@ -795,6 +795,11 @@ pub(crate) fn dragged(ctx: &Context) -> Option<Id> {
|
||||
ctx.dragged_id()
|
||||
}
|
||||
|
||||
/// Whether a pointer button is down.
|
||||
pub(crate) fn button_down(ctx: &Context) -> bool {
|
||||
ctx.input(|input| input.pointer.any_down())
|
||||
}
|
||||
|
||||
/// Where the press that is held down began, while a button is down.
|
||||
pub(crate) fn held_press_origin(ctx: &Context) -> Option<Pos2> {
|
||||
ctx.input(|input| if input.pointer.any_down() { input.pointer.press_origin() } else { None })
|
||||
|
||||
@@ -850,21 +850,29 @@ impl Env {
|
||||
Env { scoped: Arc::new(scoped) }
|
||||
}
|
||||
|
||||
/// A child entry that changes layer-local fields only (arena, item, row, roving, grid, scroll owner,
|
||||
/// transform, ink): the key carries over, because none of its inputs change.
|
||||
/// This env for a body that starts a layout room of its own (a layer, a pane): the flow grid and the content
|
||||
/// column of the room around it do not reach in.
|
||||
/// column of the room around it do not reach in. When opened inside a bar, it leaves the bar (`InBar(false)`) and
|
||||
/// recomputes the env key so styles do not reuse the bar's cache entries.
|
||||
pub(crate) fn new_room(&self) -> Env {
|
||||
self.derive_local(|scoped| {
|
||||
let reset = |scoped: &mut Scoped| {
|
||||
scoped.start_room();
|
||||
scoped.bracket = None;
|
||||
scoped.lazy = None;
|
||||
scoped.measure = None;
|
||||
// A pane opened from a bar is not the bar's line.
|
||||
scoped.inherited_mut().values.set(InBar(false));
|
||||
})
|
||||
};
|
||||
if self.get::<InBar>().0 {
|
||||
self.derive(|scoped| {
|
||||
reset(scoped);
|
||||
// A pane opened from a bar is not the bar's line.
|
||||
scoped.inherited_mut().values.set(InBar(false));
|
||||
})
|
||||
} else {
|
||||
self.derive_local(reset)
|
||||
}
|
||||
}
|
||||
|
||||
/// A child entry that changes layer-local fields only (arena, item, row, roving, grid, scroll owner,
|
||||
/// transform, ink): the key carries over, because none of its inputs change.
|
||||
pub(crate) fn derive_local(&self, f: impl FnOnce(&mut Scoped)) -> Env {
|
||||
let mut scoped = (*self.scoped).clone();
|
||||
f(&mut scoped);
|
||||
|
||||
+12
-1
@@ -130,16 +130,27 @@ pub enum RowPressed {
|
||||
/// takes a box wider than its line, a select fits its widest entry up to a field length, a rule shows only with the
|
||||
/// member after it, and a row too long for its room narrows its last units first. A layer or pane opened from the bar
|
||||
/// starts without it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, crate::contract::MemoProps)]
|
||||
#[doc(hidden)]
|
||||
pub struct InBar(pub bool);
|
||||
|
||||
impl EnvValue for InBar {
|
||||
const AFFECTS_STYLE: bool = true;
|
||||
|
||||
fn root() -> Self {
|
||||
InBar(false)
|
||||
}
|
||||
|
||||
fn style_hash(&self) -> Option<u64> {
|
||||
use std::hash::{Hash as _, Hasher as _};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
self.hash(&mut hasher);
|
||||
Some(hasher.finish())
|
||||
}
|
||||
}
|
||||
|
||||
impl super::StyleValue for InBar {}
|
||||
|
||||
/// The component set: an app sets it on its root (`RootEnv::set`) and a container may set another for its subtree
|
||||
/// (`Overrides::values`); every window, layer and popup opened inside takes the scope's. A component with variants
|
||||
/// reads it in `style` (`StyleCx::set`) and maps it to one of them. It is in the style key, so a change restyles as a
|
||||
|
||||
@@ -17,8 +17,11 @@ pub(crate) use registration::{Group, Stop};
|
||||
use crate::runtime::egui::focus as egui_focus;
|
||||
use crate::runtime::egui::memory::FastMap;
|
||||
use crate::runtime::frame::PerViewport;
|
||||
use crate::runtime::inspect;
|
||||
use crate::style::log_once;
|
||||
use craft_behavior::{DocKey, OwnerClass, PartRef};
|
||||
use egui::{Context, Id, IdSet, ViewportId};
|
||||
use smallvec::SmallVec;
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
@@ -194,6 +197,13 @@ pub(crate) struct State {
|
||||
/// How many of egui's focus candidates of the running pass (`Memory::focus_candidates`) `take_app_widgets` has
|
||||
/// read.
|
||||
pub(super) candidates_seen: usize,
|
||||
/// The widget the runtime gave egui's focus, under its own press rule, until the end hook settles it
|
||||
/// (`settle_given`): the focus of an app's own widget is left to egui's rule there.
|
||||
given: Option<Id>,
|
||||
/// The app's document canvas whose focus is off egui's press rule (`hold_canvas_focus`).
|
||||
held_canvas: Option<Id>,
|
||||
/// The canvases the running pass declared with `host_canvas`, which the end hook looks up among egui's widgets.
|
||||
host_canvases: SmallVec<[Id; 1]>,
|
||||
/// A text widget that gave its Escape on to the enclosing scopes and lets focus go at the end of the pass.
|
||||
surrender_after_scopes: Option<Id>,
|
||||
/// A text widget in a scope that gives focus back to its opener, held one more pass: the scope the Escape closes is
|
||||
@@ -228,7 +238,10 @@ pub(crate) fn apply(ctx: &Context, acts: Vec<Act>) {
|
||||
}
|
||||
for act in acts {
|
||||
match act {
|
||||
Act::Focus(id, filter) => egui_focus::focus_with_filter(ctx, id, filter),
|
||||
Act::Focus(id, filter) => {
|
||||
egui_focus::focus_with_filter(ctx, id, filter);
|
||||
with(ctx, |state| state.given = Some(id));
|
||||
}
|
||||
Act::Surrender(id) => egui_focus::surrender(ctx, id),
|
||||
}
|
||||
}
|
||||
@@ -236,16 +249,19 @@ pub(crate) fn apply(ctx: &Context, acts: Vec<Act>) {
|
||||
|
||||
/// Registers a stop of the running pass in the innermost open scope, in registration order: after the app's own
|
||||
/// widgets drawn before it (`take_app_widgets`). The app's own widget `stop` names (`host_canvas`) takes the place of
|
||||
/// its stop as one of those widgets, if the pass took it already.
|
||||
/// its stop as one of those widgets, if the pass took it already; focus the runtime gave that stop follows the canvas's
|
||||
/// keys from then on.
|
||||
pub(crate) fn register_stop(ctx: &Context, stop: Stop) {
|
||||
take_app_widgets(ctx, Some(stop.root));
|
||||
let held = stop.host && egui_focus::has_focus(ctx, stop.root);
|
||||
let acts = with(ctx, |state| {
|
||||
if stop.host
|
||||
&& let Some(rec) = state.stops.iter_mut().find(|rec| rec.stop.host && rec.stop.id == stop.id)
|
||||
{
|
||||
state.stop_roots.insert(stop.root);
|
||||
let acts = if held && state.given == Some(stop.root) { vec![nav::focus_act(&stop)] } else { Vec::new() };
|
||||
rec.stop = stop;
|
||||
return Vec::new();
|
||||
return acts;
|
||||
}
|
||||
state.push_stop(stop)
|
||||
});
|
||||
@@ -318,9 +334,23 @@ fn take_app_widgets(ctx: &Context, except: Option<Id>) {
|
||||
/// them; Page Up and Down, Home and End arrive as its `Intent::Move`, as while it has the focus. A bare Tab with nothing
|
||||
/// focused is never the canvas's, even when it keeps Tab: it moves focus into the window or toggles the panels, so the
|
||||
/// canvas cannot trap keyboard navigation. With the canvas focused, the same keys stay in egui, a Tab it keeps and
|
||||
/// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel. Call it
|
||||
/// each pass the canvas shows.
|
||||
/// Escape too, as for any focused widget of the app's own; Escape with nothing focused is the window's cancel.
|
||||
///
|
||||
/// A press that nothing takes leaves the canvas focused, whoever gave it the focus and whatever the app's
|
||||
/// `surrender_focus_on`: a press on the app's own widgets that take no focus or on empty space moves no focus. The canvas
|
||||
/// loses the focus to a component or widget that takes it, Tab, F6, a dialog, the app's own request or surrender, and
|
||||
/// when it is no longer drawn.
|
||||
///
|
||||
/// Call it in each pass the canvas shows, before or after the canvas is drawn, with the id of the focusable, enabled
|
||||
/// egui widget the app draws for it in every such pass (`Sense::click()`, `Sense::drag()`; the bare flags `Sense::CLICK`
|
||||
/// and `Sense::DRAG` are not focusable). egui drops the focus of an id that no such widget of the pass has, so Tab would
|
||||
/// lose the focus at the canvas and start over at the window's first stop. A pass that declares a canvas and draws no
|
||||
/// such widget reports the finding `canvas-without-widget`, and debug builds log it once; a canvas drawn in an invisible
|
||||
/// `Ui` (an egui sizing pass) is not reported as disabled. A pass that hides or disables the canvas makes no call.
|
||||
pub fn host_canvas(ctx: &Context, id: Id, keys: KeyUse) {
|
||||
if !crate::runtime::measure::active(ctx) {
|
||||
with(ctx, |state| state.host_canvases.push(id));
|
||||
}
|
||||
register_stop(ctx, Stop::new(id, keys.with_chrome_key(true)).host());
|
||||
}
|
||||
|
||||
@@ -1079,6 +1109,7 @@ pub(crate) fn begin(ctx: &Context, tab_all_controls: bool, dialog_tab: TabReach)
|
||||
dialog_tab,
|
||||
frame: crate::runtime::egui::pass::frame_nr(ctx, viewport(ctx)),
|
||||
};
|
||||
let focused = input.focused;
|
||||
let (acts, announcements, host_focus) = with(ctx, |state| {
|
||||
state.awaited = None;
|
||||
let host_focus = state.record.host_focus;
|
||||
@@ -1090,23 +1121,81 @@ pub(crate) fn begin(ctx: &Context, tab_all_controls: bool, dialog_tab: TabReach)
|
||||
if !host_focus || !acts.is_empty() {
|
||||
egui_focus::clear_directional_focus(ctx);
|
||||
}
|
||||
hold_canvas_focus(ctx, focused);
|
||||
apply(ctx, acts);
|
||||
for text in announcements {
|
||||
crate::runtime::frame::announce(ctx, text);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes the focus `focused` off egui's press rule while it is on the app's document canvas, as the last pass declared
|
||||
/// it: whoever gave that focus, only `State::apply_press` decides what a press does to it. A canvas the app no longer
|
||||
/// declares is one of the app's own widgets, whose focus is egui's again.
|
||||
fn hold_canvas_focus(ctx: &Context, focused: Option<Id>) {
|
||||
let (held, left) = with(ctx, |state| {
|
||||
let held = focused.filter(|id| nav::declared_canvas(&state.last_stops, *id));
|
||||
let before = std::mem::replace(&mut state.held_canvas, held);
|
||||
(held, before.filter(|id| held.is_none() && focused == Some(*id)))
|
||||
});
|
||||
if let Some(id) = held {
|
||||
egui_focus::never_surrender(ctx, id);
|
||||
} else if let Some(id) = left {
|
||||
egui_focus::leave_to_egui(ctx, id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the text widget `widget` at the end of this pass, after the enclosing scopes have had its Escape: a scope
|
||||
/// deciding whether to close still finds the focused stop. No key is replayed and no other widget loses focus.
|
||||
pub(crate) fn surrender_after_scopes(ctx: &Context, widget: Id) {
|
||||
with(ctx, |state| state.surrender_after_scopes = Some(widget));
|
||||
}
|
||||
|
||||
/// Reports each canvas the running pass declared (`host_canvas`) whose id no focusable, enabled egui widget of the pass
|
||||
/// has. Read at the pass's end, since a canvas may be declared before it is drawn. A canvas hidden for one pass and still
|
||||
/// declared counts: egui drops its focus at the end of that pass. Only a visible widget counts as disabled: egui disables
|
||||
/// every widget of an invisible `Ui`, as the sizing pass of an `Area`, a `Window` or a `Grid` has.
|
||||
fn report_undrawn_canvases(ctx: &Context) {
|
||||
for id in with(ctx, |state| state.host_canvases.clone()) {
|
||||
let fault = match egui_focus::drawn_widget(ctx, id) {
|
||||
None => "no egui widget with the id was drawn",
|
||||
Some(widget) if !widget.sense.is_focusable() => "its widget's sense takes no focus",
|
||||
Some(widget) if widget.visible && !widget.enabled => "its widget is disabled, which takes no focus",
|
||||
Some(_) => continue,
|
||||
};
|
||||
if cfg!(debug_assertions) {
|
||||
log_once(fault.to_owned(), || log::warn!("`host_canvas` declared the canvas {id:?}: {fault}"));
|
||||
}
|
||||
if inspect::reports(ctx) {
|
||||
let subject = format!("{id:?}: {fault}");
|
||||
inspect::finding(ctx, inspect::Finding { rule: "canvas-without-widget", component: "host_canvas", subject });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves the focus the runtime gave an app's own widget (`State::app_widget`) to egui's rule, at the end of a pass that
|
||||
/// drew the widget with no pointer button down: until then the press, and the click its release makes, of the gesture
|
||||
/// that gave the focus never takes it back. The record of a focus that has moved, or that egui dropped
|
||||
/// because no pass drew the widget, ends here too.
|
||||
fn settle_given(ctx: &Context, app_widget: impl Fn(Id) -> bool) {
|
||||
let Some(id) = with(ctx, |state| state.given) else { return };
|
||||
if egui_focus::has_focus(ctx, id) {
|
||||
let drawn = egui_focus::drawn_widget(ctx, id).is_some();
|
||||
if !drawn || (app_widget(id) && crate::runtime::egui::input::button_down(ctx)) {
|
||||
return;
|
||||
}
|
||||
if app_widget(id) {
|
||||
egui_focus::leave_to_egui(ctx, id);
|
||||
}
|
||||
}
|
||||
with(ctx, |state| state.given = None);
|
||||
}
|
||||
|
||||
/// The end hook: applies the press's focus move, returns focus to the opener of a scope that went away,
|
||||
/// moves it off a stop that was not registered, and records what the next input hook reads.
|
||||
pub(crate) fn end(ctx: &Context) {
|
||||
let viewport = viewport(ctx);
|
||||
take_app_widgets(ctx, None);
|
||||
report_undrawn_canvases(ctx);
|
||||
// A field held a pass for the scope it sits in lets go now, unless that scope is going away with focus in the field:
|
||||
// nav::end below then gives the focus back to the scope's opener from where the field holds it.
|
||||
if let Some(widget) = with(ctx, |state| state.surrender_deferred.take())
|
||||
@@ -1144,6 +1233,7 @@ pub(crate) fn end(ctx: &Context) {
|
||||
let frame = crate::runtime::egui::pass::frame_nr(ctx, viewport);
|
||||
let acts = with(ctx, |state| nav::end(state, focused, on_app_widget, frame));
|
||||
apply(ctx, acts);
|
||||
settle_given(ctx, app_widget);
|
||||
// Escape over a captured framework press or drag cancels it (`frame::begin_pass`), whatever egui has focused.
|
||||
let captured = crate::runtime::pointer::press_captured(ctx) || crate::runtime::drag::running(ctx);
|
||||
let host_focus = !captured && with(ctx, |state| state.focus_now).is_some_and(app_widget);
|
||||
@@ -1188,6 +1278,14 @@ pub fn keyboard_in_menu(ctx: &Context) -> bool {
|
||||
focused_rec(ctx).is_some_and(|rec| menu_scope(ctx, rec.scope).is_some()) && with(ctx, |state| state.visible)
|
||||
}
|
||||
|
||||
/// Whether the focused stop took the focus when its scope opened (a menu's first row as the menu showed) and has kept
|
||||
/// it since: no key, press or request (an AccessKit `Focus`, the app's [`request`]) has moved it. A menu row reads it
|
||||
/// to tell a key that reached the row its menu's opening focused, which may not be meant for it, from a key on a row
|
||||
/// the user or assistive technology chose.
|
||||
pub fn focus_came_with_open(ctx: &Context) -> bool {
|
||||
focused_rec(ctx).is_some_and(|rec| origin(ctx, &rec) == Some(FocusOrigin::Open))
|
||||
}
|
||||
|
||||
/// The innermost menu scope around the component whose body is running: the menu a row being shown sits in.
|
||||
#[doc(hidden)]
|
||||
pub fn running_menu(ctx: &Context) -> Option<Id> {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Focus movement: Tab and F6, roving groups, initial focus, restore, programmatic requests and focus after
|
||||
//! removal. Every movement reads last pass's registrations and returns the egui changes to apply.
|
||||
|
||||
use super::{Act, BeginIn, FocusOrigin, FocusTarget, Initial, PickedIn, State, StopKey, StopRec, TabReach};
|
||||
use super::{Act, BeginIn, FocusOrigin, FocusTarget, Initial, PickedIn, State, Stop, StopKey, StopRec, TabReach};
|
||||
use crate::runtime::egui::focus as egui_focus;
|
||||
use crate::runtime::egui::memory::FastMap;
|
||||
use craft_behavior::nav::step;
|
||||
@@ -195,6 +195,7 @@ impl State {
|
||||
self.entered = false;
|
||||
self.asked = false;
|
||||
self.candidates_seen = 0;
|
||||
self.host_canvases.clear();
|
||||
}
|
||||
|
||||
/// The registrations of last pass, which Tab and the arrows move over.
|
||||
@@ -264,24 +265,13 @@ impl State {
|
||||
fn enter_stop(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec<Act> {
|
||||
self.note_entry(&rec);
|
||||
let stop = &rec.stop;
|
||||
let roving = stop.group.is_some();
|
||||
let keys = stop.keys;
|
||||
// An app's own widget (`Stop::host`) reads its Escape from egui, as a stop that claims it does: egui keeps its
|
||||
// focus on it.
|
||||
let escape = stop.host || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape);
|
||||
let filter = egui_focus::filter(
|
||||
keys.keep == super::KeepKeys::Tab,
|
||||
roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows),
|
||||
roving || keys.keep == super::KeepKeys::BlockArrows,
|
||||
escape,
|
||||
);
|
||||
let moved = self.focus_now != Some(stop.root) || self.focused.get(&stop.root) != Some(&stop.key());
|
||||
if moved {
|
||||
self.arrived = Some((self.frame, stop.key(), origin));
|
||||
}
|
||||
self.focused.insert(stop.root, stop.key());
|
||||
self.focus_now = Some(stop.root);
|
||||
vec![Act::Focus(stop.root, filter)]
|
||||
vec![focus_act(stop)]
|
||||
}
|
||||
|
||||
/// Focus moving to `rec` from outside a scope that traps nothing and restores focus (a layer that Tab reaches, such as
|
||||
@@ -744,6 +734,27 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `id` is the app's document canvas, as the pass that registered `stops` declared it (`host_canvas`).
|
||||
pub(super) fn declared_canvas(stops: &[StopRec], id: Id) -> bool {
|
||||
stops.iter().any(|rec| rec.stop.host && !rec.stop.automatic() && rec.stop.root == id)
|
||||
}
|
||||
|
||||
/// Focus on the egui widget of `stop`, with the key filter its keys ask for.
|
||||
pub(super) fn focus_act(stop: &Stop) -> Act {
|
||||
let roving = stop.group.is_some();
|
||||
let keys = stop.keys;
|
||||
// The app's canvas (`host_canvas`) reads its Escape from egui, as a stop that claims it does: egui keeps its focus
|
||||
// on it. Every other widget of the app's own keeps Escape by its own egui filter.
|
||||
let escape = (stop.host && !stop.automatic()) || keys.claims.iter().any(|chord| chord.key == craft_keymap::Key::Escape);
|
||||
let filter = egui_focus::filter(
|
||||
keys.keep == super::KeepKeys::Tab,
|
||||
roving || matches!(keys.keep, super::KeepKeys::InlineArrows | super::KeepKeys::BlockArrows),
|
||||
roving || keys.keep == super::KeepKeys::BlockArrows,
|
||||
escape,
|
||||
);
|
||||
Act::Focus(stop.root, filter)
|
||||
}
|
||||
|
||||
fn cycle(entries: &[Entry], current: Option<&StopRec>, top: Option<Id>, forward: bool) -> Option<usize> {
|
||||
if entries.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Focus on press (spec 8.3): the press is classified at the begin hook from last pass's shapes, and the
|
||||
//! classified focus move applies at the end hook.
|
||||
|
||||
use super::nav::declared_canvas;
|
||||
use super::{Act, State, StopKey};
|
||||
use crate::runtime::egui::focus as egui_focus;
|
||||
use crate::runtime::{pointer, sampler};
|
||||
@@ -148,10 +149,10 @@ impl State {
|
||||
self.stops.iter().chain(&self.last_stops).find(|rec| rec.stop.press_only && rec.stop.root == widget).cloned()
|
||||
}
|
||||
|
||||
/// The press's focus move at the end hook; `focused` is egui's focus now. The press moves the framework's focus
|
||||
/// only: when `focused` is an app's own widget (`on_app_widget`), egui's own surrender rule, by the app's
|
||||
/// `surrender_focus_on`, decides whether a press elsewhere takes it; a press a component takes still moves focus
|
||||
/// to the component.
|
||||
/// The press's focus move at the end hook; `focused` is egui's focus now. A press a component takes moves focus to
|
||||
/// the component, whatever has it. A press nothing takes ends the focus of a component only: it leaves the app's
|
||||
/// document canvas focused (`declared_canvas`), and when `focused` is an app's own widget (`on_app_widget`),
|
||||
/// egui's own surrender rule, by the app's `surrender_focus_on`, decides whether a press elsewhere takes it.
|
||||
pub(super) fn apply_press(&mut self, focused: Option<Id>, on_app_widget: bool) -> Vec<Act> {
|
||||
let Some(plan) = self.press.plan.take() else { return Vec::new() };
|
||||
match plan.kind {
|
||||
@@ -166,7 +167,12 @@ impl State {
|
||||
None if self.in_trapping_scope() => Vec::new(),
|
||||
None => focused.map(Act::Surrender).into_iter().collect(),
|
||||
},
|
||||
PressFocus::Unclaimed if focused == self.press.focus_at_begin && !on_app_widget && !self.in_trapping_scope() => {
|
||||
PressFocus::Unclaimed
|
||||
if focused == self.press.focus_at_begin
|
||||
&& !on_app_widget
|
||||
&& !focused.is_some_and(|id| declared_canvas(&self.stops, id))
|
||||
&& !self.in_trapping_scope() =>
|
||||
{
|
||||
focused.map(Act::Surrender).into_iter().collect()
|
||||
}
|
||||
_ => Vec::new(),
|
||||
|
||||
@@ -208,13 +208,17 @@ impl Group {
|
||||
|
||||
/// The innermost open `KeepAnchor` layer opened from the stop `opener`, the collection the layer names for its
|
||||
/// opener's list keys (`FocusPolicy::list`) and the layer's policy. `None` while no such layer is open, or it names no
|
||||
/// collection or one that registered no stop in the last pass (a list not shown leaves the keys with the opener).
|
||||
/// collection or one that registered no stop in the last pass (a list not shown leaves the keys with the opener). A
|
||||
/// layer playing its exit fade is closed: the opener keeps its keys, so an Enter right after Escape opens the list
|
||||
/// again instead of activating the row of the list that is leaving.
|
||||
pub(crate) fn dropdown_target(ctx: &Context, opener: StopKey) -> Option<(Id, Id, FocusPolicy)> {
|
||||
with(ctx, |state| {
|
||||
let layer =
|
||||
*state.last_scope_order.iter().rev().find(|id| {
|
||||
state.last_scopes.get(*id).is_some_and(|scope| scope.policy.initial == Initial::KeepAnchor && scope.opener == Some(opener))
|
||||
})?;
|
||||
let layer = *state.last_scope_order.iter().rev().find(|id| {
|
||||
state
|
||||
.last_scopes
|
||||
.get(*id)
|
||||
.is_some_and(|scope| scope.policy.initial == Initial::KeepAnchor && !scope.closing && scope.opener == Some(opener))
|
||||
})?;
|
||||
let policy = state.last_scopes.get(&layer)?.policy;
|
||||
let shown = |list: &Id| state.last_stops.iter().any(|rec| rec.stop.id == *list);
|
||||
policy.list.filter(shown).map(|list| (layer, list, policy))
|
||||
|
||||
@@ -871,6 +871,8 @@ pub(crate) fn end_pass(ui: &mut Ui) {
|
||||
paint_frame_layers(&ctx);
|
||||
}
|
||||
toast::end_pass(&ctx);
|
||||
// Every taker of the pass has run, and the layers and the focus are the pass's still.
|
||||
keys::hand_on_cancel(&ctx);
|
||||
overlay::end_pass(&ctx);
|
||||
focus::end(&ctx);
|
||||
let sweeps: Vec<fn(&Context)> = pass_state::with::<FrameState, _>(&ctx, |state| state.sweeps.values().copied().collect());
|
||||
|
||||
@@ -65,9 +65,14 @@ pub(crate) fn steps_of(ctx: &Context, id: Id) -> Vec<&'static str> {
|
||||
pass_state::with::<Log, _>(ctx, |log| log.steps.get(&id).cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Whether a finding reported now is kept.
|
||||
pub(crate) fn reports(ctx: &Context) -> bool {
|
||||
fixture_frame() || recording(ctx)
|
||||
}
|
||||
|
||||
/// Reports a finding.
|
||||
pub(crate) fn finding(ctx: &Context, finding: Finding) {
|
||||
if !fixture_frame() && !recording(ctx) {
|
||||
if !reports(ctx) {
|
||||
return;
|
||||
}
|
||||
pass_state::with::<Log, _>(ctx, |log| {
|
||||
@@ -86,7 +91,7 @@ pub(crate) fn findings(ctx: &Context) -> Vec<Finding> {
|
||||
/// Records that the canvas control `type_name` showed in this pass, so the canvas-control cases can check that a
|
||||
/// press away from its parts reaches the tool.
|
||||
pub(crate) fn canvas_control(ctx: &Context, type_name: &'static str) {
|
||||
if !fixture_frame() && !recording(ctx) {
|
||||
if !reports(ctx) {
|
||||
return;
|
||||
}
|
||||
pass_state::with::<Log, _>(ctx, |log| {
|
||||
|
||||
@@ -42,8 +42,8 @@ pub use intents::settle;
|
||||
#[doc(hidden)]
|
||||
pub use intents::take_submit;
|
||||
pub(crate) use intents::{
|
||||
Lent, context_part, context_request, context_requests, give_back, lend, request_context, route_whole_reset, scope_escape, take_cancel,
|
||||
take_every_escape, take_window_cancel,
|
||||
Lent, context_part, context_request, context_requests, give_back, hand_on_cancel, lend, request_context, route_whole_reset, scope_escape,
|
||||
take_cancel, take_every_escape, take_window_cancel,
|
||||
};
|
||||
pub use intents::{with_canvas_window_intents, with_window_intents};
|
||||
pub(crate) use nodes::{redirect_node, register_expanded, register_node};
|
||||
@@ -337,6 +337,9 @@ pub(crate) struct Stage {
|
||||
held_over: Vec<Key>,
|
||||
/// The modifiers of the last Escape of the pass that became a `Cancel`.
|
||||
escape_mods: Option<Mods>,
|
||||
/// The Escapes that windows opened from this one handed on (`intents::hand_on_cancel`), by their modifiers: the next
|
||||
/// pass's `Cancel`s.
|
||||
handed_cancels: Vec<Mods>,
|
||||
/// How many lent keys session members have taken (`lend`), counted over the viewport's life.
|
||||
lent_taken: u64,
|
||||
/// The pane moves that menu, palette or automation fires of `NavCommand` asked for: `true` is forward.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The intents routed to a component and what it leaves untaken: Submit, Cancel, Escape and context requests.
|
||||
|
||||
use super::route::push;
|
||||
use super::{Nudge, Source, Stage, current};
|
||||
use super::{Nudge, Source, Stage, current, with};
|
||||
use crate::runtime::focus::{self};
|
||||
use craft_behavior::focus::{EscapeFacts, EscapeStep, escape_step};
|
||||
use craft_behavior::{AccessRequest, CancelRule, EditCommand, EditorInput, Intent, MoveMods, NavMove, OwnerClass, PartRef};
|
||||
@@ -442,6 +442,28 @@ pub(crate) fn take_window_cancel(ctx: &Context) -> bool {
|
||||
with_canvas_window_intents(ctx, false, |window| window.take(Intent::Cancel))
|
||||
}
|
||||
|
||||
/// The end hook's hand-on: an Escape that nothing in the running window took, not even a reader of its intents, is the
|
||||
/// Cancel of the window it was opened from, where its spec says so (`WindowSpec::hands_on_cancel`). That window reads it
|
||||
/// in its next pass, which is requested. A popup or a modal open in the running window keeps the Escapes it leaves.
|
||||
pub(crate) fn hand_on_cancel(ctx: &Context) {
|
||||
let Some(opener) = crate::runtime::windows::cancel_to(ctx) else { return };
|
||||
if crate::runtime::overlay::popup_or_modal_open(ctx) {
|
||||
return;
|
||||
}
|
||||
let mut left = 0;
|
||||
with_window_intents(ctx, false, |window| {
|
||||
while window.take(Intent::Cancel) {
|
||||
left += 1;
|
||||
}
|
||||
left > 0
|
||||
});
|
||||
if left > 0 {
|
||||
let mods = current(ctx, |stage| stage.escape_mods).unwrap_or(Mods::NONE);
|
||||
with(ctx, opener, |stage| stage.handed_cancels.extend(std::iter::repeat_n(mods, left)));
|
||||
crate::runtime::egui::repaint::request_of(ctx, opener);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes back what a component left untaken, so a scope's `Submit` and `Cancel` rules see it.
|
||||
#[doc(hidden)]
|
||||
pub fn settle(ctx: &Context, id: Option<Id>, intents: &Intents) {
|
||||
|
||||
@@ -209,6 +209,17 @@ pub(crate) fn begin(ctx: &Context, press_captured: bool) -> EscapeRouting {
|
||||
push(&mut routed, focused, Intent::Cancel, false);
|
||||
cancel_mods = Some(escape.mods);
|
||||
}
|
||||
// The Escapes the windows opened from this one handed on are the window's. A modal that opened meanwhile blocks the
|
||||
// window they were pressed in, so they reach nothing.
|
||||
let handed = current(ctx, |stage| std::mem::take(&mut stage.handed_cancels));
|
||||
if !handed.is_empty() && overlay::app_modal_viewport(ctx).is_none() {
|
||||
for mods in handed {
|
||||
push(&mut routed, None, Intent::Cancel, false);
|
||||
cancel_mods = Some(mods);
|
||||
}
|
||||
// A view that reads what is sent (`Input::Sent`) runs for them as for a key of the window's own.
|
||||
current(ctx, |stage| stage.sent += 1);
|
||||
}
|
||||
// A text opener's list keys arrive as claimed chords, withheld from its text part: they go to the list. The chords
|
||||
// fired commands stood for go to the owners of their claims.
|
||||
let mut claimed = fired_claims;
|
||||
|
||||
@@ -111,8 +111,19 @@ struct LeastRuns {
|
||||
runs: Vec<(Id, u32)>,
|
||||
}
|
||||
|
||||
/// Runs `f` as a measuring run. Nested calls are fine.
|
||||
/// Runs `f` as a measuring run, for code outside the framework that measures before it shows (an app that sizes a rect
|
||||
/// by `Show::measure_in` and then shows the component with `show_at`). Nested calls are fine.
|
||||
///
|
||||
/// What `f` measures is its own: it joins no kept transcript of the body around it, in that body's measuring run or in
|
||||
/// its real run alike. Otherwise the body's measuring run would keep it as one of the body's components while the
|
||||
/// real run, measuring outside every transcript, never asks it, and the body would read as changed every frame.
|
||||
pub fn run<R>(ctx: &Context, f: impl FnOnce() -> R) -> R {
|
||||
measuring(ctx, || super::layout_memory::boundary(ctx, true, f))
|
||||
}
|
||||
|
||||
/// Runs `f` as a measuring run whose measures join the transcript of the body whose measuring run is open around it:
|
||||
/// the framework's own measuring runs. Nested calls are fine.
|
||||
pub(crate) fn measuring<R>(ctx: &Context, f: impl FnOnce() -> R) -> R {
|
||||
/// Restores the depth when the run ends, by a panic too: a context used after a caught panic is not measuring.
|
||||
struct Open<'a>(&'a Context, u32);
|
||||
impl Drop for Open<'_> {
|
||||
|
||||
@@ -449,6 +449,12 @@ pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a popup or a modal of the running viewport was shown last frame: the layers whose rank takes keys, which the
|
||||
/// window of a dock is not.
|
||||
pub(crate) fn popup_or_modal_open(ctx: &Context) -> bool {
|
||||
with_pass(ctx, |pass| pass.last.iter().any(|entry| !entry.exiting && entry.rank.takes_keys()))
|
||||
}
|
||||
|
||||
/// The layer that receives Cancel: the newest member of the topmost family that takes keys.
|
||||
pub fn top(ctx: &Context) -> Option<Id> {
|
||||
crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays);
|
||||
|
||||
@@ -1233,18 +1233,24 @@ pub fn shapes_at(ctx: &Context, at: Pos2) -> Vec<(Id, Option<PartRef>)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of `owner` holding a press in this viewport that was open when the pass began: in the pass that ends the
|
||||
/// press too, and in none after it.
|
||||
pub fn pressed_part(ctx: &Context, owner: Id) -> Option<PartRef> {
|
||||
PerViewport::<Shapes>::with(ctx, pass::current_viewport(ctx), |record| {
|
||||
record.pressed_parts.iter().find_map(|(id, part)| (*id == owner).then_some(*part))
|
||||
})
|
||||
}
|
||||
|
||||
/// The part of `owner` holding the pointer's hover or an open press in this viewport.
|
||||
///
|
||||
/// An open press keeps its part while the pointer moves away. A press open at the start of the pass keeps its part
|
||||
/// for that whole pass, so a child can still declare it after an enclosing arena has processed the release.
|
||||
pub fn active_part(ctx: &Context, owner: Id) -> Option<PartRef> {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
let pressed =
|
||||
PerViewport::<Shapes>::with(ctx, viewport, |record| record.pressed_parts.iter().find_map(|(id, part)| (*id == owner).then_some(*part)));
|
||||
let pressed = pressed_part(ctx, owner);
|
||||
if pressed.is_some() {
|
||||
return pressed;
|
||||
}
|
||||
with_hover(ctx, viewport, |under, captured| {
|
||||
with_hover(ctx, pass::current_viewport(ctx), |under, captured| {
|
||||
if captured {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -161,6 +161,9 @@ pub(crate) struct Record {
|
||||
min_size: Option<Vec2>,
|
||||
/// For a popup window ([`show_popup`]): the window its layer was opened from, while the layer shows.
|
||||
opener: Option<ViewportId>,
|
||||
/// The window an Escape nothing in this one takes goes to: the one it was opened from, where its spec says so
|
||||
/// (`WindowSpec::hands_on_cancel`).
|
||||
cancel_to: Option<ViewportId>,
|
||||
}
|
||||
|
||||
/// The raise of the window holding an app-modal layer above the palettes the modal lowered. The raise goes out in the
|
||||
@@ -217,6 +220,11 @@ pub(crate) fn os_resizes(ctx: &Context, viewport: ViewportId) -> bool {
|
||||
chrome == WindowChrome::Inset && PerViewport::<Record>::with(ctx, viewport, |record| record.resizable != Some(false))
|
||||
}
|
||||
|
||||
/// The window an Escape nothing in the running viewport's window takes goes to (`WindowSpec::hands_on_cancel`).
|
||||
pub(crate) fn cancel_to(ctx: &Context) -> Option<ViewportId> {
|
||||
PerViewport::<Record>::with_existing(ctx, pass::current_viewport(ctx), |record| record.cancel_to).flatten()
|
||||
}
|
||||
|
||||
/// Whether the app runs the move of `viewport`'s window (`Overlay::moved_by_app`).
|
||||
pub(crate) fn app_moves(ctx: &Context, viewport: ViewportId) -> bool {
|
||||
PerViewport::<Record>::with(ctx, viewport, |record| record.moved_by_app)
|
||||
|
||||
@@ -89,6 +89,9 @@ pub struct WindowSpec {
|
||||
pub takes_focus: bool,
|
||||
/// Whether pointer input passes through the window to the window below it.
|
||||
pub passes_pointer: bool,
|
||||
/// Whether an Escape nothing in the window takes is the Cancel of the window it was opened from (a dock window's):
|
||||
/// no component, layer, capture or app widget of the window, and no reader of its intents.
|
||||
pub hands_on_cancel: bool,
|
||||
}
|
||||
|
||||
impl WindowSpec {
|
||||
@@ -121,6 +124,7 @@ impl WindowSpec {
|
||||
shown_after_first_paint: false,
|
||||
takes_focus: true,
|
||||
passes_pointer: false,
|
||||
hands_on_cancel: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,6 +188,13 @@ impl WindowSpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether an Escape nothing in the window takes is the Cancel of the window it was opened from.
|
||||
#[must_use]
|
||||
pub fn hands_on_cancel(mut self, hands_on_cancel: bool) -> Self {
|
||||
self.hands_on_cancel = hands_on_cancel;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets whether the window opens hidden and appears after its first paint, so a window that shows a capture or
|
||||
/// other content that must be ready does not flash an empty frame.
|
||||
#[must_use]
|
||||
|
||||
@@ -54,6 +54,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
keep_placed(ctx, viewport, pos, size.filter(|_| open.follows_size));
|
||||
}
|
||||
let spec = open.spec;
|
||||
let cancel_to = spec.hands_on_cancel.then(|| crate::runtime::egui::pass::current_viewport(ctx));
|
||||
let state = shared(ctx, |shared| shared.app);
|
||||
let os = os_of(ctx);
|
||||
let (chrome, captions) = frame_of_spec(ctx, spec);
|
||||
@@ -64,6 +65,7 @@ pub(crate) fn show_viewport(ctx: &Context, open: &ViewportOpen<'_>, mut body: im
|
||||
record.resizable = Some(open.resizable);
|
||||
record.min_size = open.limits.0;
|
||||
record.moved_by_app = open.moved_by_app;
|
||||
record.cancel_to = cancel_to;
|
||||
record.awaiting_first_paint |= spec.shown_after_first_paint && record.facts.is_none();
|
||||
if record.title.as_deref() != Some(open.title) {
|
||||
record.title = Some(open.title.to_owned());
|
||||
|
||||
@@ -289,6 +289,19 @@ impl<'a> StyleCx<'a> {
|
||||
self.color(craft_theme::ensure_contrast(start, fill, craft_theme::text_contrast_min(self.contrast())))
|
||||
}
|
||||
|
||||
/// The ink for icons and non-text on a user colour: the higher-contrast of `text.normal` and `text.on_strong` on the fill,
|
||||
/// pushed to the non-text contrast it needs (3.0 in standard, 4.5 in high contrast).
|
||||
pub fn icon_ink_on(&self, fill: DataColor) -> StyleColor {
|
||||
let fill = Rgba::from(fill.0);
|
||||
let text = &self.tokens.color.text;
|
||||
let start = if craft_theme::contrast_ratio(text.on_strong, fill) > craft_theme::contrast_ratio(text.normal, fill) {
|
||||
text.on_strong
|
||||
} else {
|
||||
text.normal
|
||||
};
|
||||
self.color(craft_theme::ensure_contrast(start, fill, craft_theme::non_text_contrast_min(self.contrast())))
|
||||
}
|
||||
|
||||
/// The ink of a glyph or label in the data colour `color` on the surface `on`, pushed to the contrast the text
|
||||
/// needs: the inverse of [`ink_on`](Self::ink_on).
|
||||
pub fn ink_of(&self, color: DataColor, on: Rgba) -> StyleColor {
|
||||
|
||||
@@ -39,6 +39,12 @@ impl DataColor {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color32> for DataColor {
|
||||
fn from(color: Color32) -> Self {
|
||||
DataColor(color)
|
||||
}
|
||||
}
|
||||
|
||||
/// The surface a container or part sits on, which picks fill, edge, shadow and ink.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -12,6 +12,7 @@ use crate::runtime::frame::{ChromeToggle, take_output};
|
||||
use crate::runtime::ime;
|
||||
use crate::runtime::keys::with_window_intents;
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
use crate::testing::contract::findings;
|
||||
use crate::testing::focus::{Stop, egui_focused, key_release, named_id, pop_scope, push_scope, register_stop, widget};
|
||||
use crate::testing::input::{key_press, key_reached, slop};
|
||||
use crate::testing::pointer::{self, moved, press, release};
|
||||
@@ -750,6 +751,277 @@ fn an_app_field_that_keeps_tab_types_it_and_a_single_line_field_tabs_on() {
|
||||
assert_eq!(texts.borrow().1, "", "and types nothing");
|
||||
}
|
||||
|
||||
/// How the focus of the app's own widget `id` in `mixed_window`, given by Tab (`tab`) or by the app's own egui request,
|
||||
/// ends.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct FocusEnds {
|
||||
/// egui's focus after the press and after the release of a click elsewhere.
|
||||
click: (Option<Id>, Option<Id>),
|
||||
/// Whether the widget lost focus by egui's word, in each pass from the press on.
|
||||
lost: Vec<bool>,
|
||||
/// egui's focus after Escape, the focus given again.
|
||||
escape: Option<Id>,
|
||||
/// egui's focus after a click elsewhere while the app's option is never to surrender it, the focus given again.
|
||||
kept: Option<Id>,
|
||||
}
|
||||
|
||||
fn focus_ends(id: Id, tab: bool) -> FocusEnds {
|
||||
let lost = Rc::new(RefCell::new(Vec::new()));
|
||||
let losses = Rc::clone(&lost);
|
||||
let mut base = mixed_window();
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
base(ui);
|
||||
losses.borrow_mut().push(ui.ctx().read_response(id).is_some_and(|response| response.lost_focus()));
|
||||
};
|
||||
let give = |frames: &mut Frames, show: &mut dyn FnMut(&mut Ui)| {
|
||||
for _ in 0..MIXED.len() {
|
||||
if tab && egui_focused(&frames.ctx) != Some(id) {
|
||||
tab_with(frames, &mut &mut *show, Modifiers::NONE);
|
||||
}
|
||||
}
|
||||
if !tab {
|
||||
fixture::host_focus(&frames.ctx, id);
|
||||
}
|
||||
frames.idle(2, &mut *show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(id), "the widget has the focus");
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
let empty = Pos2::new(300.0, 450.0);
|
||||
give(&mut frames, &mut show);
|
||||
lost.borrow_mut().clear();
|
||||
let click = click_focus(&mut frames, &mut show, empty);
|
||||
frames.idle(2, &mut show);
|
||||
let lost = lost.take();
|
||||
give(&mut frames, &mut show);
|
||||
press_key(&mut frames, &mut show, Key::Escape);
|
||||
let escape = egui_focused(&frames.ctx);
|
||||
fixture::set_app_surrender(&frames.ctx, true);
|
||||
give(&mut frames, &mut show);
|
||||
let (_, kept) = click_focus(&mut frames, &mut show, empty);
|
||||
FocusEnds { click, lost, escape, kept }
|
||||
}
|
||||
|
||||
/// Focus that Tab gave an app's own button or text field ends as the focus the app's own request gave it: a click
|
||||
/// elsewhere and Escape release it once, by egui's rule and the app's surrender option.
|
||||
#[trial]
|
||||
fn tab_focus_on_an_app_widget_ends_as_the_focus_the_app_gave_it() {
|
||||
for id in ["app first", "app field"].map(named_id) {
|
||||
let ends = focus_ends(id, true);
|
||||
assert_eq!(ends.click, (Some(id), None), "a click elsewhere releases it, at the release by egui's option");
|
||||
assert!(ends.lost.contains(&true), "and the widget sees its focus lost");
|
||||
assert_eq!(ends.escape, None, "Escape releases it");
|
||||
assert_eq!(ends.kept, Some(id), "the app's option keeps it over a click elsewhere");
|
||||
assert_eq!(ends, focus_ends(id, false), "as the focus the app gave it does, seen lost in the same passes");
|
||||
}
|
||||
}
|
||||
|
||||
/// A component reached with Tab keeps its focus over Escape and drops it at a press no component takes.
|
||||
#[trial]
|
||||
fn tab_focus_on_a_component_ends_by_the_framework_s_press_rule() {
|
||||
let mut show = mixed_window();
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
tab_with(&mut frames, &mut show, Modifiers::NONE);
|
||||
let one = Some(named_id("framework one"));
|
||||
assert_eq!(tab_with(&mut frames, &mut show, Modifiers::NONE), one);
|
||||
press_key(&mut frames, &mut show, Key::Escape);
|
||||
assert_eq!(egui_focused(&frames.ctx), one, "Escape leaves the component's focus");
|
||||
let empty = Pos2::new(300.0, 450.0);
|
||||
assert_eq!(click_focus(&mut frames, &mut show, empty).0, None, "a press no component takes drops it at the press");
|
||||
}
|
||||
|
||||
/// A press on a component that takes focus moves it there from the app's field that Tab focused, and the field sees its
|
||||
/// focus lost once.
|
||||
#[trial]
|
||||
fn a_press_on_a_component_takes_the_focus_tab_gave_an_app_field() {
|
||||
let field = named_id("app field");
|
||||
let rect = Rect::from_min_size(Pos2::new(300.0, 400.0), egui::vec2(160.0, 40.0));
|
||||
let lost = Rc::new(Cell::new(0));
|
||||
let losses = Rc::clone(&lost);
|
||||
let mut base = mixed_window();
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
base(ui);
|
||||
sensing::show(ui, &[ProbeRoot::new("probe", rect, Sense::CLICK | Sense::TAKE_FOCUS)]);
|
||||
register_stop(ui.ctx(), Stop::new(ProbeRoot::id("probe"), KeyUse::of(Input::Pointer)));
|
||||
losses.set(losses.get() + usize::from(ui.ctx().read_response(field).is_some_and(|response| response.lost_focus())));
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
for _ in 0..3 {
|
||||
tab_with(&mut frames, &mut show, Modifiers::NONE);
|
||||
}
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(field));
|
||||
lost.set(0);
|
||||
let probe = Some(ProbeRoot::id("probe"));
|
||||
assert_eq!(click_focus(&mut frames, &mut show, rect.center()), (probe, probe), "the press moves the focus to the component");
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(lost.get(), 1, "the field sees its focus lost once");
|
||||
}
|
||||
|
||||
/// What gives an app's field the focus during a click elsewhere.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum GivenAt {
|
||||
/// The press closes a popup, which gives the focus back to the field it opened from.
|
||||
PopupPress,
|
||||
/// The app's request at the press.
|
||||
Press,
|
||||
/// The app's request at the release, in a pass that draws the field later.
|
||||
Release,
|
||||
}
|
||||
|
||||
/// Focus the runtime gives an app's own widget during a click elsewhere stands: neither the press nor its release takes
|
||||
/// it back. The next click elsewhere does, by egui's rule.
|
||||
#[trial]
|
||||
fn a_click_that_gives_an_app_field_the_focus_does_not_take_it_back() {
|
||||
for at in [GivenAt::PopupPress, GivenAt::Press, GivenAt::Release] {
|
||||
let field = named_id("app field");
|
||||
let (asking, popup) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
|
||||
let (ask, open) = (Rc::clone(&asking), Rc::clone(&popup));
|
||||
let mut base = mixed_window();
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
let (pressed, clicked) = ui.input(|input| (input.pointer.primary_pressed(), input.pointer.any_click()));
|
||||
let now = if matches!(at, GivenAt::Release) { clicked } else { pressed };
|
||||
if now && ask.take() {
|
||||
match at {
|
||||
GivenAt::PopupPress => open.set(false),
|
||||
GivenAt::Press | GivenAt::Release => _ = request(ui.ctx(), FocusTarget::Id(field)),
|
||||
}
|
||||
}
|
||||
base(ui);
|
||||
if open.get() {
|
||||
push_scope(ui.ctx(), named_id("popup"), FocusPolicy::POPUP, None);
|
||||
widget(ui, named_id("popup button"));
|
||||
register_stop(ui.ctx(), Stop::new(named_id("popup button"), KeyUse::of(Input::Pointer)));
|
||||
pop_scope(ui.ctx());
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
if matches!(at, GivenAt::PopupPress) {
|
||||
fixture::host_focus(&frames.ctx, field);
|
||||
frames.idle(1, &mut show);
|
||||
popup.set(true);
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(named_id("popup button")), "the popup takes the focus");
|
||||
}
|
||||
asking.set(true);
|
||||
let empty = Pos2::new(300.0, 450.0);
|
||||
assert_eq!(click_focus(&mut frames, &mut show, empty).1, Some(field), "{at:?}: the focus stands over the release");
|
||||
assert_eq!(click_focus(&mut frames, &mut show, empty).1, None, "{at:?}: the next click elsewhere takes it");
|
||||
}
|
||||
}
|
||||
|
||||
/// A canvas declared after a component registered behind it is first taken as one of the app's widgets: focus the runtime
|
||||
/// gave it there follows the canvas's rules, which keep it over Escape.
|
||||
#[trial]
|
||||
fn focus_given_to_a_canvas_before_its_declaration_is_the_canvas_s() {
|
||||
let canvas = named_id("host canvas");
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
fixture::host_button(ui, canvas, Rect::from_min_size(Pos2::new(100.0, 300.0), egui::vec2(80.0, 30.0)));
|
||||
widget(ui, named_id("button"));
|
||||
register_stop(ui.ctx(), Stop::new(named_id("button"), KeyUse::of(Input::Pointer)));
|
||||
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.frame(Vec::new(), |_| {});
|
||||
request(&frames.ctx, FocusTarget::Id(canvas));
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(canvas));
|
||||
press_key(&mut frames, &mut show, Key::Escape);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(canvas), "egui keeps the focus on the canvas over its Escape");
|
||||
}
|
||||
|
||||
/// A window of the app's own document canvas, declared while `declared` holds, beside the app's field of `host_window`, a
|
||||
/// button and an area of the app's own that take no focus, and the component `probe`, which takes it.
|
||||
struct CanvasWindow {
|
||||
declared: Rc<Cell<bool>>,
|
||||
host: Rc<RefCell<Host>>,
|
||||
/// egui's focus in each pass, at its start and after the canvas was drawn.
|
||||
in_pass: Rc<RefCell<Vec<Option<Id>>>>,
|
||||
}
|
||||
|
||||
impl CanvasWindow {
|
||||
const BUTTON: Rect = Rect { min: Pos2::new(300.0, 100.0), max: Pos2::new(380.0, 130.0) };
|
||||
const AREA: Rect = Rect { min: Pos2::new(300.0, 200.0), max: Pos2::new(380.0, 230.0) };
|
||||
const PROBE: Rect = Rect { min: Pos2::new(300.0, 300.0), max: Pos2::new(380.0, 330.0) };
|
||||
const CANVAS: Rect = Rect { min: Pos2::new(100.0, 400.0), max: Pos2::new(180.0, 430.0) };
|
||||
const EMPTY: Pos2 = Pos2::new(500.0, 450.0);
|
||||
|
||||
fn new() -> (Self, impl FnMut(&mut Ui)) {
|
||||
let (host, mut base) = host_window();
|
||||
let window = Self { declared: Rc::new(Cell::new(true)), host, in_pass: Rc::default() };
|
||||
let (declared, in_pass) = (Rc::clone(&window.declared), Rc::clone(&window.in_pass));
|
||||
let show = move |ui: &mut Ui| {
|
||||
in_pass.borrow_mut().push(egui_focused(ui.ctx()));
|
||||
base(ui);
|
||||
fixture::host_button(ui, named_id("app button"), Self::BUTTON);
|
||||
fixture::host_unfocusable_area(ui, named_id("app area"), Self::AREA);
|
||||
sensing::show(ui, &[ProbeRoot::new("probe", Self::PROBE, Sense::CLICK | Sense::TAKE_FOCUS)]);
|
||||
register_stop(ui.ctx(), Stop::new(ProbeRoot::id("probe"), KeyUse::of(Input::Pointer)));
|
||||
fixture::host_button(ui, Self::canvas(), Self::CANVAS);
|
||||
if declared.get() {
|
||||
host_canvas(ui.ctx(), Self::canvas(), KeyUse::CANVAS);
|
||||
}
|
||||
in_pass.borrow_mut().push(egui_focused(ui.ctx()));
|
||||
};
|
||||
(window, show)
|
||||
}
|
||||
|
||||
fn canvas() -> Id {
|
||||
named_id("host canvas")
|
||||
}
|
||||
|
||||
/// Gives the canvas the focus, by the app's own request or the framework's.
|
||||
fn focus(frames: &mut Frames, show: &mut impl FnMut(&mut Ui), app: bool) {
|
||||
if app {
|
||||
fixture::host_focus(&frames.ctx, Self::canvas());
|
||||
} else {
|
||||
request(&frames.ctx, FocusTarget::Id(Self::canvas()));
|
||||
}
|
||||
frames.idle(2, &mut *show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(Self::canvas()));
|
||||
}
|
||||
}
|
||||
|
||||
/// A click that nothing takes leaves the app's document canvas focused in every pass, whoever gave it the focus: by the
|
||||
/// framework's press rule and by egui's. A canvas the app no longer declares follows egui's rule.
|
||||
#[trial]
|
||||
fn a_click_nothing_takes_leaves_the_app_s_canvas_focused() {
|
||||
for app in [true, false] {
|
||||
let (window, mut show) = CanvasWindow::new();
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
CanvasWindow::focus(&mut frames, &mut show, app);
|
||||
window.in_pass.take();
|
||||
for at in [CanvasWindow::BUTTON.center(), CanvasWindow::AREA.center(), CanvasWindow::EMPTY] {
|
||||
click_focus(&mut frames, &mut show, at);
|
||||
let passes = window.in_pass.take();
|
||||
assert!(!passes.is_empty() && passes.iter().all(|focused| *focused == Some(CanvasWindow::canvas())), "app {app}, {at:?}: {passes:?}");
|
||||
}
|
||||
window.declared.set(false);
|
||||
frames.idle(2, &mut show);
|
||||
let (pressed, clicked) = click_focus(&mut frames, &mut show, CanvasWindow::EMPTY);
|
||||
assert_eq!((pressed, clicked), (Some(CanvasWindow::canvas()), None), "app {app}: an app's plain widget loses it at the click");
|
||||
}
|
||||
}
|
||||
|
||||
/// A press on a component that takes focus, or on the app's own field, takes it from the app's document canvas.
|
||||
#[trial]
|
||||
fn a_press_that_takes_focus_takes_it_from_the_app_s_canvas() {
|
||||
for app in [true, false] {
|
||||
let (window, mut show) = CanvasWindow::new();
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
CanvasWindow::focus(&mut frames, &mut show, app);
|
||||
let probe = Some(ProbeRoot::id("probe"));
|
||||
assert_eq!(click_focus(&mut frames, &mut show, CanvasWindow::PROBE.center()), (probe, probe), "app {app}: the component");
|
||||
CanvasWindow::focus(&mut frames, &mut show, app);
|
||||
let at = window.host.borrow().rect.center();
|
||||
assert_eq!(click_focus(&mut frames, &mut show, at).1, Some(field()), "app {app}: the app's field");
|
||||
}
|
||||
}
|
||||
|
||||
/// Where Tab reaches only text fields (the Mac's default), it reaches the app's own text field and skips the app's
|
||||
/// own buttons, as it skips the framework's.
|
||||
#[trial]
|
||||
@@ -998,6 +1270,100 @@ fn a_host_canvas_marks_the_window_and_tab_toggles_its_panels() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Focus that Tab moves to the app's canvas in a layer returns to the stop it came from when the layer goes away, also
|
||||
/// when the group the canvas sits in first appears in the pass of the Tab: declaring the canvas enters nothing.
|
||||
#[trial]
|
||||
fn declaring_a_focused_canvas_keeps_the_opener_of_its_layer() {
|
||||
let (opener, canvas) = (named_id("opener"), named_id("host canvas"));
|
||||
let layer = Rc::new(Cell::new(true));
|
||||
let grouped = Rc::new(Cell::new(false));
|
||||
let (shown, group) = (Rc::clone(&layer), Rc::clone(&grouped));
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
widget(ui, opener);
|
||||
register_stop(ui.ctx(), Stop::new(opener, KeyUse::of(Input::Pointer)));
|
||||
if !shown.get() {
|
||||
return;
|
||||
}
|
||||
push_scope(ui.ctx(), named_id("layer"), FocusPolicy::TAB_LAYER, None);
|
||||
if group.get() {
|
||||
push_scope(ui.ctx(), named_id("group"), FocusPolicy::NONE, None);
|
||||
}
|
||||
widget(ui, canvas);
|
||||
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
|
||||
if group.get() {
|
||||
pop_scope(ui.ctx());
|
||||
}
|
||||
pop_scope(ui.ctx());
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
focus_stop(&mut frames, &mut show, opener);
|
||||
grouped.set(true);
|
||||
assert_eq!(tab_with(&mut frames, &mut show, Modifiers::NONE), Some(canvas), "Tab goes from the stop into the layer");
|
||||
layer.set(false);
|
||||
frames.idle(2, &mut show);
|
||||
assert_eq!(egui_focused(&frames.ctx), Some(opener), "the layer gives the focus back to the stop it came from");
|
||||
}
|
||||
|
||||
/// How an app's window shows the canvas of `host_canvas_findings`.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Shown {
|
||||
/// Neither declared nor drawn.
|
||||
Hidden,
|
||||
/// Declared, and drawn with a focusable widget that senses clicks or drags.
|
||||
Click,
|
||||
Drag,
|
||||
/// Declared, and drawn with a focusable widget in an egui window, whose first pass sizes it invisibly.
|
||||
Window,
|
||||
/// Declared, and drawn with a widget that senses drags and is not focusable.
|
||||
Unfocusable,
|
||||
/// Declared, and drawn in a disabled `Ui`.
|
||||
Disabled,
|
||||
/// Declared and not drawn.
|
||||
Undrawn,
|
||||
}
|
||||
|
||||
/// Whether the canvas holds egui focus after a Tab from nothing in a window that shows it as `shown`, declared before it
|
||||
/// is drawn, and the subjects of the findings on it.
|
||||
fn host_canvas_findings(shown: Shown) -> (bool, Vec<String>) {
|
||||
let canvas = named_id("host canvas");
|
||||
let mut show = move |ui: &mut Ui| {
|
||||
if !matches!(shown, Shown::Hidden) {
|
||||
host_canvas(ui.ctx(), canvas, KeyUse::CANVAS);
|
||||
}
|
||||
let rect = Rect::from_min_size(Pos2::new(100.0, 300.0), egui::vec2(80.0, 30.0));
|
||||
match shown {
|
||||
Shown::Hidden | Shown::Undrawn => {}
|
||||
Shown::Click => _ = fixture::host_button(ui, canvas, rect),
|
||||
Shown::Drag => _ = fixture::host_drag_area(ui, canvas, rect),
|
||||
Shown::Window => areas::host_egui_window(ui.ctx(), named_id("host window"), |ui| _ = widget(ui, canvas)),
|
||||
Shown::Unfocusable => fixture::host_unfocusable_area(ui, canvas, rect),
|
||||
Shown::Disabled => fixture::host_disabled_button(ui, canvas, rect),
|
||||
}
|
||||
};
|
||||
let mut frames = Frames::new();
|
||||
frames.idle(2, &mut show);
|
||||
press_key(&mut frames, &mut show, Key::Tab);
|
||||
frames.idle(2, &mut show);
|
||||
let found = findings(&frames.ctx).into_iter().filter(|finding| finding.rule == "canvas-without-widget");
|
||||
(egui_focused(&frames.ctx) == Some(canvas), found.map(|finding| finding.subject).collect())
|
||||
}
|
||||
|
||||
/// Guards the finding that tells an app its canvas stop takes Tab and loses the focus: `host_canvas` named an id that no
|
||||
/// focusable egui widget of the pass has.
|
||||
#[trial]
|
||||
fn a_host_canvas_no_focusable_widget_draws_is_a_finding() {
|
||||
for shown in [Shown::Click, Shown::Drag, Shown::Window] {
|
||||
assert_eq!(host_canvas_findings(shown), (true, Vec::new()), "{shown:?}: Tab stays at a canvas with a focusable widget");
|
||||
}
|
||||
assert_eq!(host_canvas_findings(Shown::Hidden).1, Vec::<String>::new(), "a hidden canvas makes no call");
|
||||
for (shown, says) in [(Shown::Undrawn, "no egui widget"), (Shown::Unfocusable, "sense"), (Shown::Disabled, "disabled")] {
|
||||
let (focused, found) = host_canvas_findings(shown);
|
||||
assert!(!focused, "{shown:?}: egui drops the focus Tab gave the canvas");
|
||||
assert!(matches!(found.as_slice(), [only] if only.contains(says)), "{shown:?}: {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// What `event` did with nothing focused in a window whose host declares its canvas with `keys`: whether the event
|
||||
/// reached egui's input, and the ids of the commands it fired.
|
||||
fn clipboard_with_canvas(keys: KeyUse, event: Event) -> (bool, Vec<String>) {
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn body(ui: &mut Ui, key: &'static str, layout: &BodyLayout, sizes: &[Vec2])
|
||||
let place = |ui: &mut Ui| sizes.iter().map(|size| place_in_flow(ui, *size)).collect::<Vec<_>>();
|
||||
let builder = egui::UiBuilder::new().max_rect(ui.available_rect_before_wrap()).sizing_pass().invisible();
|
||||
let env = crate::runtime::env::Env::of(ui);
|
||||
crate::runtime::measure::run(&ui.ctx().clone(), || ui.scope_builder(builder, |ui| run_body(ui, &env, id, layout, Vec2::ZERO, place)));
|
||||
crate::runtime::measure::measuring(&ui.ctx().clone(), || ui.scope_builder(builder, |ui| run_body(ui, &env, id, layout, Vec2::ZERO, place)));
|
||||
run_body(ui, &env, id, layout, Vec2::ZERO, place)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,15 @@
|
||||
//! move band is reported once.
|
||||
|
||||
use craft_behavior::{Cursor, CursorIcon};
|
||||
use craft_host::target::{ShellInfo, WindowChrome, WindowInfo, WindowKind};
|
||||
use craft_host::target::{Backend, Os, ShellInfo, WindowChrome, WindowInfo, WindowKind};
|
||||
use craft_ui::contract::overlay::Resize;
|
||||
use craft_ui::contract::{
|
||||
BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Props as _, Role, Show as _, ShowContainer as _, Sizing,
|
||||
BodyCx, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Mount, Overlay, Props as _, Role, Show as _,
|
||||
ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::runtime::InstallSpec;
|
||||
use craft_ui::runtime::focus::FocusPolicy;
|
||||
use craft_ui::runtime::windows::WindowSpec;
|
||||
use craft_ui::style::StyleCx;
|
||||
use craft_ui::testing::layout::allocate;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
@@ -17,8 +20,9 @@ use craft_ui::testing::trial;
|
||||
use craft_ui::testing::windows::FakeSystem;
|
||||
use craft_ui_test_kit::contract::{PlainStyle, Probe, Seen};
|
||||
use craft_ui_test_kit::windows::Windows;
|
||||
use craft_window::policy::{Desktop, DesktopKind, Runtime, TitleBarPref};
|
||||
use egui::viewport::ResizeDirection;
|
||||
use egui::{Event, Pos2, Rect, Response, Ui, Vec2, ViewportCommand, pos2, vec2};
|
||||
use egui::{Event, Pos2, Rect, Response, Ui, Vec2, ViewportCommand, ViewportInfo, pos2, vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -185,3 +189,32 @@ fn where_appkit_resizes_a_window_the_app_registers_no_grips_and_leaves_the_curso
|
||||
let cursor = craft_ui::runtime::cursor::current(&windows.ctx);
|
||||
assert!(matches!(cursor, None | Some(Cursor::System(CursorIcon::Default))), "over AppKit's edge the cursor is left to the OS: {cursor:?}");
|
||||
}
|
||||
|
||||
/// photocraft#16905: a full-window container (RAW Develop, Vanishing Point) in an OS window of its own, in a window the
|
||||
/// app frames, moves by its title row and resizes by its edges. Its fallback overlay covers the main window and neither
|
||||
/// moves nor resizes, and the window took that rule: no move band and no grips, so the window could not be moved.
|
||||
#[trial]
|
||||
fn a_full_window_container_in_its_own_window_moves_and_resizes_it() {
|
||||
const WINDOW: Vec2 = Vec2::new(900.0, 640.0);
|
||||
let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None };
|
||||
let integrated =
|
||||
craft_window::policy::decide(Os::Linux, Runtime::Native, Backend::X11, &desktop, WindowKind::Main, TitleBarPref::Integrated, None);
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(FakeSystem::new())).frame(integrated));
|
||||
let rig = Rig::new(Mount::viewport_with(Overlay::full_window(FocusPolicy::DIALOG), WindowSpec::dialog()));
|
||||
let rect = Rect::from_min_size(Pos2::new(100.0, 100.0), WINDOW);
|
||||
windows.child_info(ViewportInfo {
|
||||
inner_rect: Some(rect),
|
||||
outer_rect: Some(rect),
|
||||
native_pixels_per_point: Some(1.0),
|
||||
..ViewportInfo::default()
|
||||
});
|
||||
for _ in 0..4 {
|
||||
rig.frame(&windows, vec![], vec![]);
|
||||
}
|
||||
let title = rig.header.get();
|
||||
assert!(title.is_positive(), "the title row showed");
|
||||
let sent = drag(pos2(title.center().x + 30.0, title.center().y), vec2(40.0, 20.0), |events| rig.frame(&windows, vec![], events));
|
||||
assert!(sent.contains(&ViewportCommand::StartDrag), "a drag of the title row moves the window: {sent:?}");
|
||||
let sent = drag(pos2(WINDOW.x - 1.0, WINDOW.y / 2.0), vec2(-20.0, 0.0), |events| rig.frame(&windows, vec![], events));
|
||||
assert_eq!(resizes(&sent), [ResizeDirection::East], "a drag of the right edge resizes the window: {sent:?}");
|
||||
}
|
||||
@@ -53,3 +53,34 @@ fn a_dropdown_box_fills_under_the_pointer_and_while_open() {
|
||||
assert_eq!(open, hover, "an open box keeps the hover fill");
|
||||
});
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn icon_ink_on_reaches_non_text_contrast_minimum_under_standard_and_high_contrast() {
|
||||
let ctx = egui::Context::default();
|
||||
let white_paper = craft_ui::style::DataColor::new(Color32::WHITE);
|
||||
let dark_paper = craft_ui::style::DataColor::new(Color32::from_rgb(0x18, 0x18, 0x1b));
|
||||
|
||||
// Standard contrast: at least 3.0:1
|
||||
let standard_tokens = tokens(Mode::Light, Contrast::Standard);
|
||||
with_cx(&ctx, &standard_tokens, Variant::SECONDARY, ControlSize::Md, |cx| {
|
||||
let ink_white = cx.icon_ink_on(white_paper);
|
||||
let ratio_white = craft_theme::contrast_ratio(craft_theme::Rgba::from(ink_white.egui()), craft_theme::Rgba::from(white_paper.0));
|
||||
assert!(ratio_white >= 3.0, "standard contrast icon ink on white paper reaches 3:1: {ratio_white}");
|
||||
|
||||
let ink_dark = cx.icon_ink_on(dark_paper);
|
||||
let ratio_dark = craft_theme::contrast_ratio(craft_theme::Rgba::from(ink_dark.egui()), craft_theme::Rgba::from(dark_paper.0));
|
||||
assert!(ratio_dark >= 3.0, "standard contrast icon ink on dark paper reaches 3:1: {ratio_dark}");
|
||||
});
|
||||
|
||||
// High contrast: at least 4.5:1
|
||||
let high_tokens = tokens(Mode::Light, Contrast::High);
|
||||
with_cx(&ctx, &high_tokens, Variant::SECONDARY, ControlSize::Md, |cx| {
|
||||
let ink_white = cx.icon_ink_on(white_paper);
|
||||
let ratio_white = craft_theme::contrast_ratio(craft_theme::Rgba::from(ink_white.egui()), craft_theme::Rgba::from(white_paper.0));
|
||||
assert!(ratio_white >= 4.5, "high contrast icon ink on white paper reaches 4.5:1: {ratio_white}");
|
||||
|
||||
let ink_dark = cx.icon_ink_on(dark_paper);
|
||||
let ratio_dark = craft_theme::contrast_ratio(craft_theme::Rgba::from(ink_dark.egui()), craft_theme::Rgba::from(dark_paper.0));
|
||||
assert!(ratio_dark >= 4.5, "high contrast icon ink on dark paper reaches 4.5:1: {ratio_dark}");
|
||||
});
|
||||
}
|
||||
@@ -111,7 +111,8 @@ pub struct DockConfig {
|
||||
pub tab_look: PanelTabLook,
|
||||
/// A floating window opens in an OS window of its own where the window host opens OS windows and reports where
|
||||
/// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and
|
||||
/// with this off, it shows in the app window.
|
||||
/// with this off, it shows in the app window. A window that takes over a held press (`DockArea::continue_move`)
|
||||
/// opens its OS window once that press ends.
|
||||
pub native_windows: bool,
|
||||
/// Docked groups' menus get Minimize and Move Group Up and Down.
|
||||
pub group_order_items: bool,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! its accessibility node. A container describes each divider as a [`Divider`] in reading order and applies the
|
||||
//! coordinate the drag or the keys ask for; this module owns everything that is the same for all of them, including
|
||||
//! the mirroring for right-to-left. A component that draws its own dividers (a column bar, a margin handle) calls
|
||||
//! [`declare`] in its parts, `pointer` and [`keys`] in its update, and [`describe`] in its access, and declares `KeyUse::SPLITTER` for the arrow keys.
|
||||
//! [`declare_focusing`] in its parts, `pointer` and [`keys`] in its update, and [`describe`] in its access, and declares `KeyUse::SPLITTER` for the arrow keys.
|
||||
|
||||
use crate::contract::{Access, Component, Cx, Focus as _, Name, Numeric, PartBuilder, PartsCx, Pointer as _, Role};
|
||||
use craft_behavior::dock::DockEdge;
|
||||
@@ -93,18 +93,26 @@ fn along_y(mv: NavMove) -> NavMove {
|
||||
}
|
||||
|
||||
/// Declares the part `key.at(index)` for `divider`: an edge part above the panes that takes drags and is its own Tab
|
||||
/// stop. `rect` is the container's rect, which the bar is mirrored across for right-to-left. The part is returned for
|
||||
/// what a caller adds (a tooltip that names the edge).
|
||||
/// stop. A press on it leaves key focus where it is (`Sense::KEEP_FOCUS`), so a pointer drag does not make the divider
|
||||
/// the key target: the arrow keys after it still reach whatever held them, and only a divider reached by Tab takes
|
||||
/// them to resize. `rect` is the container's rect, which the bar is mirrored across for right-to-left. The part is
|
||||
/// returned for what a caller adds (a tooltip that names the edge).
|
||||
pub fn declare<'a, C: Component>(cx: &'a mut PartsCx<'_, C>, rect: Rect, key: PartKey, index: u64, divider: &Divider) -> PartBuilder<'a> {
|
||||
let bar = Flow::new(rect, cx.flow.is_rtl()).to_physical(divider.bar);
|
||||
cx.part(key.at(index), bar)
|
||||
.sense(Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.sense(Sense::DRAG | Sense::KEEP_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Edge, 0))
|
||||
.cursor(divider.cursor())
|
||||
.focusable()
|
||||
.over()
|
||||
}
|
||||
|
||||
/// [`declare`] for a value control drawn with dividers (a column bar, a margin handle) rather than a splitter between
|
||||
/// panes: a press on the divider takes key focus, so the arrow keys after a click step it.
|
||||
pub fn declare_focusing<'a, C: Component>(cx: &'a mut PartsCx<'_, C>, rect: Rect, key: PartKey, index: u64, divider: &Divider) -> PartBuilder<'a> {
|
||||
declare(cx, rect, key, index, divider).sense(Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
}
|
||||
|
||||
/// What the pointer did to the divider `key.at(index)` this pass.
|
||||
pub fn pointer<C: Component>(cx: &Cx<'_, C>, key: PartKey, index: u64, divider: &Divider) -> Option<Drag> {
|
||||
drag(cx.part(key.at(index)).press.phase, cx.rect, cx.flow.is_rtl(), divider)
|
||||
|
||||
@@ -18,8 +18,8 @@ pub enum DockEvent<P> {
|
||||
},
|
||||
/// Auto-Collapse Iconic Panels was chosen in a column menu. The host flips its preference and passes it back.
|
||||
ToggleAutoCollapse,
|
||||
/// The area opened, switched or closed its flyout: an icon click, Escape, a press outside, or the focus
|
||||
/// leaving it under Auto-Collapse. A host that binds the flyout takes it as the request when its binding is given.
|
||||
/// The area opened, switched or closed its flyout: an icon click, Escape, or a press outside or the focus leaving
|
||||
/// it under Auto-Collapse. A host that binds the flyout takes it as the request when its binding is given.
|
||||
FlyoutChanged {
|
||||
/// The panel now in the flyout; `None` when it closed.
|
||||
panel: Option<P>,
|
||||
|
||||
@@ -51,8 +51,11 @@ impl Outcome for FlyoutOutput {
|
||||
|
||||
/// A popup beside an iconic column, on the side of the canvas, whose top left the caller places. Escape closes it; with
|
||||
/// Auto-Collapse Iconic Panels a press outside it and the focus leaving it close it too. Its body is measured at the
|
||||
/// flyout's width first: the flyout is as tall as the body measures within the room below its top, and at least its
|
||||
/// `size`'s height, and the body then shows in the rect that takes.
|
||||
/// flyout's width first: the flyout is as tall as the body measures, at most the height of `within`, and at least its
|
||||
/// `size`'s height, and the body then shows in the rect that takes. A flyout that fits below its top stays there; one
|
||||
/// taller than the room below its top moves up by what it overflows and no further, its bottom on `within`'s (the
|
||||
/// layer's keep rule moves it the least distance into its bounds), and only one taller than `within` starts at
|
||||
/// `within`'s top and scrolls.
|
||||
///
|
||||
/// The user resizes it by its top and bottom edges, the edge away from the column and the two corners there; the
|
||||
/// column side stays. The flyout keeps no rect of its own: each step comes back in [`FlyoutShown::placed`] and the
|
||||
@@ -140,8 +143,9 @@ impl Flyout {
|
||||
}
|
||||
};
|
||||
let size = self.size;
|
||||
// A body measures no taller than the room below the top, inside the bounds.
|
||||
let room = (self.within.bottom() - top_left.y).max(size.y);
|
||||
// A body measures no taller than the bounds: a flyout that does not fit below its top moves up by its overflow
|
||||
// alone, so only a body taller than the bounds is limited to them.
|
||||
let room = self.within.height().max(size.y);
|
||||
let overlay = self.overlay(top_left, ui.is_rtl());
|
||||
self.props = self.props.mount(Mount::Layer(overlay));
|
||||
let shown = ui.show_container(popup, self, |ui, cx| {
|
||||
|
||||
@@ -208,7 +208,8 @@ pub struct IconicColumnStyle {
|
||||
/// icon groups, the top and bottom of the stack and each icon group's cells, which join its tabs. The flyout shows
|
||||
/// its group through the `view` of [`show_flyouts`](IconicColumn::show_flyouts), with the opened panel active, as tall as the view measures the
|
||||
/// group within the room and at least the height of its panels' default heights; a group the user sized keeps that
|
||||
/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`.
|
||||
/// size. The flyout's top is level with its group's icons, shifted by the group's `flyout_offset`, inside `within`;
|
||||
/// a flyout taller than the room below that top moves up by what it overflows and no further.
|
||||
/// The user resizes it by its top and bottom edges and the edge away from the column; each step comes back in
|
||||
/// [`IconicColumnOutput::flyout`], which the host keeps in the group (`flyout_width`, `height`, `flyout_offset`).
|
||||
///
|
||||
|
||||
@@ -422,6 +422,112 @@ fn a_flyout_with_an_offset_in_a_short_viewport_stays_inside_and_resizes_its_widt
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the panels of the tall-body trials, which set no heights.
|
||||
const TALL: [&str; 8] = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];
|
||||
/// What the body of a flyout in the tall-body trial measures.
|
||||
const TALL_BODY: f32 = 300.0;
|
||||
/// The room below the last group's icon in the short-window trial.
|
||||
const ROOM_BELOW: f32 = 200.0;
|
||||
/// How much shorter than that room the body of the flyout that fits measures, and how much taller the one that does not.
|
||||
const OVERFLOW: f32 = 40.0;
|
||||
|
||||
/// What [`tall_flyouts`] returns: the fixture, the panel whose flyout is open (the trial sets it) and the rect the open
|
||||
/// flyout's body showed in, last pass.
|
||||
type TallFlyouts = (Fixture, Rc<Cell<Option<u8>>>, Rc<Cell<Option<Rect>>>);
|
||||
|
||||
/// A column of the [`TALL`] panels, each in a group of its own, on the left window edge; its flyouts stay inside the
|
||||
/// bounds `within` holds and their bodies measure the height `body` holds. Returns the fixture, the panel whose flyout
|
||||
/// is open (the trial sets it) and the rect the open flyout's body showed in, last pass.
|
||||
fn tall_flyouts(within: &Rc<Cell<Rect>>, body: &Rc<Cell<f32>>) -> TallFlyouts {
|
||||
let (open, shown) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None)));
|
||||
let (bounds, measures, now, seen) = (Rc::clone(within), Rc::clone(body), Rc::clone(&open), Rc::clone(&shown));
|
||||
let mut column = Column::new((0..TALL.len() as u8).map(|panel| Group::new(vec![panel], 0)).collect());
|
||||
column.iconic = true;
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let current = now.get();
|
||||
let mut opened = current;
|
||||
IconicColumn::new("Panels", global("iconic column", "tall flyouts"), &column, Bind::bound(&mut opened), &|panel: &u8| {
|
||||
PanelSpec::new(TALL[usize::from(*panel) % TALL.len()])
|
||||
})
|
||||
.edge(DockEdge::Start)
|
||||
.opens(Side::End)
|
||||
.within(bounds.get())
|
||||
.show_flyouts_at(ui, Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)), |group, at, ui, _| {
|
||||
match at {
|
||||
GroupAt::Measure(_) => return Some(measures.get()),
|
||||
GroupAt::Show(rect) => {
|
||||
if group.active_panel().is_some_and(|panel| Some(*panel) == current) {
|
||||
seen.set(Some(rect));
|
||||
}
|
||||
Panel::new("Flyout").show_at(ui, rect, |_, _| ());
|
||||
}
|
||||
}
|
||||
None
|
||||
});
|
||||
now.set(opened);
|
||||
});
|
||||
fixture.room(SCREEN).settle();
|
||||
(fixture, open, shown)
|
||||
}
|
||||
|
||||
/// Closes the open flyout of [`tall_flyouts`] and opens the last group's.
|
||||
fn reopen_last(fixture: &mut Fixture, open: &Cell<Option<u8>>) {
|
||||
open.set(None);
|
||||
fixture.settle();
|
||||
open.set(Some(TALL.len() as u8 - 1));
|
||||
fixture.settle();
|
||||
}
|
||||
|
||||
/// A flyout whose body measures taller than the room below its group's icons moves up to stay inside the bounds, as
|
||||
/// tall as the body (or as the bounds when those are shorter): it is not cut to the room below its top with the rest
|
||||
/// of its body laid out below the bounds. The panels set no heights, so the group's height does not give the room.
|
||||
#[trial]
|
||||
fn a_flyout_taller_than_the_room_below_its_icons_moves_up_inside_the_bounds() {
|
||||
let (within, body) = (Rc::new(Cell::new(screen())), Rc::new(Cell::new(TALL_BODY)));
|
||||
let (mut fixture, open, shown) = tall_flyouts(&within, &body);
|
||||
let last = TALL[TALL.len() - 1];
|
||||
let icon = fixture.by_label(last).expect("the last group's icon").rect;
|
||||
for height in [icon.bottom() + 8.0, 200.0] {
|
||||
// The bounds end just below the last icon, or are shorter than the body.
|
||||
let bounds = Rect::from_min_size(Pos2::ZERO, Vec2::new(SCREEN.x, height));
|
||||
within.set(bounds);
|
||||
reopen_last(&mut fixture, &open);
|
||||
let rect = shown.get().expect("the last group's flyout is open");
|
||||
let wanted = TALL_BODY.min(bounds.height());
|
||||
assert!(bounds.bottom() - icon.top() < TALL_BODY, "the bounds leave less room below the icon than the body takes: {icon:?} in {bounds:?}");
|
||||
assert!(bounds.contains_rect(rect), "{height}: the flyout {rect:?} stays inside {bounds:?}");
|
||||
assert!(rect.height() > wanted || near(rect.height(), wanted), "{height}: the flyout {rect:?} takes the body's height {wanted}");
|
||||
assert!(rect.top() < icon.top(), "{height}: the flyout {rect:?} moves up from its icon {icon:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// On a short window a flyout whose body fits below its group's icons keeps its top at the icons, and one whose body
|
||||
/// is taller than the room below them moves up only by what it overflows, its bottom on the bounds' bottom: neither
|
||||
/// takes the whole height of the bounds over the column's other icons.
|
||||
#[trial]
|
||||
fn a_flyout_on_a_short_window_moves_up_only_by_its_overflow() {
|
||||
let (within, body) = (Rc::new(Cell::new(screen())), Rc::new(Cell::new(TALL_BODY)));
|
||||
let (mut fixture, open, shown) = tall_flyouts(&within, &body);
|
||||
let icon = fixture.by_label(TALL[TALL.len() - 1]).expect("the last group's icon").rect;
|
||||
let bounds = Rect::from_min_size(Pos2::ZERO, Vec2::new(SCREEN.x, icon.top() + ROOM_BELOW));
|
||||
within.set(bounds);
|
||||
let sizes = StyleCx::with_root(fixture.ctx(), DockSizes::style);
|
||||
let least = sizes.strip + sizes.least;
|
||||
assert!(icon.top() - OVERFLOW > bounds.top(), "the bounds leave room above the icon for the taller flyout to move up: {icon:?}");
|
||||
for over in [-OVERFLOW, OVERFLOW] {
|
||||
let height = ROOM_BELOW + over;
|
||||
assert!(height > least, "{over}: the body {height} measures taller than the flyout's least height {least}");
|
||||
body.set(height);
|
||||
reopen_last(&mut fixture, &open);
|
||||
let rect = shown.get().expect("the last group's flyout is open");
|
||||
// A body that fits stays at the icon's top; a taller one moves up by its overflow alone.
|
||||
let top = icon.top() - over.max(0.0);
|
||||
assert!(near(rect.height(), height), "{over}: the flyout {rect:?} takes its body's height {height}");
|
||||
assert!(near(rect.top(), top), "{over}: the flyout {rect:?} has its top at {top}, below the icon {icon:?} or up by its overflow");
|
||||
assert!(bounds.contains_rect(rect), "{over}: the flyout {rect:?} stays inside {bounds:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each icon group's grip strip has its own room at the group's top: across the group, below the bar or the group
|
||||
/// before it and above the group's first icon, overlapping no icon. A drag that starts on a grip moves its whole
|
||||
/// group, as a drag on an icon moves its panel.
|
||||
@@ -717,7 +823,7 @@ fn icon_groups_apart_by_a_rule_show_one_level_rule_between_them() {
|
||||
let band = |group: u64| fixture.part_rect(id, GRIP.at(group)).expect("each group keeps a grip band");
|
||||
let (first, last, next) = (cell(0), cell(1), cell(2));
|
||||
let (top, lower) = (band(0), band(1));
|
||||
assert!(first.top() < gripped_first.top() - 0.5, "the first icon {first:?} stands higher than under a grip strip {gripped_first:?}");
|
||||
assert!(first.top() < gripped_first.top(), "the first icon {first:?} stands higher than under a grip strip {gripped_first:?}");
|
||||
for (group, band) in [top, lower].into_iter().enumerate() {
|
||||
assert!(grip_ticks(&shapes, band).is_none(), "group {group}: the band shows no marks");
|
||||
}
|
||||
@@ -733,7 +839,7 @@ fn icon_groups_apart_by_a_rule_show_one_level_rule_between_them() {
|
||||
let between: Vec<_> = level.iter().filter(|(a, _, _)| a.y > last.bottom() && a.y < next.top()).collect();
|
||||
let [(a, b, ink)] = between.as_slice() else { panic!("one rule between the groups: {level:?}") };
|
||||
let middle = (last.bottom() + next.top()) / 2.0;
|
||||
assert!((a.y - middle).abs() <= 0.5, "the rule {a:?} lies in the middle of the room from {last:?} to {next:?}");
|
||||
assert!(near(a.y, middle), "the rule {a:?} lies in the middle of the room from {last:?} to {next:?}");
|
||||
let (left, right) = (a.x.min(b.x), a.x.max(b.x));
|
||||
let span = right - left;
|
||||
assert!(left > 0.0 && right < RAIL && span > RAIL - span, "the rule reaches across the column, short of its sides: {a:?} to {b:?}");
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
|
||||
use super::{DockConfig, FloatingGroupOutput, PanelSpec};
|
||||
use crate::runtime::windows::{WindowAction, WindowHost, WindowSpec};
|
||||
use crate::runtime::{drag, overlay};
|
||||
use craft_behavior::GesturePhase;
|
||||
use crate::runtime::{drag, overlay, pointer};
|
||||
use craft_behavior::dock::{Action, Floating};
|
||||
use craft_behavior::placement::{Defaults, monitor_of, place};
|
||||
use craft_behavior::{Buttons, GesturePhase};
|
||||
use craft_host::target::WindowKind;
|
||||
use egui::{Context, Pos2, Rect, Vec2, ViewportId};
|
||||
|
||||
@@ -29,6 +29,8 @@ pub struct Opening {
|
||||
pub rect: Rect,
|
||||
/// The OS window to open, or `None` where the group shows in the app window.
|
||||
pub spec: Option<WindowSpec>,
|
||||
/// The group shows in the app window until the drag that moves it there ends, and in an OS window after.
|
||||
pub waits: bool,
|
||||
}
|
||||
|
||||
/// Whether the groups of panels with `specs` open OS windows: the dock's `config` turns them on, the platform opens
|
||||
@@ -53,9 +55,11 @@ pub fn pixels_per_point(ctx: &Context, viewport: ViewportId) -> Option<f32> {
|
||||
}
|
||||
|
||||
/// The window a group of panels with `specs` opens: a document window when any panel is a document, else a tool
|
||||
/// window (a palette level, no taskbar entry).
|
||||
/// window (a palette level, no taskbar entry). An Escape nothing in it takes is the Cancel of the window the dock is in.
|
||||
pub fn spec_for(specs: &[PanelSpec]) -> WindowSpec {
|
||||
if specs.iter().any(|spec| spec.window_kind == WindowKind::Document) { WindowSpec::document() } else { WindowSpec::tool() }
|
||||
let document = specs.iter().any(|spec| spec.window_kind == WindowKind::Document);
|
||||
let spec = if document { WindowSpec::document() } else { WindowSpec::tool() };
|
||||
spec.hands_on_cancel(true)
|
||||
}
|
||||
|
||||
/// The rect in the main window's points of `desktop`, a rect in desktop points: where a window at `desktop` would sit
|
||||
@@ -87,17 +91,38 @@ pub fn restore<P>(ctx: &Context, window: &Floating<P>) -> Rect {
|
||||
/// at its own rect. `specs` are its panels' specs; `group` is the id of the group that shows it. A window that opens
|
||||
/// opens at its [`restore`]d rect; an open window stays at the placement the dock model recorded for it, so the
|
||||
/// monitor fit of `restore` never sends back a place the user gave it.
|
||||
///
|
||||
/// A window opens no OS window while a drag moves it in the app window: the OS gives an OS window no press that went
|
||||
/// down in another window, so the drag would end. `continues` says that the window takes over the held press in this
|
||||
/// pass (`DockArea::continue_move`), which a window never placed on the desktop does in the app window.
|
||||
#[doc(hidden)]
|
||||
pub fn opening<P>(ctx: &Context, config: &DockConfig, window: &Floating<P>, specs: &[PanelSpec], group: egui::Id) -> Opening {
|
||||
pub fn opening<P>(ctx: &Context, config: &DockConfig, window: &Floating<P>, specs: &[PanelSpec], group: egui::Id, continues: bool) -> Opening {
|
||||
let layer = Opening { rect: window.rect, spec: None, waits: false };
|
||||
if !allowed(ctx, config, specs) {
|
||||
return Opening { rect: window.rect, spec: None };
|
||||
return layer;
|
||||
}
|
||||
let open = WindowHost::of(ctx).viewport_of(group).is_some();
|
||||
if !open {
|
||||
let takes_over = continues && window.native.is_none() && pointer::frame(ctx).buttons.contains(Buttons::PRIMARY);
|
||||
if takes_over || pointer::pressed_part(ctx, group).is_some() || drag::sourced_by(ctx, group) {
|
||||
return Opening { waits: true, ..layer };
|
||||
}
|
||||
}
|
||||
let recorded = window.native.as_ref().filter(|_| open).and_then(|native| {
|
||||
let at = native.position()?;
|
||||
Some(Rect::from_min_size(Pos2::from(at), Vec2::from(native.normal.size)))
|
||||
});
|
||||
Opening { rect: recorded.unwrap_or_else(|| restore(ctx, window)), spec: Some(spec_for(specs)) }
|
||||
Opening { rect: recorded.unwrap_or_else(|| restore(ctx, window)), spec: Some(spec_for(specs)), waits: false }
|
||||
}
|
||||
|
||||
/// Asks for the pass in which a group that waits to open its OS window ([`Opening::waits`]) opens it: the next one once
|
||||
/// the press that moved it has ended, or the one after a target in another window had its chance to take the drop.
|
||||
#[doc(hidden)]
|
||||
pub fn waited(ctx: &Context, opening: &Opening, output: &FloatingGroupOutput) {
|
||||
let ended = output.placed.is_some_and(|change| matches!(change.phase, GesturePhase::Commit | GesturePhase::Cancel));
|
||||
if opening.waits && (ended || pointer::pressed_part(ctx, output.response.id).is_none()) {
|
||||
crate::runtime::frame::request_repaint(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
/// The action that records where the OS put the native window `window`, shown in `viewport`: its placement, as an
|
||||
|
||||
@@ -440,7 +440,9 @@ impl<T: Value + 'static> ToolbarDrawer<'_, T> {
|
||||
if let Some(run) = run_of(&groups[group].slots, tool) {
|
||||
row = row.run(run);
|
||||
}
|
||||
if let Some(icon) = &command.icon {
|
||||
if let Some(icon) = &groups[group].tools[tool].icon {
|
||||
row = row.icon(icon.clone());
|
||||
} else if let Some(icon) = &command.icon {
|
||||
row = row.icon(IconSpec::svg(IconId::from(icon.clone())));
|
||||
}
|
||||
if on_toolbar(toolbar, &groups[group].tools[tool].id, grouped_tools_drag) {
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::contract::{
|
||||
use crate::display::TargetMark;
|
||||
use crate::layout_components::Row;
|
||||
use crate::menu::{self, Menu, MenuItem};
|
||||
use crate::primitives::{PaintShape, StrokeWidth};
|
||||
use crate::primitives::{IconSpec, PaintShape, StrokeWidth};
|
||||
use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::style::{ComponentStyle, GlyphRole, StyleColor, StyleCx};
|
||||
@@ -200,7 +200,11 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> {
|
||||
/// enabled state, marked dot).
|
||||
/// The button itself runs the command, so the face only wears it, and the button's selected state with it.
|
||||
fn face(&self, laid: &Laid, selected: bool, glyphs: GlyphRole) -> IconButton<'static> {
|
||||
let icon = self.lead(laid).and_then(|resolved| resolved.icon.clone()).map_or_else(|| IconId::new("more"), IconId::from);
|
||||
// The shown tool's own icon, when it has one and the face stands for it, else its command's.
|
||||
let own = if self.click.is_none() { self.tools.get(laid.shown).and_then(|tool| tool.icon.clone()) } else { None };
|
||||
let icon = own.unwrap_or_else(|| {
|
||||
IconSpec::svg(self.lead(laid).and_then(|resolved| resolved.icon.clone()).map_or_else(|| IconId::new("more"), IconId::from))
|
||||
});
|
||||
let command = self.click.clone().or_else(|| self.tools.get(laid.shown).map(|tool| tool.command.clone()));
|
||||
let face = match command {
|
||||
Some(command) => IconButton::command(icon, command),
|
||||
@@ -381,7 +385,10 @@ impl<T: Value + 'static> Component for FlyoutButton<'_, T> {
|
||||
let rows = Menu::inline(name.clone()).show(ui, |ui, _| {
|
||||
let mut ran = None;
|
||||
for (at, tool) in tools.iter().enumerate() {
|
||||
let item = MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown);
|
||||
let mut item = MenuItem::command(tool.command.clone()).radio_mark(tool.id == *shown);
|
||||
if let Some(icon) = &tool.icon {
|
||||
item = item.icon(icon.clone());
|
||||
}
|
||||
let row = match tips.filter(|tips| tips.has(&tool.id)) {
|
||||
Some(tips) => item.show_with_tip(ui, |ui| tips.show(&tool.id, ui)),
|
||||
None => item.show(ui),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The data of a tool rail: tools, slots and the tool each slot showed last.
|
||||
|
||||
use crate::primitives::IconSpec;
|
||||
use crate::runtime::commands::CommandRef;
|
||||
use crate::runtime::env::Label;
|
||||
use egui::Ui;
|
||||
@@ -8,7 +9,7 @@ use egui::Ui;
|
||||
pub type SlotId = u32;
|
||||
|
||||
/// One tool of a slot. A tool is a command: the command gives the label, the icon, the chord and the enabled state,
|
||||
/// and picking the tool runs it.
|
||||
/// and picking the tool runs it. An [`icon`](RailTool::icon) of the tool's own replaces the command's.
|
||||
#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps, crate::contract::PlainData)]
|
||||
#[non_exhaustive]
|
||||
pub struct RailTool<T> {
|
||||
@@ -16,12 +17,24 @@ pub struct RailTool<T> {
|
||||
pub id: T,
|
||||
/// The command the tool runs.
|
||||
pub command: CommandRef,
|
||||
/// The icon the tool shows in place of its command's: the app's own artwork, a value glyph, where the icon sets
|
||||
/// have none.
|
||||
#[plain_data(assume = "an icon is a value: an SVG name, a colour or a 'static glyph compared by address, never written through")]
|
||||
pub icon: Option<IconSpec<'static>>,
|
||||
}
|
||||
|
||||
impl<T> RailTool<T> {
|
||||
/// A tool reported as `id` that runs `command`.
|
||||
/// A tool reported as `id` that runs `command`, showing its command's icon.
|
||||
pub fn new(id: T, command: impl Into<CommandRef>) -> Self {
|
||||
RailTool { id, command: command.into() }
|
||||
RailTool { id, command: command.into(), icon: None }
|
||||
}
|
||||
|
||||
/// Shows `icon` for the tool, on its rail button, its flyout row and its drawer row, in place of its command's
|
||||
/// icon: an app's own tool artwork (`IconSpec::glyph`).
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: impl Into<IconSpec<'static>>) -> Self {
|
||||
self.icon = Some(icon.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -476,3 +476,55 @@ fn idle_key_bytes(count: u8) -> usize {
|
||||
fn a_tool_rails_idle_key_bytes_do_not_grow_with_its_slots() {
|
||||
assert_eq!(idle_key_bytes(10), idle_key_bytes(100), "the key follows revisions, not the slots, the hidden or the remembered tools");
|
||||
}
|
||||
|
||||
/// A tool's own icon replaces its command's: the app's glyph paints the rail button that shows the tool and the tool's
|
||||
/// row in the flyout, and a tool without one keeps its command's icon.
|
||||
#[trial]
|
||||
fn a_tools_own_icon_paints_its_button_and_its_flyout_row() {
|
||||
use crate::primitives::{Glyph, IconSpec};
|
||||
use crate::style::UiTokens;
|
||||
|
||||
// An app's tool artwork: one ellipse across its rect, a shape nothing else on the rail paints, so the frame's
|
||||
// shapes say where the glyph painted.
|
||||
#[derive(crate::contract::MemoProps)]
|
||||
struct Artwork;
|
||||
impl Glyph for Artwork {
|
||||
fn paint(&self, painter: &egui::Painter, _: &UiTokens, rect: Rect, color: egui::Color32, _: bool) {
|
||||
painter.add(egui::Shape::ellipse_filled(rect.center(), rect.size() / 2.0, color));
|
||||
}
|
||||
}
|
||||
// Where the glyph painted in the fixture's next frame. A frame that replays a memoized view repeats its shapes, so
|
||||
// the shapes of one frame show every place the glyph is on screen.
|
||||
let painted = |fixture: &mut Fixture| -> Vec<Rect> {
|
||||
fixture
|
||||
.frame_shapes()
|
||||
.iter()
|
||||
.filter_map(|shape| match shape {
|
||||
egui::Shape::Ellipse(ellipse) => Some(Rect::from_center_size(ellipse.center, ellipse.radius * 2.0)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut group = tools(&[1, 2]);
|
||||
group[0] = group[0].clone().icon(IconSpec::glyph(&Artwork));
|
||||
let (slots, last) = (Tracked::new(vec![ToolSlot::new(0, group)]), Tracked::new(LastUsed::default()));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
ToolRail::new("Tools", &slots, &1, &last).show_rail(ui, |_, _| {});
|
||||
});
|
||||
fixture.room(Vec2::new(200.0, 400.0)).settle();
|
||||
let button = rect(&fixture, "Brush");
|
||||
let face = painted(&mut fixture);
|
||||
assert!(!face.is_empty() && face.iter().all(|at| button.contains_rect(*at)), "the glyph paints the Brush button: {face:?} in {button:?}");
|
||||
|
||||
// With the flyout open the glyph paints the Brush row too, and the Pencil row keeps its command's icon.
|
||||
fixture.frame(vec![secondary(button.center(), true), secondary(button.center(), false)]);
|
||||
fixture.settle();
|
||||
let pencil = rect(&fixture, "Pencil");
|
||||
let shown = painted(&mut fixture);
|
||||
assert!(
|
||||
shown.iter().any(|at| !button.intersects(*at) && !pencil.contains(at.center())),
|
||||
"the open flyout's Brush row paints the glyph too: {shown:?}, button {button:?}, Pencil row {pencil:?}"
|
||||
);
|
||||
assert!(shown.iter().all(|at| !pencil.contains_rect(*at)), "the Pencil row keeps its command's icon: {shown:?} in {pencil:?}");
|
||||
}
|
||||
@@ -172,8 +172,9 @@ pub struct DockArea<'a, P: Clone + Eq + Hash + Debug + Send + Sync + 'static> {
|
||||
/// The floating window holding the panel takes over the held primary press in this pass, with the pointer at the
|
||||
/// grab point inside the window ([`FloatingGroup::continue_move`]): the window follows the pointer and docks where it
|
||||
/// would dock on release. A request of the pass: a host that floats a panel from a rail's `torn_off` keeps it for
|
||||
/// the one pass after, when the window shows. Without a held press, or when no window holds the panel, it does
|
||||
/// nothing.
|
||||
/// the one pass after, when the window shows. Where the dock opens OS windows (`DockConfig::native_windows`), the
|
||||
/// window shows in the app window until the press ends, and then opens its OS window where it was released. Without
|
||||
/// a held press, when no window holds the panel, or when the window has shown in an OS window, it does nothing.
|
||||
#[prop(quantity = "panel and grab point")]
|
||||
continue_move: Option<(P, Vec2)>,
|
||||
/// Moves key focus to the group that shows the panel, as a press on the group's body does, and picks its tab, as a
|
||||
@@ -1725,7 +1726,8 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
let rights: Vec<Permissions> = window.panels().map(|panel| scene.permissions(panel)).collect();
|
||||
let dock = scene.dock.with(("floating", window.id));
|
||||
let group_id = dock.with("window");
|
||||
let opening = native::opening(&ctx, scene.config, window, &specs, group_id);
|
||||
let continued = scene.continue_move.filter(|(panel, _)| window.panels().any(|held| held == *panel)).map(|(_, grab)| grab);
|
||||
let opening = native::opening(&ctx, scene.config, window, &specs, group_id, continued.is_some());
|
||||
// An OS window lays out at its own monitor's scale, which sizes its chrome; one in the app window at the
|
||||
// main window's.
|
||||
let scale = opening
|
||||
@@ -1791,7 +1793,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
if scene.focus.is_some_and(|focus| window.panels().any(|held| held == focus)) {
|
||||
group = group.raise();
|
||||
}
|
||||
if let Some((_, grab)) = scene.continue_move.filter(|(panel, _)| window.panels().any(|held| held == *panel)) {
|
||||
if let Some(grab) = continued {
|
||||
group = group.continue_move(grab);
|
||||
}
|
||||
if scene.raise.is_some_and(|raised| window.panels().any(|held| held == raised)) {
|
||||
@@ -1827,6 +1829,7 @@ impl<P: Clone + Eq + Hash + Debug + Send + Sync + 'static> Pass<'_, P> {
|
||||
});
|
||||
self.dock = area_dock;
|
||||
let output = shown.output;
|
||||
native::waited(&ctx, &opening, &output);
|
||||
// The window's grips, then everything it drew, in the OS window it shows in, if it has one.
|
||||
let grips = output.grip.map(|(rect, node)| DockSource::new(SourceKind::WindowGrip(anchor.clone()), rect, node));
|
||||
let resize =
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(crate) mod tab_focus;
|
||||
pub(crate) mod workspace_dialogs;
|
||||
|
||||
pub(crate) mod native;
|
||||
pub(crate) mod native_drag;
|
||||
pub(crate) mod panes;
|
||||
|
||||
/// The docking sizes of the default theme with the given divider gap, least pane and strip height.
|
||||
|
||||
@@ -1606,6 +1606,101 @@ fn enter_and_escape_in_a_native_palettes_field_stay_the_fields() {
|
||||
}
|
||||
}
|
||||
|
||||
/// What panel 1's body holds that takes an Escape pressed in its window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Taker {
|
||||
Nothing,
|
||||
/// A field, which a click focuses.
|
||||
Field,
|
||||
/// A button whose context menu a secondary click opens.
|
||||
Menu,
|
||||
/// App code that reads the window's leftover Escape.
|
||||
App,
|
||||
}
|
||||
|
||||
/// Panels of which panel 1 holds `taker`.
|
||||
struct EscapePalette {
|
||||
taker: Taker,
|
||||
opacity: Option<f64>,
|
||||
}
|
||||
|
||||
impl DockPanels<u32> for EscapePalette {
|
||||
fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) {
|
||||
match self.taker {
|
||||
_ if *panel != 1 => {}
|
||||
Taker::Nothing => {}
|
||||
Taker::Field => {
|
||||
NumberField::new("Opacity", Bind::bound(&mut self.opacity)).show(ui);
|
||||
}
|
||||
Taker::Menu => {
|
||||
let target = Button::new("Target").show(ui);
|
||||
let _ = Menu::context("Target menu", &target).show(ui, |ui, _| {
|
||||
MenuItem::new("Row").show(ui);
|
||||
});
|
||||
}
|
||||
Taker::App => {
|
||||
keys::with_window_intents(ui.ctx(), false, |window| window.take(Intent::Cancel));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An Escape pressed in a native palette that holds `taker`, with the field focused or the menu open: how many of the
|
||||
/// main window's Cancels two readers found that the app runs before its dock, one after the other.
|
||||
fn main_window_cancels(taker: Taker) -> (usize, usize) {
|
||||
let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new()));
|
||||
let palette = dock.palette.expect("the palette's window opened");
|
||||
let mut panels = EscapePalette { taker, opacity: Some(50.0) };
|
||||
let mut read = (0, 0);
|
||||
let mut frame = |child: Vec<Event>| {
|
||||
dock.windows.frame(vec![], child, |ui| {
|
||||
let cancel = |ui: &Ui| usize::from(keys::with_window_intents(ui.ctx(), false, |window| window.take(Intent::Cancel)));
|
||||
read.0 += cancel(ui);
|
||||
read.1 += cancel(ui);
|
||||
let _ = DockArea::new("Native dock", Bind::bound(&mut dock.workspace), &dock.specs, &mut panels, DockConfig::default()).show(ui);
|
||||
})
|
||||
};
|
||||
frame(vec![]);
|
||||
let out = frame(vec![]);
|
||||
let at = |name: &str| {
|
||||
let tree = tree_of_viewport(&out, palette);
|
||||
let part = tree.keys().into_iter().find(|key| tree.name_of(*key) == Some(name) && tree.role_of(*key) != Some(Role::LABEL));
|
||||
part.and_then(|key| tree.bounds_of(key)).expect("the palette shows it").center()
|
||||
};
|
||||
let opened = match taker {
|
||||
Taker::Field => {
|
||||
let field = at("Opacity");
|
||||
vec![vec![moved(field), press(field)], vec![release(field)]]
|
||||
}
|
||||
Taker::Menu => {
|
||||
let target = at("Target");
|
||||
vec![vec![moved(target)], vec![secondary(target, true)], vec![secondary(target, false)]]
|
||||
}
|
||||
Taker::Nothing | Taker::App => vec![],
|
||||
};
|
||||
let escape = [vec![key_press(Key::Escape, Modifiers::NONE)], vec![key_release(Key::Escape, Modifiers::NONE)], vec![], vec![]];
|
||||
for events in opened.into_iter().chain([vec![], vec![]]).chain(escape) {
|
||||
frame(events);
|
||||
}
|
||||
read
|
||||
}
|
||||
|
||||
/// An Escape that nothing in a native palette takes is the main window's Cancel, once: the app reads it where it reads
|
||||
/// the main window's own, and the read takes it.
|
||||
#[trial]
|
||||
fn an_escape_nothing_in_a_native_palette_takes_is_the_main_windows_cancel_once() {
|
||||
assert_eq!(main_window_cancels(Taker::Nothing), (1, 0), "the first read finds the Escape, the second nothing");
|
||||
}
|
||||
|
||||
/// An Escape in a native palette that a focused field, an open menu or the app's own code there takes or keeps never
|
||||
/// reaches the main window.
|
||||
#[trial]
|
||||
fn an_escape_taken_in_a_native_palette_never_reaches_the_main_window() {
|
||||
for taker in [Taker::Field, Taker::Menu, Taker::App] {
|
||||
assert_eq!(main_window_cancels(taker), (0, 0), "{taker:?}: the Escape stays in the palette's window");
|
||||
}
|
||||
}
|
||||
|
||||
/// A palette float made in the app window.
|
||||
fn float() -> Floating<u32> {
|
||||
Floating::single(104, vec![1], 0, Rect::from_min_size(Pos2::new(40.0, 40.0), Vec2::new(300.0, 200.0)))
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! A host's own drag (a rail popup's title) that floats a panel and hands its press to the panel's window, in a dock
|
||||
//! that opens its floats in OS windows.
|
||||
|
||||
use super::Numbered;
|
||||
use craft_behavior::dock::{Floating, Layout, Node, Workspace};
|
||||
use craft_ui::contract::{Bind, BodyCx, Role, Tracked};
|
||||
use craft_ui::docking::{DockConfig, DockPanels, GroupDrag};
|
||||
use craft_ui::patterns::dock::DockArea;
|
||||
use craft_ui::runtime::drag;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::pointer::{moved, press, release};
|
||||
use craft_ui::testing::trial;
|
||||
use craft_ui_test_kit::windows::{Out, Windows};
|
||||
use egui::{Event, Key, Modifiers, Pos2, Rect, Sense, Ui, Vec2, ViewportId, ViewportInfo};
|
||||
use std::sync::Arc;
|
||||
|
||||
const DOCKED: usize = 1;
|
||||
const FLOATED: usize = 2;
|
||||
/// The main window on the desktop.
|
||||
const MAIN_AT: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(900.0, 700.0) };
|
||||
/// Where the host floats the panel, in the main window.
|
||||
const WINDOW_AT: Rect = Rect { min: Pos2::new(130.0, 90.0), max: Pos2::new(330.0, 210.0) };
|
||||
/// The host's popup title, clear of the docked group's tab strip.
|
||||
const TITLE_AT: Rect = Rect { min: Pos2::new(130.0, 230.0), max: Pos2::new(290.0, 254.0) };
|
||||
/// The grab point inside the window the host hands its press over at.
|
||||
const GRAB: Vec2 = Vec2::new(40.0, 12.0);
|
||||
const SLACK: f32 = 1.5;
|
||||
|
||||
struct Empty;
|
||||
|
||||
impl DockPanels<usize> for Empty {
|
||||
fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {}
|
||||
}
|
||||
|
||||
/// A dock over a host that shows a popup title, and the OS windows the dock opened.
|
||||
struct Host {
|
||||
windows: Windows,
|
||||
workspace: Arc<Workspace<usize>>,
|
||||
specs: Tracked<Numbered>,
|
||||
popup: bool,
|
||||
hand_over: Option<(usize, Vec2)>,
|
||||
/// Where the dock opened its first OS window on the desktop.
|
||||
opened_at: Option<Pos2>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
fn new(root: Option<Node<usize>>) -> Self {
|
||||
let windows = Windows::new();
|
||||
windows.root_info(info(MAIN_AT));
|
||||
windows.child_info(info(WINDOW_AT.translate(MAIN_AT.min.to_vec2())));
|
||||
let workspace = Arc::new(Workspace::new(Layout::new(root, Vec::new())));
|
||||
let mut host = Host { windows, workspace, specs: Tracked::new(Numbered), popup: true, hand_over: None, opened_at: None };
|
||||
for _ in 0..3 {
|
||||
host.frame(vec![]);
|
||||
}
|
||||
host
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> Out {
|
||||
let Host { windows, workspace, specs, popup, hand_over, .. } = self;
|
||||
let out = windows.frame(events, vec![], |ui| {
|
||||
let mut panels = Empty;
|
||||
let config = DockConfig::default().title_bar_docks(false);
|
||||
let mut area = DockArea::new("Dock", Bind::bound(&mut *workspace), &*specs, &mut panels, config);
|
||||
if let Some(request) = hand_over.take() {
|
||||
area = area.continue_move(request);
|
||||
}
|
||||
area.show(ui);
|
||||
if !*popup {
|
||||
return;
|
||||
}
|
||||
egui::Area::new(egui::Id::unique("host popup")).order(egui::Order::Foreground).fixed_pos(TITLE_AT.min).show(ui.ctx(), |ui| {
|
||||
let (_, title) = ui.allocate_exact_size(TITLE_AT.size(), Sense::drag());
|
||||
if title.drag_started() {
|
||||
*popup = false;
|
||||
let mut floated = workspace.layout().clone();
|
||||
floated.floating.push(Floating::single(100, vec![FLOATED], 0, WINDOW_AT));
|
||||
*workspace = Arc::new(Workspace::new(floated));
|
||||
*hand_over = Some((FLOATED, GRAB));
|
||||
}
|
||||
});
|
||||
});
|
||||
if self.opened_at.is_none() {
|
||||
self.opened_at = out.builders.iter().find(|(viewport, _)| *viewport != ViewportId::ROOT).and_then(|(_, builder)| builder.position);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn frames(&mut self, first: Vec<Event>) {
|
||||
self.frame(first);
|
||||
for _ in 0..3 {
|
||||
self.frame(vec![]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Presses the popup's title and drags it to `to`, held there.
|
||||
fn drag_to(&mut self, to: Pos2) {
|
||||
let from = TITLE_AT.center();
|
||||
self.frame(vec![moved(from)]);
|
||||
self.frame(vec![press(from)]);
|
||||
for step in 1..=4 {
|
||||
self.frame(vec![moved(from + (to - from) * (step as f32 / 4.0))]);
|
||||
}
|
||||
self.frame(vec![]);
|
||||
}
|
||||
|
||||
fn dragging(&self) -> bool {
|
||||
drag::active::<GroupDrag<usize>>(&self.windows.ctx).is_some()
|
||||
}
|
||||
|
||||
fn floats(&self) -> bool {
|
||||
self.workspace.layout().floating.iter().any(|window| window.contains(&FLOATED))
|
||||
}
|
||||
}
|
||||
|
||||
fn info(rect: Rect) -> ViewportInfo {
|
||||
ViewportInfo {
|
||||
focused: Some(true),
|
||||
inner_rect: Some(rect),
|
||||
outer_rect: Some(rect),
|
||||
native_pixels_per_point: Some(1.0),
|
||||
..ViewportInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A dock of one docked group, and a point on the free room of its tab strip.
|
||||
fn docked() -> (Host, Pos2) {
|
||||
let mut host = Host::new(Some(Node::tabs(vec![DOCKED], 0)));
|
||||
let out = host.frame(vec![]);
|
||||
let tree = &out.trees.iter().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the main window ran a pass").1;
|
||||
let tab = tree.with_role(Role::TAB).into_iter().find_map(|key| tree.bounds_of(key)).expect("the docked tab shows");
|
||||
(host, Pos2::new(tab.right() + 20.0, tab.center().y))
|
||||
}
|
||||
|
||||
/// Dropped on a docked group's tab strip, the panel joins the group: the drag shows the dock's mark, and no OS window
|
||||
/// opens at any point of it.
|
||||
#[trial]
|
||||
fn a_press_handed_to_a_float_docks_it_on_the_strip_it_is_released_on() {
|
||||
let (mut host, strip) = docked();
|
||||
host.drag_to(strip);
|
||||
assert_eq!(host.opened_at, None, "no OS window opens while the press is held");
|
||||
assert!(drag::mark(&host.windows.ctx).is_some(), "the strip under the pointer shows the drop mark");
|
||||
host.frames(vec![release(strip)]);
|
||||
let layout = host.workspace.layout();
|
||||
assert!(layout.floating.is_empty() && layout.place(&FLOATED).is_some_and(|at| layout.place(&DOCKED) == Some(at)), "it joins: {layout:?}");
|
||||
assert_eq!(host.opened_at, None, "a docked panel opens no OS window");
|
||||
}
|
||||
|
||||
/// Released where nothing takes it, the panel floats in an OS window at the place it was dropped.
|
||||
#[trial]
|
||||
fn a_press_handed_to_a_float_opens_its_os_window_where_it_is_released() {
|
||||
let mut host = Host::new(None);
|
||||
let to = Pos2::new(400.0, 300.0);
|
||||
host.drag_to(to);
|
||||
assert!(host.dragging(), "the panel's drag runs");
|
||||
assert_eq!(host.opened_at, None, "no OS window opens while the press is held");
|
||||
host.frames(vec![release(to)]);
|
||||
let at = host.opened_at.expect("the OS window opens after the release");
|
||||
assert!(at.distance(MAIN_AT.min + (to - GRAB).to_vec2()) < SLACK, "where it was dropped: {at:?}");
|
||||
assert!(host.floats() && !host.dragging(), "the panel floats and no drag is left");
|
||||
}
|
||||
|
||||
/// Escape, or the main window losing the focus, ends the drag: the panel's OS window opens where the host floated it,
|
||||
/// and the button's later release drops nothing.
|
||||
#[trial]
|
||||
fn a_cancelled_press_handed_to_a_float_leaves_it_floating() {
|
||||
for cancel in [key_press(Key::Escape, Modifiers::NONE), Event::WindowFocused(false)] {
|
||||
let (mut host, strip) = docked();
|
||||
host.drag_to(strip);
|
||||
assert!(host.dragging(), "{cancel:?}: the panel's drag runs");
|
||||
host.frames(vec![cancel.clone()]);
|
||||
assert!(!host.dragging(), "{cancel:?} ends the drag");
|
||||
host.frames(vec![release(strip)]);
|
||||
assert!(host.floats(), "{cancel:?}: the release docks nothing");
|
||||
let at = host.opened_at.expect("the panel's OS window opens");
|
||||
assert!(at.distance(MAIN_AT.min + WINDOW_AT.min.to_vec2()) < SLACK, "{cancel:?}: where the host floated it: {at:?}");
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use craft_ui::docking::{DockColumn, HidePanels, PanelKey, PanelSpec};
|
||||
use craft_ui::testing::memory::global;
|
||||
use craft_ui::testing::pointer;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Pos2, Rect};
|
||||
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeSet;
|
||||
use std::rc::Rc;
|
||||
@@ -80,3 +80,35 @@ fn a_resize_under_a_pruned_view_keeps_the_hidden_panels() {
|
||||
"the resize reached the layout"
|
||||
);
|
||||
}
|
||||
|
||||
/// Tabs until the divider holds key focus.
|
||||
fn tab_to_divider(fixture: &mut Fixture) {
|
||||
for _ in 0..12 {
|
||||
if craft_ui::testing::access::focused_key(fixture.tree()) == divider(fixture).node {
|
||||
return;
|
||||
}
|
||||
fixture.key(Key::Tab, Modifiers::NONE).idle(2);
|
||||
}
|
||||
panic!("Tab never reached the divider");
|
||||
}
|
||||
|
||||
/// A pointer drag of a divider leaves key focus where it was, so the next arrow key does not resize the dock; a
|
||||
/// divider reached by Tab still resizes with the arrows.
|
||||
#[trial]
|
||||
fn a_dragged_divider_does_not_keep_the_arrow_keys_but_a_tabbed_one_takes_them() {
|
||||
let (mut fixture, rects) = column();
|
||||
fixture.settle();
|
||||
let grip = divider(&fixture);
|
||||
fixture.drag(&grip, Vec2::new(0.0, 20.0)).idle(2);
|
||||
let dragged = rects.borrow()[0].bottom();
|
||||
assert_ne!(craft_ui::testing::access::focused_key(fixture.tree()), divider(&fixture).node, "the drag did not focus the divider");
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE).idle(2);
|
||||
assert!((rects.borrow()[0].bottom() - dragged).abs() < 0.5, "the arrows after a pointer drag left the dock as it was");
|
||||
|
||||
let (mut fixture, rects) = column();
|
||||
fixture.settle();
|
||||
tab_to_divider(&mut fixture);
|
||||
let tabbed = rects.borrow()[0].bottom();
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE).idle(2);
|
||||
assert!((rects.borrow()[0].bottom() - tabbed).abs() > 0.5, "an arrow key moves the divider Tab reached");
|
||||
}
|
||||
@@ -878,7 +878,7 @@ impl StartScreen<'_> {
|
||||
column_links(&page, ui, links_title.as_ref(), links);
|
||||
});
|
||||
});
|
||||
ui.allocate_space(vec2(0.0, margin));
|
||||
ui.add_space(env.tokens.size.page.margin);
|
||||
});
|
||||
return StartOutput { response: shown.output, actions: actions.into_inner() };
|
||||
}
|
||||
|
||||
@@ -211,9 +211,9 @@ fn page_templates() -> Vec<Template> {
|
||||
/// The links of the Column stories: a call to action and two plain links.
|
||||
fn column_links() -> [StartLink; 3] {
|
||||
[
|
||||
StartLink::url("Join the community", Some(IconId::new("message-circle")), "https://example.com/chat").primary(),
|
||||
StartLink::url("Join the community", Some(IconId::new("note")), "https://example.com/chat").primary(),
|
||||
StartLink::url("Website", Some(IconId::new("globe")), "https://example.com"),
|
||||
StartLink::url("Source code", Some(IconId::new("git-branch")), "https://example.com/source"),
|
||||
StartLink::url("Source code", Some(IconId::new("open")), "https://example.com/source"),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -388,6 +388,42 @@ fn whole_bar(_: &mut WholeBar, ui: &mut Ui) {
|
||||
);
|
||||
}
|
||||
|
||||
/// The cursor over the File title and over the band of the whole bar in a window, with the band's cursor `look`.
|
||||
fn cursors_over_the_bar(look: craft_ui::contract::MoveBandCursor) -> (Option<craft_behavior::Cursor>, Option<craft_behavior::Cursor>) {
|
||||
let layout = craft_window::Layout { left: vec![], right: vec![Caption::Minimize, Caption::Maximize, Caption::Close] };
|
||||
let frame = Frame::Integrated(Captions { family: CaptionFamily::Windows, layout });
|
||||
let desktop = Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None };
|
||||
let windows = Windows::with(InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)).frame(Decision { frame, overridden: None, desktop }));
|
||||
let mut root = craft_ui::runtime::env::RootEnv::default();
|
||||
root.values.set(look);
|
||||
windows.root_env(root);
|
||||
let show = |ui: &mut Ui| whole_bar(&mut WholeBar { version: 0 }, ui);
|
||||
windows.frame(vec![], vec![], show);
|
||||
let settled = windows.frame(vec![], vec![], show);
|
||||
let tree = &settled.trees.iter().rev().find(|(viewport, _)| *viewport == ViewportId::ROOT).expect("the root pass ran").1;
|
||||
let title = |name: &str| {
|
||||
tree.with_role(Role::MENU_ITEM).into_iter().find(|key| tree.name_of(*key) == Some(name)).and_then(|key| tree.bounds_of(key)).expect("a title")
|
||||
};
|
||||
let (file, help) = (title("File"), title("Help"));
|
||||
let over = |at: Pos2| {
|
||||
windows.frame(vec![moved(at)], vec![], show);
|
||||
windows.frame(vec![], vec![], show);
|
||||
craft_ui::runtime::cursor::current(&windows.ctx)
|
||||
};
|
||||
(over(file.center()), over(Pos2::new(help.right() + 40.0, help.center().y)))
|
||||
}
|
||||
|
||||
/// A title bar's move band shows the open hand by default, also through the menu titles on it, which sense clicks
|
||||
/// only; under `MoveBandCursor::Arrow` the band and the titles show the arrow, as an OS title bar does.
|
||||
#[trial]
|
||||
fn a_move_band_shows_the_arrow_when_the_app_asks() {
|
||||
use craft_behavior::{Cursor, CursorIcon};
|
||||
use craft_ui::contract::MoveBandCursor;
|
||||
let grab = Some(Cursor::System(CursorIcon::Grab));
|
||||
assert_eq!(cursors_over_the_bar(MoveBandCursor::Hand), (grab.clone(), grab), "the hand over the band and the titles on it");
|
||||
assert_eq!(cursors_over_the_bar(MoveBandCursor::Arrow), (None, None), "the arrow over the band and the titles on it");
|
||||
}
|
||||
|
||||
/// A whole title bar an app shows through a memoized view in the shell's title slot (1600 × 1000 px at 125 %) fills
|
||||
/// the slot as the bar shown directly does: the captions end at the slot's end edge and the document title is drawn
|
||||
/// whole after the last menu.
|
||||
|
||||
@@ -51,13 +51,15 @@ pub struct SplitButtonStyle {
|
||||
radius: CornerRadius,
|
||||
}
|
||||
|
||||
/// What a split button reports: the main part's response (`clicked()` runs the action) and the entry picked from
|
||||
/// the menu this pass.
|
||||
/// What a split button reports: whether its action runs, and the entry picked from the menu this pass.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct SplitOutput<T> {
|
||||
/// The main part's response.
|
||||
/// The button's response, which reports the clicks on the arrow as the main part's.
|
||||
pub response: Response,
|
||||
/// The action runs in this pass: a click on the main part, or an activation by key or AccessKit. Never a click on
|
||||
/// the arrow.
|
||||
pub activated: bool,
|
||||
/// The entry the user picked.
|
||||
pub chosen: Option<T>,
|
||||
/// The pointer's stay over the main part: hovered, entered, left and clicked under the pointer.
|
||||
@@ -228,6 +230,11 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The arrow opens the menu: a click on it never runs the action, nor fires the bound command.
|
||||
fn activated(&self, cx: &Cx<'_, Self>) -> bool {
|
||||
cx.activation().is_some() && cx.part_activated(ARROW).is_none()
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
cx.join_roving();
|
||||
let menu = cx.popup("menu");
|
||||
@@ -307,7 +314,7 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> SplitOutput<T> {
|
||||
SplitOutput { response: cx.response.clone(), chosen: self.chosen, hover: cx.hover() }
|
||||
SplitOutput { activated: self.activated(&cx), response: cx.response.clone(), chosen: self.chosen, hover: cx.hover() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,10 @@ pub struct Picture<'a> {
|
||||
#[style_key]
|
||||
#[prop]
|
||||
extent: PictureSize,
|
||||
/// Whether a rendered picture shows the transparency grid behind its transparent pixels (default on). Off for
|
||||
/// a picture that is a mask on the surface it sits on, such as an equation.
|
||||
#[prop]
|
||||
checker: bool,
|
||||
}
|
||||
|
||||
impl<'a> Picture<'a> {
|
||||
@@ -117,7 +121,7 @@ impl<'a> Picture<'a> {
|
||||
}
|
||||
|
||||
fn from_source(label: impl Into<Label>, source: Source<'a>) -> Self {
|
||||
Picture { common: Common::new(), revision: Revision::default(), source, aspect: None, extent: PictureSize::Icon }.label(label)
|
||||
Picture { common: Common::new(), revision: Revision::default(), source, aspect: None, extent: PictureSize::Icon, checker: true }.label(label)
|
||||
}
|
||||
|
||||
/// The width of the picture's rect at `height`: the set aspect, else the SVG's own, else a square.
|
||||
@@ -202,7 +206,7 @@ impl Component for Picture<'_> {
|
||||
let rect = cx.content_rect;
|
||||
let request = ThumbRequest::for_cell(rect.width().max(rect.height()), cx.ctx.pixels_per_point());
|
||||
let state = thumbnails.state(&cx.ctx, *source, key, &request, Priority::VISIBLE);
|
||||
thumbnails.paint(&ui.content_painter(cx), rect, &state, &ThumbPaint::default());
|
||||
thumbnails.paint(&ui.content_painter(cx), rect, &state, &ThumbPaint::default().checker(self.checker));
|
||||
}
|
||||
Source::Svg(svg) => {
|
||||
let ppp = cx.ctx.pixels_per_point();
|
||||
|
||||
@@ -82,3 +82,12 @@ fn picture_painter(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
fn picture_fill(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
Picture::painter("Preview", ThumbAspect::new(4, 1), |cx, rect| cx.checker(rect)).extent(PictureSize::Fill).show(ui).into()
|
||||
}
|
||||
|
||||
/// A rendered picture without the transparency grid, for a mask that sits on the surface.
|
||||
#[story(Picture<'static>, covers = [], drive = Drive::Never)]
|
||||
fn picture_rendered_without_checker(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let options = ThumbnailOptions::new();
|
||||
let thumbnails = Thumbnails::<u64>::in_context(ui.ctx(), "craft_ui::stories::picture_rendered_without_checker", options);
|
||||
let source = FakeThumbSource::<u64>::new().later(true);
|
||||
Picture::rendered("Mask", 1, &thumbnails, &source).extent(PictureSize::Thumb(ThumbSize::Large)).checker(false).show(ui).into()
|
||||
}
|
||||
@@ -466,7 +466,8 @@ impl Component for ListRow<'_> {
|
||||
access.expanded(open);
|
||||
if !self.disclosure_by_host {
|
||||
let pattern = if open { &words.collapse } else { &words.expand };
|
||||
access.node(DISCLOSURE, Role::BUTTON).name = Name::Text(named(pattern, label));
|
||||
// the triangle names the row as a screen reader hears it
|
||||
access.node(DISCLOSURE, Role::BUTTON).name = Name::Text(named(pattern, self.accessible_name.as_deref().unwrap_or(label)));
|
||||
}
|
||||
}
|
||||
let selected =
|
||||
@@ -590,7 +591,10 @@ impl Component for ListRow<'_> {
|
||||
&& placed.disclosure.is_some()
|
||||
&& !self.disclosure_by_host
|
||||
{
|
||||
ui.face(DISCLOSURE, Disclosure::new(Bind::given(open)).node(false).label(cx.resolved.label.to_owned()));
|
||||
ui.face(
|
||||
DISCLOSURE,
|
||||
Disclosure::new(Bind::given(open)).node(false).label(self.accessible_name.clone().unwrap_or_else(|| cx.resolved.label.to_owned())),
|
||||
);
|
||||
}
|
||||
{
|
||||
let draw = ui.draw();
|
||||
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user