diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000000..873f4f7aac --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[lints] +cargo.unused_workspace_dependencies = "allow" diff --git a/.gitattributes b/.gitattributes index 5d79390a23..fa27512336 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,10 @@ +# Font-build test fixtures are compared byte for byte: a checkout must not convert them. +crates/fonts-build/tests/fixture/** -text + +# The pinned font index is hashed and compiled in as committed: a checkout must not convert its +# line endings, or `Index::bundled` fails its checksum on Windows. +crates/font-store/index/sources.json -text +crates/font-store/index/indexes/*.gz binary + # Copies of the vendored krilla source diff, one per patch (see vendor/krilla/README.craft.md). vendor/krilla/patches/*.patch linguist-generated=true diff --git a/.github/workflows/atomic.yml b/.github/workflows/atomic.yml index 1471832d28..1a20fa6791 100644 --- a/.github/workflows/atomic.yml +++ b/.github/workflows/atomic.yml @@ -45,3 +45,14 @@ jobs: - name: Check inherited Linux ACLs if: runner.os == 'Linux' run: cargo test -p craft-atomic --locked -- --ignored --nocapture + + wasm: + name: Atomic WASM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: wasm32-unknown-unknown + - run: cargo check -p craft-atomic --target wasm32-unknown-unknown + diff --git a/.github/workflows/cms.yml b/.github/workflows/cms.yml new file mode 100644 index 0000000000..a15a48c9d3 --- /dev/null +++ b/.github/workflows/cms.yml @@ -0,0 +1,26 @@ +name: Colour management + +on: + workflow_dispatch: + push: + branches: [main] + paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] + pull_request: + paths: ['crates/cms/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/cms.yml'] + +permissions: + contents: read + +jobs: + cms: + timeout-minutes: 20 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - run: cargo clippy -p craft-cms --all-targets --all-features --locked -- -D warnings + # Release: the FOGRA39 fit and ink-limit tests take about 35 s in debug and 4 s here. Tests that need + # installed system profiles print "skipped:" when none are present. + - run: cargo test -p craft-cms --all-features --release --locked -- --nocapture diff --git a/.github/workflows/menu.yml b/.github/workflows/menu.yml new file mode 100644 index 0000000000..6d0e082cb1 --- /dev/null +++ b/.github/workflows/menu.yml @@ -0,0 +1,39 @@ +name: Menu + +on: + push: + branches: [main] + paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] + pull_request: + paths: ["crates/menu/**", "crates/keymap/**", "crates/quit/**", "Cargo.toml", "Cargo.lock", ".github/workflows/menu.yml"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: menu-${{ github.ref }} + cancel-in-progress: true + +jobs: + linux: + timeout-minutes: 15 + name: Menu (Linux) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + with: + components: rustfmt, clippy + targets: aarch64-apple-darwin, wasm32-unknown-unknown + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: craft-menu-linux + - run: cargo fmt -p craft-menu --check + - run: cargo clippy -p craft-menu --all-targets --locked -- -D warnings + # The macOS backend type-checks from Linux; it needs no linker or SDK. + - run: cargo clippy -p craft-menu --lib --locked --target aarch64-apple-darwin -- -D warnings + - run: cargo clippy -p craft-menu --lib --locked --target wasm32-unknown-unknown -- -D warnings + - run: cargo test -p craft-menu --locked diff --git a/.github/workflows/pdf.yml b/.github/workflows/pdf.yml index c72ac7f727..a494d085cf 100644 --- a/.github/workflows/pdf.yml +++ b/.github/workflows/pdf.yml @@ -3,9 +3,9 @@ name: Shared PDF on: push: branches: [main] - paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] + paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**","scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] pull_request: - paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] + paths: ["crates/pdf/**", "crates/plate-test/**", "crates/prepress/**", "crates/cms/**", "vendor/hayro*/**", "vendor/krilla/**", "vendor/linesweeper/**","scripts/test-pdf-backends.sh", "scripts/*fetch-pdf-test-fonts.py", "Cargo.toml", "Cargo.lock", ".github/workflows/pdf.yml"] workflow_dispatch: permissions: diff --git a/.github/workflows/window.yml b/.github/workflows/window.yml index b07bce3844..f570ef5ceb 100644 --- a/.github/workflows/window.yml +++ b/.github/workflows/window.yml @@ -46,3 +46,5 @@ jobs: - run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings - run: cargo test -p craft-window --locked -- --nocapture - run: cargo test -p craft-window --locked --features egui -- --nocapture + - run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings + - run: cargo test -p craft-window --locked --features restore,egui -- --nocapture diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml new file mode 100644 index 0000000000..cf9499419e --- /dev/null +++ b/.github/workflows/workspace.yml @@ -0,0 +1,77 @@ +name: Workspace + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + native: + name: Workspace + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + timeout-minutes: 120 + tools: "" + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: | + set -euo pipefail + corpus_fetcher=.test-inputs/photocraft + mkdir -p "$corpus_fetcher" + git -C "$corpus_fetcher" init + git -C "$corpus_fetcher" remote add origin https://github.com/storytold/PhotoCraft.git + git -C "$corpus_fetcher" fetch --quiet --depth=1 origin 74330157cb601573ae4523a95bb9132822fc3918 + git -C "$corpus_fetcher" checkout --quiet --detach FETCH_HEAD + (cd "$corpus_fetcher" && cargo xtask corpus --psd --psd-tools --atn) + python scripts/test-fetch-pdf-test-fonts.py + python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" + printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$corpus_fetcher/corpus" >> "$GITHUB_ENV" + printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" + command: | + cargo fmt --check + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo clippy --workspace --all-targets --all-features --locked -- -D warnings + cargo test --workspace --locked + cargo test --workspace --all-features --locked + windows-command: | + powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' + cargo fmt --check + cargo clippy --workspace --all-targets --locked -- -D warnings + cargo clippy --workspace --all-targets --all-features --locked -- -D warnings + cargo test --workspace --locked + cargo test --workspace --all-features --locked + + msrv: + name: Rust 1.95 + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + toolchain: 1.95.0 + targets: "" + tools: "" + craft-fonts-ref: "" + require-craft-fonts: false + timeout-minutes: 15 + dev-debug: "" + command: cargo check --workspace --lib --all-features --locked + + wasm: + name: UI and settings WASM + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest"]' + targets: wasm32-unknown-unknown + tools: "" + craft-fonts-ref: "" + require-craft-fonts: false + timeout-minutes: 15 + command: cargo check -p craft-ui -p craft-settings --all-features --locked --target wasm32-unknown-unknown diff --git a/.gitignore b/.gitignore index c725b3c4b7..3c25188721 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ plan/ plans/ /target +# Also a sub-crate's own build directory: `crates/pdf/read-only-contract/target/` is not covered +# by the anchored `/target` above, and 803 of its files reached a commit once (#185 review). +target/ .DS_Store /.claude/ .idea/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..31364ecf95 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,65 @@ +# Changelog + +All crates share the workspace version. See [the versioning policy](docs/versioning.md). + +## v0.1.0 — 2026-10-12 + +First coordinated Git release of craft-libs. Applications can pin a named baseline instead of +following development commits. This is an initial 0.x release: compatibility is maintained +within `0.1.x`; changes requiring consumer migration use a new minor version. + +### Included crates + +- **craft-atomic:** same-directory staged file replacement, exclusive creation, streaming + writes, transient rename retries and fault-injection support, extracted from PhotoCraft. +- **craft-settings:** app-owned TOML settings with platform/portable paths, atomic saves, + backups, damaged-file recovery, schema migrations and preservation of unknown fields. +- **craft-quit:** native macOS termination, optional egui close handling and an optional + application menu. Save decisions and prompts stay with the app. +- **craft-print:** CUPS and native Windows PDF submission, printer discovery, copies, duplex, + colour and scaling options. Includes bounded PDF sheet handling and the pinned Windows + completion fix. PDF generation stays with the app. +- **craft-ui:** egui icon buttons, tabs, splits, resize handles, toolbar overflow, transactional + docking, theme helpers and print-settings controls. Commands, content, localization and + application state stay with the consumer. Docking serialization is opt-in through `serde`. + +### Requirements and adoption + +- Rust **1.95+**, edition 2024. Public UI integrations use **egui 0.36**. +- Use `git = "https://github.com/storytold/craft-libs", tag = "v0.1.0"` for each required crate; + use the same tag everywhere. The [README](README.md#use-a-released-version) has a complete + manifest example and a commit-pin alternative. Commit application lockfiles. +- No automatic migration from an arbitrary earlier Git revision is implied. Compare the API + you used with this release and test affected workflows before changing pins. +- For `craft-quit`, run the close hook last in `eframe::App::logic`, after the app's unsaved-work + decision. Finish asynchronous saves before requesting close; termination does not execute + code after `run_native`. See the crate's API documentation before adoption. +- This release is distributed through Git only. No crates.io packages are published by it. + +### Platform coverage and known limits + +The release gate checks the workspace on Linux, macOS and Windows with default and all features, +plus Linux minimum-compiler and UI/settings WASM checks. UI tests include offscreen visual +regressions. Windows print tests exercise a temporary paused spooler queue; those checks do +not establish physical printer fidelity or every application's native GUI behavior. + +- `craft-ui` supports native and WASM use. Font coverage, bidirectional text and screen-reader + behavior still depend on the application and upstream stack; see [#17](https://github.com/storytold/craft-libs/issues/17). +- `craft-settings` persistence is native-only. WASM exposes settings traits, document helpers + and error types. Concurrent writers are best-effort, last-writer-wins; strict coordination + needs an application-owned lock. +- `craft-atomic` does not preserve all filesystem metadata during replacement. Directory sync + is best effort; tests do not prove physical power-loss durability. See its README's contract. +- `craft-quit`'s native behavior is macOS-specific; other platforms keep their normal close + path. Earlier hardware testing of the close hook is recorded in + [#3](https://github.com/storytold/craft-libs/issues/3); it does not qualify every consuming app. +- `craft-print` requires CUPS command-line tools on Linux/macOS or the native Windows spooler. + Browser submission is unsupported. Windows accepts a bounded subset of print-ready PDFs; + unsupported inputs and driver paper/scaling mismatches return errors. Printing is synchronous, + so call it from a worker. Physical output needs hardware testing. +- Windows printing retains a pinned Git dependency on the maintained `winprint` fork. Its + build dependencies require the license/advisory policy exceptions documented in + [craft-print's README](crates/print/README.md). Registry publication is deferred. + +Planned crates and open feature PRs are not part of this release. Existing commit pins remain +valid, and consumers do not need to update simply because `main` changes. diff --git a/Cargo.lock b/Cargo.lock index c498071459..cf0e0bd472 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2386,9 +2386,14 @@ dependencies = [ name = "craft-window" version = "0.1.0" dependencies = [ + "craft-atomic", + "craft-settings", "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "serde", + "serde_json", + "tempfile", "wayland-client", ] diff --git a/Cargo.toml b/Cargo.toml index 24e26a3843..629bab64cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -149,11 +149,13 @@ chrono = { version = "0.4.45", default-features = false, features = ["std"] } [workspace.lints.rust] unsafe_code = "forbid" +unused_workspace_dependencies = "allow" unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } [workspace.lints.clippy] cognitive_complexity = "deny" too_many_arguments = "deny" +unused_workspace_dependencies = "allow" wildcard_imports = "deny" dbg_macro = "warn" todo = "warn" diff --git a/README.md b/README.md index 825ff5f8cd..a45fd58705 100644 --- a/README.md +++ b/README.md @@ -17,12 +17,41 @@ A Cargo workspace (edition 2024, resolver 3). Each library is a crate under `cra (`license.workspace = true`, and so on) and `[lints] workspace = true`. Register each crate in `[workspace.dependencies]` in the root `Cargo.toml`. -Apps depend on a crate by git: +## Use a released version + +The first coordinated release is **[v0.1.0](https://github.com/storytold/craft-libs/releases/tag/v0.1.0)**. +It gives consumers a fixed baseline while development continues on `main`. All five crates +share this version. They require Rust 1.95 or later; the UI integrations use egui 0.36. + +Add only the crates you need, using the same tag for every craft-libs dependency: ```toml -craft- = { git = "https://github.com/storytold/craft-libs", rev = "" } +[dependencies] +craft-ui = { git = "https://github.com/storytold/craft-libs", tag = "v0.1.0" } +craft-settings = { git = "https://github.com/storytold/craft-libs", tag = "v0.1.0" } +# Optional, for egui close handling and the macOS application menu: +craft-quit = { git = "https://github.com/storytold/craft-libs", tag = "v0.1.0", features = ["menu"] } ``` +`craft-atomic` and `craft-print` use the same dependency syntax. Enable `craft-ui`'s +`serde` feature if you need to serialize its docking layout. These are Git releases; +crates.io publication is deferred. + +Release tags are never moved or reused. For a commit pin, resolve the tag with +`git ls-remote https://github.com/storytold/craft-libs 'refs/tags/v0.1.0^{}'` and replace +`tag = "v0.1.0"` with `rev = ""` on every craft-libs dependency. +Use either `tag` or `rev`, not both. An existing commit pin keeps working; switching to this +release may require adapting to changes since that commit. + +Commit your application's `Cargo.lock` and build with `cargo build --locked` for reproducible +Rust dependency resolution. A Git pin fixes craft-libs source, not every transitive dependency. +A library's own lockfile does not constrain its downstream consumers. Upgrade deliberately: +read the release notes, update all craft-libs pins together, refresh the lockfile with +`cargo check`, and run your application's tests and affected workflows before committing. + +See the [release notes](CHANGELOG.md) for included functionality and known limits, and the +[versioning policy](docs/versioning.md) for compatibility guarantees and release checks. + ## Libraries - [`craft-platform`](crates/platform/README.md): optional native dialog lifecycle, Linux/BSD desktop appearance observation and browser download ownership; application policy stays in the apps. diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index 2e448abc5d..1590372ad5 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -558,7 +558,11 @@ pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); let stem: String = file.chars().take(64).collect(); - format!(".{stem}.{}-{n}.craft_tmp", std::process::id()) + #[cfg(not(target_arch = "wasm32"))] + let pid = std::process::id(); + #[cfg(target_arch = "wasm32")] + let pid = 0; + format!(".{stem}.{pid}-{n}.craft_tmp") } /// The end of an error message: whether an original file was left as it was. @@ -621,7 +625,11 @@ mod tests { impl TempDir { fn new(tag: &str) -> Self { static N: AtomicU64 = AtomicU64::new(0); - let d = std::env::temp_dir().join(format!("craft-atomic-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + #[cfg(not(target_arch = "wasm32"))] + let pid = std::process::id(); + #[cfg(target_arch = "wasm32")] + let pid = 0; + let d = std::env::temp_dir().join(format!("craft-atomic-{tag}-{pid}-{}", N.fetch_add(1, Ordering::Relaxed))); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).ok(); Self(d) @@ -1242,4 +1250,18 @@ mod tests { assert_eq!(std::fs::read(&p).ok(), Some(b"best effort data".to_vec())); assert_no_temp(&d.0); } + + #[test] + fn temp_name_format_is_valid() { + let name = temp_name("document.craft"); + assert!(name.starts_with(".document.craft.")); + assert!(name.ends_with(".craft_tmp")); + } + + #[cfg(target_arch = "wasm32")] + #[test] + fn wasm_atomic_write_returns_unsupported() { + let err = atomic_write(Path::new("dummy.craft"), b"data").unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::Unsupported); + } } diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index a59058f082..b1535f78c2 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -111,9 +111,9 @@ impl CmykModel { // Overprints with black: multiplicative in reflectance above a first-surface floor. let floor = 0.006; let mut prim = [[0.0; 3]; 16]; - for m in 0..16 { + for (m, slot) in prim.iter_mut().enumerate() { let p = base[m & 7]; - prim[m] = if m & 8 == 0 { + *slot = if m & 8 == 0 { p } else { std::array::from_fn(|i| { @@ -133,7 +133,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -141,7 +141,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/cms/tests/cms.rs b/crates/cms/tests/cms.rs index 727034d21e..37504fc334 100644 --- a/crates/cms/tests/cms.rs +++ b/crates/cms/tests/cms.rs @@ -587,6 +587,9 @@ fn system_profiles() { } } } + if seen == 0 { + eprintln!("skipped: no system ICC profiles found"); + } eprintln!("parsed {seen} system profiles"); } @@ -614,12 +617,18 @@ fn oracle_moxcms_rgb() { fn oracle_moxcms_system_cmyk() { use moxcms::{ColorProfile, Layout, RenderingIntent, TransformOptions as MoxOpts}; let path = "/System/Library/ColorSync/Profiles/Generic CMYK Profile.icc"; - let Ok(bytes) = std::fs::read(path) else { return }; + let Ok(bytes) = std::fs::read(path) else { + eprintln!("skipped: {path} not found"); + return; + }; let ours_p = Profile::parse(&bytes).unwrap(); let theirs_p = ColorProfile::new_from_slice(&bytes).unwrap(); let s = ColorProfile::new_from_slice(&srgb().to_bytes()).unwrap(); let opts = MoxOpts { rendering_intent: RenderingIntent::RelativeColorimetric, ..Default::default() }; - let Ok(mt) = theirs_p.create_transform_8bit(Layout::Rgba, &s, Layout::Rgb, opts) else { return }; + let Ok(mt) = theirs_p.create_transform_8bit(Layout::Rgba, &s, Layout::Rgb, opts) else { + eprintln!("skipped: moxcms cannot build a transform from {path}"); + return; + }; let src: Vec = (0..2048u32).flat_map(|i| [(i * 37 % 256) as u8, (i * 91 % 256) as u8, (i * 13 % 256) as u8, (i * 57 % 256) as u8]).collect(); let mut theirs = vec![0u8; 2048 * 3]; mt.transform(&src, &mut theirs).unwrap(); diff --git a/crates/crs/src/lib.rs b/crates/crs/src/lib.rs index 2585bc6059..6feae22fde 100644 --- a/crates/crs/src/lib.rs +++ b/crates/crs/src/lib.rs @@ -74,7 +74,8 @@ impl Value { } /// The `crs:` settings of a packet, by name without the prefix (`Exposure2012`). Where a name -/// occurs more than once (in several `rdf:Description`s), the last one is kept. +/// occurs more than once (in several `rdf:Description`s), the first text-bearing value is kept, +/// as [`craft_metadata::parse_xmp`] reads every packet: a blank repeat must not hide it. #[derive(Clone, Debug, Default, PartialEq)] pub struct Settings { pub entries: BTreeMap, diff --git a/crates/crs/src/tests.rs b/crates/crs/src/tests.rs index d850e6c3bb..3faab6a2aa 100644 --- a/crates/crs/src/tests.rs +++ b/crates/crs/src/tests.rs @@ -78,10 +78,14 @@ fn structures_other_prefixes_and_other_namespaces() { assert_eq!(masks.items().first().and_then(|m| m.field("crs:What")).and_then(XmpValue::text), Some("Correction")); assert_eq!(s.get("Empty"), Some(&Value::Text(String::new()))); assert_eq!(s.get("format"), None); - // The last value of a repeated name wins. + // A repeated name keeps its first value, as `craft_metadata` reads every packet: an empty + // repeat must not hide what an earlier description said. let second = format!("/>"); let twice = with("crs:Texture=\"1\"").replace("/>", &second); - assert_eq!(Settings::parse(twice.as_bytes()).unwrap().text("Texture"), Some("2")); + assert_eq!(Settings::parse(twice.as_bytes()).unwrap().text("Texture"), Some("1")); + let blank = format!("/>"); + let hiding = with("crs:Texture=\"1\"").replace("/>", &blank); + assert_eq!(Settings::parse(hiding.as_bytes()).unwrap().text("Texture"), Some("1"), "a blank repeat does not win"); } #[test] diff --git a/crates/drawingml/src/preset/extra.rs b/crates/drawingml/src/preset/extra.rs index ad9efb3bd3..391295891c 100644 --- a/crates/drawingml/src/preset/extra.rs +++ b/crates/drawingml/src/preset/extra.rs @@ -764,20 +764,32 @@ mod tests { /// Sizes the digests were taken at: wide, tall and square. const GOLD_SIZES: [(f64, f64); 4] = [(120.0, 80.0), (300.0, 50.0), (64.0, 64.0), (50.0, 300.0)]; + /// `v` as the digest prints it: a value that prints as zero at 3 decimal places becomes + /// `0.0`, so a residue such as `-1.4e-14` left by a sine or cosine of a right angle prints + /// `0.000` whatever its sign. Its sign depends on the platform's libm, and `{:.3}` prints a + /// negative residue as `-0.000`. + fn digest_coord(v: f64) -> f64 { + if v.abs() < 0.0005 { 0.0 } else { v } + } + /// FNV-1a over each outline's path elements, for every adjust set and size. Coordinates are - /// printed to 3 decimal places so last-bit libm differences between platforms do not change it. + /// printed to 3 decimal places through [`digest_coord`] so last-bit libm differences between + /// platforms do not change it. fn outline_digest(name: &str) -> u64 { use std::fmt::Write; + let c = digest_coord; let mut text = String::new(); for adj in GOLD_ADJ { for (w, h) in GOLD_SIZES { let g = build(name, w, h, adj).unwrap_or_else(|| panic!("{name} builds no outline")); for el in g.outline().elements() { let _ = match *el { - PathEl::MoveTo(p) => write!(text, "M{:.3},{:.3}", p.x, p.y), - PathEl::LineTo(p) => write!(text, "L{:.3},{:.3}", p.x, p.y), - PathEl::QuadTo(a, p) => write!(text, "Q{:.3},{:.3},{:.3},{:.3}", a.x, a.y, p.x, p.y), - PathEl::CurveTo(a, b, p) => write!(text, "C{:.3},{:.3},{:.3},{:.3},{:.3},{:.3}", a.x, a.y, b.x, b.y, p.x, p.y), + PathEl::MoveTo(p) => write!(text, "M{:.3},{:.3}", c(p.x), c(p.y)), + PathEl::LineTo(p) => write!(text, "L{:.3},{:.3}", c(p.x), c(p.y)), + PathEl::QuadTo(a, p) => write!(text, "Q{:.3},{:.3},{:.3},{:.3}", c(a.x), c(a.y), c(p.x), c(p.y)), + PathEl::CurveTo(a, b, p) => { + write!(text, "C{:.3},{:.3},{:.3},{:.3},{:.3},{:.3}", c(a.x), c(a.y), c(b.x), c(b.y), c(p.x), c(p.y)) + } PathEl::ClosePath => write!(text, "Z"), }; } @@ -789,21 +801,23 @@ mod tests { /// Digests of every name's outlines as the string dispatch built them (craft-libs 2b35d243; /// DeckCraft's fc35ad67 gave other digests for curvedRightArrow and curvedDownArrow), so - /// this refactor is proven output-identical: any changed outline fails here. + /// this refactor is proven output-identical: any changed outline fails here. pieWedge, + /// curvedRightArrow and curvedDownArrow were taken again when [`digest_coord`] began printing + /// their near-zero residues as `0.000`; their outlines are unchanged. const GOLDEN: [(&str, u64); 38] = [ ("lineInv", 0x4a58a16923e54a4f), ("nonIsoscelesTrapezoid", 0x79eca0b36812e282), - ("pieWedge", 0x2a0d3ffe5e9a481d), + ("pieWedge", 0x5fb58e0214989f4d), ("leftRightArrowCallout", 0x9cd88f0ab55f76e5), ("upDownArrowCallout", 0x568bc91708855007), ("quadArrowCallout", 0xca59015298b1584b), ("circularArrow", 0x4227aa468cfe990e), ("leftCircularArrow", 0x6fc3779ce4b08914), ("leftRightCircularArrow", 0x9dd43d9ba80e47df), - ("curvedRightArrow", 0x83e7dd251401715d), + ("curvedRightArrow", 0xf60d53e01a88930c), ("curvedLeftArrow", 0x82472848de4a9fec), ("curvedUpArrow", 0xcfbd88c1aea4bf9d), - ("curvedDownArrow", 0xa6f75eaf0ee71d49), + ("curvedDownArrow", 0x01b1ac2f13de11b9), ("swooshArrow", 0x63ff193fdf1d0427), ("callout1", 0xe7e0410f96282e8d), ("callout2", 0xcaa7730106a9ee1b), @@ -831,6 +845,19 @@ mod tests { ("chartPlus", 0x979031aae16250d7), ]; + /// A near-zero residue prints the same whichever sign the platform's libm left on it, and + /// values that round away from zero keep their sign. + #[test] + fn digest_prints_near_zero_residues_without_a_sign() { + let print = |v: f64| format!("{:.3}", digest_coord(v)); + for v in [-1.4210854715202004e-14, 1.4210854715202004e-14, -7.105427357601002e-15, -0.0, 0.0, -0.00049, 0.00049] { + assert_eq!(print(v), "0.000", "{v:e}"); + } + assert_eq!(print(-0.0006), "-0.001"); + assert_eq!(print(-12.25), "-12.250"); + assert_eq!(print(0.0006), "0.001"); + } + /// Every name builds the same outline as before the `Name` enum, and unknown names build nothing. #[test] fn outlines_match_the_string_dispatch() { diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index c140ee5137..0109e9040e 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -768,7 +768,7 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { /// Write tags as binary DXF (DXF Reference, "Binary DXF Files", R13+ layout): the sentinel, /// then per tag a 2-byte little-endian group code and the value in the binary form of the code's /// [`Kind`]: a zero-terminated string, an 8-byte real, a 2-, 4- or 8-byte integer, a 1-byte -/// boolean, or a binary chunk (one length byte, then up to 255 bytes; longer data is split into +/// boolean, or a binary chunk (one length byte, then up to 127 bytes; longer data is split into /// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as /// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text /// is stored as a number; a code outside the 16-bit range is skipped. @@ -822,8 +822,8 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } Kind::Hex => { let bytes = hex_bytes(&t.value.as_str()); - // An empty chunk is still one group, as in ASCII. - let mut chunks: Vec<&[u8]> = bytes.chunks(255).collect(); + // At most 127 bytes per group, as in ASCII; an empty chunk is still one group. + let mut chunks: Vec<&[u8]> = bytes.chunks(127).collect(); if chunks.is_empty() { chunks.push(&[]); } diff --git a/crates/dxf/tests/binary_write.rs b/crates/dxf/tests/binary_write.rs index fb2d082106..4ecaf17097 100644 --- a/crates/dxf/tests/binary_write.rs +++ b/crates/dxf/tests/binary_write.rs @@ -44,9 +44,8 @@ fn binary_converts_values_to_their_codes_kind() { let back = parse(&write_binary(&tags, true)).unwrap(); assert_eq!(back[0], Tag::i(70, 12)); assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX))); - assert_eq!(back[2].code, 310); - assert_eq!(back[3].code, 310, "300 bytes are split into chunks of at most 255"); - assert_eq!(back[2].str().len() + back[3].str().len(), 600); + let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); + assert_eq!(sizes, vec![254, 254, 92], "300 bytes are split into chunks of at most 127 (254 hex digits)"); } #[test] diff --git a/crates/dxf/tests/hex_chunks.rs b/crates/dxf/tests/hex_chunks.rs index 61100b0828..80e9e91933 100644 --- a/crates/dxf/tests/hex_chunks.rs +++ b/crates/dxf/tests/hex_chunks.rs @@ -2,7 +2,6 @@ //! 1004 specify at most 127 payload bytes per chunk, even though a length byte represents 255. //! Inspect writer bytes without our parser; accept any compliant partition preserving payload, //! code and following-record framing. Oversized binary read fixtures test tolerance only. -//! Pending writer regressions extend the chunk-size finding in issue #1025. //! Public DXF Reference, Group Codes in Numerical Order and Binary DXF Files: //! //! @@ -100,7 +99,6 @@ fn binary_reader_tolerates_the_full_length_byte_domain() { } #[test] -#[ignore = "Confirmed ASCII DXF writer nonconformance: hex payloads above 127 bytes are emitted as one oversized chunk"] fn ascii_writer_splits_large_payloads_into_conforming_chunks() { for code in (310..=319).chain([1004]) { for length in [128, 254, 255, 256, 1024] { @@ -112,7 +110,6 @@ fn ascii_writer_splits_large_payloads_into_conforming_chunks() { } #[test] -#[ignore = "Confirmed binary DXF writer nonconformance: 255-byte partitioning exceeds the documented 127-byte group limit"] fn binary_writer_splits_large_payloads_into_conforming_chunks() { for code in (310..=319).chain([1004]) { for length in [128, 254, 255, 256, 1024] { diff --git a/crates/dxf/tests/roundtrip.rs b/crates/dxf/tests/roundtrip.rs index 87f1e812c7..362bc725fa 100644 --- a/crates/dxf/tests/roundtrip.rs +++ b/crates/dxf/tests/roundtrip.rs @@ -120,7 +120,7 @@ fn hex_chunks_keep_bytes_and_order() { // DXF groups 310–319 and 1004 permit 127 payload bytes per chunk. A binary length // byte can represent more, but that is reader tolerance, not writer conformance. // Larger payloads need chunk-size/reassembly checks rather than exact tag equality; - // see hex_chunks.rs for the independent wire checks and pending writer regressions. + // see hex_chunks.rs for the independent wire checks. for length in [0, 1, 2, 126, 127] { let hex: String = (0..length).fold(String::new(), |mut out, i| { use std::fmt::Write as _; diff --git a/crates/kra/src/lib.rs b/crates/kra/src/lib.rs index 7485b9dd59..12ae3468bc 100644 --- a/crates/kra/src/lib.rs +++ b/crates/kra/src/lib.rs @@ -161,6 +161,16 @@ fn children<'a>(el: &'a El, container: &'static str, tag: &'static str) -> impl } fn node(el: &El, is_mask: bool, count: &mut usize) -> Result { + let mut out = node_fields(el, is_mask)?; + if !is_mask { + out.layers = layers(el, count)?; + out.masks = children(el, "masks", "mask").map(|m| node(m, true, count)).collect::>()?; + } + Ok(out) +} + +/// A node's own attributes, without its children. +fn node_fields(el: &El, is_mask: bool) -> Result { let owned = |name: &str| attr(el, name).map(str::to_string); let node_type = attr(el, "nodetype").unwrap_or("").to_string(); // Only the kinds whose pixels are read need sound numbers; a node an application will leave @@ -168,7 +178,7 @@ fn node(el: &El, is_mask: bool, count: &mut usize) -> Result { let read = matches!(node_type.as_str(), "paintlayer" | "grouplayer" | "transparencymask"); let lenient = |v: Result, default: f64| if read { v } else { Ok(v.unwrap_or(default)) }; let (x, y) = if is_mask && !read { (offset(el, "x").unwrap_or(0), offset(el, "y").unwrap_or(0)) } else { (offset(el, "x")?, offset(el, "y")?) }; - let mut out = Node { + let out = Node { node_type, name: owned("name"), visible: attr(el, "visible") != Some("0"), @@ -187,22 +197,39 @@ fn node(el: &El, is_mask: bool, count: &mut usize) -> Result { layers: Vec::new(), masks: Vec::new(), }; - if !is_mask { - out.layers = layers(el, count)?; - out.masks = children(el, "masks", "mask").map(|m| node(m, true, count)).collect::>()?; - } Ok(out) } -/// The `` of `el`. Recursion is bounded by [`MAX_XML_DEPTH`]. +/// The `` of `el`, walked with an explicit stack: groups can nest up to [`MAX_XML_DEPTH`] +/// deep, more than a small thread stack can recurse. fn layers(el: &El, count: &mut usize) -> Result> { + struct Frame<'a> { + node: Node, + rest: std::vec::IntoIter<&'a El>, + } + let mut root = children(el, "layers", "layer").collect::>().into_iter(); + let mut stack: Vec = Vec::new(); let mut out = Vec::new(); - for child in children(el, "layers", "layer") { + loop { + let next = match stack.last_mut() { + Some(frame) => frame.rest.next(), + None => root.next(), + }; + let Some(child) = next else { + let Some(frame) = stack.pop() else { break }; + match stack.last_mut() { + Some(parent) => parent.node.layers.push(frame.node), + None => out.push(frame.node), + } + continue; + }; *count += 1; if *count > MAX_NODES { return Err(invalid(format!("more than {MAX_NODES} layers"))); } - out.push(node(child, false, count)?); + let mut built = node_fields(child, false)?; + built.masks = children(child, "masks", "mask").map(|m| node(m, true, count)).collect::>()?; + stack.push(Frame { node: built, rest: children(child, "layers", "layer").collect::>().into_iter() }); } Ok(out) } diff --git a/crates/latex/src/tests.rs b/crates/latex/src/tests.rs index 55bde24892..ccf349c800 100644 --- a/crates/latex/src/tests.rs +++ b/crates/latex/src/tests.rs @@ -353,9 +353,9 @@ fn table_borders_and_borderless_round_trip() { let mut doc = Document::new(); let mut t_borderless = Table::new(2, 2, 400.0); t_borderless.props.style = None; - for r in 0..2 { - for c in 0..2 { - t_borderless.rows[r].cells[c].blocks = vec![para_block(Paragraph::with_text("cell", CharProps::default()))]; + for row in &mut t_borderless.rows { + for cell in &mut row.cells { + cell.blocks = vec![para_block(Paragraph::with_text("cell", CharProps::default()))]; } } doc.body = vec![Arc::new(Block::Table(t_borderless))]; @@ -369,9 +369,9 @@ fn table_borders_and_borderless_round_trip() { let mut doc_bordered = Document::new(); let mut t_bordered = Table::new(2, 2, 400.0); t_bordered.props.style = Some("TableGrid".to_string()); - for r in 0..2 { - for c in 0..2 { - t_bordered.rows[r].cells[c].blocks = vec![para_block(Paragraph::with_text("cell", CharProps::default()))]; + for row in &mut t_bordered.rows { + for cell in &mut row.cells { + cell.blocks = vec![para_block(Paragraph::with_text("cell", CharProps::default()))]; } } doc_bordered.body = vec![Arc::new(Block::Table(t_bordered))]; diff --git a/crates/openpgp/src/tests.rs b/crates/openpgp/src/tests.rs index 4dc30a0d34..f78519ba08 100644 --- a/crates/openpgp/src/tests.rs +++ b/crates/openpgp/src/tests.rs @@ -443,7 +443,8 @@ fn the_unhashed_area_never_decides_who_is_blamed() { // An issuer only in the unhashed area finds a key, which counts because it fits. let alice = secret(ALICE, Make::default()); - let mut config = config(&alice.primary_key, pgp::packet::SignatureType::Binary, t, vec![]); + let alice_created = made(&alice); + let mut config = config(&alice.primary_key, pgp::packet::SignatureType::Binary, alice_created, vec![]); config.hashed_subpackets.retain(|p| matches!(p.data, SubpacketData::SignatureCreationTime(_))); config.unhashed_subpackets = vec![Subpacket::regular(SubpacketData::IssuerFingerprint(alice.primary_key.fingerprint())).unwrap()]; let sig = config.sign(&alice.primary_key, &Password::empty(), SIGNED_PART.as_bytes()).unwrap(); diff --git a/crates/ora/src/lib.rs b/crates/ora/src/lib.rs index b2a91cc40b..69d494d0dc 100644 --- a/crates/ora/src/lib.rs +++ b/crates/ora/src/lib.rs @@ -189,28 +189,63 @@ fn props(el: &El) -> Result { }) } -/// The elements of `stack`. Recursion is bounded by [`MAX_XML_DEPTH`]. +/// The elements of `stack`, walked with an explicit stack: a stack can nest up to +/// [`MAX_XML_DEPTH`] deep, more than a small thread stack can recurse. fn stack(el: &El, count: &mut usize) -> Result> { + struct Frame<'a> { + props: Props, + isolation: Option, + children: Vec, + rest: std::vec::IntoIter<&'a El>, + } + let mut root = el.elements().collect::>().into_iter(); + let mut frames: Vec = Vec::new(); let mut out = Vec::new(); - for child in el.elements() { + loop { + let next = match frames.last_mut() { + Some(frame) => frame.rest.next(), + None => root.next(), + }; + let Some(child) = next else { + let Some(frame) = frames.pop() else { break }; + let node = Node::Stack(Stack { props: frame.props, isolation: frame.isolation, children: frame.children }); + match frames.last_mut() { + Some(parent) => parent.children.push(node), + None => out.push(node), + } + continue; + }; *count += 1; if *count > MAX_NODES { return Err(invalid(format!("more than {MAX_NODES} layers"))); } - out.push(match child.name.as_str() { - "layer" => Node::Layer(Layer { - props: props(child)?, - x: int(child, "x")?, - y: int(child, "y")?, - src: child.attr("src").map(|s| s.trim().to_string()), - }), - "stack" => Node::Stack(Stack { + match child.name.as_str() { + "layer" => { + let node = Node::Layer(Layer { + props: props(child)?, + x: int(child, "x")?, + y: int(child, "y")?, + src: child.attr("src").map(|s| s.trim().to_string()), + }); + match frames.last_mut() { + Some(parent) => parent.children.push(node), + None => out.push(node), + } + } + "stack" => frames.push(Frame { props: props(child)?, isolation: child.attr("isolation").map(|s| s.trim().to_string()), - children: stack(child, count)?, + children: Vec::new(), + rest: child.elements().collect::>().into_iter(), }), - other => Node::Other { tag: other.to_string(), name: child.attr("name").map(str::to_string) }, - }); + other => { + let node = Node::Other { tag: other.to_string(), name: child.attr("name").map(str::to_string) }; + match frames.last_mut() { + Some(parent) => parent.children.push(node), + None => out.push(node), + } + } + } } Ok(out) } diff --git a/crates/pdf/tests/font_tables.rs b/crates/pdf/tests/font_tables.rs new file mode 100644 index 0000000000..30f2346684 --- /dev/null +++ b/crates/pdf/tests/font_tables.rs @@ -0,0 +1,110 @@ +//! The font programs the writer embeds keep the source font's `OS/2` table (#1781 in DesignCraft): +//! its `fsType` is where the font states its embedding rights, and the subsetter writes none. +#![cfg(feature = "write")] +#![allow(clippy::unwrap_used, clippy::panic)] + +use backend::geom::Point; +use backend::page::PageSettings; +use backend::text::{GlyphId, KrillaGlyph}; +use craft_pdf::write::{self, Metadata, Writer, backend}; +use hayro_syntax::object::{Object, Stream}; + +/// A two-glyph TrueType font with an `OS/2` table whose `fsType` is 4 (Preview & Print). +const TINY_GLYF: &[u8] = include_bytes!("../../fonts-build/tests/fixture/subset/Tiny-glyf.ttf"); + +/// `text` set in `font_bytes`, one glyph per character, as a one-page PDF. +fn document(font_bytes: &[u8], text: &str) -> Vec { + let face = ttf_parser::Face::parse(font_bytes, 0).unwrap(); + let glyphs: Vec<_> = text + .char_indices() + .map(|(start, c)| { + let id = face.glyph_index(c).unwrap_or_else(|| panic!("the fixture covers {c:?}")); + let advance = f32::from(face.glyph_hor_advance(id).unwrap()) / f32::from(face.units_per_em()); + KrillaGlyph::new(GlyphId::new(u32::from(id.0)), advance, 0.0, 0.0, 0.0, start..start + c.len_utf8(), None) + }) + .collect(); + let font = write::font(font_bytes, 0, None).unwrap(); + let mut writer = Writer::new(backend::SerializeSettings::default(), Metadata::default()); + let mut page = writer.document_mut().start_page_with(PageSettings::from_wh(200.0, 100.0).unwrap()); + let mut surface = page.surface(); + surface.draw_glyphs(Point::from_xy(20.0, 50.0), &glyphs, font, text, 18.0, false); + surface.finish(); + page.finish(); + writer.finish().unwrap() +} + +/// The decoded `FontFile2` programs of `pdf`, through the font descriptors that name them. +fn font_files(pdf: &[u8]) -> Vec> { + let pdf = hayro_syntax::Pdf::new(std::sync::Arc::new(pdf.to_vec())).unwrap(); + pdf.objects() + .into_iter() + .filter_map(|o| match o { + Object::Dict(d) => d.get::>(b"FontFile2"), + _ => None, + }) + .map(|s| s.decoded().unwrap().to_vec()) + .collect() +} + +/// `(tag, offset, length, checksum)` of each table in the sfnt `font`. +fn tables(font: &[u8]) -> Vec<([u8; 4], usize, usize, u32)> { + let be32 = |at: usize| u32::from_be_bytes(font[at..at + 4].try_into().unwrap()); + let n = usize::from(u16::from_be_bytes(font[4..6].try_into().unwrap())); + (0..n) + .map(|k| (font[12 + 16 * k..16 + 16 * k].try_into().unwrap(), be32(20 + 16 * k) as usize, be32(24 + 16 * k) as usize, be32(16 + 16 * k))) + .collect() +} + +fn checksum(data: &[u8]) -> u32 { + data.chunks(4).fold(0u32, |sum, c| { + let mut word = [0u8; 4]; + word[..c.len()].copy_from_slice(c); + sum.wrapping_add(u32::from_be_bytes(word)) + }) +} + +fn table<'a>(font: &'a [u8], tag: &[u8; 4]) -> Option<&'a [u8]> { + tables(font).into_iter().find(|t| &t.0 == tag).map(|(_, off, len, _)| &font[off..off + len]) +} + +#[test] +fn an_embedded_truetype_subset_keeps_the_os2_table_and_its_fstype() { + let face = ttf_parser::Face::parse(TINY_GLYF, 0).unwrap(); + let text: String = ('!'..='~').filter(|c| face.glyph_index(*c).is_some()).collect(); + assert!(!text.is_empty(), "the fixture maps some ASCII"); + let files = font_files(&document(TINY_GLYF, &text)); + assert_eq!(files.len(), 1, "one embedded TrueType program"); + let sub = &files[0]; + let os2 = table(sub, b"OS/2").expect("the subset carries an OS/2 table"); + assert_eq!(os2, table(TINY_GLYF, b"OS/2").unwrap(), "the source's OS/2, unchanged"); + assert_eq!(u16::from_be_bytes(os2[8..10].try_into().unwrap()), 4, "fsType: Preview & Print"); + // A valid sfnt: tags in order, each table's checksum right, the whole font summing to the + // magic number through head.checkSumAdjustment. + let t = tables(sub); + assert!( + t.windows(2).all(|w| w[0].0 < w[1].0), + "tables in tag order: {:?}", + t.iter().map(|t| String::from_utf8_lossy(&t.0).to_string()).collect::>() + ); + for (tag, off, len, sum) in &t { + let mut data = sub[*off..off + len].to_vec(); + if tag == b"head" { + data[8..12].fill(0); + } + assert_eq!(checksum(&data), *sum, "{} checksum", String::from_utf8_lossy(tag)); + assert_eq!(off % 4, 0, "{} is 4-byte aligned", String::from_utf8_lossy(tag)); + } + assert_eq!(checksum(sub), 0xB1B0_AFBA, "whole-font checksum"); + // And it still reads as a font with the glyphs it was given. + let reread = ttf_parser::Face::parse(sub, 0).unwrap(); + // A subset, not the source font embedded whole: of the fixture's 11 glyphs, .notdef and the + // ones the text uses, and only their outlines. + assert!( + 2 <= reread.number_of_glyphs() && reread.number_of_glyphs() < face.number_of_glyphs(), + "{} of {} glyphs", + reread.number_of_glyphs(), + face.number_of_glyphs() + ); + assert!(table(sub, b"glyf").unwrap().len() < table(TINY_GLYF, b"glyf").unwrap().len(), "only the used glyphs' outlines"); + assert_eq!(reread.permissions(), face.permissions()); +} diff --git a/crates/pdf/tests/interpretation.rs b/crates/pdf/tests/interpretation.rs index 9433c0426d..124746aaf2 100644 --- a/crates/pdf/tests/interpretation.rs +++ b/crates/pdf/tests/interpretation.rs @@ -65,6 +65,88 @@ mod device { execute(&mut fresh).unwrap(); assert_eq!(fresh.paths, 1); } + + /// Records the clips the interpreter applies, alongside the paths painted under them. + #[derive(Default)] + struct ClipDevice { + clips: Vec, + paths: usize, + } + + impl Device<'_> for ClipDevice { + fn set_soft_mask(&mut self, _: Option>) {} + fn set_blend_mode(&mut self, _: BlendMode) {} + fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) { + self.paths += 1; + } + fn push_clip_path(&mut self, clip_path: &ClipPath) { + self.clips.push(clip_path.path.clone()); + } + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + fn draw_glyph(&mut self, _: &Glyph<'_>, _: Affine, _: Affine, _: &Paint<'_>, _: &GlyphDrawMode) {} + fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) {} + fn pop_clip_path(&mut self) {} + fn pop_transparency_group(&mut self) {} + } + + fn clips_of(content: &str) -> ClipDevice { + let bytes = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 20] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj\n4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF", + content.len() + ); + let pdf = craft_pdf::open_slice(bytes.as_bytes(), None).unwrap(); + let page = &pdf.pages()[0]; + let cache = InterpreterCache::new(); + let mut context = Context::new( + page.initial_transform(true).to_kurbo(), + Rect::new(0.0, 0.0, 40.0, 20.0), + &cache, + page.xref(), + InterpreterSettings::default(), + ); + let mut device = ClipDevice::default(); + craft_pdf::interpret_page(page, &mut context, &mut device).unwrap(); + device + } + + /// A glyph shown in a clipping render mode adds its outline to the clipping path, and that + /// clip applies to everything painted after `ET`. When the glyphs shown have no outline -- a + /// space, say -- the clip is empty and nothing paints through it. The interpreter applied a + /// clip only once a glyph had contributed an outline, so such a text object clipped nothing + /// and what followed painted unmasked. + /// + /// A text object that shows no glyph at all is a different case: there the clipping path is + /// unchanged, as readers leave it. + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn a_glyph_shown_in_a_clipping_mode_clips_even_with_no_outline() { + // `7 Tr` is clip-only, and the glyph shown has no outline: the clip is empty. + let empty = clips_of("q BT 7 Tr /F1 12 Tf 4 4 Td ( ) Tj ET 1 0 0 rg 0 0 40 20 re f Q"); + assert_eq!(empty.clips.len(), 1, "the empty clip is applied"); + assert!(empty.clips[0].is_empty(), "and it clips everything away: {:?}", empty.clips[0]); + + // Visible glyphs in the same mode clip to their outlines, as they always did: one clip, not + // empty, and the fill still painted beneath it (noted in review). + let visible = clips_of("q BT 7 Tr /F1 12 Tf 4 4 Td (H) Tj ET 1 0 0 rg 0 0 40 20 re f Q"); + assert_eq!(visible.clips.len(), 1, "the glyph outline is applied as the clip"); + assert!(!visible.clips[0].is_empty(), "and it holds the outline"); + assert_eq!(visible.paths, 1); + + // A clipping mode with no glyph shown at all leaves the clipping path alone. + let none = clips_of("q BT 7 Tr /F1 12 Tf 4 4 Td ET 1 0 0 rg 0 0 40 20 re f Q"); + assert!(none.clips.is_empty(), "nothing was shown, so nothing clips"); + assert_eq!(none.paths, 1); + + // No text object: the fill is unclipped, as it always was. + let plain = clips_of("q 1 0 0 rg 0 0 40 20 re f Q"); + assert!(plain.clips.is_empty(), "nothing clips the fill"); + assert_eq!(plain.paths, 1); + + // A painting mode never clips, outline or not. + let painting = clips_of("q BT 0 Tr /F1 12 Tf 4 4 Td ( ) Tj ET 1 0 0 rg 0 0 40 20 re f Q"); + assert!(painting.clips.is_empty(), "a painting text mode never clips"); + assert_eq!(painting.paths, 1); + } } #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] @@ -119,6 +201,37 @@ fn caller_decode_policy_survives_open_fallback() { assert_eq!(normal.decode_limits(), craft_pdf::syntax::DecodeLimits::default()); } +/// What the clip does to the page, rendered: the device test above shows the clip the interpreter +/// sets, this shows the pixels it leaves (noted in review). +#[cfg(all(feature = "raster", not(target_arch = "wasm32")))] +mod rendered { + use craft_pdf::raster::{self, Options, RenderCache}; + + /// The share of a 40 x 20 pt page painted red (the fill), after `text` and then the fill. + fn red_share(text: &str) -> f64 { + let content = format!("q {text} 1 0 0 rg 0 0 40 20 re f Q"); + let bytes = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 20] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj\n4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\ntrailer << /Root 1 0 R >>\n%%EOF", + content.len() + ); + let pdf = craft_pdf::open_slice(bytes.as_bytes(), None).unwrap(); + let page = raster::render(&pdf.pages()[0], &RenderCache::new(), &Default::default(), &Options { background: [255; 4], ..Default::default() }) + .unwrap(); + let pixels = page.bytes().as_chunks::<4>().0; + let red = pixels.iter().filter(|p| p[0] > 200 && p[1] < 80 && p[2] < 80).count(); + red as f64 / pixels.len() as f64 + } + + #[test] + fn an_empty_text_clip_hides_what_follows_and_a_visible_one_shows_its_glyphs() { + assert!(red_share("") > 0.99, "no text object: the fill covers the page"); + assert_eq!(red_share("BT 7 Tr /F1 12 Tf 4 4 Td ( ) Tj ET"), 0.0, "an outline-less glyph in 7 Tr: nothing paints"); + let through = red_share("BT 7 Tr /F1 12 Tf 4 4 Td (H) Tj ET"); + assert!(through > 0.02 && through < 0.5, "visible glyphs in 7 Tr: the fill shows through the H only ({through})"); + assert!(red_share("BT 7 Tr /F1 12 Tf 4 4 Td ET") > 0.99, "no glyph shown: the clip is unchanged"); + } +} + /// A path reaches the device as a rectangle only when it is one. A five-point open polyline whose /// points reach every corner of its own bounding box (VectorCraft #2920, a zigzag in an `.ai` /// file) used to be drawn as that box. diff --git a/crates/platform/README.md b/crates/platform/README.md index 14494d613a..f7f475dc8f 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -41,7 +41,9 @@ permission to discard work. Run those guards before `craft_quit::on_close_reques `appearance::Watcher` caches the desktop preference and wakes only on changes. Subscription precedes the first read. ReadOne/legacy Read, the standard namespace and GNOME fallback are handled together; -malformed values retain the last valid answer, and explicit no-preference clears it. Disconnection +on GNOME the "default" (Light) setting and portal value 0 read as light; elsewhere 0 is no preference. +Malformed values retain the last valid answer, and explicit no-preference clears it. +`Watcher::wait_first(timeout)` blocks until the first answer, a known absence, or the timeout (about 250 ms in an eframe creator), so the first frame uses the desktop theme. Disconnection retains the last valid value until a fresh answer. A later service owner triggers a reread; session reconnection has bounded backoff. Dropping cancels asynchronous work and waits at most 100 ms for acknowledgement, joining only an already-finished worker. A synchronously blocked OS call or caller wake callback can outlive diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs index c696510d3d..1c255f09a5 100644 --- a/crates/platform/src/appearance.rs +++ b/crates/platform/src/appearance.rs @@ -3,9 +3,12 @@ //! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback, //! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility. //! Palettes, manual choices and the fallback when no preference exists belong to the host. -use std::sync::{ - Arc, - atomic::{AtomicBool, AtomicU8, Ordering}, +use std::{ + sync::{ + Arc, Condvar, Mutex, PoisonError, + atomic::{AtomicBool, AtomicU8, Ordering}, + }, + time::Duration, }; /// Desktop color preference observed independently of the application palette. @@ -20,6 +23,12 @@ pub enum Theme { struct Shared { value: AtomicU8, active: AtomicBool, + /// True once the source has answered, found no answer, or been cancelled. + settled: Mutex, + settled_changed: Condvar, + /// `XDG_CURRENT_DESKTOP` names GNOME; read once when the watcher starts. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + gnome: bool, #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] wake: Box, } @@ -32,13 +41,20 @@ impl Shared { } } #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + fn settle(&self) { + *self.settled.lock().unwrap_or_else(PoisonError::into_inner) = true; + self.settled_changed.notify_all(); + } + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] fn publish(&self, theme: Option) { let code = match theme { Some(Theme::Dark) => 1, Some(Theme::Light) => 2, None => 0, }; - if self.value.swap(code, Ordering::AcqRel) != code && self.active.load(Ordering::Acquire) { + let changed = self.value.swap(code, Ordering::AcqRel) != code; + self.settle(); + if changed && self.active.load(Ordering::Acquire) { (self.wake)(); } } @@ -81,6 +97,20 @@ impl Watcher { pub fn current(&self) -> Option { self.shared.get() } + /// Block until the first answer is known, then return it; at most `timeout`. + /// + /// Returns early, with `current()`, when the portal is absent and the `gsettings` fallback + /// found nothing, or when the desktop reports no preference. Call it once while building the + /// first frame so a light desktop does not flash dark: + /// + /// ```ignore + /// let theme = watcher.wait_first(std::time::Duration::from_millis(250)); + /// ``` + pub fn wait_first(&self, timeout: Duration) -> Option { + let settled = self.shared.settled.lock().unwrap_or_else(PoisonError::into_inner); + drop(self.shared.settled_changed.wait_timeout_while(settled, timeout, |settled| !*settled).unwrap_or_else(PoisonError::into_inner)); + self.current() + } /// Enable or suppress future change notifications without stopping observation. /// Changing this flag does not itself wake the host or clear the cached preference. pub fn set_active(&self, active: bool) { @@ -92,7 +122,15 @@ impl Watcher { wake: impl Fn() + Send + Sync + 'static, source: impl FnOnce(Arc) -> F + Send + 'static, ) -> Option { - let shared = Arc::new(Shared { value: AtomicU8::new(0), active: AtomicBool::new(active), wake: Box::new(wake) }); + let gnome = is_gnome(std::env::var("XDG_CURRENT_DESKTOP").ok().as_deref()); + let shared = Arc::new(Shared { + value: AtomicU8::new(0), + active: AtomicBool::new(active), + settled: Mutex::new(false), + settled_changed: Condvar::new(), + gnome, + wake: Box::new(wake), + }); let worker_shared = Arc::clone(&shared); let (stop, stopped) = async_channel::bounded::<()>(1); let (done, finished) = std::sync::mpsc::channel(); @@ -103,8 +141,9 @@ impl Watcher { async { let _ = stopped.recv().await; }, - source(worker_shared), + source(Arc::clone(&worker_shared)), )); + worker_shared.settle(); let _ = done.send(()); }) .ok()?; @@ -116,6 +155,7 @@ impl Drop for Watcher { self.set_active(false); #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] { + self.shared.settle(); self.stop.close(); if let Some(worker) = self.worker.take() { let _ = self.finished.recv_timeout(std::time::Duration::from_millis(100)); @@ -129,6 +169,12 @@ impl Drop for Watcher { } } +/// Whether a colon-separated `XDG_CURRENT_DESKTOP` value names GNOME. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn is_gnome(desktop: Option<&str>) -> bool { + desktop.is_some_and(|list| list.split(':').any(|name| name.eq_ignore_ascii_case("gnome"))) +} + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod portal { use super::{Shared, Theme}; @@ -144,27 +190,31 @@ mod portal { const TIMEOUT: Duration = Duration::from_secs(2); // Outer None means unknown/malformed; Some(None) is an explicit no-preference answer. - fn decode(namespace: &str, value: &Value<'_>) -> Option> { + // GNOME 42-46 writes 'default' (portal value 0) for Settings > Appearance > Light, so on GNOME + // both mean light; elsewhere both are no preference. + fn decode(namespace: &str, value: &Value<'_>, gnome: bool) -> Option> { match (namespace, value) { (STANDARD, Value::U32(n)) => Some(match n { 1 => Some(Theme::Dark), 2 => Some(Theme::Light), + 0 if gnome => Some(Theme::Light), _ => None, }), (GNOME, Value::Str(s)) => Some(match s.as_str() { "prefer-dark" => Some(Theme::Dark), "prefer-light" => Some(Theme::Light), + "default" if gnome => Some(Theme::Light), _ => None, }), _ => None, } } - fn reply(namespace: &str, value: &Value<'_>, legacy: bool) -> Option> { + fn reply(namespace: &str, value: &Value<'_>, legacy: bool, gnome: bool) -> Option> { if legacy { let Value::Value(inner) = value else { return None }; - decode(namespace, inner) + decode(namespace, inner, gnome) } else { - decode(namespace, value) + decode(namespace, value, gnome) } } fn combined(standard: Option>, gnome: Option>) -> Option> { @@ -177,11 +227,11 @@ mod portal { }) .await } - async fn read(connection: &zbus::Connection, namespace: &str) -> Option> { + async fn read(connection: &zbus::Connection, namespace: &str, gnome: bool) -> Option> { for (method, legacy) in [("ReadOne", false), ("Read", true)] { if let Some(Ok(message)) = bounded(connection.call_method(Some(DEST), PATH, Some(IFACE), method, &(namespace, KEY))).await && let Ok(value) = message.body().deserialize::() - && let Some(answer) = reply(namespace, &value, legacy) + && let Some(answer) = reply(namespace, &value, legacy, gnome) { return Some(answer); } @@ -213,6 +263,8 @@ mod portal { loop { let mut connected = false; let _ = session(&shared, &mut fallback_used, &mut connected).await; + // No session bus, no portal and an empty fallback all end here without a publish. + shared.settle(); if connected { retry = Duration::from_secs(5); } @@ -235,7 +287,7 @@ mod portal { && let Some(text) = crate::process::capture(&exe, &["get", GNOME, KEY], TIMEOUT).await { let text = text.trim().trim_matches('\''); - if let Some(answer) = decode(GNOME, &Value::from(text)) { + if let Some(answer) = decode(GNOME, &Value::from(text), shared.gnome) { shared.publish(answer); } } @@ -255,8 +307,8 @@ mod portal { // MatchRule installs before activation: unlike a proxy subscription it needs no current owner. let mut changes = bounded(zbus::MessageStream::for_match_rule(rule().ok()?, &connection, Some(64))).await?.ok()?; let mut owners = bounded(zbus::MessageStream::for_match_rule(owner_rule().ok()?, &connection, Some(8))).await?.ok()?; - let mut standard = read(&connection, STANDARD).await; - let mut gnome = read(&connection, GNOME).await; + let mut standard = read(&connection, STANDARD, shared.gnome).await; + let mut gnome = read(&connection, GNOME, shared.gnome).await; match combined(standard, gnome) { Some(answer) => { *connected = true; @@ -286,7 +338,7 @@ mod portal { if key != KEY { continue; } - let Some(answer) = decode(&namespace, &value) else { continue }; + let Some(answer) = decode(&namespace, &value, shared.gnome) else { continue }; match namespace.as_str() { STANDARD => standard = Some(answer), GNOME => gnome = Some(answer), @@ -323,6 +375,7 @@ mod portal { } use super::{GNOME, STANDARD, combined, decode, reply}; + use crate::appearance::is_gnome; use crate::appearance::{Theme, Watcher}; use std::{ sync::{Arc, atomic::Ordering}, @@ -339,18 +392,70 @@ mod portal { } #[test] fn malformed_is_distinct_from_no_preference_and_legacy_is_exact() { - assert_eq!(decode(STANDARD, &Value::U32(0)), Some(None)); - assert_eq!(decode(STANDARD, &Value::U32(77)), Some(None)); - assert_eq!(decode(STANDARD, &Value::from("dark")), None); - assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::U32(1))), true), Some(Some(Theme::Dark))); - assert_eq!(reply(STANDARD, &Value::U32(1), true), None); - assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))), true), None); - assert_eq!(decode(STANDARD, &Value::Value(Box::new(Value::U32(1)))), None); - assert_eq!(decode(STANDARD, &Value::I32(1)), None); - assert_eq!(decode(GNOME, &Value::from("default")), Some(None)); - assert_eq!(decode(GNOME, &Value::U32(1)), None); - - assert_eq!(reply(GNOME, &Value::from("prefer-light"), false), Some(Some(Theme::Light))); + assert_eq!(decode(STANDARD, &Value::U32(0), false), Some(None)); + assert_eq!(decode(STANDARD, &Value::U32(77), false), Some(None)); + assert_eq!(decode(STANDARD, &Value::from("dark"), false), None); + assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::U32(1))), true, false), Some(Some(Theme::Dark))); + assert_eq!(reply(STANDARD, &Value::U32(1), true, false), None); + assert_eq!(reply(STANDARD, &Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))), true, false), None); + assert_eq!(decode(STANDARD, &Value::Value(Box::new(Value::U32(1))), false), None); + assert_eq!(decode(STANDARD, &Value::I32(1), false), None); + assert_eq!(decode(GNOME, &Value::U32(1), false), None); + assert_eq!(reply(GNOME, &Value::from("prefer-light"), false, false), Some(Some(Theme::Light))); + } + #[test] + fn gnome_light_setting_reads_as_light_and_zero_is_no_preference_elsewhere() { + assert_eq!(decode(GNOME, &Value::from("default"), true), Some(Some(Theme::Light))); + // A GNOME schema installed on another desktop doesn't make that desktop light. + assert_eq!(decode(GNOME, &Value::from("default"), false), Some(None)); + assert_eq!(decode(GNOME, &Value::from("prefer-dark"), false), Some(Some(Theme::Dark))); + assert_eq!(decode(GNOME, &Value::from("prefer-light"), false), Some(Some(Theme::Light))); + assert_eq!(decode(STANDARD, &Value::U32(0), true), Some(Some(Theme::Light))); + assert_eq!(decode(STANDARD, &Value::U32(0), false), Some(None)); + for gnome in [true, false] { + assert_eq!(decode(STANDARD, &Value::U32(1), gnome), Some(Some(Theme::Dark))); + assert_eq!(decode(STANDARD, &Value::U32(2), gnome), Some(Some(Theme::Light))); + } + assert!(is_gnome(Some("GNOME"))); + assert!(is_gnome(Some("ubuntu:GNOME"))); + assert!(is_gnome(Some("gnome-classic:gnome"))); + assert!(!is_gnome(Some("KDE"))); + assert!(!is_gnome(Some("X-Cinnamon"))); + assert!(!is_gnome(None)); + } + fn spawn_idle(source: impl FnOnce(Arc) + Send + 'static) -> Result { + Watcher::spawn(false, || {}, move |shared| async move { source(shared) }).ok_or("worker creation failed") + } + #[test] + fn wait_first_returns_at_once_after_a_publish() -> Result<(), Box> { + let watcher = spawn_idle(|shared| { + shared.publish(Some(Theme::Light)); + std::thread::sleep(Duration::from_millis(500)); + })?; + let started = std::time::Instant::now(); + assert_eq!(watcher.wait_first(Duration::from_secs(2)), Some(Theme::Light)); + assert!(started.elapsed() < Duration::from_secs(1)); + Ok(()) + } + #[test] + fn wait_first_times_out_without_an_answer_and_drop_stays_bounded() -> Result<(), Box> { + let watcher = Watcher::spawn(false, || {}, |_| futures_lite::future::pending::<()>()).ok_or("worker creation failed")?; + let started = std::time::Instant::now(); + assert_eq!(watcher.wait_first(Duration::from_millis(50)), None); + assert!(started.elapsed() >= Duration::from_millis(50)); + drop(watcher); + Ok(()) + } + #[test] + fn wait_first_returns_early_for_no_preference_and_for_a_source_that_ends_empty() -> Result<(), Box> { + let none = spawn_idle(|shared| shared.publish(None))?; + let ended = spawn_idle(|_| {})?; + for watcher in [none, ended] { + let started = std::time::Instant::now(); + assert_eq!(watcher.wait_first(Duration::from_secs(2)), None); + assert!(started.elapsed() < Duration::from_secs(1)); + } + Ok(()) } #[test] fn manual_cache_changes_do_not_wake_and_drop_cancels_pending_source() -> Result<(), Box> { diff --git a/crates/plotter/src/gpgl/silhouette.rs b/crates/plotter/src/gpgl/silhouette.rs index 9d5dff2d13..a30aa19905 100644 --- a/crates/plotter/src/gpgl/silhouette.rs +++ b/crates/plotter/src/gpgl/silhouette.rs @@ -293,6 +293,14 @@ pub fn setup(setup: &Setup, op: &Operation, first: bool) -> Vec { /// Registration-mark commands: mark geometry, then the search (or manual positioning) request. /// The device answers ` 0\x03` (see [`parse_status`]) once it has the marks. +/// +/// The full registration sequence (TB99 through TB55, plus TB123/TB124 for search and +/// TB23 for manual positioning) is documented in the community driver [py_silhouette] +/// (`zero_on_registration_mark()`), which reverse-engineered the protocol from public +/// behaviour — not from any proprietary binary. The `TB54,0,0` sub-command sets the +/// registration-mark offset to zero (the mark is at its expected position). +/// +/// [py_silhouette]: https://github.com/mossblaser/py_silhouette/blob/main/py_silhouette/device.py pub fn registration(reg: &Registration) -> Vec { let raw = |s: &str| Command::Raw(s.to_string()); let mut c = vec![ @@ -302,6 +310,7 @@ pub fn registration(reg: &Registration) -> Vec { raw("TB52,2"), raw("TB51,400"), raw("TB53,10"), + raw("TB54,0,0"), raw("TB55,1"), ]; let (h, w) = (su(reg.length_mm), su(reg.width_mm)); diff --git a/crates/plotter/tests/golden.rs b/crates/plotter/tests/golden.rs index 26aaae5545..4d5029010b 100644 --- a/crates/plotter/tests/golden.rs +++ b/crates/plotter/tests/golden.rs @@ -135,7 +135,7 @@ fn silhouette_registration_marks() { let p = silhouette::encode(&pro, &j).unwrap(); let (head, rest) = p.split_at_registration(); let text = |c: &[Command]| c.iter().map(Command::to_ascii).collect::>().join(" "); - assert!(text(head).ends_with(" FC18,1,1 TB50,0 TB99 TB52,2 TB51,400 TB53,10 TB55,1 TB123,4600,3600,200,100")); + assert!(text(head).ends_with(" FC18,1,1 TB50,0 TB99 TB52,2 TB51,400 TB53,10 TB54,0,0 TB55,1 TB123,4600,3600,200,100")); // The design is shifted so the first mark is the origin. assert_eq!(text(rest), "M100,100 D100,300 M100,0 SO0"); assert_eq!(p.registration_wait, Some(head.len())); @@ -148,7 +148,7 @@ fn silhouette_registration_marks() { reg.origin_right_mm = 0.0; assert!(ascii(®).ends_with(" TB124,4600,3600,0,0")); reg.search = false; - assert_eq!(ascii(®), "TB50,0 TB99 TB52,2 TB51,400 TB53,10 TB55,1 TB23,4600,3600"); + assert_eq!(ascii(®), "TB50,0 TB99 TB52,2 TB51,400 TB53,10 TB54,0,0 TB55,1 TB23,4600,3600"); } #[test] diff --git a/crates/prepress/README.md b/crates/prepress/README.md index 80b1e08f7b..fe559e8d41 100644 --- a/crates/prepress/README.md +++ b/crates/prepress/README.md @@ -57,6 +57,24 @@ let black = p.tint(InkId::process(Process::Black), 10, 10); let gold = p.inks.lookup("Gold").and_then(|id| p.tint(id, 10, 10)); ``` +At print resolution, separate in bands. Each band holds every ink for a run of rows, at most +`MAX_PLATE_PIXELS`, so memory stays bounded however high the resolution: + +```rust +use std::ops::ControlFlow; +use craft_prepress::{plates_in_bands, Options}; + +plates_in_bands(&pdf, 0, 600.0, &Options::default(), |band| { + // band.plates is page-wide and band.plates.height rows tall, from row band.top. + ControlFlow::Continue(()) +})?; +``` + +Each band renders the page again once per ink, so time grows with the number of bands: a +Letter page at 900 dpi makes 19 bands. Across the page the renderer's side limit +(`craft_pdf::raster::MAX_SIDE`, 8192 pixels) still applies, about 960 dpi on Letter or A4; down +the page it doesn't. + The plates are the PDF as printed, so a preview built on them shows what the writer produced, not what the document model intended. @@ -90,7 +108,8 @@ separate as they are. | Constant | Value | Why | |---|---|---| | `MAX_SPOT_INKS` | 32 spot inks per page | A `DeviceN` space has at most 32 colorants, and each plate costs a render and a byte per pixel. Further spots are listed in `Plates::unseparated`. | -| `MAX_PLATE_PIXELS` | 4 MP per plate (2000 × 2000) | A page with many inks stays within a few hundred megabytes. The resolution is lowered to fit; `Plates::dpi` reports the one used. | +| `MAX_PLATE_PIXELS` | 4 MP per plate (2000 × 2000) | A page with many inks stays within a few hundred megabytes. `plates` lowers the resolution to fit, and `plates_in_bands` makes bands this size; `Plates::dpi` reports the one used. | +| `MAX_BANDED_PIXELS` | 256 MP per plate of a page separated in bands | Bounds the pixels a banded page adds up to; the resolution is lowered to fit. It does not bound the band count: a very thin, tall page makes one band per 8192 rows. | The renderer's side limit (`craft_pdf::raster::MAX_SIDE`) also lowers the resolution. diff --git a/crates/prepress/src/lib.rs b/crates/prepress/src/lib.rs index 5b8967a897..3fa4f472e7 100644 --- a/crates/prepress/src/lib.rs +++ b/crates/prepress/src/lib.rs @@ -19,4 +19,4 @@ pub use coverage::{Above, Coverage, InkStats, MAX_REGIONS, Region, Stats}; pub use ink::{Alternate, Ink, InkColor, InkId, InkSet, Overprint, Process, Spot, normalize_name, to_pdf_color}; pub use marks::{MarkOptions, Marks, MarksError}; pub use output::{Output, OutputError}; -pub use plates::{Conversion, Error, Fallback, MAX_PLATE_PIXELS, MAX_SPOT_INKS, Options, Plates, plates}; +pub use plates::{Band, Conversion, Error, Fallback, MAX_BANDED_PIXELS, MAX_PLATE_PIXELS, MAX_SPOT_INKS, Options, Plates, plates, plates_in_bands}; diff --git a/crates/prepress/src/plates.rs b/crates/prepress/src/plates.rs index 332c8b6b2a..b2e818efa0 100644 --- a/crates/prepress/src/plates.rs +++ b/crates/prepress/src/plates.rs @@ -12,6 +12,7 @@ //! 6fcf2a4, MIT OR Apache-2.0), with craft-cms in place of moxcms. use std::collections::HashSet; +use std::ops::ControlFlow; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex}; @@ -35,6 +36,12 @@ pub const MAX_SPOT_INKS: usize = 32; /// hundred megabytes. The resolution is reduced to fit; [`Plates::dpi`] says what was used. pub const MAX_PLATE_PIXELS: f32 = 4.0e6; +/// Pixels per plate of a page separated in bands (256 MP, 16000 × 16000). It bounds the memory a +/// page's bands add up to; a long page reaches it, while across a Letter or A4 page the side limit +/// stops near 960 dpi first. The resolution is reduced to fit. It does not bound the band count: a +/// page a few points wide and very tall still makes one band per 8192 rows. +pub const MAX_BANDED_PIXELS: f32 = 2.56e8; + /// The resolution, in pixels per point, inks are discovered at before the plates render. const DISCOVERY_SCALE: f32 = 0.1; @@ -148,8 +155,51 @@ pub enum Error { /// Separates page `page` (from 0) of `pdf` at `dpi`, reduced to fit [`MAX_PLATE_PIXELS`] and /// the renderer's side limit: one plate per ink, the four process inks and up to /// [`MAX_SPOT_INKS`] spot inks the page paints. Spot inks only soft masks use are left out -/// (masks don't print). Never panics. +/// (masks don't print). [`plates_in_bands`] separates at higher resolutions. Never panics. pub fn plates(pdf: &[u8], page: usize, dpi: f32, opts: &Options) -> Result { + let mut whole = None; + // One band of the whole page: `plate_scale` keeps it within `MAX_PLATE_PIXELS`. + separate(pdf, page, dpi, opts, plate_scale, Some(u32::MAX), &mut |band: Band| { + whole = Some(band.plates); + ControlFlow::Break(()) + })?; + whole.ok_or(Error::Render(raster::Error::OutputLimit)) +} + +/// Rows of a page's plates, from [`plates_in_bands`]. +#[derive(Clone, Debug)] +pub struct Band { + /// The band's first row on the page, from the top. + pub top: u32, + /// The page's height in pixels. The band's own height is the plates' height. + pub page_height: u32, + /// The band's plates: as wide as the page, `height` rows from `top`. Every band has the + /// same inks, in the same order. + pub plates: Plates, +} + +/// Separates page `page` (from 0) of `pdf` at `dpi` as [`plates`] does, in bands from the top +/// down, each at most [`MAX_PLATE_PIXELS`]. The resolution is reduced only to fit the +/// renderer's side limit across the page (`MAX_SIDE`, 8192 pixels) and [`MAX_BANDED_PIXELS`] +/// in all; [`Plates::dpi`] says what was used. The page's inks are found once, so every band has the same ones. +/// +/// `each` gets the bands in order and returns [`ControlFlow::Break`] to stop. Each band renders +/// the page again, clipped to its rows. Never panics. +pub fn plates_in_bands(pdf: &[u8], page: usize, dpi: f32, opts: &Options, mut each: impl FnMut(Band) -> ControlFlow<()>) -> Result<(), Error> { + separate(pdf, page, dpi, opts, banded_scale, None, &mut each) +} + +/// Separates in bands of `rows` rows, else as many as fit [`MAX_PLATE_PIXELS`], at `scale_of`'s +/// scale. +fn separate( + pdf: &[u8], + page: usize, + dpi: f32, + opts: &Options, + scale_of: fn(f32, f32, f32) -> f32, + rows: Option, + each: &mut dyn FnMut(Band) -> ControlFlow<()>, +) -> Result<(), Error> { if !dpi.is_finite() || dpi <= 0.0 { return Err(Error::InvalidDpi); } @@ -161,12 +211,51 @@ pub fn plates(pdf: &[u8], page: usize, dpi: f32, opts: &Options) -> Result MAX_BANDED_PIXELS as u64 { + return Err(Error::Render(raster::Error::OutputLimit)); + } + let rows = rows.unwrap_or(fit).clamp(1, page_height); + let mut top = 0; + while top < page_height { + let height = rows.min(page_height - top); + let mut planes = Vec::with_capacity(separated.len()); + for ink in &separated { + let plate = Plate { ink: ink.clone(), overprint: opts.overprint, simulation: simulation.clone(), spots_as_process: false }; + let settings = InterpreterSettings { plate: Some(plate), ..Default::default() }; + let viewport = raster::Options { size: Some([width, height]), offset: [0.0, top as f32], ..film(scale) }; + let film = raster::render(p, &cache, &settings, &viewport)?; + // The film is gray on white: its red channel is the paper left uncovered. + planes.push(film.bytes().as_chunks::<4>().0.iter().map(|[red, ..]| 255 - red).collect()); + } + let plates = + Plates { inks: inks.clone(), unseparated: unseparated.clone(), width, height, dpi: scale * 72.0, conversion: conversion.clone(), planes }; + if each(Band { top, page_height, plates }).is_break() { + break; + } + top += height; + } + Ok(()) +} +/// The inks page `p` paints, found at `scale`, a low resolution: the process inks, then up to +/// [`MAX_SPOT_INKS`] spots as the [`InkSet`], the renderer's inks to separate in the same +/// order, and the names of spots left unseparated. +fn discover<'a>(p: &'a craft_pdf::syntax::page::Page<'a>, cache: &RenderCache<'a>, scale: f32) -> Result<(InkSet, Vec, Vec), Error> { let log = Arc::new(Mutex::new(SpotLog::default())); - let discover = InterpreterSettings { ink_sink: Some(spot_sink(&log)), ..Default::default() }; - render(p, &cache, &discover, DISCOVERY_SCALE.min(scale))?; + let settings = InterpreterSettings { ink_sink: Some(spot_sink(&log)), ..Default::default() }; + raster::render(p, cache, &settings, &film(scale))?; let spots = std::mem::take(&mut log.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).order); let mut inks = InkSet::new(); @@ -186,30 +275,31 @@ pub fn plates(pdf: &[u8], page: usize, dpi: f32, opts: &Options) -> Result unseparated.push(ink.name().to_string()), } } - - let mut size = None; - let mut planes = Vec::with_capacity(separated.len()); - for ink in separated { - let plate = Plate { ink, overprint: opts.overprint, simulation: simulation.clone(), spots_as_process: false }; - let settings = InterpreterSettings { plate: Some(plate), ..Default::default() }; - let film = render(p, &cache, &settings, scale)?; - size = Some((film.width, film.height)); - // The film is gray on white: its red channel is the paper left uncovered. - planes.push(film.bytes().as_chunks::<4>().0.iter().map(|[red, ..]| 255 - red).collect()); - } - let (width, height) = size.unwrap_or((0, 0)); - Ok(Plates { inks, unseparated, width, height, dpi: scale * 72.0, conversion, planes }) + Ok((inks, separated, unseparated)) } -fn render<'a>( - page: &'a craft_pdf::syntax::page::Page<'a>, - cache: &RenderCache<'a>, - settings: &InterpreterSettings, - scale: f32, -) -> Result { - // The plate's gray film must keep its tints: no color replacement. - let options = raster::Options { scale: [scale, scale], background: [255; 4], color_replacement: None, ..Default::default() }; - Ok(raster::render(page, cache, settings, &options)?) +/// Raster options for a gray film at `scale`. The plate's film must keep its tints: no color +/// replacement. +fn film(scale: f32) -> raster::Options { + raster::Options { scale: [scale, scale], background: [255; 4], color_replacement: None, ..Default::default() } +} + +/// The scale a `w` × `h` pt page separates at in bands: `scale`, within the renderer's side +/// limit across the page and [`MAX_BANDED_PIXELS`]. Down the page there is no side limit. +fn banded_scale(w: f32, h: f32, scale: f32) -> f32 { + let (w, h) = (w.max(1.0), h.max(1.0)); + // The margin keeps the floored size under the cap despite f32 rounding. + let cap = MAX_BANDED_PIXELS * 0.999; + let by_area = (cap / (w * h)).sqrt(); + let mut s = scale.min(by_area).min(MAX_SIDE as f32 / w); + // A side scaled under one pixel still renders one, so the other side alone must fit. + if w * s < 1.0 { + s = s.min(cap / h); + } + if h * s < 1.0 { + s = s.min(cap / w); + } + if s.is_finite() && s > 0.0 { s } else { f32::MIN_POSITIVE } } /// The scale a `w` × `h` pt page separates at: `scale`, within [`MAX_PLATE_PIXELS`] and @@ -341,6 +431,168 @@ fn output_intents(pdf: &Pdf, page: usize) -> Vec> { mod tests { use super::*; + /// A 40 × 40 pt page: a black disc with anti-aliased edges, a spot square overprinting it. + fn disc_and_spot() -> Vec { + let content = "0 0 0 1 k 20 4 m 29 4 36 11 36 20 c 36 29 29 36 20 36 c 11 36 4 29 4 20 c 4 11 11 4 20 4 c f /GS0 gs /CS0 cs 0.5 scn 10.3 10.3 19.4 19.4 re f"; + let resources = "/ColorSpace << /CS0 [/Separation /Gold /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.3 1 0] /N 1 >>] >> /ExtGState << /GS0 << /op true >> >>"; + let mut out = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +" + .to_vec(); + out.extend_from_slice( + b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +", + ); + out.extend_from_slice( + format!( + "3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << {resources} >> >> endobj +" + ) + .as_bytes(), + ); + out.extend_from_slice( + format!( + "4 0 obj << /Length {} >> stream +{content} +endstream endobj +", + content.len() + ) + .as_bytes(), + ); + out.extend_from_slice( + b"trailer << /Root 1 0 R >> +%%EOF", + ); + out + } + + #[test] + fn bands_join_into_the_page_rendered_whole() { + let pdf = disc_and_spot(); + let whole = plates(&pdf, 0, 216.0, &Options::default()).unwrap(); + assert_eq!((whole.width, whole.height, whole.planes.len()), (120, 120, 5)); + let mut joined = vec![Vec::new(); 5]; + let mut tops = Vec::new(); + separate(&pdf, 0, 216.0, &Options::default(), plate_scale, Some(7), &mut |band: Band| { + assert_eq!((band.plates.width, band.page_height, band.plates.inks.len()), (120, 120, 5)); + tops.push((band.top, band.plates.height)); + for (plane, part) in joined.iter_mut().zip(&band.plates.planes) { + plane.extend_from_slice(part); + } + ControlFlow::Continue(()) + }) + .unwrap(); + assert_eq!(tops.len(), 18, "17 bands of 7 rows and one of 1: {tops:?}"); + assert_eq!(tops.last(), Some(&(119, 1))); + assert!(whole.planes.iter().any(|p| p.iter().any(|t| *t > 0 && *t < 255)), "the disc's edge is anti-aliased"); + assert_eq!(joined, whole.planes, "no seam between bands"); + } + + #[test] + fn bands_reach_resolutions_past_the_plate_cap_and_can_stop() { + let pdf = disc_and_spot(); + // 40 pt at 3700 dpi is 2055 pixels a side: 4.2 MP, past `MAX_PLATE_PIXELS`. + assert!(plates(&pdf, 0, 3700.0, &Options::default()).unwrap().dpi < 3700.0); + let mut bands = Vec::new(); + plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |band| { + let p = &band.plates; + assert!((p.width * p.height) as f32 <= MAX_PLATE_PIXELS); + bands.push((band.top, p.height, p.width, p.dpi, band.page_height)); + ControlFlow::Continue(()) + }) + .unwrap(); + let &(_, _, width, dpi, page_height) = bands.first().unwrap(); + assert_eq!((width, page_height), (2055, 2055)); + assert!((dpi - 3700.0).abs() < 0.01); + assert_eq!(bands.iter().map(|b| b.1).sum::(), 2055); + + let mut seen = 0; + plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |_| { + seen += 1; + ControlFlow::Break(()) + }) + .unwrap(); + assert_eq!(seen, 1); + assert!(matches!(plates_in_bands(&pdf, 0, f32::NAN, &Options::default(), |_| ControlFlow::Continue(())), Err(Error::InvalidDpi))); + } + + /// A 10 × 2000 pt strip, black only in its bottom 10 pt. + fn tall_strip() -> Vec { + let content = "0 0 0 1 k 0 0 10 10 re f"; + let mut out = b"%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +" + .to_vec(); + out.extend_from_slice( + b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +", + ); + out.extend_from_slice( + b"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 10 2000] /Contents 4 0 R >> endobj +", + ); + out.extend_from_slice( + format!( + "4 0 obj << /Length {} >> stream +{content} +endstream endobj +", + content.len() + ) + .as_bytes(), + ); + out.extend_from_slice( + b"trailer << /Root 1 0 R >> +%%EOF", + ); + out + } + + #[test] + fn a_page_past_the_renderers_height_limit_separates_in_bands() { + // At 600 dpi the strip is 83 × 16 666 pixels: past `MAX_SIDE` down the page. + let pdf = tall_strip(); + let mut rows = 0; + let mut bands = 0; + let mut black_rows = Vec::new(); + plates_in_bands(&pdf, 0, 600.0, &Options::default(), |band| { + let p = &band.plates; + assert_eq!((p.width, band.page_height), (83, 16_666)); + let k = p.plane(InkId::process(crate::Process::Black)).unwrap(); + for (y, row) in k.chunks(p.width as usize).enumerate() { + if row.iter().all(|t| *t == 255) { + black_rows.push(band.top + y as u32); + } + } + rows += p.height; + bands += 1; + ControlFlow::Continue(()) + }) + .unwrap(); + assert_eq!((rows, bands), (16_666, 3), "bands of at most MAX_SIDE rows"); + // The square's top edge is 1990 pt down, row 16 583.3: rows 16 584 to the last are solid. + assert_eq!(black_rows.first(), Some(&16_584), "{:?}", &black_rows[..black_rows.len().min(3)]); + assert_eq!(black_rows.len(), 82); + } + + #[test] + fn banded_scale_keeps_the_side_and_area_limits() { + assert_eq!(banded_scale(40.0, 40.0, 10.0), 10.0); + assert!(612.0 * banded_scale(612.0, 792.0, 2400.0 / 72.0) <= MAX_SIDE as f32); + let s = banded_scale(100.0, 1.0e6, 10.0); + assert!(100.0 * 1.0e6 * s * s <= MAX_BANDED_PIXELS * 1.0001); + assert!(banded_scale(0.0, f32::NAN, 1.0) > 0.0); + // A 1 pt wide, very tall page: its width floors to one pixel, which the cap still counts. + let s = banded_scale(1.0, 1.0e9, 1.0); + let [width, height] = [1.0f32, 1.0e9].map(|side| (side * s).floor().max(1.0)); + assert!(width * height <= MAX_BANDED_PIXELS); + // A page whose exact area scale rounds up in f32 by a pixel row. + let s = banded_scale(17.0, 15_058_824.0, 1.0); + let [width, height] = [17.0f32, 15_058_824.0].map(|side| u64::from((side * s).floor().max(1.0) as u32)); + assert!(width * height <= MAX_BANDED_PIXELS as u64); + } + #[test] fn plates_fit_the_pixel_and_side_caps() { assert_eq!(plate_scale(40.0, 40.0, 1.0), 1.0); diff --git a/crates/proof/src/hunspell.rs b/crates/proof/src/hunspell.rs index 966ded72fd..08629a052b 100644 --- a/crates/proof/src/hunspell.rs +++ b/crates/proof/src/hunspell.rs @@ -754,11 +754,12 @@ mod tests { /// spec's default `~/.local/share` applies, and with no home there is no folder. #[test] fn xdg_data_home_follows_the_spec() { - let home = Path::new("/home/a"); - assert_eq!(xdg_data_home(Some("/data".into()), Some(home)), Some(PathBuf::from("/data"))); - assert_eq!(xdg_data_home(Some("/data".into()), None), Some(PathBuf::from("/data"))); + let home = std::env::temp_dir().join("xdg-home"); + let data = std::env::temp_dir().join("xdg-data"); + assert_eq!(xdg_data_home(Some(data.as_os_str().to_owned()), Some(&home)), Some(data.clone())); + assert_eq!(xdg_data_home(Some(data.as_os_str().to_owned()), None), Some(data)); for xdg in [None, Some(""), Some("relative/data")] { - assert_eq!(xdg_data_home(xdg.map(Into::into), Some(home)), Some(home.join(".local/share")), "{xdg:?}"); + assert_eq!(xdg_data_home(xdg.map(Into::into), Some(&home)), Some(home.join(".local/share")), "{xdg:?}"); assert_eq!(xdg_data_home(xdg.map(Into::into), None), None, "{xdg:?}"); } } @@ -1010,7 +1011,12 @@ mod tests { assert!(load(&aff, &big).unwrap_err().contains("too large")); // A directory, and on Unix an endless device, are not dictionary files. (No clock: a // reader that read `/dev/zero` would never return, so the error itself is the proof.) - assert!(load(&aff, &dir).unwrap_err().contains("not a regular file")); + let error = load(&aff, &dir).unwrap_err(); + // Windows may reject opening a directory before the reader can inspect its type. + #[cfg(unix)] + assert!(error.contains("not a regular file"), "{error}"); + #[cfg(not(unix))] + assert!(!error.is_empty()); #[cfg(unix)] assert!(load(&aff, Path::new("/dev/zero")).unwrap_err().contains("not a regular file")); // Turkish reads through the same reader. diff --git a/crates/proof/src/it/grammar.rs b/crates/proof/src/it/grammar.rs index 9019218c3c..a46a5012a0 100644 --- a/crates/proof/src/it/grammar.rs +++ b/crates/proof/src/it/grammar.rs @@ -172,7 +172,7 @@ fn ends_sentence(gap: &str, prev: &str) -> bool { return false; } rest.starts_with(char::is_whitespace) - && rest.trim_start().chars().all(|c| c.is_whitespace() || matches!(c, '"' | '“' | '«' | '(' | '[' | '\'' | '—')) + && rest.trim_start().chars().all(|c| c.is_whitespace() || matches!(c, '"' | '“' | '‘' | '«' | '(' | '[' | '\'' | '—')) } fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec) { @@ -402,6 +402,9 @@ mod tests { assert!(fixes("Vado a Roma. il cane dorme.").contains(&pair("il", "Il"))); assert!(fixes("Vado a Roma? sì.").contains(&pair("sì", "Sì"))); assert!(!fixes("Vado a Roma. Il cane dorme.").iter().any(|(_, b)| b == "Il")); + // A single opening quote can open the next sentence, as `“` and `«` do (wordcraft#3675). + assert!(fixes("Vado. ‘poi’ torno.").contains(&pair("poi", "Poi")), "{:?}", fixes("Vado. ‘poi’ torno.")); + assert!(fixes("Vado. ‘Poi’ torno.").is_empty(), "{:?}", fixes("Vado. ‘Poi’ torno.")); for t in ["Il sig. rossi arriva.", "Vedi pp. dieci e oltre.", "Nella tab. due.", "Il dr. bianchi arriva.", "Mele, pere ecc. sono frutti."] { assert!( !fixes(t).iter().any(|(_, b)| b.starts_with(char::is_uppercase) && b != "Il" && b != "Vedi" && b != "Nella" && b != "Mele"), diff --git a/crates/proof/src/tr/mod.rs b/crates/proof/src/tr/mod.rs index 5472fbe210..c728d5872a 100644 --- a/crates/proof/src/tr/mod.rs +++ b/crates/proof/src/tr/mod.rs @@ -100,11 +100,7 @@ fn check(d: &TrDict, word: &str, opts: &crate::Options) -> bool { } // Compound words separated by hyphens (e.g., `afyon-karahisar`) - if w.contains('-') && w.split('-').all(|part| part.is_empty() || check(d, part, opts)) { - return true; - } - - false + w.contains('-') && w.split('-').all(|part| part.is_empty() || check(d, part, opts)) } #[cfg(test)] diff --git a/crates/ui/README.md b/crates/ui/README.md index 4bd8b8106f..f2ae27b0fe 100644 --- a/crates/ui/README.md +++ b/crates/ui/README.md @@ -97,6 +97,8 @@ is separate; application-specific dialog behavior remains in each app. ## SVG catalogs +For common Insert Shapes choices and previews, see [the shared shape gallery](docs/shape-gallery.md). + ```rust use std::sync::OnceLock; use craft_ui::icons::{SvgIconSet, SvgStyle}; diff --git a/crates/ui/docs/dialog-tabs.md b/crates/ui/docs/dialog-tabs.md new file mode 100644 index 0000000000..41edbb9ba9 --- /dev/null +++ b/crates/ui/docs/dialog-tabs.md @@ -0,0 +1,26 @@ +# Dialog tabs that join their page + +`Tab::show_dialog_at` adds the page-joining appearance proposed in +[WordCraft #4029](https://github.com/storytold/wordcraft/pull/4029), using the library's existing +accessible tab interaction. It suits settings and property dialogs across Craft apps. + +Provide a `DialogTabStyle` with the application's colors, border, font and top corner radius. +Allocate rectangles using the application's layout and optionally `tabs::fit`; draw a baseline +before the tabs. Selected tabs use `style.page` and erase their bottom border so they join the +page. Use `style.border` for the baseline centered on the bottom edge; the selected cover extends +half its width below the interaction rectangle. Other sides and text retain their original clip. +The page should start at the tabs' bottom edge and use the same fill. + +```rust +let response = craft_ui::tabs::Tab::new(stable_id, localized_label, selected) + .show_dialog_at(ui, rect, &style); +if response.clicked() { + // Update the application's selected page. +} +``` + +IDs must remain stable independently of translated labels. Selection, overflow, arrow-key +navigation and page content remain caller-owned. The underlying `Tab` supplies accessibility, +keyboard focus/activation, drag response and disabled behavior. Text clips to its rectangle; +invalid stroke widths become zero and invalid font sizes use 12 points. No app assets or theme +are bundled, and consumer migration is separate. diff --git a/crates/ui/docs/frosted-backdrops.md b/crates/ui/docs/frosted-backdrops.md new file mode 100644 index 0000000000..847a9e8349 --- /dev/null +++ b/crates/ui/docs/frosted-backdrops.md @@ -0,0 +1,31 @@ +# Frosted ribbon and panel backdrops + +`craft_ui::backdrop` extracts the CPU sampling and blur from +[WordCraft #4019](https://github.com/storytold/wordcraft/pull/4019). It can serve ribbons, rulers, +floating palettes and inspectors without depending on a page renderer or an app's theme. + +1. Capture the contributing content in the host. Build `Thumbnail::from_image` when its pixels + change; select a block size appropriate to capture resolution (WordCraft uses about four + logical points per cell). +2. Supply `BackdropLayer`s in screen coordinates and call `compose` for the covered area. + Layers without captures use their fallback color, so first-frame rendering remains defined. +3. Keep a `BackdropTexture` per region/context and upload the composed image. Paint its full + UV rectangle behind controls using normal egui clipping and apply a caller-chosen tint. + +The output uses bilinear thumbnail samples and three separable box-blur passes (five cells +sideways/two vertically), intended for soft UI glass, not photographic filtering. Capture pixels +are premultiplied; they composite over the supplied paper's opaque RGB. Output is opaque and +the host's overlaid tint supplies translucency. No brightness threshold or dark/light alpha is +hard-coded. Choose tint for text contrast and provide an opaque fallback when transparency is off. + +Inputs are validated before multiplication/allocation. Source images are capped at 16,777,216 +pixels, thumbnails/output at 262,144 texels, output and uploaded texture sides at 1024. A long, +thin upload is rejected even when its total pixel count fits; the existing cache is preserved. +Invalid captures/areas return +`None`; invalid layer rectangles are ignored. Identical texture images skip uploads. Distinct +windows/contexts use distinct cache instances; dropping one releases its texture. + +The host owns capture and invalidation, including changes while transparency is off. When the +effect is re-enabled, backfill missing/stale captures before using them. Keep captures out of +the composition being captured to avoid feedback. Consumer adoption and GPU framebuffer capture +are separate work; this module adds no renderer callback, global UI flag or document dependency. diff --git a/crates/ui/docs/shape-gallery.md b/crates/ui/docs/shape-gallery.md new file mode 100644 index 0000000000..6221de8d8b --- /dev/null +++ b/crates/ui/docs/shape-gallery.md @@ -0,0 +1,35 @@ +# Shared Insert Shapes choices and previews + +`craft_ui::shapes` shares the shape/connector menu and original procedural previews contributed in +[WordCraft #2142](https://github.com/storytold/wordcraft/pull/2142). It provides semantic preset +identities, default ordering, connector/arrow classification, capability filtering and a menu built +on the existing accessible `IconButton`. This is reusable menu logic as well as painting. + +The overlap is concrete: GridCraft's [Insert ribbon](https://github.com/storytold/gridcraft/blob/b8771d51fb4da60bd48c13cf313d6d6014dc5e66/crates/ui-egui/src/ribbon.rs#L1534) +offers rectangle, rounded rectangle, ellipse, triangle, line, arrow and text box. WordCraft also +offers diamond, star, heart and connectors. Each host must filter by what its engine supports; +a preview does not imply import/export or rendering support in that app. + +```rust +let chosen = craft_ui::shapes::menu(ui, 220.0, font, &button_style, + |preset| supported_by_this_app(preset), + |preset| localize(preset.source_label()), +); +if let Some(preset) = chosen { + // Adapt the semantic choice to this app's insertion operation. +} +``` + +`ShapePreset::key()` is a stable choice key, not a universal command payload. +The enum is non-exhaustive: capability adapters should reject unknown future presets by default. +WordCraft maps `StraightArrowConnector` to `kind: "straightConnector", arrow: "end"`; GridCraft +must hide it until its own engine supports attachment/routing. An ordinary `Arrow` remains a +different semantic choice. The library does not silently substitute unsupported objects. + +Apps own localization, theme, popup lifetime, current document, insertion coordinates, undo and +selection. Additional actions such as New Drawing Canvas remain app-specific menu entries. +`paint_preset` is also available for app-owned gallery layouts. The previews use original path +geometry and no external assets. They are UI icons, not editable document geometry or a shape +rendering engine. Star and heart contours honor `fill` across their full area, including with no +outline; their fixed concave paths use triangle fans around verified interior centers. +Consumer adoption and command adapters are separate work. diff --git a/crates/ui/src/backdrop.rs b/crates/ui/src/backdrop.rs new file mode 100644 index 0000000000..18d391ca6c --- /dev/null +++ b/crates/ui/src/backdrop.rs @@ -0,0 +1,255 @@ +//! Bounded CPU frosted backdrops from caller-supplied images, independent of document rendering. +//! +//! Applications own capture, layout, invalidation, tint/contrast, reduced-transparency preference +//! and texture lifetime. These helpers neither read a framebuffer nor install a renderer callback. + +use egui::{Color32, ColorImage, Context, Rect, TextureHandle, TextureOptions, pos2}; + +const MAX_SOURCE_PIXELS: usize = 16_777_216; +const MAX_TEXELS: usize = 262_144; +const MAX_SIDE: usize = 1024; + +/// An averaged, opaque thumbnail of a captured surface. Pixels are stored in sRGB byte space, +/// matching the original UI effect rather than a color-managed photographic Gaussian blur. +#[derive(Clone, Debug)] +pub struct Thumbnail { + width: usize, + height: usize, + pixels: Vec<[f32; 3]>, +} + +impl Thumbnail { + /// Average `block`-pixel squares, compositing premultiplied input over `paper`. The paper's + /// unmultiplied RGB is treated as opaque. Zero block means one. Empty/malformed images, + /// source images over 16,777,216 pixels or thumbnails over 262,144 texels return `None`. + pub fn from_image(image: &ColorImage, block: usize, paper: Color32) -> Option { + if !valid_image(image, MAX_SOURCE_PIXELS) { + return None; + } + let block = block.max(1); + let [iw, ih] = image.size; + let (width, height) = (iw.div_ceil(block), ih.div_ceil(block)); + let count = width.checked_mul(height).filter(|&n| n <= MAX_TEXELS)?; + let paper = opaque_rgb(paper); + let mut pixels = Vec::with_capacity(count); + for ty in 0..height { + for tx in 0..width { + let mut sum = [0.0; 3]; + let mut n = 0.0_f32; + for y in ty * block..(ty * block).saturating_add(block).min(ih) { + for x in tx * block..(tx * block).saturating_add(block).min(iw) { + let color = image.pixels.get(y * iw + x).copied().unwrap_or(Color32::TRANSPARENT); + let missing = 1.0 - f32::from(color.a()) / 255.0; + for (channel, value) in sum.iter_mut().enumerate() { + *value += f32::from(color.to_array()[channel]) + paper[channel] * missing; + } + n += 1.0; + } + } + pixels.push(sum.map(|value| value / n.max(1.0))); + } + } + Some(Self { width, height, pixels }) + } + + fn sample(&self, u: f32, v: f32) -> [f32; 3] { + let x = (u * self.width as f32 - 0.5).clamp(0.0, (self.width - 1) as f32); + let y = (v * self.height as f32 - 0.5).clamp(0.0, (self.height - 1) as f32); + let (x0, y0) = (x as usize, y as usize); + let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1)); + let at = |x, y| self.pixels.get(y * self.width + x).copied().unwrap_or([0.0; 3]); + let (a, b, c, d) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)); + let (tx, ty) = (x - x0 as f32, y - y0 as f32); + std::array::from_fn(|i| (a[i] * (1.0 - tx) + b[i] * tx) * (1.0 - ty) + (c[i] * (1.0 - tx) + d[i] * tx) * ty) + } +} + +/// One captured surface in caller-chosen screen coordinates. Later layers cover earlier ones. +/// Missing thumbnails use opaque `fallback` RGB, allowing first-frame/capture-off fallback. +pub struct BackdropLayer<'a> { + pub rect: Rect, + pub thumbnail: Option<&'a Thumbnail>, + pub fallback: Color32, +} + +/// Sample the layers into a small opaque image and soften it with three box passes per axis +/// (five cells sideways, two vertically). Cells are about four logical points, at most 1024 +/// per side and 262,144 in total. Linear texture filtering supplies the final upsampling. +/// +/// Invalid/empty/excessive areas return `None`; invalid layer rectangles are skipped. The +/// background and fallback colors use opaque unmultiplied RGB. Layer count and capture cadence +/// are caller policy: cache thumbnails and compose only when contributing content/layout changes. +pub fn compose(area: Rect, layers: &[BackdropLayer<'_>], background: Color32) -> Option { + if !valid_rect(area) { + return None; + } + let width = (area.width() / 4.0).ceil().clamp(1.0, MAX_SIDE as f32) as usize; + let height = (area.height() / 4.0).ceil().clamp(1.0, (MAX_TEXELS / width).min(MAX_SIDE) as f32) as usize; + let mut pixels = vec![opaque_rgb(background); width * height]; + for layer in layers.iter().filter(|layer| valid_rect(layer.rect) && layer.rect.intersects(area)) { + let fallback = opaque_rgb(layer.fallback); + for y in 0..height { + for x in 0..width { + let at = + pos2(area.left() + (x as f32 + 0.5) * area.width() / width as f32, area.top() + (y as f32 + 0.5) * area.height() / height as f32); + if layer.rect.contains(at) { + let (u, v) = ((at.x - layer.rect.left()) / layer.rect.width(), (at.y - layer.rect.top()) / layer.rect.height()); + if let Some(pixel) = pixels.get_mut(y * width + x) { + *pixel = layer.thumbnail.map_or(fallback, |thumbnail| thumbnail.sample(u, v)); + } + } + } + } + } + for _ in 0..3 { + box_pass(&mut pixels, width, height, true); + box_pass(&mut pixels, width, height, false); + } + let byte = |value: f32| value.round().clamp(0.0, 255.0) as u8; + Some(ColorImage::new([width, height], pixels.into_iter().map(|p| Color32::from_rgb(byte(p[0]), byte(p[1]), byte(p[2]))).collect())) +} + +fn box_pass(pixels: &mut [[f32; 3]], width: usize, height: usize, horizontal: bool) { + let (lines, length, radius) = if horizontal { (height, width, 5) } else { (width, height, 2) }; + let at = |line: usize, cell: usize| if horizontal { line * width + cell } else { cell * width + line }; + let divisor = (2 * radius + 1) as f32; + for line in 0..lines { + let source: Vec<_> = (0..length).map(|cell| pixels.get(at(line, cell)).copied().unwrap_or([0.0; 3])).collect(); + for cell in 0..length { + let mut sum = [0.0; 3]; + for offset in 0..=2 * radius { + let value = source.get((cell + offset).saturating_sub(radius).min(length - 1)).copied().unwrap_or([0.0; 3]); + for channel in 0..3 { + sum[channel] += value[channel]; + } + } + if let Some(pixel) = pixels.get_mut(at(line, cell)) { + *pixel = sum.map(|v| v / divisor); + } + } + } +} + +fn opaque_rgb(color: Color32) -> [f32; 3] { + let [r, g, b, _] = color.to_srgba_unmultiplied(); + [f32::from(r), f32::from(g), f32::from(b)] +} + +fn valid_rect(rect: Rect) -> bool { + rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0 && rect.size().max_elem() <= 1_000_000.0 +} + +fn valid_image(image: &ColorImage, limit: usize) -> bool { + let [w, h] = image.size; + w > 0 && h > 0 && w.checked_mul(h).is_some_and(|n| n <= limit && n == image.pixels.len()) +} + +/// An explicitly owned texture cache. Keep one per backdrop and egui context. Identical images +/// do not upload again; changed images update the same texture. Dropping this releases it. +#[derive(Default)] +pub struct BackdropTexture { + texture: Option, + image: Option, +} + +impl BackdropTexture { + /// Upload a bounded valid image using linear filtering. Invalid images return `None` without + /// replacing the cache. Use a distinct cache per context; texture IDs belong to that context. + pub fn update(&mut self, ctx: &Context, name: &str, image: ColorImage) -> Option { + if !valid_image(&image, MAX_TEXELS) || image.size.iter().any(|&side| side > MAX_SIDE) { + return None; + } + if self.image.as_ref() != Some(&image) { + if let Some(texture) = self.texture.as_mut() { + texture.set(image.clone(), TextureOptions::LINEAR); + } else { + self.texture = Some(ctx.load_texture(name, image.clone(), TextureOptions::LINEAR)); + } + self.image = Some(image); + } + self.texture.as_ref().map(TextureHandle::id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn area() -> Rect { + Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(40.0, 20.0)) + } + #[test] + fn transparent_capture_composites_over_paper_and_missing_capture_uses_fallback() { + let image = ColorImage::new([2, 2], vec![Color32::TRANSPARENT; 4]); + let thumbnail = Thumbnail::from_image(&image, 2, Color32::RED); + assert!(thumbnail.is_some()); + let layers = [BackdropLayer { rect: area(), thumbnail: thumbnail.as_ref(), fallback: Color32::BLUE }]; + let image = compose(area(), &layers, Color32::GREEN); + assert!(image.as_ref().is_some_and(|image| image.pixels.iter().all(|p| *p == Color32::RED))); + let layers = [BackdropLayer { rect: area(), thumbnail: None, fallback: Color32::BLUE }]; + let image = compose(area(), &layers, Color32::GREEN); + assert!(image.as_ref().is_some_and(|image| image.pixels.iter().all(|p| *p == Color32::BLUE))); + } + #[test] + fn downsampling_and_softening_mix_neighbours_without_changing_opaque_output() { + let image = ColorImage::new([2, 1], vec![Color32::BLACK, Color32::WHITE]); + let thumbnail = Thumbnail::from_image(&image, 1, Color32::WHITE); + let layers = [BackdropLayer { rect: area(), thumbnail: thumbnail.as_ref(), fallback: Color32::RED }]; + let image = compose(area(), &layers, Color32::GREEN); + assert!(image.as_ref().is_some_and(|image| image.pixels.iter().all(|p| p.a() == 255 && p.r() > 0 && p.r() < 255))); + } + #[test] + fn malformed_dimensions_empty_images_and_large_allocations_are_bounded() { + let malformed = ColorImage { size: [usize::MAX, 2], pixels: vec![], source_size: egui::Vec2::ZERO }; + assert!(Thumbnail::from_image(&malformed, usize::MAX, Color32::WHITE).is_none()); + assert!(Thumbnail::from_image(&ColorImage::new([0, 0], vec![]), 0, Color32::WHITE).is_none()); + assert!(compose(Rect::NAN, &[], Color32::WHITE).is_none()); + assert!(compose(Rect::NOTHING, &[], Color32::WHITE).is_none()); + let large = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1_000_000.0, 1_000_000.0)); + let image = compose(large, &[], Color32::WHITE); + assert!(image.as_ref().is_some_and(|image| image.pixels.len() <= MAX_TEXELS && image.size.iter().all(|&side| side <= MAX_SIDE))); + } + #[test] + fn texture_cache_updates_changed_content_but_skips_identical_uploads() { + let ctx = Context::default(); + let mut cache = BackdropTexture::default(); + let image = ColorImage::new([1, 1], vec![Color32::RED]); + let mut first_id = None; + let out = ctx.run_ui(egui::RawInput::default(), |_| { + first_id = cache.update(&ctx, "backdrop", image.clone()); + }); + assert!(first_id.is_some()); + assert!(out.textures_delta.set.iter().any(|(id, _)| Some(*id) == first_id)); + out.drop_without_applying_deltas(); + let out = ctx.run_ui(egui::RawInput::default(), |_| { + assert_eq!(cache.update(&ctx, "backdrop", image.clone()), first_id); + }); + assert!(out.textures_delta.set.iter().all(|(id, _)| Some(*id) != first_id)); + out.drop_without_applying_deltas(); + let out = ctx.run_ui(egui::RawInput::default(), |_| { + assert_eq!(cache.update(&ctx, "backdrop", ColorImage::new([1, 1], vec![Color32::BLUE])), first_id); + }); + assert_eq!(out.textures_delta.set.iter().filter(|(id, _)| Some(**id) == first_id).count(), 1); + out.drop_without_applying_deltas(); + } + + #[test] + fn texture_upload_rejects_long_thin_images_without_replacing_the_cache() { + let ctx = Context::default(); + let mut cache = BackdropTexture::default(); + let image = ColorImage::new([1, 1], vec![Color32::RED]); + let mut kept = None; + ctx.run_ui(egui::RawInput::default(), |_| { + kept = cache.update(&ctx, "bounded", image.clone()); + }) + .drop_without_applying_deltas(); + assert!(kept.is_some()); + for size in [[MAX_SIDE + 1, 1], [1, MAX_SIDE + 1]] { + let out = ctx.run_ui(egui::RawInput::default(), |_| { + assert!(cache.update(&ctx, "bounded", ColorImage::new(size, vec![Color32::BLUE; size[0] * size[1]])).is_none()); + assert_eq!(cache.update(&ctx, "bounded", image.clone()), kept); + }); + assert!(out.textures_delta.set.iter().all(|(id, _)| Some(*id) != kept)); + out.drop_without_applying_deltas(); + } + } +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 3c98f5f0c6..e5a2d06c23 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -5,6 +5,7 @@ //! Applications own their assets, themes, layouts, commands and document semantics. Components //! accept focused style values and return egui responses; no application engine is required. +pub mod backdrop; pub mod buttons; pub mod capture; pub mod combo; @@ -18,6 +19,7 @@ pub mod layout; pub mod localized; pub mod panes; pub mod printing; +pub mod shapes; pub mod tabs; #[cfg(all(feature = "screen-testing", not(target_arch = "wasm32")))] pub mod testing; diff --git a/crates/ui/src/shapes/mod.rs b/crates/ui/src/shapes/mod.rs new file mode 100644 index 0000000000..fcf809746e --- /dev/null +++ b/crates/ui/src/shapes/mod.rs @@ -0,0 +1,174 @@ +//! Shared shape-choice semantics and procedural previews, without document insertion commands. + +use crate::buttons::{IconButton, IconButtonStyle}; +use egui::{Align2, FontId, Ui, Vec2}; + +mod paint; +pub use paint::paint_preset; + +/// A menu choice, not a document shape model. Connector routing/attachment and text editing stay +/// in each app's engine. Stable keys are suitable for IDs and explicit adapters, not localized text. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ShapePreset { + Rectangle, + RoundedRectangle, + Ellipse, + Triangle, + Diamond, + Line, + Arrow, + Star, + Heart, + TextBox, + StraightConnector, + StraightArrowConnector, + ElbowConnector, + ElbowArrowConnector, + CurvedConnector, + CurvedArrowConnector, +} + +/// Default presentation order. Filter by actual application capabilities before showing choices; +/// having a preview here never means an application's importer/renderer supports the shape. +pub const PRESETS: &[ShapePreset] = &[ + ShapePreset::Rectangle, + ShapePreset::RoundedRectangle, + ShapePreset::Ellipse, + ShapePreset::Triangle, + ShapePreset::Diamond, + ShapePreset::Line, + ShapePreset::Arrow, + ShapePreset::Star, + ShapePreset::Heart, + ShapePreset::TextBox, + ShapePreset::StraightConnector, + ShapePreset::StraightArrowConnector, + ShapePreset::ElbowConnector, + ShapePreset::ElbowArrowConnector, + ShapePreset::CurvedConnector, + ShapePreset::CurvedArrowConnector, +]; + +impl ShapePreset { + /// Stable semantic choice key, independent of labels and any application's command protocol. + pub const fn key(self) -> &'static str { + match self { + Self::Rectangle => "rectangle", + Self::RoundedRectangle => "roundedRectangle", + Self::Ellipse => "ellipse", + Self::Triangle => "triangle", + Self::Diamond => "diamond", + Self::Line => "line", + Self::Arrow => "arrow", + Self::Star => "star", + Self::Heart => "heart", + Self::TextBox => "textBox", + Self::StraightConnector => "straightConnector", + Self::StraightArrowConnector => "straightArrowConnector", + Self::ElbowConnector => "elbowConnector", + Self::ElbowArrowConnector => "elbowArrowConnector", + Self::CurvedConnector => "curvedConnector", + Self::CurvedArrowConnector => "curvedArrowConnector", + } + } + + /// English source string for the application's localization catalog. The menu always asks + /// the caller for a label; it never installs a translation service or uses a label as identity. + pub const fn source_label(self) -> &'static str { + match self { + Self::Rectangle => "Rectangle", + Self::RoundedRectangle => "Rounded Rectangle", + Self::Ellipse => "Oval", + Self::Triangle => "Triangle", + Self::Diamond => "Diamond", + Self::Line => "Line", + Self::Arrow => "Arrow", + Self::Star => "Star", + Self::Heart => "Heart", + Self::TextBox => "Text Box", + Self::StraightConnector => "Straight Connector", + Self::StraightArrowConnector => "Straight Arrow Connector", + Self::ElbowConnector => "Elbow Connector", + Self::ElbowArrowConnector => "Elbow Arrow Connector", + Self::CurvedConnector => "Curved Connector", + Self::CurvedArrowConnector => "Curved Arrow Connector", + } + } + + pub const fn is_connector(self) -> bool { + matches!( + self, + Self::StraightConnector + | Self::StraightArrowConnector + | Self::ElbowConnector + | Self::ElbowArrowConnector + | Self::CurvedConnector + | Self::CurvedArrowConnector + ) + } + + /// Whether this choice has an arrow at its end. An ordinary arrow remains a different + /// choice from a connector with an arrow; the application decides its attachment semantics. + pub const fn has_end_arrow(self) -> bool { + matches!(self, Self::Arrow | Self::StraightArrowConnector | Self::ElbowArrowConnector | Self::CurvedArrowConnector) + } +} + +/// Show the default shape list, returning the chosen semantic preset without executing commands. +/// +/// `supported` hides capabilities absent from the host. `label` supplies localized accessible +/// text; IDs remain stable even for duplicate translations. The caller owns the popup, theme, +/// font, optional canvas/gallery actions and command mapping. Wrap repeated menus in `push_id`. +/// Uses the existing [`IconButton`] for keyboard/pointer/accessibility and disabled-state behavior. +/// Rows clip long labels; widths must be finite, positive and at most 4096 points or no rows show. +pub fn menu( + ui: &mut Ui, + width: f32, + font: FontId, + style: &IconButtonStyle, + mut supported: impl FnMut(ShapePreset) -> bool, + mut label: impl FnMut(ShapePreset) -> String, +) -> Option { + if !width.is_finite() || width <= 0.0 || width > 4096.0 { + return None; + } + let font = FontId::new(if font.size.is_finite() { font.size.clamp(1.0, 128.0) } else { 12.0 }, font.family); + let height = (font.size + 10.0).max(26.0); + let mut chosen = None; + let mut previous_connector = false; + let mut have_item = false; + for &preset in PRESETS { + if !supported(preset) { + continue; + } + if have_item && preset.is_connector() && !previous_connector { + ui.separator(); + } + previous_connector = preset.is_connector(); + have_item = true; + let label = label(preset); + ui.push_id(preset.key(), |ui| { + let response = IconButton::new(&label, Vec2::new(width, height), style).show(ui, |ui, rect, tint| { + let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(rect)); + let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), Vec2::splat(20.0)); + paint_preset(&painter, icon, preset, egui::Stroke::new(1.4, tint), tint.gamma_multiply(0.15)); + let text_rect = egui::Rect::from_min_max(egui::pos2((rect.left() + 30.0).min(rect.right()), rect.top()), rect.max); + painter.with_clip_rect(ui.clip_rect().intersect(text_rect)).text( + text_rect.left_center(), + Align2::LEFT_CENTER, + &label, + font.clone(), + tint, + ); + }); + if response.clicked() { + chosen = Some(preset); + } + }); + } + chosen +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/shapes/paint.rs b/crates/ui/src/shapes/paint.rs new file mode 100644 index 0000000000..ef0172d65f --- /dev/null +++ b/crates/ui/src/shapes/paint.rs @@ -0,0 +1,126 @@ +use super::ShapePreset; +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, StrokeKind, vec2}; + +/// Paint an original procedural preview, adapted from WordCraft's Insert Shapes menu (#2142). +/// Preview geometry is independent of document geometry: it does not insert/render editable +/// document objects. No external icon assets, fonts or application dependencies are needed. +/// Invalid/empty/excessive rectangles produce no paint; stroke widths are bounded to the icon. +pub fn paint_preset(painter: &Painter, rect: Rect, preset: ShapePreset, stroke: Stroke, fill: Color32) { + if !rect.is_finite() || rect.width() <= 0.0 || rect.height() <= 0.0 || rect.size().max_elem() > 4096.0 { + return; + } + let painter = painter.with_clip_rect(painter.clip_rect().intersect(rect)); + let scale = rect.width().min(rect.height()) / 20.0; + let origin = rect.center() - vec2(10.0, 10.0) * scale; + let point = |x: f32, y: f32| origin + vec2(x, y) * scale; + let width = if stroke.width.is_finite() { stroke.width.clamp(0.0, rect.width().min(rect.height()) * 0.25) } else { 0.0 }; + let stroke = Stroke::new(width, stroke.color); + let polygon = |points: &[(f32, f32)]| { + painter.add(Shape::convex_polygon(points.iter().map(|&(x, y)| point(x, y)).collect(), fill, stroke)); + }; + let line = |points: &[(f32, f32)]| { + painter.add(Shape::line(points.iter().map(|&(x, y)| point(x, y)).collect(), stroke)); + }; + let head = |tip: Pos2, previous: Pos2| { + let direction = (tip - previous).normalized(); + let side = vec2(-direction.y, direction.x); + painter.add(Shape::line( + vec![tip - direction * (4.0 * scale) + side * (2.5 * scale), tip, tip - direction * (4.0 * scale) - side * (2.5 * scale)], + stroke, + )); + }; + match preset { + ShapePreset::Rectangle | ShapePreset::RoundedRectangle | ShapePreset::TextBox => { + let shape = Rect::from_min_max(point(3.0, 5.0), point(17.0, 15.0)); + let radius = if preset == ShapePreset::RoundedRectangle { 3.0 * scale } else { 0.0 }; + painter.rect(shape, radius, fill, stroke, StrokeKind::Inside); + if preset == ShapePreset::TextBox { + for y in [8.0, 10.0, 12.0] { + line(&[(6.0, y), (14.0, y)]); + } + } + } + ShapePreset::Ellipse => { + painter.add(Shape::ellipse_filled(rect.center(), vec2(7.5, 5.5) * scale, fill)); + painter.add(Shape::ellipse_stroke(rect.center(), vec2(7.5, 5.5) * scale, stroke)); + } + ShapePreset::Triangle => polygon(&[(10.0, 3.5), (17.0, 16.5), (3.0, 16.5)]), + ShapePreset::Diamond => polygon(&[(10.0, 3.0), (17.0, 10.0), (10.0, 17.0), (3.0, 10.0)]), + ShapePreset::Line | ShapePreset::Arrow => { + line(&[(4.0, 16.0), (16.0, 4.0)]); + if preset.has_end_arrow() { + head(point(16.0, 4.0), point(4.0, 16.0)); + } + } + ShapePreset::Star => { + let points: Vec<_> = (0..10) + .map(|i| { + let angle = -std::f32::consts::FRAC_PI_2 + i as f32 * std::f32::consts::PI / 5.0; + let radius = if i % 2 == 0 { 8.0 } else { 3.3 }; + point(10.0 + radius * angle.cos(), 10.8 + radius * angle.sin()) + }) + .collect(); + fill_contour(&painter, point(10.0, 10.8), &points, fill); + painter.add(Shape::closed_line(points, stroke)); + } + ShapePreset::Heart => { + let points: Vec<_> = (0..32) + .map(|i| { + let t = i as f32 / 32.0 * std::f32::consts::TAU; + point( + 10.0 + 16.0 * t.sin().powi(3) * 0.44, + 9.6 - (13.0 * t.cos() - 5.0 * (2.0 * t).cos() - 2.0 * (3.0 * t).cos() - (4.0 * t).cos()) * 0.44, + ) + }) + .collect(); + fill_contour(&painter, point(10.0, 10.0), &points, fill); + painter.add(Shape::closed_line(points, stroke)); + } + _ => { + let points: Vec<_> = match preset { + ShapePreset::ElbowConnector | ShapePreset::ElbowArrowConnector => { + vec![point(4.0, 15.0), point(10.0, 15.0), point(10.0, 5.0), point(16.0, 5.0)] + } + ShapePreset::CurvedConnector | ShapePreset::CurvedArrowConnector => (0..=16) + .map(|i| { + let t = i as f32 / 16.0; + let m = 1.0 - t; + let w = [m * m * m, 3.0 * m * m * t, 3.0 * m * t * t, t * t * t]; + point(w[0] * 4.0 + w[1] * 12.0 + w[2] * 8.0 + w[3] * 16.0, w[0] * 15.0 + w[1] * 15.0 + w[2] * 5.0 + w[3] * 5.0) + }) + .collect(), + _ => vec![point(4.0, 15.0), point(16.0, 5.0)], + }; + painter.add(Shape::line(points.clone(), stroke)); + if let Some(&first) = points.first() { + painter.circle_filled(first, 1.6 * scale, stroke.color); + } + if let [.., previous, tip] = points.as_slice() { + if preset.has_end_arrow() { + head(*tip, *previous); + } else { + painter.circle_filled(*tip, 1.6 * scale, stroke.color); + } + } + } + } + // The painter's existing clip handles its host; all preview geometry stays in the icon box. +} + +/// These two fixed contours are star-shaped around the supplied center: it lies in every +/// edge's interior half-plane. A triangle fan therefore fills their concavities without the +/// convex-polygon assumption. This is not a triangulator for arbitrary application paths. +fn fill_contour(painter: &Painter, center: Pos2, points: &[Pos2], fill: Color32) { + if points.len() < 3 || fill == Color32::TRANSPARENT { + return; + } + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(center, fill); + for &point in points { + mesh.colored_vertex(point, fill); + } + for index in 0..points.len() { + mesh.add_triangle(0, 1 + index as u32, 1 + ((index + 1) % points.len()) as u32); + } + painter.add(Shape::mesh(mesh)); +} diff --git a/crates/ui/src/shapes/tests.rs b/crates/ui/src/shapes/tests.rs new file mode 100644 index 0000000000..32d89e426e --- /dev/null +++ b/crates/ui/src/shapes/tests.rs @@ -0,0 +1,114 @@ +use super::*; +use crate::buttons::ButtonVisuals; +use egui::{Color32, CornerRadius, Stroke}; +use egui_kittest::kittest::Queryable; + +fn style() -> IconButtonStyle { + let normal = ButtonVisuals { fill: Color32::TRANSPARENT, stroke: Stroke::NONE, icon: Color32::BLACK }; + IconButtonStyle { + normal, + hovered: ButtonVisuals { fill: Color32::LIGHT_BLUE, ..normal }, + pressed: None, + selected: normal, + corner_radius: CornerRadius::same(3), + focus_stroke: Stroke::new(1.0, Color32::BLUE), + } +} + +#[test] +fn capability_filtered_menu_uses_stable_identity_for_duplicate_localized_labels() { + let mut h = egui_kittest::Harness::builder().with_size(Vec2::new(400.0, 300.0)).build_ui_state( + |ui, chosen: &mut Option| { + if let Some(preset) = menu( + ui, + 180.0, + FontId::proportional(12.0), + &style(), + |p| matches!(p, ShapePreset::Rectangle | ShapePreset::Ellipse), + |_| "Object".into(), + ) { + *chosen = Some(preset); + } + }, + None, + ); + h.run_steps(2); + let items: Vec<_> = h.get_all_by_label("Object").collect(); + assert_eq!(items.len(), 2); + items[1].click(); + h.run_steps(2); + assert_eq!(*h.state(), Some(ShapePreset::Ellipse)); +} + +#[test] +fn catalog_keys_are_unique_and_arrow_connector_semantics_remain_distinct() { + let keys: std::collections::HashSet<_> = PRESETS.iter().map(|p| p.key()).collect(); + assert_eq!(keys.len(), PRESETS.len()); + assert!(ShapePreset::StraightArrowConnector.is_connector()); + assert!(ShapePreset::StraightArrowConnector.has_end_arrow()); + assert!(!ShapePreset::Arrow.is_connector()); + assert!(ShapePreset::Arrow.has_end_arrow()); + assert!(!ShapePreset::ElbowConnector.has_end_arrow()); +} + +#[test] +fn every_procedural_preview_tessellates_and_invalid_geometry_is_inert() { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + for &preset in PRESETS { + let rect = egui::Rect::from_min_size(egui::pos2(10.0, 10.0), Vec2::splat(20.0)); + paint_preset(ui.painter(), rect, preset, Stroke::new(f32::NAN, Color32::BLACK), Color32::LIGHT_BLUE); + } + }); + out.textures_delta.clear(); + for primitive in ctx.tessellate(out.shapes, out.pixels_per_point) { + assert!(primitive.clip_rect.min.x >= 10.0 && primitive.clip_rect.min.y >= 10.0); + assert!(primitive.clip_rect.max.x <= 30.0 && primitive.clip_rect.max.y <= 30.0); + if let egui::epaint::Primitive::Mesh(mesh) = primitive.primitive { + assert!(mesh.is_valid()); + assert!(mesh.vertices.iter().all(|v| v.pos.is_finite())); + } + } + let out = ctx.run_ui(egui::RawInput::default(), |ui| { + for &preset in PRESETS { + paint_preset(ui.painter(), egui::Rect::NAN, preset, Stroke::NONE, Color32::WHITE); + } + }); + assert!(out.shapes.is_empty() || out.shapes.iter().all(|s| matches!(s.shape, egui::Shape::Noop))); + out.drop_without_applying_deltas(); +} + +#[test] +fn concave_previews_fill_the_star_tips_and_heart_without_an_outline() { + let cross = |a: egui::Pos2, b: egui::Pos2, c: egui::Pos2| { + let ab = b - a; + let ac = c - a; + ab.x * ac.y - ab.y * ac.x + }; + for (preset, sample) in [(ShapePreset::Star, egui::pos2(20.0, 14.0)), (ShapePreset::Heart, egui::pos2(20.0, 20.0))] { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + paint_preset(ui.painter(), egui::Rect::from_min_size(egui::pos2(10.0, 10.0), Vec2::splat(20.0)), preset, Stroke::NONE, Color32::RED); + }); + out.textures_delta.clear(); + let mut covered = false; + for primitive in ctx.tessellate(out.shapes, out.pixels_per_point) { + if let egui::epaint::Primitive::Mesh(mesh) = primitive.primitive { + assert!(mesh.is_valid()); + for triangle in mesh.indices.as_chunks::<3>().0 { + let [a, b, c] = [mesh.vertices[triangle[0] as usize], mesh.vertices[triangle[1] as usize], mesh.vertices[triangle[2] as usize]]; + // Consistent winding verifies each fixed contour's center stays in its kernel. + assert!(cross(a.pos, b.pos, c.pos) > 0.0); + covered |= primitive.clip_rect.contains(sample) + && a.color == Color32::RED + && b.color == Color32::RED + && c.color == Color32::RED + && cross(a.pos, b.pos, sample) >= -0.0001 + && cross(b.pos, c.pos, sample) >= -0.0001 + && cross(c.pos, a.pos, sample) >= -0.0001; + } + } + } + assert!(covered, "{preset:?} must honor its fill with no outline"); + } +} diff --git a/crates/ui/src/tabs/dialog.rs b/crates/ui/src/tabs/dialog.rs new file mode 100644 index 0000000000..292cbb4cf2 --- /dev/null +++ b/crates/ui/src/tabs/dialog.rs @@ -0,0 +1,143 @@ +//! Page-joining dialog tab painting on the existing accessible tab interaction. + +use super::Tab; +use egui::{Align2, Color32, CornerRadius, FontId, Rect, Response, Stroke, StrokeKind, Ui, pos2}; + +/// A focused style adapter, not an application theme. The selected fill should match the page +/// below the strip. Draw the strip's baseline before its tabs: selected tabs erase their bottom +/// border to visually join that page. Applications own strip layout, overflow and page selection. +#[derive(Clone, Debug)] +pub struct DialogTabStyle { + pub page: Color32, + pub inactive: Color32, + pub hovered: Color32, + pub text: Color32, + pub selected_text: Color32, + /// Use this stroke for the strip baseline too. The selected seam covers half its width + /// below the tab, matching a baseline centered on the bottom edge. + pub border: Stroke, + pub font: FontId, + pub top_radius: u8, +} + +impl Tab<'_> { + /// Paint a raised dialog tab and return the same response as [`Tab::show_at`]. + /// + /// Stable IDs, selected accessibility state, parent disabled state, keyboard activation and + /// focus outlines all come from the existing tab. The application supplies localized text, + /// geometry and style. Oversized labels clip within their tab instead of covering neighbours. + /// The selected tab joins a page beginning at `rect.bottom()`; unselected tabs sit two points + /// lower. No page is selected implicitly, and arrow-key navigation remains caller policy. + pub fn show_dialog_at(self, ui: &mut Ui, rect: Rect, style: &DialogTabStyle) -> Response { + let selected = self.selected; + let label = self.label; + self.show_at(ui, rect, |ui, response| { + let inset = if selected { 0.0 } else { 2.0_f32.min(rect.height() * 0.25) }; + let shown = Rect::from_min_max(pos2(rect.left(), rect.top() + inset), rect.max); + let width = if style.border.width.is_finite() { style.border.width.clamp(0.0, rect.width().min(rect.height()) * 0.5) } else { 0.0 }; + let stroke = Stroke::new(width, style.border.color); + let fill = if selected { + style.page + } else if response.hovered() { + style.hovered + } else { + style.inactive + }; + let radius = CornerRadius { nw: style.top_radius, ne: style.top_radius, sw: 0, se: 0 }; + let mut paint_bounds = rect; + if selected { + paint_bounds.max.y += width * 0.5; + } + let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(paint_bounds)); + painter.rect(shown, radius, fill, stroke, StrokeKind::Inside); + // Cover only the selected tab's bottom edge, preserving the vertical border corners. + if selected && width > 0.0 && rect.width() > 2.0 * width { + painter.rect_filled( + Rect::from_min_max(pos2(rect.left() + width, rect.bottom() - width), pos2(rect.right() - width, rect.bottom() + width * 0.5)), + 0.0, + style.page, + ); + } + let text_rect = rect.shrink2(egui::vec2(2.0_f32.min(rect.width() * 0.25), 0.0)); + let color = if selected { style.selected_text } else { style.text }; + let font = FontId::new(if style.font.size.is_finite() { style.font.size.clamp(1.0, 512.0) } else { 12.0 }, style.font.family.clone()); + painter.with_clip_rect(text_rect.intersect(ui.clip_rect())).text(rect.center(), Align2::CENTER_CENTER, label, font, color); + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Id, Vec2}; + use egui_kittest::kittest::Queryable; + + fn style() -> DialogTabStyle { + DialogTabStyle { + page: Color32::WHITE, + inactive: Color32::LIGHT_GRAY, + hovered: Color32::GRAY, + text: Color32::BLACK, + selected_text: Color32::BLACK, + border: Stroke::new(1.0, Color32::DARK_GRAY), + font: FontId::proportional(12.0), + top_radius: 5, + } + } + + #[test] + fn painting_preserves_accessible_selection_and_click_response_with_duplicate_labels() { + let mut h = egui_kittest::Harness::builder().with_size(Vec2::new(400.0, 200.0)).build_ui_state( + |ui, selected: &mut usize| { + for index in 0..2 { + let (_, rect) = ui.allocate_space(Vec2::new(100.0, 26.0)); + let response = Tab::new(Id::unique(("dialog", index)), "Options", *selected == index).show_dialog_at(ui, rect, &style()); + if response.clicked() { + *selected = index; + } + } + }, + 0, + ); + h.run_steps(2); + let tabs: Vec<_> = h.get_all_by_label("Options").collect(); + assert_eq!(tabs.len(), 2); + tabs[1].click(); + h.run_steps(2); + assert_eq!(*h.state(), 1); + } + + #[test] + fn malformed_style_and_long_text_tessellate_inside_small_tab() { + let ctx = egui::Context::default(); + let mut style = style(); + style.border.width = f32::NAN; + style.font.size = f32::INFINITY; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let (_, rect) = ui.allocate_space(Vec2::new(5.0, 3.0)); + Tab::new(Id::unique("small"), "A long localized label", true).show_dialog_at(ui, rect, &style); + }); + out.textures_delta.clear(); + let _ = ctx.tessellate(out.shapes, out.pixels_per_point); + } + + #[test] + fn selected_tab_erases_a_baseline_centered_on_its_bottom_edge() { + let mut h = egui_kittest::Harness::builder().with_size(Vec2::new(120.0, 80.0)).wgpu().build_ui(|ui| { + ui.painter().rect_filled(ui.max_rect(), 0.0, Color32::WHITE); + let rect = Rect::from_min_size(egui::pos2(10.0, 10.0), Vec2::new(100.0, 26.0)); + let mut style = style(); + style.border = Stroke::new(2.0, Color32::BLACK); + ui.painter().line_segment([rect.left_bottom(), rect.right_bottom()], style.border); + Tab::new(Id::unique("joined"), "Options", true).show_dialog_at(ui, rect, &style); + }); + h.ctx.set_pixels_per_point(1.0); + h.run_steps(3); + let image = h.render(); + assert!(image.is_ok()); + if let Ok(image) = image { + let pixel = image.get_pixel(60, 36); + assert!(pixel[0] >= 245 && pixel[1] >= 245 && pixel[2] >= 245, "seam remains visible: {pixel:?}"); + } + } +} diff --git a/crates/ui/src/tabs/mod.rs b/crates/ui/src/tabs/mod.rs index ab6d16aece..fa48e90f0b 100644 --- a/crates/ui/src/tabs/mod.rs +++ b/crates/ui/src/tabs/mod.rs @@ -7,6 +7,9 @@ use egui::{Id, Rect, Response, Sense, Stroke, StrokeKind, Ui, Vec2}; +mod dialog; +pub use dialog::DialogTabStyle; + /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] pub struct TabFit { diff --git a/crates/update/src/dialog.rs b/crates/update/src/dialog.rs index 740d763eaa..1af759e4af 100644 --- a/crates/update/src/dialog.rs +++ b/crates/update/src/dialog.rs @@ -38,6 +38,13 @@ pub struct StartupPrompt { /// The update is ready and waits for the app to close: the main button reads "Restart to /// Update" and answers [`StartupPromptResponse::UpdateAndRestart`]. pub is_ready: bool, + /// The app holds unsaved work it can save: the update button reads Save and Update and asks + /// for that save first. + pub offer_save: bool, + /// The app is saving the work; the update starts once it is done. + pub is_saving: bool, + /// The user chose Save and Update and the app has not taken the request yet. + pub save_wanted: bool, /// Puts the card's words in the interface language ([`crate::translate`]); English by default. pub translate: Translate, } @@ -64,6 +71,9 @@ impl StartupPrompt { status_note: None, is_installing: false, is_ready: false, + offer_save: false, + is_saving: false, + save_wanted: false, translate: english, } } @@ -152,10 +162,12 @@ impl StartupPrompt { ui.add_space(4.0); } - if self.is_installing { + if self.is_installing || self.is_saving { + // Plain dots: the save's words add no new non-ASCII glyph to the card (#343). + let status = if self.is_saving { t("Saving your work...", &[]) } else { t("Downloading and installing update…", &[]) }; ui.horizontal(|ui| { ui.spinner(); - ui.label(RichText::new(t("Downloading and installing update…", &[])).size(12.0).color(text_primary)); + ui.label(RichText::new(status).size(12.0).color(text_primary)); }); } else { let desc = t( @@ -194,6 +206,11 @@ impl StartupPrompt { } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + // Nothing in the button's place: the second click of a double click + // must not dismiss the update. Esc and the close button still do. + if self.is_saving { + return; + } if self.is_installing { let dismiss_btn = egui::Button::new(RichText::new(button(t, "Dismiss")).size(10.5).monospace().color(text_muted)) .corner_radius(egui::CornerRadius::ZERO) @@ -203,7 +220,13 @@ impl StartupPrompt { } } else { if self.is_self_updating || self.is_ready { - let label = if self.is_ready { "Restart to Update" } else { "Update and Restart" }; + let label = if self.offer_save { + "Save and Update" + } else if self.is_ready { + "Restart to Update" + } else { + "Update and Restart" + }; let update_btn = egui::Button::new(RichText::new(button(t, label)).size(10.5).strong().monospace().color(on_fill)) .fill(fill) @@ -613,7 +636,7 @@ fn decode_icon(png: &[u8], max_side: u32) -> Option { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::suite::PHOTOCRAFT; use egui::{Context, Event, FullOutput, Key, Modifiers, RawInput, Rect}; @@ -646,6 +669,9 @@ mod tests { status_note: None, is_installing: false, is_ready: false, + offer_save: false, + is_saving: false, + save_wanted: false, translate: english, } } @@ -982,7 +1008,7 @@ mod tests { } /// Where the frame painted `text` (inside its galley, so a pointer there is over it). - fn text_pos(output: &FullOutput, text: &str) -> Option { + pub(crate) fn text_pos(output: &FullOutput, text: &str) -> Option { fn find(shape: &egui::Shape, text: &str) -> Option { match shape { egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)), @@ -1084,6 +1110,104 @@ mod tests { assert!(card, "dialog card missing"); } + /// Work the app can save: the main button says so, and a click answers as the update button does. + #[test] + fn a_prompt_with_work_to_save_offers_save_and_update() { + let ctx = dark_context(); + let mut prompt = StartupPrompt { offer_save: true, ..prompt_for(true) }; + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + let painted = painted_text(&output); + assert!(painted.contains("SAVE AND UPDATE") && painted.contains("LATER"), "{painted}"); + assert!(!painted.contains("UPDATE AND RESTART"), "{painted}"); + let at = text_pos(&output, "SAVE AND UPDATE").expect("SAVE AND UPDATE is painted"); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]); + frame(&ctx, &mut prompt, vec![button(true)]); + let (response, _) = frame(&ctx, &mut prompt, vec![button(false)]); + assert_eq!(response, StartupPromptResponse::UpdateAndRestart); + } + + /// A ready update with work to save offers Save and Update, not Restart to Update. + #[test] + fn a_ready_prompt_with_work_to_save_offers_save_and_update() { + let ctx = dark_context(); + let mut prompt = StartupPrompt { is_ready: true, offer_save: true, ..prompt_for(false) }; + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + let painted = painted_text(&output); + assert!(painted.contains("SAVE AND UPDATE"), "{painted}"); + assert!(!painted.contains("RESTART TO UPDATE"), "{painted}"); + let at = text_pos(&output, "SAVE AND UPDATE").expect("SAVE AND UPDATE is painted"); + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]); + frame(&ctx, &mut prompt, vec![button(true)]); + let (response, _) = frame(&ctx, &mut prompt, vec![button(false)]); + assert_eq!(response, StartupPromptResponse::UpdateAndRestart); + } + + /// A copy that can't update itself keeps its Download button, whatever the app can save. + #[test] + fn a_download_prompt_never_offers_save_and_update() { + let ctx = dark_context(); + let mut prompt = StartupPrompt { offer_save: true, ..prompt_for(false) }; + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + let painted = painted_text(&output); + assert!(painted.contains("DOWNLOAD") && !painted.contains("SAVE AND UPDATE"), "{painted}"); + } + + /// While the app saves, the card says that and stays ASCII (#343). No button takes the place + /// of Save and Update, where the second click of a double click would land; Esc and the + /// close button still dismiss. + #[test] + fn a_saving_prompt_says_so_and_offers_no_second_click() { + let ctx = dark_context(); + let mut prompt = StartupPrompt { is_saving: true, offer_save: true, ..prompt_for(true) }; + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + let painted = painted_text(&output); + assert!(painted.contains("Saving your work..."), "{painted}"); + for absent in ["Downloading", "SAVE AND UPDATE", "DISMISS", "LATER"] { + assert!(!painted.contains(absent), "{absent} in {painted}"); + } + assert!(painted.is_ascii(), "the prompt paints a non-ASCII character: {painted:?}"); + } + + /// The new button and status words are the app's to translate. + #[test] + fn the_save_button_and_status_go_through_the_translator() { + for (offer_save, is_saving) in [(true, false), (false, true)] { + let ctx = dark_context(); + let mut prompt = StartupPrompt { offer_save, is_saving, ..prompt_for(true) }.with_translator(pseudo); + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + let painted = painted_text(&output); + assert_all_translated(&painted, &["P", "PhotoCraft"]); + assert!(!offer_save || painted.contains("[ | SAVE AND UPDATE]"), "{painted}"); + assert!(!is_saving || painted.contains("[ | Saving your work...]"), "{painted}"); + } + } + + /// The second click of a double click lands where Save and Update was: it must not dismiss. + #[test] + fn a_second_click_during_the_save_leaves_the_prompt_open() { + let ctx = dark_context(); + let mut prompt = StartupPrompt { offer_save: true, ..prompt_for(true) }; + frame(&ctx, &mut prompt, Vec::new()); + let (_, output) = frame(&ctx, &mut prompt, Vec::new()); + // Right of the label's centre, where a right-aligned Dismiss would sit. + let at = text_pos(&output, "SAVE AND UPDATE").expect("SAVE AND UPDATE is painted") + egui::vec2(40.0, 0.0); + prompt.is_saving = true; + let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + frame(&ctx, &mut prompt, Vec::new()); + frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]); + frame(&ctx, &mut prompt, vec![button(true)]); + let (response, _) = frame(&ctx, &mut prompt, vec![button(false)]); + assert_eq!(response, StartupPromptResponse::Pending); + assert!(prompt.open); + } + #[test] fn installing_prompt_paints_status_and_dismiss() { let ctx = dark_context(); diff --git a/crates/update/src/updater.rs b/crates/update/src/updater.rs index 7251ba1ec5..86ef6d9966 100644 --- a/crates/update/src/updater.rs +++ b/crates/update/src/updater.rs @@ -578,14 +578,36 @@ impl Updater { /// Like [`Self::show`], but an installation only starts, and a ready update only asks the app /// to close, when `can_start` is true. An app passes `false` while it holds unsaved work. pub fn show_if(&mut self, ctx: &egui::Context, can_start: bool) -> Action { + self.show_with_save(ctx, can_start, false) + } + + /// Like [`Self::show_if`], and offers Save and Update while `can_save` is true. It is true only + /// when a successful save alone makes `can_start` true: every piece of unsaved work is in a + /// document the app can save without asking the user, and nothing else holds the install back + /// (a print job, a comment draft). It stays true during the save. After a click, + /// [`Self::take_save_request`] tells the app to save, the install starts (or a ready update + /// asks the app to close) once `can_start` is true, and [`Self::save_stopped`] reports a save that did not get there. + pub fn show_with_save(&mut self, ctx: &egui::Context, can_start: bool, can_save: bool) -> Action { + // A save the user asked for ended with nothing unsaved: go on as the click would have. + // For a ready update that sets `close_wanted`, so the close below happens in this frame. + if self.prompt.as_ref().is_some_and(|p| p.is_saving) { + if can_start { + self.stop_saving(); + self.start_install(ctx); + } else if !can_save { + self.save_stopped(None); + } + } // The close waits for the app to hold no unsaved work: the user may have edited while the // update installed. It is only asked for: the helper, which waits just a minute for the // app to exit, starts at the exit itself (`start_pending_update`), so a close the user // cancels leaves the update ready. if can_start && self.restart.is_some() && std::mem::take(&mut self.close_wanted) { + self.stop_saving(); return Action::Close; } let Some(prompt) = &mut self.prompt else { return Action::None }; + prompt.offer_save = can_save && !can_start; match prompt.show(ctx) { StartupPromptResponse::Pending => Action::None, StartupPromptResponse::UpdateAndRestart => { @@ -644,11 +666,52 @@ impl Updater { } } + /// True once after the user chose Save and Update: the app then saves its work. + #[must_use] + pub fn take_save_request(&mut self) -> bool { + self.prompt.as_mut().is_some_and(|p| std::mem::take(&mut p.save_wanted)) + } + + /// The save ended and the work is still not all saved: it failed, was cancelled, or more was + /// typed meanwhile. The prompt says why (`error`) or goes back to asking for the work to be + /// saved, and nothing installs by itself. An update that is already ready stays ready: the app + /// is asked to close once the work is saved only while that close is still pending, otherwise + /// Restart to Update asks again. A save that leaves nothing unsaved needs no call. + /// A call while the prompt isn't saving (after Dismiss, or after `can_save` fell) changes + /// nothing, so the app also reports a failed save the way it always does. + pub fn save_stopped(&mut self, error: Option) { + if !self.prompt.as_ref().is_some_and(|p| p.is_saving) { + return; + } + self.stop_saving(); + let note = if self.installed { self.installed_note() } else { save_first_note() }; + if let Some(prompt) = &mut self.prompt { + match error { + Some(error) => prompt.set_message(error), + None => prompt.set_note(note), + } + } + } + + /// The prompt no longer waits for a save. + fn stop_saving(&mut self) { + if let Some(prompt) = &mut self.prompt { + prompt.is_saving = false; + prompt.save_wanted = false; + } + } + fn request_install(&mut self, ctx: &egui::Context, can_start: bool) { if can_start { self.start_install(ctx); } else if let Some(prompt) = &mut self.prompt { - prompt.set_note(Note::new("Save or close your open work first; the update restarts the app.", &[])); + if prompt.offer_save { + prompt.is_saving = true; + prompt.save_wanted = true; + prompt.clear_message(); + } else { + prompt.set_note(save_first_note()); + } } } @@ -697,6 +760,11 @@ impl Updater { } } +/// The prompt's answer to Update and Restart while the app holds unsaved work. +fn save_first_note() -> Note { + Note::new("Save or close your open work first; the update restarts the app.", &[]) +} + impl Drop for Updater { /// The app is exiting: an installed update that is still waiting starts its helper, which /// waits for this process to exit before it installs. @@ -1185,6 +1253,248 @@ mod tests { assert_eq!(u.show(&ctx), Action::None); } + /// One frame of [`Updater::show_with_save`] on the screen the dialog tests use. + fn frame_saving(u: &mut Updater, ctx: &egui::Context, can_start: bool, can_save: bool, events: Vec) -> (Action, egui::FullOutput) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); + let mut action = Action::None; + let input = egui::RawInput { screen_rect: Some(screen), events, ..egui::RawInput::default() }; + let mut output = ctx.run_ui(input, |ui| action = u.show_with_save(ui.ctx(), can_start, can_save)); + output.textures_delta.clear(); + (action, output) + } + + /// Makes the open prompt a self-updating one: the test exe is not an install, so + /// [`StartupPrompt::new`] says it isn't. + fn self_updating(u: &mut Updater) { + if let Some(prompt) = &mut u.prompt { + prompt.is_self_updating = true; + } + } + + /// The real button, clicked with unsaved work the app can save. + fn click_save(u: &mut Updater, ctx: &egui::Context) { + self_updating(u); + frame_saving(u, ctx, false, true, Vec::new()); + let (_, output) = frame_saving(u, ctx, false, true, Vec::new()); + let at = crate::dialog::tests::text_pos(&output, "SAVE AND UPDATE").expect("SAVE AND UPDATE is painted"); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame_saving(u, ctx, false, true, vec![egui::Event::PointerMoved(at)]); + frame_saving(u, ctx, false, true, vec![button(true)]); + frame_saving(u, ctx, false, true, vec![button(false)]); + } + + /// Whether the open prompt shows the app saving. + fn saving(u: &Updater) -> bool { + u.prompt.as_ref().is_some_and(|p| p.is_saving) + } + + /// The open prompt's message, or nothing. + fn prompt_message(u: &Updater) -> String { + u.prompt.as_ref().and_then(StartupPrompt::message).unwrap_or_default() + } + + /// An updater whose install has finished and waits for the app to close. + fn installed(ctx: &egui::Context) -> Updater { + let mut u = updater(Ok(None)); + u.offer(newer()); + let (tx, rx) = channel(); + u.install = Some((rx, newer())); + assert!(tx.send(Ok(Restart::scheduled())).is_ok()); + u.tick(ctx); + u + } + + /// The whole promise: one click asks the app to save, and the install starts on its own once + /// nothing is left unsaved. The test exe is no install, so `start_install` ends in its note. + #[test] + fn save_and_update_saves_first_and_then_installs() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + assert!(u.take_save_request(), "the click asks the app to save"); + assert!(!u.take_save_request(), "once"); + assert!(saving(&u)); + assert!(u.install.is_none(), "nothing is scheduled over unsaved work"); + frame_saving(&mut u, &ctx, false, true, Vec::new()); + assert!(u.install.is_none() && saving(&u), "the save is still running"); + frame_saving(&mut u, &ctx, true, false, Vec::new()); + assert!(!saving(&u)); + assert!(u.install.is_some() || prompt_message(&u).starts_with("Cannot auto-update"), "{}", prompt_message(&u)); + } + + /// The hint from a click before the app could save doesn't stay beside the spinner. + #[test] + fn a_note_from_an_earlier_click_goes_when_the_save_starts() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + u.request_install(&ctx, false); + assert!(prompt_message(&u).starts_with("Save or close")); + click_save(&mut u, &ctx); + assert_eq!(prompt_message(&u), ""); + } + + /// A save that failed says why, and nothing installs when the work is saved some other way. + #[test] + fn a_failed_save_says_why_and_calls_the_install_off() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + u.save_stopped(Some("disk full".into())); + assert!(!saving(&u)); + assert_eq!(prompt_message(&u), "disk full"); + frame_saving(&mut u, &ctx, true, false, Vec::new()); + assert_eq!(prompt_message(&u), "disk full"); + assert!(u.install.is_none()); + } + + /// A save that ended with work still unsaved (more was typed, a lossy format) doesn't leave the + /// spinner up: the prompt goes back to the hint and the button can be clicked again. + #[test] + fn a_save_that_leaves_work_unsaved_goes_back_to_the_note() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + assert!(u.take_save_request()); + u.save_stopped(None); + assert!(!saving(&u)); + assert!(prompt_message(&u).starts_with("Save or close"), "{}", prompt_message(&u)); + let (_, output) = frame_saving(&mut u, &ctx, false, true, Vec::new()); + assert!(crate::dialog::tests::text_pos(&output, "SAVE AND UPDATE").is_some()); + } + + /// The app can no longer save its way out (an untitled document appeared): no endless spinner. + #[test] + fn work_that_can_no_longer_be_saved_stops_the_saving() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + frame_saving(&mut u, &ctx, false, false, Vec::new()); + assert!(!saving(&u)); + assert!(prompt_message(&u).starts_with("Save or close"), "{}", prompt_message(&u)); + } + + /// A report that arrives when the prompt isn't saving (after Dismiss) changes nothing. + #[test] + fn a_late_save_stopped_changes_nothing() { + let mut u = updater(Ok(None)); + u.offer(newer()); + u.save_stopped(Some("disk full".into())); + assert_eq!(prompt_message(&u), ""); + } + + /// Dismiss takes the wish to install with it: a later offer doesn't install without a click. + #[test] + fn dismissing_during_the_save_forgets_the_install() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frame_saving(&mut u, &ctx, false, true, vec![escape]); + assert!(!u.prompt_open()); + assert!(!u.take_save_request()); + u.offer(newer()); + self_updating(&mut u); + frame_saving(&mut u, &ctx, true, false, Vec::new()); + assert!(u.prompt.as_ref().is_some_and(|p| !p.is_installing)); + assert_eq!(prompt_message(&u), ""); + } + + /// A newer release offered during the save is a new question: it installs nothing by itself. + #[test] + fn a_new_offer_during_the_save_installs_nothing() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + click_save(&mut u, &ctx); + u.offer(newer()); + self_updating(&mut u); + frame_saving(&mut u, &ctx, true, false, Vec::new()); + assert!(u.prompt.as_ref().is_some_and(|p| !p.is_installing)); + assert_eq!(prompt_message(&u), ""); + assert!(!u.take_save_request()); + } + + /// The button only shows with unsaved work, in an app that can save it. `show_if` never offers it. + #[test] + fn the_button_needs_both_unsaved_work_and_an_app_that_can_save() { + let ctx = egui::Context::default(); + let mut u = updater(Ok(None)); + u.offer(newer()); + self_updating(&mut u); + let offered = |u: &Updater| u.prompt.as_ref().is_some_and(|p| p.offer_save); + frame_saving(&mut u, &ctx, false, true, Vec::new()); + assert!(offered(&u), "unsaved work the app can save"); + frame(&mut u, &ctx, false); + assert!(!offered(&u), "show_if"); + frame_saving(&mut u, &ctx, false, true, Vec::new()); + frame_saving(&mut u, &ctx, true, true, Vec::new()); + assert!(!offered(&u), "nothing to save"); + frame_saving(&mut u, &ctx, false, true, Vec::new()); + frame_saving(&mut u, &ctx, false, false, Vec::new()); + assert!(!offered(&u), "the app can't save it"); + } + + /// With the update already installed, the save leads to the close, once, and no second install. + #[test] + fn save_and_update_on_a_finished_install_closes_the_app_once() { + let ctx = egui::Context::default(); + let mut u = installed(&ctx); + click_save(&mut u, &ctx); + assert!(u.take_save_request()); + assert_eq!(frame_saving(&mut u, &ctx, false, true, Vec::new()).0, Action::None); + assert_eq!(frame_saving(&mut u, &ctx, true, false, Vec::new()).0, Action::Close); + assert!(!saving(&u), "a close the user cancels leaves no spinner"); + assert_eq!(frame_saving(&mut u, &ctx, true, false, Vec::new()).0, Action::None); + assert!(u.install.is_none()); + } + + /// A stopped save on a finished install keeps saying the update is ready. + #[test] + fn a_stopped_save_on_a_finished_install_keeps_its_note() { + let ctx = egui::Context::default(); + let mut u = installed(&ctx); + click_save(&mut u, &ctx); + u.save_stopped(None); + assert_eq!(prompt_message(&u), crate::translate::fill(READY_TEXT, &[("app", "PhotoCraft")])); + } + + /// A ready update whose close was canceled offers Save and Update while the app can save. + #[test] + fn a_ready_update_offers_save_and_update_over_restart_to_update() { + let ctx = egui::Context::default(); + let mut u = installed(&ctx); + assert_eq!(frame(&mut u, &ctx, true), Action::Close); + frame_saving(&mut u, &ctx, false, true, Vec::new()); + let (_, output) = frame_saving(&mut u, &ctx, false, true, Vec::new()); + assert!(crate::dialog::tests::text_pos(&output, "SAVE AND UPDATE").is_some()); + assert!(crate::dialog::tests::text_pos(&output, "RESTART TO UPDATE").is_none()); + let (_, output) = frame_saving(&mut u, &ctx, false, false, Vec::new()); + assert!(crate::dialog::tests::text_pos(&output, "RESTART TO UPDATE").is_some()); + } + + /// Save and Update after a canceled close asks the app to close once, in the frame the save ends. + #[test] + fn save_and_update_after_a_canceled_close_closes_once_the_work_is_saved() { + let ctx = egui::Context::default(); + let mut u = installed(&ctx); + assert_eq!(frame(&mut u, &ctx, true), Action::Close); + assert_eq!(frame(&mut u, &ctx, true), Action::None); + click_save(&mut u, &ctx); + assert!(u.take_save_request()); + assert_eq!(frame_saving(&mut u, &ctx, false, true, Vec::new()).0, Action::None); + assert_eq!(frame_saving(&mut u, &ctx, true, false, Vec::new()).0, Action::Close); + assert!(!saving(&u), "a close the user cancels leaves no spinner"); + assert_eq!(frame_saving(&mut u, &ctx, true, false, Vec::new()).0, Action::None); + assert!(u.install.is_none()); + } + /// A finished installation that still has to start its helper asks the app to close only /// when it may, and starts the helper only at the exit, once. #[test] diff --git a/crates/video/src/hevc/decode/filter.rs b/crates/video/src/hevc/decode/filter.rs index d5b94161d7..69f936bc15 100644 --- a/crates/video/src/hevc/decode/filter.rs +++ b/crates/video/src/hevc/decode/filter.rs @@ -522,10 +522,7 @@ fn sao_edge_ctb( return false; } } - if !pic.pps.loop_filter_across_tiles && pic.layout.tile_id[pic.layout.rs_to_ts[nrs] as usize] != pic.layout.tile_id[cur_ts as usize] { - return false; - } - true + pic.pps.loop_filter_across_tiles || pic.layout.tile_id[pic.layout.rs_to_ts[nrs] as usize] == pic.layout.tile_id[cur_ts as usize] }; // avail[dy][dx]: the CTB at (rx + dx - 1, ry + dy - 1) may be used. let (rx, ry) = (rs % pic.wctb, rs / pic.wctb); diff --git a/crates/web-host/Cargo.toml b/crates/web-host/Cargo.toml index 1f50f570ff..f3eabdbee2 100644 --- a/crates/web-host/Cargo.toml +++ b/crates/web-host/Cargo.toml @@ -14,6 +14,7 @@ web-sys = { version = "0.3", features = ["Blob", "CustomEvent", "CustomEventInit [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3" +web-sys = { version = "0.3", features = ["MessageEventInit"] } [lints] workspace = true diff --git a/crates/web-host/src/lib.rs b/crates/web-host/src/lib.rs index 0d6c0bb15e..89f88684bb 100644 --- a/crates/web-host/src/lib.rs +++ b/crates/web-host/src/lib.rs @@ -9,6 +9,7 @@ //! | `ready` | app → host | `version`, `appVersion?`, `file?` (`true`: it reads a `File`/`Blob` in slices) | //! | `host` | host → app | `version`, `handoff?` (`true`: the host routes hand-offs) | //! | `open` | host → app | `name`, and `bytes` or `file` + `size` | +//! | `attach-pdf` | host → app | `name`, `bytes`, `page` (from 1), `insertion` ([x,y,z]), `width`, `height` in drawing units | //! | `save` | app → host | `name`, `bytes`, `id?`, `saveAs?` | //! | `saved` | host → app | `id` | //! | `dirty` | app → host | `dirty` | @@ -81,6 +82,7 @@ pub enum Outgoing { pub enum Incoming { Host, Open, + AttachPdf, Saved, HandoffDone, } @@ -98,12 +100,13 @@ impl Outgoing { } impl Incoming { - pub const ALL: [Self; 4] = [Self::Host, Self::Open, Self::Saved, Self::HandoffDone]; + pub const ALL: [Self; 5] = [Self::Host, Self::Open, Self::AttachPdf, Self::Saved, Self::HandoffDone]; pub const fn kind(self) -> &'static str { match self { Self::Host => "host", Self::Open => "open", + Self::AttachPdf => "attach-pdf", Self::Saved => "saved", Self::HandoffDone => "handoff-done", } diff --git a/crates/web-host/src/web.rs b/crates/web-host/src/web.rs index bca9a9b1a7..642eca5fb3 100644 --- a/crates/web-host/src/web.rs +++ b/crates/web-host/src/web.rs @@ -40,6 +40,9 @@ pub enum Message { Host { version: String, handoff: bool }, /// Open a document as File › Open would. `name` is already cleaned ([`crate::file_name`]). Open { name: String, data: FileData }, + /// Attach one PDF page to the current drawing without opening another document. + /// Bytes stay a view until the app checks their length. Page numbers start at one. + AttachPdf { name: String, bytes: js_sys::Uint8Array, page: u32, insertion: [f64; 3], width: f64, height: f64 }, /// The save with this `id` is stored. Saved { id: String }, /// The host gave a handed-off file to the app that edits it. @@ -209,6 +212,31 @@ fn read(kind: Incoming, data: &JsValue) -> Option { let name = file_name(string(data, "name").as_deref(), "document"); Message::Open { name, data: file_data(data)? } } + Incoming::AttachPdf => { + let FileData::Bytes(bytes) = file_data(data)? else { return None }; + let page = get(data, "page").as_f64()?; + if !(page.is_finite() && page >= 1.0 && page <= f64::from(u32::MAX) && page.fract() == 0.0) { + return None; + } + let coords = get(data, "insertion").dyn_into::().ok()?; + if coords.length() != 3 { + return None; + } + let mut insertion = [0.0; 3]; + for (i, out) in insertion.iter_mut().enumerate() { + *out = coords.get(u32::try_from(i).ok()?).as_f64().filter(|v| v.is_finite())?; + } + let width = get(data, "width").as_f64().filter(|v| v.is_finite() && *v > 0.0)?; + let height = get(data, "height").as_f64().filter(|v| v.is_finite() && *v > 0.0)?; + Message::AttachPdf { + name: file_name(string(data, "name").as_deref(), "document.pdf"), + bytes, + page: page as u32, + insertion, + width, + height, + } + } Incoming::Saved => Message::Saved { id: string(data, "id")? }, Incoming::HandoffDone => { Message::HandoffDone { name: string(data, "name").unwrap_or_default(), app: string(data, "app").unwrap_or_default() } @@ -248,17 +276,91 @@ fn string(data: &JsValue, key: &str) -> Option { get(data, key).as_string() } -/// Node tests for the parsing of a host's objects: wrong shapes, missing fields, and sizes the -/// host states against the data it sends. No browser; run with `wasm-bindgen-test-runner`. +/// Browser tests for parsing and delivery of a host's objects, including origin/source checks. #[cfg(test)] mod tests { use super::*; use wasm_bindgen_test::wasm_bindgen_test; + wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + + #[wasm_bindgen_test] + fn test_attach_pdf_rejects_foreign_origin() { + let window = web_sys::window().unwrap(); + let origin = window.location().origin().unwrap(); + let host = Host { + app: "pdf-attach-test", + transport: Transport::Parent { window: window.clone(), parent: window.clone(), origin: origin.clone() }, + dirty: Cell::new(None), + }; + let received = Rc::new(Cell::new(0)); + let counter = received.clone(); + host.listen(move |_| counter.set(counter.get() + 1)); + let data = obj(&[ + ("type", "pdf-attach-test:attach-pdf".into()), + ("name", "page.pdf".into()), + ("bytes", buffer(3).into()), + ("page", 1.into()), + ("insertion", js_sys::Array::of3(&10.into(), &20.into(), &3.into()).into()), + ("width", 100.into()), + ("height", 80.into()), + ]); + let send = |origin: &str, source: Option<&web_sys::Window>| { + let init = web_sys::MessageEventInit::new(); + init.set_origin(origin); + init.set_source(source.map(|s| s.as_ref())); + init.set_data(&data); + let event = web_sys::MessageEvent::new_with_event_init_dict("message", &init).unwrap(); + window.dispatch_event(&event).unwrap(); + }; + send("https://foreign.example", Some(&window)); + assert_eq!(received.get(), 0, "a foreign origin changes nothing"); + send(&origin, None); + assert_eq!(received.get(), 0, "the expected origin with another source changes nothing"); + send(&origin, Some(&window)); + assert_eq!(received.get(), 1, "the same payload from the authorized parent is delivered"); + } + fn obj(fields: &[(&str, JsValue)]) -> JsValue { object(&[], fields).expect("an object").into() } + #[wasm_bindgen_test] + fn attach_pdf_checks_page_rectangle_and_bytes() { + let valid = || { + obj(&[ + ("name", "../sheet.pdf".into()), + ("bytes", buffer(3).into()), + ("page", 2.into()), + ("insertion", js_sys::Array::of3(&10.into(), &20.into(), &3.into()).into()), + ("width", 100.into()), + ("height", 80.into()), + ]) + }; + let Some(Message::AttachPdf { name, bytes, page, insertion, width, height }) = read(Incoming::AttachPdf, &valid()) else { + panic!("valid attachment must be delivered"); + }; + assert_eq!(name, "sheet.pdf"); + assert_eq!(bytes.length(), 3); + assert_eq!((page, insertion, width, height), (2, [10.0, 20.0, 3.0], 100.0, 80.0)); + for (key, value) in [ + ("bytes", JsValue::NULL), + ("page", 0.into()), + ("page", 1.5.into()), + ("page", f64::INFINITY.into()), + ("page", 4294967296.0.into()), + ("insertion", js_sys::Array::of2(&0.into(), &0.into()).into()), + ("insertion", js_sys::Array::of3(&0.into(), &f64::NAN.into(), &0.into()).into()), + ("width", 0.into()), + ("height", (-1).into()), + ("width", "100".into()), + ] { + let data = valid(); + js_sys::Reflect::set(&data, &key.into(), &value).unwrap(); + assert!(read(Incoming::AttachPdf, &data).is_none(), "invalid {key} must be dropped"); + } + } + fn buffer(len: u32) -> js_sys::ArrayBuffer { js_sys::ArrayBuffer::new(len) } diff --git a/crates/window/Cargo.toml b/crates/window/Cargo.toml index 2ccc0765b8..39efa5f1c1 100644 --- a/crates/window/Cargo.toml +++ b/crates/window/Cargo.toml @@ -11,9 +11,15 @@ repository.workspace = true # `decorate`: set the decision on an `egui::ViewportBuilder`. `title_bar`: an app-drawn strip as # the title bar (on macOS with AppKit's `movable` flag). `Viewports`: one immediate viewport per window. egui = ["dep:egui", "dep:objc2", "dep:objc2-app-kit"] +# `restore`: the window-restore store (`window.json` beside `config.toml`) and the pure `place`. No egui. +restore = ["dep:craft-atomic", "dep:craft-settings", "dep:serde", "dep:serde_json"] [dependencies] egui = { workspace = true, optional = true } +craft-atomic = { workspace = true, optional = true } +craft-settings = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } # Only Linux and the BSDs probe a Wayland compositor; everywhere else the frame is the OS's. [target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies] @@ -24,5 +30,8 @@ wayland-client = "0.31" objc2 = { version = "0.6.4", default-features = false, features = ["std"], optional = true } objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSResponder", "NSView", "NSWindow"], optional = true } +[dev-dependencies] +tempfile = "3" + [lints] workspace = true diff --git a/crates/window/README.md b/crates/window/README.md index 2816b9fe82..e9dc47fbb4 100644 --- a/crates/window/README.md +++ b/crates/window/README.md @@ -8,53 +8,65 @@ window per document. ## Why -egui apps either keep the desktop's window frame (titlebar, borders, window buttons) or turn it off -and draw their own. Across the suite this had drifted: - -- some apps always drew their own frame on Linux (so KDE's titlebar was replaced by the app's), -- some always kept the desktop's, -- some probed the compositor and only drew their own on GNOME. - -So two Craft apps open side by side on KDE could wear different titlebars. This crate makes the -decision in one place, matching each desktop. +egui apps either keep the desktop's window frame (title bar, borders, window buttons) or turn it +off and draw their own. This crate makes that decision in one place, so every Craft app wears the +same title bar on a given desktop. ## The rule -| Platform | Frame | -| --- | --- | -| macOS, Windows | desktop (the OS) | -| Linux/BSD on X11 | desktop (the window manager) | -| Linux/BSD on Wayland **with** `zxdg_decoration_manager_v1` (KDE, Sway, Hyprland, COSMIC) | desktop (the compositor) | -| Linux/BSD on Wayland **without** it (GNOME's Mutter) | the app | +The app's own bar is the title bar by default (`Frame::Integrated`). The user setting "Use system +title bar" (`TitleBarPref::System`) gives the frame to the OS, window manager or compositor +(`Frame::Native`). -When the app draws the frame, the decision carries the window-button `Layout` the desktop names -(GNOME's `button-layout`), so the app's header bar puts minimize/maximize/close where that desktop -puts them. This crate decides *whether* and *where*; drawing the buttons stays in each app, whose -title bars differ. +| Platform, desktop, backend | Default | With "Use system title bar" | +| --- | --- | --- | +| macOS | `Inset`: full-size content view, hidden title, traffic lights over the app's bar | `Native` | +| Windows | `Integrated(Windows)`: minimize, maximize, close at the right | `Native` | +| GNOME, Wayland or XWayland | `Integrated(Adwaita)`, in the order of `button-layout` | `Native` | +| KDE, Wayland or X11 | `Integrated(Breeze)`, in the order of KWin's `ButtonsOnLeft` and `ButtonsOnRight` | `Native` | +| COSMIC, Xfce, Cinnamon, MATE, other floating desktops | `Integrated(Generic)` in the order of `gtk-decoration-layout`; Adwaita or Breeze when the GTK theme is one of those | `Native` | +| Tiling compositors and window managers (Sway, Hyprland, i3, niri, river, from `XDG_CURRENT_DESKTOP`) | `Native` | `Native` | +| Wayland without server-side decorations, not GNOME | `Integrated(Generic)` | `Native` | +| Web | `Native`; no frame code runs | `Native` | + +The backend is the one the app opens its window on: an app that forces XWayland on a Wayland +session passes `Backend::X11`. The Wayland registry is probed (500 ms at most) only for +`Backend::Wayland`. + +`policy::decide` is pure and takes the OS, backend, desktop, setting and override. `decide_for` +reads the platform once and calls it. ### Override -`_TITLEBAR` forces the choice. With the default prefix `CRAFT`: `CRAFT_TITLEBAR=app` forces -the app frame, `=system` (or `=desktop`) forces the desktop frame. Apps pass their own prefix -(`Prefix::new("PDFCRAFT")` → `PDFCRAFT_TITLEBAR`) so each keeps its own variable name. +`_TITLEBAR` wins over the setting. With the default prefix `CRAFT`: `CRAFT_TITLEBAR=app` +forces the app's bar (also on tiling compositors), `=system` or `=desktop` forces the native frame. +Apps pass their own prefix (`Prefix::new("PDFCRAFT")` reads `PDFCRAFT_TITLEBAR`). +When `_TITLEBAR` is unset, `CRAFT_TITLEBAR` applies, so one variable covers every app. `Decision::overridden` reports `Some(true)` or `Some(false)` when the variable decided. ## Use ```rust,ignore -use craft_window::{Choice, Prefix, decorate}; +use craft_window::Prefix; +use craft_window::policy::{Backend, Frame, TitleBarPref, apply, decide_for}; // Once at startup, before the window is created: -let choice = Choice::probe(Prefix::new("PHOTOCRAFT")); -let viewport = decorate(egui::ViewportBuilder::default().with_title("PhotoCraft"), choice.frame()); +let pref = if settings.system_title_bar { TitleBarPref::System } else { TitleBarPref::Integrated }; +// Backend::from_env() is what winit opens; an app that forces XWayland passes Backend::X11. +let decision = decide_for(Prefix::new("PHOTOCRAFT"), Backend::from_env(), pref); +let viewport = apply(egui::ViewportBuilder::default().with_title("PhotoCraft"), &decision.frame); -// If the app draws the frame, lay the header-bar buttons out by the desktop's order: -if let Some(layout) = choice.frame().layout() { - // layout.left / layout.right -> draw Minimize/Maximize/Close there +if let Frame::Integrated(captions) = &decision.frame { + // captions.family picks the button look; captions.layout.left / .right place the buttons. } ``` -An app that offers a "System title bar" preference checks `choice.overridden()` and its own setting, -and can override the probe by setting the frame to `Frame::Desktop`. +This crate decides *whether* and *where*; drawing the buttons stays in each app. + +## Older API + +`Choice::probe`, the root `Frame::{Desktop, App}` and `decorate` follow the earlier two-way rule +(the desktop draws the frame, except on Wayland without server-side decorations). They still work; +`policy` supersedes them. The `egui` feature adds [`decorate`], the [`title_bar`](#the-apps-own-title-bar) module and `Viewports`. Without it, the crate is pure decision and bookkeeping logic with no egui dependency. @@ -143,6 +155,24 @@ for event in viewports.show( Immediate viewports repaint every window when one repaints, so cache expensive per-window drawing. +## Window restore + +Feature `restore` (no egui): `craft_window::restore`. + +- `place(saved, monitors, home, &Defaults) -> Placement` is pure. First launch: the default size fitted + to the home monitor, maximized when it does not fit. Saved sizes are points at interface zoom 1. + A window with less than 64×64 pt of its top strip on any one monitor moves to its saved monitor, + else the nearest, else the primary; sizes clamp to the monitor's usable area and `min`. Positions + are physical pixels (negative left of or above the primary). `Defaults::no_position` (Wayland) + neither reads nor returns a position. Full screen returns only with `Defaults::restore_fullscreen`. +- `Store::open(app_id)` keeps `window.json` beside `config.toml` (same folder rules as + `craft-settings`), `Store::in_memory()` keeps nothing. `get`, `set`, `save`. + Format: `{ "schema_version": 1, "windows": { "main": Placement, "": Placement } }`. + Writes are atomic and private; a damaged file is moved aside as `window.broken-.json`; a newer + `schema_version` is read-only; unknown keys are written back unchanged. +- `restore::legacy` reads eframe's `"window"` entry of `app.ron` (without a RON crate) and has small + JSON helpers for an app's own old format. + ## Notes - The Wayland probe opens a short-lived connection and reads the global registry once, on its own diff --git a/crates/window/src/desktop.rs b/crates/window/src/desktop.rs new file mode 100644 index 0000000000..2ec0fc4c7a --- /dev/null +++ b/crates/window/src/desktop.rs @@ -0,0 +1,130 @@ +//! Which desktop and backend the window opens on, read from the environment and, on Wayland, the +//! compositor's registry. + +/// The windowing backend the app opens its window on. An app that forces XWayland on a Wayland +/// session passes [`Backend::X11`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Backend { + Wayland, + X11, +} + +/// The kind of desktop, as far as the frame decision cares. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DesktopKind { + Gnome, + Kde, + /// A tiling compositor or window manager (Sway, Hyprland, i3, niri, river, ...). + Tiling, + /// Any other desktop: COSMIC, Xfce, Cinnamon, MATE, an unknown one. Budgie counts as GNOME. + Other, +} + +/// What the running desktop is and offers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Desktop { + pub kind: DesktopKind, + /// Whether the compositor offers server-side decorations (`zxdg_decoration_manager_v1`). + /// `None` when not probed (X11, or the probe failed). + pub ssd: Option, + /// The GTK theme name, when `GTK_THEME` or GTK's `settings.ini` names one. + pub gtk_theme: Option, + /// The icon theme: KDE's (`kdeglobals`) or GTK's setting, else `breeze` on KDE and `Adwaita` + /// elsewhere. `None` off Linux and the BSDs. + pub icon_theme: Option, +} + +impl Backend { + /// The backend winit opens by default: Wayland when `WAYLAND_DISPLAY` or `WAYLAND_SOCKET` is + /// set, else X11. An app that forces X11 (XWayland) passes [`Backend::X11`] instead. + pub fn from_env() -> Backend { + let set = |k| std::env::var_os(k).is_some_and(|v| !v.is_empty()); + if set("WAYLAND_DISPLAY") || set("WAYLAND_SOCKET") { Backend::Wayland } else { Backend::X11 } + } +} + +impl Desktop { + /// Read the desktop. Reads environment variables and small config files; the Wayland registry + /// is probed (500 ms at most) only when `backend` is [`Backend::Wayland`]. + pub fn detect(backend: Backend) -> Desktop { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] + { + let var = |k: &str| std::env::var(k).ok(); + let ssd = if backend == Backend::Wayland { crate::platform::wayland_offers_ssd() } else { None }; + let kind = kind_from_env(&var); + Desktop { kind, ssd, gtk_theme: crate::layout::read_gtk_theme(&var), icon_theme: Some(crate::layout::read_icon_theme(kind, &var)) } + } + #[cfg(not(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd")))] + { + let _ = backend; + Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None } + } + } +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// Compositors and window managers that tile, matched against the `XDG_CURRENT_DESKTOP` entries. +const TILING: &[&str] = &["sway", "hyprland", "i3", "niri", "river", "bspwm", "awesome", "dwl", "qtile", "herbstluftwm", "leftwm", "xmonad", "dwm"]; + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// The desktop kind from the first of its variables that is set (`XDG_CURRENT_DESKTOP`, +/// `XDG_SESSION_DESKTOP`, `DESKTOP_SESSION`). `ubuntu:GNOME` and `Budgie:GNOME` count as GNOME. +pub(crate) fn kind_from_env(var: &dyn Fn(&str) -> Option) -> DesktopKind { + // A compositor's own socket variable names it even when the desktop variables are missing. + if ["SWAYSOCK", "I3SOCK", "HYPRLAND_INSTANCE_SIGNATURE", "NIRI_SOCKET"].iter().any(|k| var(k).is_some_and(|v| !v.is_empty())) { + return DesktopKind::Tiling; + } + for key in ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"] { + let Some(v) = var(key).map(|v| v.to_ascii_lowercase()).filter(|v| !v.trim().is_empty()) else { continue }; + if v.split(':').map(str::trim).any(|entry| TILING.contains(&entry)) { + return DesktopKind::Tiling; + } + return if v.contains("gnome") { + DesktopKind::Gnome + } else if v.contains("kde") || v.contains("plasma") { + DesktopKind::Kde + } else { + DesktopKind::Other + }; + } + if var("KDE_FULL_SESSION").is_some() { + DesktopKind::Kde + } else if var("GNOME_DESKTOP_SESSION_ID").is_some() { + DesktopKind::Gnome + } else { + DesktopKind::Other + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option + use<> { + let pairs: Vec<(String, String)> = pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + move |k| pairs.iter().find(|(key, _)| key == k).map(|(_, v)| v.clone()) + } + + #[test] + fn the_desktop_comes_from_the_first_variable_set() { + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")])), DesktopKind::Gnome); + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "KDE")])), DesktopKind::Kde); + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "X-Cinnamon"), ("KDE_FULL_SESSION", "true")])), DesktopKind::Other); + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", " "), ("DESKTOP_SESSION", "plasma")])), DesktopKind::Kde); + assert_eq!(kind_from_env(&env(&[("KDE_FULL_SESSION", "true")])), DesktopKind::Kde); + assert_eq!(kind_from_env(&env(&[("GNOME_DESKTOP_SESSION_ID", "x")])), DesktopKind::Gnome); + assert_eq!(kind_from_env(&env(&[])), DesktopKind::Other); + } + + #[test] + fn tiling_compositors_are_recognised() { + for name in ["sway", "Hyprland", "i3", "niri", "river", "bspwm"] { + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", name)])), DesktopKind::Tiling, "{name}"); + } + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "i3:GNOME-Flashback")])), DesktopKind::Tiling); + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "COSMIC")])), DesktopKind::Other); + assert_eq!(kind_from_env(&env(&[("SWAYSOCK", "/run/sway.sock")])), DesktopKind::Tiling); + assert_eq!(kind_from_env(&env(&[("NIRI_SOCKET", "/run/niri")])), DesktopKind::Tiling); + assert_eq!(kind_from_env(&env(&[("XDG_CURRENT_DESKTOP", "Budgie:GNOME")])), DesktopKind::Gnome); + } +} diff --git a/crates/window/src/layout.rs b/crates/window/src/layout.rs new file mode 100644 index 0000000000..1c62a53658 --- /dev/null +++ b/crates/window/src/layout.rs @@ -0,0 +1,234 @@ +//! Where the desktop puts the window buttons, and which look they get. The parsers are pure +//! functions over strings; the file reads at the bottom are thin. + +use crate::{Layout, policy::CaptionFamily}; + +use crate::desktop::DesktopKind; + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// The value of `key` in `[section]` of an INI-style file (GTK's `settings.ini`, KDE's `kwinrc`). +pub(crate) fn ini_value(text: &str, section: &str, key: &str) -> Option { + let mut inside = false; + for line in text.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + inside = name == section; + } else if inside + && let Some((k, v)) = line.split_once('=') + && k.trim() == key + { + return Some(v.trim().to_string()); + } + } + None +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// KWin's button order (`[org.kde.kdecoration2]` `ButtonsOnLeft` / `ButtonsOnRight`, one letter a +/// button: `I` minimize, `A` maximize, `X` close) as a GTK layout string. Missing keys keep KWin's +/// defaults: the window menu on the left, minimize, maximize and close on the right. +pub(crate) fn kwin_layout(kwinrc: &str) -> String { + let side = |key: &str, default: &str| { + let letters = ini_value(kwinrc, "org.kde.kdecoration2", key).unwrap_or_else(|| default.to_string()); + letters + .chars() + .filter_map(|c| match c { + 'I' => Some("minimize"), + 'A' => Some("maximize"), + 'X' => Some("close"), + _ => None, + }) + .collect::>() + .join(",") + }; + format!("{}:{}", side("ButtonsOnLeft", "MS"), side("ButtonsOnRight", "HIAX")) +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// The `gtk-decoration-layout` and `gtk-theme-name` of a GTK 3 `settings.ini`. +pub(crate) fn gtk_settings(settings_ini: &str) -> (Option, Option) { + (ini_value(settings_ini, "Settings", "gtk-decoration-layout"), ini_value(settings_ini, "Settings", "gtk-theme-name")) +} + +/// The caption look. GNOME's apps are libadwaita's whatever the GTK theme, and KWin draws Breeze; +/// elsewhere the GTK theme says (Adwaita, adw-gtk3, Yaru, Breeze), and any other theme gets the +/// plain buttons. +pub(crate) fn family(kind: DesktopKind, gtk_theme: Option<&str>) -> CaptionFamily { + match kind { + DesktopKind::Gnome => CaptionFamily::Adwaita, + DesktopKind::Kde => CaptionFamily::Breeze, + DesktopKind::Tiling | DesktopKind::Other => family_from_gtk_theme(gtk_theme), + } +} + +/// The family a GTK theme name stands for, else [`CaptionFamily::Generic`]. +pub(crate) fn family_from_gtk_theme(gtk_theme: Option<&str>) -> CaptionFamily { + let theme = gtk_theme.unwrap_or_default().trim().to_ascii_lowercase(); + if ["adwaita", "adw-gtk3", "yaru"].iter().any(|p| theme.starts_with(p)) { + CaptionFamily::Adwaita + } else if theme.starts_with("breeze") { + CaptionFamily::Breeze + } else { + CaptionFamily::Generic + } +} + +/// What a desktop that names no layout gets: GNOME's default shows Close only, GTK's all three. +pub(crate) fn default_layout(kind: DesktopKind) -> Layout { + if kind == DesktopKind::Gnome { Layout::parse("appmenu:close") } else { Layout::default() } +} + +/// A parsed layout, or the default when the text names no usable button. +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +fn parse_or_default(text: Option<&str>, kind: DesktopKind) -> Layout { + text.map(Layout::parse).filter(Layout::is_usable).unwrap_or_else(|| default_layout(kind)) +} + +/// The layout `kind` uses, read from the desktop's files (`kwinrc` on KDE, GTK's `settings.ini` +/// elsewhere). GNOME's comes from `gsettings`, then GTK's `settings.ini`, then Close only. +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] +pub(crate) fn read_layout(kind: DesktopKind, var: &dyn Fn(&str) -> Option) -> Layout { + match kind { + DesktopKind::Gnome => { + let from_gsettings = crate::platform::gsettings_button_layout().map(|v| Layout::parse(&v)).filter(Layout::is_usable); + from_gsettings.unwrap_or_else(|| { + let ini = read_config(var, "gtk-3.0/settings.ini").unwrap_or_default(); + parse_or_default(gtk_settings(&ini).0.as_deref(), kind) + }) + } + DesktopKind::Kde => { + let rc = read_config(var, "kwinrc").unwrap_or_default(); + parse_or_default(Some(&kwin_layout(&rc)), kind) + } + DesktopKind::Tiling | DesktopKind::Other => { + let ini = read_config(var, "gtk-3.0/settings.ini").unwrap_or_default(); + parse_or_default(gtk_settings(&ini).0.as_deref(), kind) + } + } +} + +/// The GTK theme name from GTK 3's `settings.ini`. +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] +pub(crate) fn read_gtk_theme(var: &dyn Fn(&str) -> Option) -> Option { + let from_env = var("GTK_THEME").map(|t| t.split(':').next().unwrap_or_default().to_string()).filter(|t| !t.is_empty()); + from_env.or_else(|| read_config(var, "gtk-3.0/settings.ini").and_then(|ini| gtk_settings(&ini).1)) +} + +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] +/// The icon theme name for `kind`'s own setting (`kdeglobals` `[Icons] Theme` on KDE, GTK's +/// `gtk-icon-theme-name` elsewhere), else the desktop's default theme. +pub(crate) fn icon_theme(kind: DesktopKind, kdeglobals: &str, settings_ini: &str) -> String { + let found = + if kind == DesktopKind::Kde { ini_value(kdeglobals, "Icons", "Theme") } else { ini_value(settings_ini, "Settings", "gtk-icon-theme-name") }; + found.filter(|t| !t.is_empty()).unwrap_or_else(|| if kind == DesktopKind::Kde { "breeze" } else { "Adwaita" }.to_string()) +} + +/// [`icon_theme`] from the user's config files. +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] +pub(crate) fn read_icon_theme(kind: DesktopKind, var: &dyn Fn(&str) -> Option) -> String { + let kdeglobals = if kind == DesktopKind::Kde { read_config(var, "kdeglobals").unwrap_or_default() } else { String::new() }; + let ini = read_config(var, "gtk-3.0/settings.ini").unwrap_or_default(); + icon_theme(kind, &kdeglobals, &ini) +} + +/// A small file under the user's config directory (`XDG_CONFIG_HOME`, else `~/.config`). +#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] +fn read_config(var: &dyn Fn(&str) -> Option, relative: &str) -> Option { + use std::io::Read; + let config = var("XDG_CONFIG_HOME") + .filter(|d| std::path::Path::new(d).is_absolute()) + .map(std::path::PathBuf::from) + .or_else(|| var("HOME").map(|h| std::path::Path::new(&h).join(".config")))?; + let mut bytes = Vec::new(); + // Config files are small; the cap keeps a stray huge file from stalling startup. + std::fs::File::open(config.join(relative)).ok()?.take(1 << 20).read_to_end(&mut bytes).ok()?; + Some(String::from_utf8_lossy(&bytes).into_owned()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Button::{Close, Maximize, Minimize}; + + #[test] + fn the_family_follows_the_desktop_then_the_gtk_theme() { + assert_eq!(family(DesktopKind::Gnome, Some("Arc")), CaptionFamily::Adwaita); + assert_eq!(family(DesktopKind::Kde, None), CaptionFamily::Breeze); + assert_eq!(family(DesktopKind::Other, Some("adw-gtk3-dark")), CaptionFamily::Adwaita); + assert_eq!(family(DesktopKind::Other, Some("Yaru-blue")), CaptionFamily::Adwaita); + assert_eq!(family(DesktopKind::Other, Some("Breeze-Dark")), CaptionFamily::Breeze); + assert_eq!(family(DesktopKind::Other, Some("Mint-Y")), CaptionFamily::Generic); + assert_eq!(family(DesktopKind::Other, None), CaptionFamily::Generic); + } + + #[test] + fn kwin_button_letters_become_a_gtk_layout() { + assert_eq!(kwin_layout(""), ":minimize,maximize,close", "KWin's defaults"); + let rc = "[Desktops]\nButtonsOnLeft=X\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\nlibrary=org.kde.breeze\n"; + assert_eq!(kwin_layout(rc), "close,minimize,maximize:"); + assert_eq!(ini_value(rc, "org.kde.kdecoration2", "library").as_deref(), Some("org.kde.breeze")); + assert_eq!(ini_value(rc, "nope", "library"), None); + // Garbage is just no buttons on that side, never a panic. + assert_eq!(kwin_layout("[org.kde.kdecoration2]\nButtonsOnRight=\u{ff}\u{20ac}=X\n"), ":close"); + } + + #[test] + fn the_icon_theme_comes_from_the_setting_or_the_desktop_default() { + let globals = "[Icons]\nTheme=breeze-dark\n"; + let ini = "[Settings]\ngtk-icon-theme-name=Papirus\n"; + assert_eq!(icon_theme(DesktopKind::Kde, globals, ini), "breeze-dark"); + assert_eq!(icon_theme(DesktopKind::Other, globals, ini), "Papirus"); + assert_eq!(icon_theme(DesktopKind::Gnome, "", ""), "Adwaita"); + assert_eq!(icon_theme(DesktopKind::Kde, "", ini), "breeze"); + } + + #[test] + fn kwin_order_parses_into_a_layout() { + let rc = "[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n"; + let layout = Layout::parse(&kwin_layout(rc)); + assert_eq!(layout.left, vec![Close, Minimize, Maximize]); + assert!(layout.right.is_empty()); + } + + #[test] + fn gtk_settings_give_the_layout_and_theme() { + let ini = "[Settings]\ngtk-theme-name=Yaru\ngtk-decoration-layout=close,maximize:\n"; + assert_eq!(gtk_settings(ini), (Some("close,maximize:".into()), Some("Yaru".into()))); + assert_eq!(gtk_settings(""), (None, None)); + let layout = Layout::parse("close,maximize:"); + assert_eq!((layout.left, layout.right), (vec![Close, Maximize], vec![])); + } + + #[test] + fn missing_or_unusable_layouts_fall_back_to_the_desktops_default() { + assert_eq!(parse_or_default(None, DesktopKind::Gnome).right, vec![Close], "GNOME's default shows Close only"); + assert_eq!(parse_or_default(Some("appmenu:spacer"), DesktopKind::Other).right, vec![Minimize, Maximize, Close]); + assert_eq!(parse_or_default(Some("close:"), DesktopKind::Other).left, vec![Close]); + } + + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] + #[test] + fn settings_files_are_read_from_the_config_dir() { + let dir = std::env::temp_dir().join(format!("craft-window-layout-{}", std::process::id())); + std::fs::create_dir_all(dir.join("gtk-3.0")).unwrap_or_default(); + std::fs::write(dir.join("gtk-3.0/settings.ini"), "[Settings]\ngtk-theme-name=Yaru\ngtk-decoration-layout=close,maximize:\n") + .unwrap_or_default(); + std::fs::write(dir.join("kwinrc"), "[org.kde.kdecoration2]\nButtonsOnRight=AX\n").unwrap_or_default(); + let path = dir.to_string_lossy().into_owned(); + let var = move |k: &str| (k == "XDG_CONFIG_HOME").then(|| path.clone()); + assert_eq!(read_gtk_theme(&var).as_deref(), Some("Yaru")); + std::fs::write(dir.join("kdeglobals"), "[Icons]\nTheme=breeze-dark\n").unwrap_or_default(); + assert_eq!(read_icon_theme(DesktopKind::Kde, &var), "breeze-dark"); + let path2 = dir.to_string_lossy().into_owned(); + let with_env = move |k: &str| match k { + "XDG_CONFIG_HOME" => Some(path2.clone()), + "GTK_THEME" => Some("Breeze:dark".to_string()), + _ => None, + }; + assert_eq!(read_gtk_theme(&with_env).as_deref(), Some("Breeze"), "GTK_THEME wins over settings.ini"); + assert_eq!(read_layout(DesktopKind::Other, &var).left, vec![Close, Maximize]); + assert_eq!(read_layout(DesktopKind::Kde, &var).right, vec![Maximize, Close]); + // A relative XDG_CONFIG_HOME is ignored, as the XDG spec says; with no HOME nothing is found. + assert_eq!(read_gtk_theme(&|k: &str| (k == "XDG_CONFIG_HOME").then(|| "rel".to_string())), None); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/window/src/lib.rs b/crates/window/src/lib.rs index f85c256f53..94063f9bb9 100644 --- a/crates/window/src/lib.rs +++ b/crates/window/src/lib.rs @@ -10,7 +10,11 @@ //! compositor — so on KDE, say, one app wore KWin's title bar while another wore its own. This //! crate makes the decision one place. //! -//! The rule, by platform: +//! This page describes the first-generation rule ([`Choice::probe`], [`Frame`], [`decorate`]), +//! which stays for apps that have not moved. The current rule is in [`policy`]: the app's own bar +//! is the title bar by default, and the user setting "Use system title bar" turns that off. +//! +//! The rule of the first-generation API, by platform: //! //! - **macOS and Windows:** the OS always draws the frame ([`Frame::Desktop`]). (An app that insets //! its content under the traffic lights, or draws its own caption buttons on Windows, still asks @@ -127,15 +131,26 @@ //! } //! } //! ``` +//! +//! # Window restore +//! +//! The `restore` feature (no egui) adds [`restore`]: where a window opens, from the last session's +//! geometry and the connected monitors, and the `window.json` store beside `config.toml`. +mod desktop; +mod layout; mod list; mod menu; mod place; +pub mod policy; #[cfg(feature = "egui")] pub mod title_bar; #[cfg(feature = "egui")] mod viewports; +#[cfg(feature = "restore")] +pub mod restore; + pub use list::{Closed, WindowId, WindowList}; pub use menu::{Document, MenuEntry, WindowMenu}; pub use place::{CASCADE_STEP, Rect, cascade, monitor_of}; @@ -168,7 +183,7 @@ impl Prefix { } } -/// Who draws the window frame. +/// Who draws the window frame. Superseded by [`policy::Frame`]; kept for apps that have not moved. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Frame { /// The desktop draws it: the OS on macOS and Windows, the window manager on X11, the @@ -196,7 +211,7 @@ impl Frame { } /// How the frame was decided, so an app can log it or offer a "System title bar" preference that -/// knows the current state. +/// knows the current state. Superseded by [`policy::Decision`] and [`policy::decide_for`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Choice { frame: Frame, @@ -311,10 +326,15 @@ impl Layout { Self { left, right } } + /// The layout with the two sides swapped, for right-to-left UIs. + pub fn mirrored(&self) -> Self { + Self { left: self.right.clone(), right: self.left.clone() } + } + /// Whether the layout has at least one button, so the window can be closed by mouse. A layout /// with none (a desktop that named only buttons this crate skips) falls back to the default. #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] - fn is_usable(&self) -> bool { + pub(crate) fn is_usable(&self) -> bool { !self.left.is_empty() || !self.right.is_empty() } } @@ -345,7 +365,7 @@ fn app_draws_frame() -> bool { } } -/// Apply a [`Frame`] to an [`egui::ViewportBuilder`]: decorations on for the desktop frame, off for +/// Apply a [`Frame`] to an [`egui::ViewportBuilder`] (superseded by [`policy::apply`]): decorations on for the desktop frame, off for /// the app frame. Call before the window is created. The app still draws its header bar and, for /// [`Frame::App`], lays its window buttons out by [`Frame::layout`]. #[cfg(feature = "egui")] @@ -377,6 +397,12 @@ mod platform { bounded(registry_leaves_frame_to_app).flatten().unwrap_or(false) } + /// Whether the Wayland compositor offers server-side decorations: `None` when there is no + /// answer (no compositor, an inherited socket, a stalled registry), same deadline as above. + pub(super) fn wayland_offers_ssd() -> Option { + bounded(registry_leaves_frame_to_app).flatten().map(|leaves| !leaves) + } + /// Run `f` on a short-lived worker thread with a 500 ms deadline, so a stalled dependency can't /// block window startup. `None` when the thread can't be spawned or `f` doesn't finish in time; /// otherwise `f`'s return value. For a child process, prefer [`gsettings_button_layout`], which @@ -518,6 +544,12 @@ mod tests { assert!(layout.right.is_empty()); } + #[test] + fn mirrored_swaps_the_sides() { + let layout = Layout::parse("close:minimize,maximize").mirrored(); + assert_eq!((layout.left, layout.right), (vec![Button::Minimize, Button::Maximize], vec![Button::Close])); + } + #[test] fn a_layout_naming_no_known_button_is_not_usable() { assert!(!Layout::parse("appmenu:spacer").is_usable()); diff --git a/crates/window/src/policy.rs b/crates/window/src/policy.rs new file mode 100644 index 0000000000..8e3544841c --- /dev/null +++ b/crates/window/src/policy.rs @@ -0,0 +1,345 @@ +//! The frame policy: who draws the title bar, decided from the OS, desktop, backend, the user's +//! "Use system title bar" setting and the `_TITLEBAR` override. +//! +//! The app's own bar is the title bar by default ([`Frame::Integrated`]); the setting turns that +//! off ([`Frame::Native`]). +//! +//! | Platform, desktop, backend | Default | With "Use system title bar" | +//! |---|---|---| +//! | macOS | `Inset` | `Native` | +//! | Windows | `Integrated(Windows)` | `Native` | +//! | GNOME, Wayland or XWayland | `Integrated(Adwaita)`, `button-layout` order | `Native` | +//! | KDE, Wayland or X11 | `Integrated(Breeze)`, KWin's order | `Native` | +//! | COSMIC, Xfce, Cinnamon, MATE, other floating desktops | `Integrated(Generic)`, or Adwaita or Breeze when the GTK theme is one of those | `Native` | +//! | Tiling compositors and window managers | `Native` | `Native` | +//! | Wayland without server-side decorations, not GNOME | `Integrated(Generic)` | `Native` | +//! | Web | `Native` (no frame code runs) | `Native` | +//! +//! ```ignore +//! let d = craft_window::policy::decide_for(Prefix::default(), Backend::Wayland, TitleBarPref::Integrated); +//! let viewport = craft_window::policy::apply(egui::ViewportBuilder::default(), &d.frame); +//! ``` + +pub use crate::desktop::{Backend, Desktop, DesktopKind}; +use crate::{Layout, Prefix, layout}; + +/// Whether KDE, COSMIC, Xfce, Cinnamon, MATE and X11 window managers, which draw their own frame, +/// get the app's bar by default. Set to `false` for [`Frame::Native`] on those desktops instead; +/// nothing else changes. +const INTEGRATED_ON_SSD_DESKTOPS: bool = true; + +/// The user setting "Use system title bar". +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TitleBarPref { + /// The app's bar is the title bar. + #[default] + Integrated, + /// The OS, window manager or compositor draws it. + System, +} + +/// The operating system family. Linux stands for Linux and the BSDs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Os { + Mac, + Windows, + Linux, + Web, +} + +impl Os { + /// The OS this build runs on. + pub const fn current() -> Os { + if cfg!(target_os = "macos") { + Os::Mac + } else if cfg!(target_os = "windows") { + Os::Windows + } else if cfg!(target_arch = "wasm32") { + Os::Web + } else { + Os::Linux + } + } +} + +/// The look of the caption buttons. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CaptionFamily { + Windows, + Adwaita, + Breeze, + Generic, +} + +impl CaptionFamily { + /// A family by name (`windows`, `adwaita`, `breeze`, `generic`), case-insensitive. + pub fn parse(name: &str) -> Option { + match name.trim().to_ascii_lowercase().as_str() { + "windows" => Some(Self::Windows), + "adwaita" => Some(Self::Adwaita), + "breeze" => Some(Self::Breeze), + "generic" => Some(Self::Generic), + _ => None, + } + } +} + +/// Caption buttons the app draws: their look and which end of the bar they sit at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Captions { + pub family: CaptionFamily, + pub layout: Layout, +} + +/// Where macOS puts the traffic lights over the app's bar, in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MacInset { + /// Width reserved at the leading edge for the lights. + pub leading: f32, + /// Distance from the window's top to the lights' vertical centre. + pub centre_from_top: f32, +} + +impl Default for MacInset { + /// The standard lights' geometry. + fn default() -> Self { + Self { leading: 78.0, centre_from_top: 14.0 } + } +} + +/// Who draws the title bar. +#[derive(Clone, Debug, PartialEq)] +pub enum Frame { + /// The OS, window manager or compositor draws it; the app's strip sits below it. + Native, + /// macOS: full-size content view and hidden title; the traffic lights sit over the app's bar. + Inset(MacInset), + /// Decorations are off; the app's bar is the title bar, with these caption buttons. + Integrated(Captions), +} + +/// The decided frame and how it was decided. +#[derive(Clone, Debug, PartialEq)] +pub struct Decision { + pub frame: Frame, + /// `Some(true)` when `_TITLEBAR` forced the app's bar, `Some(false)` when it forced the + /// system's, `None` when the platform and setting decided. + pub overridden: Option, + /// The desktop the decision was made for, so an app can hide the "Use system title bar" row + /// where it changes nothing (tiling compositors, web) without probing again. + pub desktop: Desktop, +} + +/// The decision, pure. `env` is the value of `_TITLEBAR` (`app`, `system` or `desktop`); +/// it wins over `pref`. Caption layouts are each family's default; [`decide_for`] fills in the +/// desktop's own. +pub fn decide(os: Os, backend: Backend, desktop: &Desktop, pref: TitleBarPref, env: Option<&str>) -> Decision { + decide_with(os, backend, desktop, pref, env, &layout::default_layout) +} + +/// `layout` supplies the caption layout for a desktop kind; it is called only when the frame comes +/// out integrated. +fn decide_with( + os: Os, + backend: Backend, + desktop: &Desktop, + pref: TitleBarPref, + env: Option<&str>, + layout: &dyn Fn(DesktopKind) -> Layout, +) -> Decision { + let overridden = crate::parse_override(env); + let integrated = match (overridden, pref) { + (Some(app), _) => app, + (None, pref) => pref == TitleBarPref::Integrated, + }; + let frame = + if integrated { integrated_frame(os, backend, desktop, overridden.is_some(), INTEGRATED_ON_SSD_DESKTOPS, layout) } else { Frame::Native }; + Decision { frame, overridden, desktop: desktop.clone() } +} + +/// The frame when the app's bar is wanted. `forced` is set when the override asked for it, which +/// also applies on tiling compositors. +/// `integrated_on_ssd` says whether desktops that draw their own frame get the app's bar. +fn integrated_frame( + os: Os, + backend: Backend, + desktop: &Desktop, + forced: bool, + integrated_on_ssd: bool, + layout: &dyn Fn(DesktopKind) -> Layout, +) -> Frame { + let captions = |family: CaptionFamily| { + let kind = if family == CaptionFamily::Windows { DesktopKind::Other } else { desktop.kind }; + Frame::Integrated(Captions { family, layout: layout(kind) }) + }; + match os { + Os::Web => Frame::Native, + Os::Mac => Frame::Inset(MacInset::default()), + Os::Windows => captions(CaptionFamily::Windows), + Os::Linux => { + let no_ssd = backend == Backend::Wayland && desktop.ssd == Some(false); + match desktop.kind { + DesktopKind::Tiling if !forced => Frame::Native, + DesktopKind::Tiling => captions(layout::family_from_gtk_theme(desktop.gtk_theme.as_deref())), + DesktopKind::Gnome => captions(CaptionFamily::Adwaita), + // Open decision 1: the line below is the only place that picks the app's bar on + // desktops that draw their own frame. `false` gives `Native` there. + _ if !no_ssd && !integrated_on_ssd && !forced => Frame::Native, + DesktopKind::Kde => captions(CaptionFamily::Breeze), + DesktopKind::Other if no_ssd => captions(CaptionFamily::Generic), + DesktopKind::Other => captions(layout::family(DesktopKind::Other, desktop.gtk_theme.as_deref())), + } + } + } +} + +/// Read the platform once (500 ms at most, as for [`crate::Choice::probe`]) and decide. +/// `prefix` names the override variable `_TITLEBAR`; when it is unset, `CRAFT_TITLEBAR` +/// applies. `backend` is the one the app opens its window on, [`Backend::from_env`] +/// unless the app forces X11. +pub fn decide_for(prefix: Prefix, backend: Backend, pref: TitleBarPref) -> Decision { + let os = Os::current(); + let env = std::env::var(prefix.var_name()).or_else(|_| std::env::var(Prefix::default().var_name())).ok(); + let desktop = + if os == Os::Linux { Desktop::detect(backend) } else { Desktop { kind: DesktopKind::Other, ssd: None, gtk_theme: None, icon_theme: None } }; + decide_with(os, backend, &desktop, pref, env.as_deref(), &|kind| desktop_layout(os, kind)) +} + +/// The desktop's window-button layout, where it names one. +fn desktop_layout(os: Os, kind: DesktopKind) -> Layout { + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))] + if os == Os::Linux { + return layout::read_layout(kind, &|k: &str| std::env::var(k).ok()); + } + let _ = os; + layout::default_layout(kind) +} + +/// Apply a [`Frame`] to an [`egui::ViewportBuilder`] before the window is created: decorations off +/// for [`Frame::Integrated`], a full-size content view with hidden title and transparent title bar +/// for [`Frame::Inset`], decorations on for [`Frame::Native`]. +#[cfg(feature = "egui")] +pub fn apply(builder: egui::ViewportBuilder, frame: &Frame) -> egui::ViewportBuilder { + match frame { + Frame::Native => builder.with_decorations(true), + Frame::Inset(_) => builder.with_decorations(true).with_fullsize_content_view(true).with_title_shown(false).with_titlebar_shown(false), + Frame::Integrated(_) => builder.with_decorations(false), + } +} + +impl From<&crate::Frame> for Frame { + /// The old two-way frame as a new one: `Desktop` is `Native`, `App(layout)` is integrated + /// with generic captions. + fn from(old: &crate::Frame) -> Self { + match old { + crate::Frame::Desktop => Frame::Native, + crate::Frame::App(layout) => Frame::Integrated(Captions { family: CaptionFamily::Generic, layout: layout.clone() }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use CaptionFamily::{Adwaita, Breeze, Generic, Windows}; + use TitleBarPref::{Integrated as Int, System}; + + fn desk(kind: DesktopKind, ssd: Option, theme: Option<&str>) -> Desktop { + Desktop { kind, ssd, gtk_theme: theme.map(str::to_string), icon_theme: None } + } + + fn family_of(d: &Decision) -> Option { + match &d.frame { + Frame::Integrated(c) => Some(c.family), + _ => None, + } + } + + #[test] + fn every_row_of_the_table() { + use DesktopKind::{Gnome, Kde, Other, Tiling}; + // (os, backend, desktop, expected family; None = Native) + let rows: Vec<(Os, Backend, Desktop, Option)> = vec![ + (Os::Windows, Backend::Wayland, desk(Other, None, None), Some(Windows)), + (Os::Linux, Backend::Wayland, desk(Gnome, Some(false), None), Some(Adwaita)), + (Os::Linux, Backend::X11, desk(Gnome, None, Some("Arc")), Some(Adwaita)), + (Os::Linux, Backend::Wayland, desk(Kde, Some(true), None), Some(Breeze)), + (Os::Linux, Backend::X11, desk(Kde, None, None), Some(Breeze)), + (Os::Linux, Backend::Wayland, desk(Other, Some(true), Some("Adwaita")), Some(Adwaita)), + (Os::Linux, Backend::Wayland, desk(Other, Some(true), Some("Breeze-Dark")), Some(Breeze)), + (Os::Linux, Backend::X11, desk(Other, None, Some("Mint-Y")), Some(Generic)), + (Os::Linux, Backend::Wayland, desk(Other, Some(true), None), Some(Generic)), + (Os::Linux, Backend::Wayland, desk(Tiling, Some(true), None), None), + (Os::Linux, Backend::X11, desk(Tiling, None, None), None), + (Os::Linux, Backend::Wayland, desk(Other, Some(false), Some("Adwaita")), Some(Generic)), + (Os::Web, Backend::X11, desk(Other, None, None), None), + ]; + for (os, backend, d, want) in rows { + let got = decide(os, backend, &d, Int, None); + assert_eq!(family_of(&got), want, "{os:?} {backend:?} {d:?}"); + assert_eq!(got.overridden, None); + if want.is_none() { + assert_eq!(got.frame, Frame::Native); + } + let system = decide(os, backend, &d, System, None); + assert_eq!(system.frame, Frame::Native, "system bar: {os:?} {d:?}"); + } + } + + #[test] + fn native_on_ssd_desktops_when_the_flag_is_off() { + use DesktopKind::{Gnome, Kde, Other}; + let frame = |kind, backend, ssd, forced| integrated_frame(Os::Linux, backend, &desk(kind, ssd, None), forced, false, &layout::default_layout); + assert_eq!(frame(Kde, Backend::Wayland, Some(true), false), Frame::Native); + assert_eq!(frame(Other, Backend::X11, None, false), Frame::Native); + assert!(matches!(frame(Kde, Backend::Wayland, Some(true), true), Frame::Integrated(_)), "the override still forces the bar"); + assert!(matches!(frame(Gnome, Backend::Wayland, Some(false), false), Frame::Integrated(_))); + assert!(matches!(frame(Other, Backend::Wayland, Some(false), false), Frame::Integrated(_)), "no SSD: nothing else draws a frame"); + } + + #[test] + fn the_decision_carries_the_desktop() { + let d = desk(DesktopKind::Tiling, Some(true), None); + assert_eq!(decide(Os::Linux, Backend::Wayland, &d, Int, None).desktop, d); + } + + #[test] + fn macos_gets_the_inset() { + let d = decide(Os::Mac, Backend::X11, &desk(DesktopKind::Other, None, None), Int, None); + assert_eq!(d.frame, Frame::Inset(MacInset::default())); + assert_eq!(decide(Os::Mac, Backend::X11, &desk(DesktopKind::Other, None, None), System, None).frame, Frame::Native); + } + + #[test] + fn the_override_wins_over_the_setting_both_ways() { + let kde = desk(DesktopKind::Kde, Some(true), None); + let system = decide(Os::Linux, Backend::Wayland, &kde, Int, Some("system")); + assert_eq!((system.frame, system.overridden), (Frame::Native, Some(false))); + let desktop = decide(Os::Linux, Backend::Wayland, &kde, Int, Some("desktop")); + assert_eq!((desktop.frame, desktop.overridden), (Frame::Native, Some(false))); + let app = decide(Os::Linux, Backend::Wayland, &kde, System, Some("app")); + assert_eq!(app.overridden, Some(true)); + assert_eq!(family_of(&app), Some(Breeze)); + // `app` also forces the bar on a tiling compositor, which would otherwise be native. + let tiling = desk(DesktopKind::Tiling, Some(true), None); + assert_eq!(family_of(&decide(Os::Linux, Backend::Wayland, &tiling, Int, Some("app"))), Some(Generic)); + // An unknown value is no override. + let unknown = decide(Os::Linux, Backend::Wayland, &kde, System, Some("maybe")); + assert_eq!((unknown.frame, unknown.overridden), (Frame::Native, None)); + } + + #[test] + fn default_layouts_follow_the_family() { + let gnome = decide(Os::Linux, Backend::Wayland, &desk(DesktopKind::Gnome, Some(false), None), Int, None); + assert!(matches!(gnome.frame, Frame::Integrated(c) if c.layout.right == vec![crate::Button::Close])); + let win = decide(Os::Windows, Backend::X11, &desk(DesktopKind::Other, None, None), Int, None); + assert!(matches!(win.frame, Frame::Integrated(c) if c.layout == Layout::default())); + } + + #[test] + fn the_old_frame_converts() { + assert_eq!(Frame::from(&crate::Frame::Desktop), Frame::Native); + assert!(matches!(Frame::from(&crate::Frame::App(Layout::default())), Frame::Integrated(_))); + assert_eq!(CaptionFamily::parse(" Breeze "), Some(Breeze)); + } +} diff --git a/crates/window/src/restore/legacy.rs b/crates/window/src/restore/legacy.rs new file mode 100644 index 0000000000..b0f569f62f --- /dev/null +++ b/crates/window/src/restore/legacy.rs @@ -0,0 +1,281 @@ +//! Readers for window geometry that apps stored before the `window.json` store. +//! +//! eframe keeps a RON map of strings in `app.ron` (`ui.ron`); its `"window"` entry is the RON of +//! egui-winit's `WindowSettings`, and `"egui"` holds the interface zoom. No RON crate is +//! involved: the readers look up the few named fields they need, in both layouts eframe has +//! used (a flat struct, and one with a nested `normal_geometry`). Nothing is written back; old +//! builds keep working from the old file. +//! +//! An old layout has no scale factor, so imports assume 1; [`place`](super::place) takes the +//! real one from the monitor the window lands on. + +use std::path::Path; + +use serde_json::Value; + +use super::place::{NormalRect, Placement}; + +/// The placement in an eframe `app.ron` text: its `"window"` entry, with the size converted to +/// points at zoom 1 using the `"egui"` entry's `zoom_factor` (1 when absent). +pub fn eframe_app_ron(text: &str) -> Option { + let window = ron_string_entry(text, "window")?; + let zoom = ron_string_entry(text, "egui").and_then(|e| number(field(&e, "zoom_factor")?)).unwrap_or(1.0); + eframe_window_settings(&window, zoom) +} + +/// [`eframe_app_ron`] for a file; `None` when it is missing or unreadable. +pub fn eframe_app_ron_file(path: &Path) -> Option { + eframe_app_ron(&std::fs::read_to_string(path).ok()?) +} + +/// The placement in the RON of one eframe `WindowSettings`. `zoom` is the interface zoom factor +/// the size was saved under (eframe saves points at that zoom). +pub fn eframe_window_settings(ron: &str, zoom: f32) -> Option { + let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + // The nested layout also names the scale; the flat one does not. + let geometry = field(ron, "normal_geometry").and_then(group).unwrap_or(ron); + let scale = field(geometry, "scale_factor").and_then(number).filter(|s| *s > 0.0).unwrap_or(1.0); + let size = field(geometry, "inner_size_points").and_then(vec2)?; + let pos = field(geometry, "outer_position_pixels").and_then(vec2).or_else(|| field(geometry, "inner_position_pixels").and_then(vec2)); + // The window's pixel size divided by zoom × scale (eframe >= 0.36), so × zoom is points at + // zoom 1. Older eframe saved points at the then-current zoom, which this reads the same way. + let size = size.map(|v| v * zoom); + // Windows parks a minimized window near (-32000, -32000). + let pos = pos.filter(|p| p.iter().all(|v| *v > -30000.0)); + Some(Placement { + normal: NormalRect { pos: pos.map_or([0.0; 2], |p| p.map(|v| v / scale)), size }, + position_px: pos.map(|p| p.map(|v| v.round() as i32)), + scale, + zoom, + maximized: field(ron, "maximized").is_some_and(truth), + fullscreen: field(ron, "fullscreen").is_some_and(truth), + monitor: None, + }) +} + +/// The value at `path` of a JSON object (`json_at(&v, &["window", "size"])`). +pub fn json_at<'a>(v: &'a Value, path: &[&str]) -> Option<&'a Value> { + path.iter().try_fold(v, |v, k| v.get(*k)) +} + +/// A finite number at `path`. +pub fn json_f32(v: &Value, path: &[&str]) -> Option { + json_at(v, path)?.as_f64().filter(|n| n.is_finite()).map(|n| n as f32) +} + +/// A bool at `path`. +pub fn json_bool(v: &Value, path: &[&str]) -> Option { + json_at(v, path)?.as_bool() +} + +/// A pair of finite numbers at `path`, written as `[a, b]` or as an object with the two given keys. +pub fn json_pair(v: &Value, path: &[&str], keys: [&str; 2]) -> Option<[f32; 2]> { + let at = json_at(v, path)?; + let num = |x: Option<&Value>| x?.as_f64().filter(|n| n.is_finite()).map(|n| n as f32); + match at { + Value::Array(a) if a.len() == 2 => Some([num(a.first())?, num(a.get(1))?]), + Value::Object(_) => Some([num(at.get(keys[0]))?, num(at.get(keys[1]))?]), + _ => None, + } +} + +/// [`json_at`] on the text of a JSON file; `None` when missing or not JSON. +pub fn read_json_file(path: &Path) -> Option { + serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok() +} + +// ---- RON scanning -------------------------------------------------------------------------- + +/// The text after `name:` for the first `name` that is a whole identifier. +fn field<'a>(text: &'a str, name: &str) -> Option<&'a str> { + let mut from = 0; + while let Some(i) = text[from..].find(name) { + let start = from + i; + let end = start + name.len(); + let before_ok = text[..start].chars().next_back().is_none_or(|c| !(c.is_alphanumeric() || c == '_')); + let rest = text[end..].trim_start(); + if before_ok && let Some(value) = rest.strip_prefix(':') { + return Some(value.trim_start()); + } + from = end; + } + None +} + +/// The text inside the parentheses that `s` starts with, as `(…)` or `Some(…)`. +fn group(s: &str) -> Option<&str> { + let s = s.strip_prefix("Some").map_or(s, str::trim_start); + let s = s.strip_prefix('(')?; + let mut depth = 1usize; + for (i, c) in s.char_indices() { + match c { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + return Some(&s[..i]); + } + } + _ => {} + } + } + None +} + +fn number(s: &str) -> Option { + let end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E'))).unwrap_or(s.len()); + s[..end].parse::().ok().filter(|n| n.is_finite()) +} + +fn truth(s: &str) -> bool { + s.starts_with("true") +} + +/// `Some((x: 1.0, y: 2.0))`, `(x: 1.0, y: 2.0)` or `(1.0, 2.0)`; `None` for `None`. +fn vec2(s: &str) -> Option<[f32; 2]> { + let inner = group(s)?; + // `Some((…))` wraps the pair in a second group. + let inner = if inner.trim_start().starts_with('(') { group(inner.trim_start())? } else { inner }; + if let (Some(x), Some(y)) = (field(inner, "x").and_then(number), field(inner, "y").and_then(number)) { + return Some([x, y]); + } + let (a, b) = inner.split_once(',')?; + Some([number(a.trim())?, number(b.trim())?]) +} + +/// The string value for `key` in a RON map of strings (`{"key": "value", …}`), unescaped. +fn ron_string_entry(text: &str, key: &str) -> Option { + let mut literals = string_literals(text).into_iter(); + while let Some(k) = literals.next() { + let v = literals.next()?; + if k == key { + return Some(v); + } + } + None +} + +/// Every string literal of `text` in order: `"…"` with escapes, and raw `r#"…"#`. +fn string_literals(text: &str) -> Vec { + let mut out = Vec::new(); + let b = text.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i] == b'r' && matches!(b.get(i + 1), Some(b'"' | b'#')) { + let hashes = b[i + 1..].iter().take_while(|c| **c == b'#').count(); + if b.get(i + 1 + hashes) == Some(&b'"') { + let body = i + 2 + hashes; + let close = format!("\"{}", "#".repeat(hashes)); + let Some(len) = text[body..].find(&close) else { break }; + out.push(text[body..body + len].to_owned()); + i = body + len + close.len(); + continue; + } + } + if b[i] == b'"' { + let (s, next) = escaped(text, i + 1); + out.push(s); + i = next; + continue; + } + i += 1; + } + out +} + +/// Reads an escaped literal body starting at byte `from`; returns it and the index after the closing quote. +fn escaped(text: &str, from: usize) -> (String, usize) { + let mut s = String::new(); + let mut chars = text[from..].char_indices(); + while let Some((i, c)) = chars.next() { + match c { + '"' => return (s, from + i + 1), + '\\' => match chars.next().map(|(_, e)| e) { + Some('n') => s.push('\n'), + Some('t') => s.push('\t'), + Some('r') => s.push('\r'), + Some('u') => { + let mut hex = String::new(); + for (_, h) in chars.by_ref() { + if h == '}' { + break; + } + if h != '{' { + hex.push(h); + } + } + if let Some(ch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) { + s.push(ch); + } + } + Some(other) => s.push(other), + None => break, + }, + c => s.push(c), + } + } + (s, text.len()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::restore::Store; + + const FLAT: &str = r#"{ + "egui": "(options:(zoom_factor:1.5,other:1))", + "window": "(outer_position_pixels:Some((x:120.0,y:-30.0)),fullscreen:false,maximized:true,inner_size_points:Some((x:800.0,y:600.0)))", +}"#; + + #[test] + fn imports_the_flat_eframe_layout_with_zoom() { + let p = eframe_app_ron(FLAT).unwrap(); + assert_eq!(p.position_px, Some([120, -30])); + assert_eq!(p.normal.size, [1200.0, 900.0]); + assert_eq!(p.zoom, 1.5); + assert!(p.maximized && !p.fullscreen); + } + + #[test] + fn imports_the_nested_layout_with_its_scale() { + let w = "(normal_geometry:(outer_position_pixels:Some((x:200.0,y:100.0)),scale_factor:2.0,inner_size_points:(x:640.0,y:480.0)),fullscreen:true,maximized:false)"; + let text = format!("{{\"window\": r#\"{w}\"#}}"); + let p = eframe_app_ron(&text).unwrap(); + assert_eq!((p.scale, p.position_px, p.normal.size), (2.0, Some([200, 100]), [640.0, 480.0])); + assert_eq!(p.normal.pos, [100.0, 50.0]); + assert!(p.fullscreen); + } + + #[test] + fn missing_position_and_garbage_are_handled() { + let w = "(outer_position_pixels:None,fullscreen:false,maximized:false,inner_size_points:Some((x:300.0,y:200.0)))"; + assert_eq!(eframe_window_settings(w, 1.0).unwrap().position_px, None); + assert!(eframe_window_settings("(", 1.0).is_none()); + assert!(eframe_app_ron("not ron").is_none()); + } + + #[test] + fn minimized_windows_parked_off_screen_have_no_position() { + let w = "(outer_position_pixels:Some((x:-32000.0,y:-32000.0)),fullscreen:false,maximized:false,inner_size_points:Some((x:300.0,y:200.0)))"; + let p = eframe_window_settings(w, 1.0).unwrap(); + assert_eq!((p.position_px, p.normal.size), (None, [300.0, 200.0])); + } + + #[test] + fn imported_placement_lands_in_the_store() { + let mut store = Store::in_memory(); + store.set("main", &eframe_app_ron(FLAT).unwrap()); + assert_eq!(store.get("main").unwrap().position_px, Some([120, -30])); + } + + #[test] + fn json_helpers_read_nested_values() { + let v: Value = serde_json::from_str(r#"{"window":{"size":[800,600],"pos":{"x":1,"y":2},"max":true,"w":3.5}}"#).unwrap(); + assert_eq!(json_pair(&v, &["window", "size"], ["w", "h"]), Some([800.0, 600.0])); + assert_eq!(json_pair(&v, &["window", "pos"], ["x", "y"]), Some([1.0, 2.0])); + assert_eq!(json_bool(&v, &["window", "max"]), Some(true)); + assert_eq!(json_f32(&v, &["window", "w"]), Some(3.5)); + assert_eq!(json_f32(&v, &["window", "nope"]), None); + } +} diff --git a/crates/window/src/restore/mod.rs b/crates/window/src/restore/mod.rs new file mode 100644 index 0000000000..2e77433c9a --- /dev/null +++ b/crates/window/src/restore/mod.rs @@ -0,0 +1,30 @@ +//! Window restore: where a window opens and the file that remembers it. No egui. +//! +//! - [`place`]: saved [`Placement`] + connected [`Monitor`]s + app [`Defaults`] → the geometry to +//! open with. Pure; the rules are on its documentation. +//! - [`Store`]: `window.json` beside the app's `config.toml`, one [`Placement`] per window key +//! (`"main"` for the first window). +//! - [`legacy`]: readers for what apps stored before, such as eframe's `"window"` entry in +//! `app.ron`. +//! +//! Keep one [`Store`] per app, shared by every window (for example behind an `Arc>`): +//! each write rewrites the whole file from that store's copy, so two stores in one process +//! overwrite each other. +//! +//! ``` +//! use craft_window::restore::{Defaults, Monitor, MonitorKey, Store, place}; +//! +//! let mut store = Store::in_memory(); +//! let monitors = [Monitor::new(MonitorKey::new("DP-1", [1920, 1080]), [0, 0], [1920, 1080], 1.0)]; +//! let defaults = Defaults::new([1200.0, 800.0], [480.0, 320.0]); +//! let opened = place(store.get("main").as_ref(), &monitors, Some(0), &defaults); +//! store.set("main", &opened); +//! assert_eq!(store.get("main"), Some(opened)); +//! ``` + +pub mod legacy; +mod place; +mod store; + +pub use place::{Defaults, Monitor, MonitorKey, NormalRect, Placement, place}; +pub use store::{FILE_NAME, MAIN, Pending, ReadOnly, SCHEMA_VERSION, Store, write_pending}; diff --git a/crates/window/src/restore/place.rs b/crates/window/src/restore/place.rs new file mode 100644 index 0000000000..34a5fa6e63 --- /dev/null +++ b/crates/window/src/restore/place.rs @@ -0,0 +1,538 @@ +//! The model and the pure placement rules: saved geometry plus the connected monitors in, the +//! geometry to open with out. +//! +//! Units. Sizes and `NormalRect`s are logical points at interface zoom 1, so a window saved while the +//! user ran the interface at 150 % does not open smaller each launch. Positions are physical +//! pixels in the desktop's coordinate space (negative for a monitor left of or above the primary). + +use serde::{Deserialize, Serialize}; + +/// How much of the window's top strip must lie on one monitor, in points on each axis, for the +/// user to still be able to grab it. +const BAR: f32 = 64.0; +const MAX_POINTS: f32 = 100_000.0; + +/// A rectangle in logical points at zoom 1: top-left corner and size. (Not `craft_window::Rect`, +/// which is the cascade module's.) +/// +/// `pos` is `Placement::position_px` divided by `Placement::scale`; it is informational, and +/// `[0, 0]` when the position is unknown. +#[derive(Clone, Copy, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct NormalRect { + pub pos: [f32; 2], + pub size: [f32; 2], +} + +/// Identifies a monitor across launches: the name the platform reports and its size in pixels. +/// +/// The size is part of the key because names repeat (`"Built-in Display"`) or change (`DP-1` +/// after a re-plug), and a monitor switched to another resolution is a different place to put a +/// window. A key that no longer matches falls back to the nearest connected monitor. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct MonitorKey { + pub name: String, + pub size_px: [u32; 2], +} + +impl MonitorKey { + pub fn new(name: impl Into, size_px: [u32; 2]) -> Self { + Self { name: name.into(), size_px } + } +} + +/// What to remember about a window, and what [`place`] returns for the app to open it with. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct Placement { + /// The last window state that was neither maximized nor full screen. + pub normal: NormalRect, + /// Outer top-left corner in physical pixels; `None` where the platform does not tell (Wayland). + #[serde(default)] + pub position_px: Option<[i32; 2]>, + /// Physical pixels per point of the monitor the window was on, without interface zoom. + #[serde(default = "one")] + pub scale: f32, + /// The interface zoom factor while saving. Informational: `normal` is already at zoom 1. + #[serde(default = "one")] + pub zoom: f32, + #[serde(default)] + pub maximized: bool, + #[serde(default)] + pub fullscreen: bool, + #[serde(default)] + pub monitor: Option, +} + +impl Placement { + /// A window of `size` points, position unknown, on a monitor of `scale`, not maximized. + pub fn new(size: [f32; 2], scale: f32) -> Self { + make(size, None, scale, 1.0, None) + } +} + +fn one() -> f32 { + 1.0 +} + +/// A connected monitor. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Monitor { + pub key: MonitorKey, + /// Top-left corner in the desktop's pixel space. + pub pos_px: [i32; 2], + pub size_px: [u32; 2], + /// Physical pixels per point. + pub scale: f32, + /// The part not taken by the taskbar, Dock or menu bar: top-left corner and size in pixels. + /// When set, it replaces [`Defaults::screen_room`] for this monitor. + pub work_px: Option<([i32; 2], [u32; 2])>, +} + +impl Monitor { + pub fn new(key: MonitorKey, pos_px: [i32; 2], size_px: [u32; 2], scale: f32) -> Self { + Self { key, pos_px, size_px, scale, work_px: None } + } + + /// Sets the usable area (see [`work_px`](Self::work_px)). + pub fn with_work_px(mut self, pos_px: [i32; 2], size_px: [u32; 2]) -> Self { + self.work_px = Some((pos_px, size_px)); + self + } +} + +/// What the app wants when nothing (usable) is saved, and how the platform behaves. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Defaults { + /// Size of a first window, in points. + pub size: [f32; 2], + /// The smallest window, in points. Yields to a monitor smaller than this. + pub min: [f32; 2], + /// Points a monitor loses to the taskbar, Dock or menu bar, per axis. + pub screen_room: [f32; 2], + /// Restore full screen. Off by default: most apps open as a window. + pub restore_fullscreen: bool, + /// The platform hides window positions (Wayland): none is applied or returned. + pub no_position: bool, +} + +impl Defaults { + pub fn new(size: [f32; 2], min: [f32; 2]) -> Self { + Self { size, min, screen_room: [0.0, 48.0], restore_fullscreen: false, no_position: false } + } + + pub fn with_screen_room(mut self, room: [f32; 2]) -> Self { + self.screen_room = room; + self + } + + pub fn with_restore_fullscreen(mut self, on: bool) -> Self { + self.restore_fullscreen = on; + self + } + + pub fn with_no_position(mut self, on: bool) -> Self { + self.no_position = on; + self + } +} + +impl Monitor { + fn scale(&self) -> f32 { + if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 } + } + + fn points(&self) -> [f32; 2] { + self.size_px.map(|s| s as f32 / self.scale()) + } + + /// Position and size in pixels of the area windows may use. + fn bounds(&self) -> ([i32; 2], [u32; 2]) { + self.work_px.unwrap_or((self.pos_px, self.size_px)) + } + + /// Size in points of the area windows may use: the work area, else the monitor less `room`. + fn usable(&self, room: [f32; 2]) -> [f32; 2] { + let s = self.scale(); + match self.work_px { + Some((_, size)) => size.map(|v| (v as f32 / s).max(1.0)), + None => { + let p = self.points(); + std::array::from_fn(|i| (p[i] - room[i].max(0.0)).max(1.0)) + } + } + } + + fn centre_px(&self) -> [f64; 2] { + std::array::from_fn(|i| f64::from(self.pos_px[i]) + f64::from(self.size_px[i]) / 2.0) + } + + /// `pos` moved the least that puts a window of `size` points fully in the usable area. + fn keep_on(&self, pos: [i32; 2], size: [f32; 2]) -> [i32; 2] { + let (bpos, bsize) = self.bounds(); + std::array::from_fn(|i| { + let lo = i64::from(bpos[i]); + let win = (f64::from(size[i]) * f64::from(self.scale())).round() as i64; + let hi = (lo + i64::from(bsize[i]) - win).max(lo); + i32::try_from(i64::from(pos[i]).clamp(lo, hi)).unwrap_or(bpos[i]) + }) + } + + /// Area in points of the window's top strip (full width, up to 64 pt tall) lying on this + /// monitor, if at least min(width, 64) × min(height, 64) pt of it does. A few pixels of slack + /// absorb Windows' snapped offset of about -7 px. + fn bar_overlap(&self, pos: [i32; 2], size: [f32; 2]) -> Option { + const SLACK_PX: f64 = 8.0; + let s = f64::from(self.scale()); + let strip = [size[0], size[1].min(BAR)]; + let need = [size[0].min(BAR), size[1].min(BAR)]; + let mut got = [0.0f64; 2]; + for i in 0..2 { + let a0 = f64::from(pos[i]); + let a1 = a0 + f64::from(strip[i]) * s; + let b0 = f64::from(self.pos_px[i]); + let b1 = b0 + f64::from(self.size_px[i]); + got[i] = (a1.min(b1) - a0.max(b0)).max(0.0); + } + (0..2).all(|i| got[i] + SLACK_PX >= f64::from(need[i]) * s).then(|| (got[0] / s * got[1] / s) as f32) + } +} + +/// Size no bigger than `room` and no smaller than `min` unless `room` is. +fn fit(size: [f32; 2], room: [f32; 2], min: [f32; 2]) -> [f32; 2] { + std::array::from_fn(|i| size[i].min(room[i]).max(min[i].min(room[i])).max(1.0)) +} + +fn in_points(v: f32) -> bool { + v.is_finite() && (1.0..=MAX_POINTS).contains(&v) +} + +/// The saved record with out-of-range numbers repaired, or `None` when its size is no size. +pub(super) fn sane(s: &Placement) -> Option { + if !s.normal.size.iter().all(|v| in_points(*v)) { + return None; + } + let mut s = s.clone(); + if !s.normal.pos.iter().all(|v| v.is_finite()) { + s.normal.pos = [0.0; 2]; + } + if !(s.scale.is_finite() && s.scale > 0.0 && s.scale <= 16.0) { + s.scale = 1.0; + } + if !(s.zoom.is_finite() && (0.1..=10.0).contains(&s.zoom)) { + s.zoom = 1.0; + } + Some(s) +} + +fn make(size: [f32; 2], pos_px: Option<[i32; 2]>, scale: f32, zoom: f32, monitor: Option) -> Placement { + let pos = pos_px.map_or([0.0, 0.0], |p| p.map(|v| v as f32 / scale)); + Placement { normal: NormalRect { pos, size }, position_px: pos_px, scale, zoom, maximized: false, fullscreen: false, monitor } +} + +/// Where a window opens: `saved` kept on a connected monitor, else the default size on `home` +/// (index into `monitors` of the monitor the system opens it on; the one at the origin, else the +/// first, when `None`). +/// +/// - Nothing saved: [`Defaults::size`] fitted to the usable area of `home`; maximized when the +/// monitor is too small for it. The position is left to the system. +/// - The saved size is points at zoom 1 and is not scaled by `zoom`. +/// - `normal` is kept as saved while `maximized`; only the flag says it was maximized. +/// - Off screen: when less than 64×64 pt of the window's top strip lies on any one monitor, the +/// window moves to its saved monitor, else the one nearest its centre, else the primary. +/// - The size is clamped to the usable area of the monitor it lands on and to `min`. +/// - A different `scale` than saved is taken from the monitor; the size stays in points. +/// - [`Defaults::no_position`]: no position in, none out. +/// - Full screen comes back only with [`Defaults::restore_fullscreen`]. +/// - Without monitors (the platform lists none) nothing can be checked: the saved geometry is kept, +/// with the size raised to `min`. +pub fn place(saved: Option<&Placement>, monitors: &[Monitor], home: Option, d: &Defaults) -> Placement { + let saved = saved.and_then(sane); + let primary = monitors.iter().find(|m| m.pos_px == [0, 0]).or(monitors.first()); + let home = home.and_then(|i| monitors.get(i)).or(primary); + match (saved, home) { + (None, None) => make(fit(d.size, [MAX_POINTS; 2], d.min), None, 1.0, 1.0, None), + (None, Some(h)) => first_launch(h, d), + (Some(s), None) => { + let size = fit(s.normal.size, [MAX_POINTS; 2], d.min); + let pos = if d.no_position { None } else { s.position_px }; + Placement { maximized: s.maximized, fullscreen: s.fullscreen && d.restore_fullscreen, ..make(size, pos, s.scale, s.zoom, s.monitor) } + } + (Some(s), Some(h)) => restore(&s, monitors, h, primary.unwrap_or(h), d), + } +} + +fn first_launch(home: &Monitor, d: &Defaults) -> Placement { + let usable = home.usable(d.screen_room); + let too_small = (0..2).any(|i| d.size[i] > usable[i]); + let size = fit(d.size, usable, d.min); + Placement { maximized: too_small, ..make(size, None, home.scale(), 1.0, Some(home.key.clone())) } +} + +fn restore(s: &Placement, monitors: &[Monitor], home: &Monitor, primary: &Monitor, d: &Defaults) -> Placement { + let size = s.normal.size; + let saved_pos = if d.no_position { None } else { s.position_px }; + let by_key = || s.monitor.as_ref().and_then(|k| monitors.iter().find(|m| &m.key == k)); + + let mut visible = false; + let target = match saved_pos { + Some(p) => { + // On mixed-DPI desktops pixel ranges overlap; the saved monitor decides first. + let shown = monitors + .iter() + .filter_map(|m| m.bar_overlap(p, size).map(|a| (a, m))) + .max_by(|a, b| { + let key = |m: &Monitor| s.monitor.as_ref() == Some(&m.key); + key(a.1).cmp(&key(b.1)).then(a.0.total_cmp(&b.0)) + }) + .map(|(_, m)| m); + visible = shown.is_some(); + shown.or_else(by_key).unwrap_or_else(|| nearest(monitors, p, size, s.scale).unwrap_or(primary)) + } + None => by_key().unwrap_or(home), + }; + + let fitted = fit(size, target.usable(d.screen_room), d.min); + let kept = visible && fitted == size; + let pos = saved_pos.map(|p| if kept { p } else { target.keep_on(p, fitted) }); + // A kept position on the saved monitor keeps its saved scale: the pixel ranges of mixed-DPI + // monitors overlap, and the position was measured at that scale. + let scale = if kept && s.monitor.as_ref() == Some(&target.key) { s.scale } else { target.scale() }; + Placement { + maximized: s.maximized, + fullscreen: s.fullscreen && d.restore_fullscreen, + ..make(fitted, pos, scale, s.zoom, Some(target.key.clone())) + } +} + +/// The monitor whose centre is closest to the window's centre. +fn nearest(monitors: &[Monitor], pos: [i32; 2], size: [f32; 2], scale: f32) -> Option<&Monitor> { + let c: [f64; 2] = std::array::from_fn(|i| f64::from(pos[i]) + f64::from(size[i]) * f64::from(scale) / 2.0); + let dist = |m: &Monitor| { + let mc = m.centre_px(); + (mc[0] - c[0]).powi(2) + (mc[1] - c[1]).powi(2) + }; + monitors.iter().min_by(|a, b| dist(a).total_cmp(&dist(b))) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + + fn mon(name: &str, pos: [i32; 2], size: [u32; 2], scale: f32) -> Monitor { + Monitor::new(MonitorKey::new(name, size), pos, size, scale) + } + + fn hd() -> Monitor { + mon("A", [0, 0], [1920, 1080], 1.0) + } + + fn defaults() -> Defaults { + let mut d = Defaults::new([1200.0, 800.0], [400.0, 300.0]); + d.screen_room = [0.0, 40.0]; + d + } + + fn saved(pos: Option<[i32; 2]>, size: [f32; 2], scale: f32, m: &Monitor) -> Placement { + let mut p = make(size, pos, scale, 1.0, Some(m.key.clone())); + p.maximized = false; + p + } + + #[test] + fn first_launch_uses_default_size_and_leaves_position_to_the_system() { + let p = place(None, &[hd()], Some(0), &defaults()); + assert_eq!(p.normal.size, [1200.0, 800.0]); + assert_eq!(p.position_px, None); + assert!(!p.maximized); + } + + #[test] + fn first_launch_on_a_small_monitor_fits_and_maximizes() { + let small = mon("S", [0, 0], [1280, 720], 1.0); + let p = place(None, &[small], None, &defaults()); + assert_eq!(p.normal.size, [1200.0, 680.0]); + assert!(p.maximized); + } + + #[test] + fn monitor_gone_moves_the_window_to_a_connected_one() { + let gone = mon("Gone", [1920, 0], [1920, 1080], 1.0); + let s = saved(Some([2500, 100]), [800.0, 600.0], 1.0, &gone); + let p = place(Some(&s), &[hd()], Some(0), &defaults()); + assert_eq!(p.monitor, Some(hd().key)); + let [x, y] = p.position_px.unwrap(); + assert!((0..=1920 - 800).contains(&x) && (0..=1080 - 600).contains(&y)); + } + + #[test] + fn window_dragged_off_screen_comes_back_but_a_visible_bar_stays() { + let m = hd(); + let off = saved(Some([1900, 100]), [800.0, 600.0], 1.0, &m); + let p = place(Some(&off), std::slice::from_ref(&m), Some(0), &defaults()); + assert_eq!(p.position_px, Some([1120, 100])); + // 100 pt of the bar still on the monitor: untouched. + let ok = saved(Some([1820, 100]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&ok), &[m], Some(0), &defaults()).position_px, Some([1820, 100])); + } + + #[test] + fn mixed_dpi_prefers_the_saved_monitor_and_keeps_its_scale() { + let mac = mon("Mac", [0, 0], [3024, 1964], 2.0); + let ext = mon("Ext", [1512, 0], [1920, 1080], 1.0); + let s = saved(Some([2000, 100]), [800.0, 600.0], 2.0, &mac); + let p = place(Some(&s), &[mac.clone(), ext], Some(0), &defaults()); + assert_eq!((p.monitor, p.scale, p.position_px), (Some(mac.key), 2.0, Some([2000, 100]))); + } + + #[test] + fn bar_is_a_strip_not_a_corner() { + let m = hd(); + // Left edge: 100 px of an 800 pt window show on the right of x = -700; the strip is wide enough. + let s = saved(Some([-700, 100]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), std::slice::from_ref(&m), Some(0), &defaults()).position_px, Some([-700, 100])); + // Only 30 px show: moved back. + let s = saved(Some([-770, 100]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), std::slice::from_ref(&m), Some(0), &defaults()).position_px, Some([0, 100])); + // Windows' snapped -7 px offset on the left or top is fine. + let s = saved(Some([-7, -7]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), std::slice::from_ref(&m), Some(0), &defaults()).position_px, Some([-7, -7])); + // Top edge: the strip is 64 pt tall; 40 pt of it visible is not enough. + let s = saved(Some([100, -24]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), std::slice::from_ref(&m), Some(0), &defaults()).position_px, Some([100, 0])); + } + + #[test] + fn work_area_replaces_screen_room() { + let m = hd().with_work_px([0, 0], [1920, 1000]); + let p = place(None, &[m], Some(0), &Defaults::new([1200.0, 1100.0], [400.0, 300.0])); + assert_eq!(p.normal.size, [1200.0, 1000.0]); + assert!(p.maximized); + } + + #[test] + fn bar_above_the_top_edge_counts_as_off_screen() { + let m = hd(); + let s = saved(Some([100, -50]), [800.0, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), &[m], Some(0), &defaults()).position_px, Some([100, 0])); + } + + #[test] + fn scale_change_keeps_points_and_takes_the_new_scale() { + let old = hd(); + let hidpi = mon("B", [0, 0], [3840, 2160], 2.0); + let s = saved(Some([200, 100]), [1000.0, 700.0], 1.0, &old); + let p = place(Some(&s), std::slice::from_ref(&hidpi), Some(0), &defaults()); + assert_eq!(p.normal.size, [1000.0, 700.0]); + assert_eq!(p.scale, 2.0); + assert_eq!(p.monitor, Some(hidpi.key)); + assert_eq!(p.position_px, Some([200, 100])); + assert_eq!(p.normal.pos, [100.0, 50.0]); + } + + #[test] + fn smaller_monitor_clamps_to_usable_area_and_min() { + let big = mon("Big", [0, 0], [3840, 2160], 1.0); + let s = saved(Some([100, 100]), [3000.0, 1800.0], 1.0, &big); + let small = mon("S", [0, 0], [1280, 720], 1.0); + let p = place(Some(&s), std::slice::from_ref(&small), Some(0), &defaults()); + assert_eq!(p.normal.size, [1280.0, 680.0]); + assert_eq!(p.position_px, Some([0, 40])); + // A monitor below `min`: the monitor wins. + let tiny = mon("T", [0, 0], [320, 240], 1.0); + let p = place(Some(&s), &[tiny], Some(0), &defaults()); + assert_eq!(p.normal.size, [320.0, 200.0]); + // `min` raises a sliver saved size. + let sliver = saved(None, [50.0, 50.0], 1.0, &small); + assert_eq!(place(Some(&sliver), &[small], Some(0), &defaults()).normal.size, [400.0, 300.0]); + } + + #[test] + fn negative_origin_monitors_are_valid_places() { + let left = mon("L", [-1920, 0], [1920, 1080], 1.0); + let above = mon("U", [0, -1080], [1920, 1080], 1.0); + let ms = [hd(), left.clone(), above.clone()]; + let s = saved(Some([-1500, 100]), [800.0, 600.0], 1.0, &left); + assert_eq!(place(Some(&s), &ms, Some(0), &defaults()).position_px, Some([-1500, 100])); + let s = saved(Some([300, -900]), [800.0, 600.0], 1.0, &above); + assert_eq!(place(Some(&s), &ms, Some(0), &defaults()).position_px, Some([300, -900])); + // The left monitor is unplugged: back onto the primary, not stuck at a negative x. + let s = saved(Some([-1500, 100]), [800.0, 600.0], 1.0, &left); + assert_eq!(place(Some(&s), &[hd()], Some(0), &defaults()).position_px, Some([0, 100])); + } + + #[test] + fn nearest_monitor_wins_when_the_saved_one_is_gone() { + let right = mon("R", [1920, 0], [1920, 1080], 1.0); + let far = mon("F", [5000, 0], [1920, 1080], 1.0); + let gone = mon("Gone", [3840, 0], [1920, 1080], 1.0); + let s = saved(Some([6000, 100]), [800.0, 600.0], 1.0, &gone); + let p = place(Some(&s), &[hd(), right, far.clone()], Some(0), &defaults()); + assert_eq!(p.monitor, Some(far.key)); + } + + #[test] + fn wayland_neither_reads_nor_returns_a_position() { + let mut d = defaults(); + d.no_position = true; + let m = hd(); + let s = saved(Some([5000, 5000]), [800.0, 600.0], 1.0, &m); + let p = place(Some(&s), std::slice::from_ref(&m), Some(0), &d); + assert_eq!(p.position_px, None); + assert_eq!(p.normal.size, [800.0, 600.0]); + assert_eq!(place(None, &[m], Some(0), &d).position_px, None); + } + + #[test] + fn size_saved_at_zoom_one_does_not_shrink_with_zoom() { + let m = hd(); + let mut s = saved(Some([100, 100]), [1000.0, 700.0], 1.0, &m); + s.zoom = 1.5; + let p = place(Some(&s), &[m], Some(0), &defaults()); + assert_eq!(p.normal.size, [1000.0, 700.0]); + assert_eq!(p.zoom, 1.5); + } + + #[test] + fn maximized_keeps_the_normal_rect() { + let m = hd(); + let mut s = saved(Some([100, 100]), [900.0, 600.0], 1.0, &m); + s.maximized = true; + let p = place(Some(&s), &[m], Some(0), &defaults()); + assert!(p.maximized); + assert_eq!((p.normal.size, p.position_px), ([900.0, 600.0], Some([100, 100]))); + } + + #[test] + fn full_screen_needs_the_opt_in() { + let m = hd(); + let mut s = saved(Some([100, 100]), [900.0, 600.0], 1.0, &m); + s.fullscreen = true; + let mut d = defaults(); + assert!(!place(Some(&s), std::slice::from_ref(&m), Some(0), &d).fullscreen); + d.restore_fullscreen = true; + assert!(place(Some(&s), &[m], Some(0), &d).fullscreen); + } + + #[test] + fn nonsense_saved_numbers_fall_back_to_a_first_launch() { + let m = hd(); + let mut s = saved(Some([0, 0]), [f32::NAN, 600.0], 1.0, &m); + assert_eq!(place(Some(&s), std::slice::from_ref(&m), Some(0), &defaults()).normal.size, [1200.0, 800.0]); + s.normal.size = [800.0, 600.0]; + s.scale = 0.0; + s.zoom = 99.0; + let p = place(Some(&s), &[m], Some(0), &defaults()); + assert_eq!((p.scale, p.zoom), (1.0, 1.0)); + } + + #[test] + fn no_monitors_keeps_the_saved_geometry() { + let m = hd(); + let s = saved(Some([10, 20]), [800.0, 600.0], 1.0, &m); + let p = place(Some(&s), &[], None, &defaults()); + assert_eq!((p.normal.size, p.position_px), ([800.0, 600.0], Some([10, 20]))); + } +} diff --git a/crates/window/src/restore/store.rs b/crates/window/src/restore/store.rs new file mode 100644 index 0000000000..2e184231a7 --- /dev/null +++ b/crates/window/src/restore/store.rs @@ -0,0 +1,414 @@ +//! `window.json`: the saved [`Placement`] of each window, beside the app's `config.toml`. +//! +//! ```json +//! { "schema_version": 1, "windows": { "main": { ... }, "": { ... } } } +//! ``` +//! +//! The folder is chosen by `craft_settings::paths`, so portable installs keep the file in the +//! portable folder and `_CONFIG_DIR` moves it with `config.toml`. Writes are atomic and +//! private. A file that does not parse is moved aside (`window.broken-.json`, the +//! `craft_settings::recovery` convention) and the store starts empty. A file with a newer +//! `schema_version` is read but never written. Keys this version does not know are written back +//! unchanged. Two running instances of one app overwrite each other; the last writer wins. + +use std::collections::BTreeMap; +use std::io; +use std::path::{Path, PathBuf}; + +use craft_atomic::{NewFilePermissions, WriteOptions}; +use craft_settings::paths::{self, Location, Portable, Probe}; +use craft_settings::recovery; +use serde_json::{Map, Value, json}; + +use super::place::{Placement, sane}; + +/// The file name beside `config.toml`. +pub const FILE_NAME: &str = "window.json"; +/// The `schema_version` this code writes. +pub const SCHEMA_VERSION: u64 = 1; +/// The key of the app's first window. +pub const MAIN: &str = "main"; + +/// Why a store does not write. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ReadOnly { + /// The file has a newer `schema_version` than this code knows. + NewerSchema(u64), + /// The file exists but could not be read (permissions, say); it is left alone. + Unreadable, +} + +/// A write [`Store::take_pending`] prepared. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pending { + pub path: PathBuf, + pub bytes: Vec, + /// Pass to [`Store::mark_saved`] after the write succeeded. + pub generation: u64, +} + +/// Writes `pending` atomically and privately, creating the folder. Needs no access to the store. +pub fn write_pending(pending: &Pending) -> io::Result<()> { + if let Some(dir) = pending.path.parent() { + std::fs::create_dir_all(dir)?; + } + WriteOptions::default().with_new_file_permissions(NewFilePermissions::Private).atomic_write(&pending.path, &pending.bytes) +} + +/// The saved placements of an app's windows. +#[derive(Debug)] +pub struct Store { + path: Option, + /// Entries stay raw so one that fails to parse is neither lost nor fatal to the others. + windows: BTreeMap, + /// Top-level keys other than `schema_version` and `windows`. + extra: Map, + read_only: Option, + /// Counts changes; the store is dirty while it is ahead of `saved`. + generation: u64, + saved: u64, + moved_aside: Option, +} + +impl Store { + /// The store for `app_id` in the folder `craft_settings` picks for its `config.toml`, with + /// the suite's default portable marker. In an isolated or in-memory configuration + /// (`_CONFIG_DIR` empty) nothing is read or written. + pub fn open(app_id: &str) -> Self { + Self::open_with(app_id, &Portable::DEFAULT, &Location::Auto, &Probe::default()) + } + + /// [`open`](Self::open) with the app's own portable names, location override and probe: the + /// same arguments its `craft_settings` options use. + pub fn open_with(app_id: &str, portable: &Portable, location: &Location, probe: &Probe) -> Self { + match paths::resolve(app_id, portable, location, probe).dir { + Some(dir) => Self::at(&dir.join(FILE_NAME)), + None => Self::in_memory(), + } + } + + /// A store backed by the file at `path`. A missing file is an empty store. + pub fn at(path: &Path) -> Self { + let mut store = Self { path: Some(path.to_path_buf()), ..Self::in_memory() }; + store.load(); + store + } + + /// A store that reads and writes nothing: tests, agents, the web. + pub fn in_memory() -> Self { + Self { path: None, windows: BTreeMap::new(), extra: Map::new(), read_only: None, generation: 0, saved: 0, moved_aside: None } + } + + /// The file this store writes, if it has one. + pub fn path(&self) -> Option<&Path> { + self.path.as_deref() + } + + /// Where a damaged file was moved to while opening, if one was. + pub fn moved_aside(&self) -> Option<&Path> { + self.moved_aside.as_deref() + } + + /// Why [`save`](Self::save) writes nothing, if so. + pub fn read_only(&self) -> Option<&ReadOnly> { + self.read_only.as_ref() + } + + /// The placement saved under `key`; `None` when absent or not a placement. + pub fn get(&self, key: &str) -> Option { + serde_json::from_value(self.windows.get(key)?.clone()).ok() + } + + /// Replaces the placement under `key`. Fields of the old entry that this version does not know + /// stay. A placement with a non-finite size is ignored. Nothing is written until + /// [`save`](Self::save) or [`take_pending`](Self::take_pending). + pub fn set(&mut self, key: &str, placement: &Placement) { + let Some(placement) = sane(placement) else { return }; + let Ok(Value::Object(new)) = serde_json::to_value(&placement) else { return }; + let merged = match self.windows.get(key) { + Some(Value::Object(old)) => { + let mut m = old.clone(); + m.extend(new); + m + } + _ => new, + }; + let merged = Value::Object(merged); + if self.windows.get(key) != Some(&merged) { + self.windows.insert(key.to_owned(), merged); + self.generation += 1; + } + } + + /// Forgets `key`. + pub fn remove(&mut self, key: &str) { + if self.windows.remove(key).is_some() { + self.generation += 1; + } + } + + /// The keys with an entry, in order. + pub fn keys(&self) -> impl Iterator { + self.windows.keys().map(String::as_str) + } + + /// Whether something changed since the last successful write. + pub fn is_dirty(&self) -> bool { + self.generation != self.saved + } + + /// The write that would bring the file up to date, or `None` when there is nothing to write + /// (in memory, read-only, or unchanged). Write it with [`write_pending`], without holding any + /// lock on the store, then report success with [`mark_saved`](Self::mark_saved). + pub fn take_pending(&self) -> Option { + let path = self.path.clone().filter(|_| self.read_only.is_none() && self.is_dirty())?; + let mut doc = self.extra.clone(); + doc.insert("schema_version".into(), json!(SCHEMA_VERSION)); + doc.insert("windows".into(), Value::Object(self.windows.clone().into_iter().collect())); + let mut bytes = serde_json::to_vec_pretty(&Value::Object(doc)).ok()?; + bytes.push(b'\n'); + Some(Pending { path, bytes, generation: self.generation }) + } + + /// Records that [`Pending::generation`] reached the disk. The store stays dirty if it changed + /// again meanwhile, and after a failed write (do not call this then), so the next + /// [`take_pending`](Self::take_pending) retries. + pub fn mark_saved(&mut self, generation: u64) { + self.saved = self.saved.max(generation.min(self.generation)); + } + + /// [`take_pending`](Self::take_pending), [`write_pending`] and [`mark_saved`](Self::mark_saved) + /// in one call. `Ok(true)` when written; `Ok(false)` when there was nothing to write. + pub fn save(&mut self) -> io::Result { + let Some(pending) = self.take_pending() else { return Ok(false) }; + write_pending(&pending)?; + self.mark_saved(pending.generation); + Ok(true) + } + + fn load(&mut self) { + let Some(path) = self.path.clone() else { return }; + let text = match std::fs::read_to_string(&path) { + Ok(t) => t, + Err(e) if e.kind() == io::ErrorKind::NotFound => return, + // Invalid UTF-8 is damage; anything else may be transient, so leave the file be. + Err(e) if e.kind() == io::ErrorKind::InvalidData => return self.start_over(&path), + Err(_) => { + self.read_only = Some(ReadOnly::Unreadable); + return; + } + }; + let Some(mut doc) = serde_json::from_str::(&text).ok().and_then(|v| match v { + Value::Object(m) => Some(m), + _ => None, + }) else { + return self.start_over(&path); + }; + let Some(version) = doc.remove("schema_version").and_then(|v| v.as_u64()) else { + return self.start_over(&path); + }; + // A newer file is never judged by this version's shape rules, so never moved aside. + if version > SCHEMA_VERSION { + self.read_only = Some(ReadOnly::NewerSchema(version)); + if let Some(Value::Object(m)) = doc.remove("windows") { + self.windows = m.into_iter().collect(); + } + self.extra = doc; + return; + } + let Some(Value::Object(windows)) = doc.remove("windows") else { + return self.start_over(&path); + }; + self.windows = windows.into_iter().collect(); + self.extra = doc; + } + + fn start_over(&mut self, path: &Path) { + match recovery::move_aside(path) { + Ok(to) => self.moved_aside = Some(to), + // Cannot rename it away: do not overwrite what we could not set aside. + Err(_) => self.read_only = Some(ReadOnly::Unreadable), + } + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::restore::{Monitor, MonitorKey}; + + fn sample(x: i32) -> Placement { + let m = Monitor::new(MonitorKey::new("DP-1", [1920, 1080]), [0, 0], [1920, 1080], 1.0); + let mut p = crate::restore::place(None, &[m], Some(0), &crate::restore::Defaults::new([800.0, 600.0], [300.0, 200.0])); + p.position_px = Some([x, 10]); + p + } + + fn siblings(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + } + + #[test] + fn round_trip_through_the_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nested").join(FILE_NAME); + let mut s = Store::at(&path); + assert!(s.get(MAIN).is_none()); + s.set(MAIN, &sample(5)); + s.set("doc-2", &sample(6)); + assert!(s.save().unwrap()); + assert!(!s.save().unwrap(), "nothing changed"); + let again = Store::at(&path); + assert_eq!(again.get(MAIN), Some(sample(5))); + assert_eq!(again.get("doc-2"), Some(sample(6))); + assert_eq!(again.keys().collect::>(), ["doc-2", MAIN]); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(v["schema_version"], 1); + } + + #[cfg(unix)] + #[test] + fn the_file_is_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + let mut s = Store::at(&path); + s.set(MAIN, &sample(1)); + s.save().unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o077, 0); + } + + #[test] + fn corrupt_file_is_moved_aside_and_the_store_starts_empty() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + std::fs::write(&path, "{ not json").unwrap(); + let mut s = Store::at(&path); + assert!(s.get(MAIN).is_none() && s.read_only().is_none()); + let aside = s.moved_aside().unwrap().to_path_buf(); + assert_eq!(std::fs::read_to_string(aside).unwrap(), "{ not json"); + assert!(!path.exists()); + s.set(MAIN, &sample(1)); + s.save().unwrap(); + assert!(Store::at(&path).get(MAIN).is_some()); + assert_eq!(siblings(dir.path()).len(), 2); + } + + #[test] + fn json_without_a_schema_version_counts_as_corrupt() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + std::fs::write(&path, r#"{"windows":{}}"#).unwrap(); + assert!(Store::at(&path).moved_aside().is_some()); + } + + #[test] + fn newer_schema_is_read_but_never_written() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + let mut doc = json!({ "schema_version": 2, "windows": {}, "future": [1] }); + doc["windows"][MAIN] = serde_json::to_value(sample(7)).unwrap(); + let text = serde_json::to_string(&doc).unwrap(); + std::fs::write(&path, &text).unwrap(); + let mut s = Store::at(&path); + assert_eq!(s.read_only(), Some(&ReadOnly::NewerSchema(2))); + assert_eq!(s.get(MAIN), Some(sample(7))); + s.set(MAIN, &sample(8)); + assert!(!s.save().unwrap()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), text); + assert_eq!(siblings(dir.path()), [FILE_NAME]); + } + + #[test] + fn unknown_keys_survive_a_write() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + let mut doc = json!({ "schema_version": 1, "note": {"a": 1}, "windows": { "odd": {"unexpected": true} } }); + doc["windows"][MAIN] = serde_json::to_value(sample(1)).unwrap(); + std::fs::write(&path, doc.to_string()).unwrap(); + let mut s = Store::at(&path); + assert!(s.get("odd").is_none()); + s.set(MAIN, &sample(2)); + s.save().unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(v["note"], json!({"a": 1})); + assert_eq!(v["windows"]["odd"], json!({"unexpected": true})); + assert_eq!(Store::at(&path).get(MAIN), Some(sample(2))); + } + + #[test] + fn newer_schema_with_an_unexpected_shape_is_not_moved_aside() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + std::fs::write(&path, r#"{"schema_version":3,"windows":[1,2]}"#).unwrap(); + let s = Store::at(&path); + assert_eq!(s.read_only(), Some(&ReadOnly::NewerSchema(3))); + assert!(s.moved_aside().is_none() && path.exists()); + } + + #[test] + fn non_finite_placements_are_never_stored() { + let mut s = Store::in_memory(); + let mut p = sample(1); + p.normal.size[0] = f32::NAN; + s.set(MAIN, &p); + assert!(s.get(MAIN).is_none() && !s.is_dirty()); + let mut p = sample(1); + p.normal.pos[1] = f32::INFINITY; + s.set(MAIN, &p); + assert_eq!(s.get(MAIN).unwrap().normal.pos, [0.0, 0.0]); + } + + #[test] + fn set_keeps_unknown_fields_of_the_entry() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(FILE_NAME); + let mut entry = serde_json::to_value(sample(1)).unwrap(); + entry["later"] = json!("x"); + std::fs::write(&path, json!({"schema_version": 1, "windows": {MAIN: entry}}).to_string()).unwrap(); + let mut s = Store::at(&path); + s.set(MAIN, &sample(2)); + s.save().unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!(v["windows"][MAIN]["later"], "x"); + assert_eq!(Store::at(&path).get(MAIN), Some(sample(2))); + } + + #[test] + fn dirty_clears_only_after_the_write_is_reported() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Store::at(&dir.path().join(FILE_NAME)); + s.set(MAIN, &sample(1)); + let first = s.take_pending().unwrap(); + s.set(MAIN, &sample(2)); + write_pending(&first).unwrap(); + s.mark_saved(first.generation); + assert!(s.is_dirty(), "changed again while the first write was in flight"); + let second = s.take_pending().unwrap(); + assert!(s.is_dirty(), "taking a write does not clear it"); + write_pending(&second).unwrap(); + s.mark_saved(second.generation); + assert!(!s.is_dirty() && s.take_pending().is_none()); + } + + #[test] + fn in_memory_store_keeps_values_and_writes_nothing() { + let mut s = Store::in_memory(); + s.set(MAIN, &sample(3)); + assert_eq!(s.get(MAIN), Some(sample(3))); + assert!(!s.save().unwrap()); + assert!(s.path().is_none()); + } + + #[test] + fn open_puts_the_file_beside_config_toml() { + let dir = tempfile::tempdir().unwrap(); + let s = Store::open_with("app", &Portable::DEFAULT, &Location::Dir(dir.path().to_path_buf()), &Probe::default()); + assert_eq!(s.path(), Some(dir.path().join(FILE_NAME).as_path())); + let mem = Store::open_with("app", &Portable::DEFAULT, &Location::Memory, &Probe::default()); + assert!(mem.path().is_none()); + } +} diff --git a/docs/installation-policy.md b/docs/installation-policy.md new file mode 100644 index 0000000000..616575e1e2 --- /dev/null +++ b/docs/installation-policy.md @@ -0,0 +1,121 @@ +# Installing the Craft apps on Windows + +This is a proposed policy, not a claim about a published release. Preparation covers every +current Craft app with a Windows MSI, plus the launcher's new-install folder. The +[adoption inventory](windows-installation-adoption.md) records the scope and remaining gates. +Folders are preserved except for the proposed automatic migration of an exact former default +path (see below). That exception also covers a manually chosen path with the same spelling; +all other chosen folders stay. Maintainer acceptance of this exception is part of accepting +the policy. Storage of settings, caches and models is separate: [settings-storage.md](settings-storage.md). + +## Installation contexts + +**The policy (amended 29/10/2026): new installs are per-machine**, so every app sits in one +`Program Files\ArtCraft` folder. Per-user copies that already exist keep their context. + +**What the released packages do today differs, and this is a known gap.** Each app ships one +dual-scope MSI (Microsoft's "Single Package Authoring": `ALLUSERS=2` with `MSIINSTALLPERUSER=1` +in the Property table, written by WiX's `Package/Scope="perUserOrMachine"`). That authored +default is **per-user**: run with no scope property, the package installs for one account. So +today only the launcher, which passes `ALLUSERS=1` for a new install, follows the policy by +itself. A person running the MSI directly gets per-machine only by choosing "Everyone" in its +wizard. Closing the gap is follow-up work: one small PR per app making its package per-machine +only (`Scope="perMachine"`, no scope page), which also removes the per-user default here and +in the [adoption inventory](windows-installation-adoption.md). + +| Context | Default destination | Who chooses it today | +|---|---|---| +| Per-machine (the policy for new installs) | `%ProgramFiles%\ArtCraft\` (`Program Files (x86)` for a 32-bit package) | The launcher, with `ALLUSERS=1`; the setup wizard's "Everyone" choice | +| Per-user (the package's authored default; kept for existing copies) | `%LOCALAPPDATA%\Programs\ArtCraft\` | An MSI run with no scope property; the wizard's "Only for me" choice; copies installed per-user keep their context on update | + +**Permission prompts.** Each all-users install or update asks Windows for permission. One +prompt per **Update all** run was built (craft-launcher#974) with a hidden PowerShell, which +antivirus flagged; it was reverted (craft-launcher#1077). The launcher's signed installer +helper (craft-launcher#1080, in review) does all-users downgrades under one prompt, with no script. +Update all keeps one prompt per all-users package until it uses that helper too. No resident +service is planned. + +The launcher itself remains per-user only, with new copies under +`%LOCALAPPDATA%\Programs\ArtCraft\Launcher`. Existing launcher folders and its current +self-update mechanism are preserved. + +In a per-user install Windows Installer itself redirects the `ProgramFiles` folder to the +user's own Programs folder and the `HKMU` registry root to `HKCU`, so one package serves both +contexts. Everything a package writes follows its context automatically: + +- `InstallDir` record: `HKLM\Software\` per-machine, `HKCU\Software\` per-user. +- File associations and "Open with" registrations: `HKLM\Software\Classes` per-machine, + `HKCU\Software\Classes` per-user. +- Registry writes use context-sensitive roots. Existing component key paths and app-owned + associations are retained where valid. Each package must pass the compiled install-policy + checks; unresolved ICE57 shortcut diagnostics are tracked separately from the path policy. + +Scope is chosen before launch conditions and directory costing. The scope page must not be +added as a late checkbox after the default directory has already been resolved. +The page also has to leave `ALLUSERS` unset for "Only for me". Setting `ALLUSERS=2` there makes +Windows Installer search for related products as if the run were per-machine, so an interactive +upgrade skips the existing per-user copy and installs a second registration beside it. +Windows Installer also resolves Program Files once, for the context it started in, so the wizard +sets the new-install folder itself after the choice. Without that, "Everyone" installed into the +user profile with a machine-wide registration. + +For the same scope and folder, the ArtCraft Launcher and a direct install of the same MSI +produce the same result: the launcher dispatches the same package and only adds properties. +For an update, those are `INSTALLFOLDER` (the remembered folder) and the context properties of +the copy being updated. For a new install, the launcher also sets `ALLUSERS=1`, so the copy is +per-machine; a direct run of the MSI keeps the package's per-user default unless the person +picks "Everyone" in the wizard. + +## What an update must preserve + +- **The exact folder, subject to the following exception.** An ordinary update installs into + the remembered folder of the copy being replaced. Every chosen folder outside the exact + former default is preserved. +- **Explicit automatic-migration exception: the former default.** This proposal moves a copy + whose remembered folder is exactly `%ProgramFiles%\\` to + `%ProgramFiles%\ArtCraft\` on its next update, without a separate migration confirmation. + It also moves that exact path when someone typed it by hand: Windows Installer kept no + record that distinguishes a chosen path from an accepted default. Matching the path is not + evidence that the person accepted a default. An unreadable or different folder stays. + Maintainers must accept this exact-path exception as part of the policy before it is + adopted; it must not be described as preserving every manually chosen folder. Package-owned + shortcuts are recreated, but a shortcut someone made by hand to the old path may break. + Requiring migration consent instead is a change to this proposed rule; an in-app choice + would not itself require another Windows elevation prompt. +- **The context.** A per-machine copy updates per-machine (`ALLUSERS=1`), a per-user copy + per-user. MSI major upgrades cannot cross installation contexts, so a context change is a + deliberate uninstall-and-reinstall, never an ordinary upgrade. The launcher queries + authoritative MSI registration, not the hive containing a display entry. An unknown or + conflicting context stops the update rather than selecting the new-install default. +- **No duplicates.** Installing in the other context while a copy already exists is a visible + stop with a message naming the fix, never a silent second copy. The wizard pre-ticks the + matching scope when a copy in the other context is registered. +- **The chosen folder survives elevation.** `INSTALLFOLDER` is a secure MSI property, so + the elevated installer receives the same exact destination selected in the setup wizard. +- **Custom folders stay first-class.** A chosen exact app folder is used as-is; a chosen + suite root gets the app subfolder appended once (`D:\Craft` becomes `D:\Craft\PhotoCraft`, + never `D:\Craft\PhotoCraft\PhotoCraft`). A missing drive or an unavailable folder is a + visible error, not permission to fall back to the default. + +## What an app must still do without the launcher + +Install, launch, update and uninstall work standalone: the MSI's own wizard, its App Paths +registration (`Win+R`), its Start Menu shortcut and its entry in "Apps & features" never +require the launcher. The launcher reuses a standalone installation it finds rather than +installing a duplicate, and detection reads both contexts' registrations. + +## Other platforms + +macOS `.app` bundles, Linux packages/AppImages and FreeBSD tarballs keep their platform-native +conventions; nothing imitates the Windows directory tree. Linux settings live under +`XDG_CONFIG_HOME` and persistent models under `XDG_DATA_HOME` (`~/.local/share/ArtCraft/models`) +per [settings-storage.md](settings-storage.md). + +## Models are not caches + +Downloaded model files are persistent user assets. An app's cache cleanup and an app's +uninstaller must never delete them, another app's data, or user documents; existing model +folders are discovered read-only. See [settings-storage.md](settings-storage.md) for where +models live and what is disposable. Model resources shipped inside an application package, +such as bundled OCR resources, remain part of that package; this does not give an installer +ownership of separately downloaded shared models or discovered model folders. diff --git a/docs/settings-storage.md b/docs/settings-storage.md index f5bf6a52e3..066a7ccb14 100644 --- a/docs/settings-storage.md +++ b/docs/settings-storage.md @@ -2,6 +2,8 @@ How every Craft app stores its settings, and what goes where. The shared code is [`craft-settings`](../crates/settings/README.md); this page is the policy it implements. +Where the apps install on Windows, and what an update may move, is the companion policy +[installation-policy.md](installation-policy.md). Discussion: [storytold/craft-libs#12](https://github.com/storytold/craft-libs/issues/12). ## What goes where @@ -10,7 +12,8 @@ Discussion: [storytold/craft-libs#12](https://github.com/storytold/craft-libs/is |---|---|---| | Settings people might edit | `config.toml` in the config folder | One readable file with comments, atomic saves, backup, recovery, migrations | | Window and UI state | `ui.ron` / `app.ron` beside `config.toml` | Changes every session; not worth comments or hand edits | -| Caches and models | Platform cache folder (`paths::cache_dir`); `%LOCALAPPDATA%` on Windows so it does not roam | Disposable, large | +| Caches | Platform cache folder (`paths::cache_dir`); `%LOCALAPPDATA%` on Windows so it does not roam | Disposable, large | +| Downloaded models | The user's chosen persistent model root (suggested `%LOCALAPPDATA%\ArtCraft\models` on Windows; `$XDG_DATA_HOME/ArtCraft/models` on Linux, or `~/.local/share/ArtCraft/models` when it is unset) | Persistent user assets: never deleted by cache cleanup or an app's uninstaller, never disposable ([installation-policy.md](installation-policy.md)) | | Recovery and autosave files | Platform data folder (`paths::data_dir`) | Not settings; must survive a settings reset | | Settings that belong to a library or project (LightCraft) | Inside that folder, via `SettingsStore::open_at` | Travels with the library | | API keys and tokens | The OS keychain | Never in a plain-text file | diff --git a/docs/versioning.md b/docs/versioning.md new file mode 100644 index 0000000000..58c22cbf3e --- /dev/null +++ b/docs/versioning.md @@ -0,0 +1,81 @@ +# Versioning and releases + +craft-libs releases give applications a fixed dependency baseline. Consumers decide when to +upgrade; development on `main` is not a reason to refresh a working application's pins. + +## One workspace, one release + +All crates inherit `workspace.package.version` and ship together under an annotated `vX.Y.Z` +Git tag. A release contains the crates listed in that tag's README, not proposed crates in +open pull requests. A crate can keep the same implementation across several workspace releases. +Use the same tag or commit for every craft-libs dependency in a consumer's dependency graph; +mixing Git sources can create duplicate crate instances and incompatible Rust types. + +Tags identify reviewed commits and are never moved, deleted or reused to fix a release. +Corrections get a new version. The release notes and policy are stored with the source so a +consumer can read the contract that applied to its version. GitHub Releases carry the same notes. +Publishing to crates.io will be a separate step; these tags do not imply registry availability. + +## Compatibility while versions are 0.x + +The initial release is `0.1.0`. APIs are still developing, but compatibility within a minor +release line is intentional: + +- **Patch (`0.1.0` → `0.1.1`):** compatible fixes, documentation and additive APIs that preserve + existing callers. Keep public signatures, feature defaults, supported targets, minimum Rust + version and documented behavior compatible. Check that additions do not break exhaustive + matches, struct literals, trait implementations or other existing source patterns. +- **Minor (`0.1.x` → `0.2.0`):** changes requiring consumer action. This includes removing or + changing public APIs, incompatible persisted representations, feature/default changes, + dropping a supported target, raising the minimum Rust version, or upgrading a dependency + such as egui when its exposed types become incompatible. Explain the before/after and migration. +- **`1.0.0`:** a separate decision that the public contracts are ready for long-term stability. + After that, breaking changes require a major release; compatible additions use minor releases. + +Documented invalid input can be rejected more strictly in a patch to fix a defect or security +issue. Call out any observable change. Do not use “0.x” or “bug fix” to silently break a valid, +documented workflow. App-owned settings schemas and migration policy remain the app's +responsibility; library releases do not automatically migrate consumer data. + +For public egui APIs in `0.1.x`, keep the egui 0.36 compatibility line. The minimum Rust version +is 1.95. Compatible transitive updates still need validation and release-note coverage when +observable. Cargo's version-range rules do not select newer Git tags: changing a release pin +is always an explicit manifest edit. + +## Support and scope + +The newest minor line receives routine fixes. Important fixes to older lines are considered +case by case; there is no promise of maintaining every 0.x line or an LTS schedule. Existing +tags remain available so consumers can upgrade on their own schedule. Release notes identify +known limitations; a tag is not a claim that every driver, OS version or consuming app was tested. + +Platform boundaries are crate-specific. See each crate's API/README and the release notes. +In particular, native printing needs the OS spooler, settings persistence is native-only, and +browser UI compatibility does not imply native services work in a browser. Consumers must test +their own save/close flows, accessibility, rendering and printing where they use those services. + +## Preparing a release + +1. Choose a reviewed commit on `main`. Inspect open defects, changes since the previous tag, + crate metadata and any changed platform/dependency contracts. Update the shared version + and lockfile when needed; the first release already uses `0.1.0`. +2. Add a dated `CHANGELOG.md` entry with the included crates, changes, compatibility requirements, + migration steps and known limits. Update the README's recommended pin. Keep fixes and + unrelated pending features out of the release preparation unless they block the baseline. +3. Run formatting, workspace Clippy with warnings denied, and workspace tests, both default + and all features. The `Workspace` workflow runs these on Linux, macOS and Windows, requires + Windows spooler regression tests, checks the minimum compiler on Linux, and checks the + documented UI/settings WASM surface. All release jobs must pass for the candidate source. + Repository-local build commands must also follow the host's storage/allocation rules. +4. Review consumer impact and existing platform evidence. Exercise affected native workflows + when behavior changes; unit tests and cross-compilation cannot establish GUI or physical + printer acceptance. Record limitations instead of extending the support claim beyond evidence. +5. Merge the preparation PR and verify the checks for the actual release commit. Create an + annotated tag on that exact commit (`git tag -a vX.Y.Z FULL_SHA -m "craft-libs vX.Y.Z"`), + push only that tag, and create a GitHub Release using that version's changelog entry. + Tag-triggered CI should also pass. Do not publish crates as part of this Git-only release. +6. Verify that the remote tag resolves to the intended commit, the release notes are visible, + and a small external consumer resolves and checks with the documented pin. Preserve the + source identity, check results and release URL. Never repair a published tag by moving it. + +The workflow validates source; it does not automatically tag or publish on every push. diff --git a/docs/windows-installation-adoption.md b/docs/windows-installation-adoption.md new file mode 100644 index 0000000000..a3f1ce49e9 --- /dev/null +++ b/docs/windows-installation-adoption.md @@ -0,0 +1,46 @@ +# Windows installation policy adoption + +This is the inventory for the policy across the live app repositories and the launcher, not +merely the repositories on one developer's machine. The app packages below were merged on +27/10/2026 and released on 28/10/2026 as dual-scope MSIs whose authored default is per-user. +The policy since 29/10/2026 is per-machine for new installs: today the launcher applies it +(`ALLUSERS=1`), and per-machine-only packages are follow-up work, one PR per app (see +[installation-policy.md](installation-policy.md)). + +| Repository | Prepared Windows scope | Verification boundary | +|---|---|---| +| `effectcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `pdfcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `lightcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `photocraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `figcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `vectorcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `wordcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `gridcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `deckcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `filmcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `craft-launcher` | Per-user launcher; context-safe app updates | x64, x86 and arm64 metadata checks pass; real installation gates pending | +| `artcraft` | Not applicable | No Windows MSI definition on the inventoried default branch | +| `soundcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `cadcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `designcraft` | Released dual-scope, per-user authored default; the launcher installs per-machine | x64, x86 and arm64 metadata checks pass; real msiexec runs pass in both scopes (fresh install, upgrade, repair, uninstall; wizard and silent); clean-machine and second-account gates pending | +| `artcraftx` | Not applicable | No Windows MSI definition on the inventoried default branch | +| `AniCraft` | Not applicable | No Windows MSI definition on the inventoried default branch | + +## Before publication and release + +- Maintainer acceptance of the shared path/scope/model-ownership policy is still required. +- Keep app changes independent. Reconcile open installer UI and file-association PRs rather + than assuming their work is absent or overwriting it. +- Test real release payloads and previous release MSIs in an authorised clean Windows test + environment. Verify both standalone and launcher routes, old/custom folders, both scopes, + second-account visibility, optional shortcuts and menus, active apps, cancellation, rollback, + repair, uninstall and launcher self-update. Validate actual MSI assignment context, not only the + registry hive containing a display/uninstall entry. +- Metadata-only fixtures never substitute for those tests. x86/arm64 package validation on an + x64 host does not prove application execution on those architectures. +- No macOS/Linux layout change, settings migration, user-model relocation or new cleanup is + included. These platforms retain their native conventions. +- ArtCraft and ArtCraftX have no Windows MSI definition in the inventoried source; AniCraft + has no default branch/source to package. Do not invent installers for those repositories as + part of this rollout. diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rs index 1e9c0b80bd..022c4d1bce 100644 --- a/vendor/hayro-interpret/src/interpret/mod.rs +++ b/vendor/hayro-interpret/src/interpret/mod.rs @@ -709,13 +709,24 @@ fn interpret_window<'a>( .next() .is_some(); - if has_outline { + // PdfCraft patch: a glyph shown in a clipping mode that contributes no outline + // still clips -- the clip is empty, so nothing paints through it, as a glyph with + // an outline clips to its shape. Applying nothing instead left what followed + // unmasked. A text object that shows no glyph at all is not this case and leaves + // the clipping path alone, and a glyph whose outline is unavailable (Type 3) + // leaves the real clip unknown, so both stay unclipped. + let state = &context.get().text_state; + let empty_clip = state.clip_shown && !state.clip_unsupported; + + if has_outline || empty_clip { let clip_path = context.get().ctm * context.get().text_state.clip_paths.clone(); context.push_clip_path(clip_path, FillRule::NonZero, device); } context.get_mut().text_state.clip_paths.truncate(0); + context.get_mut().text_state.clip_shown = false; + context.get_mut().text_state.clip_unsupported = false; } TypedInstruction::TextFont(t) => { let name = t.0; diff --git a/vendor/hayro-interpret/src/interpret/state.rs b/vendor/hayro-interpret/src/interpret/state.rs index a146d2660f..d6fd263aa8 100644 --- a/vendor/hayro-interpret/src/interpret/state.rs +++ b/vendor/hayro-interpret/src/interpret/state.rs @@ -149,6 +149,15 @@ pub(crate) struct TextState<'a> { // When setting the text rendering mode to `clip`, the glyphs should instead be collected // as paths and then applied as 1 single clip path. This field stores those clip paths. pub(crate) clip_paths: BezPath, + /// PdfCraft patch: whether a glyph was shown in a clipping render mode (4 to 7) in this text + /// object, so `ET` knows to apply the clip even when none of them contributed an outline: the + /// clip is then empty and nothing paints through it. A text object that shows no glyph at all + /// leaves the clipping path alone, which is what readers do with it. + pub(crate) clip_shown: bool, + /// PdfCraft patch: whether a glyph in a clipping mode could not be turned into an outline + /// (a Type 3 glyph, which `clip_glyph` does not implement). The real clip is then unknown, so + /// `ET` leaves what follows unclipped rather than hiding it. + pub(crate) clip_unsupported: bool, } impl<'a> TextState<'a> { @@ -245,6 +254,8 @@ impl Default for TextState<'_> { text_line_matrix: Affine::IDENTITY, rise: 0.0, clip_paths: BezPath::default(), + clip_shown: false, + clip_unsupported: false, } } } diff --git a/vendor/hayro-interpret/src/interpret/text.rs b/vendor/hayro-interpret/src/interpret/text.rs index f9f68b1e6d..fecf66c04b 100644 --- a/vendor/hayro-interpret/src/interpret/text.rs +++ b/vendor/hayro-interpret/src/interpret/text.rs @@ -243,6 +243,9 @@ fn show_glyph<'a>( } pub(crate) fn clip_glyph(context: &mut Context<'_>, glyph: &Glyph<'_>, transform: Affine) { + // PdfCraft patch: this glyph is shown in a clipping mode, so the text object clips at `ET` + // whether or not the glyph has an outline to clip to. + context.get_mut().text_state.clip_shown = true; match glyph { Glyph::Outline(o) => { let outline = transform * o.outline(); @@ -254,6 +257,9 @@ pub(crate) fn clip_glyph(context: &mut Context<'_>, glyph: &Glyph<'_>, transform } Glyph::Type3(_) => { warn!("text rendering mode clip not implemented for shape glyphs"); + // PdfCraft patch: the clip this glyph belongs to cannot be built, so `ET` leaves what + // follows unclipped rather than applying an empty clip and hiding it. + context.get_mut().text_state.clip_unsupported = true; } } } diff --git a/vendor/krilla/README.craft.md b/vendor/krilla/README.craft.md index a2bf5c6a65..9b21d4f4a8 100644 --- a/vendor/krilla/README.craft.md +++ b/vendor/krilla/README.craft.md @@ -27,6 +27,7 @@ itself omits those texts. Its examples and four CC0 ICC profiles are retained wi | `patches/15-pdfx-conformance.patch` | PDF/X conformance key | `serialize.rs` | | `patches/16-modification-date.patch` | Modification date | `interchange/metadata.rs` | | `patches/17-color-precision.patch` | Color precision | `graphics/{color,shading_function}.rs` | +| `patches/18-subset-os2.patch` | Embedding permissions in TrueType subsets | `text/cid.rs` | Each patch applies with `patch -p1` from this directory, in numeric order, to the pristine crate. `SOURCE.json` records, for every retained file, the upstream hash (`upstream_sha256`) @@ -434,3 +435,19 @@ as a multiple of 1/255: C75 becomes 0.7490196 and C4 M4 Y4 K4 becomes 0.03921568 Tests: `crates/pdf/tests/print_color.rs` (`f32_colors_*`, `gray_stops_keep_their_exact_black_in_cmyk_shadings`, `mesh_*`, `rgb_mesh_is_a_device_rgb_shading`). + +## 18: embedding permissions in TrueType subsets + +The subsetter writes only the tables it subsets (`glyf`/`loca`, `head`, `hmtx`, `maxp`, `name`, +`post`, and `cvt `, `fpgm`, `prep` unchanged), so a `FontFile2` program had no `OS/2` table and +the font's embedding permissions (`OS/2.fsType`) never reached the PDF: a Preview & Print or +Restricted font looked unrestricted to anything reading the file later (storytold/designcraft#1781). + +`CIDFont` now adds the source font's `OS/2` table, byte for byte, to a TrueType subset that lacks +one. `with_table` rewrites the table directory in tag order with its binary-search fields, +aligns each table to four bytes with its checksum, and recomputes `head.checkSumAdjustment`. A +font with no `OS/2` is embedded as before. CFF programs are still embedded bare (`FontFile3` +`/CIDFontType0C`), which has no table directory to carry it. + +craft-pdf's `font_tables` test embeds a TrueType font with `fsType` 4 and checks the program's +`OS/2` matches the source, its table order and checksums, and that it still parses. diff --git a/vendor/krilla/SOURCE.json b/vendor/krilla/SOURCE.json index c3b497bb27..6a0fc87ae3 100644 --- a/vendor/krilla/SOURCE.json +++ b/vendor/krilla/SOURCE.json @@ -332,7 +332,7 @@ { "path": "src/text/cid.rs", "upstream_sha256": "5332282160b75e2a24345b546ead219476768829bef881562f5658dd50ce97f2", - "sha256": "5332282160b75e2a24345b546ead219476768829bef881562f5658dd50ce97f2" + "sha256": "4bb482edddaf1cac916cb110e8139c90c53582f0c1c7afc6fa1cf6b037ccae5e" }, { "path": "src/text/font.rs", diff --git a/vendor/krilla/patches/18-subset-os2.patch b/vendor/krilla/patches/18-subset-os2.patch new file mode 100644 index 0000000000..21a50a7362 --- /dev/null +++ b/vendor/krilla/patches/18-subset-os2.patch @@ -0,0 +1,104 @@ +diff --git a/src/text/cid.rs b/src/text/cid.rs +index 2c52127..dbd4e37 100644 +--- a/src/text/cid.rs ++++ b/src/text/cid.rs +@@ -238,6 +238,8 @@ impl CIDFont { + let num_glyphs = subsetted.num_glyphs(); + let subsetted_data = subsetted.font_data().0; + ++ // Outlives the stream, which may borrow it. ++ let with_os2; + let font_stream = { + let mut data = subsetted_data.as_ref().as_ref(); + +@@ -248,6 +250,14 @@ impl CIDFont { + + if let Some(cff) = subsetted_ref.data_for_tag(Cff::TAG) { + data = cff.as_bytes(); ++ } else if let Some(os2) = self.font.font_ref().data_for_tag(OS2_TAG) { ++ // The subsetter writes no `OS/2`, so the font's embedding permissions ++ // (`fsType`) would not reach the PDF: a Preview & Print or Restricted font ++ // would look unrestricted to what reads it later. Keep the source's table. ++ if let Some(font) = with_table(data, OS2_TAG.to_be_bytes(), os2.as_bytes()) { ++ with_os2 = font; ++ data = &with_os2; ++ } + } + + FilterStreamBuilder::new_from_binary_data(data).finish(&sc.serialize_settings()) +@@ -433,6 +443,75 @@ pub(crate) fn base_font_name(font: &Font, data: &T) -> String { + format!("{subset_tag}+{trimmed}") + } + ++const OS2_TAG: skrifa::raw::types::Tag = skrifa::raw::types::Tag::new(b"OS/2"); ++ ++/// The sfnt `font` with `table` added under `tag`, or `None` when `font` can't be read as one or ++/// already has that table. The table directory is written in tag order with its binary-search ++/// fields, every table 4-byte aligned with its checksum, and `head.checkSumAdjustment` ++/// recomputed (OpenType, "Table directory" and "Calculating checksums"). ++fn with_table(font: &[u8], tag: [u8; 4], table: &[u8]) -> Option> { ++ let be16 = |at: usize| Some(u16::from_be_bytes(font.get(at..at + 2)?.try_into().ok()?)); ++ let be32 = |at: usize| Some(u32::from_be_bytes(font.get(at..at + 4)?.try_into().ok()?)); ++ let count = usize::from(be16(4)?); ++ let mut tables: Vec<([u8; 4], &[u8])> = Vec::with_capacity(count + 1); ++ for k in 0..count { ++ let record = 12 + 16 * k; ++ let t: [u8; 4] = font.get(record..record + 4)?.try_into().ok()?; ++ let (offset, length) = (be32(record + 8)? as usize, be32(record + 12)? as usize); ++ tables.push((t, font.get(offset..offset.checked_add(length)?)?)); ++ } ++ if tables.iter().any(|(t, _)| *t == tag) { ++ return None; ++ } ++ tables.push((tag, table)); ++ tables.sort_by_key(|(t, _)| *t); ++ let n = u16::try_from(tables.len()).ok()?; ++ let entry_selector = 15 - n.leading_zeros() as u16; ++ let search_range = (1u16 << entry_selector).checked_mul(16)?; ++ let range_shift = n.checked_mul(16)?.checked_sub(search_range)?; ++ let checksum = |data: &[u8]| { ++ data.chunks(4).fold(0u32, |sum, c| { ++ let mut word = [0u8; 4]; ++ word[..c.len()].copy_from_slice(c); ++ sum.wrapping_add(u32::from_be_bytes(word)) ++ }) ++ }; ++ let mut out = Vec::with_capacity(font.len() + table.len() + 16 + 3); ++ out.extend_from_slice(font.get(0..4)?); ++ for v in [n, search_range, entry_selector, range_shift] { ++ out.extend_from_slice(&v.to_be_bytes()); ++ } ++ let mut offset = 12 + 16 * tables.len(); ++ let mut head_at = None; ++ for (t, data) in &tables { ++ let mut data = data.to_vec(); ++ if t == b"head" { ++ // checkSumAdjustment is zero while the checksums are taken ++ data.get_mut(8..12)?.fill(0); ++ head_at = Some(offset); ++ } ++ out.extend_from_slice(t); ++ out.extend_from_slice(&checksum(&data).to_be_bytes()); ++ out.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes()); ++ out.extend_from_slice(&u32::try_from(data.len()).ok()?.to_be_bytes()); ++ offset = offset.checked_add(data.len().next_multiple_of(4))?; ++ } ++ for (t, data) in &tables { ++ let start = out.len(); ++ out.extend_from_slice(data); ++ if t == b"head" { ++ out.get_mut(start + 8..start + 12)?.fill(0); ++ } ++ out.resize(out.len().next_multiple_of(4), 0); ++ } ++ if let Some(at) = head_at { ++ let adjustment = 0xB1B0_AFBAu32.wrapping_sub(checksum(&out)); ++ out.get_mut(at + 8..at + 12)? ++ .copy_from_slice(&adjustment.to_be_bytes()); ++ } ++ Some(out) ++} ++ + #[cfg_attr(feature = "comemo", comemo::memoize)] + fn subset_font(font: Font, glyph_remapper: &GlyphRemapper) -> KrillaResult<(Font, Rect)> { + let mut bbox: Option = None; diff --git a/vendor/krilla/src/text/cid.rs b/vendor/krilla/src/text/cid.rs index 2c5212715f..dbd4e37602 100644 --- a/vendor/krilla/src/text/cid.rs +++ b/vendor/krilla/src/text/cid.rs @@ -238,6 +238,8 @@ impl CIDFont { let num_glyphs = subsetted.num_glyphs(); let subsetted_data = subsetted.font_data().0; + // Outlives the stream, which may borrow it. + let with_os2; let font_stream = { let mut data = subsetted_data.as_ref().as_ref(); @@ -248,6 +250,14 @@ impl CIDFont { if let Some(cff) = subsetted_ref.data_for_tag(Cff::TAG) { data = cff.as_bytes(); + } else if let Some(os2) = self.font.font_ref().data_for_tag(OS2_TAG) { + // The subsetter writes no `OS/2`, so the font's embedding permissions + // (`fsType`) would not reach the PDF: a Preview & Print or Restricted font + // would look unrestricted to what reads it later. Keep the source's table. + if let Some(font) = with_table(data, OS2_TAG.to_be_bytes(), os2.as_bytes()) { + with_os2 = font; + data = &with_os2; + } } FilterStreamBuilder::new_from_binary_data(data).finish(&sc.serialize_settings()) @@ -433,6 +443,75 @@ pub(crate) fn base_font_name(font: &Font, data: &T) -> String { format!("{subset_tag}+{trimmed}") } +const OS2_TAG: skrifa::raw::types::Tag = skrifa::raw::types::Tag::new(b"OS/2"); + +/// The sfnt `font` with `table` added under `tag`, or `None` when `font` can't be read as one or +/// already has that table. The table directory is written in tag order with its binary-search +/// fields, every table 4-byte aligned with its checksum, and `head.checkSumAdjustment` +/// recomputed (OpenType, "Table directory" and "Calculating checksums"). +fn with_table(font: &[u8], tag: [u8; 4], table: &[u8]) -> Option> { + let be16 = |at: usize| Some(u16::from_be_bytes(font.get(at..at + 2)?.try_into().ok()?)); + let be32 = |at: usize| Some(u32::from_be_bytes(font.get(at..at + 4)?.try_into().ok()?)); + let count = usize::from(be16(4)?); + let mut tables: Vec<([u8; 4], &[u8])> = Vec::with_capacity(count + 1); + for k in 0..count { + let record = 12 + 16 * k; + let t: [u8; 4] = font.get(record..record + 4)?.try_into().ok()?; + let (offset, length) = (be32(record + 8)? as usize, be32(record + 12)? as usize); + tables.push((t, font.get(offset..offset.checked_add(length)?)?)); + } + if tables.iter().any(|(t, _)| *t == tag) { + return None; + } + tables.push((tag, table)); + tables.sort_by_key(|(t, _)| *t); + let n = u16::try_from(tables.len()).ok()?; + let entry_selector = 15 - n.leading_zeros() as u16; + let search_range = (1u16 << entry_selector).checked_mul(16)?; + let range_shift = n.checked_mul(16)?.checked_sub(search_range)?; + let checksum = |data: &[u8]| { + data.chunks(4).fold(0u32, |sum, c| { + let mut word = [0u8; 4]; + word[..c.len()].copy_from_slice(c); + sum.wrapping_add(u32::from_be_bytes(word)) + }) + }; + let mut out = Vec::with_capacity(font.len() + table.len() + 16 + 3); + out.extend_from_slice(font.get(0..4)?); + for v in [n, search_range, entry_selector, range_shift] { + out.extend_from_slice(&v.to_be_bytes()); + } + let mut offset = 12 + 16 * tables.len(); + let mut head_at = None; + for (t, data) in &tables { + let mut data = data.to_vec(); + if t == b"head" { + // checkSumAdjustment is zero while the checksums are taken + data.get_mut(8..12)?.fill(0); + head_at = Some(offset); + } + out.extend_from_slice(t); + out.extend_from_slice(&checksum(&data).to_be_bytes()); + out.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes()); + out.extend_from_slice(&u32::try_from(data.len()).ok()?.to_be_bytes()); + offset = offset.checked_add(data.len().next_multiple_of(4))?; + } + for (t, data) in &tables { + let start = out.len(); + out.extend_from_slice(data); + if t == b"head" { + out.get_mut(start + 8..start + 12)?.fill(0); + } + out.resize(out.len().next_multiple_of(4), 0); + } + if let Some(at) = head_at { + let adjustment = 0xB1B0_AFBAu32.wrapping_sub(checksum(&out)); + out.get_mut(at + 8..at + 12)? + .copy_from_slice(&adjustment.to_be_bytes()); + } + Some(out) +} + #[cfg_attr(feature = "comemo", comemo::memoize)] fn subset_font(font: Font, glyph_remapper: &GlyphRemapper) -> KrillaResult<(Font, Rect)> { let mut bbox: Option = None;