mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 16:59:56 +01:00
Merge next into fix/derived-number-value-fits-field
This commit is contained in:
commit
031356cfff
411 files changed
+16354
-1497
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
|
||||
@@ -122,10 +122,12 @@ jobs:
|
||||
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
|
||||
cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }}
|
||||
lint-cache: false
|
||||
# The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them.
|
||||
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
|
||||
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
|
||||
unreached-rs-allow: |
|
||||
**/fixtures/**
|
||||
vendor/**
|
||||
crates/pdf/read-only-contract/**
|
||||
timeout-minutes: &timeout 120
|
||||
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
|
||||
tools: &tools cargo-nextest@0.9.150
|
||||
@@ -167,8 +169,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
+39
-14
@@ -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",
|
||||
@@ -1901,6 +1902,7 @@ dependencies = [
|
||||
"craft-scraft-format",
|
||||
"craft-settings",
|
||||
"craft-sf2",
|
||||
"craft-shared-vec",
|
||||
"craft-sheet",
|
||||
"craft-shx",
|
||||
"craft-silhouette-studio",
|
||||
@@ -2039,6 +2041,7 @@ name = "craft-appkit"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-app-kit 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
]
|
||||
@@ -2271,6 +2274,7 @@ dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-flags",
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
@@ -2409,6 +2413,7 @@ name = "craft-dialogs"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"craft-appkit",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-browse",
|
||||
@@ -2772,6 +2777,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 +2792,7 @@ dependencies = [
|
||||
"cap-primitives",
|
||||
"craft-atomic",
|
||||
"craft-font-catalog",
|
||||
"craft-font-os-windows",
|
||||
"flate2",
|
||||
"log",
|
||||
"ruzstd",
|
||||
@@ -4026,6 +4040,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-shared-vec"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-shared-vec",
|
||||
"proptest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
@@ -4145,6 +4169,7 @@ dependencies = [
|
||||
name = "craft-suite-account"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-platform",
|
||||
"dirs",
|
||||
"keyring",
|
||||
"keyring-core",
|
||||
@@ -5571,7 +5596,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "ecolor"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"emath",
|
||||
@@ -5627,7 +5652,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "eframe"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5662,7 +5687,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"accesskit",
|
||||
"ahash",
|
||||
@@ -5681,7 +5706,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-wgpu"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5700,7 +5725,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui-winit"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"block2 0.6.2",
|
||||
"bytemuck",
|
||||
@@ -5720,7 +5745,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_glow"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"egui",
|
||||
@@ -5733,7 +5758,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "egui_kittest"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui",
|
||||
@@ -5810,7 +5835,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "emath"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
@@ -5883,7 +5908,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytemuck",
|
||||
@@ -5909,7 +5934,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "epaint_default_fonts"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[package]]
|
||||
name = "equator"
|
||||
@@ -15241,19 +15266,19 @@ dependencies = [
|
||||
[[patch.unused]]
|
||||
name = "egui_demo_lib"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_extras"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_inspection"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
|
||||
[[patch.unused]]
|
||||
name = "egui_system_font_provider"
|
||||
version = "0.37.0"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
|
||||
source = "git+https://github.com/storytold/egui.git?rev=b9770908e0f304896f9658d239a7b29cf8af1564#b9770908e0f304896f9658d239a7b29cf8af1564"
|
||||
+16
-14
@@ -32,6 +32,7 @@ craft-ssip = { path = "crates/ssip" }
|
||||
craft-ber = { path = "crates/ber" }
|
||||
craft-proto = { path = "crates/proto" }
|
||||
craft-render-parity = { path = "crates/render-parity" }
|
||||
craft-shared-vec = { path = "crates/shared-vec" }
|
||||
acadrust = "=0.6.6"
|
||||
log = "0.4"
|
||||
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
|
||||
@@ -123,6 +124,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" }
|
||||
@@ -316,20 +318,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
|
||||
linesweeper = { path = "vendor/linesweeper" }
|
||||
vello_common = { path = "vendor/vello_common" }
|
||||
vello_cpu = { path = "vendor/vello_cpu" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
|
||||
|
||||
@@ -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)
|
||||
@@ -374,6 +377,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui`
|
||||
feature).
|
||||
- [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md).
|
||||
- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`.
|
||||
- [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies.
|
||||
- [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft.
|
||||
- [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused.
|
||||
@@ -476,7 +480,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`.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-appkit"
|
||||
description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,11 +8,12 @@ rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
|
||||
# `NSNotificationCenter` with a block.
|
||||
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
|
||||
|
||||
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
|
||||
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS
|
||||
//! only; the crate is empty elsewhere.
|
||||
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
|
||||
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
|
||||
//!
|
||||
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
|
||||
//! block says why it is sound.
|
||||
@@ -14,6 +14,8 @@ use block2::RcBlock;
|
||||
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
|
||||
use objc2_foundation::{NSNotification, NSNotificationCenter};
|
||||
|
||||
pub mod save_panel;
|
||||
|
||||
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
|
||||
/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once
|
||||
/// for the process; a later call replaces nothing and does nothing.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
|
||||
use objc2_app_kit::{NSPopUpButton, NSSavePanel};
|
||||
use objc2_foundation::{NSObject, NSObjectProtocol};
|
||||
|
||||
/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems
|
||||
/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it.
|
||||
pub fn new_save_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
|
||||
// SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as
|
||||
// `Option`, so nil is `None`.
|
||||
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
|
||||
if panel.is_some() {
|
||||
return panel;
|
||||
}
|
||||
// SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`.
|
||||
unsafe { msg_send![NSSavePanel::class(), savePanel] }
|
||||
}
|
||||
|
||||
/// The closure a [`PopUpChoice`] calls.
|
||||
pub struct Ivars {
|
||||
on_choose: Box<dyn Fn(usize)>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
// SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`.
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = Ivars]
|
||||
#[name = "CraftPopUpChoice"]
|
||||
/// The target of a pop-up menu's action; see [`on_choose`].
|
||||
pub struct PopUpChoice;
|
||||
|
||||
// SAFETY: NSObjectProtocol has no additional requirements.
|
||||
unsafe impl NSObjectProtocol for PopUpChoice {}
|
||||
|
||||
impl PopUpChoice {
|
||||
// SAFETY: NSControl's target-action sends the pop-up button as the one object argument.
|
||||
#[unsafe(method(choose:))]
|
||||
fn choose(&self, sender: &NSPopUpButton) {
|
||||
if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) {
|
||||
(self.ivars().on_choose)(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target,
|
||||
/// so the caller keeps the returned object for as long as `popup` can send its action.
|
||||
pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained<PopUpChoice> {
|
||||
let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) });
|
||||
// SAFETY: NSObject's designated initializer, called once on the allocated subclass.
|
||||
let target: Retained<PopUpChoice> = unsafe { msg_send![super(this), init] };
|
||||
let object: &AnyObject = ⌖
|
||||
// SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps
|
||||
// `target` alive while `popup` can send it (the documentation above).
|
||||
unsafe {
|
||||
popup.setTarget(Some(object));
|
||||
popup.setAction(Some(sel!(choose:)));
|
||||
}
|
||||
target
|
||||
}
|
||||
@@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
|
||||
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
|
||||
| `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. |
|
||||
| `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. |
|
||||
| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
|
||||
| `synthetic` | `Click`, `Move`, `Drag`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.drag` (a press, moves in even steps and the release, from one request), `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. |
|
||||
| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. |
|
||||
| `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. |
|
||||
| `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. |
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::security;
|
||||
use crate::server::{self, Listening};
|
||||
|
||||
/// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so
|
||||
/// freeing a taken port is enough.
|
||||
/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`].
|
||||
pub const RETRY: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence
|
||||
@@ -123,6 +123,10 @@ pub struct AgentLink {
|
||||
applied: Option<Option<AgentSettings>>,
|
||||
retry_at: Option<Instant>,
|
||||
retry: Duration,
|
||||
/// The token a failed start already read and checked, for its retries with the same settings;
|
||||
/// cleared once a start succeeds or the settings change. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms
|
||||
/// on the UI thread, which every retry of a taken port would otherwise pay again.
|
||||
checked_token: Option<String>,
|
||||
status: AgentLinkStatus,
|
||||
}
|
||||
|
||||
@@ -144,6 +148,7 @@ impl AgentLink {
|
||||
applied: None,
|
||||
retry_at: None,
|
||||
retry: RETRY,
|
||||
checked_token: None,
|
||||
status: AgentLinkStatus::default(),
|
||||
}
|
||||
}
|
||||
@@ -166,7 +171,12 @@ impl AgentLink {
|
||||
|
||||
/// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it
|
||||
/// on another port, stop it, or keep it while other settings change. Does nothing while `want`
|
||||
/// equals the last call's and no retry of a failed start is due.
|
||||
/// equals the last call's and no retry of a failed start is due. A token file refused as it is
|
||||
/// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still
|
||||
/// can't be used (a folder in its place, a folder that can't be written) schedules no retry:
|
||||
/// that lasts until someone changes it, and on Windows each check blocks the UI thread for
|
||||
/// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`]
|
||||
/// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again.
|
||||
pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate {
|
||||
let mut update = LinkUpdate::default();
|
||||
if self.launch.is_some() {
|
||||
@@ -174,9 +184,15 @@ impl AgentLink {
|
||||
}
|
||||
let now = motion::now();
|
||||
let retry_due = self.retry_at.is_some_and(|at| now >= at);
|
||||
if self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want) && !retry_due {
|
||||
let unchanged = self.applied.as_ref().is_some_and(|applied| applied.as_ref() == want);
|
||||
if unchanged && !retry_due {
|
||||
return update;
|
||||
}
|
||||
// Only a retry with the same settings reuses the token its failed start checked: after a
|
||||
// change (agents off and on again, another port) the file may hold another token by now.
|
||||
if !unchanged {
|
||||
self.checked_token = None;
|
||||
}
|
||||
let before = (self.status.clone(), self.applied.clone().flatten());
|
||||
self.applied = Some(want.cloned());
|
||||
self.retry_at = None;
|
||||
@@ -218,6 +234,10 @@ impl AgentLink {
|
||||
update.requests = Some(requests);
|
||||
Ok(())
|
||||
}
|
||||
Err(problem @ LinkProblem::TokenFile(_)) => {
|
||||
log::warn!("{problem}");
|
||||
Err(problem)
|
||||
}
|
||||
Err(problem) => {
|
||||
log::warn!("{problem}");
|
||||
self.retry_at = Some(motion::now() + self.retry);
|
||||
@@ -229,13 +249,21 @@ impl AgentLink {
|
||||
|
||||
/// The token from the settings folder (created `0600` when missing), the server, then the
|
||||
/// connection file. Any failure leaves nothing running.
|
||||
fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
/// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]).
|
||||
/// The token file is the link's own, so one refused as it is gets a new token (see
|
||||
/// [`fresh_token`]).
|
||||
fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver<ControlRequest>), LinkProblem> {
|
||||
let token_file = dir.join(TOKEN_FILE);
|
||||
let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?;
|
||||
let token = match self.checked_token.clone() {
|
||||
Some(token) => token,
|
||||
None => fresh_token(&token_file)?,
|
||||
};
|
||||
self.checked_token = Some(token.clone());
|
||||
let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?;
|
||||
let running = Running { server, dir: dir.to_path_buf(), port_pref };
|
||||
let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone());
|
||||
write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?;
|
||||
self.checked_token = None;
|
||||
Ok((running, requests))
|
||||
}
|
||||
|
||||
@@ -250,3 +278,22 @@ impl AgentLink {
|
||||
self.status.problem = Some(problem);
|
||||
}
|
||||
}
|
||||
|
||||
/// The token in `token_file`, created when missing. A regular file the check refuses (one an
|
||||
/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged
|
||||
/// token) is replaced with a new token, once: the token is only this link's secret, and a client
|
||||
/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted
|
||||
/// the file. Anything else in the way (a folder, a link) is reported, not removed.
|
||||
fn fresh_token(token_file: &Path) -> Result<String, LinkProblem> {
|
||||
let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()));
|
||||
let problem = match read() {
|
||||
Ok(token) => return Ok(token),
|
||||
Err(problem) => problem,
|
||||
};
|
||||
if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) {
|
||||
return Err(problem);
|
||||
}
|
||||
log::warn!("{problem}; writing a new token file");
|
||||
std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?;
|
||||
read()
|
||||
}
|
||||
@@ -5,8 +5,9 @@
|
||||
//! (`engine.execute`, `ui.inspect`, `ui.set`, `ui.dialog.*`, `ui.screenshot`, …) and hands the
|
||||
//! [`Reply`] to [`ControlChannel::settle`]. The channel replies at once, after the queued
|
||||
//! injected input has been processed ([`Reply::AfterInput`], so a following `ui.inspect` sees
|
||||
//! the effect), when a background job ends ([`Reply::AfterJob`]), or when a screenshot completes
|
||||
//! ([`Reply::Screenshot`], through [`crate::screenshot::Captures`]).
|
||||
//! the effect), when a background job ends ([`Reply::AfterJob`]), when the app answers a dialog's
|
||||
//! held OK ([`Reply::AfterHeldOk`]), or when a screenshot completes ([`Reply::Screenshot`], through
|
||||
//! [`crate::screenshot::Captures`]).
|
||||
//!
|
||||
//! Deadlines: a request still queued when its [`REPLY_DEADLINE`] passes is dropped before dispatch
|
||||
//! and the transport replies [`expired_error`] (safe to re-send); one that was dispatched and gave
|
||||
@@ -15,6 +16,7 @@
|
||||
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
use craft_ui::dialog::{DialogHost, DialogId, HeldOk};
|
||||
use craft_ui::runtime::motion;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
@@ -133,6 +135,19 @@ pub enum Reply {
|
||||
/// A `ui.accessTree`: hold the reply until the window's settled access tree can be read
|
||||
/// ([`ControlChannel::poll_access_trees`]).
|
||||
AccessTree,
|
||||
/// A `ui.dialog.confirm` that filed the held OK of a dialog for the app: hold the reply until the
|
||||
/// app answers it ([`ControlChannel::poll_held`]).
|
||||
#[non_exhaustive]
|
||||
AfterHeldOk {
|
||||
/// The dialog whose OK is held.
|
||||
dialog: DialogId,
|
||||
/// Which open of the dialog ([`DialogHost::open_serial`]): a later open of the same dialog
|
||||
/// is not the one the request confirmed.
|
||||
open: u64,
|
||||
/// The app's refusal of the dialog's previous OK, when this confirm filed OK again after it:
|
||||
/// the earlier confirms still held for this open are answered with it.
|
||||
refused: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Reply {
|
||||
@@ -174,6 +189,7 @@ pub struct ControlChannel {
|
||||
input_waiters: Vec<Sender<ControlResponse>>,
|
||||
job_waiters: Vec<(JobId, Sender<ControlResponse>)>,
|
||||
tree_waiters: Vec<Sender<ControlResponse>>,
|
||||
held_waiters: Vec<(DialogId, u64, Sender<ControlResponse>)>,
|
||||
/// The screenshot queue; the app calls its `issue` and `drain` from its UI and logic phases.
|
||||
pub captures: Captures,
|
||||
}
|
||||
@@ -181,7 +197,14 @@ pub struct ControlChannel {
|
||||
impl ControlChannel {
|
||||
/// Attach a transport's receiver (TCP, stdin, tests).
|
||||
pub fn new(rx: Receiver<ControlRequest>) -> Self {
|
||||
Self { rx, input_waiters: Vec::new(), job_waiters: Vec::new(), tree_waiters: Vec::new(), captures: Captures::default() }
|
||||
Self {
|
||||
rx,
|
||||
input_waiters: Vec::new(),
|
||||
job_waiters: Vec::new(),
|
||||
tree_waiters: Vec::new(),
|
||||
held_waiters: Vec::new(),
|
||||
captures: Captures::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The next request to run, claimed through [`Dispatch::start`]. Expired or abandoned
|
||||
@@ -200,8 +223,16 @@ impl ControlChannel {
|
||||
|
||||
/// Reply now, or park the reply on input, a job or a screenshot. `settle_ms` is the
|
||||
/// screenshot settle delay ([`crate::screenshot::settle_ms`] of the animation time);
|
||||
/// `document` the identity a screenshot is attributed to.
|
||||
/// `document` the identity a screenshot is attributed to. A screenshot is admitted at
|
||||
/// [`motion::now`]; [`Self::settle_at`] takes the time instead.
|
||||
pub fn settle(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64) {
|
||||
self.settle_at(req, outcome, document, settle_ms, motion::now());
|
||||
}
|
||||
|
||||
/// [`Self::settle`] with a screenshot admitted at `now`: its settle delay and its
|
||||
/// [`crate::screenshot::DEADLINE`] count from `now`, on the clock the app passes to
|
||||
/// [`Captures::issue`] and [`Captures::drain`].
|
||||
pub fn settle_at(&mut self, req: ControlRequest, outcome: Reply, document: Option<DocumentId>, settle_ms: f64, now: Instant) {
|
||||
let reply = req.reply;
|
||||
match outcome {
|
||||
Reply::Done(v) => {
|
||||
@@ -210,9 +241,21 @@ impl ControlChannel {
|
||||
Reply::AfterInput => self.input_waiters.push(reply),
|
||||
Reply::AfterJob(job) => self.job_waiters.push((job, reply)),
|
||||
Reply::AccessTree => self.tree_waiters.push(reply),
|
||||
Reply::AfterHeldOk { dialog, open, refused } => {
|
||||
if let Some(reason) = refused {
|
||||
self.held_waiters.retain(|(earlier, earlier_open, tx)| {
|
||||
let answered = (*earlier, *earlier_open) == (dialog, open);
|
||||
if answered {
|
||||
let _ = tx.send(json!({"ok": false, "error": reason}));
|
||||
}
|
||||
!answered
|
||||
});
|
||||
}
|
||||
self.held_waiters.push((dialog, open, reply));
|
||||
}
|
||||
Reply::Screenshot { token, path, region, viewport } => {
|
||||
let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms };
|
||||
if let Err((reply, e)) = self.captures.admit(request, motion::now()) {
|
||||
if let Err((reply, e)) = self.captures.admit(request, now) {
|
||||
let _ = reply.send(json!({"ok": false, "error": e}));
|
||||
}
|
||||
}
|
||||
@@ -291,6 +334,29 @@ impl ControlChannel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers the held `ui.dialog.confirm` requests ([`Reply::AfterHeldOk`]) from `host`: success
|
||||
/// once the app accepted the dialog's held OK; once it refused it, an error whose text is the
|
||||
/// refusal's reason, English for a reason given as a `Word`; an error once the dialog closed
|
||||
/// while it waited, also when the same dialog opened again since. A request stays held while
|
||||
/// the app has not answered. Call it in every pass after the app answered the held OKs it
|
||||
/// answers in that pass and before the pass runs the host ([`DialogHost::run`]), which closes a
|
||||
/// dialog the app accepted; calling it more than once in a pass is harmless.
|
||||
pub fn poll_held(&mut self, host: &DialogHost) {
|
||||
self.held_waiters.retain(|(dialog, open, reply)| {
|
||||
let answer = match host.held_state(*dialog) {
|
||||
_ if host.open_serial(*dialog) != Some(*open) => {
|
||||
json!({"ok": false, "error": "the dialog closed while its OK waited for the app's answer"})
|
||||
}
|
||||
Some(HeldOk::Waiting) => return true,
|
||||
Some(HeldOk::Accepted) => json!({"ok": true, "result": null}),
|
||||
Some(HeldOk::Refused(reason)) => json!({"ok": false, "error": reason.as_str()}),
|
||||
_ => json!({"ok": false, "error": "the app refused OK"}),
|
||||
};
|
||||
let _ = reply.send(answer);
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
/// Drops the host's queued input and the step in flight, and fails every
|
||||
/// [`Reply::AfterInput`] waiter with `input cancelled: {reason}`, also when only waiters
|
||||
/// remain (their input was already consumed). True when anything was pending or waiting.
|
||||
@@ -331,6 +397,6 @@ impl ControlChannel {
|
||||
|
||||
/// Waiters of every kind, for `ui.inspect`'s `pending` count and tests.
|
||||
pub fn waiting(&self) -> usize {
|
||||
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.captures.pending()
|
||||
self.input_waiters.len() + self.job_waiters.len() + self.tree_waiters.len() + self.held_waiters.len() + self.captures.pending()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` on an app's [`DialogHost`], for every dialog type.
|
||||
//!
|
||||
//! The app's method table hands these methods to [`dialog_method`] and lists [`inspect`] under `ui.inspect`'s
|
||||
//! `dialogs`. A dialog is named by the `id` `inspect` lists, or `"top"` for the top one; its fields are its
|
||||
//! The app's method table hands these methods to [`dialog_method`], or to [`dialog_reply`] for a reply that waits
|
||||
//! for the app's answer to a held OK, and lists [`inspect`] under `ui.inspect`'s `dialogs`. A dialog is named by the
|
||||
//! `id` `inspect` lists, or `"top"` for the top one; its fields are its
|
||||
//! [`StackDialog::json_fields`](craft_ui::dialog::StackDialog::json_fields). Opening a dialog (`ui.dialog.open`) and
|
||||
//! running the command its answer is for stay the app's: an answer waits for the app's `DialogHost::take` as a
|
||||
//! click's would.
|
||||
@@ -10,6 +11,7 @@ use craft_ui::dialog::{DialogHost, DialogId, HeldOk, StandardPrompt};
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::control::Reply;
|
||||
use crate::protocol::Params;
|
||||
|
||||
/// The most `fields` one `ui.dialog.set` call takes.
|
||||
@@ -36,7 +38,8 @@ pub fn inspect(host: &DialogHost) -> Value {
|
||||
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field,
|
||||
/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]).
|
||||
/// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field
|
||||
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it.
|
||||
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it;
|
||||
/// a second confirm while that answer waits is refused.
|
||||
/// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape
|
||||
/// answer gives that answer, with its tag; any other dialog closes with its children with Cancel.
|
||||
pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
@@ -49,6 +52,26 @@ pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params:
|
||||
Some(run(host, ctx, method, params, fields))
|
||||
}
|
||||
|
||||
/// [`dialog_method`] as the [`Reply`] the app hands to [`ControlChannel::settle`](crate::ControlChannel::settle): a
|
||||
/// `ui.dialog.confirm` that files a dialog's held OK for the app replies once the app answers it
|
||||
/// ([`Reply::AfterHeldOk`], answered by [`ControlChannel::poll_held`](crate::ControlChannel::poll_held)), so a refusal
|
||||
/// reaches the caller as the reply's error, in its reason's English text. Every other call replies at once.
|
||||
pub fn dialog_reply(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Reply> {
|
||||
// The dialog is named before the call: a confirm that closes it may leave another dialog on top.
|
||||
let named = dialog_id(host, params).ok();
|
||||
// A refusal this confirm replaces still answers the confirms it refused.
|
||||
let refused = match named.and_then(|id| host.held_state(id)) {
|
||||
Some(HeldOk::Refused(reason)) => Some(reason.as_str().to_owned()),
|
||||
_ => None,
|
||||
};
|
||||
let result = dialog_method(host, ctx, method, params)?;
|
||||
let held = named.filter(|&id| method == "ui.dialog.confirm" && result.is_ok() && host.held_state(id) == Some(HeldOk::Waiting));
|
||||
Some(match held.and_then(|id| Some((id, host.open_serial(id)?))) {
|
||||
Some((dialog, open)) => Reply::AfterHeldOk { dialog, open, refused },
|
||||
None => Reply::from_result(result),
|
||||
})
|
||||
}
|
||||
|
||||
fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, fields: &[&str]) -> Result<Value, String> {
|
||||
let params = Params(params).only(None, fields)?;
|
||||
let read = Params(¶ms);
|
||||
@@ -67,6 +90,10 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
|
||||
}
|
||||
},
|
||||
"ui.dialog.confirm" => {
|
||||
// A second OK while the first waits files nothing, as the disabled button shows.
|
||||
if host.held_state(id) == Some(HeldOk::Waiting) {
|
||||
return Err("the dialog's OK waits for the app's answer to an earlier OK".to_owned());
|
||||
}
|
||||
if let Some(choice) = params.get("choice") {
|
||||
host.set_json_field(ctx, id, "choice", choice.clone())?;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,11 @@
|
||||
//! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept
|
||||
//! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it.
|
||||
|
||||
#[cfg(not(windows))]
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{BufRead, Write};
|
||||
use std::io::BufRead;
|
||||
#[cfg(not(windows))]
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -319,30 +322,34 @@ fn read_token_file(path: &Path) -> Result<String, AutomationError> {
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one
|
||||
/// that caused it, with the path in its message.
|
||||
fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> {
|
||||
let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display()));
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?;
|
||||
std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?;
|
||||
}
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
|
||||
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
|
||||
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
|
||||
// On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's
|
||||
// access list, and the token is written through the handle that created it.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
|
||||
owner_only::current_user_sid()
|
||||
.and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes()))
|
||||
.map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display())))
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(path).map_err(|e| at(path, e))?;
|
||||
writeln!(file, "{token}").map_err(|e| at(path, e))
|
||||
}
|
||||
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
|
||||
}
|
||||
|
||||
/// The server's token, lower-cased. Both given is
|
||||
@@ -355,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
|
||||
/// file can be reached by others: <why>; restrict it to its owner`), and its trimmed content is
|
||||
/// validated. A missing one is created with a generated token (parent directories created,
|
||||
/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a
|
||||
/// newline); losing that create race to another process reads the winner's file instead.
|
||||
/// newline); losing that create race to another process reads the winner's file instead. On
|
||||
/// Windows a create that does not finish in time fails (`I/O: <path>: cannot create the control
|
||||
/// token file for its owner only: <why>`), and a file it left at the path is not read as a winner's.
|
||||
pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result<String, AutomationError> {
|
||||
server_token_with(supplied, token_file, create_token_file)
|
||||
}
|
||||
|
||||
/// [`server_token`], with `create` making a missing token file.
|
||||
fn server_token_with(
|
||||
supplied: Option<&str>,
|
||||
token_file: Option<&Path>,
|
||||
create: impl FnOnce(&Path, &str) -> std::io::Result<()>,
|
||||
) -> Result<String, AutomationError> {
|
||||
if supplied.is_some() && token_file.is_some() {
|
||||
return Err(token_conflict());
|
||||
}
|
||||
@@ -370,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result
|
||||
};
|
||||
match read_token_file(path) {
|
||||
Ok(existing) => Ok(existing.to_ascii_lowercase()),
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) {
|
||||
Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) {
|
||||
Ok(()) => Ok(token),
|
||||
// Another process won the create-new race.
|
||||
Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(e),
|
||||
// Another process won the create-new race. A file left by a create that ran out of time is this one's.
|
||||
Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()),
|
||||
Err(e) => Err(AutomationError::Io(e.to_string())),
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
|
||||
@@ -141,6 +141,12 @@ fn server_token_sources_and_validation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use craft_platform::owner_only;
|
||||
let sddl = owner_only::sddl_of(&file).unwrap();
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
}
|
||||
assert_eq!(server_token(None, Some(&file)).unwrap(), created);
|
||||
|
||||
// An existing file's content is trimmed and lower-cased.
|
||||
@@ -163,3 +169,25 @@ fn server_token_sources_and_validation() {
|
||||
"bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE"
|
||||
);
|
||||
}
|
||||
|
||||
// A token file create that runs out of time fails with its own error, even when it left a file at
|
||||
// the path: that file is not read as another process's. A create that another process beat to the
|
||||
// path reads that process's token.
|
||||
#[trial]
|
||||
fn a_token_file_create_that_runs_out_of_time_is_an_error() {
|
||||
let dir = scratch_dir("token-limit");
|
||||
let file = dir.join("token");
|
||||
let late = |p: &Path, _: &str| {
|
||||
std::fs::write(p, "partial").unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display())))
|
||||
};
|
||||
let err = server_token_with(None, Some(&file), late).unwrap_err().to_string();
|
||||
assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}");
|
||||
std::fs::remove_file(&file).unwrap();
|
||||
let beaten = |p: &Path, _: &str| {
|
||||
create_token_file(p, TOKEN).unwrap();
|
||||
Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"))
|
||||
};
|
||||
assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`,
|
||||
//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
|
||||
//! `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`.
|
||||
//!
|
||||
//! This module reads and validates the protocol's parameters; the window host queues the input
|
||||
//! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`],
|
||||
@@ -12,7 +12,8 @@
|
||||
//! withdraws a step queued for a document or focus that changed before the pass consumed it.
|
||||
//!
|
||||
//! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a
|
||||
//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves
|
||||
//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps
|
||||
//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves
|
||||
//! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go.
|
||||
//!
|
||||
//! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application
|
||||
@@ -22,8 +23,7 @@
|
||||
//!
|
||||
//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action
|
||||
//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a
|
||||
//! drag is `ui.click {hold}`, `ui.move` and `ui.release`.
|
||||
//! missing, ambiguous, disabled or undeclared node is refused before anything is queued.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -43,6 +43,12 @@ pub const MAX_CLICKS: u64 = 256;
|
||||
/// display, yet small enough that egui's pointer delta between two such points stays finite.
|
||||
pub const MAX_SCREEN_POINT: f64 = 1e6;
|
||||
|
||||
/// Most moves one `ui.drag` may ask for (`steps`).
|
||||
pub const MAX_DRAG_STEPS: u64 = 200;
|
||||
|
||||
/// The moves a `ui.drag` makes when its request names no `steps`.
|
||||
pub const DRAG_STEPS: u64 = 12;
|
||||
|
||||
/// The longest hover rest one `ui.move` may ask for (`rest`, seconds).
|
||||
pub const MAX_REST: f64 = 10.0;
|
||||
|
||||
@@ -302,6 +308,71 @@ impl Move {
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release
|
||||
/// there.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct Drag {
|
||||
/// Where the button goes down.
|
||||
pub from: At,
|
||||
/// Where the button comes up.
|
||||
pub to: At,
|
||||
/// The button pressed.
|
||||
pub button: PointerButton,
|
||||
/// Moves from `from` to `to`; the last one lands on `to`.
|
||||
pub steps: u64,
|
||||
/// Modifiers held from the press to the release.
|
||||
pub mods: Mods,
|
||||
}
|
||||
|
||||
impl Drag {
|
||||
/// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object
|
||||
/// `{x?, y?, coordinates?, page?, control?}` in its own space, as `ui.click` reads its point; a missing one is
|
||||
/// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button`
|
||||
/// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`];
|
||||
/// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``.
|
||||
pub fn from_params(params: &Value) -> Result<Self, String> {
|
||||
let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?;
|
||||
let p = Params(&p);
|
||||
let point = |name: &str| -> Result<At, String> {
|
||||
let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) };
|
||||
let point = Params(point).only(Some(name), &POINT)?;
|
||||
At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}"))
|
||||
};
|
||||
let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS);
|
||||
if !(1..=MAX_DRAG_STEPS).contains(&steps) {
|
||||
return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})"));
|
||||
}
|
||||
Ok(Self {
|
||||
from: point("from")?,
|
||||
to: point("to")?,
|
||||
button: button(&p)?.unwrap_or(PointerButton::Primary),
|
||||
steps,
|
||||
mods: p.modifiers(&KEY_MODIFIERS)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the
|
||||
/// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click.
|
||||
/// Both points are placed before anything is queued (a control point against the access tree the host kept for
|
||||
/// `viewport`), so a point that cannot be placed leaves no press down. When the host withdraws the rest of the
|
||||
/// gesture after its press ran, the button stays down until `ui.release`, as any held input does.
|
||||
pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> {
|
||||
let (from, to) = (self.from.place(host, viewport, map)?, self.to.place(host, viewport, map)?);
|
||||
let steps = u16::try_from(self.steps).unwrap_or(u16::MAX);
|
||||
host.inject_click(viewport, from, self.button, 1, self.mods, true);
|
||||
for step in 1..=steps {
|
||||
let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) };
|
||||
host.inject_move(viewport, at, self.mods, 0.0);
|
||||
}
|
||||
host.inject_release(viewport, Some(to), Released::Button(self.button));
|
||||
// A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing
|
||||
// stays held.
|
||||
host.inject_click(viewport, to, self.button, 0, self.mods, false);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The most notches one `ui.wheel` turn in lines may ask for, either way.
|
||||
pub const MAX_NOTCHES: f32 = 100.0;
|
||||
|
||||
@@ -429,6 +500,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V
|
||||
"ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)),
|
||||
"ui.drop" => drop_files(params, host, viewport, map),
|
||||
"ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)),
|
||||
"ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)),
|
||||
"ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)),
|
||||
"ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)),
|
||||
"ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)),
|
||||
|
||||
@@ -308,6 +308,96 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() {
|
||||
TcpListener::bind(("127.0.0.1", port)).expect("the port was let go");
|
||||
}
|
||||
|
||||
/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the
|
||||
/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every
|
||||
/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again.
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_not_retried_until_the_settings_change() {
|
||||
let dir = temp_dir("link-token-no-retry");
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let wanted = free_port();
|
||||
assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
// The file is fixed, but the same settings don't look at it again.
|
||||
std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
let same = link.sync(Some(&on(u32::from(wanted))), &host);
|
||||
assert!(same.requests.is_none() && !same.changed, "no retry with the same settings");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
|
||||
let changed = link.sync(Some(&on(0)), &host);
|
||||
assert!(changed.requests.is_some(), "a settings change tries again");
|
||||
assert_eq!(link.status().problem, None);
|
||||
}
|
||||
|
||||
/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its
|
||||
/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can
|
||||
/// connect instead of staying out until someone deletes the file (photocraft#17006).
|
||||
#[trial]
|
||||
fn a_refused_token_file_is_replaced_with_a_new_token() {
|
||||
let dir = temp_dir("link-token-refresh");
|
||||
let file = dir.path().join(TOKEN_FILE);
|
||||
std::fs::write(&file, "not a token\n").unwrap();
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
let token = std::fs::read_to_string(&file).unwrap();
|
||||
assert_ne!(token.trim(), "not a token");
|
||||
assert_eq!(token.trim().len(), 64, "a new token: {token:?}");
|
||||
assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening"));
|
||||
}
|
||||
|
||||
/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows
|
||||
/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time.
|
||||
#[trial]
|
||||
fn a_taken_port_retry_reuses_the_checked_token() {
|
||||
let dir = temp_dir("link-token-reuse");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
// Reading the file now fails, so a retry that read it would report a token file problem.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let retried = link.sync(Some(&on(port)), &host);
|
||||
assert!(retried.requests.is_some(), "{:?}", link.status());
|
||||
assert_eq!(link.status().problem, None);
|
||||
|
||||
// Once a start succeeded, the next one reads the file again.
|
||||
let moved = link.sync(Some(&on(0)), &host);
|
||||
assert!(moved.requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// The checked token is kept only for retries with the same settings: turning agents off and on again reads the token
|
||||
/// file again, so a server never listens with a token the file no longer holds.
|
||||
#[trial]
|
||||
fn a_settings_change_reads_the_token_file_again() {
|
||||
let dir = temp_dir("link-token-settings");
|
||||
let host = host();
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO);
|
||||
let taken = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = u32::from(taken.local_addr().unwrap().port());
|
||||
assert!(link.sync(Some(&on(port)), &host).requests.is_none());
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status());
|
||||
|
||||
assert!(!link.sync(None, &host).stopped, "nothing was running");
|
||||
// While agents are off the token file changes; here it can't be read at all, which the next start must report.
|
||||
std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
drop(taken);
|
||||
let back = link.sync(Some(&on(port)), &host);
|
||||
assert!(back.requests.is_none(), "started with the token the file no longer holds");
|
||||
assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status());
|
||||
}
|
||||
|
||||
/// Dropping the link stops its server and removes its connection file.
|
||||
#[trial]
|
||||
fn dropping_the_link_removes_its_connection_file() {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
//! `ui.dialog.*` on typed dialogs through one generic path.
|
||||
|
||||
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect};
|
||||
use std::sync::mpsc::{Receiver, channel};
|
||||
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse};
|
||||
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, dialog_reply, inspect};
|
||||
use craft_ui::contract::{Bind, SaveKey};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt};
|
||||
use craft_ui::dialog::{DialogHost, DialogId, DialogResult, PromptChoice, PromptKind, StandardPrompt};
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use craft_ui::runtime::env::{Label, Word};
|
||||
use craft_ui::testing::trial;
|
||||
use egui::Context;
|
||||
use serde_json::{Value, json};
|
||||
@@ -124,6 +128,91 @@ fn param_dialog_automation_follows_its_rows() {
|
||||
assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom")));
|
||||
}
|
||||
|
||||
const TAKEN: Word = Word::keyed("craft_automation.nameTaken", "A preset with that name exists");
|
||||
|
||||
/// The open parameter dialog `id` names.
|
||||
fn held(host: &mut DialogHost, id: DialogId) -> &mut HostedParamDialog {
|
||||
host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::<HostedParamDialog>()).expect("the held dialog is open")
|
||||
}
|
||||
|
||||
/// A `ui.dialog.confirm` that files a held OK replies with the app's answer: nothing while the app has not answered,
|
||||
/// an error with the refusal's English text once it refuses, success once it accepts, and an error when the dialog
|
||||
/// closes first, also when it opened again since. A second confirm while the answer waits is refused, and one after a
|
||||
/// refusal no poll has read answers the earlier confirm with it. A dialog without a held OK replies at once.
|
||||
#[trial]
|
||||
fn a_confirm_of_a_held_ok_replies_with_the_apps_answer() {
|
||||
let ctx = Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
let (_requests, rx) = channel();
|
||||
let mut control = ControlChannel::new(rx);
|
||||
let dialog = |ctx: &Context, held: bool| {
|
||||
let dialog = HostedParamDialog::new(ctx, "blur", DialogFields::new(), |fields| {
|
||||
ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1}"#)).values(Bind::bound(fields))
|
||||
});
|
||||
if held { dialog.held_ok() } else { dialog }
|
||||
};
|
||||
let confirm = |host: &mut DialogHost, control: &mut ControlChannel, id: DialogId| -> Receiver<ControlResponse> {
|
||||
let (request, reply) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": id.value()}));
|
||||
let outcome = dialog_reply(host, &ctx, &request.method, &request.params).expect("a ui.dialog method");
|
||||
control.settle(request, outcome, None, 0.0);
|
||||
reply
|
||||
};
|
||||
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
control.poll_held(&host);
|
||||
assert!(reply.try_recv().is_err(), "the reply waits for the app's answer");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
let again = confirm(&mut host, &mut control, id);
|
||||
assert!(again.try_recv().is_ok_and(|reply| reply["ok"] == false), "a second OK while the first waits is refused");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
assert!(held(&mut host, id).take_ok().is_some(), "OK filed the answer for the app");
|
||||
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
|
||||
control.poll_held(&host);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
|
||||
assert_eq!(control.waiting(), 0);
|
||||
|
||||
// A confirm after a refusal no poll has read yet answers the earlier confirm with that refusal.
|
||||
let first = confirm(&mut host, &mut control, id);
|
||||
assert!(held(&mut host, id).take_ok().is_some(), "OK files the answer again after a refusal");
|
||||
held(&mut host, id).answer_ok(Err(Label::from(TAKEN)));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert_eq!(first.try_recv(), Ok(json!({"ok": false, "error": "A preset with that name exists"})));
|
||||
assert_eq!(control.waiting(), 1);
|
||||
assert!(held(&mut host, id).take_ok().is_some());
|
||||
held(&mut host, id).answer_ok(Ok(()));
|
||||
control.poll_held(&host);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})));
|
||||
assert!(host.confirm_by_id(&ctx, id), "the accepted dialog closes");
|
||||
assert!(matches!(host.take_keyed::<HostedParamDialog>(), Some((DialogResult::Ok(_), _))));
|
||||
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
control.poll_held(&host);
|
||||
let closed = reply.try_recv().expect("a closed dialog answers the held confirm");
|
||||
assert_eq!(closed["ok"], false);
|
||||
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
|
||||
host.take_keyed::<HostedParamDialog>();
|
||||
|
||||
// The same dialog opened again is a new open: its answer is not the closed one's.
|
||||
let id = host.open(dialog(&ctx, true));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
assert_eq!(host.open(dialog(&ctx, true)), id, "a reopened dialog has the same id");
|
||||
assert_eq!(control.waiting(), 1);
|
||||
control.poll_held(&host);
|
||||
let closed = reply.try_recv().expect("the closed open's confirm is answered");
|
||||
assert!(closed["error"].as_str().is_some_and(|error| error.contains("closed")), "{closed}");
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
host.take_keyed::<HostedParamDialog>();
|
||||
|
||||
let id = host.open(dialog(&ctx, false));
|
||||
let reply = confirm(&mut host, &mut control, id);
|
||||
assert_eq!(reply.try_recv(), Ok(json!({"ok": true, "result": null})), "a dialog without a held OK replies at once");
|
||||
assert_eq!(control.waiting(), 0);
|
||||
}
|
||||
|
||||
/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that
|
||||
/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread.
|
||||
#[trial]
|
||||
|
||||
@@ -248,6 +248,34 @@ fn a_request_past_its_deadline_times_out() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A screenshot settled at a given time counts its settle delay and its deadline from that time, on the clock the app
|
||||
/// also passes to `issue` and `drain`, not from the wall clock.
|
||||
#[trial]
|
||||
fn a_screenshot_settled_at_a_time_counts_from_that_time() {
|
||||
use craft_automation::control::{ControlChannel, ControlRequest, Reply};
|
||||
use craft_automation::screenshot::ScreenshotParams;
|
||||
use serde_json::json;
|
||||
|
||||
let ctx = Context::default();
|
||||
// An app clock ahead of the wall clock.
|
||||
let arrived = motion::now() + Duration::from_secs(60);
|
||||
let (_transport, requests) = channel();
|
||||
let mut control = ControlChannel::new(requests);
|
||||
control.captures.note_geometry(ViewportId::ROOT, geometry(800.0, 600.0));
|
||||
let (request, rx) = ControlRequest::new("ui.screenshot", json!({}));
|
||||
let params = ScreenshotParams::from_params(&json!({})).expect("no params");
|
||||
control.settle_at(request, Reply::screenshot(1, params, ViewportId::ROOT), None, 500.0, arrived);
|
||||
assert!(rx.try_recv().is_err(), "the reply waits for the capture");
|
||||
|
||||
let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, arrived + Duration::from_millis(400), None);
|
||||
assert!(finished.is_empty(), "inside its deadline: {:?}", finished.iter().map(error).collect::<Vec<_>>());
|
||||
assert!(callbacks.is_empty(), "not issued inside its settle delay");
|
||||
assert!(control.captures.drain(arrived + DEADLINE - Duration::from_millis(1), None).is_empty(), "inside its deadline");
|
||||
let finished = control.captures.drain(arrived + DEADLINE, None);
|
||||
assert_eq!(finished.len(), 1);
|
||||
assert!(error(&finished[0]).contains("timed out"), "{}", error(&finished[0]));
|
||||
}
|
||||
|
||||
/// Cancelling releases the budget at once; an image that arrives afterwards is dropped.
|
||||
#[trial]
|
||||
fn cancellation_releases_the_budget_and_drops_a_late_image() {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest,
|
||||
//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest,
|
||||
//! document coordinates and input-method compositions, as the passes see them, and the params refused before
|
||||
//! anything is queued.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_automation::access::NO_TREE;
|
||||
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
|
||||
use craft_automation::access::{NO_CONTROL, NO_TREE};
|
||||
use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::runtime::egui::injected::hook_without_pass;
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
@@ -123,6 +123,52 @@ fn a_held_press_stays_down_until_its_release() {
|
||||
assert!(!rig.now().primary_down, "a click without hold releases");
|
||||
}
|
||||
|
||||
/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its
|
||||
/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point.
|
||||
#[trial]
|
||||
fn a_drag_presses_moves_in_steps_and_releases_at_its_end() {
|
||||
let mut rig = Rig::new();
|
||||
rig.fx.settle();
|
||||
rig.take();
|
||||
let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point");
|
||||
rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true}));
|
||||
let after = rig.now();
|
||||
let events: Vec<Event> = rig.take().into_iter().flat_map(|pass| pass.events).collect();
|
||||
let buttons: Vec<(Pos2, bool, bool)> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift");
|
||||
let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. }));
|
||||
let moves: Vec<Pos2> = held
|
||||
.take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. }))
|
||||
.filter_map(|event| match event {
|
||||
Event::PointerMoved(at) => Some(*at),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}");
|
||||
assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}");
|
||||
assert_eq!(moves.last(), Some(&to), "the last step lands on `to`");
|
||||
assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held");
|
||||
}
|
||||
|
||||
/// A drag keeps its modifiers held after its release while other input stays down, as a click does.
|
||||
#[trial]
|
||||
fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() {
|
||||
let mut rig = Rig::new();
|
||||
rig.send("ui.key", json!({"key": "Space", "hold": true}));
|
||||
rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true}));
|
||||
let after = rig.now();
|
||||
assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up");
|
||||
assert!(after.shift, "the modifiers stay with the held key");
|
||||
rig.send("ui.release", json!({}));
|
||||
assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go");
|
||||
}
|
||||
|
||||
/// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go.
|
||||
#[trial]
|
||||
fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() {
|
||||
@@ -292,6 +338,25 @@ fn document_points_need_a_canvas() {
|
||||
assert_eq!(screen, Some(Ok(())));
|
||||
}
|
||||
|
||||
/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. That holds
|
||||
/// for a document end without a canvas and for a control end that names no control of the window.
|
||||
#[trial]
|
||||
fn a_drag_with_an_end_it_cannot_place_queues_no_press() {
|
||||
let mut rig = Rig::new();
|
||||
rig.fx.settle();
|
||||
let (host, ctx) = (rig.host(), rig.fx.ctx().clone());
|
||||
let none = |_: usize, _: Pos2| None;
|
||||
let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}});
|
||||
assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned())));
|
||||
assert!(host.injected_idle());
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing");
|
||||
let params = json!({"from": {"x": 1, "y": 1}, "to": {"control": {"name": "Save"}, "x": 4}});
|
||||
let answer = input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &map);
|
||||
assert!(matches!(&answer, Some(Err(error)) if error.starts_with(NO_CONTROL)), "{answer:?}");
|
||||
assert!(host.injected_idle());
|
||||
assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the drag to an unplaced control queued nothing");
|
||||
}
|
||||
|
||||
/// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application
|
||||
/// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key
|
||||
/// stays down, and the waiters fail with `TARGET_CHANGED`.
|
||||
@@ -358,6 +423,14 @@ fn bad_input_params_are_refused_before_anything_is_queued() {
|
||||
("ui.move", json!({"x": 10, "y": 10, "rest": "long"})),
|
||||
("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})),
|
||||
("ui.move", json!({"x": 10, "y": -far})),
|
||||
("ui.drag", json!({"from": {"x": 10}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})),
|
||||
("ui.drag", json!({"from": {"x": 10}, "to": {"control": {"name": "Save"}, "coordinates": "document"}})),
|
||||
("ui.key", json!({"key": "A", "hold": true, "nudge": 1})),
|
||||
("ui.key", json!({"key": 5})),
|
||||
("ui.key", json!({"key": "NoSuchKey", "hold": true})),
|
||||
|
||||
@@ -41,8 +41,8 @@ pub struct Workspace<P> {
|
||||
/// goes back.
|
||||
#[serde(default)]
|
||||
hidden: Vec<(P, Location<P>)>,
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the
|
||||
/// workspace.
|
||||
/// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that
|
||||
/// floats records the place it would reopen at. Saved with the workspace.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
floated: Vec<(P, Location<P>)>,
|
||||
/// Counts the replacements of this live workspace. Not saved, and not part of equality.
|
||||
@@ -264,6 +264,16 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?,
|
||||
_ => false,
|
||||
};
|
||||
// Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel
|
||||
// that would reopen in a floating window has no docked place.
|
||||
let hidden_place = match &action {
|
||||
Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed
|
||||
.restored(panel, &policy)
|
||||
.filter(|restored| !floats(&restored.layout, panel))
|
||||
.and_then(|restored| restored.layout.location(panel).ok())
|
||||
.map(|location| (panel.clone(), location)),
|
||||
_ => None,
|
||||
};
|
||||
if !reopened {
|
||||
// SetNative records where the window system has a floating window, so a lock
|
||||
// does not refuse it.
|
||||
@@ -278,6 +288,12 @@ impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
proposed.hidden.push((panel, location));
|
||||
}
|
||||
proposed.track_floated(&before);
|
||||
if let Some((panel, location)) = hidden_place
|
||||
&& floats(&proposed.layout, &panel)
|
||||
&& !proposed.floated.iter().any(|(p, _)| p == &panel)
|
||||
{
|
||||
proposed.floated.push((panel, location));
|
||||
}
|
||||
all_closed.extend(closed);
|
||||
}
|
||||
let visible: HashSet<P> = proposed.layout.panels().into_iter().cloned().collect();
|
||||
|
||||
+47
-16
@@ -1,6 +1,7 @@
|
||||
//! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and
|
||||
//! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens
|
||||
//! items that have a short form, then drops command items and titles from the end. All of them read no egui types.
|
||||
//! items that have a short form, in the order their host ranks, and drops command items and titles from the end.
|
||||
//! All of them read no egui types.
|
||||
|
||||
/// Tabs visible on a strip and tabs that need an overflow menu, all in original order.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -230,19 +231,39 @@ pub struct FitItem {
|
||||
pub keep: FitKeep,
|
||||
/// The extent of the item's shorter form, if it has one.
|
||||
pub short: Option<f32>,
|
||||
/// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first.
|
||||
pub short_order: u16,
|
||||
/// Whether the item keeps its full form until no more free items can leave.
|
||||
pub short_late: bool,
|
||||
}
|
||||
|
||||
impl FitItem {
|
||||
/// An item `extent` long in `section`.
|
||||
pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self {
|
||||
FitItem { extent, section, keep, short: None }
|
||||
FitItem { extent, section, keep, short: None, short_order: 0, short_late: false }
|
||||
}
|
||||
|
||||
/// The item with a shorter form `extent` long, which it takes before any free item leaves.
|
||||
/// The item with a shorter form `extent` long, which it takes before any free item leaves unless it is late.
|
||||
/// An item marked [`FitItem::short_late`] takes that form only after no free item is left to leave.
|
||||
pub const fn short(mut self, extent: f32) -> Self {
|
||||
self.short = Some(extent);
|
||||
self
|
||||
}
|
||||
|
||||
/// The item with its short form ranked `order`: lower ranks shorten first, and the last item of a rank first.
|
||||
/// Every item ranks 0 by default.
|
||||
pub const fn short_order(mut self, order: u16) -> Self {
|
||||
self.short_order = order;
|
||||
self
|
||||
}
|
||||
|
||||
/// The item takes its short form only after every free item that can leave has left.
|
||||
/// The other items go to the overflow menu before this one shortens. A free item with a late short form leaves
|
||||
/// in its turn instead.
|
||||
pub const fn short_late(mut self) -> Self {
|
||||
self.short_late = true;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order.
|
||||
@@ -277,11 +298,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64)
|
||||
}
|
||||
|
||||
/// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show.
|
||||
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last
|
||||
/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then
|
||||
/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long,
|
||||
/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are
|
||||
/// never listed as short. Negative and non-finite lengths count as zero.
|
||||
/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest
|
||||
/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a
|
||||
/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the
|
||||
/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the
|
||||
/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back.
|
||||
/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short.
|
||||
/// Negative and non-finite lengths count as zero.
|
||||
pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit {
|
||||
let (available, gap, section_gap, overflow_extent) =
|
||||
(item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent));
|
||||
@@ -302,19 +325,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32,
|
||||
// The shadow run holds each item at the extent it takes: shortened items at their `short` extent.
|
||||
let mut run: Vec<FitItem> = items.to_vec();
|
||||
let mut short = vec![false; items.len()];
|
||||
while !fits(&run, &shown) {
|
||||
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else {
|
||||
break;
|
||||
};
|
||||
short[last] = true;
|
||||
if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) {
|
||||
item.extent = extent;
|
||||
// Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank
|
||||
// first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits.
|
||||
let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| {
|
||||
while !fits(run, shown) {
|
||||
let next = (0..items.len())
|
||||
.rev()
|
||||
.filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late)
|
||||
.min_by_key(|&at| items[at].short_order);
|
||||
let Some(next) = next else { break };
|
||||
short[next] = true;
|
||||
if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) {
|
||||
item.extent = extent;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
shorten(false, &mut run, &mut short, &shown);
|
||||
while !fits(&run, &shown) {
|
||||
let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break };
|
||||
shown[last] = false;
|
||||
}
|
||||
shorten(true, &mut run, &mut short, &shown);
|
||||
let (kept, left): (Vec<usize>, Vec<usize>) = (0..items.len()).partition(|&at| shown[at]);
|
||||
let short = kept.iter().copied().filter(|&at| short[at]).collect();
|
||||
Fit { shown: kept, overflow: left, short }
|
||||
|
||||
@@ -85,15 +85,12 @@ pub struct GridCursor {
|
||||
impl GridCursor {
|
||||
/// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A
|
||||
/// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share
|
||||
/// does not go below it.
|
||||
/// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns.
|
||||
pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self {
|
||||
let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0);
|
||||
let content: Vec<f32> = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect();
|
||||
let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x)
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width })
|
||||
.collect();
|
||||
let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x);
|
||||
keep_fill_least(columns, &mut widths, least);
|
||||
let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect();
|
||||
GridCursor {
|
||||
flow,
|
||||
@@ -266,6 +263,44 @@ impl GridCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a
|
||||
/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight.
|
||||
/// The fill columns together take more than their room only when their least widths do not fit in it.
|
||||
fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) {
|
||||
let fills: Vec<(usize, f32)> = columns
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None })
|
||||
.collect();
|
||||
let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum();
|
||||
if !room.is_finite() {
|
||||
// Room with no bound leaves every share above its least.
|
||||
for (i, _) in &fills {
|
||||
widths[*i] = widths[*i].max(least(*i));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut raised = vec![false; columns.len()];
|
||||
loop {
|
||||
let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::<f32>();
|
||||
let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum();
|
||||
let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 };
|
||||
let mut more = false;
|
||||
for (i, weight) in &fills {
|
||||
if !raised[*i] && share(*weight) < least(*i) {
|
||||
raised[*i] = true;
|
||||
more = true;
|
||||
}
|
||||
}
|
||||
if !more {
|
||||
for (i, weight) in &fills {
|
||||
widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) };
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `columns` with each `Fill` column as a `Content` column.
|
||||
fn as_content(columns: &[ColumnWidth]) -> Vec<ColumnWidth> {
|
||||
columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect()
|
||||
@@ -288,4 +323,43 @@ mod tests {
|
||||
cursor.cell(Vec2::new(150.0, 100.0));
|
||||
assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds");
|
||||
}
|
||||
|
||||
/// The widths of one row of `columns` placed by `last`, read from the cells.
|
||||
fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec<f32> {
|
||||
let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last);
|
||||
columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &fitting);
|
||||
let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0]));
|
||||
assert!(shares[0] < 120.0, "the first column's share is below its least");
|
||||
assert!(raised[0] >= 120.0, "the first column keeps its least");
|
||||
assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow");
|
||||
assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights");
|
||||
assert_eq!(raised[3], shares[3], "the content column keeps its width");
|
||||
assert_eq!(raised.iter().sum::<f32>(), 300.0, "the row fills the grid and no more");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]);
|
||||
let widths = row_widths(&columns, &last);
|
||||
assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least");
|
||||
assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room");
|
||||
assert_eq!(widths.iter().sum::<f32>(), 330.0, "the row is as wide as the least widths and no wider");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() {
|
||||
let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content];
|
||||
let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]);
|
||||
let shares = row_widths(&columns, &last);
|
||||
let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0]));
|
||||
assert_eq!(kept, shares);
|
||||
}
|
||||
}
|
||||
@@ -18,9 +18,10 @@ fn is_unit_char(c: char) -> bool {
|
||||
}
|
||||
|
||||
/// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can
|
||||
/// tell it from a number or an operator.
|
||||
/// tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch).
|
||||
pub fn is_unit_spelling(spelling: &str) -> bool {
|
||||
!spelling.is_empty() && spelling.chars().all(is_unit_char)
|
||||
let letters = spelling.strip_prefix('/').unwrap_or(spelling);
|
||||
!letters.is_empty() && letters.chars().all(is_unit_char)
|
||||
}
|
||||
|
||||
/// A unit spelling and the factor that turns its quantity into the base unit.
|
||||
@@ -41,7 +42,9 @@ struct Unit {
|
||||
/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it
|
||||
/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest
|
||||
/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a
|
||||
/// quantity when `px` is registered. A group separator counts only before exactly three digits.
|
||||
/// quantity when `px` is registered. A registered spelling that starts with `/` (`/in`) is a unit when the letters after
|
||||
/// the `/` start it, so `40/in` is 40 of it; any other `/` divides (`80/2`). A group separator counts only before
|
||||
/// exactly three digits.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Reader {
|
||||
decimal: char,
|
||||
@@ -213,8 +216,9 @@ impl Parse<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no
|
||||
/// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it.
|
||||
/// A number and the longest registered unit spelling at the start of the letters after it, or after a `/` when a
|
||||
/// registered spelling starts with `/`. Letters that start no unit stay unread: a product sign (`2x3`) takes them,
|
||||
/// and anything else leaves the text unread, which refuses it. A `/` that starts no unit is left to divide.
|
||||
fn quantity(&mut self, scaled: bool) -> Result<f64, NotAValue> {
|
||||
let number = self.number()?;
|
||||
self.tag = None;
|
||||
@@ -223,8 +227,11 @@ impl Parse<'_> {
|
||||
return Ok(number / 100.0);
|
||||
}
|
||||
let reader = self.reader;
|
||||
let run: Vec<char> = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect();
|
||||
let unit = (1..=run.len()).rev().find_map(|len| {
|
||||
let after = &self.chars[self.at..];
|
||||
let slash = usize::from(after.first() == Some(&'/'));
|
||||
let letters = after[slash..].iter().take_while(|c| is_unit_char(**c)).count();
|
||||
let run = &after[..slash + letters];
|
||||
let unit = (1 + slash..=run.len()).rev().find_map(|len| {
|
||||
let lowered = run[..len].iter().collect::<String>().to_lowercase();
|
||||
reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit))
|
||||
});
|
||||
@@ -326,6 +333,20 @@ mod tests {
|
||||
near(&percent, "2%", 14.0);
|
||||
assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share");
|
||||
|
||||
let per_inch = Reader::new().unit_tagged("/in", 1.0, 0);
|
||||
assert!(is_unit_spelling("/in") && !is_unit_spelling("/") && !is_unit_spelling("in/") && !is_unit_spelling("//in"));
|
||||
for text in ["40/in", "40 /in", "40/IN", "80/2", "80/2/in"] {
|
||||
near(&per_inch, text, 40.0);
|
||||
}
|
||||
assert_eq!(per_inch.read_tagged("40/in", None), Ok((40.0, Some(0))), "the spelling names its unit");
|
||||
assert_eq!(per_inch.read("*2", Some(20.0)), Ok(40.0), "a relative product");
|
||||
assert_eq!(per_inch.read("/2", Some(80.0)), Ok(40.0), "a leading / still divides the start value");
|
||||
for bad in ["", "/in", "40/inch", "40/"] {
|
||||
assert_eq!(per_inch.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value");
|
||||
}
|
||||
near(&lengths, "144/2in", 1.0);
|
||||
assert_eq!(lengths.read("144/in", None), Err(NotAValue), "without a /in spelling, /in is a division with no number");
|
||||
|
||||
let german = Reader::new().decimal(',').group('.');
|
||||
near(&german, "1.234,5", 1234.5);
|
||||
near(&german, "1.234.567", 1_234_567.0);
|
||||
|
||||
@@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() {
|
||||
assert!(workspace.floated().is_empty(), "closing drops the record");
|
||||
}
|
||||
|
||||
/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old
|
||||
/// group keeps its front tab; docking it then returns it to that group at its old index.
|
||||
#[test]
|
||||
fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() {
|
||||
let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0));
|
||||
let mut opened = Workspace::new(docked());
|
||||
opened.apply(Action::close(2), false, allow).unwrap();
|
||||
opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap();
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(2), false, allow).unwrap();
|
||||
workspace.apply(float, false, allow).unwrap();
|
||||
let layout = workspace.layout();
|
||||
assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. })));
|
||||
assert_eq!(group_members(layout, 3), [3]);
|
||||
assert_eq!(front(layout, 3), 3, "the old group keeps its front tab");
|
||||
assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives");
|
||||
|
||||
let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) };
|
||||
let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone());
|
||||
workspace.apply(back, false, allow).unwrap();
|
||||
assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index");
|
||||
|
||||
let mut workspace = Workspace::new(docked());
|
||||
workspace.apply(Action::close(6), false, allow).unwrap();
|
||||
workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap();
|
||||
assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place");
|
||||
}
|
||||
|
||||
/// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6].
|
||||
fn columns() -> Layout<u32> {
|
||||
let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]);
|
||||
|
||||
@@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() {
|
||||
assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}");
|
||||
}
|
||||
|
||||
/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a
|
||||
/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order.
|
||||
#[test]
|
||||
fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() {
|
||||
let item = |extent| FitItem::new(extent, 0, FitKeep::Free);
|
||||
let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)];
|
||||
let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0);
|
||||
assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}");
|
||||
assert!(fit.overflow.is_empty(), "{fit:?}");
|
||||
|
||||
// Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second.
|
||||
let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late();
|
||||
let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)];
|
||||
let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0);
|
||||
|
||||
let roomy = at(180.0);
|
||||
assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}");
|
||||
assert!(roomy.short.is_empty(), "{roomy:?}");
|
||||
|
||||
let tight = at(130.0);
|
||||
assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}");
|
||||
assert!(tight.short.is_empty(), "{tight:?}");
|
||||
|
||||
let narrow = at(100.0);
|
||||
assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}");
|
||||
assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}");
|
||||
|
||||
let narrowest = at(50.0);
|
||||
assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() {
|
||||
let natural = [80.0, 90.0, 85.0, 95.0, 70.0];
|
||||
|
||||
@@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
Variation::WarmCool => (&words.cool, &words.warm),
|
||||
Variation::VividMuted => (&words.muted, &words.vivid),
|
||||
};
|
||||
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Text::new(left.clone()).show(ui);
|
||||
Text::new(right.clone()).show(ui);
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::{Button, PopupMark};
|
||||
use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring};
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchStyle, paint_ring, ring_band};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi,
|
||||
Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _,
|
||||
@@ -372,7 +372,7 @@ pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contra
|
||||
if style.ring {
|
||||
let ground =
|
||||
ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) });
|
||||
ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground);
|
||||
ui.draw().surface_styled(well.shrink(ring_band(well)), &ground);
|
||||
} else {
|
||||
ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge);
|
||||
}
|
||||
|
||||
@@ -448,7 +448,7 @@ pub struct ColorPanel<'a> {
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
@@ -471,7 +471,7 @@ struct Inputs<'a> {
|
||||
wells: Option<&'a [PairWell; 2]>,
|
||||
edited: Option<&'a Option<PickedColor>>,
|
||||
shown: &'a ColorPanelShown,
|
||||
recent: &'a [Srgba],
|
||||
recent: Option<&'a [Srgba]>,
|
||||
recent_setup: Option<&'a RecentSetup>,
|
||||
}
|
||||
|
||||
@@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> {
|
||||
wells: None,
|
||||
edited: None,
|
||||
shown: None,
|
||||
recent: &[],
|
||||
recent: None,
|
||||
recent_setup: None,
|
||||
gamut: None,
|
||||
}
|
||||
@@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags.
|
||||
/// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row
|
||||
/// for a host that gives them, an empty list included; without them it shows no row.
|
||||
pub fn recent(mut self, colors: &'a [Srgba]) -> Self {
|
||||
self.recent = colors;
|
||||
self.recent = Some(colors);
|
||||
self
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Swatch, SwatchSpacing};
|
||||
use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::TypeRole;
|
||||
use craft_ui::text::{HexField, TextField};
|
||||
use egui::Ui;
|
||||
|
||||
@@ -131,8 +132,8 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and
|
||||
/// picks nothing; a Shift click moves to the next mode.
|
||||
/// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end
|
||||
/// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode.
|
||||
fn spectrum(&mut self, ui: &mut Ui) {
|
||||
let mode = self.shown_mode();
|
||||
let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum };
|
||||
@@ -145,6 +146,7 @@ impl Body<'_> {
|
||||
.gamut(gamut)
|
||||
.gamut_revision(revision)
|
||||
.web_safe(self.now.web_safe_ramp)
|
||||
.square_boxes(true)
|
||||
.sizing(Sizing::Fill)
|
||||
.show(ui);
|
||||
self.ramp_events(ramp.edit.events);
|
||||
@@ -154,14 +156,19 @@ impl Body<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Recent Colors as a spaced palette; a pick sets the colour.
|
||||
/// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list
|
||||
/// is empty, where the first applied color will go.
|
||||
// PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and
|
||||
// `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip).
|
||||
fn recent(&mut self, ui: &mut Ui) {
|
||||
if self.inputs.recent.is_empty() {
|
||||
let Some(recent) = self.inputs.recent else {
|
||||
return;
|
||||
};
|
||||
Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui);
|
||||
if recent.is_empty() {
|
||||
return;
|
||||
}
|
||||
let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect();
|
||||
let mut current = self.color();
|
||||
let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced);
|
||||
if let Some(setup) = self.inputs.recent_setup {
|
||||
|
||||
@@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::canvas::context_click;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx,
|
||||
Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi,
|
||||
PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{Marker, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
@@ -240,6 +240,11 @@ pub struct ColorRamp<'a> {
|
||||
/// Whether the white and black boxes follow the bar; on by default.
|
||||
#[prop]
|
||||
boxes: bool,
|
||||
/// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a
|
||||
/// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by
|
||||
/// its content and in a short one.
|
||||
#[prop]
|
||||
square_boxes: bool,
|
||||
/// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value.
|
||||
#[prop(into)]
|
||||
kind_name: Option<Label>,
|
||||
@@ -265,6 +270,7 @@ impl<'a> ColorRamp<'a> {
|
||||
web_safe: false,
|
||||
recolor_clicks: false,
|
||||
boxes: true,
|
||||
square_boxes: false,
|
||||
kind_name: None,
|
||||
colors: Arc::default(),
|
||||
shown_ends: ends,
|
||||
@@ -416,6 +422,12 @@ impl Component for ColorRamp<'_> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
/// With [`square_boxes`](ColorRamp::square_boxes), as tall as its two end boxes stacked, each as tall as it is wide;
|
||||
/// else the style's least, a color band.
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
if self.square_boxes { Vec2::new(0.0, cx.style.boxes * 2.0) } else { Vec2::ZERO }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
@@ -136,11 +136,19 @@ pub(super) fn group_rename(groups: &[SwatchGroup], index: usize, text: &str) ->
|
||||
(!name.is_empty() && !groups.iter().enumerate().any(|(i, g)| i != index && g.name == name)).then(|| name.to_owned())
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header, then its swatches.
|
||||
/// Whether the browser shows a header row for `group`: every group but the one with an empty name, which holds the
|
||||
/// swatches outside every group.
|
||||
fn has_header(group: &SwatchGroup) -> bool {
|
||||
!group.name.is_empty()
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header (none for the swatches outside every group), then its swatches.
|
||||
fn flat<'a>(groups: impl IntoIterator<Item = &'a SwatchGroup>) -> Vec<SwatchKey> {
|
||||
let mut rows = Vec::new();
|
||||
for group in groups {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
if has_header(group) {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
}
|
||||
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
|
||||
}
|
||||
rows
|
||||
@@ -167,10 +175,21 @@ fn resolve_move(groups: &[SwatchGroup], names: &[&str], to: usize, parent: Optio
|
||||
(group < groups.len()).then_some((group, slot))
|
||||
}
|
||||
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay.
|
||||
/// The slot groups `names` land in when dropped at flat row `to`, counted in the groups that stay: each staying group
|
||||
/// whose first row (its header, or its first swatch when it has none) is above `to`. Groups never land above the
|
||||
/// swatches outside every group when those come first.
|
||||
fn group_slot(groups: &[SwatchGroup], names: &[&str], to: usize) -> usize {
|
||||
let remaining = flat(groups.iter().filter(|g| !names.contains(&g.name.as_str())));
|
||||
remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count()
|
||||
let mut row = 0;
|
||||
let mut slot = 0;
|
||||
let mut staying = groups.iter().filter(|g| !names.contains(&g.name.as_str())).peekable();
|
||||
let floor = usize::from(staying.peek().is_some_and(|g| !has_header(g)));
|
||||
for group in staying {
|
||||
if row < to {
|
||||
slot += 1;
|
||||
}
|
||||
row += usize::from(has_header(group)) + group.entries.len();
|
||||
}
|
||||
slot.max(floor)
|
||||
}
|
||||
|
||||
/// The `at` of each edit that moves `moved` (in library order) one by one within `order`, so that they end up together
|
||||
@@ -352,8 +371,8 @@ impl SwatchLibrary {
|
||||
}
|
||||
|
||||
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
|
||||
/// taken out. Anything else leaves the library as it is.
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches; no header for the group with an empty
|
||||
/// name) that remain once the moved ones are taken out. Anything else leaves the library as it is.
|
||||
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
|
||||
if mv.copy {
|
||||
return false;
|
||||
@@ -641,17 +660,24 @@ fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec<PresetRow<SwatchKey>
|
||||
}
|
||||
|
||||
/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and
|
||||
/// colour value (the name alone for a swatch without a colour).
|
||||
/// colour value (the name alone for a swatch without a colour). A group with an empty name holds the swatches outside
|
||||
/// every group: its swatches show at the top level, with no header.
|
||||
pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec<PresetRow<SwatchKey>> {
|
||||
let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::<usize>());
|
||||
for group in groups {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
let header = has_header(group);
|
||||
let depth = usize::from(header);
|
||||
if header {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
}
|
||||
for entry in &group.entries {
|
||||
let named = match entry.color() {
|
||||
Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())),
|
||||
None => entry.name.clone(),
|
||||
};
|
||||
rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named));
|
||||
rows.push(
|
||||
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), depth).tooltip(named.clone()).accessible_name(named),
|
||||
);
|
||||
}
|
||||
}
|
||||
rows
|
||||
@@ -676,6 +702,27 @@ pub(crate) mod tests {
|
||||
SwatchGroup { name: name.to_owned(), entries: entries.iter().map(|n| SwatchEntry::new((*n).to_owned(), SwatchColor::Gray(0.5))).collect() }
|
||||
}
|
||||
|
||||
/// The swatches outside every group (the group with an empty name) have no header row, so a place below them
|
||||
/// counts them as rows: a group dropped there lands after them, and a swatch dropped there joins them. A group
|
||||
/// dropped above them lands after them too.
|
||||
#[trial]
|
||||
fn drops_below_the_ungrouped_swatches_land_after_them() {
|
||||
let library = SwatchLibrary::new(vec![group("", &["A", "B"]), group("G", &["C"]), group("H", &["D"])]);
|
||||
let rows: Vec<_> = swatch_rows(&library.groups, &SwatchesWords::default()).into_iter().map(|row| row.key).collect();
|
||||
assert_eq!(rows, flat(&library.groups), "the reorder counts the rows the browser shows");
|
||||
|
||||
for to in [0, 2] {
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Group("H".to_owned()), vec![SwatchKey::Group("H".to_owned())], to, false)));
|
||||
let order: Vec<_> = moved.groups.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(order, ["", "H", "G"], "H dropped at row {to} lands below the ungrouped swatches, above G");
|
||||
}
|
||||
|
||||
let mut moved = library.clone();
|
||||
assert!(moved.apply_reorder(&ReorderMove::new(SwatchKey::Swatch("C".to_owned()), vec![SwatchKey::Swatch("C".to_owned())], 2, false)));
|
||||
assert_eq!(moved.find("C"), Some(SwatchAt::new(0, 2)), "C joins the ungrouped swatches, after B");
|
||||
}
|
||||
|
||||
/// Edits that move several items down or up give the order the browser's own reorder gives.
|
||||
#[trial]
|
||||
fn multi_item_moves_apply_as_the_reorder_does() {
|
||||
|
||||
@@ -18,7 +18,7 @@ use craft_ui::patterns::presets::{
|
||||
};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use egui::{Response, Ui};
|
||||
use egui::{AsIdSalt, IdSalt, Response, Ui};
|
||||
|
||||
use super::library::{HostThumb, find_swatch, has, panel_source};
|
||||
use super::menu::event_edits;
|
||||
@@ -77,6 +77,8 @@ type PayloadAdder<'a> = Box<dyn for<'b> Fn(PresetBrowser<'b, SwatchKey>) -> Pres
|
||||
/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop)
|
||||
/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in
|
||||
/// [`SwatchesPanelOutput::events`].
|
||||
/// - [`document`](SwatchesPanel::document) keeps the browser's own state (an open rename field, the scroll position)
|
||||
/// per document, so a host that shows one panel for several documents does not carry it from one to another.
|
||||
/// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
@@ -96,6 +98,7 @@ pub struct SwatchesPanel<'a> {
|
||||
takes_drop: Option<DropMaker<'a>>,
|
||||
payloads: Vec<PayloadAdder<'a>>,
|
||||
row_items: Option<RowItemsFn<'a>>,
|
||||
document: Option<IdSalt>,
|
||||
}
|
||||
|
||||
/// What the body decided; `show` stores the state and reports the rest after the real run.
|
||||
@@ -126,6 +129,7 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop: None,
|
||||
payloads: Vec::new(),
|
||||
row_items: None,
|
||||
document: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +220,14 @@ impl<'a> SwatchesPanel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The document whose swatches the panel shows. The browser keeps its own state (an open rename field, the scroll
|
||||
/// position) for each document, so a rename left open in one document does not open on another document's
|
||||
/// swatch of the same name. Without it the browser keeps that state for the `Ui` it is shown in.
|
||||
pub fn document(mut self, document: impl AsIdSalt) -> Self {
|
||||
self.document = Some(IdSalt::new(document));
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the panel and returns the user's actions this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
|
||||
let SwatchesPanel {
|
||||
@@ -234,12 +246,15 @@ impl<'a> SwatchesPanel<'a> {
|
||||
takes_drop,
|
||||
payloads,
|
||||
row_items,
|
||||
document,
|
||||
} = self;
|
||||
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let words = Env::of(ui).words::<SwatchesWords>();
|
||||
let mut held_state = Held::new(state);
|
||||
let ctx = ui.ctx().clone();
|
||||
let browser_id = ui.scope_id();
|
||||
// A document's browser has an id of its own; otherwise the browser takes the scope id of the `Ui` it is shown in.
|
||||
let document_id = document.map(|document| ui.scope_id().with(document));
|
||||
let browser_id = document_id.unwrap_or_else(|| ui.scope_id());
|
||||
let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons {
|
||||
Some(icons) => {
|
||||
groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect()
|
||||
@@ -267,6 +282,9 @@ impl<'a> SwatchesPanel<'a> {
|
||||
.select(select)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.selection(Bind::bound(&mut st.selection));
|
||||
if let Some(id) = document_id {
|
||||
browser = browser.browser_id(id);
|
||||
}
|
||||
if let Some(options) = footer_options {
|
||||
browser = browser.footer(options);
|
||||
}
|
||||
|
||||
@@ -202,6 +202,50 @@ impl WheelRig {
|
||||
}
|
||||
}
|
||||
|
||||
/// The names focus takes from the hue ring of a wheel shown in an arena (a split area's body) between two buttons,
|
||||
/// one per Tab in `keys` (with its modifiers).
|
||||
fn arena_tab_walk(inner: WheelInner, keys: &[Modifiers]) -> Vec<Option<String>> {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = craft_ui::buttons::Button::new("Before").show(ui);
|
||||
let limits = |_: &usize| craft_ui::contract::SizeLimits::default();
|
||||
let rules = craft_ui::docking::tree::FrameRules::new(&limits);
|
||||
let area = Rect::from_min_size(ui.max_rect().min + vec2(0.0, 40.0), vec2(400.0, 340.0));
|
||||
let _ = craft_ui::docking::SplitArea::pair("Panels", craft_behavior::Axis::X, (0usize, 1usize), 0.99, rules).show_at(ui, area, |ui, _| {
|
||||
let _ = ColorWheel::new("Color wheel", Bind::given(ModelValues::new("hsb", &[200.0, 50.0, 50.0]))).inner(inner).show(ui);
|
||||
});
|
||||
let _ = craft_ui::buttons::Button::new("After").show(ui);
|
||||
});
|
||||
fixture.room(vec2(420.0, 420.0));
|
||||
fixture.settle();
|
||||
let hue = fixture.by_label("Hue").expect("the ring");
|
||||
fixture.access(AccessActionKind::Focus, &hue);
|
||||
fixture.idle(2);
|
||||
let focused = |fixture: &Fixture| {
|
||||
let tree = fixture.tree();
|
||||
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
|
||||
};
|
||||
assert_eq!(focused(&fixture).as_deref(), Some("Hue"), "{inner:?}: the ring takes focus");
|
||||
keys.iter()
|
||||
.map(|mods| {
|
||||
fixture.key(Key::Tab, *mods);
|
||||
fixture.idle(2);
|
||||
focused(&fixture)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// In an arena, as in a docked panel, Tab from the hue ring lands on the saturation and brightness control, also when a
|
||||
/// square shows it through its own folded picker, then goes on past the wheel; Shift-Tab comes back the same way.
|
||||
#[trial]
|
||||
fn in_an_arena_tab_from_the_ring_reaches_the_saturation_and_brightness_control() {
|
||||
let (on, back) = (Modifiers::NONE, Modifiers::SHIFT);
|
||||
for inner in [WheelInner::Triangle, WheelInner::Square] {
|
||||
let walk = arena_tab_walk(inner, &[on, on, back, back]);
|
||||
let expected = ["Saturation and brightness", "After", "Saturation and brightness", "Hue"].map(|name| Some(name.to_owned()));
|
||||
assert_eq!(walk, expected, "{inner:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A square wheel hands a press between the square and the ring to the square; its named markers speak their colour,
|
||||
/// pick on a click, and a press held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both
|
||||
/// variants.
|
||||
|
||||
@@ -1,13 +1,49 @@
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, and its swatch size.
|
||||
//! `PaintChip`'s menu mark, the arrow after the well that is part of the chip, its swatch size and its ring.
|
||||
|
||||
use craft_color_ui::ui::{Paint, PaintChip, PaintChipSize};
|
||||
use craft_color_ui::ui::{GradientPreview, Paint, PaintChip, PaintChipSize};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::PopupMark;
|
||||
use craft_ui::contract::{Bind, Role, Show as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Rect, Shape};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Every shape of the frame, groups opened.
|
||||
fn flat(shapes: Vec<Shape>) -> Vec<Shape> {
|
||||
shapes.into_iter().flat_map(|shape| if let Shape::Vec(inner) = shape { flat(inner) } else { vec![shape] }).collect()
|
||||
}
|
||||
|
||||
/// A ring chip wider than it is high keeps an open middle: the hole inside the band is at least a third of the chip's
|
||||
/// height, and the band is as thick at the sides as at the top and bottom. Checked for a solid paint, drawn as a band
|
||||
/// of the colour, and for a gradient, whose middle is covered by the surface the chip sits on.
|
||||
#[trial]
|
||||
fn a_wide_ring_chip_keeps_an_open_middle() {
|
||||
let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(0.2, 0.4, 0.8)), (1.0, Srgba::WHITE)]);
|
||||
for paint in [Paint::Solid(Srgba::rgb(0.2, 0.4, 0.8)), Paint::Gradient(gradient)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut paint = paint.clone();
|
||||
let _ = PaintChip::new("Stroke", Bind::bound(&mut paint), Srgba::BLACK).ring(true).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
let well = fixture.by_role(Role::COLOR_WELL).first().copied().expect("the chip is a colour well").rect;
|
||||
assert!(well.width() > well.height(), "the chip is wider than it is high");
|
||||
// The hole is the smallest rect drawn round the well's centre.
|
||||
let hole = flat(fixture.frame_shapes())
|
||||
.into_iter()
|
||||
.filter_map(|shape| match shape {
|
||||
Shape::Rect(rect) => Some(rect.rect),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|rect: &Rect| rect.center().distance(well.center()) < 0.5 && rect.width() < well.width() - 2.0)
|
||||
.min_by(|a, b| a.area().total_cmp(&b.area()))
|
||||
.expect("a hole inside the band");
|
||||
assert!(hole.height() >= well.height() / 3.0, "the hole is {:?} in a {:?} well", hole.size(), well.size());
|
||||
let (side, top) = (hole.left() - well.left(), hole.top() - well.top());
|
||||
assert!((side - top).abs() < 0.5, "the band is {side} at the sides and {top} at the top");
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on the menu mark, past the well, opens the chip's popover, as a click on the well does.
|
||||
#[trial]
|
||||
fn a_click_on_the_menu_mark_opens_the_popover() {
|
||||
|
||||
@@ -7,15 +7,17 @@ use std::rc::Rc;
|
||||
use craft_behavior::{EditEvent, Mixed, Selection};
|
||||
use craft_color_ui::palette::{SwatchColor, SwatchGroup};
|
||||
use craft_color_ui::ui::{
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey,
|
||||
SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows,
|
||||
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel,
|
||||
PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState,
|
||||
SwatchesWords, swatch_rows,
|
||||
};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::{ColorModel as _, HsbModel, Srgba};
|
||||
use craft_ui::choice::SwatchTable;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::contract::tooltip::DELAY;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::{Label, Scale};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::testing::focus::AccessActionKind;
|
||||
@@ -254,6 +256,36 @@ fn the_fill_stroke_spectrums_tooltip_names_the_shown_mode_and_shift_click_cycles
|
||||
assert!(edits.borrow().is_empty(), "a Shift click picks nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// In a host sized by its content (a floating Color panel) the FillStroke spectrum is as tall as its end boxes stacked,
|
||||
/// each at least as tall as it is wide, not a thin band; in a short group it keeps that height and the body scrolls.
|
||||
#[trial]
|
||||
fn a_fill_stroke_spectrum_keeps_its_end_boxes_square_in_a_content_sized_host() {
|
||||
for (room, content_sized) in [(COLOR_ROOM, true), (Vec2::new(280.0, 96.0), false)] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let show = |ui: &mut egui::Ui, state: &mut ColorPanelState| {
|
||||
let _ = ColorPanel::new(Bind::bound(state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke).show(ui);
|
||||
};
|
||||
if content_sized {
|
||||
let _ = Stack::new().show(ui, |ui, _| show(ui, &mut state));
|
||||
} else {
|
||||
show(ui, &mut state);
|
||||
}
|
||||
});
|
||||
fixture.room(room).settle();
|
||||
let bar = fixture.by_label("Color Ramp").expect("the spectrum").rect;
|
||||
let ends: Vec<_> = fixture
|
||||
.by_role(Role::BUTTON)
|
||||
.into_iter()
|
||||
.filter(|button| button.rect.left() >= bar.right() - 0.5 && button.rect.y_range().intersects(bar.y_range()))
|
||||
.collect();
|
||||
assert_eq!(ends.len(), 2, "{room:?}: the white and black boxes beside the bar ({bar:?})");
|
||||
for end in ends {
|
||||
assert!(end.rect.height() >= end.rect.width() - 0.5, "{room:?}: an end box at least square ({:?} beside {bar:?})", end.rect);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SWATCHES: [(&str, [f32; 3]); 6] = [
|
||||
("Red", [0.90, 0.28, 0.30]),
|
||||
("Orange", [0.97, 0.42, 0.08]),
|
||||
@@ -408,6 +440,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() {
|
||||
assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::<Vec<_>>(), [swatch("Violet").to_rgba()], "and still reports the pick");
|
||||
}
|
||||
|
||||
/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in
|
||||
/// it; a host that gives no recent colors gets no row.
|
||||
#[trial]
|
||||
fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() {
|
||||
let caption = |recent: Option<&'static [Srgba]>| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut state = ColorPanelState::default();
|
||||
let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke);
|
||||
let _ = match recent {
|
||||
Some(colors) => panel.recent(colors),
|
||||
None => panel,
|
||||
}
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
fixture.texts().iter().any(|run| run.text == "Recent Colors")
|
||||
};
|
||||
assert!(caption(Some(&[])), "an empty list shows the row's caption");
|
||||
assert!(caption(Some(&RECENT)), "a list with a color shows it");
|
||||
assert!(!caption(None), "a host with no recent colors shows no row");
|
||||
}
|
||||
|
||||
/// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first;
|
||||
/// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`.
|
||||
#[trial]
|
||||
@@ -541,6 +595,30 @@ fn swatches_panel_reports_each_edit_and_leaves_the_library() {
|
||||
assert_eq!(state.rename, Some(SwatchKey::Swatch("Color Swatch 2".to_owned())), "the new swatch opens for renaming");
|
||||
}
|
||||
|
||||
/// A group with an empty name holds the swatches outside every group: they show at the top with no header, so no
|
||||
/// heading or disclosure button of the panel is left without a name, and a named group keeps its header.
|
||||
#[trial]
|
||||
fn swatches_outside_every_group_show_without_a_header() {
|
||||
let entry = |name: &str, rgb: [f32; 3]| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb(rgb));
|
||||
let groups = vec![
|
||||
SwatchGroup { name: String::new(), entries: vec![entry("Red", [1.0, 0.0, 0.0]), entry("Blue", [0.0, 0.0, 1.0])] },
|
||||
SwatchGroup { name: "Other".to_owned(), entries: vec![entry("Green", [0.0, 1.0, 0.0])] },
|
||||
];
|
||||
let (fixture, _) = swatches_rig(groups, SwatchesState::default());
|
||||
let tree = fixture.tree();
|
||||
let unnamed: Vec<_> = tree
|
||||
.keys()
|
||||
.into_iter()
|
||||
.filter(|&key| matches!(tree.role_of(key), Some(Role::HEADING | Role::BUTTON)))
|
||||
.filter(|&key| tree.name_of(key).is_none_or(|name| name.is_empty() || name.starts_with(',')))
|
||||
.map(|key| (tree.role_of(key), tree.name_of(key), tree.bounds_of(key)))
|
||||
.collect();
|
||||
assert!(unnamed.is_empty(), "every heading and button is named, starting with a label: {unnamed:?}");
|
||||
assert!(fixture.by_label("Red, #ff0000").is_some(), "the ungrouped swatches show");
|
||||
let headings: Vec<_> = tree.with_role(Role::HEADING).into_iter().filter_map(|key| tree.name_of(key)).collect();
|
||||
assert!(headings.iter().any(|name| name.starts_with("Other")), "a named group keeps its header: {headings:?}");
|
||||
}
|
||||
|
||||
/// Tb-8 (5): a click uses any swatch, as production applied every one: a colour swatch reports its colour, and a
|
||||
/// gradient, pattern or None swatch reports where it is with no colour, for the host to apply its paint. The panel
|
||||
/// reported only colour swatches.
|
||||
@@ -628,6 +706,34 @@ fn a_dragged_swatch_carries_the_hosts_payload_beside_the_panels_own_move() {
|
||||
assert_eq!(edits.borrow().len(), 1, "a drop outside the panel edits nothing: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
/// A panel shown for one document after another keeps a rename left open with its document: the other document's
|
||||
/// swatch of the same name opens no field, and Enter there renames nothing.
|
||||
#[trial]
|
||||
fn a_rename_left_open_stays_with_its_document() {
|
||||
let entry = |name: &str| craft_color_ui::palette::SwatchEntry::new(name.to_owned(), SwatchColor::Rgb([1.0, 0.0, 0.0]));
|
||||
let groups = vec![SwatchGroup { name: "Basics".to_owned(), entries: vec![entry("Red"), entry("Rose")] }];
|
||||
let document = Rc::new(Cell::new(1_u32));
|
||||
let edits = Rc::new(RefCell::new(Vec::new()));
|
||||
let (shown, seen) = (Rc::clone(&document), Rc::clone(&edits));
|
||||
let mut state = SwatchesState::default();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = SwatchesPanel::new(&groups, Bind::bound(&mut state), RED).document(shown.get()).show(ui);
|
||||
seen.borrow_mut().extend(out.edits);
|
||||
});
|
||||
fixture.room(Vec2::new(320.0, 400.0)).settle();
|
||||
let red = fixture.by_label("Red, #ff0000").expect("the Red swatch");
|
||||
fixture.click(&red).key(Key::F2, Modifiers::NONE).type_text("X").settle();
|
||||
let typed = |fixture: &Fixture, text: &str| {
|
||||
let tree = fixture.tree();
|
||||
tree.keys().into_iter().any(|key| tree.value_of(key) == Some(text))
|
||||
};
|
||||
assert!(typed(&fixture, "X"), "the rename field is open in the first document");
|
||||
document.set(2);
|
||||
fixture.settle();
|
||||
fixture.type_text("Y").key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert!(!edits.borrow().iter().any(|edit| matches!(edit, SwatchEdit::Rename { .. })), "nothing is renamed: {:?}", edits.borrow());
|
||||
}
|
||||
|
||||
fn table_entries(count: usize) -> Vec<(Label, Srgba)> {
|
||||
(0..count).map(|i| (Label::from(format!("Index {i}")), Srgba::rgb(i as f32 / count as f32, 0.5, 0.25))).collect()
|
||||
}
|
||||
@@ -768,3 +874,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() {
|
||||
fixture.click(&marker).idle(1);
|
||||
assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker");
|
||||
}
|
||||
|
||||
/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its
|
||||
/// right edge.
|
||||
#[trial]
|
||||
fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default());
|
||||
let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui);
|
||||
});
|
||||
fixture.room(COLOR_ROOM).settle();
|
||||
let grid = fixture.by_label("Variations").expect("the variations grid").rect;
|
||||
let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted"));
|
||||
let (shades, tints) = (run("Shades"), run("Tints"));
|
||||
assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}");
|
||||
assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}");
|
||||
}
|
||||
@@ -32,6 +32,10 @@ craft-flags = { workspace = true, optional = true }
|
||||
dirs = { version = "7", optional = true }
|
||||
log = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours).
|
||||
craft-platform = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
tempfile = "3"
|
||||
|
||||
+268
-119
@@ -101,7 +101,7 @@ impl App {
|
||||
/// Record `port` as the running app's, readable only by the user like the token files.
|
||||
pub fn write_current_port(&self, port: u16) -> Result<PathBuf> {
|
||||
let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?;
|
||||
self.write_token_file(&path, &port.to_string())?;
|
||||
self.write_private(&path, &port.to_string(), true)?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -141,16 +141,27 @@ impl App {
|
||||
}
|
||||
|
||||
/// Write `token` to `path`, readable and writable only by the user: the folder is made `0700`
|
||||
/// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one
|
||||
/// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file
|
||||
/// is removed and no token is written. A file left by an earlier launch is replaced. The process
|
||||
/// file beside it ([`pid_path`]) records this process, best effort.
|
||||
/// and the file `0600` on Unix; on Windows the file is created with an access list of the user
|
||||
/// and SYSTEM only and the token is written through the handle that created it
|
||||
/// (`create_for_user`), so the file never has its folder's access list. A file left by an
|
||||
/// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process,
|
||||
/// best effort.
|
||||
pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> {
|
||||
self.write_private(path, token, false)
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while
|
||||
/// this one was being created is replaced (the discovery file, which names the latest launch);
|
||||
/// otherwise this write fails and that launch's token stays.
|
||||
fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some());
|
||||
let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace);
|
||||
#[cfg(not(windows))]
|
||||
let restrict = |_: &Path| Ok(());
|
||||
write_token_file_with(path, token, restrict)
|
||||
let create = {
|
||||
let _ = replace;
|
||||
create_new_file
|
||||
};
|
||||
write_token_file_with(path, token, create)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows).
|
||||
fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> {
|
||||
/// [`App::write_token_file`], with `create` making the new file with its contents, readable only
|
||||
/// by the user.
|
||||
fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> {
|
||||
let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?;
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let _ = std::fs::remove_file(path);
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let opened = opts.open(path)?;
|
||||
// On a refusal the file goes with the closure, so it is closed before it is removed.
|
||||
let mut f = match restrict(path).map(|()| opened) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(path);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
f.write_all(token.as_bytes())?;
|
||||
f.write_all(b"\n")?;
|
||||
f.sync_all()?;
|
||||
create(path, format!("{token}\n").as_bytes())?;
|
||||
let pid = std::process::id();
|
||||
let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n"));
|
||||
let _ = std::fs::write(pid_path(path), line);
|
||||
@@ -369,74 +367,148 @@ fn held_by_another(path: &Path, token: &str) -> bool {
|
||||
read_token(path).is_some_and(|held| !tokens_match(&held, token.trim()))
|
||||
}
|
||||
|
||||
/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process
|
||||
/// is left suspended (security software holding it), and waiting on it without a limit froze
|
||||
/// the app.
|
||||
#[cfg(windows)]
|
||||
const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// How a run of `icacls` ended.
|
||||
#[cfg(any(windows, test))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum IcaclsEnd {
|
||||
Succeeded,
|
||||
Failed,
|
||||
/// It didn't finish within [`ICACLS_LIMIT`] and was ended.
|
||||
TimedOut,
|
||||
/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a
|
||||
/// file created this way has its folder's access list; the token file there is made by
|
||||
/// `create_for_user`.
|
||||
fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.mode(0o600);
|
||||
}
|
||||
let mut f = opts.open(path)?;
|
||||
f.write_all(contents)?;
|
||||
f.sync_all()
|
||||
}
|
||||
|
||||
/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is
|
||||
/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder,
|
||||
/// the user's own local app data, which other users can't read by default; nothing is known about
|
||||
/// the permissions of any other folder.
|
||||
/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell;
|
||||
/// on some computers a new process is left suspended (security software holding it), and waiting
|
||||
/// on it without a limit froze the app.
|
||||
#[cfg(windows)]
|
||||
const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
|
||||
/// Windows: create `path` with the current user as owner and an access list of that user and
|
||||
/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written
|
||||
/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`.
|
||||
/// Another account never gets a moment in which the file has its folder's access list and could be
|
||||
/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names;
|
||||
/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and
|
||||
/// what `replace` changes.
|
||||
#[cfg(windows)]
|
||||
fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> {
|
||||
use craft_platform::owner_only;
|
||||
/// How many creates that were not waited for are still running.
|
||||
static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c));
|
||||
create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0
|
||||
}
|
||||
|
||||
/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names
|
||||
/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that
|
||||
/// folder's permissions; in the default folder, the user's own local app data, which other users
|
||||
/// can't read by default, `path` created with that folder's access list ([`create_new_file`]).
|
||||
#[cfg(any(windows, test))]
|
||||
fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> {
|
||||
match end {
|
||||
IcaclsEnd::Succeeded => Ok(()),
|
||||
IcaclsEnd::TimedOut if !custom_folder => Ok(()),
|
||||
IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))),
|
||||
IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))),
|
||||
fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> {
|
||||
if custom_folder {
|
||||
Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display())))
|
||||
} else {
|
||||
create_new_file(path, contents)
|
||||
}
|
||||
}
|
||||
|
||||
/// Windows: drop inherited entries and grant only the current user full access. An `icacls`
|
||||
/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means.
|
||||
#[cfg(windows)]
|
||||
fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?;
|
||||
let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty());
|
||||
let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}"));
|
||||
let child = std::process::Command::new("icacls")
|
||||
.arg(path)
|
||||
.args(["/inheritance:r", "/grant:r", &format!("{who}:F")])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.creation_flags(0x0800_0000)
|
||||
.spawn()?;
|
||||
let end = match wait_within(child, ICACLS_LIMIT)? {
|
||||
Some(status) if status.success() => IcaclsEnd::Succeeded,
|
||||
Some(_) => IcaclsEnd::Failed,
|
||||
None => IcaclsEnd::TimedOut,
|
||||
/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its
|
||||
/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path`
|
||||
/// (`.<name>.<process id>.<count>.tmp`), and the file takes the name `path` only once `private`
|
||||
/// has finished, so `path` never holds a file that is still being written: with `replace` by a
|
||||
/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`],
|
||||
/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool
|
||||
/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result.
|
||||
/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its
|
||||
/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any
|
||||
/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that
|
||||
/// leaves new processes suspended holds at most the threads that were started together. The
|
||||
/// thread's handle is returned for tests.
|
||||
#[cfg(any(windows, test))]
|
||||
fn create_within(
|
||||
path: &Path,
|
||||
contents: &[u8],
|
||||
custom_folder: bool,
|
||||
replace: bool,
|
||||
limit: std::time::Duration,
|
||||
stuck: &'static std::sync::atomic::AtomicUsize,
|
||||
private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static,
|
||||
) -> (Result<()>, Option<std::thread::JoinHandle<()>>) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{RecvTimeoutError, channel};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
/// Numbers the thread's files within this process.
|
||||
static COUNT: AtomicU64 = AtomicU64::new(0);
|
||||
if stuck.load(Ordering::Acquire) > 0 {
|
||||
return (not_waited_for(path, contents, custom_folder), None);
|
||||
}
|
||||
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed)));
|
||||
let (sender, receiver) = channel();
|
||||
// Set under the lock when the caller stops waiting; the thread reads it under the same lock
|
||||
// before it reports, so its result is either received or its file is removed.
|
||||
let abandoned = Arc::new(Mutex::new(false));
|
||||
let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned));
|
||||
let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || {
|
||||
let made = private(&own_file, &owned_contents);
|
||||
let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if *abandoned {
|
||||
let _ = std::fs::remove_file(&own_file);
|
||||
stuck.fetch_sub(1, Ordering::AcqRel);
|
||||
} else {
|
||||
let _ = sender.send(made);
|
||||
}
|
||||
});
|
||||
let handle = match spawned {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => return (Err(e), None),
|
||||
};
|
||||
restriction_result(end, custom_folder, path)
|
||||
let made = match receiver.recv_timeout(limit) {
|
||||
Ok(made) => made,
|
||||
Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))),
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match receiver.try_recv() {
|
||||
Ok(made) => made,
|
||||
Err(_) => {
|
||||
*abandoned = true;
|
||||
stuck.fetch_add(1, Ordering::AcqRel);
|
||||
drop(abandoned);
|
||||
return (not_waited_for(path, contents, custom_folder), Some(handle));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let placed = match made {
|
||||
// `owner_only` ended a tool that ran out of its own time: the same as not waiting.
|
||||
Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder),
|
||||
made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }),
|
||||
};
|
||||
let _ = std::fs::remove_file(&staged);
|
||||
(placed, Some(handle))
|
||||
}
|
||||
|
||||
/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it
|
||||
/// hasn't finished by then.
|
||||
/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch
|
||||
/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a
|
||||
/// `create_new` there would, instead of replacing the first one's token. The new name is a hard
|
||||
/// link. On a volume without hard links the file is renamed once `path` is found free; there a
|
||||
/// launch that puts its file at `path` between that check and the rename has it replaced, as std
|
||||
/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the
|
||||
/// caller to remove.
|
||||
#[cfg(any(windows, test))]
|
||||
fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result<Option<std::process::ExitStatus>> {
|
||||
let start = std::time::Instant::now();
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
return Ok(Some(status));
|
||||
fn place_new(staged: &Path, path: &Path) -> Result<()> {
|
||||
match std::fs::hard_link(staged, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => {
|
||||
Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display())))
|
||||
}
|
||||
if start.elapsed() >= limit {
|
||||
// Not waited for afterwards: a suspended process may not end at once.
|
||||
let _ = child.kill();
|
||||
return Ok(None);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
Err(_) => std::fs::rename(staged, path),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -456,50 +528,127 @@ mod tests {
|
||||
/// An app with no data folder and no environment, whose times read `t<seconds>`.
|
||||
const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 };
|
||||
|
||||
/// #6145: a child that doesn't finish in time is given up on, not waited for forever.
|
||||
#[cfg(unix)]
|
||||
/// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder
|
||||
/// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created
|
||||
/// anyway and holds the token. Either way the file the late create makes is removed when it
|
||||
/// finishes and never takes the token file's name, even when a later write has put a file
|
||||
/// there. While it runs, the next create starts no thread of its own. A create that finishes in
|
||||
/// time puts its file in place unless a file already has the name, and one that fails leaves
|
||||
/// nothing. A create that fails as timed out by itself is taken as one not waited for.
|
||||
#[test]
|
||||
fn a_slow_child_is_waited_for_only_so_long() {
|
||||
use std::time::{Duration, Instant};
|
||||
let start = Instant::now();
|
||||
let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap();
|
||||
assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none());
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
let quick = std::process::Command::new("true").spawn().unwrap();
|
||||
assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success()));
|
||||
let failing = std::process::Command::new("false").spawn().unwrap();
|
||||
assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success()));
|
||||
}
|
||||
|
||||
/// #6145's freeze fix stays in the default folder, the user's own; a folder picked with
|
||||
/// the app's `CONTROL_DIR` gets no token unless the file was really restricted.
|
||||
#[test]
|
||||
fn only_the_default_folder_accepts_an_icacls_that_timed_out() {
|
||||
let path = Path::new("control/7878.token");
|
||||
for custom in [false, true] {
|
||||
assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok());
|
||||
assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err());
|
||||
fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Duration;
|
||||
static STUCK: AtomicUsize = AtomicUsize::new(0);
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let names = || {
|
||||
let mut names: Vec<String> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
names.sort();
|
||||
names
|
||||
};
|
||||
for custom in [true, false] {
|
||||
let path = dir.join("7878.port");
|
||||
let (go, wait) = channel::<()>();
|
||||
let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| {
|
||||
wait.recv().map_err(Error::other)?;
|
||||
create_new_file(p, c)
|
||||
});
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 1);
|
||||
if custom {
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists());
|
||||
let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") };
|
||||
let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused);
|
||||
assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
assert!(none.is_none());
|
||||
// A later write of the same contents, as a retry of the same port would make.
|
||||
create_new_file(&path, b"7878\n").unwrap();
|
||||
} else {
|
||||
made.unwrap();
|
||||
}
|
||||
go.send(()).unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
assert_eq!(names(), ["7878.port"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("7878"));
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok());
|
||||
let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(e.to_string().contains("7878.token"), "{e}");
|
||||
let path = dir.join("quick.token");
|
||||
let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// Another launch's file at the name is kept, as `create_new` keeps it.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("quick"));
|
||||
// With `replace` (the discovery file) the later launch's file takes the name.
|
||||
let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("later"));
|
||||
let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) };
|
||||
let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused);
|
||||
assert!(made.is_err());
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
// A create whose tool was ended after its own limit, within this one, is taken as one
|
||||
// that was not waited for.
|
||||
let ended =
|
||||
|_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) };
|
||||
let path = dir.join("ended.token");
|
||||
let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended);
|
||||
assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut);
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["quick.token"]);
|
||||
let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended);
|
||||
made.unwrap();
|
||||
handle.unwrap().join().unwrap();
|
||||
assert_eq!(names(), ["ended.token", "quick.token"]);
|
||||
assert_eq!(read_token(&path).as_deref(), Some("ended"));
|
||||
assert_eq!(STUCK.load(Ordering::Acquire), 0);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A file that couldn't be restricted is removed, empty and with no process file beside it, and
|
||||
/// the error goes to the caller. A restricted one gets its token.
|
||||
/// A file that couldn't be created leaves no process file beside it, and the error goes to the
|
||||
/// caller. A created one gets the token and a newline.
|
||||
#[test]
|
||||
fn a_token_file_that_could_not_be_restricted_is_removed() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id()));
|
||||
fn a_token_file_that_could_not_be_created_leaves_nothing() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id()));
|
||||
let path = dir.join("7879.token");
|
||||
let e = write_token_file_with(&path, "secret-token", |p| {
|
||||
assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in");
|
||||
restriction_result(IcaclsEnd::TimedOut, true, p)
|
||||
})
|
||||
.unwrap_err();
|
||||
let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err();
|
||||
assert_eq!(e.kind(), ErrorKind::TimedOut);
|
||||
assert!(!path.exists() && !pid_path(&path).exists());
|
||||
write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap();
|
||||
write_token_file_with(&path, "secret-token", create_new_file).unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n");
|
||||
assert!(pid_path(&path).exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// On Windows the token file is its user's alone from the moment it exists: in a folder that
|
||||
/// lets Users read what is created in it, the file has no entry for Users and no other
|
||||
/// account's access.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_token_file_is_private_from_the_start_on_windows() {
|
||||
use craft_platform::owner_only;
|
||||
let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
|
||||
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
|
||||
let path = dir.join("7880.token");
|
||||
TEST.write_token_file(&path, "secret-token").unwrap();
|
||||
let sddl = owner_only::sddl_of(&path).unwrap();
|
||||
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
|
||||
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
|
||||
assert_eq!(read_token(&path).as_deref(), Some("secret-token"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
@@ -228,6 +229,7 @@ craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
craft-audio-dsp = { workspace = true, optional = true }
|
||||
craft-sbs = { workspace = true, optional = true }
|
||||
craft-shared-vec = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ui = [
|
||||
@@ -500,6 +502,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"]
|
||||
|
||||
@@ -801,6 +805,9 @@ settings-testing = ["settings", "craft-settings/testing"]
|
||||
sf2 = ["dep:craft-sf2"]
|
||||
sf2-test-support = ["sf2", "craft-sf2/test-support"]
|
||||
|
||||
shared-vec = ["dep:craft-shared-vec"]
|
||||
shared-vec-serde = ["shared-vec", "craft-shared-vec/serde"]
|
||||
|
||||
sheet = ["dep:craft-sheet"]
|
||||
|
||||
shx = ["dep:craft-shx"]
|
||||
@@ -939,6 +946,7 @@ ui-system_fonts = ["ui", "craft-ui/system_fonts"]
|
||||
ui-testing = ["ui", "craft-ui/testing"]
|
||||
|
||||
update = ["dep:craft-update"] # native only: downloads and installs through getrandom without wasm support
|
||||
update-local-mirror = ["update", "craft-update/local-mirror"]
|
||||
update-oci_migration = ["update", "craft-update/oci_migration"]
|
||||
|
||||
usd = ["dep:craft-usd"]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
/// The egui fork the library is built and tested with. Apps patch egui to exactly this.
|
||||
pub const GIT: &str = "https://github.com/storytold/egui.git";
|
||||
/// The commit of [`GIT`].
|
||||
pub const REV: &str = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec";
|
||||
pub const REV: &str = "b9770908e0f304896f9658d239a7b29cf8af1564";
|
||||
|
||||
/// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]).
|
||||
pub const PACKAGES: &[&str] = &[
|
||||
|
||||
@@ -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")]
|
||||
@@ -331,6 +333,8 @@ pub use craft_scraft_format as scraft_format;
|
||||
pub use craft_settings as settings;
|
||||
#[cfg(feature = "sf2")]
|
||||
pub use craft_sf2 as sf2;
|
||||
#[cfg(feature = "shared-vec")]
|
||||
pub use craft_shared_vec as shared_vec;
|
||||
#[cfg(feature = "sheet")]
|
||||
pub use craft_sheet as sheet;
|
||||
#[cfg(feature = "shx")]
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
/// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member.
|
||||
pub const NOT_IN_FACADE: &[(&str, &str)] = &[
|
||||
("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"),
|
||||
("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"),
|
||||
("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"),
|
||||
("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"),
|
||||
("fonts-build", "a build-script helper; apps call it from build.rs"),
|
||||
|
||||
@@ -31,13 +31,14 @@ serde_json = { workspace = true, optional = true }
|
||||
rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] }
|
||||
|
||||
# The file-dialog probe asks the session bus whether the desktop portal offers a file chooser.
|
||||
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`). rfd and winit already
|
||||
# use these.
|
||||
# The free-standing Open and Folder panel (`beginWithCompletionHandler:`), and the Save sheet with a
|
||||
# Format menu (`beginSheetModalForWindow:completionHandler:`). rfd and winit already use these.
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
block2 = "0.6.2"
|
||||
craft-appkit = { workspace = true }
|
||||
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] }
|
||||
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSAccessibilityProtocols", "NSApplication", "NSButton", "NSControl", "NSOpenPanel", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSText", "NSTextField", "NSView", "NSWindow", "objc2-core-foundation"] }
|
||||
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSString", "NSURL", "objc2-core-foundation"] }
|
||||
|
||||
# The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked.
|
||||
# The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the
|
||||
|
||||
@@ -44,7 +44,7 @@ pub type Override = Box<dyn FnMut(&Request) -> Answer>;
|
||||
|
||||
pub enum Kind { Open { multiple: bool }, Folder, Save }
|
||||
pub struct FileDialog { pub kind: Kind, pub title: Option<String>, pub filters: Vec<Filter>,
|
||||
pub directory: Option<PathBuf>, pub file_name: Option<String> }
|
||||
pub directory: Option<PathBuf>, pub file_name: Option<String>, pub format_label: Option<String> }
|
||||
pub struct Filter { pub name: String, pub extensions: Vec<String> }
|
||||
pub struct Message { pub level: MessageLevel, pub title: String, pub description: String,
|
||||
pub buttons: MessageButtons }
|
||||
@@ -66,7 +66,7 @@ impl<T> Dialogs<T> {
|
||||
```
|
||||
|
||||
`FileDialog` has builders: `FileDialog::open().title("Place").filter("Images", &["png", "jpg"])`,
|
||||
and `open_many`, `folder`, `save`, `directory`, `file_name`.
|
||||
and `open_many`, `folder`, `save`, `directory`, `file_name`, `format_label`.
|
||||
|
||||
In an eframe app:
|
||||
|
||||
@@ -127,6 +127,12 @@ they start only with a parent in a running app, and answer `Unavailable` otherwi
|
||||
before the event loop starts or after it ends (startup and crash messages) stay blocking `rfd`
|
||||
calls in the app.
|
||||
|
||||
A Save that offers two or more file types is a sheet the crate makes itself, with a Format menu
|
||||
that lists each type by name, the suggested name's type chosen. Choosing a type changes the
|
||||
extension in the name field, and the answer is `Saved` with the chosen type's index in `filter`.
|
||||
The menu's label is `FileDialog::format_label`, set from `FilePanels::set_format_label` (English
|
||||
"Format:" when unset). A Save with one type is rfd's sheet, which has no menu.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- Linux portal Save (`org.freedesktop.portal.FileChooser.SaveFile`), so the file type the user
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The Format menu of a macOS Save panel with two or more file types: which types it lists, which one is chosen
|
||||
//! when the panel opens, the name a choice gives the file and the extensions the panel then allows. Plain rules on
|
||||
//! names and filters, so they are tested on every platform; `macos.rs` shows the menu.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::Filter;
|
||||
use crate::service::normal;
|
||||
|
||||
/// The indices into `filters` of the file types the menu lists, in order: types with an extension other than `*`.
|
||||
/// Empty when fewer than two remain: the panel then has no menu.
|
||||
pub(crate) fn entries(filters: &[Filter]) -> Vec<usize> {
|
||||
let listed: Vec<usize> = filters
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| f.extensions.iter().any(|e| !normal(e).is_empty()) && !f.extensions.iter().any(|e| normal(e) == "*"))
|
||||
.map(|(at, _)| at)
|
||||
.collect();
|
||||
if listed.len() < 2 { Vec::new() } else { listed }
|
||||
}
|
||||
|
||||
/// The menu's item titles for `entries`, one per entry and all different: a pop-up menu keeps one item per title, so
|
||||
/// a name that repeats gets its extensions after it (`Document (docx)`), and a title that still matches an earlier
|
||||
/// title or another type's name gets a number after it.
|
||||
pub(crate) fn titles(filters: &[Filter], entries: &[usize]) -> Vec<String> {
|
||||
let names: Vec<&str> = entries.iter().map(|&at| filters.get(at).map_or("", |f| f.name.as_str())).collect();
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for (&at, name) in entries.iter().zip(&names) {
|
||||
let mut base = (*name).to_owned();
|
||||
if names.iter().filter(|n| *n == name).count() > 1 {
|
||||
let extensions: Vec<String> = filters.get(at).map(|f| f.extensions.iter().map(|e| normal(e)).collect()).unwrap_or_default();
|
||||
base = format!("{name} ({})", extensions.join(", "));
|
||||
}
|
||||
let taken = |title: &str| out.iter().any(|t| t == title) || (title != *name && names.contains(&title));
|
||||
let mut title = base.clone();
|
||||
let mut number = 2;
|
||||
while taken(&title) {
|
||||
title = format!("{base} {number}");
|
||||
number += 1;
|
||||
}
|
||||
out.push(title);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The file type a Save answer reports, as an index into `filters`: the one chosen in the menu (menu position
|
||||
/// `chosen`), unless the name the panel returned ends in an extension that only another listed type has: the user
|
||||
/// typed it, and the file is saved in that type. `kept` is the name the field still showed when the last choice could
|
||||
/// not rename it. A returned name equal to it that still has the extension of the name the panel opened with
|
||||
/// (`opened_with`) keeps the chosen type: the save flow gives a name with the opened extension the chosen type's
|
||||
/// extension (`with_chosen_type`). Any other extension stays on the name, so the type reported is the one the name has.
|
||||
pub(crate) fn answered_type(
|
||||
returned: &str,
|
||||
kept: Option<&str>,
|
||||
opened_with: Option<&str>,
|
||||
filters: &[Filter],
|
||||
entries: &[usize],
|
||||
chosen: usize,
|
||||
) -> Option<usize> {
|
||||
let chosen = entries.get(chosen).copied()?;
|
||||
let Some(ext) = extension(returned) else { return Some(chosen) };
|
||||
let kept_opened = kept == Some(returned) && opened_with.and_then(extension).as_ref() == Some(&ext);
|
||||
if filters.get(chosen).is_some_and(|f| lists(f, &ext)) || kept_opened {
|
||||
return Some(chosen);
|
||||
}
|
||||
Some(entries.iter().copied().find(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(chosen))
|
||||
}
|
||||
|
||||
/// The menu position chosen when the panel opens: the type whose extensions include `name`'s, else the first.
|
||||
pub(crate) fn initial(name: &str, filters: &[Filter], entries: &[usize]) -> usize {
|
||||
let Some(ext) = extension(name) else { return 0 };
|
||||
entries.iter().position(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The name the panel shows once `chosen` is picked: an extension `chosen` lists stays; one that another of
|
||||
/// `filters` lists becomes `chosen`'s first; any other is part of the name (`art.v2`), and `chosen`'s first extension
|
||||
/// is added after it. An empty name stays empty.
|
||||
pub(crate) fn renamed(name: &str, chosen: &Filter, filters: &[Filter]) -> String {
|
||||
let Some(first) = chosen.extensions.iter().map(|e| normal(e)).find(|e| !e.is_empty()) else { return name.to_owned() };
|
||||
if name.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
match extension(name) {
|
||||
Some(ext) if lists(chosen, &ext) => name.to_owned(),
|
||||
Some(ext) if filters.iter().any(|f| lists(f, &ext)) => Path::new(name).with_extension(first).to_string_lossy().into_owned(),
|
||||
_ => format!("{name}.{first}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The extensions the panel allows with menu position `selected` chosen: that type's first, so that AppKit adds it
|
||||
/// to a name typed without one, then the other listed types', so that a name typed with one of theirs is kept.
|
||||
pub(crate) fn allowed(filters: &[Filter], entries: &[usize], selected: usize) -> Vec<String> {
|
||||
let chosen = entries.get(selected).copied();
|
||||
let order = chosen.into_iter().chain(entries.iter().copied().filter(|&at| Some(at) != chosen));
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for ext in order.filter_map(|at| filters.get(at)).flat_map(|f| f.extensions.iter().map(|e| normal(e))) {
|
||||
if !ext.is_empty() && !out.contains(&ext) {
|
||||
out.push(ext);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name`'s extension as compared, if it has one.
|
||||
fn extension(name: &str) -> Option<String> {
|
||||
Path::new(name).extension().and_then(|e| e.to_str()).map(normal)
|
||||
}
|
||||
|
||||
/// Whether `filter` lists `ext` (already [`normal`]).
|
||||
fn lists(filter: &Filter, ext: &str) -> bool {
|
||||
filter.extensions.iter().any(|e| normal(e) == ext)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -0,0 +1,110 @@
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn filters() -> Vec<Filter> {
|
||||
vec![Filter::new("Document", &["doc"]), Filter::new("Drawing", &["ai"]), Filter::new("Picture", &["jpg", "jpeg"])]
|
||||
}
|
||||
|
||||
/// The menu lists the types with an extension; "every file" types and ones without an extension stay out, and a
|
||||
/// panel left with one type gets no menu.
|
||||
#[trial]
|
||||
fn the_menu_lists_types_with_extensions_and_needs_two() {
|
||||
assert_eq!(entries(&filters()), [0, 1, 2]);
|
||||
let mixed = [Filter::new("Document", &["doc"]), Filter::new("All files", &["*"]), Filter::new("Any", &[]), Filter::new("Drawing", &[".ai"])];
|
||||
assert_eq!(entries(&mixed), [0, 3], "the dot is not part of the extension");
|
||||
assert!(entries(&[Filter::new("Document", &["doc"]), Filter::new("All files", &["*"])]).is_empty());
|
||||
assert!(entries(&[]).is_empty());
|
||||
}
|
||||
|
||||
/// Two types with one name both stay in the menu, under different titles; other titles are the names.
|
||||
#[trial]
|
||||
fn types_that_share_a_name_get_different_titles() {
|
||||
let twice = [Filter::new("Document", &["doc"]), Filter::new("Document", &["docx"]), Filter::new("Drawing", &["ai"])];
|
||||
let listed = entries(&twice);
|
||||
assert_eq!(listed, [0, 1, 2]);
|
||||
let shown = titles(&twice, &listed);
|
||||
assert_eq!(shown.len(), listed.len());
|
||||
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
|
||||
assert_eq!(shown[2], "Drawing");
|
||||
for set in [
|
||||
vec![Filter::new("Document", &["doc"]), Filter::new("Document", &["doc"])],
|
||||
vec![Filter::new("X (x) 2", &["a"]), Filter::new("X", &["x"]), Filter::new("X", &["x"])],
|
||||
vec![Filter::new("X", &["x"]), Filter::new("X", &["x"]), Filter::new("X (x) 2", &["a"]), Filter::new("X (x)", &["b"])],
|
||||
] {
|
||||
let shown = titles(&set, &entries(&set));
|
||||
assert_eq!(shown.len(), set.len());
|
||||
assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer reports the chosen type, unless the user typed another listed type's extension; a name the panel kept
|
||||
/// when a choice could not rename it keeps the chosen type.
|
||||
#[trial]
|
||||
fn a_typed_extension_of_another_type_is_the_type_saved() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
let (kept, opened) = (Some("Untitled-1.doc"), Some("Untitled-1.doc"));
|
||||
let answer = |returned, kept| answered_type(returned, kept, opened, &all, &listed, 1);
|
||||
assert_eq!(answer("Untitled-1.ai", None), Some(1));
|
||||
assert_eq!(answer("Untitled-1.doc", kept), Some(1), "the panel kept the opened name");
|
||||
assert_eq!(answer("Other.doc", kept), Some(0), "the user typed a new name after that");
|
||||
assert_eq!(answer("Untitled-1.doc", None), Some(0), "the user typed the first type's extension back");
|
||||
assert_eq!(answer("photo.JPEG", kept), Some(2), "the user typed another type's extension");
|
||||
assert_eq!(answer("Other.doc", Some("Other.doc")), Some(1), "a kept name with the opened extension");
|
||||
assert_eq!(answer("Other.jpg", Some("Other.jpg")), Some(2), "a kept name with another type's extension keeps that type");
|
||||
assert_eq!(answer("notes.v2", None), Some(1));
|
||||
assert_eq!(answer("art", None), Some(1));
|
||||
assert_eq!(answered_type("art.ai", None, opened, &all, &listed, 9), None, "a position the menu doesn't have");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_suggested_name_chooses_its_type_and_any_other_the_first() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
for (name, at) in [("Untitled-1.doc", 0), ("art.AI", 1), ("photo.jpeg", 2), ("Untitled-1", 0), ("notes.v2", 0), ("", 0)] {
|
||||
assert_eq!(initial(name, &all, &listed), at, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Choosing a type replaces the extension of another listed type, keeps one of its own and adds its own after any
|
||||
/// other dot in the name.
|
||||
#[trial]
|
||||
fn choosing_a_type_gives_the_name_its_extension() {
|
||||
let all = filters();
|
||||
let drawing = &all[1];
|
||||
for (name, expected) in [
|
||||
("Untitled-1.doc", "Untitled-1.ai"),
|
||||
("Plan 1.DOC", "Plan 1.ai"),
|
||||
("photo.jpeg", "photo.ai"),
|
||||
("art.ai", "art.ai"),
|
||||
("art.AI", "art.AI"),
|
||||
("art", "art.ai"),
|
||||
("art.v2", "art.v2.ai"),
|
||||
("", ""),
|
||||
] {
|
||||
assert_eq!(renamed(name, drawing, &all), expected, "{name}");
|
||||
}
|
||||
assert_eq!(renamed("photo.jpeg", &all[2], &all), "photo.jpeg", "a second extension of the chosen type stays");
|
||||
}
|
||||
|
||||
/// A sequence of choices (A to B to C) ends with C's extension, and back to A gives A's.
|
||||
#[trial]
|
||||
fn each_choice_follows_the_previous_one() {
|
||||
let all = filters();
|
||||
let mut name = "Untitled-1.doc".to_owned();
|
||||
for (at, ext) in [(1, "ai"), (2, "jpg"), (0, "doc")] {
|
||||
name = renamed(&name, &all[at], &all);
|
||||
assert_eq!(Path::new(&name).extension().and_then(|e| e.to_str()), Some(ext));
|
||||
assert_eq!(Path::new(&name).file_stem().and_then(|e| e.to_str()), Some("Untitled-1"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen type's extension comes first, so AppKit adds it to a bare name; the others stay allowed.
|
||||
#[trial]
|
||||
fn the_chosen_type_is_allowed_first() {
|
||||
let all = filters();
|
||||
let listed = entries(&all);
|
||||
assert_eq!(allowed(&all, &listed, 0), ["doc", "ai", "jpg", "jpeg"]);
|
||||
assert_eq!(allowed(&all, &listed, 1), ["ai", "doc", "jpg", "jpeg"]);
|
||||
assert_eq!(allowed(&all, &listed, 2), ["jpg", "jpeg", "doc", "ai"]);
|
||||
}
|
||||
@@ -20,6 +20,8 @@
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod filter;
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
mod format_menu;
|
||||
mod native;
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
pub(crate) mod portal;
|
||||
@@ -92,12 +94,18 @@ pub struct FileDialog {
|
||||
pub directory: Option<PathBuf>,
|
||||
/// The file name a Save dialog suggests.
|
||||
pub file_name: Option<String>,
|
||||
/// The label of the file type menu a macOS Save panel with two or more file types shows; `None` shows
|
||||
/// [`FORMAT_LABEL`]. Other platforms' dialogs label their menu themselves.
|
||||
pub format_label: Option<String>,
|
||||
}
|
||||
|
||||
/// The English label of the macOS Save panel's file type menu.
|
||||
pub const FORMAT_LABEL: &str = "Format:";
|
||||
|
||||
impl FileDialog {
|
||||
/// A dialog of `kind` with nothing else set.
|
||||
pub fn new(kind: Kind) -> Self {
|
||||
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None }
|
||||
Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None, format_label: None }
|
||||
}
|
||||
|
||||
/// Choose one existing file.
|
||||
@@ -143,6 +151,12 @@ impl FileDialog {
|
||||
self.file_name = Some(file_name.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the label of the macOS Save panel's file type menu, in the app's language.
|
||||
pub fn format_label(mut self, label: impl Into<String>) -> Self {
|
||||
self.format_label = Some(label.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The icon a message box shows.
|
||||
@@ -223,7 +237,7 @@ pub enum Answer {
|
||||
/// The chosen files or folder.
|
||||
Paths(Vec<PathBuf>),
|
||||
/// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's
|
||||
/// current filter; rfd reports `None`).
|
||||
/// current filter, or the macOS panel's Format menu; rfd reports `None`).
|
||||
Saved {
|
||||
/// The name as typed.
|
||||
path: PathBuf,
|
||||
|
||||
+142
-8
@@ -6,22 +6,29 @@
|
||||
//! rfd can't show this panel: its async dialogs always begin a sheet, on the main or first window
|
||||
//! when no parent is given (rfd 0.17.2 `backend/macos/modal_future.rs:71-102`).
|
||||
//!
|
||||
//! Save and message boxes are sheets on the parent window through rfd, as native apps show them.
|
||||
//! rfd falls back to the blocking `runModal` when the app isn't running or has no window
|
||||
//! (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
|
||||
//! Save and message boxes are sheets on the parent window, as native apps show them. A Save that
|
||||
//! offers two or more file types is a sheet made here ([`show_save_sheet`]), with a Format menu:
|
||||
//! rfd's Save panel lists the extensions of every type and has no menu to choose one
|
||||
//! (rfd 0.17.2 `backend/macos/file_dialog/panel_ffi.rs:107-120`). Other Saves and message boxes
|
||||
//! are rfd's sheets. rfd falls back to the blocking `runModal` when the app isn't running or has no
|
||||
//! window (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a
|
||||
//! running app.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::ffi::c_void;
|
||||
use std::rc::Rc;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2::rc::Retained;
|
||||
use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSView};
|
||||
use objc2_foundation::{NSArray, NSString, NSURL};
|
||||
use objc2::MainThreadOnly;
|
||||
use objc2::rc::{Retained, Weak};
|
||||
use objc2_app_kit::{
|
||||
NSAccessibility, NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView, NSWindow,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
|
||||
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
|
||||
|
||||
use crate::{Answer, FileDialog, Kind, Reply};
|
||||
use crate::{Answer, FORMAT_LABEL, FileDialog, Filter, Kind, Reply, format_menu};
|
||||
|
||||
const NOT_MAIN: &str = "dialogs show from the main thread only";
|
||||
const NOT_RUNNING: &str = "the app isn't running yet, so the dialog can't be shown";
|
||||
@@ -62,6 +69,133 @@ fn contains(root: &NSView, view: *const c_void) -> bool {
|
||||
std::ptr::eq((root as *const NSView).cast(), view) || root.subviews().iter().any(|child| contains(&child, view))
|
||||
}
|
||||
|
||||
/// The app's window that `parent`'s view is in.
|
||||
fn window_of<W: HasWindowHandle>(mtm: MainThreadMarker, parent: &W) -> Option<Retained<NSWindow>> {
|
||||
let view = match parent.window_handle().map(|h| h.as_raw()) {
|
||||
Ok(RawWindowHandle::AppKit(h)) => h.ns_view.as_ptr().cast_const(),
|
||||
_ => return None,
|
||||
};
|
||||
NSApplication::sharedApplication(mtm).windows().iter().find(|window| window.contentView().is_some_and(|content| contains(&content, view)))
|
||||
}
|
||||
|
||||
/// The Format menu's height and the room around and between its label and menu, in points.
|
||||
const ACCESSORY_HEIGHT: f64 = 38.0;
|
||||
const MARGIN: f64 = 12.0;
|
||||
const GAP: f64 = 8.0;
|
||||
/// The Format menu's size, in points.
|
||||
const MENU: NSSize = NSSize::new(260.0, 26.0);
|
||||
|
||||
/// Shows a Save sheet with a Format menu on `parent` (a [`sheet_parent`]) when `d` offers two or more file types
|
||||
/// ([`format_menu::entries`]), and answers through `reply` with the type chosen in the menu. Choosing a type puts the
|
||||
/// type's extensions first in the allowed types, which AppKit adds to a name typed without one, and sets the name
|
||||
/// field to [`format_menu::renamed`]. The SDK's `NSSavePanel.h` says the name field can only be set while the panel is
|
||||
/// configured; macOS 27.2 shows the new name. Where a system keeps the suggested name, the answer's `filter` still names the chosen
|
||||
/// type, so the save flow settles the extension (`ExtensionPolicy::picked_type`, or the app's own rule) and asks
|
||||
/// before replacing a file the panel did not ask about; a kept name with another extension reports that extension's
|
||||
/// type ([`format_menu::answered_type`]). Gives `reply` back when `d` offers fewer types, for rfd's panel.
|
||||
///
|
||||
/// The menu is the panel's accessory view, set before `beginSheetModalForWindow:completionHandler:` shows the sheet:
|
||||
/// an accessory set after the sheet began made macOS dismiss the sheet at once (storytold/vectorcraft#1800). The
|
||||
/// completion handler holds the panel, the menu and the menu's target until the sheet closes; the target holds the
|
||||
/// panel weakly.
|
||||
pub(crate) fn show_save_sheet<W: HasWindowHandle>(d: &FileDialog, parent: &W, reply: Reply) -> Result<(), Reply> {
|
||||
let entries = format_menu::entries(&d.filters);
|
||||
if entries.is_empty() {
|
||||
return Err(reply);
|
||||
}
|
||||
let Some(mtm) = MainThreadMarker::new() else { return Err(reply) };
|
||||
let Some(window) = window_of(mtm, parent) else { return Err(reply) };
|
||||
let Some(panel) = craft_appkit::save_panel::new_save_panel(mtm) else {
|
||||
reply.send(Answer::Unavailable("macOS returned no Save panel".into()));
|
||||
return Ok(());
|
||||
};
|
||||
let name = d.file_name.clone().unwrap_or_default();
|
||||
let selected = format_menu::initial(&name, &d.filters, &entries);
|
||||
set_allowed_types(&panel, &d.filters, &entries, selected);
|
||||
if let Some(title) = &d.title {
|
||||
panel.setMessage(Some(&NSString::from_str(title)));
|
||||
}
|
||||
if let Some(directory) = d.directory.as_deref().and_then(NSURL::from_directory_path) {
|
||||
panel.setDirectoryURL(Some(&directory));
|
||||
}
|
||||
panel.setExtensionHidden(false);
|
||||
if !name.is_empty() {
|
||||
panel.setNameFieldStringValue(&NSString::from_str(&name));
|
||||
}
|
||||
let label = d.format_label.as_deref().unwrap_or(FORMAT_LABEL);
|
||||
let (accessory, popup) = accessory(mtm, label, &d.filters, &entries, selected);
|
||||
panel.setAccessoryView(Some(&accessory));
|
||||
|
||||
// The name the field kept when the last choice could not rename it.
|
||||
let kept: Rc<RefCell<Option<String>>> = Rc::default();
|
||||
let (filters, listed, weak, kept_by_choice) = (d.filters.clone(), entries.clone(), Weak::new(&*panel), kept.clone());
|
||||
let choice = craft_appkit::save_panel::on_choose(mtm, &popup, move |at| {
|
||||
let (Some(panel), Some(chosen)) = (weak.load(), listed.get(at).and_then(|&i| filters.get(i))) else { return };
|
||||
set_allowed_types(&panel, &filters, &listed, at);
|
||||
let name = panel.nameFieldStringValue().to_string();
|
||||
let new_name = format_menu::renamed(&name, chosen, &filters);
|
||||
panel.setNameFieldStringValue(&NSString::from_str(&new_name));
|
||||
let shown = panel.nameFieldStringValue().to_string();
|
||||
*kept_by_choice.borrow_mut() = (shown != new_name).then_some(shown);
|
||||
});
|
||||
let reply = Cell::new(Some(reply));
|
||||
let answered = panel.clone();
|
||||
let (filters, opened_with) = (d.filters.clone(), d.file_name.clone());
|
||||
let handler = RcBlock::new(move |response: NSModalResponse| {
|
||||
// The menu sends its action to `choice` while the sheet is open; the handler keeps it until then.
|
||||
let _target = &choice;
|
||||
let Some(reply) = reply.take() else { return };
|
||||
if response != NSModalResponseOK {
|
||||
return reply.send(Answer::Cancelled);
|
||||
}
|
||||
let Some(path) = answered.URL().and_then(|url| url.to_file_path()) else { return reply.send(Answer::Cancelled) };
|
||||
let returned = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let filter = usize::try_from(popup.indexOfSelectedItem())
|
||||
.ok()
|
||||
.and_then(|at| format_menu::answered_type(&returned, kept.borrow().as_deref(), opened_with.as_deref(), &filters, &entries, at));
|
||||
reply.send(Answer::Saved { path, filter });
|
||||
});
|
||||
panel.beginSheetModalForWindow_completionHandler(&window, &handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets `panel`'s allowed file types to [`format_menu::allowed`].
|
||||
fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], entries: &[usize], selected: usize) {
|
||||
let types: Vec<Retained<NSString>> = format_menu::allowed(filters, entries, selected).iter().map(|e| NSString::from_str(e)).collect();
|
||||
// As rfd does, and as `show_panel` does for Open.
|
||||
#[allow(deprecated)]
|
||||
panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types)));
|
||||
}
|
||||
|
||||
/// The label and the Format menu of `filters`' `entries`, `selected` chosen, in a view for the panel's accessory.
|
||||
fn accessory(
|
||||
mtm: MainThreadMarker,
|
||||
text: &str,
|
||||
filters: &[Filter],
|
||||
entries: &[usize],
|
||||
selected: usize,
|
||||
) -> (Retained<NSView>, Retained<NSPopUpButton>) {
|
||||
let label = NSTextField::labelWithString(&NSString::from_str(text), mtm);
|
||||
label.sizeToFit();
|
||||
let size = label.frame().size;
|
||||
label.setFrameOrigin(NSPoint::new(MARGIN, (ACCESSORY_HEIGHT - size.height) / 2.0));
|
||||
let x = MARGIN + size.width + GAP;
|
||||
let frame = NSRect::new(NSPoint::new(x, (ACCESSORY_HEIGHT - MENU.height) / 2.0), MENU);
|
||||
let popup = NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), frame, false);
|
||||
// The label beside the menu is not tied to it for VoiceOver, so the menu carries the label's words as its name.
|
||||
popup.setAccessibilityLabel(Some(&NSString::from_str(text.trim_end_matches([':', ':']))));
|
||||
for title in format_menu::titles(filters, entries) {
|
||||
popup.addItemWithTitle(&NSString::from_str(&title));
|
||||
}
|
||||
if let Ok(index) = isize::try_from(selected) {
|
||||
popup.selectItemAtIndex(index);
|
||||
}
|
||||
let view = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, ACCESSORY_HEIGHT)));
|
||||
view.addSubview(&label);
|
||||
view.addSubview(&popup);
|
||||
(view, popup)
|
||||
}
|
||||
|
||||
/// Shows an Open or Folder panel that doesn't block the window and answers through `reply` when
|
||||
/// it closes. AppKit calls the completion handler on the main thread.
|
||||
pub(crate) fn show_panel(d: &FileDialog, reply: Reply) -> Option<Panel> {
|
||||
|
||||
@@ -63,10 +63,13 @@ pub(crate) fn show<W: HasWindowHandle + HasDisplayHandle>(request: Request, pare
|
||||
|
||||
fn show_file<W: HasWindowHandle + HasDisplayHandle>(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown {
|
||||
#[cfg(target_os = "macos")]
|
||||
let parent = match d.kind {
|
||||
let (parent, reply) = match d.kind {
|
||||
Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) },
|
||||
Kind::Save => match crate::macos::sheet_parent(parent) {
|
||||
Ok(parent) => Some(parent),
|
||||
Ok(parent) => match crate::macos::show_save_sheet(&d, parent, reply) {
|
||||
Ok(()) => return Shown::default(),
|
||||
Err(reply) => (Some(parent), reply),
|
||||
},
|
||||
Err(why) => {
|
||||
reply.send(Answer::Unavailable(why));
|
||||
return Shown::default();
|
||||
|
||||
@@ -190,10 +190,7 @@ fn saved(results: &HashMap<String, OwnedValue>) -> Result<Saved, String> {
|
||||
.map_err(|e: zbus::zvariant::Error| e.to_string())?;
|
||||
let uri = uris.first().ok_or("no file in the portal's answer")?;
|
||||
let path = file_uri_path(uri).ok_or_else(|| format!("not a local file: {uri}"))?;
|
||||
let filter = results.get("current_filter").and_then(|v| {
|
||||
let (label, _globs): (String, Vec<(u32, String)>) = v.try_clone().ok()?.try_into().ok()?;
|
||||
Some(label)
|
||||
});
|
||||
let filter = results.get("current_filter").and_then(|v| filter_label(v));
|
||||
Ok(Saved { path, filter })
|
||||
}
|
||||
|
||||
@@ -309,6 +306,18 @@ fn options<'a>(req: &'a SaveRequest, token: &'a str) -> HashMap<&'static str, Va
|
||||
o
|
||||
}
|
||||
|
||||
/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of
|
||||
/// another shape.
|
||||
fn filter_label(value: &Value<'_>) -> Option<String> {
|
||||
match value {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes.
|
||||
// pc: apps/photocraft/src/portal_save.rs:134 file_uri_path
|
||||
fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
|
||||
@@ -27,3 +27,45 @@ fn file_uris_become_local_paths() {
|
||||
assert_eq!(file_uri_path("sftp://host/x.png"), None);
|
||||
assert_eq!(file_uri_path("file://host/x.png"), None);
|
||||
}
|
||||
|
||||
/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string)
|
||||
/// gives the path alone; `uris` of another shape is an error.
|
||||
#[trial]
|
||||
fn an_answer_of_another_shape_is_not_read() {
|
||||
let answer_with = |uris: Value<'_>, filter: Option<Value<'_>>| {
|
||||
let mut r = HashMap::new();
|
||||
r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap());
|
||||
if let Some(filter) = filter {
|
||||
r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap());
|
||||
}
|
||||
saved(&r)
|
||||
};
|
||||
let card = || Value::from(vec!["file:///tmp/card".to_string()]);
|
||||
let malformed = [
|
||||
Value::from(("PNG".to_string(),)),
|
||||
Value::from(("PNG".to_string(), vec![(0u32,)])),
|
||||
Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])),
|
||||
Value::from((1u32, vec![(0u32, "*.png".to_string())])),
|
||||
Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)),
|
||||
Value::from("PNG"),
|
||||
];
|
||||
for filter in malformed {
|
||||
let shape = filter.value_signature().to_string();
|
||||
assert_eq!(answer_with(card(), Some(filter)), Ok(Saved { path: "/tmp/card".into(), filter: None }), "{shape}");
|
||||
}
|
||||
// The shape the portal defines is still read, and so is the one `options` sends.
|
||||
let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())]));
|
||||
assert_eq!(answer_with(card(), Some(png)), Ok(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }));
|
||||
let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"])));
|
||||
assert_eq!(filter_label(&sent), Some("Photoshop".into()));
|
||||
let malformed = [
|
||||
Value::from(vec![1u32]),
|
||||
Value::from(vec![("file:///tmp/card".to_string(),)]),
|
||||
Value::from(Vec::<String>::new()),
|
||||
Value::from("file:///tmp/card"),
|
||||
];
|
||||
for uris in malformed {
|
||||
let shape = uris.value_signature().to_string();
|
||||
assert!(answer_with(uris, None).is_err(), "{shape}");
|
||||
}
|
||||
}
|
||||
@@ -276,6 +276,8 @@ pub struct FilePanels {
|
||||
extension_policy: ExtensionPolicy,
|
||||
replace_guard: ReplaceGuard,
|
||||
replace_words: ReplaceWords,
|
||||
/// The label of the macOS Save panel's file type menu; `None` shows [`crate::FORMAT_LABEL`].
|
||||
format_label: Option<String>,
|
||||
/// Why no file dialog can open on this system, when the probe knows.
|
||||
backend_problem: fn() -> Option<String>,
|
||||
/// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host.
|
||||
@@ -325,6 +327,7 @@ impl FileService {
|
||||
extension_policy: ExtensionPolicy::default(),
|
||||
replace_guard: ReplaceGuard::default(),
|
||||
replace_words: ReplaceWords::default(),
|
||||
format_label: None,
|
||||
backend_problem: probe::known_problem,
|
||||
#[cfg(feature = "ui")]
|
||||
prompts: Vec::new(),
|
||||
@@ -393,6 +396,12 @@ impl FilePanels {
|
||||
self.replace_words = words;
|
||||
}
|
||||
|
||||
/// The label of the file type menu on a macOS Save panel that offers two or more types ("Format:" in English);
|
||||
/// the app sets it again when the language changes.
|
||||
pub fn set_format_label(&mut self, label: impl Into<String>) {
|
||||
self.format_label = Some(label.into());
|
||||
}
|
||||
|
||||
/// [`extension_policy`](FilePanels::extension_policy) on panels the app already keeps, for a
|
||||
/// preference that changes while the app runs.
|
||||
pub fn set_extension_policy(&mut self, policy: ExtensionPolicy) {
|
||||
@@ -647,6 +656,7 @@ impl FilePanels {
|
||||
if request.kind == PickKind::Save {
|
||||
let adds_extension = cfg!(windows) && !request.filters.is_empty();
|
||||
dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension));
|
||||
dialog.format_label = self.format_label.clone();
|
||||
}
|
||||
dialog
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ impl Reader<'_> {
|
||||
"w:linkStyles" => s.link_styles = on_off(k),
|
||||
"w:removePersonalInformation" => s.remove_personal_info = on_off(k),
|
||||
"w:removeDateAndTime" => s.remove_date_time = on_off(k),
|
||||
"w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k),
|
||||
"w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k),
|
||||
"w:compat" => {
|
||||
s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off);
|
||||
// Only Word's own setting: another `w:uri` names a different application's.
|
||||
|
||||
@@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp
|
||||
if s.gutter_at_top {
|
||||
w.empty("w:gutterAtTop", &[]);
|
||||
}
|
||||
// After `w:gutterAtTop` and before `w:proofState` in CT_Settings.
|
||||
if s.hide_spelling_errors {
|
||||
w.empty("w:hideSpellingErrors", &[]);
|
||||
}
|
||||
if s.hide_grammar_errors {
|
||||
w.empty("w:hideGrammaticalErrors", &[]);
|
||||
}
|
||||
if let Some(id) = template_rel {
|
||||
w.empty("w:attachedTemplate", &[("r:id", id)]);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ const OWNED: &[&str] = &[
|
||||
"w:displayBackgroundShape",
|
||||
"w:mirrorMargins",
|
||||
"w:gutterAtTop",
|
||||
"w:hideSpellingErrors",
|
||||
"w:hideGrammaticalErrors",
|
||||
"w:attachedTemplate",
|
||||
"w:linkStyles",
|
||||
"w:mailMerge",
|
||||
|
||||
@@ -204,3 +204,50 @@ fn do_not_track_moves_round_trips() {
|
||||
assert!(s.contains("<w:doNotTrackMoves/>"), "{s}");
|
||||
assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves);
|
||||
}
|
||||
|
||||
/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`,
|
||||
/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged
|
||||
/// part), written in a generated part, and left out when they are turned off.
|
||||
#[test]
|
||||
fn hidden_proofing_errors_round_trip() {
|
||||
let original = SETTINGS.replace("<w:proofState", r#"<w:hideSpellingErrors/><w:hideGrammaticalErrors w:val="1"/><w:proofState"#);
|
||||
let mut doc = craft_docx::read(&with_settings(&original)).unwrap();
|
||||
assert!(doc.settings.hide_spelling_errors && doc.settings.hide_grammar_errors);
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert_eq!(s.matches("hideSpellingErrors").count(), 1, "{s}");
|
||||
assert_eq!(s.matches("hideGrammaticalErrors").count(), 1, "{s}");
|
||||
assert!(pos(&s, "<w:hideSpellingErrors/>") < pos(&s, "<w:hideGrammaticalErrors/>"));
|
||||
assert!(pos(&s, "<w:hideGrammaticalErrors/>") < pos(&s, "<w:proofState"), "{s}");
|
||||
assert!(s.contains("ClauseSet"), "a merged part: {s}");
|
||||
doc.settings.hide_spelling_errors = false;
|
||||
doc.settings.hide_grammar_errors = false;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert!(!s.contains("hideSpellingErrors") && !s.contains("hideGrammaticalErrors"), "{s}");
|
||||
|
||||
// Turned on in a part that lacks them: inserted once each, before `w:proofState`.
|
||||
let mut doc = craft_docx::read(&with_settings(SETTINGS)).unwrap();
|
||||
assert!(!doc.settings.hide_spelling_errors && !doc.settings.hide_grammar_errors);
|
||||
doc.settings.hide_spelling_errors = true;
|
||||
doc.settings.hide_grammar_errors = true;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert_eq!(s.matches("hideSpellingErrors").count(), 1, "{s}");
|
||||
assert_eq!(s.matches("hideGrammaticalErrors").count(), 1, "{s}");
|
||||
assert!(pos(&s, "removeDateAndTime") < pos(&s, "<w:hideSpellingErrors/>"), "{s}");
|
||||
assert!(pos(&s, "<w:hideGrammaticalErrors/>") < pos(&s, "<w:proofState"), "{s}");
|
||||
|
||||
// `w:val="false"` and `w:val="0"` show them.
|
||||
let off = SETTINGS.replace("<w:proofState", r#"<w:hideSpellingErrors w:val="false"/><w:hideGrammaticalErrors w:val="0"/><w:proofState"#);
|
||||
let read = craft_docx::read(&with_settings(&off)).unwrap();
|
||||
assert!(!read.settings.hide_spelling_errors && !read.settings.hide_grammar_errors);
|
||||
let s = text(&save(&read), "word/settings.xml");
|
||||
assert!(!s.contains("hideSpellingErrors") && !s.contains("hideGrammaticalErrors"), "{s}");
|
||||
|
||||
// A document of our own: absent by default, written when on, and read back.
|
||||
let mut doc = craft_wordmodel::Document::new();
|
||||
assert!(!text(&save(&doc), "word/settings.xml").contains("hideSpellingErrors"));
|
||||
doc.settings.hide_grammar_errors = true;
|
||||
let s = text(&save(&doc), "word/settings.xml");
|
||||
assert!(s.contains("<w:hideGrammaticalErrors/>") && !s.contains("hideSpellingErrors"), "{s}");
|
||||
let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap();
|
||||
assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use craft_behavior::CanvasView;
|
||||
use egui::Pos2;
|
||||
use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point};
|
||||
|
||||
use super::model::SelectedAnchors;
|
||||
use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection};
|
||||
|
||||
/// A shown direction handle: its path's index, its knot, side and screen end.
|
||||
@@ -46,15 +47,34 @@ impl BezierOverlay<'_> {
|
||||
reach: f32,
|
||||
) -> Option<BezierHit> {
|
||||
// pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind).
|
||||
let shown = shown_handles(paths, selection, handles, view);
|
||||
let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view);
|
||||
let anchors = paths.iter().map(EditPath::anchor_count).sum::<usize>() <= MAX_ANCHORS;
|
||||
hit_in(paths, &shown, anchors, view, at, reach)
|
||||
}
|
||||
}
|
||||
|
||||
/// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection
|
||||
/// does not show.
|
||||
pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
|
||||
/// does not show. `anchors` holds the anchors `sel` selects.
|
||||
pub(super) fn shown_handles(
|
||||
paths: &[EditPath],
|
||||
sel: &PathSelection,
|
||||
anchors: &SelectedAnchors,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view)
|
||||
}
|
||||
|
||||
/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the
|
||||
/// number of selected anchors that `OneAnchor` counts.
|
||||
fn shown_handles_of(
|
||||
paths: &[EditPath],
|
||||
sel: &PathSelection,
|
||||
has_anchor: impl Fn(u64, KnotRef) -> bool,
|
||||
selected: usize,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
let mut shown = Vec::new();
|
||||
for (index, path) in paths.iter().enumerate() {
|
||||
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
|
||||
@@ -65,13 +85,13 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
|
||||
let Some(knot) = path.knot(knot_ref) else { continue };
|
||||
for side in [HandleSide::In, HandleSide::Out] {
|
||||
let of_selection = || {
|
||||
sel.has_anchor(path.key, knot_ref)
|
||||
|| next_to_selected_anchor(path, sel, knot_ref, side)
|
||||
has_anchor(path.key, knot_ref)
|
||||
|| next_to_selected_anchor(path, &has_anchor, knot_ref, side)
|
||||
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
|
||||
};
|
||||
let wanted = match handles {
|
||||
HandlesShown::All => true,
|
||||
HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(),
|
||||
HandlesShown::OneAnchor => selected == 1 && of_selection(),
|
||||
HandlesShown::Selected => of_selection(),
|
||||
};
|
||||
if wanted && !knot.retracted(side) {
|
||||
@@ -85,31 +105,38 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha
|
||||
|
||||
/// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not
|
||||
/// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted.
|
||||
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`.
|
||||
pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec<Shown> {
|
||||
/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per
|
||||
/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none.
|
||||
pub(super) fn other_handles(
|
||||
paths: &[EditPath],
|
||||
at: usize,
|
||||
sel: &PathSelection,
|
||||
anchors: &SelectedAnchors,
|
||||
handles: HandlesShown,
|
||||
view: &CanvasView,
|
||||
) -> Vec<Shown> {
|
||||
let Some(path) = paths.get(at) else { return Vec::new() };
|
||||
let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key));
|
||||
let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() };
|
||||
let mut own = PathSelection::new(Some(path.key), anchors.clone(), None);
|
||||
for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) {
|
||||
own = own.also(*key, rest.clone());
|
||||
if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) {
|
||||
return Vec::new();
|
||||
}
|
||||
if let Some(edited) = sel.path.filter(|edited| *edited != path.key) {
|
||||
own = own.also(edited, sel.anchors.clone());
|
||||
}
|
||||
shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect()
|
||||
let edited = sel.path.map_or(0, |_| sel.anchors.len());
|
||||
let own = PathSelection::new(Some(path.key), Vec::new(), None);
|
||||
shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view)
|
||||
.into_iter()
|
||||
.map(|shown| Shown { path: at, ..shown })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out
|
||||
/// handle or the next anchor's in handle, across a closed subpath's seam too.
|
||||
fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool {
|
||||
fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
|
||||
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
|
||||
let count = sub.knots.len();
|
||||
match side {
|
||||
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))),
|
||||
HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))),
|
||||
HandleSide::In => {
|
||||
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
|
||||
sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
|
||||
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles};
|
||||
pub(crate) use mark::paint_mark;
|
||||
pub use mark::{AnchorsShown, HitMark, SegmentMark};
|
||||
use mark::{Fill, paint_handle, segment_path, stroke};
|
||||
use model::SelectedAnchors;
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
pub(crate) use model::reads;
|
||||
pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection};
|
||||
pub use style::BezierStyle;
|
||||
pub use words::BezierWords;
|
||||
@@ -381,6 +384,8 @@ struct Scene {
|
||||
items: Vec<Item>,
|
||||
/// Over [`MAX_ANCHORS`] or hidden: outlines only.
|
||||
limited: bool,
|
||||
/// The anchors the selection selects (none when `limited`).
|
||||
selected: SelectedAnchors,
|
||||
}
|
||||
|
||||
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
|
||||
@@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> {
|
||||
let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::<usize>() > MAX_ANCHORS;
|
||||
let mut items = Vec::new();
|
||||
if limited {
|
||||
return Scene { items, limited };
|
||||
return Scene { items, limited, selected: SelectedAnchors::default() };
|
||||
}
|
||||
let selected = SelectedAnchors::of(self.selection);
|
||||
let near = rect.expand(reach);
|
||||
let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) };
|
||||
let shown =
|
||||
if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) };
|
||||
let mut handles = shown.iter().peekable();
|
||||
for (at, path) in paths.iter().enumerate() {
|
||||
let count = path.anchor_count();
|
||||
@@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Scene { items, limited }
|
||||
Scene { items, limited, selected }
|
||||
}
|
||||
|
||||
/// Whether the press on `item` is the tool's.
|
||||
@@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> {
|
||||
for item in &scene.items {
|
||||
let press = self.takes(item);
|
||||
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
|
||||
let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot);
|
||||
let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot);
|
||||
let part = cx.part(item.part(), item.shape.clone()).priority(item.priority());
|
||||
let part = if press { part.sense(PRESS) } else { part };
|
||||
let part = if keyboard {
|
||||
@@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> {
|
||||
draw_end(path, item.knot, item.at, fill);
|
||||
}
|
||||
Kind::Anchor if item.shown => {
|
||||
let fill = if self.selection.draws_selected(path.key, item.knot) {
|
||||
let fill = if scene.selected.draws_selected(path.key, item.knot) {
|
||||
Fill::Path(style.line)
|
||||
} else {
|
||||
Fill::Style(if cx.part_if_declared(item.part()).is_some() {
|
||||
@@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> {
|
||||
// The handles of anchors selected in paths the overlay does not edit: drawn, never parts.
|
||||
if !circles {
|
||||
for (at, path) in paths.iter().enumerate() {
|
||||
for shown in other_handles(paths, at, self.selection, self.handles, &view) {
|
||||
for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) {
|
||||
draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! the overlays report. The host converts its own path type to these each frame and applies the
|
||||
//! edits to its own.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use kurbo::{BezPath, CubicBez, Point, Vec2};
|
||||
|
||||
@@ -235,6 +237,8 @@ impl PathSelection {
|
||||
|
||||
/// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`.
|
||||
pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum());
|
||||
self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot))
|
||||
}
|
||||
|
||||
@@ -245,6 +249,8 @@ impl PathSelection {
|
||||
|
||||
/// Whether `knot` of `path` is a selected anchor.
|
||||
pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 });
|
||||
self.path == Some(path) && self.anchors.contains(&knot)
|
||||
}
|
||||
|
||||
@@ -268,6 +274,79 @@ impl PathSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays
|
||||
/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one
|
||||
/// path holding every anchor listed for it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct SelectedAnchors {
|
||||
path: Option<u64>,
|
||||
anchors: HashSet<KnotRef>,
|
||||
others: HashSet<(u64, KnotRef)>,
|
||||
listed: HashSet<u64>,
|
||||
others_len: usize,
|
||||
}
|
||||
|
||||
impl SelectedAnchors {
|
||||
/// The anchors `sel` selects.
|
||||
pub(super) fn of(sel: &PathSelection) -> Self {
|
||||
let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum();
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
reads::add(sel.anchors.len() + others_len);
|
||||
Self {
|
||||
path: sel.path,
|
||||
anchors: sel.anchors.iter().copied().collect(),
|
||||
others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(),
|
||||
listed: sel.others.iter().map(|(key, _)| *key).collect(),
|
||||
others_len,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]).
|
||||
pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.path == Some(path) && self.anchors.contains(&knot)
|
||||
}
|
||||
|
||||
/// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]).
|
||||
pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
|
||||
}
|
||||
|
||||
/// Whether `knot` is one of the anchors `others` lists for `path`.
|
||||
pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool {
|
||||
self.others.contains(&(path, knot))
|
||||
}
|
||||
|
||||
/// Whether `others` lists `path`, with or without anchors.
|
||||
pub(super) fn lists(&self, path: u64) -> bool {
|
||||
self.listed.contains(&path)
|
||||
}
|
||||
|
||||
/// The number of anchors `others` lists over every path.
|
||||
pub(super) fn others_len(&self) -> usize {
|
||||
self.others_len
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work.
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
pub(crate) mod reads {
|
||||
use std::cell::Cell;
|
||||
|
||||
thread_local! {
|
||||
static READS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Counts `n` entries read.
|
||||
pub(crate) fn add(n: usize) {
|
||||
READS.with(|reads| reads.set(reads.get() + n));
|
||||
}
|
||||
|
||||
/// The entries read since the last call, and starts the count again.
|
||||
pub(crate) fn take() -> usize {
|
||||
READS.with(|reads| reads.replace(0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of a knot's two direction handles.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_behavior::Value;
|
||||
use craft_color_ui::ui::{ChosenColor, ColorChoice, NamedColor};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, FieldLabelRole, Props as _, Show as _, ShowContainer as _, SideLabel};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
@@ -549,31 +549,34 @@ impl DivideSlicesDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// One axis: its check box, then (while it is on) what the value counts and the value.
|
||||
/// One axis: its check box, then (while it is on) what the value counts and the value. Both axes show the same Divide
|
||||
/// By and value labels, so those rows describe their controls, and each control is named by its label and the axis's
|
||||
/// caption.
|
||||
fn axis_rows(ui: &mut Ui, axis: &mut AxisState, caption: &Label, words: &SliceWords, lengths: LengthUnits) {
|
||||
Field::new(caption.clone()).show(ui, |ui, _| {
|
||||
Checkbox::new(Bind::bound(&mut axis.on)).label(caption.clone()).show(ui);
|
||||
});
|
||||
let in_axis = |control: &Label| Label::from(words.axis_control.fill(&[("control", control.as_str()), ("axis", caption.as_str())]));
|
||||
let unit = if axis.by_size { words.size.clone() } else { words.count.clone() };
|
||||
Field::new(words.divide_by.clone()).enabled(axis.on).show(ui, |ui, _| {
|
||||
RadioGroup::new(words.divide_by.clone(), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
|
||||
let describes = || SideLabel::new().role(FieldLabelRole::Describes);
|
||||
Field::new(words.divide_by.clone()).side(describes()).enabled(axis.on).show(ui, |ui, _| {
|
||||
RadioGroup::new(in_axis(&words.divide_by), Bind::bound(&mut axis.by_size)).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Radio::new(false).label(words.count.clone()).show(ui);
|
||||
Radio::new(true).label(words.size.clone()).show(ui);
|
||||
});
|
||||
});
|
||||
});
|
||||
Field::new(unit).enabled(axis.on).show(ui, |ui, _| {
|
||||
let value_name = in_axis(&unit);
|
||||
Field::new(unit).side(describes()).enabled(axis.on).show(ui, |ui, _| {
|
||||
if axis.by_size {
|
||||
let field =
|
||||
NumberField::length(words.divide_value.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
|
||||
let field = NumberField::length(value_name.clone(), Bind::given(Some(axis.size)), lengths).range(1.0..=AxisState::MAX_SIZE).show(ui);
|
||||
if let Some(Some(size)) = field.value().copied() {
|
||||
axis.size = AxisState::size_of(size, axis.size);
|
||||
}
|
||||
} else {
|
||||
let max = f64::from(AxisState::MAX_COUNT);
|
||||
let field =
|
||||
NumberField::new(words.divide_value.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
|
||||
let field = NumberField::new(value_name.clone(), Bind::given(Some(f64::from(axis.count)))).range(1.0..=max).commit_decimals(0).show(ui);
|
||||
if let Some(Some(count)) = field.value().copied() {
|
||||
axis.count = count.round().clamp(1.0, max) as u32;
|
||||
}
|
||||
|
||||
@@ -72,5 +72,8 @@ craft_ui::words! {
|
||||
count: "slice.count" = "slices, evenly spaced";
|
||||
size: "slice.size" = "per slice";
|
||||
divide_value: "slice.divideValue" = "Value";
|
||||
/// The name a screen reader reads for one axis's Divide By group and value field: `{control}` the row's
|
||||
/// visible label, `{axis}` the axis's caption.
|
||||
axis_control: template "slice.axisControl" = "{control}, {axis}";
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ impl Outcome for StrokeEditorOutput {
|
||||
/// with a line sample drawn at opacity 1; the row matching [`StrokeStyle::line_style`] is selected, none for Custom.
|
||||
/// Picking one applies [`StrokeStyle::with_line_style`].
|
||||
/// - Rows: Alignment (Inside, Center, Outside; enabled only when [`closed`](Self::closed)); Caps (Butt / Flat, Round,
|
||||
/// Square; disabled for a solid closed path); Corners (Miter, Round, Bevel; enabled only with
|
||||
/// Square; disabled for a solid closed path unless [`caps_on_closed`](Self::caps_on_closed)); Corners (Miter, Round, Bevel; enabled only with
|
||||
/// [`corners`](Self::corners)); the app's [`rows`](Self::rows); Miter limit (1–500, `×`; enabled only for Miter
|
||||
/// corners); Opacity ([`StrokeSections::OPACITY`], 0–100 %, stored 0..=1). Choices are selects, or segmented icon
|
||||
/// buttons with [`StrokeSections::ICONS`]. Under the rows of an open path: "Open paths use centered strokes".
|
||||
@@ -96,6 +96,7 @@ pub struct StrokeEditor<'a> {
|
||||
value: Bind<'a, StrokeStyle>,
|
||||
sections: StrokeSections,
|
||||
closed: bool,
|
||||
caps_on_closed: bool,
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
@@ -109,6 +110,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
value,
|
||||
sections: StrokeSections::default(),
|
||||
closed: true,
|
||||
caps_on_closed: false,
|
||||
corners: true,
|
||||
mixed: StrokeMixed::default(),
|
||||
rows: &[],
|
||||
@@ -121,13 +123,20 @@ impl<'a> StrokeEditor<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the stroked path is closed: alignment applies and caps need dashes.
|
||||
/// True by default.
|
||||
/// Whether the stroked path is closed: alignment applies and caps need dashes, unless
|
||||
/// [`caps_on_closed`](Self::caps_on_closed) is set. True by default.
|
||||
pub fn closed(mut self, closed: bool) -> Self {
|
||||
self.closed = closed;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the Caps row stays enabled on a closed path without dashes. False by default: the row is then disabled
|
||||
/// for a solid closed path and enabled for an open or dashed one.
|
||||
pub fn caps_on_closed(mut self, enabled: bool) -> Self {
|
||||
self.caps_on_closed = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the path has corners for the Corners and Miter limit rows (an ellipse has none). True by default.
|
||||
pub fn corners(mut self, corners: bool) -> Self {
|
||||
self.corners = corners;
|
||||
@@ -148,7 +157,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
|
||||
/// Shows the editor.
|
||||
pub fn show(self, ui: &mut Ui) -> StrokeEditorOutput {
|
||||
let StrokeEditor { label, mut value, sections, closed, corners, mixed, rows } = self;
|
||||
let StrokeEditor { label, mut value, sections, closed, caps_on_closed, corners, mixed, rows } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<StrokeWords>();
|
||||
let name: Arc<str> = label.as_str().into();
|
||||
@@ -164,7 +173,7 @@ impl<'a> StrokeEditor<'a> {
|
||||
Some((base, draft)) if base == held => draft,
|
||||
_ => held.clone(),
|
||||
};
|
||||
let body = Body { words: &words, style: &style, sections, closed, corners, mixed, rows, name: name.clone() };
|
||||
let body = Body { words: &words, style: &style, sections, closed, caps_on_closed, corners, mixed, rows, name: name.clone() };
|
||||
body.show(ui, &mut found);
|
||||
if !found.events.is_empty() {
|
||||
for event in &found.events {
|
||||
@@ -251,6 +260,7 @@ struct Body<'a> {
|
||||
style: &'a StrokeStyle,
|
||||
sections: StrokeSections,
|
||||
closed: bool,
|
||||
caps_on_closed: bool,
|
||||
corners: bool,
|
||||
mixed: StrokeMixed,
|
||||
rows: &'a [StrokeChoiceRow<'a>],
|
||||
@@ -325,7 +335,7 @@ impl Body<'_> {
|
||||
|
||||
fn grid(&self, ui: &mut Ui, found: &mut Found) {
|
||||
let (style, mixed, words) = (self.style, self.mixed, self.words);
|
||||
let solid_closed = self.closed && style.dashes.is_empty() && !mixed.dashes;
|
||||
let solid_closed = self.closed && !self.caps_on_closed && style.dashes.is_empty() && !mixed.dashes;
|
||||
let icons = self.sections.contains(StrokeSections::ICONS);
|
||||
FieldGroup::new(words.title.clone()).show(ui, |ui, _| {
|
||||
let align = [
|
||||
|
||||
@@ -465,6 +465,54 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() {
|
||||
assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}");
|
||||
}
|
||||
|
||||
// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all
|
||||
// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw.
|
||||
#[trial]
|
||||
fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() {
|
||||
let painted_with = |selection: PathSelection, handles: HandlesShown| {
|
||||
let mut other = path_b();
|
||||
other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0));
|
||||
let third =
|
||||
EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]);
|
||||
let mut h = harness(vec![path_a(), other, third]);
|
||||
h.update(|st| (st.selection, st.handles) = (selection, handles));
|
||||
format!("{:?}", h.fixture.frame_shapes())
|
||||
};
|
||||
let one = || sel(1, &[]).also(2, vec![kr(0)]);
|
||||
assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected));
|
||||
let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]);
|
||||
assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected));
|
||||
assert_eq!(
|
||||
painted_with(two(), HandlesShown::OneAnchor),
|
||||
painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor),
|
||||
"painting is the same from frame to frame"
|
||||
);
|
||||
}
|
||||
|
||||
// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square:
|
||||
// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries
|
||||
// read (a search of the lists for each anchor laid out or drawn quadruples them).
|
||||
#[trial]
|
||||
fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
|
||||
let reads_for = |n: usize| {
|
||||
let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0));
|
||||
let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]);
|
||||
let others: Vec<EditPath> =
|
||||
(0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect();
|
||||
let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None);
|
||||
for other in &others {
|
||||
selection = selection.also(other.key, (0..4).map(kr).collect());
|
||||
}
|
||||
let mut h = harness(std::iter::once(edited).chain(others).collect());
|
||||
craft_draw::ui::pen::bezier::reads::take();
|
||||
h.update(|st| st.selection = selection);
|
||||
craft_draw::ui::pen::bezier::reads::take()
|
||||
};
|
||||
let (small, large) = (reads_for(60), reads_for(120));
|
||||
assert!(small > 0, "the frame reads the selection");
|
||||
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
|
||||
}
|
||||
|
||||
// Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at.
|
||||
|
||||
// `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.
|
||||
|
||||
@@ -4,11 +4,15 @@
|
||||
use craft_behavior::geometry::Constraint;
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
use craft_behavior::{CanvasView, EditEvent};
|
||||
use craft_draw::ui::slice::{SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool, SliceToolSettings};
|
||||
use craft_ui::contract::{CommandSet, Show as _};
|
||||
use craft_draw::ui::slice::{
|
||||
DivideBy, DivideSlices, DivideSlicesDialog, SliceCommand, SliceEvent, SliceItem, SliceMode, SliceOrigin, SliceOverlay, SliceRefusal, SliceTool,
|
||||
SliceToolSettings,
|
||||
};
|
||||
use craft_ui::contract::{CommandSet, Role, Show as _};
|
||||
use craft_ui::dialog::DialogHost;
|
||||
use craft_ui::runtime::commands::CommandRef;
|
||||
use craft_ui::runtime::frame::take_output;
|
||||
use craft_ui::testing::{ToolFixture, trial};
|
||||
use craft_ui::testing::{Fixture, ToolFixture, access, trial};
|
||||
use egui::{Key, Modifiers, Pos2, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
@@ -203,3 +207,37 @@ fn delete_takes_the_key_for_the_selected_slice() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names a screen reader reads for the nodes of `role` in the shown Divide Slice dialog, in tree order.
|
||||
fn divide_names(divide: DivideSlices, role: Role) -> Vec<String> {
|
||||
let host = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&host);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.room(Vec2::new(900.0, 700.0));
|
||||
host.borrow_mut().open(DivideSlicesDialog::new(divide));
|
||||
fixture.idle(10);
|
||||
let tree = fixture.tree();
|
||||
fixture.by_role(role).iter().map(|target| access::name(tree, target.node).unwrap_or_default().to_owned()).collect()
|
||||
}
|
||||
|
||||
/// Divide Slice's two axes show the same Divide By choice and value rows; each axis's radio group and value field
|
||||
/// name their axis by its caption after their visible label, so a screen reader tells the rows from the columns.
|
||||
#[trial]
|
||||
fn divide_slice_names_each_axis_control_by_its_axis() {
|
||||
let by_count = DivideSlices::new(Some(DivideBy::Count(2)), Some(DivideBy::Count(3)));
|
||||
let by_size = DivideSlices::new(Some(DivideBy::Size(72.0)), Some(DivideBy::Size(36.0)));
|
||||
let cases = [
|
||||
("the Divide By groups", by_count, Role::RADIO_GROUP, "Divide By"),
|
||||
("the count fields", by_count, Role::SPIN_BUTTON, "slices, evenly spaced"),
|
||||
("the size fields", by_size, Role::SPIN_BUTTON, "per slice"),
|
||||
];
|
||||
for (what, divide, role, label) in cases {
|
||||
let names = divide_names(divide, role);
|
||||
let [rows, columns] = names.as_slice() else { panic!("{what}: one for each axis, got {names:?}") };
|
||||
assert_ne!(rows, columns, "{what} have different names");
|
||||
for (name, axis) in [(rows, "Divide Horizontally Into"), (columns, "Divide Vertically Into")] {
|
||||
assert!(name.starts_with(label), "{what}: {name:?} starts with the visible label {label:?}");
|
||||
assert!(name.contains(axis), "{what}: {name:?} names its axis {axis:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The stroke editor's dash fields: typing in the blank after the pattern adds an entry, clearing a later field ends
|
||||
//! the pattern there, and the first field never clears.
|
||||
//! the pattern there, and the first field never clears. Its Caps row on a solid closed path: disabled by default,
|
||||
//! enabled with `caps_on_closed`.
|
||||
|
||||
use craft_draw::ui::stroke::{StrokeEditor, StrokeSections, StrokeStyle};
|
||||
use craft_draw::ui::stroke::{LineCap, StrokeEditor, StrokeSections, StrokeStyle};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers};
|
||||
@@ -34,6 +35,39 @@ fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
|
||||
fixture.idle(3);
|
||||
}
|
||||
|
||||
/// The panel editor over a solid closed path, with `caps_on_closed` as given, and the style it writes through to.
|
||||
fn closed_editor(caps_on_closed: bool) -> (Fixture, Rc<RefCell<StrokeStyle>>) {
|
||||
let style = Rc::new(RefCell::new(StrokeStyle::default()));
|
||||
let shown = Rc::clone(&style);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut style = shown.borrow_mut();
|
||||
let _ = StrokeEditor::new("Stroke", Bind::bound(&mut *style))
|
||||
.sections(StrokeSections::PANEL)
|
||||
.closed(true)
|
||||
.caps_on_closed(caps_on_closed)
|
||||
.show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, style)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn caps_on_closed_keeps_the_cap_buttons_enabled_on_a_solid_closed_path() {
|
||||
let (mut fixture, style) = closed_editor(false);
|
||||
let square = fixture.by_label("Square").expect("the editor shows Square");
|
||||
assert!(fixture.tree().is_disabled_key(square.node), "by default Caps is disabled for a solid closed path");
|
||||
fixture.click(&square);
|
||||
fixture.idle(3);
|
||||
assert_ne!(style.borrow().cap, LineCap::Square, "a disabled cap button does not change the cap");
|
||||
|
||||
let (mut fixture, style) = closed_editor(true);
|
||||
let square = fixture.by_label("Square").expect("the editor shows Square");
|
||||
assert!(!fixture.tree().is_disabled_key(square.node), "with caps_on_closed Caps is enabled");
|
||||
fixture.click(&square);
|
||||
fixture.idle(3);
|
||||
assert_eq!(style.borrow().cap, LineCap::Square, "the cap button sets the cap");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn dash_fields_add_after_the_pattern_and_a_cleared_field_ends_it() {
|
||||
let (mut fixture, style) = editor(vec![4.0, 2.0]);
|
||||
|
||||
@@ -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,10 @@ 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]
|
||||
#[prop]
|
||||
compact: bool,
|
||||
}
|
||||
|
||||
/// How many times a closed [`FontPicker`] built its stop list on `ctx`, for regression trials.
|
||||
@@ -774,6 +782,7 @@ impl<'a> FontPicker<'a> {
|
||||
host: &[],
|
||||
current_host: None,
|
||||
host_picked: None,
|
||||
compact: false,
|
||||
}
|
||||
.label(label)
|
||||
.enabled(catalog.is_ready())
|
||||
@@ -893,11 +902,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 +931,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 +939,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 +989,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 +1006,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,962 @@
|
||||
//! 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);
|
||||
// One writable handle writes and flushes the copy: Windows flushes only through a handle that can write, and the
|
||||
// copy doesn't take the source's permissions (`std::fs::copy` would), so a read-only store file still copies.
|
||||
let copied = File::open(&p.source).and_then(|mut source| {
|
||||
let mut copy = File::create(&part)?;
|
||||
std::io::copy(&mut source, &mut copy)?;
|
||||
copy.sync_all()
|
||||
});
|
||||
if let Err(e) = copied {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(io(what())(e));
|
||||
}
|
||||
folder.unload(&p.path);
|
||||
let checked = 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,354 @@ 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 read_only_store_files_are_made_available() {
|
||||
let server = Server::start();
|
||||
server.serve_fixture(&fixture());
|
||||
let (store, dir, root, shared) = shared_store(&server, "os-fonts-read-only");
|
||||
let set_read_only = |read_only: bool| {
|
||||
for name in entries(&dir.join("testsans")) {
|
||||
let path = dir.join("testsans").join(name);
|
||||
let mut permissions = std::fs::metadata(&path).unwrap().permissions();
|
||||
permissions.set_readonly(read_only);
|
||||
std::fs::set_permissions(&path, permissions).unwrap();
|
||||
}
|
||||
};
|
||||
set_read_only(true);
|
||||
let copies = store.make_available(GOOGLE_FONTS, "Test Sans");
|
||||
set_read_only(false);
|
||||
assert_eq!(copies.unwrap().len(), 3, "a read-only store file still copies");
|
||||
assert!(entries(&shared.join("testsans")).iter().all(|name| !name.starts_with('.')), "no copy is left aside");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[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.
|
||||
#[cfg(unix)]
|
||||
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());
|
||||
// Absolute on every platform: `/elsewhere` isn't on Windows.
|
||||
let elsewhere = root.join("elsewhere");
|
||||
let host = [("HOST_XDG_DATA_HOME", elsewhere.to_str().unwrap())];
|
||||
assert!(with(&host, &flatpak).is_err(), "the grant is for another folder");
|
||||
info("xdg-data/fonts;");
|
||||
assert_eq!(with(&host, &flatpak), Ok(elsewhere.join("fonts/Craft")));
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
@@ -95,13 +95,17 @@ below), and `Embed::documents(&["Noto Sans", …])` only the families it names (
|
||||
- `embedded_elsewhere(&["Noto Sans Math", …])` names families another table of the app embeds,
|
||||
so `check_text` and the catalog check count their characters as covered.
|
||||
- `dir(path)` and `required(bool)` override the two environment variables.
|
||||
- `tab_face()` also embeds Noto Sans Condensed SemiBold from `fonts/latin-manifest.txt`, with the
|
||||
role `tab`. `scripts` and `filter` do not apply to it. A checkout without that manifest or its
|
||||
row embeds the other faces and prints a warning, even with `CRAFT_FONTS_REQUIRED=1`.
|
||||
|
||||
`write` returns the embedded `ManifestEntry`s, for build-time checks such as "the interface face
|
||||
is present". The generated file is a slice expression of `EmbeddedFace { family, style, scripts,
|
||||
index, bytes, role }` literals; any struct with those fields and that name in scope works too.
|
||||
`role` is the manifest line's ninth field: `Some("ui")`, `Some("mono")`, `Some("signature")` or
|
||||
`None`; craft-ui's font stack leads the Monospace family with the `mono` face and the signature
|
||||
family (`FontRef::signature()`) with the `signature` face. `EmbeddedFace` itself has `name()`,
|
||||
`None`, or `Some("tab")` on the face `tab_face()` adds; craft-ui's font stack leads the Monospace
|
||||
family with the `mono` face, the signature family (`FontRef::signature()`) with the `signature`
|
||||
face and the tab-title family with the `tab` face. `EmbeddedFace` itself has `name()`,
|
||||
`has_script(tag)`, `is_cjk()` and `weight()`.
|
||||
|
||||
## Document fonts
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use crate::cmap::Cmap;
|
||||
use crate::manifest::{ManifestEntry, ParseError, parse_manifest, script_matches};
|
||||
use crate::manifest::{ManifestEntry, ParseError, TAB_FACE, TAB_ROLE, parse_manifest, script_matches};
|
||||
|
||||
const DIR_VAR: &str = "CRAFT_FONTS_DIR";
|
||||
const REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED";
|
||||
@@ -55,6 +55,35 @@ fn rerun_if_changed(cargo: &mut Vec<String>, path: &Path) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `entry` of `manifest` as a face to embed, once its font file resolves to a file inside the checkout `root` and its
|
||||
/// licence file, if it exists, does too.
|
||||
fn checked_face(manifest: &Path, dir: &Path, root: &Path, entry: ManifestEntry, cut: bool, cargo: &mut Vec<String>) -> Result<Face, Error> {
|
||||
let manifest = manifest.to_path_buf();
|
||||
// A manifest path names a file in the checkout, and is served under the same name.
|
||||
for file in [&entry.file, &entry.licence_file] {
|
||||
if !file.is_empty() && !is_checkout_relative(file) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
|
||||
}
|
||||
}
|
||||
let file = dir.join(&entry.file);
|
||||
// `include_bytes!` resolves relative paths from the including source file.
|
||||
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
|
||||
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
|
||||
// missing licence is only warned about when serving; one that exists must be inside.
|
||||
if !path.starts_with(root) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(root)) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
rerun_if_changed(cargo, &path)?;
|
||||
let (index, sha256) = (entry.index, entry.sha256.clone());
|
||||
Ok(Face { entry, path, index, cut, sha256 })
|
||||
}
|
||||
|
||||
/// Whether the build script is building for wasm32 (web builds usually embed fewer faces).
|
||||
pub fn target_is_wasm() -> bool {
|
||||
std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|arch| arch == "wasm32")
|
||||
@@ -75,6 +104,7 @@ pub struct Embed {
|
||||
families: Option<Vec<String>>,
|
||||
elsewhere: Vec<String>,
|
||||
serve: Option<Serve>,
|
||||
tab: bool,
|
||||
}
|
||||
|
||||
/// Where [`Embed::serve`] copies the faces, and the URL prefix they are served under.
|
||||
@@ -174,6 +204,18 @@ impl Embed {
|
||||
self
|
||||
}
|
||||
|
||||
/// Also embed the tab-title face, Noto Sans Condensed SemiBold ([`TAB_FACE`]), from the checkout's
|
||||
/// `fonts/latin-manifest.txt`, with the `tab` role ([`TAB_ROLE`]); craft-ui's font stack leads its tab-title family
|
||||
/// with it. [`Embed::scripts`] and [`Embed::filter`] do not apply to it. A checkout without that manifest, or a
|
||||
/// manifest without the face's row, embeds the other faces and prints a `cargo::warning`, required or not. A
|
||||
/// manifest that does not parse, or a row whose file is missing or outside the checkout, is an [`Error`] when
|
||||
/// required and a `cargo::warning` otherwise; the other faces are embedded either way when not required. A
|
||||
/// [`Embed::serve`] table carries no roles, so it leaves the face out and prints a `cargo::warning`.
|
||||
pub fn tab_face(mut self) -> Self {
|
||||
self.tab = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Read this checkout instead of `CRAFT_FONTS_DIR`.
|
||||
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
|
||||
self.dir = Some(dir.into());
|
||||
@@ -239,7 +281,7 @@ impl Embed {
|
||||
|
||||
let selected = match &dir {
|
||||
None => Err(Error::NotSet),
|
||||
Some(dir) => self.select(dir, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
|
||||
Some(dir) => self.select(dir, required, cargo).and_then(|faces| if required { self.check_required(dir, faces) } else { Ok(faces) }),
|
||||
};
|
||||
let mut selected = selected;
|
||||
if let Ok(faces) = &mut selected {
|
||||
@@ -278,8 +320,39 @@ impl Embed {
|
||||
Ok(faces)
|
||||
}
|
||||
|
||||
/// The tab-title face of `fonts/latin-manifest.txt` ([`TAB_FACE`]), with the [`TAB_ROLE`] role. A checkout without
|
||||
/// that manifest, or a manifest without the face's row, gives `None` and a `cargo::warning`.
|
||||
fn select_tab_face(&self, dir: &Path, root: &Path, cargo: &mut Vec<String>) -> Result<Option<Face>, Error> {
|
||||
let manifest = dir.join("fonts/latin-manifest.txt");
|
||||
let text = match read_text_bounded(&manifest, MAX_MANIFEST_BYTES) {
|
||||
Ok(text) => text,
|
||||
Err(source) if source.kind() == io::ErrorKind::NotFound => {
|
||||
// Cargo treats a missing watched file as changed, so the build watches the folder the manifest would be in.
|
||||
rerun_if_changed(cargo, &dir.join("fonts"))?;
|
||||
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} does not exist", manifest.display()));
|
||||
return Ok(None);
|
||||
}
|
||||
Err(source) => return Err(Error::Read { path: manifest, source }),
|
||||
};
|
||||
rerun_if_changed(cargo, &manifest)?;
|
||||
let entries = parse_manifest(&text).map_err(|error| Error::Parse { manifest: manifest.clone(), error })?;
|
||||
let (family, style) = TAB_FACE;
|
||||
let Some(mut entry) = entries.into_iter().find(|entry| entry.family == family && entry.style == style) else {
|
||||
cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {} has no {family} {style} row", manifest.display()));
|
||||
return Ok(None);
|
||||
};
|
||||
entry.role = Some(TAB_ROLE.to_owned());
|
||||
let file = dir.join(&entry.file);
|
||||
if !file.exists() {
|
||||
// Cargo treats a missing watched file as changed, so the build watches the nearest folder that exists.
|
||||
let folder = file.ancestors().skip(1).find(|folder| folder.is_dir()).unwrap_or(dir);
|
||||
rerun_if_changed(cargo, folder)?;
|
||||
}
|
||||
checked_face(&manifest, dir, root, entry, false, cargo).map(Some)
|
||||
}
|
||||
|
||||
/// The wanted manifest entries with their canonical file paths.
|
||||
fn select(&self, dir: &Path, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
|
||||
fn select(&self, dir: &Path, required: bool, cargo: &mut Vec<String>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
let text = read_text_bounded(&manifest, MAX_MANIFEST_BYTES).map_err(|source| Error::Read { path: manifest.clone(), source })?;
|
||||
// Cargo treats a missing watched file as changed, which would rerun the build every time.
|
||||
@@ -325,29 +398,17 @@ impl Embed {
|
||||
uncut.push(format!("{} {}", entry.family, entry.style));
|
||||
continue;
|
||||
}
|
||||
// A manifest path names a file in the checkout, and is served under the same name.
|
||||
for file in [&entry.file, &entry.licence_file] {
|
||||
if !file.is_empty() && !is_checkout_relative(file) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: file.clone() });
|
||||
}
|
||||
faces.push(checked_face(&manifest, dir, &root, entry, cut, cargo)?);
|
||||
}
|
||||
if self.tab && self.serve.is_some() {
|
||||
cargo.push("cargo::warning=craft-fonts: not serving the tab-title face: a served table carries no roles".to_owned());
|
||||
} else if self.tab {
|
||||
match self.select_tab_face(dir, &root, cargo) {
|
||||
Ok(Some(face)) => faces.push(face),
|
||||
Ok(None) => {}
|
||||
Err(e) if required => return Err(e),
|
||||
Err(e) => cargo.push(format!("cargo::warning=craft-fonts: not embedding the tab-title face: {e}")),
|
||||
}
|
||||
let file = dir.join(&entry.file);
|
||||
// `include_bytes!` resolves relative paths from the including source file.
|
||||
let path = file.canonicalize().map_err(|source| Error::Read { path: file, source })?;
|
||||
// A symlink in the checkout must not pull a file from elsewhere on the build host. A
|
||||
// missing licence is only warned about when serving; one that exists must be inside.
|
||||
if !path.starts_with(&root) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
if !entry.licence_file.is_empty() && dir.join(&entry.licence_file).canonicalize().is_ok_and(|licence| !licence.starts_with(&root)) {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.licence_file });
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(Error::OutsideCheckout { manifest, file: entry.file });
|
||||
}
|
||||
rerun_if_changed(cargo, &path)?;
|
||||
let (index, sha256) = (entry.index, entry.sha256.clone());
|
||||
faces.push(Face { entry, path, index, cut, sha256 });
|
||||
}
|
||||
if !uncut.is_empty() {
|
||||
let why = if self.catalogs.is_some() { "Embed::subset_to was given no translation catalogs" } else { "no translation catalogs" };
|
||||
@@ -451,7 +512,8 @@ impl Embed {
|
||||
}
|
||||
|
||||
/// Warn about each catalog's and [`Embed::check_text`] file's characters that neither an
|
||||
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers.
|
||||
/// embedded face nor an [`Embed::embedded_elsewhere`] face covers. The tab-title face, which draws only tab titles,
|
||||
/// covers none of them.
|
||||
fn check_coverage(&self, faces: &[Face], dir: &Path, cargo: &mut Vec<String>) {
|
||||
let files = self.checked_files();
|
||||
if files.is_empty() {
|
||||
@@ -460,6 +522,7 @@ impl Embed {
|
||||
let elsewhere = self.elsewhere(dir, cargo);
|
||||
let fonts: Vec<(&ManifestEntry, u32, Option<Vec<u8>>)> = faces
|
||||
.iter()
|
||||
.filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE))
|
||||
.map(|face| (&face.entry, face.index, read_bounded(&face.path, MAX_FILE_BYTES).ok()))
|
||||
.chain(elsewhere.iter().map(|entry| (entry, entry.index, read_bounded(&dir.join(&entry.file), MAX_FILE_BYTES).ok())))
|
||||
.collect();
|
||||
@@ -496,16 +559,19 @@ impl Embed {
|
||||
}
|
||||
}
|
||||
|
||||
/// `faces` when `fonts/manifest.txt` gave at least one, covering every script of [`Embed::scripts`]; the tab-title
|
||||
/// face, which neither selection applies to, counts for neither.
|
||||
fn check_required(&self, dir: &Path, faces: Vec<Face>) -> Result<Vec<Face>, Error> {
|
||||
let manifest = dir.join("fonts/manifest.txt");
|
||||
if faces.is_empty() {
|
||||
let selected = || faces.iter().filter(|face| face.entry.role.as_deref() != Some(TAB_ROLE));
|
||||
if selected().next().is_none() {
|
||||
return Err(Error::NoFaces { manifest });
|
||||
}
|
||||
let missing: Vec<String> = self
|
||||
.scripts
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|tag| !faces.iter().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
|
||||
.filter(|tag| !selected().any(|face| face.entry.scripts.iter().any(|s| script_matches(s, tag))))
|
||||
.cloned()
|
||||
.collect();
|
||||
if missing.is_empty() { Ok(faces) } else { Err(Error::MissingScripts { manifest, scripts: missing }) }
|
||||
|
||||
@@ -62,7 +62,7 @@ mod sha256;
|
||||
mod tests;
|
||||
|
||||
pub use embed::{Embed, Error, target_is_wasm};
|
||||
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, UI_ROLE, parse_manifest};
|
||||
pub use manifest::{CJK_SCRIPTS, MONO_ROLE, ManifestEntry, ParseError, SIGNATURE_ROLE, TAB_FACE, TAB_ROLE, UI_ROLE, parse_manifest};
|
||||
|
||||
/// A craft-fonts face embedded by [`Embed`]: one line of `fonts/manifest.txt`.
|
||||
///
|
||||
@@ -81,8 +81,8 @@ pub struct EmbeddedFace {
|
||||
/// The font file's bytes, from `include_bytes!`.
|
||||
pub bytes: &'static [u8],
|
||||
/// The manifest line's `role`: `Some("ui")` for an interface face ([`UI_ROLE`]), `Some("mono")` for the
|
||||
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `None` for a
|
||||
/// line without one.
|
||||
/// monospace face ([`MONO_ROLE`]), `Some("signature")` for the signature face ([`SIGNATURE_ROLE`]), `Some("tab")`
|
||||
/// for the tab-title face [`Embed::tab_face`] adds ([`TAB_ROLE`]), `None` for a line without one.
|
||||
pub role: Option<&'static str>,
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
//! translation catalogs; `mono` for the monospace face, which leads an app's Monospace family; or
|
||||
//! `signature` for the handwriting face, which leads the signature family.
|
||||
//! Fields after the ninth are ignored, so a manifest that gains a field still embeds.
|
||||
//! `fonts/latin-manifest.txt` has the same format; [`Embed::tab_face`](crate::Embed::tab_face)
|
||||
//! reads one row of it and gives that face the `tab` role.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -37,6 +39,7 @@ pub struct ManifestEntry {
|
||||
pub source: String,
|
||||
/// The optional ninth field: `Some("ui")` for an interface face, `Some("mono")` for the
|
||||
/// monospace face, `Some("signature")` for the signature face, `None` when the line has no role.
|
||||
/// [`Embed::tab_face`](crate::Embed::tab_face) sets `Some("tab")` on the face it adds.
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
@@ -72,6 +75,13 @@ pub const MONO_ROLE: &str = "mono";
|
||||
/// The `role` of a signature face: `FontRef::signature()` selects the embedded faces that have it.
|
||||
pub const SIGNATURE_ROLE: &str = "signature";
|
||||
|
||||
/// The `role` [`Embed::tab_face`](crate::Embed::tab_face) gives the tab-title face it embeds from
|
||||
/// `fonts/latin-manifest.txt`: the tab-title family leads with the embedded face that has it.
|
||||
pub const TAB_ROLE: &str = "tab";
|
||||
|
||||
/// The family and style of the tab-title face in `fonts/latin-manifest.txt`.
|
||||
pub const TAB_FACE: (&str, &str) = ("Noto Sans", "Condensed SemiBold");
|
||||
|
||||
/// Script tags of the CJK faces, which craft-fonts also ships as interface faces. `Hant` covers
|
||||
/// `Hant-HK`.
|
||||
pub const CJK_SCRIPTS: &[&str] = &["Hans", "Hant", "Jpan", "Kore", "Hani"];
|
||||
|
||||
@@ -368,3 +368,75 @@ fn an_oversized_manifest_and_a_directory_face_are_errors() {
|
||||
let r = run(Embed::new(), Some(&dir), None);
|
||||
assert!(r.result.is_ok() && warnings(&r).iter().any(|w| w.contains("larger than")), "{:?}", r.cargo);
|
||||
}
|
||||
|
||||
/// `Embed::tab_face` adds only the Noto Sans Condensed SemiBold row of `fonts/latin-manifest.txt`, with the `tab` role.
|
||||
/// A checkout without that manifest or row keeps its other faces, required or not; a broken manifest or row is an
|
||||
/// error only when required. The face counts for none of the scripts a required build asks for and covers none of the
|
||||
/// characters of a checked text, and a served table leaves it out.
|
||||
#[test]
|
||||
fn the_tab_face_comes_from_the_latin_manifest_with_the_tab_role() {
|
||||
let scratch = Scratch::new("tab-face");
|
||||
let dir = checkout(&scratch, &[("Noto Sans Arabic", "Arab", "", tiny_font(&[(0x627, 0x627, None)], &[]))]);
|
||||
std::fs::write(dir.join("fonts/OFL.txt"), b"licence").unwrap();
|
||||
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
|
||||
std::fs::write(dir.join("fonts/inter.ttf"), tiny_font(&[(0x41, 0x5A, None)], &[])).unwrap();
|
||||
let latin = dir.join("fonts/latin-manifest.txt");
|
||||
let row = |family: &str, style: &str, file: &str| format!("{family} | {style} | {file} | Latn | OFL-1.1 | fonts/OFL.txt | 00 | src\n");
|
||||
let both = row("Inter", "SemiBold", "fonts/inter.ttf") + &row("Noto Sans", "Condensed SemiBold", "fonts/condensed.ttf");
|
||||
std::fs::write(&latin, &both).unwrap();
|
||||
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
assert!(r.table.contains(r#"family: "Noto Sans", style: "Condensed SemiBold""#) && r.table.contains(r#"role: Some("tab")"#), "{}", r.table);
|
||||
assert!(!r.table.contains("Inter"), "{}", r.table);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", latin.display())), "{:?}", r.cargo);
|
||||
// Scripts and the filter narrow only the main manifest's faces.
|
||||
let r = run(Embed::new().scripts(&["Arab"]).filter(|f| f.has_script("Arab")).tab_face(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
// The tab-title face does not stand in for a required script the main manifest lacks.
|
||||
let r = run(Embed::new().scripts(&["Latn"]).tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(&r.result, Err(Error::NoFaces { .. })), "{:?}", r.result);
|
||||
let r = run(Embed::new().scripts(&["Arab", "Latn"]).tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(&r.result, Err(Error::MissingScripts { scripts, .. }) if scripts == &["Latn"]), "{:?}", r.result);
|
||||
let r = run(Embed::new(), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
// A served table carries no roles, so it leaves the face out.
|
||||
let r = run(Embed::new().tab_face().serve(scratch.0.join("served"), "fonts/"), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("not serving the tab-title face")), "{:?}", r.cargo);
|
||||
// Only tab titles draw in the face, so it covers none of the characters of a checked text.
|
||||
std::fs::write(dir.join("fonts/condensed.ttf"), tiny_font(&[(0x41, 0x5A, None), (0x4E00, 0x4E00, None)], &[])).unwrap();
|
||||
let text = scratch.0.join("text.ftl");
|
||||
std::fs::write(&text, "x = \u{4E00}\n").unwrap();
|
||||
let r = run(Embed::new().tab_face().check_text([&text]), Some(&dir), Some("1"));
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular", "Noto Sans Condensed SemiBold"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("1 character no embedded face covers (\u{4E00})")), "{:?}", r.cargo);
|
||||
|
||||
// No row for the face, or no latin manifest at all: the other faces and a warning, even when required.
|
||||
std::fs::write(&latin, row("Inter", "SemiBold", "fonts/inter.ttf")).unwrap();
|
||||
for required in [None, Some("1")] {
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), required);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("has no Noto Sans Condensed SemiBold row")), "{:?}", r.cargo);
|
||||
}
|
||||
std::fs::remove_file(&latin).unwrap();
|
||||
for required in [None, Some("1")] {
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), required);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"]);
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("latin-manifest.txt does not exist")), "{:?}", r.cargo);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
|
||||
}
|
||||
|
||||
// A manifest line that does not parse, or a row whose file is missing.
|
||||
for broken in ["Noto Sans | Condensed SemiBold | fonts/condensed.ttf\n".to_owned(), row("Noto Sans", "Condensed SemiBold", "fonts/gone.ttf")] {
|
||||
std::fs::write(&latin, &broken).unwrap();
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), None);
|
||||
assert_eq!(r.result.as_ref().unwrap(), &["Noto Sans Arabic Regular"], "{broken}");
|
||||
assert!(warnings(&r).iter().any(|w| w.contains("not embedding the tab-title face")), "{broken}: {:?}", r.cargo);
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), Some("1"));
|
||||
assert!(matches!(r.result, Err(Error::Parse { .. } | Error::Read { .. })), "{broken}: {:?}", r.result);
|
||||
}
|
||||
// The build reruns when the missing file is added: it watches the folder the file would be in.
|
||||
let r = run(Embed::new().tab_face(), Some(&dir), None);
|
||||
assert!(r.cargo.iter().any(|l| l == &format!("cargo::rerun-if-changed={}", dir.join("fonts").display())), "{:?}", r.cargo);
|
||||
}
|
||||
@@ -19,6 +19,8 @@
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::VecDeque;
|
||||
use std::hash::Hash;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
|
||||
use std::thread::{self, ThreadId};
|
||||
@@ -94,14 +96,17 @@ pub enum QueueOrder {
|
||||
|
||||
impl QueueOptions {
|
||||
/// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when
|
||||
/// the core count is unknown); 0 on wasm32.
|
||||
/// the core count is unknown); 0 on wasm32. The core count is read once per process.
|
||||
// lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8;
|
||||
// ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`).
|
||||
pub fn default_lanes() -> usize {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
return 0;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))
|
||||
{
|
||||
static LANES: OnceLock<usize> = OnceLock::new();
|
||||
*LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -310,7 +310,8 @@ impl Component for Histogram<'_> {
|
||||
let accent = super::data::color32(colors.data.selection);
|
||||
let warn = cx.tone(craft_theme::variant::Tone::Warn);
|
||||
HistogramStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(cx.tokens.size.plot.width, tall)),
|
||||
// The width's floor is `measure`'s (`picture_width`), which a narrow room may take below the plot width.
|
||||
metrics: Metrics::new().min_size(Vec2::new(0.0, tall)),
|
||||
focus: cx.focus_look(),
|
||||
caption: TextLook::new(TypeRole::Caption, Stateful::new(cx.color(colors.text.normal))),
|
||||
stale: IconLook::new(cx.tokens.size.icon.sm, Stateful::new(warn)),
|
||||
|
||||
Loaded 100 of 411 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user